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