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