LegalizeDAG.cpp revision 6814f1522dd7cdeb4674a9ad199f482a2e7aaea1
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/MachineConstantPool.h"
16#include "llvm/CodeGen/MachineFunction.h"
17#include "llvm/CodeGen/MachineFrameInfo.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>
24using namespace llvm;
25
26//===----------------------------------------------------------------------===//
27/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
28/// hacks on it until the target machine can handle it.  This involves
29/// eliminating value sizes the machine cannot handle (promoting small sizes to
30/// large sizes or splitting up large values into small values) as well as
31/// eliminating operations the machine cannot handle.
32///
33/// This code also does a small amount of optimization and recognition of idioms
34/// as part of its processing.  For example, if a target does not support a
35/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
36/// will attempt merge setcc and brc instructions into brcc's.
37///
38namespace {
39class SelectionDAGLegalize {
40  TargetLowering &TLI;
41  SelectionDAG &DAG;
42
43  /// LegalizeAction - This enum indicates what action we should take for each
44  /// value type the can occur in the program.
45  enum LegalizeAction {
46    Legal,            // The target natively supports this value type.
47    Promote,          // This should be promoted to the next larger type.
48    Expand,           // This integer type should be broken into smaller pieces.
49  };
50
51  /// ValueTypeActions - This is a bitvector that contains two bits for each
52  /// value type, where the two bits correspond to the LegalizeAction enum.
53  /// This can be queried with "getTypeAction(VT)".
54  unsigned ValueTypeActions;
55
56  /// NeedsAnotherIteration - This is set when we expand a large integer
57  /// operation into smaller integer operations, but the smaller operations are
58  /// not set.  This occurs only rarely in practice, for targets that don't have
59  /// 32-bit or larger integer registers.
60  bool NeedsAnotherIteration;
61
62  /// LegalizedNodes - For nodes that are of legal width, and that have more
63  /// than one use, this map indicates what regularized operand to use.  This
64  /// allows us to avoid legalizing the same thing more than once.
65  std::map<SDOperand, SDOperand> LegalizedNodes;
66
67  /// PromotedNodes - For nodes that are below legal width, and that have more
68  /// than one use, this map indicates what promoted value to use.  This allows
69  /// us to avoid promoting the same thing more than once.
70  std::map<SDOperand, SDOperand> PromotedNodes;
71
72  /// ExpandedNodes - For nodes that need to be expanded, and which have more
73  /// than one use, this map indicates which which operands are the expanded
74  /// version of the input.  This allows us to avoid expanding the same node
75  /// more than once.
76  std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
77
78  void AddLegalizedOperand(SDOperand From, SDOperand To) {
79    bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
80    assert(isNew && "Got into the map somehow?");
81  }
82  void AddPromotedOperand(SDOperand From, SDOperand To) {
83    bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
84    assert(isNew && "Got into the map somehow?");
85  }
86
87public:
88
89  SelectionDAGLegalize(SelectionDAG &DAG);
90
91  /// Run - While there is still lowering to do, perform a pass over the DAG.
92  /// Most regularization can be done in a single pass, but targets that require
93  /// large values to be split into registers multiple times (e.g. i64 -> 4x
94  /// i16) require iteration for these values (the first iteration will demote
95  /// to i32, the second will demote to i16).
96  void Run() {
97    do {
98      NeedsAnotherIteration = false;
99      LegalizeDAG();
100    } while (NeedsAnotherIteration);
101  }
102
103  /// getTypeAction - Return how we should legalize values of this type, either
104  /// it is already legal or we need to expand it into multiple registers of
105  /// smaller integer type, or we need to promote it to a larger type.
106  LegalizeAction getTypeAction(MVT::ValueType VT) const {
107    return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
108  }
109
110  /// isTypeLegal - Return true if this type is legal on this target.
111  ///
112  bool isTypeLegal(MVT::ValueType VT) const {
113    return getTypeAction(VT) == Legal;
114  }
115
116private:
117  void LegalizeDAG();
118
119  SDOperand LegalizeOp(SDOperand O);
120  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
121  SDOperand PromoteOp(SDOperand O);
122
123  SDOperand ExpandLibCall(const char *Name, SDNode *Node,
124                          SDOperand &Hi);
125  SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
126                          SDOperand Source);
127  bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
128                   SDOperand &Lo, SDOperand &Hi);
129  void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
130                        SDOperand &Lo, SDOperand &Hi);
131  void ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
132                     SDOperand &Lo, SDOperand &Hi);
133
134  void SpliceCallInto(const SDOperand &CallResult, SDNode *OutChain);
135
136  SDOperand getIntPtrConstant(uint64_t Val) {
137    return DAG.getConstant(Val, TLI.getPointerTy());
138  }
139};
140}
141
142
143SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
144  : TLI(dag.getTargetLoweringInfo()), DAG(dag),
145    ValueTypeActions(TLI.getValueTypeActions()) {
146  assert(MVT::LAST_VALUETYPE <= 16 &&
147         "Too many value types for ValueTypeActions to hold!");
148}
149
150void SelectionDAGLegalize::LegalizeDAG() {
151  SDOperand OldRoot = DAG.getRoot();
152  SDOperand NewRoot = LegalizeOp(OldRoot);
153  DAG.setRoot(NewRoot);
154
155  ExpandedNodes.clear();
156  LegalizedNodes.clear();
157  PromotedNodes.clear();
158
159  // Remove dead nodes now.
160  DAG.RemoveDeadNodes(OldRoot.Val);
161}
162
163SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
164  assert(getTypeAction(Op.getValueType()) == Legal &&
165         "Caller should expand or promote operands that are not legal!");
166  SDNode *Node = Op.Val;
167
168  // If this operation defines any values that cannot be represented in a
169  // register on this target, make sure to expand or promote them.
170  if (Node->getNumValues() > 1) {
171    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
172      switch (getTypeAction(Node->getValueType(i))) {
173      case Legal: break;  // Nothing to do.
174      case Expand: {
175        SDOperand T1, T2;
176        ExpandOp(Op.getValue(i), T1, T2);
177        assert(LegalizedNodes.count(Op) &&
178               "Expansion didn't add legal operands!");
179        return LegalizedNodes[Op];
180      }
181      case Promote:
182        PromoteOp(Op.getValue(i));
183        assert(LegalizedNodes.count(Op) &&
184               "Expansion didn't add legal operands!");
185        return LegalizedNodes[Op];
186      }
187  }
188
189  // Note that LegalizeOp may be reentered even from single-use nodes, which
190  // means that we always must cache transformed nodes.
191  std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
192  if (I != LegalizedNodes.end()) return I->second;
193
194  SDOperand Tmp1, Tmp2, Tmp3;
195
196  SDOperand Result = Op;
197
198  switch (Node->getOpcode()) {
199  default:
200    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
201      // If this is a target node, legalize it by legalizing the operands then
202      // passing it through.
203      std::vector<SDOperand> Ops;
204      bool Changed = false;
205      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
206        Ops.push_back(LegalizeOp(Node->getOperand(i)));
207        Changed = Changed || Node->getOperand(i) != Ops.back();
208      }
209      if (Changed)
210        if (Node->getNumValues() == 1)
211          Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
212        else {
213          std::vector<MVT::ValueType> VTs(Node->value_begin(),
214                                          Node->value_end());
215          Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
216        }
217
218      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
219        AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
220      return Result.getValue(Op.ResNo);
221    }
222    // Otherwise this is an unhandled builtin node.  splat.
223    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
224    assert(0 && "Do not know how to legalize this operator!");
225    abort();
226  case ISD::EntryToken:
227  case ISD::FrameIndex:
228  case ISD::GlobalAddress:
229  case ISD::ExternalSymbol:
230  case ISD::ConstantPool:           // Nothing to do.
231    assert(getTypeAction(Node->getValueType(0)) == Legal &&
232           "This must be legal!");
233    break;
234  case ISD::CopyFromReg:
235    Tmp1 = LegalizeOp(Node->getOperand(0));
236    if (Tmp1 != Node->getOperand(0))
237      Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
238                                  Node->getValueType(0), Tmp1);
239    else
240      Result = Op.getValue(0);
241
242    // Since CopyFromReg produces two values, make sure to remember that we
243    // legalized both of them.
244    AddLegalizedOperand(Op.getValue(0), Result);
245    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
246    return Result.getValue(Op.ResNo);
247  case ISD::ImplicitDef:
248    Tmp1 = LegalizeOp(Node->getOperand(0));
249    if (Tmp1 != Node->getOperand(0))
250      Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
251    break;
252  case ISD::UNDEF: {
253    MVT::ValueType VT = Op.getValueType();
254    switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
255    default: assert(0 && "This action is not supported yet!");
256    case TargetLowering::Expand:
257    case TargetLowering::Promote:
258      if (MVT::isInteger(VT))
259        Result = DAG.getConstant(0, VT);
260      else if (MVT::isFloatingPoint(VT))
261        Result = DAG.getConstantFP(0, VT);
262      else
263        assert(0 && "Unknown value type!");
264      break;
265    case TargetLowering::Legal:
266      break;
267    }
268    break;
269  }
270  case ISD::Constant:
271    // We know we don't need to expand constants here, constants only have one
272    // value and we check that it is fine above.
273
274    // FIXME: Maybe we should handle things like targets that don't support full
275    // 32-bit immediates?
276    break;
277  case ISD::ConstantFP: {
278    // Spill FP immediates to the constant pool if the target cannot directly
279    // codegen them.  Targets often have some immediate values that can be
280    // efficiently generated into an FP register without a load.  We explicitly
281    // leave these constants as ConstantFP nodes for the target to deal with.
282
283    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
284
285    // Check to see if this FP immediate is already legal.
286    bool isLegal = false;
287    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
288           E = TLI.legal_fpimm_end(); I != E; ++I)
289      if (CFP->isExactlyValue(*I)) {
290        isLegal = true;
291        break;
292      }
293
294    if (!isLegal) {
295      // Otherwise we need to spill the constant to memory.
296      MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
297
298      bool Extend = false;
299
300      // If a FP immediate is precise when represented as a float, we put it
301      // into the constant pool as a float, even if it's is statically typed
302      // as a double.
303      MVT::ValueType VT = CFP->getValueType(0);
304      bool isDouble = VT == MVT::f64;
305      ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
306                                             Type::FloatTy, CFP->getValue());
307      if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
308          // Only do this if the target has a native EXTLOAD instruction from
309          // f32.
310          TLI.getOperationAction(ISD::EXTLOAD,
311                                 MVT::f32) == TargetLowering::Legal) {
312        LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
313        VT = MVT::f32;
314        Extend = true;
315      }
316
317      SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
318                                            TLI.getPointerTy());
319      if (Extend) {
320        Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
321                                CPIdx, DAG.getSrcValue(NULL), MVT::f32);
322      } else {
323        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
324                             DAG.getSrcValue(NULL));
325      }
326    }
327    break;
328  }
329  case ISD::TokenFactor: {
330    std::vector<SDOperand> Ops;
331    bool Changed = false;
332    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
333      SDOperand Op = Node->getOperand(i);
334      // Fold single-use TokenFactor nodes into this token factor as we go.
335      // FIXME: This is something that the DAGCombiner should do!!
336      if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
337        Changed = true;
338        for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
339          Ops.push_back(LegalizeOp(Op.getOperand(j)));
340      } else {
341        Ops.push_back(LegalizeOp(Op));  // Legalize the operands
342        Changed |= Ops[i] != Op;
343      }
344    }
345    if (Changed)
346      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
347    break;
348  }
349
350  case ISD::CALLSEQ_START:
351  case ISD::CALLSEQ_END:
352    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
353    // Do not try to legalize the target-specific arguments (#1+)
354    Tmp2 = Node->getOperand(0);
355    if (Tmp1 != Tmp2) {
356      Node->setAdjCallChain(Tmp1);
357
358      // If moving the operand from pointing to Tmp2 dropped its use count to 1,
359      // this will cause the maps used to memoize results to get confused.
360      // Create and add a dummy use, just to increase its use count.  This will
361      // be removed at the end of legalize when dead nodes are removed.
362      if (Tmp2.Val->hasOneUse())
363        DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp2,
364                    DAG.getConstant(0, MVT::i32));
365    }
366    // Note that we do not create new CALLSEQ_DOWN/UP nodes here.  These
367    // nodes are treated specially and are mutated in place.  This makes the dag
368    // legalization process more efficient and also makes libcall insertion
369    // easier.
370    break;
371  case ISD::DYNAMIC_STACKALLOC:
372    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
373    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
374    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
375    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
376        Tmp3 != Node->getOperand(2)) {
377      std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
378      std::vector<SDOperand> Ops;
379      Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
380      Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
381    } else
382      Result = Op.getValue(0);
383
384    // Since this op produces two values, make sure to remember that we
385    // legalized both of them.
386    AddLegalizedOperand(SDOperand(Node, 0), Result);
387    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
388    return Result.getValue(Op.ResNo);
389
390  case ISD::TAILCALL:
391  case ISD::CALL: {
392    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
393    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
394
395    bool Changed = false;
396    std::vector<SDOperand> Ops;
397    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
398      Ops.push_back(LegalizeOp(Node->getOperand(i)));
399      Changed |= Ops.back() != Node->getOperand(i);
400    }
401
402    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) || Changed) {
403      std::vector<MVT::ValueType> RetTyVTs;
404      RetTyVTs.reserve(Node->getNumValues());
405      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
406        RetTyVTs.push_back(Node->getValueType(i));
407      Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops,
408                                     Node->getOpcode() == ISD::TAILCALL), 0);
409    } else {
410      Result = Result.getValue(0);
411    }
412    // Since calls produce multiple values, make sure to remember that we
413    // legalized all of them.
414    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
415      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
416    return Result.getValue(Op.ResNo);
417  }
418  case ISD::BR:
419    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
420    if (Tmp1 != Node->getOperand(0))
421      Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
422    break;
423
424  case ISD::BRCOND:
425    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
426
427    switch (getTypeAction(Node->getOperand(1).getValueType())) {
428    case Expand: assert(0 && "It's impossible to expand bools");
429    case Legal:
430      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
431      break;
432    case Promote:
433      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
434      break;
435    }
436    // Basic block destination (Op#2) is always legal.
437    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
438      Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
439                           Node->getOperand(2));
440    break;
441  case ISD::BRCONDTWOWAY:
442    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
443    switch (getTypeAction(Node->getOperand(1).getValueType())) {
444    case Expand: assert(0 && "It's impossible to expand bools");
445    case Legal:
446      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
447      break;
448    case Promote:
449      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
450      break;
451    }
452    // If this target does not support BRCONDTWOWAY, lower it to a BRCOND/BR
453    // pair.
454    switch (TLI.getOperationAction(ISD::BRCONDTWOWAY, MVT::Other)) {
455    case TargetLowering::Promote:
456    default: assert(0 && "This action is not supported yet!");
457    case TargetLowering::Legal:
458      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
459        std::vector<SDOperand> Ops;
460        Ops.push_back(Tmp1);
461        Ops.push_back(Tmp2);
462        Ops.push_back(Node->getOperand(2));
463        Ops.push_back(Node->getOperand(3));
464        Result = DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops);
465      }
466      break;
467    case TargetLowering::Expand:
468      Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
469                           Node->getOperand(2));
470      Result = DAG.getNode(ISD::BR, MVT::Other, Result, Node->getOperand(3));
471      break;
472    }
473    break;
474
475  case ISD::LOAD:
476    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
477    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
478
479    if (Tmp1 != Node->getOperand(0) ||
480        Tmp2 != Node->getOperand(1))
481      Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2,
482                           Node->getOperand(2));
483    else
484      Result = SDOperand(Node, 0);
485
486    // Since loads produce two values, make sure to remember that we legalized
487    // both of them.
488    AddLegalizedOperand(SDOperand(Node, 0), Result);
489    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
490    return Result.getValue(Op.ResNo);
491
492  case ISD::EXTLOAD:
493  case ISD::SEXTLOAD:
494  case ISD::ZEXTLOAD: {
495    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
496    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
497
498    MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
499    switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
500    default: assert(0 && "This action is not supported yet!");
501    case TargetLowering::Promote:
502      assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
503      Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
504                              Tmp1, Tmp2, Node->getOperand(2), MVT::i8);
505      // Since loads produce two values, make sure to remember that we legalized
506      // both of them.
507      AddLegalizedOperand(SDOperand(Node, 0), Result);
508      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
509      return Result.getValue(Op.ResNo);
510
511    case TargetLowering::Legal:
512      if (Tmp1 != Node->getOperand(0) ||
513          Tmp2 != Node->getOperand(1))
514        Result = DAG.getExtLoad(Node->getOpcode(), Node->getValueType(0),
515                                Tmp1, Tmp2, Node->getOperand(2), SrcVT);
516      else
517        Result = SDOperand(Node, 0);
518
519      // Since loads produce two values, make sure to remember that we legalized
520      // both of them.
521      AddLegalizedOperand(SDOperand(Node, 0), Result);
522      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
523      return Result.getValue(Op.ResNo);
524    case TargetLowering::Expand:
525      //f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
526      if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
527        SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
528        Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
529        if (Op.ResNo)
530          return Load.getValue(1);
531        return Result;
532      }
533      assert(Node->getOpcode() != ISD::EXTLOAD &&
534             "EXTLOAD should always be supported!");
535      // Turn the unsupported load into an EXTLOAD followed by an explicit
536      // zero/sign extend inreg.
537      Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
538                              Tmp1, Tmp2, Node->getOperand(2), SrcVT);
539      SDOperand ValRes;
540      if (Node->getOpcode() == ISD::SEXTLOAD)
541        ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
542                             Result, DAG.getValueType(SrcVT));
543      else
544        ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
545      AddLegalizedOperand(SDOperand(Node, 0), ValRes);
546      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
547      if (Op.ResNo)
548        return Result.getValue(1);
549      return ValRes;
550    }
551    assert(0 && "Unreachable");
552  }
553  case ISD::EXTRACT_ELEMENT:
554    // Get both the low and high parts.
555    ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
556    if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
557      Result = Tmp2;  // 1 -> Hi
558    else
559      Result = Tmp1;  // 0 -> Lo
560    break;
561
562  case ISD::CopyToReg:
563    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
564
565    switch (getTypeAction(Node->getOperand(1).getValueType())) {
566    case Legal:
567      // Legalize the incoming value (must be legal).
568      Tmp2 = LegalizeOp(Node->getOperand(1));
569      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
570        Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
571      break;
572    case Promote:
573      Tmp2 = PromoteOp(Node->getOperand(1));
574      Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
575      break;
576    case Expand:
577      SDOperand Lo, Hi;
578      ExpandOp(Node->getOperand(1), Lo, Hi);
579      unsigned Reg = cast<RegSDNode>(Node)->getReg();
580      Lo = DAG.getCopyToReg(Tmp1, Lo, Reg);
581      Hi = DAG.getCopyToReg(Tmp1, Hi, Reg+1);
582      // Note that the copytoreg nodes are independent of each other.
583      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
584      assert(isTypeLegal(Result.getValueType()) &&
585             "Cannot expand multiple times yet (i64 -> i16)");
586      break;
587    }
588    break;
589
590  case ISD::RET:
591    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
592    switch (Node->getNumOperands()) {
593    case 2:  // ret val
594      switch (getTypeAction(Node->getOperand(1).getValueType())) {
595      case Legal:
596        Tmp2 = LegalizeOp(Node->getOperand(1));
597        if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
598          Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
599        break;
600      case Expand: {
601        SDOperand Lo, Hi;
602        ExpandOp(Node->getOperand(1), Lo, Hi);
603        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
604        break;
605      }
606      case Promote:
607        Tmp2 = PromoteOp(Node->getOperand(1));
608        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
609        break;
610      }
611      break;
612    case 1:  // ret void
613      if (Tmp1 != Node->getOperand(0))
614        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
615      break;
616    default: { // ret <values>
617      std::vector<SDOperand> NewValues;
618      NewValues.push_back(Tmp1);
619      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
620        switch (getTypeAction(Node->getOperand(i).getValueType())) {
621        case Legal:
622          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
623          break;
624        case Expand: {
625          SDOperand Lo, Hi;
626          ExpandOp(Node->getOperand(i), Lo, Hi);
627          NewValues.push_back(Lo);
628          NewValues.push_back(Hi);
629          break;
630        }
631        case Promote:
632          assert(0 && "Can't promote multiple return value yet!");
633        }
634      Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
635      break;
636    }
637    }
638    break;
639  case ISD::STORE:
640    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
641    Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
642
643    // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
644    if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
645      if (CFP->getValueType(0) == MVT::f32) {
646        union {
647          unsigned I;
648          float    F;
649        } V;
650        V.F = CFP->getValue();
651        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
652                             DAG.getConstant(V.I, MVT::i32), Tmp2,
653                             Node->getOperand(3));
654      } else {
655        assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
656        union {
657          uint64_t I;
658          double   F;
659        } V;
660        V.F = CFP->getValue();
661        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
662                             DAG.getConstant(V.I, MVT::i64), Tmp2,
663                             Node->getOperand(3));
664      }
665      Node = Result.Val;
666    }
667
668    switch (getTypeAction(Node->getOperand(1).getValueType())) {
669    case Legal: {
670      SDOperand Val = LegalizeOp(Node->getOperand(1));
671      if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
672          Tmp2 != Node->getOperand(2))
673        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2,
674                             Node->getOperand(3));
675      break;
676    }
677    case Promote:
678      // Truncate the value and store the result.
679      Tmp3 = PromoteOp(Node->getOperand(1));
680      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
681                           Node->getOperand(3),
682                          DAG.getValueType(Node->getOperand(1).getValueType()));
683      break;
684
685    case Expand:
686      SDOperand Lo, Hi;
687      ExpandOp(Node->getOperand(1), Lo, Hi);
688
689      if (!TLI.isLittleEndian())
690        std::swap(Lo, Hi);
691
692      Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
693                       Node->getOperand(3));
694      unsigned IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
695      Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
696                         getIntPtrConstant(IncrementSize));
697      assert(isTypeLegal(Tmp2.getValueType()) &&
698             "Pointers must be legal!");
699      //Again, claiming both parts of the store came form the same Instr
700      Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
701                       Node->getOperand(3));
702      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
703      break;
704    }
705    break;
706  case ISD::PCMARKER:
707    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
708    if (Tmp1 != Node->getOperand(0))
709      Result = DAG.getNode(ISD::PCMARKER, MVT::Other, Tmp1,Node->getOperand(1));
710    break;
711  case ISD::TRUNCSTORE:
712    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
713    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
714
715    switch (getTypeAction(Node->getOperand(1).getValueType())) {
716    case Legal:
717      Tmp2 = LegalizeOp(Node->getOperand(1));
718      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
719          Tmp3 != Node->getOperand(2))
720        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
721                             Node->getOperand(3), Node->getOperand(4));
722      break;
723    case Promote:
724    case Expand:
725      assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
726    }
727    break;
728  case ISD::SELECT:
729    switch (getTypeAction(Node->getOperand(0).getValueType())) {
730    case Expand: assert(0 && "It's impossible to expand bools");
731    case Legal:
732      Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
733      break;
734    case Promote:
735      Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
736      break;
737    }
738    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
739    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
740
741    switch (TLI.getOperationAction(Node->getOpcode(), Tmp2.getValueType())) {
742    default: assert(0 && "This action is not supported yet!");
743    case TargetLowering::Legal:
744      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
745          Tmp3 != Node->getOperand(2))
746        Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
747                             Tmp1, Tmp2, Tmp3);
748      break;
749    case TargetLowering::Promote: {
750      MVT::ValueType NVT =
751        TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
752      unsigned ExtOp, TruncOp;
753      if (MVT::isInteger(Tmp2.getValueType())) {
754        ExtOp = ISD::ZERO_EXTEND;
755        TruncOp  = ISD::TRUNCATE;
756      } else {
757        ExtOp = ISD::FP_EXTEND;
758        TruncOp  = ISD::FP_ROUND;
759      }
760      // Promote each of the values to the new type.
761      Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
762      Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
763      // Perform the larger operation, then round down.
764      Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
765      Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
766      break;
767    }
768    }
769    break;
770  case ISD::SETCC:
771    switch (getTypeAction(Node->getOperand(0).getValueType())) {
772    case Legal:
773      Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
774      Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
775      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
776        Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
777                              Node->getValueType(0), Tmp1, Tmp2);
778      break;
779    case Promote:
780      Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
781      Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
782
783      // If this is an FP compare, the operands have already been extended.
784      if (MVT::isInteger(Node->getOperand(0).getValueType())) {
785        MVT::ValueType VT = Node->getOperand(0).getValueType();
786        MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
787
788        // Otherwise, we have to insert explicit sign or zero extends.  Note
789        // that we could insert sign extends for ALL conditions, but zero extend
790        // is cheaper on many machines (an AND instead of two shifts), so prefer
791        // it.
792        switch (cast<SetCCSDNode>(Node)->getCondition()) {
793        default: assert(0 && "Unknown integer comparison!");
794        case ISD::SETEQ:
795        case ISD::SETNE:
796        case ISD::SETUGE:
797        case ISD::SETUGT:
798        case ISD::SETULE:
799        case ISD::SETULT:
800          // ALL of these operations will work if we either sign or zero extend
801          // the operands (including the unsigned comparisons!).  Zero extend is
802          // usually a simpler/cheaper operation, so prefer it.
803          Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
804          Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
805          break;
806        case ISD::SETGE:
807        case ISD::SETGT:
808        case ISD::SETLT:
809        case ISD::SETLE:
810          Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
811                             DAG.getValueType(VT));
812          Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
813                             DAG.getValueType(VT));
814          break;
815        }
816
817      }
818      Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
819                            Node->getValueType(0), Tmp1, Tmp2);
820      break;
821    case Expand:
822      SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
823      ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
824      ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
825      switch (cast<SetCCSDNode>(Node)->getCondition()) {
826      case ISD::SETEQ:
827      case ISD::SETNE:
828        if (RHSLo == RHSHi)
829          if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
830            if (RHSCST->isAllOnesValue()) {
831              // Comparison to -1.
832              Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
833              Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
834                                    Node->getValueType(0), Tmp1, RHSLo);
835              break;
836            }
837
838        Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
839        Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
840        Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
841        Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
842                              Node->getValueType(0), Tmp1,
843                              DAG.getConstant(0, Tmp1.getValueType()));
844        break;
845      default:
846        // If this is a comparison of the sign bit, just look at the top part.
847        // X > -1,  x < 0
848        if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
849          if ((cast<SetCCSDNode>(Node)->getCondition() == ISD::SETLT &&
850               CST->getValue() == 0) ||              // X < 0
851              (cast<SetCCSDNode>(Node)->getCondition() == ISD::SETGT &&
852               (CST->isAllOnesValue())))             // X > -1
853            return DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
854                                Node->getValueType(0), LHSHi, RHSHi);
855
856        // FIXME: This generated code sucks.
857        ISD::CondCode LowCC;
858        switch (cast<SetCCSDNode>(Node)->getCondition()) {
859        default: assert(0 && "Unknown integer setcc!");
860        case ISD::SETLT:
861        case ISD::SETULT: LowCC = ISD::SETULT; break;
862        case ISD::SETGT:
863        case ISD::SETUGT: LowCC = ISD::SETUGT; break;
864        case ISD::SETLE:
865        case ISD::SETULE: LowCC = ISD::SETULE; break;
866        case ISD::SETGE:
867        case ISD::SETUGE: LowCC = ISD::SETUGE; break;
868        }
869
870        // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
871        // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
872        // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
873
874        // NOTE: on targets without efficient SELECT of bools, we can always use
875        // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
876        Tmp1 = DAG.getSetCC(LowCC, Node->getValueType(0), LHSLo, RHSLo);
877        Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
878                            Node->getValueType(0), LHSHi, RHSHi);
879        Result = DAG.getSetCC(ISD::SETEQ, Node->getValueType(0), LHSHi, RHSHi);
880        Result = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
881                             Result, Tmp1, Tmp2);
882        break;
883      }
884    }
885    break;
886
887  case ISD::MEMSET:
888  case ISD::MEMCPY:
889  case ISD::MEMMOVE: {
890    Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
891    Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
892
893    if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
894      switch (getTypeAction(Node->getOperand(2).getValueType())) {
895      case Expand: assert(0 && "Cannot expand a byte!");
896      case Legal:
897        Tmp3 = LegalizeOp(Node->getOperand(2));
898        break;
899      case Promote:
900        Tmp3 = PromoteOp(Node->getOperand(2));
901        break;
902      }
903    } else {
904      Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
905    }
906
907    SDOperand Tmp4;
908    switch (getTypeAction(Node->getOperand(3).getValueType())) {
909    case Expand: {
910      // Length is too big, just take the lo-part of the length.
911      SDOperand HiPart;
912      ExpandOp(Node->getOperand(3), HiPart, Tmp4);
913      break;
914    }
915    case Legal:
916      Tmp4 = LegalizeOp(Node->getOperand(3));
917      break;
918    case Promote:
919      Tmp4 = PromoteOp(Node->getOperand(3));
920      break;
921    }
922
923    SDOperand Tmp5;
924    switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
925    case Expand: assert(0 && "Cannot expand this yet!");
926    case Legal:
927      Tmp5 = LegalizeOp(Node->getOperand(4));
928      break;
929    case Promote:
930      Tmp5 = PromoteOp(Node->getOperand(4));
931      break;
932    }
933
934    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
935    default: assert(0 && "This action not implemented for this operation!");
936    case TargetLowering::Legal:
937      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
938          Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
939          Tmp5 != Node->getOperand(4)) {
940        std::vector<SDOperand> Ops;
941        Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
942        Ops.push_back(Tmp4); Ops.push_back(Tmp5);
943        Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
944      }
945      break;
946    case TargetLowering::Expand: {
947      // Otherwise, the target does not support this operation.  Lower the
948      // operation to an explicit libcall as appropriate.
949      MVT::ValueType IntPtr = TLI.getPointerTy();
950      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
951      std::vector<std::pair<SDOperand, const Type*> > Args;
952
953      const char *FnName = 0;
954      if (Node->getOpcode() == ISD::MEMSET) {
955        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
956        // Extend the ubyte argument to be an int value for the call.
957        Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
958        Args.push_back(std::make_pair(Tmp3, Type::IntTy));
959        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
960
961        FnName = "memset";
962      } else if (Node->getOpcode() == ISD::MEMCPY ||
963                 Node->getOpcode() == ISD::MEMMOVE) {
964        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
965        Args.push_back(std::make_pair(Tmp3, IntPtrTy));
966        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
967        FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
968      } else {
969        assert(0 && "Unknown op!");
970      }
971
972      std::pair<SDOperand,SDOperand> CallResult =
973        TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
974                        DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
975      Result = LegalizeOp(CallResult.second);
976      break;
977    }
978    case TargetLowering::Custom:
979      std::vector<SDOperand> Ops;
980      Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
981      Ops.push_back(Tmp4); Ops.push_back(Tmp5);
982      Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
983      Result = TLI.LowerOperation(Result, DAG);
984      Result = LegalizeOp(Result);
985      break;
986    }
987    break;
988  }
989
990  case ISD::READPORT:
991    Tmp1 = LegalizeOp(Node->getOperand(0));
992    Tmp2 = LegalizeOp(Node->getOperand(1));
993
994    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
995      std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
996      std::vector<SDOperand> Ops;
997      Ops.push_back(Tmp1);
998      Ops.push_back(Tmp2);
999      Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1000    } else
1001      Result = SDOperand(Node, 0);
1002    // Since these produce two values, make sure to remember that we legalized
1003    // both of them.
1004    AddLegalizedOperand(SDOperand(Node, 0), Result);
1005    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1006    return Result.getValue(Op.ResNo);
1007  case ISD::WRITEPORT:
1008    Tmp1 = LegalizeOp(Node->getOperand(0));
1009    Tmp2 = LegalizeOp(Node->getOperand(1));
1010    Tmp3 = LegalizeOp(Node->getOperand(2));
1011    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1012        Tmp3 != Node->getOperand(2))
1013      Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1014    break;
1015
1016  case ISD::READIO:
1017    Tmp1 = LegalizeOp(Node->getOperand(0));
1018    Tmp2 = LegalizeOp(Node->getOperand(1));
1019
1020    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1021    case TargetLowering::Custom:
1022    default: assert(0 && "This action not implemented for this operation!");
1023    case TargetLowering::Legal:
1024      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
1025        std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1026        std::vector<SDOperand> Ops;
1027        Ops.push_back(Tmp1);
1028        Ops.push_back(Tmp2);
1029        Result = DAG.getNode(ISD::READPORT, VTs, Ops);
1030      } else
1031        Result = SDOperand(Node, 0);
1032      break;
1033    case TargetLowering::Expand:
1034      // Replace this with a load from memory.
1035      Result = DAG.getLoad(Node->getValueType(0), Node->getOperand(0),
1036                           Node->getOperand(1), DAG.getSrcValue(NULL));
1037      Result = LegalizeOp(Result);
1038      break;
1039    }
1040
1041    // Since these produce two values, make sure to remember that we legalized
1042    // both of them.
1043    AddLegalizedOperand(SDOperand(Node, 0), Result);
1044    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1045    return Result.getValue(Op.ResNo);
1046
1047  case ISD::WRITEIO:
1048    Tmp1 = LegalizeOp(Node->getOperand(0));
1049    Tmp2 = LegalizeOp(Node->getOperand(1));
1050    Tmp3 = LegalizeOp(Node->getOperand(2));
1051
1052    switch (TLI.getOperationAction(Node->getOpcode(),
1053                                   Node->getOperand(1).getValueType())) {
1054    case TargetLowering::Custom:
1055    default: assert(0 && "This action not implemented for this operation!");
1056    case TargetLowering::Legal:
1057      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1058          Tmp3 != Node->getOperand(2))
1059        Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1, Tmp2, Tmp3);
1060      break;
1061    case TargetLowering::Expand:
1062      // Replace this with a store to memory.
1063      Result = DAG.getNode(ISD::STORE, MVT::Other, Node->getOperand(0),
1064                           Node->getOperand(1), Node->getOperand(2),
1065                           DAG.getSrcValue(NULL));
1066      Result = LegalizeOp(Result);
1067      break;
1068    }
1069    break;
1070
1071  case ISD::ADD_PARTS:
1072  case ISD::SUB_PARTS:
1073  case ISD::SHL_PARTS:
1074  case ISD::SRA_PARTS:
1075  case ISD::SRL_PARTS: {
1076    std::vector<SDOperand> Ops;
1077    bool Changed = false;
1078    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1079      Ops.push_back(LegalizeOp(Node->getOperand(i)));
1080      Changed |= Ops.back() != Node->getOperand(i);
1081    }
1082    if (Changed) {
1083      std::vector<MVT::ValueType> VTs(Node->value_begin(), Node->value_end());
1084      Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
1085    }
1086
1087    // Since these produce multiple values, make sure to remember that we
1088    // legalized all of them.
1089    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1090      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
1091    return Result.getValue(Op.ResNo);
1092  }
1093
1094    // Binary operators
1095  case ISD::ADD:
1096  case ISD::SUB:
1097  case ISD::MUL:
1098  case ISD::MULHS:
1099  case ISD::MULHU:
1100  case ISD::UDIV:
1101  case ISD::SDIV:
1102  case ISD::AND:
1103  case ISD::OR:
1104  case ISD::XOR:
1105  case ISD::SHL:
1106  case ISD::SRL:
1107  case ISD::SRA:
1108    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1109    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1110    case Expand: assert(0 && "Not possible");
1111    case Legal:
1112      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
1113      break;
1114    case Promote:
1115      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
1116      break;
1117    }
1118    if (Tmp1 != Node->getOperand(0) ||
1119        Tmp2 != Node->getOperand(1))
1120      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
1121    break;
1122
1123  case ISD::UREM:
1124  case ISD::SREM:
1125    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
1126    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
1127    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1128    case TargetLowering::Legal:
1129      if (Tmp1 != Node->getOperand(0) ||
1130          Tmp2 != Node->getOperand(1))
1131        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
1132                             Tmp2);
1133      break;
1134    case TargetLowering::Promote:
1135    case TargetLowering::Custom:
1136      assert(0 && "Cannot promote/custom handle this yet!");
1137    case TargetLowering::Expand: {
1138      MVT::ValueType VT = Node->getValueType(0);
1139      unsigned Opc = (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
1140      Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
1141      Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
1142      Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
1143      }
1144      break;
1145    }
1146    break;
1147
1148  case ISD::CTPOP:
1149  case ISD::CTTZ:
1150  case ISD::CTLZ:
1151    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
1152    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1153    case TargetLowering::Legal:
1154      if (Tmp1 != Node->getOperand(0))
1155        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1156      break;
1157    case TargetLowering::Promote: {
1158      MVT::ValueType OVT = Tmp1.getValueType();
1159      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1160
1161      // Zero extend the argument.
1162      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
1163      // Perform the larger operation, then subtract if needed.
1164      Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1165      switch(Node->getOpcode())
1166      {
1167      case ISD::CTPOP:
1168        Result = Tmp1;
1169        break;
1170      case ISD::CTTZ:
1171        //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
1172        Tmp2 = DAG.getSetCC(ISD::SETEQ, TLI.getSetCCResultTy(), Tmp1,
1173                            DAG.getConstant(getSizeInBits(NVT), NVT));
1174        Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
1175                           DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
1176        break;
1177      case ISD::CTLZ:
1178        //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
1179        Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
1180                             DAG.getConstant(getSizeInBits(NVT) -
1181                                             getSizeInBits(OVT), NVT));
1182        break;
1183      }
1184      break;
1185    }
1186    case TargetLowering::Custom:
1187      assert(0 && "Cannot custom handle this yet!");
1188    case TargetLowering::Expand:
1189      switch(Node->getOpcode())
1190      {
1191      case ISD::CTPOP: {
1192        static const uint64_t mask[6] = {
1193          0x5555555555555555ULL, 0x3333333333333333ULL,
1194          0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
1195          0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
1196        };
1197        MVT::ValueType VT = Tmp1.getValueType();
1198        MVT::ValueType ShVT = TLI.getShiftAmountTy();
1199        unsigned len = getSizeInBits(VT);
1200        for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
1201          //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
1202          Tmp2 = DAG.getConstant(mask[i], VT);
1203          Tmp3 = DAG.getConstant(1ULL << i, ShVT);
1204          Tmp1 = DAG.getNode(ISD::ADD, VT,
1205                             DAG.getNode(ISD::AND, VT, Tmp1, Tmp2),
1206                             DAG.getNode(ISD::AND, VT,
1207                                         DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3),
1208                                         Tmp2));
1209        }
1210        Result = Tmp1;
1211        break;
1212      }
1213      case ISD::CTLZ: {
1214        /* for now, we do this:
1215           x = x | (x >> 1);
1216           x = x | (x >> 2);
1217           ...
1218           x = x | (x >>16);
1219           x = x | (x >>32); // for 64-bit input
1220           return popcount(~x);
1221
1222           but see also: http://www.hackersdelight.org/HDcode/nlz.cc */
1223        MVT::ValueType VT = Tmp1.getValueType();
1224        MVT::ValueType ShVT = TLI.getShiftAmountTy();
1225        unsigned len = getSizeInBits(VT);
1226        for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
1227          Tmp3 = DAG.getConstant(1ULL << i, ShVT);
1228          Tmp1 = DAG.getNode(ISD::OR, VT, Tmp1,
1229                             DAG.getNode(ISD::SRL, VT, Tmp1, Tmp3));
1230        }
1231        Tmp3 = DAG.getNode(ISD::XOR, VT, Tmp1, DAG.getConstant(~0ULL, VT));
1232        Result = LegalizeOp(DAG.getNode(ISD::CTPOP, VT, Tmp3));
1233        break;
1234      }
1235      case ISD::CTTZ: {
1236        // for now, we use: { return popcount(~x & (x - 1)); }
1237        // unless the target has ctlz but not ctpop, in which case we use:
1238        // { return 32 - nlz(~x & (x-1)); }
1239        // see also http://www.hackersdelight.org/HDcode/ntz.cc
1240        MVT::ValueType VT = Tmp1.getValueType();
1241        Tmp2 = DAG.getConstant(~0ULL, VT);
1242        Tmp3 = DAG.getNode(ISD::AND, VT,
1243                           DAG.getNode(ISD::XOR, VT, Tmp1, Tmp2),
1244                           DAG.getNode(ISD::SUB, VT, Tmp1,
1245                                       DAG.getConstant(1, VT)));
1246        // If ISD::CTLZ is legal and CTPOP isn't, then do that instead
1247        if (TLI.getOperationAction(ISD::CTPOP, VT) != TargetLowering::Legal &&
1248            TLI.getOperationAction(ISD::CTLZ, VT) == TargetLowering::Legal) {
1249          Result = LegalizeOp(DAG.getNode(ISD::SUB, VT,
1250                                        DAG.getConstant(getSizeInBits(VT), VT),
1251                                        DAG.getNode(ISD::CTLZ, VT, Tmp3)));
1252        } else {
1253          Result = LegalizeOp(DAG.getNode(ISD::CTPOP, VT, Tmp3));
1254        }
1255        break;
1256      }
1257      default:
1258        assert(0 && "Cannot expand this yet!");
1259        break;
1260      }
1261      break;
1262    }
1263    break;
1264
1265    // Unary operators
1266  case ISD::FABS:
1267  case ISD::FNEG:
1268  case ISD::FSQRT:
1269  case ISD::FSIN:
1270  case ISD::FCOS:
1271    Tmp1 = LegalizeOp(Node->getOperand(0));
1272    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1273    case TargetLowering::Legal:
1274      if (Tmp1 != Node->getOperand(0))
1275        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1276      break;
1277    case TargetLowering::Promote:
1278    case TargetLowering::Custom:
1279      assert(0 && "Cannot promote/custom handle this yet!");
1280    case TargetLowering::Expand:
1281      switch(Node->getOpcode()) {
1282      case ISD::FNEG: {
1283        // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
1284        Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
1285        Result = LegalizeOp(DAG.getNode(ISD::SUB, Node->getValueType(0),
1286                                        Tmp2, Tmp1));
1287        break;
1288      }
1289      case ISD::FABS: {
1290        // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
1291        MVT::ValueType VT = Node->getValueType(0);
1292        Tmp2 = DAG.getConstantFP(0.0, VT);
1293        Tmp2 = DAG.getSetCC(ISD::SETUGT, TLI.getSetCCResultTy(), Tmp1, Tmp2);
1294        Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
1295        Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
1296        Result = LegalizeOp(Result);
1297        break;
1298      }
1299      case ISD::FSQRT:
1300      case ISD::FSIN:
1301      case ISD::FCOS: {
1302        MVT::ValueType VT = Node->getValueType(0);
1303        Type *T = VT == MVT::f32 ? Type::FloatTy : Type::DoubleTy;
1304        const char *FnName = 0;
1305        switch(Node->getOpcode()) {
1306        case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
1307        case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
1308        case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
1309        default: assert(0 && "Unreachable!");
1310        }
1311        std::vector<std::pair<SDOperand, const Type*> > Args;
1312        Args.push_back(std::make_pair(Tmp1, T));
1313        // FIXME: should use ExpandLibCall!
1314        std::pair<SDOperand,SDOperand> CallResult =
1315          TLI.LowerCallTo(DAG.getEntryNode(), T, false, CallingConv::C, true,
1316                          DAG.getExternalSymbol(FnName, VT), Args, DAG);
1317        Result = LegalizeOp(CallResult.first);
1318        break;
1319      }
1320      default:
1321        assert(0 && "Unreachable!");
1322      }
1323      break;
1324    }
1325    break;
1326
1327    // Conversion operators.  The source and destination have different types.
1328  case ISD::ZERO_EXTEND:
1329  case ISD::SIGN_EXTEND:
1330  case ISD::TRUNCATE:
1331  case ISD::FP_EXTEND:
1332  case ISD::FP_ROUND:
1333  case ISD::FP_TO_SINT:
1334  case ISD::FP_TO_UINT:
1335  case ISD::SINT_TO_FP:
1336  case ISD::UINT_TO_FP:
1337    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1338    case Legal:
1339      //still made need to expand if the op is illegal, but the types are legal
1340      if (Node->getOpcode() == ISD::UINT_TO_FP &&
1341          TLI.getOperationAction(Node->getOpcode(),
1342                                 Node->getOperand(0).getValueType())
1343          == TargetLowering::Expand) {
1344        SDOperand Op0 = LegalizeOp(Node->getOperand(0));
1345        Tmp1 = DAG.getNode(ISD::SINT_TO_FP, Node->getValueType(0),
1346                           Op0);
1347
1348        SDOperand SignSet = DAG.getSetCC(ISD::SETLT, TLI.getSetCCResultTy(),
1349                                         Op0,
1350                                         DAG.getConstant(0,
1351                                         Op0.getValueType()));
1352        SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
1353        SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
1354                                          SignSet, Four, Zero);
1355        uint64_t FF = 0x5f800000ULL;
1356        if (TLI.isLittleEndian()) FF <<= 32;
1357        static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
1358
1359        MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
1360        SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(FudgeFactor),
1361                                              TLI.getPointerTy());
1362        CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
1363        SDOperand FudgeInReg;
1364        if (Node->getValueType(0) == MVT::f32)
1365          FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
1366                                   DAG.getSrcValue(NULL));
1367        else {
1368          assert(Node->getValueType(0) == MVT::f64 && "Unexpected conversion");
1369          FudgeInReg =
1370            LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
1371                                      DAG.getEntryNode(), CPIdx,
1372                                      DAG.getSrcValue(NULL), MVT::f32));
1373        }
1374        Result = DAG.getNode(ISD::ADD, Node->getValueType(0), Tmp1, FudgeInReg);
1375        break;
1376      }
1377      Tmp1 = LegalizeOp(Node->getOperand(0));
1378      if (Tmp1 != Node->getOperand(0))
1379        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
1380      break;
1381    case Expand:
1382      if (Node->getOpcode() == ISD::SINT_TO_FP ||
1383          Node->getOpcode() == ISD::UINT_TO_FP) {
1384        Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
1385                               Node->getValueType(0), Node->getOperand(0));
1386        break;
1387      } else if (Node->getOpcode() == ISD::TRUNCATE) {
1388        // In the expand case, we must be dealing with a truncate, because
1389        // otherwise the result would be larger than the source.
1390        ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1391
1392        // Since the result is legal, we should just be able to truncate the low
1393        // part of the source.
1394        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
1395        break;
1396      }
1397      assert(0 && "Shouldn't need to expand other operators here!");
1398
1399    case Promote:
1400      switch (Node->getOpcode()) {
1401      case ISD::ZERO_EXTEND:
1402        Result = PromoteOp(Node->getOperand(0));
1403        // NOTE: Any extend would work here...
1404        Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
1405        Result = DAG.getZeroExtendInReg(Result,
1406                                        Node->getOperand(0).getValueType());
1407        break;
1408      case ISD::SIGN_EXTEND:
1409        Result = PromoteOp(Node->getOperand(0));
1410        // NOTE: Any extend would work here...
1411        Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
1412        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1413                             Result,
1414                          DAG.getValueType(Node->getOperand(0).getValueType()));
1415        break;
1416      case ISD::TRUNCATE:
1417        Result = PromoteOp(Node->getOperand(0));
1418        Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
1419        break;
1420      case ISD::FP_EXTEND:
1421        Result = PromoteOp(Node->getOperand(0));
1422        if (Result.getValueType() != Op.getValueType())
1423          // Dynamically dead while we have only 2 FP types.
1424          Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
1425        break;
1426      case ISD::FP_ROUND:
1427      case ISD::FP_TO_SINT:
1428      case ISD::FP_TO_UINT:
1429        Result = PromoteOp(Node->getOperand(0));
1430        Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
1431        break;
1432      case ISD::SINT_TO_FP:
1433        Result = PromoteOp(Node->getOperand(0));
1434        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1435                             Result,
1436                         DAG.getValueType(Node->getOperand(0).getValueType()));
1437        Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
1438        break;
1439      case ISD::UINT_TO_FP:
1440        Result = PromoteOp(Node->getOperand(0));
1441        Result = DAG.getZeroExtendInReg(Result,
1442                                        Node->getOperand(0).getValueType());
1443        Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
1444        break;
1445      }
1446    }
1447    break;
1448  case ISD::FP_ROUND_INREG:
1449  case ISD::SIGN_EXTEND_INREG: {
1450    Tmp1 = LegalizeOp(Node->getOperand(0));
1451    MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
1452
1453    // If this operation is not supported, convert it to a shl/shr or load/store
1454    // pair.
1455    switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
1456    default: assert(0 && "This action not supported for this op yet!");
1457    case TargetLowering::Legal:
1458      if (Tmp1 != Node->getOperand(0))
1459        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
1460                             DAG.getValueType(ExtraVT));
1461      break;
1462    case TargetLowering::Expand:
1463      // If this is an integer extend and shifts are supported, do that.
1464      if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
1465        // NOTE: we could fall back on load/store here too for targets without
1466        // SAR.  However, it is doubtful that any exist.
1467        unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
1468                            MVT::getSizeInBits(ExtraVT);
1469        SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
1470        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
1471                             Node->getOperand(0), ShiftCst);
1472        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
1473                             Result, ShiftCst);
1474      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
1475        // The only way we can lower this is to turn it into a STORETRUNC,
1476        // EXTLOAD pair, targetting a temporary location (a stack slot).
1477
1478        // NOTE: there is a choice here between constantly creating new stack
1479        // slots and always reusing the same one.  We currently always create
1480        // new ones, as reuse may inhibit scheduling.
1481        const Type *Ty = MVT::getTypeForValueType(ExtraVT);
1482        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
1483        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
1484        MachineFunction &MF = DAG.getMachineFunction();
1485        int SSFI =
1486          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
1487        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
1488        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
1489                             Node->getOperand(0), StackSlot,
1490                             DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
1491        Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1492                                Result, StackSlot, DAG.getSrcValue(NULL),
1493                                ExtraVT);
1494      } else {
1495        assert(0 && "Unknown op");
1496      }
1497      Result = LegalizeOp(Result);
1498      break;
1499    }
1500    break;
1501  }
1502  }
1503
1504  // Note that LegalizeOp may be reentered even from single-use nodes, which
1505  // means that we always must cache transformed nodes.
1506  AddLegalizedOperand(Op, Result);
1507  return Result;
1508}
1509
1510/// PromoteOp - Given an operation that produces a value in an invalid type,
1511/// promote it to compute the value into a larger type.  The produced value will
1512/// have the correct bits for the low portion of the register, but no guarantee
1513/// is made about the top bits: it may be zero, sign-extended, or garbage.
1514SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
1515  MVT::ValueType VT = Op.getValueType();
1516  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1517  assert(getTypeAction(VT) == Promote &&
1518         "Caller should expand or legalize operands that are not promotable!");
1519  assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
1520         "Cannot promote to smaller type!");
1521
1522  SDOperand Tmp1, Tmp2, Tmp3;
1523
1524  SDOperand Result;
1525  SDNode *Node = Op.Val;
1526
1527  if (!Node->hasOneUse()) {
1528    std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
1529    if (I != PromotedNodes.end()) return I->second;
1530  } else {
1531    assert(!PromotedNodes.count(Op) && "Repromoted this node??");
1532  }
1533
1534  // Promotion needs an optimization step to clean up after it, and is not
1535  // careful to avoid operations the target does not support.  Make sure that
1536  // all generated operations are legalized in the next iteration.
1537  NeedsAnotherIteration = true;
1538
1539  switch (Node->getOpcode()) {
1540  default:
1541    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1542    assert(0 && "Do not know how to promote this operator!");
1543    abort();
1544  case ISD::UNDEF:
1545    Result = DAG.getNode(ISD::UNDEF, NVT);
1546    break;
1547  case ISD::Constant:
1548    Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
1549    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
1550    break;
1551  case ISD::ConstantFP:
1552    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
1553    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
1554    break;
1555  case ISD::CopyFromReg:
1556    Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(), NVT,
1557                                Node->getOperand(0));
1558    // Remember that we legalized the chain.
1559    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1560    break;
1561
1562  case ISD::SETCC:
1563    assert(getTypeAction(TLI.getSetCCResultTy()) == Legal &&
1564           "SetCC type is not legal??");
1565    Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
1566                          TLI.getSetCCResultTy(), Node->getOperand(0),
1567                          Node->getOperand(1));
1568    Result = LegalizeOp(Result);
1569    break;
1570
1571  case ISD::TRUNCATE:
1572    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1573    case Legal:
1574      Result = LegalizeOp(Node->getOperand(0));
1575      assert(Result.getValueType() >= NVT &&
1576             "This truncation doesn't make sense!");
1577      if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
1578        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
1579      break;
1580    case Promote:
1581      // The truncation is not required, because we don't guarantee anything
1582      // about high bits anyway.
1583      Result = PromoteOp(Node->getOperand(0));
1584      break;
1585    case Expand:
1586      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1587      // Truncate the low part of the expanded value to the result type
1588      Result = DAG.getNode(ISD::TRUNCATE, VT, Tmp1);
1589    }
1590    break;
1591  case ISD::SIGN_EXTEND:
1592  case ISD::ZERO_EXTEND:
1593    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1594    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
1595    case Legal:
1596      // Input is legal?  Just do extend all the way to the larger type.
1597      Result = LegalizeOp(Node->getOperand(0));
1598      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1599      break;
1600    case Promote:
1601      // Promote the reg if it's smaller.
1602      Result = PromoteOp(Node->getOperand(0));
1603      // The high bits are not guaranteed to be anything.  Insert an extend.
1604      if (Node->getOpcode() == ISD::SIGN_EXTEND)
1605        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
1606                         DAG.getValueType(Node->getOperand(0).getValueType()));
1607      else
1608        Result = DAG.getZeroExtendInReg(Result,
1609                                        Node->getOperand(0).getValueType());
1610      break;
1611    }
1612    break;
1613
1614  case ISD::FP_EXTEND:
1615    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
1616  case ISD::FP_ROUND:
1617    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1618    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
1619    case Promote:  assert(0 && "Unreachable with 2 FP types!");
1620    case Legal:
1621      // Input is legal?  Do an FP_ROUND_INREG.
1622      Result = LegalizeOp(Node->getOperand(0));
1623      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
1624                           DAG.getValueType(VT));
1625      break;
1626    }
1627    break;
1628
1629  case ISD::SINT_TO_FP:
1630  case ISD::UINT_TO_FP:
1631    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1632    case Legal:
1633      Result = LegalizeOp(Node->getOperand(0));
1634      // No extra round required here.
1635      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1636      break;
1637
1638    case Promote:
1639      Result = PromoteOp(Node->getOperand(0));
1640      if (Node->getOpcode() == ISD::SINT_TO_FP)
1641        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1642                             Result,
1643                         DAG.getValueType(Node->getOperand(0).getValueType()));
1644      else
1645        Result = DAG.getZeroExtendInReg(Result,
1646                                        Node->getOperand(0).getValueType());
1647      // No extra round required here.
1648      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1649      break;
1650    case Expand:
1651      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
1652                             Node->getOperand(0));
1653      // Round if we cannot tolerate excess precision.
1654      if (NoExcessFPPrecision)
1655        Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
1656                             DAG.getValueType(VT));
1657      break;
1658    }
1659    break;
1660
1661  case ISD::FP_TO_SINT:
1662  case ISD::FP_TO_UINT:
1663    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1664    case Legal:
1665      Tmp1 = LegalizeOp(Node->getOperand(0));
1666      break;
1667    case Promote:
1668      // The input result is prerounded, so we don't have to do anything
1669      // special.
1670      Tmp1 = PromoteOp(Node->getOperand(0));
1671      break;
1672    case Expand:
1673      assert(0 && "not implemented");
1674    }
1675    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1676    break;
1677
1678  case ISD::FABS:
1679  case ISD::FNEG:
1680    Tmp1 = PromoteOp(Node->getOperand(0));
1681    assert(Tmp1.getValueType() == NVT);
1682    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1683    // NOTE: we do not have to do any extra rounding here for
1684    // NoExcessFPPrecision, because we know the input will have the appropriate
1685    // precision, and these operations don't modify precision at all.
1686    break;
1687
1688  case ISD::FSQRT:
1689  case ISD::FSIN:
1690  case ISD::FCOS:
1691    Tmp1 = PromoteOp(Node->getOperand(0));
1692    assert(Tmp1.getValueType() == NVT);
1693    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1694    if(NoExcessFPPrecision)
1695      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
1696                           DAG.getValueType(VT));
1697    break;
1698
1699  case ISD::AND:
1700  case ISD::OR:
1701  case ISD::XOR:
1702  case ISD::ADD:
1703  case ISD::SUB:
1704  case ISD::MUL:
1705    // The input may have strange things in the top bits of the registers, but
1706    // these operations don't care.  They may have wierd bits going out, but
1707    // that too is okay if they are integer operations.
1708    Tmp1 = PromoteOp(Node->getOperand(0));
1709    Tmp2 = PromoteOp(Node->getOperand(1));
1710    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
1711    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1712
1713    // However, if this is a floating point operation, they will give excess
1714    // precision that we may not be able to tolerate.  If we DO allow excess
1715    // precision, just leave it, otherwise excise it.
1716    // FIXME: Why would we need to round FP ops more than integer ones?
1717    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
1718    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1719      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
1720                           DAG.getValueType(VT));
1721    break;
1722
1723  case ISD::SDIV:
1724  case ISD::SREM:
1725    // These operators require that their input be sign extended.
1726    Tmp1 = PromoteOp(Node->getOperand(0));
1727    Tmp2 = PromoteOp(Node->getOperand(1));
1728    if (MVT::isInteger(NVT)) {
1729      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
1730                         DAG.getValueType(VT));
1731      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
1732                         DAG.getValueType(VT));
1733    }
1734    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1735
1736    // Perform FP_ROUND: this is probably overly pessimistic.
1737    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1738      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
1739                           DAG.getValueType(VT));
1740    break;
1741
1742  case ISD::UDIV:
1743  case ISD::UREM:
1744    // These operators require that their input be zero extended.
1745    Tmp1 = PromoteOp(Node->getOperand(0));
1746    Tmp2 = PromoteOp(Node->getOperand(1));
1747    assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
1748    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
1749    Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
1750    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1751    break;
1752
1753  case ISD::SHL:
1754    Tmp1 = PromoteOp(Node->getOperand(0));
1755    Tmp2 = LegalizeOp(Node->getOperand(1));
1756    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
1757    break;
1758  case ISD::SRA:
1759    // The input value must be properly sign extended.
1760    Tmp1 = PromoteOp(Node->getOperand(0));
1761    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
1762                       DAG.getValueType(VT));
1763    Tmp2 = LegalizeOp(Node->getOperand(1));
1764    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
1765    break;
1766  case ISD::SRL:
1767    // The input value must be properly zero extended.
1768    Tmp1 = PromoteOp(Node->getOperand(0));
1769    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
1770    Tmp2 = LegalizeOp(Node->getOperand(1));
1771    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
1772    break;
1773  case ISD::LOAD:
1774    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1775    Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
1776    // FIXME: When the DAG combiner exists, change this to use EXTLOAD!
1777    if (MVT::isInteger(NVT))
1778      Result = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Tmp1, Tmp2,
1779                              Node->getOperand(2), VT);
1780    else
1781      Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp1, Tmp2,
1782                              Node->getOperand(2), VT);
1783
1784    // Remember that we legalized the chain.
1785    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1786    break;
1787  case ISD::SELECT:
1788    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1789    case Expand: assert(0 && "It's impossible to expand bools");
1790    case Legal:
1791      Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
1792      break;
1793    case Promote:
1794      Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
1795      break;
1796    }
1797    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
1798    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
1799    Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
1800    break;
1801  case ISD::TAILCALL:
1802  case ISD::CALL: {
1803    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1804    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1805
1806    std::vector<SDOperand> Ops;
1807    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i)
1808      Ops.push_back(LegalizeOp(Node->getOperand(i)));
1809
1810    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1811           "Can only promote single result calls");
1812    std::vector<MVT::ValueType> RetTyVTs;
1813    RetTyVTs.reserve(2);
1814    RetTyVTs.push_back(NVT);
1815    RetTyVTs.push_back(MVT::Other);
1816    SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops,
1817                             Node->getOpcode() == ISD::TAILCALL);
1818    Result = SDOperand(NC, 0);
1819
1820    // Insert the new chain mapping.
1821    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1822    break;
1823  }
1824  case ISD::CTPOP:
1825  case ISD::CTTZ:
1826  case ISD::CTLZ:
1827    Tmp1 = Node->getOperand(0);
1828    //Zero extend the argument
1829    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
1830    // Perform the larger operation, then subtract if needed.
1831    Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1832    switch(Node->getOpcode())
1833    {
1834    case ISD::CTPOP:
1835      Result = Tmp1;
1836      break;
1837    case ISD::CTTZ:
1838      //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
1839      Tmp2 = DAG.getSetCC(ISD::SETEQ, MVT::i1, Tmp1,
1840                          DAG.getConstant(getSizeInBits(NVT), NVT));
1841      Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
1842                           DAG.getConstant(getSizeInBits(VT),NVT), Tmp1);
1843      break;
1844    case ISD::CTLZ:
1845      //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
1846      Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
1847                           DAG.getConstant(getSizeInBits(NVT) -
1848                                           getSizeInBits(VT), NVT));
1849      break;
1850    }
1851    break;
1852  }
1853
1854  assert(Result.Val && "Didn't set a result!");
1855  AddPromotedOperand(Op, Result);
1856  return Result;
1857}
1858
1859/// ExpandAddSub - Find a clever way to expand this add operation into
1860/// subcomponents.
1861void SelectionDAGLegalize::
1862ExpandByParts(unsigned NodeOp, SDOperand LHS, SDOperand RHS,
1863              SDOperand &Lo, SDOperand &Hi) {
1864  // Expand the subcomponents.
1865  SDOperand LHSL, LHSH, RHSL, RHSH;
1866  ExpandOp(LHS, LHSL, LHSH);
1867  ExpandOp(RHS, RHSL, RHSH);
1868
1869  // FIXME: this should be moved to the dag combiner someday.
1870  assert(NodeOp == ISD::ADD_PARTS || NodeOp == ISD::SUB_PARTS);
1871  if (LHSL.getValueType() == MVT::i32) {
1872    SDOperand LowEl;
1873    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHSL))
1874      if (C->getValue() == 0)
1875        LowEl = RHSL;
1876    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHSL))
1877      if (C->getValue() == 0)
1878        LowEl = LHSL;
1879    if (LowEl.Val) {
1880      // Turn this into an add/sub of the high part only.
1881      SDOperand HiEl =
1882        DAG.getNode(NodeOp == ISD::ADD_PARTS ? ISD::ADD : ISD::SUB,
1883                    LowEl.getValueType(), LHSH, RHSH);
1884      Lo = LowEl;
1885      Hi = HiEl;
1886      return;
1887    }
1888  }
1889
1890  std::vector<SDOperand> Ops;
1891  Ops.push_back(LHSL);
1892  Ops.push_back(LHSH);
1893  Ops.push_back(RHSL);
1894  Ops.push_back(RHSH);
1895
1896  std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
1897  Lo = DAG.getNode(NodeOp, VTs, Ops);
1898  Hi = Lo.getValue(1);
1899}
1900
1901void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
1902                                            SDOperand Op, SDOperand Amt,
1903                                            SDOperand &Lo, SDOperand &Hi) {
1904  // Expand the subcomponents.
1905  SDOperand LHSL, LHSH;
1906  ExpandOp(Op, LHSL, LHSH);
1907
1908  std::vector<SDOperand> Ops;
1909  Ops.push_back(LHSL);
1910  Ops.push_back(LHSH);
1911  Ops.push_back(Amt);
1912  std::vector<MVT::ValueType> VTs;
1913  VTs.push_back(LHSL.getValueType());
1914  VTs.push_back(LHSH.getValueType());
1915  VTs.push_back(Amt.getValueType());
1916  Lo = DAG.getNode(NodeOp, VTs, Ops);
1917  Hi = Lo.getValue(1);
1918}
1919
1920
1921/// ExpandShift - Try to find a clever way to expand this shift operation out to
1922/// smaller elements.  If we can't find a way that is more efficient than a
1923/// libcall on this target, return false.  Otherwise, return true with the
1924/// low-parts expanded into Lo and Hi.
1925bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
1926                                       SDOperand &Lo, SDOperand &Hi) {
1927  assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
1928         "This is not a shift!");
1929
1930  MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
1931  SDOperand ShAmt = LegalizeOp(Amt);
1932  MVT::ValueType ShTy = ShAmt.getValueType();
1933  unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
1934  unsigned NVTBits = MVT::getSizeInBits(NVT);
1935
1936  // Handle the case when Amt is an immediate.  Other cases are currently broken
1937  // and are disabled.
1938  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
1939    unsigned Cst = CN->getValue();
1940    // Expand the incoming operand to be shifted, so that we have its parts
1941    SDOperand InL, InH;
1942    ExpandOp(Op, InL, InH);
1943    switch(Opc) {
1944    case ISD::SHL:
1945      if (Cst > VTBits) {
1946        Lo = DAG.getConstant(0, NVT);
1947        Hi = DAG.getConstant(0, NVT);
1948      } else if (Cst > NVTBits) {
1949        Lo = DAG.getConstant(0, NVT);
1950        Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
1951      } else if (Cst == NVTBits) {
1952        Lo = DAG.getConstant(0, NVT);
1953        Hi = InL;
1954      } else {
1955        Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
1956        Hi = DAG.getNode(ISD::OR, NVT,
1957           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
1958           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
1959      }
1960      return true;
1961    case ISD::SRL:
1962      if (Cst > VTBits) {
1963        Lo = DAG.getConstant(0, NVT);
1964        Hi = DAG.getConstant(0, NVT);
1965      } else if (Cst > NVTBits) {
1966        Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
1967        Hi = DAG.getConstant(0, NVT);
1968      } else if (Cst == NVTBits) {
1969        Lo = InH;
1970        Hi = DAG.getConstant(0, NVT);
1971      } else {
1972        Lo = DAG.getNode(ISD::OR, NVT,
1973           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
1974           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
1975        Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
1976      }
1977      return true;
1978    case ISD::SRA:
1979      if (Cst > VTBits) {
1980        Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
1981                              DAG.getConstant(NVTBits-1, ShTy));
1982      } else if (Cst > NVTBits) {
1983        Lo = DAG.getNode(ISD::SRA, NVT, InH,
1984                           DAG.getConstant(Cst-NVTBits, ShTy));
1985        Hi = DAG.getNode(ISD::SRA, NVT, InH,
1986                              DAG.getConstant(NVTBits-1, ShTy));
1987      } else if (Cst == NVTBits) {
1988        Lo = InH;
1989        Hi = DAG.getNode(ISD::SRA, NVT, InH,
1990                              DAG.getConstant(NVTBits-1, ShTy));
1991      } else {
1992        Lo = DAG.getNode(ISD::OR, NVT,
1993           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
1994           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
1995        Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
1996      }
1997      return true;
1998    }
1999  }
2000  // FIXME: The following code for expanding shifts using ISD::SELECT is buggy,
2001  // so disable it for now.  Currently targets are handling this via SHL_PARTS
2002  // and friends.
2003  return false;
2004
2005  // If we have an efficient select operation (or if the selects will all fold
2006  // away), lower to some complex code, otherwise just emit the libcall.
2007  if (TLI.getOperationAction(ISD::SELECT, NVT) != TargetLowering::Legal &&
2008      !isa<ConstantSDNode>(Amt))
2009    return false;
2010
2011  SDOperand InL, InH;
2012  ExpandOp(Op, InL, InH);
2013  SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy,           // NAmt = 32-ShAmt
2014                               DAG.getConstant(NVTBits, ShTy), ShAmt);
2015
2016  // Compare the unmasked shift amount against 32.
2017  SDOperand Cond = DAG.getSetCC(ISD::SETGE, TLI.getSetCCResultTy(), ShAmt,
2018                                DAG.getConstant(NVTBits, ShTy));
2019
2020  if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
2021    ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt,             // ShAmt &= 31
2022                        DAG.getConstant(NVTBits-1, ShTy));
2023    NAmt  = DAG.getNode(ISD::AND, ShTy, NAmt,              // NAmt &= 31
2024                        DAG.getConstant(NVTBits-1, ShTy));
2025  }
2026
2027  if (Opc == ISD::SHL) {
2028    SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
2029                               DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
2030                               DAG.getNode(ISD::SRL, NVT, InL, NAmt));
2031    SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt&31
2032
2033    Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
2034    Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
2035  } else {
2036    SDOperand HiLoPart = DAG.getNode(ISD::SELECT, NVT,
2037                                     DAG.getSetCC(ISD::SETEQ,
2038                                                  TLI.getSetCCResultTy(), NAmt,
2039                                                  DAG.getConstant(32, ShTy)),
2040                                     DAG.getConstant(0, NVT),
2041                                     DAG.getNode(ISD::SHL, NVT, InH, NAmt));
2042    SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
2043                               HiLoPart,
2044                               DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
2045    SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt);  // T2 = InH >> ShAmt&31
2046
2047    SDOperand HiPart;
2048    if (Opc == ISD::SRA)
2049      HiPart = DAG.getNode(ISD::SRA, NVT, InH,
2050                           DAG.getConstant(NVTBits-1, ShTy));
2051    else
2052      HiPart = DAG.getConstant(0, NVT);
2053    Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
2054    Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart, T2);
2055  }
2056  return true;
2057}
2058
2059/// FindLatestCallSeqStart - Scan up the dag to find the latest (highest
2060/// NodeDepth) node that is an CallSeqStart operation and occurs later than
2061/// Found.
2062static void FindLatestCallSeqStart(SDNode *Node, SDNode *&Found) {
2063  if (Node->getNodeDepth() <= Found->getNodeDepth()) return;
2064
2065  // If we found an CALLSEQ_START, we already know this node occurs later
2066  // than the Found node. Just remember this node and return.
2067  if (Node->getOpcode() == ISD::CALLSEQ_START) {
2068    Found = Node;
2069    return;
2070  }
2071
2072  // Otherwise, scan the operands of Node to see if any of them is a call.
2073  assert(Node->getNumOperands() != 0 &&
2074         "All leaves should have depth equal to the entry node!");
2075  for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
2076    FindLatestCallSeqStart(Node->getOperand(i).Val, Found);
2077
2078  // Tail recurse for the last iteration.
2079  FindLatestCallSeqStart(Node->getOperand(Node->getNumOperands()-1).Val,
2080                             Found);
2081}
2082
2083
2084/// FindEarliestCallSeqEnd - Scan down the dag to find the earliest (lowest
2085/// NodeDepth) node that is an CallSeqEnd operation and occurs more recent
2086/// than Found.
2087static void FindEarliestCallSeqEnd(SDNode *Node, SDNode *&Found) {
2088  if (Found && Node->getNodeDepth() >= Found->getNodeDepth()) return;
2089
2090  // If we found an CALLSEQ_END, we already know this node occurs earlier
2091  // than the Found node. Just remember this node and return.
2092  if (Node->getOpcode() == ISD::CALLSEQ_END) {
2093    Found = Node;
2094    return;
2095  }
2096
2097  // Otherwise, scan the operands of Node to see if any of them is a call.
2098  SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
2099  if (UI == E) return;
2100  for (--E; UI != E; ++UI)
2101    FindEarliestCallSeqEnd(*UI, Found);
2102
2103  // Tail recurse for the last iteration.
2104  FindEarliestCallSeqEnd(*UI, Found);
2105}
2106
2107/// FindCallSeqEnd - Given a chained node that is part of a call sequence,
2108/// find the CALLSEQ_END node that terminates the call sequence.
2109static SDNode *FindCallSeqEnd(SDNode *Node) {
2110  if (Node->getOpcode() == ISD::CALLSEQ_END)
2111    return Node;
2112  if (Node->use_empty())
2113    return 0;   // No CallSeqEnd
2114
2115  if (Node->hasOneUse())  // Simple case, only has one user to check.
2116    return FindCallSeqEnd(*Node->use_begin());
2117
2118  SDOperand TheChain(Node, Node->getNumValues()-1);
2119  if (TheChain.getValueType() != MVT::Other)
2120    TheChain = SDOperand(Node, 0);
2121  assert(TheChain.getValueType() == MVT::Other && "Is not a token chain!");
2122
2123  for (SDNode::use_iterator UI = Node->use_begin(),
2124         E = Node->use_end(); ; ++UI) {
2125    assert(UI != E && "Didn't find a user of the tokchain, no CALLSEQ_END!");
2126
2127    // Make sure to only follow users of our token chain.
2128    SDNode *User = *UI;
2129    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
2130      if (User->getOperand(i) == TheChain)
2131        if (SDNode *Result = FindCallSeqEnd(User))
2132          return Result;
2133  }
2134  assert(0 && "Unreachable");
2135  abort();
2136}
2137
2138/// FindCallSeqStart - Given a chained node that is part of a call sequence,
2139/// find the CALLSEQ_START node that initiates the call sequence.
2140static SDNode *FindCallSeqStart(SDNode *Node) {
2141  assert(Node && "Didn't find callseq_start for a call??");
2142  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
2143
2144  assert(Node->getOperand(0).getValueType() == MVT::Other &&
2145         "Node doesn't have a token chain argument!");
2146  return FindCallSeqStart(Node->getOperand(0).Val);
2147}
2148
2149
2150/// FindInputOutputChains - If we are replacing an operation with a call we need
2151/// to find the call that occurs before and the call that occurs after it to
2152/// properly serialize the calls in the block.  The returned operand is the
2153/// input chain value for the new call (e.g. the entry node or the previous
2154/// call), and OutChain is set to be the chain node to update to point to the
2155/// end of the call chain.
2156static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
2157                                       SDOperand Entry) {
2158  SDNode *LatestCallSeqStart = Entry.Val;
2159  SDNode *LatestCallSeqEnd = 0;
2160  FindLatestCallSeqStart(OpNode, LatestCallSeqStart);
2161  //std::cerr<<"Found node: "; LatestCallSeqStart->dump(); std::cerr <<"\n";
2162
2163  // It is possible that no ISD::CALLSEQ_START was found because there is no
2164  // previous call in the function.  LatestCallStackDown may in that case be
2165  // the entry node itself.  Do not attempt to find a matching CALLSEQ_END
2166  // unless LatestCallStackDown is an CALLSEQ_START.
2167  if (LatestCallSeqStart->getOpcode() == ISD::CALLSEQ_START)
2168    LatestCallSeqEnd = FindCallSeqEnd(LatestCallSeqStart);
2169  else
2170    LatestCallSeqEnd = Entry.Val;
2171  assert(LatestCallSeqEnd && "NULL return from FindCallSeqEnd");
2172
2173  // Finally, find the first call that this must come before, first we find the
2174  // CallSeqEnd that ends the call.
2175  OutChain = 0;
2176  FindEarliestCallSeqEnd(OpNode, OutChain);
2177
2178  // If we found one, translate from the adj up to the callseq_start.
2179  if (OutChain)
2180    OutChain = FindCallSeqStart(OutChain);
2181
2182  return SDOperand(LatestCallSeqEnd, 0);
2183}
2184
2185/// SpliceCallInto - Given the result chain of a libcall (CallResult), and a
2186void SelectionDAGLegalize::SpliceCallInto(const SDOperand &CallResult,
2187                                          SDNode *OutChain) {
2188  // Nothing to splice it into?
2189  if (OutChain == 0) return;
2190
2191  assert(OutChain->getOperand(0).getValueType() == MVT::Other);
2192  //OutChain->dump();
2193
2194  // Form a token factor node merging the old inval and the new inval.
2195  SDOperand InToken = DAG.getNode(ISD::TokenFactor, MVT::Other, CallResult,
2196                                  OutChain->getOperand(0));
2197  // Change the node to refer to the new token.
2198  OutChain->setAdjCallChain(InToken);
2199}
2200
2201
2202// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
2203// does not fit into a register, return the lo part and set the hi part to the
2204// by-reg argument.  If it does fit into a single register, return the result
2205// and leave the Hi part unset.
2206SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
2207                                              SDOperand &Hi) {
2208  SDNode *OutChain;
2209  SDOperand InChain = FindInputOutputChains(Node, OutChain,
2210                                            DAG.getEntryNode());
2211  if (InChain.Val == 0)
2212    InChain = DAG.getEntryNode();
2213
2214  TargetLowering::ArgListTy Args;
2215  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2216    MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
2217    const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
2218    Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
2219  }
2220  SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
2221
2222  // Splice the libcall in wherever FindInputOutputChains tells us to.
2223  const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
2224  std::pair<SDOperand,SDOperand> CallInfo =
2225    TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
2226                    Callee, Args, DAG);
2227  SpliceCallInto(CallInfo.second, OutChain);
2228
2229  NeedsAnotherIteration = true;
2230
2231  switch (getTypeAction(CallInfo.first.getValueType())) {
2232  default: assert(0 && "Unknown thing");
2233  case Legal:
2234    return CallInfo.first;
2235  case Promote:
2236    assert(0 && "Cannot promote this yet!");
2237  case Expand:
2238    SDOperand Lo;
2239    ExpandOp(CallInfo.first, Lo, Hi);
2240    return Lo;
2241  }
2242}
2243
2244
2245/// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
2246/// destination type is legal.
2247SDOperand SelectionDAGLegalize::
2248ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
2249  assert(getTypeAction(DestTy) == Legal && "Destination type is not legal!");
2250  assert(getTypeAction(Source.getValueType()) == Expand &&
2251         "This is not an expansion!");
2252  assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
2253
2254  if (!isSigned) {
2255    assert(Source.getValueType() == MVT::i64 &&
2256           "This only works for 64-bit -> FP");
2257    // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
2258    // incoming integer is set.  To handle this, we dynamically test to see if
2259    // it is set, and, if so, add a fudge factor.
2260    SDOperand Lo, Hi;
2261    ExpandOp(Source, Lo, Hi);
2262
2263    // If this is unsigned, and not supported, first perform the conversion to
2264    // signed, then adjust the result if the sign bit is set.
2265    SDOperand SignedConv = ExpandIntToFP(true, DestTy,
2266                   DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
2267
2268    SDOperand SignSet = DAG.getSetCC(ISD::SETLT, TLI.getSetCCResultTy(), Hi,
2269                                     DAG.getConstant(0, Hi.getValueType()));
2270    SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
2271    SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
2272                                      SignSet, Four, Zero);
2273    uint64_t FF = 0x5f800000ULL;
2274    if (TLI.isLittleEndian()) FF <<= 32;
2275    static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
2276
2277    MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
2278    SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(FudgeFactor),
2279                                          TLI.getPointerTy());
2280    CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
2281    SDOperand FudgeInReg;
2282    if (DestTy == MVT::f32)
2283      FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
2284                               DAG.getSrcValue(NULL));
2285    else {
2286      assert(DestTy == MVT::f64 && "Unexpected conversion");
2287      FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
2288                                  CPIdx, DAG.getSrcValue(NULL), MVT::f32);
2289    }
2290    return DAG.getNode(ISD::ADD, DestTy, SignedConv, FudgeInReg);
2291  }
2292
2293  // Check to see if the target has a custom way to lower this.  If so, use it.
2294  switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
2295  default: assert(0 && "This action not implemented for this operation!");
2296  case TargetLowering::Legal:
2297  case TargetLowering::Expand:
2298    break;   // This case is handled below.
2299  case TargetLowering::Custom:
2300    Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
2301    return LegalizeOp(TLI.LowerOperation(Source, DAG));
2302  }
2303
2304  // Expand the source, then glue it back together for the call.  We must expand
2305  // the source in case it is shared (this pass of legalize must traverse it).
2306  SDOperand SrcLo, SrcHi;
2307  ExpandOp(Source, SrcLo, SrcHi);
2308  Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
2309
2310  SDNode *OutChain = 0;
2311  SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
2312                                            DAG.getEntryNode());
2313  const char *FnName = 0;
2314  if (DestTy == MVT::f32)
2315    FnName = "__floatdisf";
2316  else {
2317    assert(DestTy == MVT::f64 && "Unknown fp value type!");
2318    FnName = "__floatdidf";
2319  }
2320
2321  SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
2322
2323  TargetLowering::ArgListTy Args;
2324  const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
2325
2326  Args.push_back(std::make_pair(Source, ArgTy));
2327
2328  // We don't care about token chains for libcalls.  We just use the entry
2329  // node as our input and ignore the output chain.  This allows us to place
2330  // calls wherever we need them to satisfy data dependences.
2331  const Type *RetTy = MVT::getTypeForValueType(DestTy);
2332
2333  std::pair<SDOperand,SDOperand> CallResult =
2334    TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, true,
2335                    Callee, Args, DAG);
2336
2337  SpliceCallInto(CallResult.second, OutChain);
2338  return CallResult.first;
2339}
2340
2341
2342
2343/// ExpandOp - Expand the specified SDOperand into its two component pieces
2344/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
2345/// LegalizeNodes map is filled in for any results that are not expanded, the
2346/// ExpandedNodes map is filled in for any results that are expanded, and the
2347/// Lo/Hi values are returned.
2348void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
2349  MVT::ValueType VT = Op.getValueType();
2350  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2351  SDNode *Node = Op.Val;
2352  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
2353  assert(MVT::isInteger(VT) && "Cannot expand FP values!");
2354  assert(MVT::isInteger(NVT) && NVT < VT &&
2355         "Cannot expand to FP value or to larger int value!");
2356
2357  // If there is more than one use of this, see if we already expanded it.
2358  // There is no use remembering values that only have a single use, as the map
2359  // entries will never be reused.
2360  if (!Node->hasOneUse()) {
2361    std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
2362      = ExpandedNodes.find(Op);
2363    if (I != ExpandedNodes.end()) {
2364      Lo = I->second.first;
2365      Hi = I->second.second;
2366      return;
2367    }
2368  } else {
2369    assert(!ExpandedNodes.count(Op) && "Re-expanding a node!");
2370  }
2371
2372  // Expanding to multiple registers needs to perform an optimization step, and
2373  // is not careful to avoid operations the target does not support.  Make sure
2374  // that all generated operations are legalized in the next iteration.
2375  NeedsAnotherIteration = true;
2376
2377  switch (Node->getOpcode()) {
2378  default:
2379    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2380    assert(0 && "Do not know how to expand this operator!");
2381    abort();
2382  case ISD::UNDEF:
2383    Lo = DAG.getNode(ISD::UNDEF, NVT);
2384    Hi = DAG.getNode(ISD::UNDEF, NVT);
2385    break;
2386  case ISD::Constant: {
2387    uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
2388    Lo = DAG.getConstant(Cst, NVT);
2389    Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
2390    break;
2391  }
2392
2393  case ISD::CopyFromReg: {
2394    unsigned Reg = cast<RegSDNode>(Node)->getReg();
2395    // Aggregate register values are always in consequtive pairs.
2396    Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
2397    Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
2398
2399    // Remember that we legalized the chain.
2400    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
2401
2402    assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
2403    break;
2404  }
2405
2406  case ISD::BUILD_PAIR:
2407    // Legalize both operands.  FIXME: in the future we should handle the case
2408    // where the two elements are not legal.
2409    assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
2410    Lo = LegalizeOp(Node->getOperand(0));
2411    Hi = LegalizeOp(Node->getOperand(1));
2412    break;
2413
2414  case ISD::CTPOP:
2415    ExpandOp(Node->getOperand(0), Lo, Hi);
2416    Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
2417                     DAG.getNode(ISD::CTPOP, NVT, Lo),
2418                     DAG.getNode(ISD::CTPOP, NVT, Hi));
2419    Hi = DAG.getConstant(0, NVT);
2420    break;
2421
2422  case ISD::CTLZ: {
2423    // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
2424    ExpandOp(Node->getOperand(0), Lo, Hi);
2425    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
2426    SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
2427    SDOperand TopNotZero = DAG.getSetCC(ISD::SETNE, TLI.getSetCCResultTy(),
2428                                        HLZ, BitsC);
2429    SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
2430    LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
2431
2432    Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
2433    Hi = DAG.getConstant(0, NVT);
2434    break;
2435  }
2436
2437  case ISD::CTTZ: {
2438    // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
2439    ExpandOp(Node->getOperand(0), Lo, Hi);
2440    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
2441    SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
2442    SDOperand BotNotZero = DAG.getSetCC(ISD::SETNE, TLI.getSetCCResultTy(),
2443                                        LTZ, BitsC);
2444    SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
2445    HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
2446
2447    Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
2448    Hi = DAG.getConstant(0, NVT);
2449    break;
2450  }
2451
2452  case ISD::LOAD: {
2453    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
2454    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2455    Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
2456
2457    // Increment the pointer to the other half.
2458    unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
2459    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
2460                      getIntPtrConstant(IncrementSize));
2461    //Is this safe?  declaring that the two parts of the split load
2462    //are from the same instruction?
2463    Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
2464
2465    // Build a factor node to remember that this load is independent of the
2466    // other one.
2467    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
2468                               Hi.getValue(1));
2469
2470    // Remember that we legalized the chain.
2471    AddLegalizedOperand(Op.getValue(1), TF);
2472    if (!TLI.isLittleEndian())
2473      std::swap(Lo, Hi);
2474    break;
2475  }
2476  case ISD::TAILCALL:
2477  case ISD::CALL: {
2478    SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2479    SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
2480
2481    bool Changed = false;
2482    std::vector<SDOperand> Ops;
2483    for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
2484      Ops.push_back(LegalizeOp(Node->getOperand(i)));
2485      Changed |= Ops.back() != Node->getOperand(i);
2486    }
2487
2488    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
2489           "Can only expand a call once so far, not i64 -> i16!");
2490
2491    std::vector<MVT::ValueType> RetTyVTs;
2492    RetTyVTs.reserve(3);
2493    RetTyVTs.push_back(NVT);
2494    RetTyVTs.push_back(NVT);
2495    RetTyVTs.push_back(MVT::Other);
2496    SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee, Ops,
2497                             Node->getOpcode() == ISD::TAILCALL);
2498    Lo = SDOperand(NC, 0);
2499    Hi = SDOperand(NC, 1);
2500
2501    // Insert the new chain mapping.
2502    AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
2503    break;
2504  }
2505  case ISD::AND:
2506  case ISD::OR:
2507  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
2508    SDOperand LL, LH, RL, RH;
2509    ExpandOp(Node->getOperand(0), LL, LH);
2510    ExpandOp(Node->getOperand(1), RL, RH);
2511    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
2512    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
2513    break;
2514  }
2515  case ISD::SELECT: {
2516    SDOperand C, LL, LH, RL, RH;
2517
2518    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2519    case Expand: assert(0 && "It's impossible to expand bools");
2520    case Legal:
2521      C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2522      break;
2523    case Promote:
2524      C = PromoteOp(Node->getOperand(0));  // Promote the condition.
2525      break;
2526    }
2527    ExpandOp(Node->getOperand(1), LL, LH);
2528    ExpandOp(Node->getOperand(2), RL, RH);
2529    Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
2530    Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
2531    break;
2532  }
2533  case ISD::SIGN_EXTEND: {
2534    SDOperand In;
2535    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2536    case Expand: assert(0 && "expand-expand not implemented yet!");
2537    case Legal: In = LegalizeOp(Node->getOperand(0)); break;
2538    case Promote:
2539      In = PromoteOp(Node->getOperand(0));
2540      // Emit the appropriate sign_extend_inreg to get the value we want.
2541      In = DAG.getNode(ISD::SIGN_EXTEND_INREG, In.getValueType(), In,
2542                       DAG.getValueType(Node->getOperand(0).getValueType()));
2543      break;
2544    }
2545
2546    // The low part is just a sign extension of the input (which degenerates to
2547    // a copy).
2548    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, In);
2549
2550    // The high part is obtained by SRA'ing all but one of the bits of the lo
2551    // part.
2552    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
2553    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
2554                                                       TLI.getShiftAmountTy()));
2555    break;
2556  }
2557  case ISD::ZERO_EXTEND: {
2558    SDOperand In;
2559    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2560    case Expand: assert(0 && "expand-expand not implemented yet!");
2561    case Legal: In = LegalizeOp(Node->getOperand(0)); break;
2562    case Promote:
2563      In = PromoteOp(Node->getOperand(0));
2564      // Emit the appropriate zero_extend_inreg to get the value we want.
2565      In = DAG.getZeroExtendInReg(In, Node->getOperand(0).getValueType());
2566      break;
2567    }
2568
2569    // The low part is just a zero extension of the input (which degenerates to
2570    // a copy).
2571    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, In);
2572
2573    // The high part is just a zero.
2574    Hi = DAG.getConstant(0, NVT);
2575    break;
2576  }
2577    // These operators cannot be expanded directly, emit them as calls to
2578    // library functions.
2579  case ISD::FP_TO_SINT:
2580    if (Node->getOperand(0).getValueType() == MVT::f32)
2581      Lo = ExpandLibCall("__fixsfdi", Node, Hi);
2582    else
2583      Lo = ExpandLibCall("__fixdfdi", Node, Hi);
2584    break;
2585  case ISD::FP_TO_UINT:
2586    if (Node->getOperand(0).getValueType() == MVT::f32)
2587      Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
2588    else
2589      Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
2590    break;
2591
2592  case ISD::SHL:
2593    // If we can emit an efficient shift operation, do so now.
2594    if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
2595      break;
2596
2597    // If this target supports SHL_PARTS, use it.
2598    if (TLI.getOperationAction(ISD::SHL_PARTS, NVT) == TargetLowering::Legal) {
2599      ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), Node->getOperand(1),
2600                       Lo, Hi);
2601      break;
2602    }
2603
2604    // Otherwise, emit a libcall.
2605    Lo = ExpandLibCall("__ashldi3", Node, Hi);
2606    break;
2607
2608  case ISD::SRA:
2609    // If we can emit an efficient shift operation, do so now.
2610    if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
2611      break;
2612
2613    // If this target supports SRA_PARTS, use it.
2614    if (TLI.getOperationAction(ISD::SRA_PARTS, NVT) == TargetLowering::Legal) {
2615      ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), Node->getOperand(1),
2616                       Lo, Hi);
2617      break;
2618    }
2619
2620    // Otherwise, emit a libcall.
2621    Lo = ExpandLibCall("__ashrdi3", Node, Hi);
2622    break;
2623  case ISD::SRL:
2624    // If we can emit an efficient shift operation, do so now.
2625    if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
2626      break;
2627
2628    // If this target supports SRL_PARTS, use it.
2629    if (TLI.getOperationAction(ISD::SRL_PARTS, NVT) == TargetLowering::Legal) {
2630      ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), Node->getOperand(1),
2631                       Lo, Hi);
2632      break;
2633    }
2634
2635    // Otherwise, emit a libcall.
2636    Lo = ExpandLibCall("__lshrdi3", Node, Hi);
2637    break;
2638
2639  case ISD::ADD:
2640    ExpandByParts(ISD::ADD_PARTS, Node->getOperand(0), Node->getOperand(1),
2641                  Lo, Hi);
2642    break;
2643  case ISD::SUB:
2644    ExpandByParts(ISD::SUB_PARTS, Node->getOperand(0), Node->getOperand(1),
2645                  Lo, Hi);
2646    break;
2647  case ISD::MUL: {
2648    if (TLI.getOperationAction(ISD::MULHU, NVT) == TargetLowering::Legal) {
2649      SDOperand LL, LH, RL, RH;
2650      ExpandOp(Node->getOperand(0), LL, LH);
2651      ExpandOp(Node->getOperand(1), RL, RH);
2652      Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
2653      RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
2654      LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
2655      Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
2656      Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
2657      Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
2658    } else {
2659      Lo = ExpandLibCall("__muldi3" , Node, Hi); break;
2660    }
2661    break;
2662  }
2663  case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
2664  case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
2665  case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
2666  case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
2667  }
2668
2669  // Remember in a map if the values will be reused later.
2670  if (!Node->hasOneUse()) {
2671    bool isNew = ExpandedNodes.insert(std::make_pair(Op,
2672                                            std::make_pair(Lo, Hi))).second;
2673    assert(isNew && "Value already expanded?!?");
2674  }
2675}
2676
2677
2678// SelectionDAG::Legalize - This is the entry point for the file.
2679//
2680void SelectionDAG::Legalize() {
2681  /// run - This is the main entry point to this class.
2682  ///
2683  SelectionDAGLegalize(*this).Run();
2684}
2685
2686