LegalizeDAG.cpp revision f8161d83f0201a32a33a0c875eb43df81d8586ab
1//===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SelectionDAG::Legalize method.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/SelectionDAG.h"
15#include "llvm/CodeGen/MachineConstantPool.h"
16#include "llvm/CodeGen/MachineFunction.h"
17#include "llvm/CodeGen/MachineFrameInfo.h"
18#include "llvm/Target/TargetLowering.h"
19#include "llvm/Target/TargetData.h"
20#include "llvm/Target/TargetOptions.h"
21#include "llvm/Constants.h"
22#include <iostream>
23using namespace llvm;
24
25//===----------------------------------------------------------------------===//
26/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
27/// hacks on it until the target machine can handle it.  This involves
28/// eliminating value sizes the machine cannot handle (promoting small sizes to
29/// large sizes or splitting up large values into small values) as well as
30/// eliminating operations the machine cannot handle.
31///
32/// This code also does a small amount of optimization and recognition of idioms
33/// as part of its processing.  For example, if a target does not support a
34/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
35/// will attempt merge setcc and brc instructions into brcc's.
36///
37namespace {
38class SelectionDAGLegalize {
39  TargetLowering &TLI;
40  SelectionDAG &DAG;
41
42  /// LegalizeAction - This enum indicates what action we should take for each
43  /// value type the can occur in the program.
44  enum LegalizeAction {
45    Legal,            // The target natively supports this value type.
46    Promote,          // This should be promoted to the next larger type.
47    Expand,           // This integer type should be broken into smaller pieces.
48  };
49
50  /// ValueTypeActions - This is a bitvector that contains two bits for each
51  /// value type, where the two bits correspond to the LegalizeAction enum.
52  /// This can be queried with "getTypeAction(VT)".
53  unsigned ValueTypeActions;
54
55  /// NeedsAnotherIteration - This is set when we expand a large integer
56  /// operation into smaller integer operations, but the smaller operations are
57  /// not set.  This occurs only rarely in practice, for targets that don't have
58  /// 32-bit or larger integer registers.
59  bool NeedsAnotherIteration;
60
61  /// LegalizedNodes - For nodes that are of legal width, and that have more
62  /// than one use, this map indicates what regularized operand to use.  This
63  /// allows us to avoid legalizing the same thing more than once.
64  std::map<SDOperand, SDOperand> LegalizedNodes;
65
66  /// PromotedNodes - For nodes that are below legal width, and that have more
67  /// than one use, this map indicates what promoted value to use.  This allows
68  /// us to avoid promoting the same thing more than once.
69  std::map<SDOperand, SDOperand> PromotedNodes;
70
71  /// ExpandedNodes - For nodes that need to be expanded, and which have more
72  /// than one use, this map indicates which which operands are the expanded
73  /// version of the input.  This allows us to avoid expanding the same node
74  /// more than once.
75  std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
76
77  void AddLegalizedOperand(SDOperand From, SDOperand To) {
78    bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
79    assert(isNew && "Got into the map somehow?");
80  }
81  void AddPromotedOperand(SDOperand From, SDOperand To) {
82    bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
83    assert(isNew && "Got into the map somehow?");
84  }
85
86public:
87
88  SelectionDAGLegalize(TargetLowering &TLI, SelectionDAG &DAG);
89
90  /// Run - While there is still lowering to do, perform a pass over the DAG.
91  /// Most regularization can be done in a single pass, but targets that require
92  /// large values to be split into registers multiple times (e.g. i64 -> 4x
93  /// i16) require iteration for these values (the first iteration will demote
94  /// to i32, the second will demote to i16).
95  void Run() {
96    do {
97      NeedsAnotherIteration = false;
98      LegalizeDAG();
99    } while (NeedsAnotherIteration);
100  }
101
102  /// getTypeAction - Return how we should legalize values of this type, either
103  /// it is already legal or we need to expand it into multiple registers of
104  /// smaller integer type, or we need to promote it to a larger type.
105  LegalizeAction getTypeAction(MVT::ValueType VT) const {
106    return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
107  }
108
109  /// isTypeLegal - Return true if this type is legal on this target.
110  ///
111  bool isTypeLegal(MVT::ValueType VT) const {
112    return getTypeAction(VT) == Legal;
113  }
114
115private:
116  void LegalizeDAG();
117
118  SDOperand LegalizeOp(SDOperand O);
119  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
120  SDOperand PromoteOp(SDOperand O);
121
122  SDOperand getIntPtrConstant(uint64_t Val) {
123    return DAG.getConstant(Val, TLI.getPointerTy());
124  }
125};
126}
127
128
129SelectionDAGLegalize::SelectionDAGLegalize(TargetLowering &tli,
130                                           SelectionDAG &dag)
131  : TLI(tli), DAG(dag), ValueTypeActions(TLI.getValueTypeActions()) {
132  assert(MVT::LAST_VALUETYPE <= 16 &&
133         "Too many value types for ValueTypeActions to hold!");
134}
135
136void SelectionDAGLegalize::LegalizeDAG() {
137  SDOperand OldRoot = DAG.getRoot();
138  SDOperand NewRoot = LegalizeOp(OldRoot);
139  DAG.setRoot(NewRoot);
140
141  ExpandedNodes.clear();
142  LegalizedNodes.clear();
143  PromotedNodes.clear();
144
145  // Remove dead nodes now.
146  DAG.RemoveDeadNodes(OldRoot.Val);
147}
148
149SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
150  assert(getTypeAction(Op.getValueType()) == Legal &&
151         "Caller should expand or promote operands that are not legal!");
152
153  // If this operation defines any values that cannot be represented in a
154  // register on this target, make sure to expand or promote them.
155  if (Op.Val->getNumValues() > 1) {
156    for (unsigned i = 0, e = Op.Val->getNumValues(); i != e; ++i)
157      switch (getTypeAction(Op.Val->getValueType(i))) {
158      case Legal: break;  // Nothing to do.
159      case Expand: {
160        SDOperand T1, T2;
161        ExpandOp(Op.getValue(i), T1, T2);
162        assert(LegalizedNodes.count(Op) &&
163               "Expansion didn't add legal operands!");
164        return LegalizedNodes[Op];
165      }
166      case Promote:
167        PromoteOp(Op.getValue(i));
168        assert(LegalizedNodes.count(Op) &&
169               "Expansion didn't add legal operands!");
170        return LegalizedNodes[Op];
171      }
172  }
173
174  std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
175  if (I != LegalizedNodes.end()) return I->second;
176
177  SDOperand Tmp1, Tmp2, Tmp3;
178
179  SDOperand Result = Op;
180  SDNode *Node = Op.Val;
181
182  switch (Node->getOpcode()) {
183  default:
184    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
185    assert(0 && "Do not know how to legalize this operator!");
186    abort();
187  case ISD::EntryToken:
188  case ISD::FrameIndex:
189  case ISD::GlobalAddress:
190  case ISD::ExternalSymbol:
191  case ISD::ConstantPool:           // Nothing to do.
192    assert(getTypeAction(Node->getValueType(0)) == Legal &&
193           "This must be legal!");
194    break;
195  case ISD::CopyFromReg:
196    Tmp1 = LegalizeOp(Node->getOperand(0));
197    if (Tmp1 != Node->getOperand(0))
198      Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
199                                  Node->getValueType(0), Tmp1);
200    break;
201  case ISD::ImplicitDef:
202    Tmp1 = LegalizeOp(Node->getOperand(0));
203    if (Tmp1 != Node->getOperand(0))
204      Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
205    break;
206  case ISD::Constant:
207    // We know we don't need to expand constants here, constants only have one
208    // value and we check that it is fine above.
209
210    // FIXME: Maybe we should handle things like targets that don't support full
211    // 32-bit immediates?
212    break;
213  case ISD::ConstantFP: {
214    // Spill FP immediates to the constant pool if the target cannot directly
215    // codegen them.  Targets often have some immediate values that can be
216    // efficiently generated into an FP register without a load.  We explicitly
217    // leave these constants as ConstantFP nodes for the target to deal with.
218
219    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
220
221    // Check to see if this FP immediate is already legal.
222    bool isLegal = false;
223    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
224           E = TLI.legal_fpimm_end(); I != E; ++I)
225      if (CFP->isExactlyValue(*I)) {
226        isLegal = true;
227        break;
228      }
229
230    if (!isLegal) {
231      // Otherwise we need to spill the constant to memory.
232      MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
233
234      bool Extend = false;
235
236      // If a FP immediate is precise when represented as a float, we put it
237      // into the constant pool as a float, even if it's is statically typed
238      // as a double.
239      MVT::ValueType VT = CFP->getValueType(0);
240      bool isDouble = VT == MVT::f64;
241      ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
242                                             Type::FloatTy, CFP->getValue());
243      if (isDouble && CFP->isExactlyValue((float)CFP->getValue())) {
244        LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
245        VT = MVT::f32;
246        Extend = true;
247      }
248
249      SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
250                                            TLI.getPointerTy());
251      if (Extend) {
252        Result = DAG.getNode(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(), CPIdx,
253                             MVT::f32);
254      } else {
255        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx);
256      }
257    }
258    break;
259  }
260  case ISD::TokenFactor: {
261    std::vector<SDOperand> Ops;
262    bool Changed = false;
263    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
264      Ops.push_back(LegalizeOp(Node->getOperand(i)));  // Legalize the operands
265      Changed |= Ops[i] != Node->getOperand(i);
266    }
267    if (Changed)
268      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
269    break;
270  }
271
272  case ISD::ADJCALLSTACKDOWN:
273  case ISD::ADJCALLSTACKUP:
274    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
275    // There is no need to legalize the size argument (Operand #1)
276    if (Tmp1 != Node->getOperand(0))
277      Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
278                           Node->getOperand(1));
279    break;
280  case ISD::DYNAMIC_STACKALLOC:
281    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
282    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
283    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
284    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
285        Tmp3 != Node->getOperand(2))
286      Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, Node->getValueType(0),
287                           Tmp1, Tmp2, Tmp3);
288    else
289      Result = Op.getValue(0);
290
291    // Since this op produces two values, make sure to remember that we
292    // legalized both of them.
293    AddLegalizedOperand(SDOperand(Node, 0), Result);
294    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
295    return Result.getValue(Op.ResNo);
296
297  case ISD::CALL:
298    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
299    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
300    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1)) {
301      std::vector<MVT::ValueType> RetTyVTs;
302      RetTyVTs.reserve(Node->getNumValues());
303      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
304        RetTyVTs.push_back(Node->getValueType(i));
305      Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2), 0);
306    } else {
307      Result = Result.getValue(0);
308    }
309    // Since calls produce multiple values, make sure to remember that we
310    // legalized all of them.
311    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
312      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
313    return Result.getValue(Op.ResNo);
314
315  case ISD::BR:
316    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
317    if (Tmp1 != Node->getOperand(0))
318      Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
319    break;
320
321  case ISD::BRCOND:
322    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
323    // FIXME: booleans might not be legal!
324    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the condition.
325    // Basic block destination (Op#2) is always legal.
326    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
327      Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
328                           Node->getOperand(2));
329    break;
330
331  case ISD::LOAD:
332    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
333    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
334    if (Tmp1 != Node->getOperand(0) ||
335        Tmp2 != Node->getOperand(1))
336      Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2);
337    else
338      Result = SDOperand(Node, 0);
339
340    // Since loads produce two values, make sure to remember that we legalized
341    // both of them.
342    AddLegalizedOperand(SDOperand(Node, 0), Result);
343    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
344    return Result.getValue(Op.ResNo);
345
346  case ISD::EXTLOAD:
347  case ISD::SEXTLOAD:
348  case ISD::ZEXTLOAD:
349    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
350    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
351    if (Tmp1 != Node->getOperand(0) ||
352        Tmp2 != Node->getOperand(1))
353      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1, Tmp2,
354                           cast<MVTSDNode>(Node)->getExtraValueType());
355    else
356      Result = SDOperand(Node, 0);
357
358    // Since loads produce two values, make sure to remember that we legalized
359    // both of them.
360    AddLegalizedOperand(SDOperand(Node, 0), Result);
361    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
362    return Result.getValue(Op.ResNo);
363
364  case ISD::EXTRACT_ELEMENT:
365    // Get both the low and high parts.
366    ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
367    if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
368      Result = Tmp2;  // 1 -> Hi
369    else
370      Result = Tmp1;  // 0 -> Lo
371    break;
372
373  case ISD::CopyToReg:
374    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
375
376    switch (getTypeAction(Node->getOperand(1).getValueType())) {
377    case Legal:
378      // Legalize the incoming value (must be legal).
379      Tmp2 = LegalizeOp(Node->getOperand(1));
380      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
381        Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
382      break;
383    case Expand: {
384      SDOperand Lo, Hi;
385      ExpandOp(Node->getOperand(1), Lo, Hi);
386      unsigned Reg = cast<RegSDNode>(Node)->getReg();
387      Result = DAG.getCopyToReg(Tmp1, Lo, Reg);
388      Result = DAG.getCopyToReg(Result, Hi, Reg+1);
389      assert(isTypeLegal(Result.getValueType()) &&
390             "Cannot expand multiple times yet (i64 -> i16)");
391      break;
392    }
393    case Promote:
394      assert(0 && "CopyToReg should not require promotion!");
395      abort();
396    }
397    break;
398
399  case ISD::RET:
400    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
401    switch (Node->getNumOperands()) {
402    case 2:  // ret val
403      switch (getTypeAction(Node->getOperand(1).getValueType())) {
404      case Legal:
405        Tmp2 = LegalizeOp(Node->getOperand(1));
406        if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
407          Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
408        break;
409      case Expand: {
410        SDOperand Lo, Hi;
411        ExpandOp(Node->getOperand(1), Lo, Hi);
412        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
413        break;
414      }
415      case Promote:
416        Tmp2 = PromoteOp(Node->getOperand(1));
417        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
418        break;
419      }
420      break;
421    case 1:  // ret void
422      if (Tmp1 != Node->getOperand(0))
423        Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
424      break;
425    default: { // ret <values>
426      std::vector<SDOperand> NewValues;
427      NewValues.push_back(Tmp1);
428      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
429        switch (getTypeAction(Node->getOperand(i).getValueType())) {
430        case Legal:
431          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
432          break;
433        case Expand: {
434          SDOperand Lo, Hi;
435          ExpandOp(Node->getOperand(i), Lo, Hi);
436          NewValues.push_back(Lo);
437          NewValues.push_back(Hi);
438          break;
439        }
440        case Promote:
441          assert(0 && "Can't promote multiple return value yet!");
442        }
443      Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
444      break;
445    }
446    }
447    break;
448  case ISD::STORE:
449    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
450    Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
451
452    // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
453    if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
454      if (CFP->getValueType(0) == MVT::f32) {
455        union {
456          unsigned I;
457          float    F;
458        } V;
459        V.F = CFP->getValue();
460        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
461                             DAG.getConstant(V.I, MVT::i32), Tmp2);
462      } else {
463        assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
464        union {
465          uint64_t I;
466          double   F;
467        } V;
468        V.F = CFP->getValue();
469        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
470                             DAG.getConstant(V.I, MVT::i64), Tmp2);
471      }
472      Op = Result;
473      Node = Op.Val;
474    }
475
476    switch (getTypeAction(Node->getOperand(1).getValueType())) {
477    case Legal: {
478      SDOperand Val = LegalizeOp(Node->getOperand(1));
479      if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
480          Tmp2 != Node->getOperand(2))
481        Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2);
482      break;
483    }
484    case Promote:
485      // Truncate the value and store the result.
486      Tmp3 = PromoteOp(Node->getOperand(1));
487      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
488                           Node->getOperand(1).getValueType());
489      break;
490
491    case Expand:
492      SDOperand Lo, Hi;
493      ExpandOp(Node->getOperand(1), Lo, Hi);
494
495      if (!TLI.isLittleEndian())
496        std::swap(Lo, Hi);
497
498      // FIXME: These two stores are independent of each other!
499      Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2);
500
501      unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
502      Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
503                         getIntPtrConstant(IncrementSize));
504      assert(isTypeLegal(Tmp2.getValueType()) &&
505             "Pointers must be legal!");
506      Result = DAG.getNode(ISD::STORE, MVT::Other, Result, Hi, Tmp2);
507    }
508    break;
509  case ISD::TRUNCSTORE:
510    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
511    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
512
513    switch (getTypeAction(Node->getOperand(1).getValueType())) {
514    case Legal:
515      Tmp2 = LegalizeOp(Node->getOperand(1));
516      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
517          Tmp3 != Node->getOperand(2))
518        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
519                             cast<MVTSDNode>(Node)->getExtraValueType());
520      break;
521    case Promote:
522    case Expand:
523      assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
524    }
525    break;
526  case ISD::SELECT:
527    // FIXME: BOOLS MAY REQUIRE PROMOTION!
528    Tmp1 = LegalizeOp(Node->getOperand(0));   // Cond
529    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
530    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
531
532    if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
533        Tmp3 != Node->getOperand(2))
534      Result = DAG.getNode(ISD::SELECT, Node->getValueType(0), Tmp1, Tmp2,Tmp3);
535    break;
536  case ISD::SETCC:
537    switch (getTypeAction(Node->getOperand(0).getValueType())) {
538    case Legal:
539      Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
540      Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
541      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
542        Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
543                              Tmp1, Tmp2);
544      break;
545    case Promote:
546      Tmp1 = PromoteOp(Node->getOperand(0));   // LHS
547      Tmp2 = PromoteOp(Node->getOperand(1));   // RHS
548
549      // If this is an FP compare, the operands have already been extended.
550      if (MVT::isInteger(Node->getOperand(0).getValueType())) {
551        MVT::ValueType VT = Node->getOperand(0).getValueType();
552        MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
553
554        // Otherwise, we have to insert explicit sign or zero extends.  Note
555        // that we could insert sign extends for ALL conditions, but zero extend
556        // is cheaper on many machines (an AND instead of two shifts), so prefer
557        // it.
558        switch (cast<SetCCSDNode>(Node)->getCondition()) {
559        default: assert(0 && "Unknown integer comparison!");
560        case ISD::SETEQ:
561        case ISD::SETNE:
562        case ISD::SETUGE:
563        case ISD::SETUGT:
564        case ISD::SETULE:
565        case ISD::SETULT:
566          // ALL of these operations will work if we either sign or zero extend
567          // the operands (including the unsigned comparisons!).  Zero extend is
568          // usually a simpler/cheaper operation, so prefer it.
569          Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
570          Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
571          break;
572        case ISD::SETGE:
573        case ISD::SETGT:
574        case ISD::SETLT:
575        case ISD::SETLE:
576          Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
577          Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
578          break;
579        }
580
581      }
582      Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
583                            Tmp1, Tmp2);
584      break;
585    case Expand:
586      SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
587      ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
588      ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
589      switch (cast<SetCCSDNode>(Node)->getCondition()) {
590      case ISD::SETEQ:
591      case ISD::SETNE:
592        Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
593        Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
594        Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
595        Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(), Tmp1,
596                              DAG.getConstant(0, Tmp1.getValueType()));
597        break;
598      default:
599        // FIXME: This generated code sucks.
600        ISD::CondCode LowCC;
601        switch (cast<SetCCSDNode>(Node)->getCondition()) {
602        default: assert(0 && "Unknown integer setcc!");
603        case ISD::SETLT:
604        case ISD::SETULT: LowCC = ISD::SETULT; break;
605        case ISD::SETGT:
606        case ISD::SETUGT: LowCC = ISD::SETUGT; break;
607        case ISD::SETLE:
608        case ISD::SETULE: LowCC = ISD::SETULE; break;
609        case ISD::SETGE:
610        case ISD::SETUGE: LowCC = ISD::SETUGE; break;
611        }
612
613        // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
614        // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
615        // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
616
617        // NOTE: on targets without efficient SELECT of bools, we can always use
618        // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
619        Tmp1 = DAG.getSetCC(LowCC, LHSLo, RHSLo);
620        Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
621                            LHSHi, RHSHi);
622        Result = DAG.getSetCC(ISD::SETEQ, LHSHi, RHSHi);
623        Result = DAG.getNode(ISD::SELECT, MVT::i1, Result, Tmp1, Tmp2);
624        break;
625      }
626    }
627    break;
628
629  case ISD::MEMSET:
630  case ISD::MEMCPY:
631  case ISD::MEMMOVE: {
632    Tmp1 = LegalizeOp(Node->getOperand(0));
633    Tmp2 = LegalizeOp(Node->getOperand(1));
634    Tmp3 = LegalizeOp(Node->getOperand(2));
635    SDOperand Tmp4 = LegalizeOp(Node->getOperand(3));
636    SDOperand Tmp5 = LegalizeOp(Node->getOperand(4));
637    if (TLI.isOperationSupported(Node->getOpcode(), MVT::Other)) {
638      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
639          Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
640          Tmp5 != Node->getOperand(4)) {
641        std::vector<SDOperand> Ops;
642        Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
643        Ops.push_back(Tmp4); Ops.push_back(Tmp5);
644        Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
645      }
646    } else {
647      // Otherwise, the target does not support this operation.  Lower the
648      // operation to an explicit libcall as appropriate.
649      MVT::ValueType IntPtr = TLI.getPointerTy();
650      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
651      std::vector<std::pair<SDOperand, const Type*> > Args;
652
653      const char *FnName = 0;
654      if (Node->getOpcode() == ISD::MEMSET) {
655        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
656        // Extend the ubyte argument to be an int value for the call.
657        Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
658        Args.push_back(std::make_pair(Tmp3, Type::IntTy));
659        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
660
661        FnName = "memset";
662      } else if (Node->getOpcode() == ISD::MEMCPY ||
663                 Node->getOpcode() == ISD::MEMMOVE) {
664        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
665        Args.push_back(std::make_pair(Tmp3, IntPtrTy));
666        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
667        FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
668      } else {
669        assert(0 && "Unknown op!");
670      }
671      std::pair<SDOperand,SDOperand> CallResult =
672        TLI.LowerCallTo(Tmp1, Type::VoidTy,
673                        DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
674      Result = LegalizeOp(CallResult.second);
675    }
676    break;
677  }
678  case ISD::ADD:
679  case ISD::SUB:
680  case ISD::MUL:
681  case ISD::UDIV:
682  case ISD::SDIV:
683  case ISD::UREM:
684  case ISD::SREM:
685  case ISD::AND:
686  case ISD::OR:
687  case ISD::XOR:
688  case ISD::SHL:
689  case ISD::SRL:
690  case ISD::SRA:
691    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
692    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
693    if (Tmp1 != Node->getOperand(0) ||
694        Tmp2 != Node->getOperand(1))
695      Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
696    break;
697  case ISD::ZERO_EXTEND:
698  case ISD::SIGN_EXTEND:
699  case ISD::TRUNCATE:
700  case ISD::FP_EXTEND:
701  case ISD::FP_ROUND:
702  case ISD::FP_TO_SINT:
703  case ISD::FP_TO_UINT:
704  case ISD::SINT_TO_FP:
705  case ISD::UINT_TO_FP:
706    switch (getTypeAction(Node->getOperand(0).getValueType())) {
707    case Legal:
708      Tmp1 = LegalizeOp(Node->getOperand(0));
709      if (Tmp1 != Node->getOperand(0))
710        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
711      break;
712    case Expand:
713      assert(Node->getOpcode() != ISD::SINT_TO_FP &&
714             Node->getOpcode() != ISD::UINT_TO_FP &&
715             "Cannot lower Xint_to_fp to a call yet!");
716
717      // In the expand case, we must be dealing with a truncate, because
718      // otherwise the result would be larger than the source.
719      assert(Node->getOpcode() == ISD::TRUNCATE &&
720             "Shouldn't need to expand other operators here!");
721      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
722
723      // Since the result is legal, we should just be able to truncate the low
724      // part of the source.
725      Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
726      break;
727
728    case Promote:
729      switch (Node->getOpcode()) {
730      case ISD::ZERO_EXTEND:
731        Result = PromoteOp(Node->getOperand(0));
732        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
733                             Result, Node->getOperand(0).getValueType());
734        break;
735      case ISD::SIGN_EXTEND:
736        Result = PromoteOp(Node->getOperand(0));
737        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
738                             Result, Node->getOperand(0).getValueType());
739        break;
740      case ISD::TRUNCATE:
741        Result = PromoteOp(Node->getOperand(0));
742        Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
743        break;
744      case ISD::FP_EXTEND:
745        Result = PromoteOp(Node->getOperand(0));
746        if (Result.getValueType() != Op.getValueType())
747          // Dynamically dead while we have only 2 FP types.
748          Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
749        break;
750      case ISD::FP_ROUND:
751      case ISD::FP_TO_SINT:
752      case ISD::FP_TO_UINT:
753        Result = PromoteOp(Node->getOperand(0));
754        Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
755        break;
756      case ISD::SINT_TO_FP:
757        Result = PromoteOp(Node->getOperand(0));
758        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
759                             Result, Node->getOperand(0).getValueType());
760        Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
761        break;
762      case ISD::UINT_TO_FP:
763        Result = PromoteOp(Node->getOperand(0));
764        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
765                             Result, Node->getOperand(0).getValueType());
766        Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
767        break;
768      }
769    }
770    break;
771  case ISD::FP_ROUND_INREG:
772  case ISD::SIGN_EXTEND_INREG:
773  case ISD::ZERO_EXTEND_INREG: {
774    Tmp1 = LegalizeOp(Node->getOperand(0));
775    MVT::ValueType ExtraVT = cast<MVTSDNode>(Node)->getExtraValueType();
776
777    // If this operation is not supported, convert it to a shl/shr or load/store
778    // pair.
779    if (!TLI.isOperationSupported(Node->getOpcode(), ExtraVT)) {
780      // If this is an integer extend and shifts are supported, do that.
781      if (Node->getOpcode() == ISD::ZERO_EXTEND_INREG) {
782        // NOTE: we could fall back on load/store here too for targets without
783        // AND.  However, it is doubtful that any exist.
784        // AND out the appropriate bits.
785        SDOperand Mask =
786          DAG.getConstant((1ULL << MVT::getSizeInBits(ExtraVT))-1,
787                          Node->getValueType(0));
788        Result = DAG.getNode(ISD::AND, Node->getValueType(0),
789                             Node->getOperand(0), Mask);
790      } else if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
791        // NOTE: we could fall back on load/store here too for targets without
792        // SAR.  However, it is doubtful that any exist.
793        unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
794                            MVT::getSizeInBits(ExtraVT);
795        SDOperand ShiftCst = DAG.getConstant(BitsDiff, MVT::i8);
796        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
797                             Node->getOperand(0), ShiftCst);
798        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
799                             Result, ShiftCst);
800      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
801        // The only way we can lower this is to turn it into a STORETRUNC,
802        // EXTLOAD pair, targetting a temporary location (a stack slot).
803
804        // NOTE: there is a choice here between constantly creating new stack
805        // slots and always reusing the same one.  We currently always create
806        // new ones, as reuse may inhibit scheduling.
807        const Type *Ty = MVT::getTypeForValueType(ExtraVT);
808        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
809        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
810        MachineFunction &MF = DAG.getMachineFunction();
811        int SSFI =
812          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
813        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
814        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
815                             Node->getOperand(0), StackSlot, ExtraVT);
816        Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
817                             Result, StackSlot, ExtraVT);
818      } else {
819        assert(0 && "Unknown op");
820      }
821      Result = LegalizeOp(Result);
822    } else {
823      if (Tmp1 != Node->getOperand(0))
824        Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
825                             ExtraVT);
826    }
827    break;
828  }
829  }
830
831  if (!Op.Val->hasOneUse())
832    AddLegalizedOperand(Op, Result);
833
834  return Result;
835}
836
837/// PromoteOp - Given an operation that produces a value in an invalid type,
838/// promote it to compute the value into a larger type.  The produced value will
839/// have the correct bits for the low portion of the register, but no guarantee
840/// is made about the top bits: it may be zero, sign-extended, or garbage.
841SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
842  MVT::ValueType VT = Op.getValueType();
843  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
844  assert(getTypeAction(VT) == Promote &&
845         "Caller should expand or legalize operands that are not promotable!");
846  assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
847         "Cannot promote to smaller type!");
848
849  std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
850  if (I != PromotedNodes.end()) return I->second;
851
852  SDOperand Tmp1, Tmp2, Tmp3;
853
854  SDOperand Result;
855  SDNode *Node = Op.Val;
856
857  // Promotion needs an optimization step to clean up after it, and is not
858  // careful to avoid operations the target does not support.  Make sure that
859  // all generated operations are legalized in the next iteration.
860  NeedsAnotherIteration = true;
861
862  switch (Node->getOpcode()) {
863  default:
864    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
865    assert(0 && "Do not know how to promote this operator!");
866    abort();
867  case ISD::CALL:
868    assert(0 && "Target's LowerCallTo implementation is buggy, returning value"
869           " types that are not supported by the target!");
870  case ISD::Constant:
871    Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
872    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
873    break;
874  case ISD::ConstantFP:
875    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
876    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
877    break;
878
879  case ISD::TRUNCATE:
880    switch (getTypeAction(Node->getOperand(0).getValueType())) {
881    case Legal:
882      Result = LegalizeOp(Node->getOperand(0));
883      assert(Result.getValueType() >= NVT &&
884             "This truncation doesn't make sense!");
885      if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
886        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
887      break;
888    case Expand:
889      assert(0 && "Cannot handle expand yet");
890    case Promote:
891      assert(0 && "Cannot handle promote-promote yet");
892    }
893    break;
894  case ISD::SIGN_EXTEND:
895  case ISD::ZERO_EXTEND:
896    switch (getTypeAction(Node->getOperand(0).getValueType())) {
897    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
898    case Legal:
899      // Input is legal?  Just do extend all the way to the larger type.
900      Result = LegalizeOp(Node->getOperand(0));
901      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
902      break;
903    case Promote:
904      // Promote the reg if it's smaller.
905      Result = PromoteOp(Node->getOperand(0));
906      // The high bits are not guaranteed to be anything.  Insert an extend.
907      if (Node->getOpcode() == ISD::SIGN_EXTEND)
908        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, VT);
909      else
910        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Result, VT);
911      break;
912    }
913    break;
914
915  case ISD::FP_EXTEND:
916    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
917  case ISD::FP_ROUND:
918    switch (getTypeAction(Node->getOperand(0).getValueType())) {
919    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
920    case Promote:  assert(0 && "Unreachable with 2 FP types!");
921    case Legal:
922      // Input is legal?  Do an FP_ROUND_INREG.
923      Result = LegalizeOp(Node->getOperand(0));
924      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
925      break;
926    }
927    break;
928
929  case ISD::SINT_TO_FP:
930  case ISD::UINT_TO_FP:
931    switch (getTypeAction(Node->getOperand(0).getValueType())) {
932    case Legal:
933      Result = LegalizeOp(Node->getOperand(0));
934      break;
935
936    case Promote:
937      Result = PromoteOp(Node->getOperand(0));
938      if (Node->getOpcode() == ISD::SINT_TO_FP)
939        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
940                             Result, Node->getOperand(0).getValueType());
941      else
942        Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
943                             Result, Node->getOperand(0).getValueType());
944      break;
945    case Expand:
946      assert(0 && "Unimplemented");
947    }
948    // No extra round required here.
949    Result = DAG.getNode(Node->getOpcode(), NVT, Result);
950    break;
951
952  case ISD::FP_TO_SINT:
953  case ISD::FP_TO_UINT:
954    switch (getTypeAction(Node->getOperand(0).getValueType())) {
955    case Legal:
956      Tmp1 = LegalizeOp(Node->getOperand(0));
957      break;
958    case Promote:
959      // The input result is prerounded, so we don't have to do anything
960      // special.
961      Tmp1 = PromoteOp(Node->getOperand(0));
962      break;
963    case Expand:
964      assert(0 && "not implemented");
965    }
966    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
967    break;
968
969  case ISD::AND:
970  case ISD::OR:
971  case ISD::XOR:
972  case ISD::ADD:
973  case ISD::SUB:
974  case ISD::MUL:
975    // The input may have strange things in the top bits of the registers, but
976    // these operations don't care.  They may have wierd bits going out, but
977    // that too is okay if they are integer operations.
978    Tmp1 = PromoteOp(Node->getOperand(0));
979    Tmp2 = PromoteOp(Node->getOperand(1));
980    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
981    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
982
983    // However, if this is a floating point operation, they will give excess
984    // precision that we may not be able to tolerate.  If we DO allow excess
985    // precision, just leave it, otherwise excise it.
986    // FIXME: Why would we need to round FP ops more than integer ones?
987    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
988    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
989      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
990    break;
991
992  case ISD::SDIV:
993  case ISD::SREM:
994    // These operators require that their input be sign extended.
995    Tmp1 = PromoteOp(Node->getOperand(0));
996    Tmp2 = PromoteOp(Node->getOperand(1));
997    if (MVT::isInteger(NVT)) {
998      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
999      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
1000    }
1001    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1002
1003    // Perform FP_ROUND: this is probably overly pessimistic.
1004    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1005      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1006    break;
1007
1008  case ISD::UDIV:
1009  case ISD::UREM:
1010    // These operators require that their input be zero extended.
1011    Tmp1 = PromoteOp(Node->getOperand(0));
1012    Tmp2 = PromoteOp(Node->getOperand(1));
1013    assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
1014    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1015    Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
1016    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1017    break;
1018
1019  case ISD::SHL:
1020    Tmp1 = PromoteOp(Node->getOperand(0));
1021    Tmp2 = LegalizeOp(Node->getOperand(1));
1022    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
1023    break;
1024  case ISD::SRA:
1025    // The input value must be properly sign extended.
1026    Tmp1 = PromoteOp(Node->getOperand(0));
1027    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1028    Tmp2 = LegalizeOp(Node->getOperand(1));
1029    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
1030    break;
1031  case ISD::SRL:
1032    // The input value must be properly zero extended.
1033    Tmp1 = PromoteOp(Node->getOperand(0));
1034    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1035    Tmp2 = LegalizeOp(Node->getOperand(1));
1036    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
1037    break;
1038  case ISD::LOAD:
1039    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1040    Tmp2 = LegalizeOp(Node->getOperand(1));   // Legalize the pointer.
1041    Result = DAG.getNode(ISD::EXTLOAD, NVT, Tmp1, Tmp2, VT);
1042
1043    // Remember that we legalized the chain.
1044    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1045    break;
1046  case ISD::SELECT:
1047    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the condition
1048    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
1049    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
1050    Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
1051    break;
1052  }
1053
1054  assert(Result.Val && "Didn't set a result!");
1055  AddPromotedOperand(Op, Result);
1056  return Result;
1057}
1058
1059/// ExpandOp - Expand the specified SDOperand into its two component pieces
1060/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
1061/// LegalizeNodes map is filled in for any results that are not expanded, the
1062/// ExpandedNodes map is filled in for any results that are expanded, and the
1063/// Lo/Hi values are returned.
1064void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
1065  MVT::ValueType VT = Op.getValueType();
1066  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1067  SDNode *Node = Op.Val;
1068  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
1069  assert(MVT::isInteger(VT) && "Cannot expand FP values!");
1070  assert(MVT::isInteger(NVT) && NVT < VT &&
1071         "Cannot expand to FP value or to larger int value!");
1072
1073  // If there is more than one use of this, see if we already expanded it.
1074  // There is no use remembering values that only have a single use, as the map
1075  // entries will never be reused.
1076  if (!Node->hasOneUse()) {
1077    std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
1078      = ExpandedNodes.find(Op);
1079    if (I != ExpandedNodes.end()) {
1080      Lo = I->second.first;
1081      Hi = I->second.second;
1082      return;
1083    }
1084  }
1085
1086  // Expanding to multiple registers needs to perform an optimization step, and
1087  // is not careful to avoid operations the target does not support.  Make sure
1088  // that all generated operations are legalized in the next iteration.
1089  NeedsAnotherIteration = true;
1090  const char *LibCallName = 0;
1091
1092  switch (Node->getOpcode()) {
1093  default:
1094    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1095    assert(0 && "Do not know how to expand this operator!");
1096    abort();
1097  case ISD::Constant: {
1098    uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
1099    Lo = DAG.getConstant(Cst, NVT);
1100    Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
1101    break;
1102  }
1103
1104  case ISD::CopyFromReg: {
1105    unsigned Reg = cast<RegSDNode>(Node)->getReg();
1106    // Aggregate register values are always in consequtive pairs.
1107    Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
1108    Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
1109
1110    // Remember that we legalized the chain.
1111    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
1112
1113    assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
1114    break;
1115  }
1116
1117  case ISD::LOAD: {
1118    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
1119    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1120    Lo = DAG.getLoad(NVT, Ch, Ptr);
1121
1122    // Increment the pointer to the other half.
1123    unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
1124    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1125                      getIntPtrConstant(IncrementSize));
1126    // FIXME: This load is independent of the first one.
1127    Hi = DAG.getLoad(NVT, Lo.getValue(1), Ptr);
1128
1129    // Remember that we legalized the chain.
1130    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
1131    if (!TLI.isLittleEndian())
1132      std::swap(Lo, Hi);
1133    break;
1134  }
1135  case ISD::CALL: {
1136    SDOperand Chain  = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1137    SDOperand Callee = LegalizeOp(Node->getOperand(1));  // Legalize the callee.
1138
1139    assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1140           "Can only expand a call once so far, not i64 -> i16!");
1141
1142    std::vector<MVT::ValueType> RetTyVTs;
1143    RetTyVTs.reserve(3);
1144    RetTyVTs.push_back(NVT);
1145    RetTyVTs.push_back(NVT);
1146    RetTyVTs.push_back(MVT::Other);
1147    SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee);
1148    Lo = SDOperand(NC, 0);
1149    Hi = SDOperand(NC, 1);
1150
1151    // Insert the new chain mapping.
1152    AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
1153    break;
1154  }
1155  case ISD::AND:
1156  case ISD::OR:
1157  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
1158    SDOperand LL, LH, RL, RH;
1159    ExpandOp(Node->getOperand(0), LL, LH);
1160    ExpandOp(Node->getOperand(1), RL, RH);
1161    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
1162    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
1163    break;
1164  }
1165  case ISD::SELECT: {
1166    SDOperand C, LL, LH, RL, RH;
1167    // FIXME: BOOLS MAY REQUIRE PROMOTION!
1168    C = LegalizeOp(Node->getOperand(0));
1169    ExpandOp(Node->getOperand(1), LL, LH);
1170    ExpandOp(Node->getOperand(2), RL, RH);
1171    Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
1172    Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
1173    break;
1174  }
1175  case ISD::SIGN_EXTEND: {
1176    // The low part is just a sign extension of the input (which degenerates to
1177    // a copy).
1178    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1179
1180    // The high part is obtained by SRA'ing all but one of the bits of the lo
1181    // part.
1182    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
1183    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1, MVT::i8));
1184    break;
1185  }
1186  case ISD::ZERO_EXTEND:
1187    // The low part is just a zero extension of the input (which degenerates to
1188    // a copy).
1189    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1190
1191    // The high part is just a zero.
1192    Hi = DAG.getConstant(0, NVT);
1193    break;
1194
1195    // These operators cannot be expanded directly, emit them as calls to
1196    // library functions.
1197  case ISD::FP_TO_SINT:
1198    if (Node->getOperand(0).getValueType() == MVT::f32)
1199      LibCallName = "__fixsfdi";
1200    else
1201      LibCallName = "__fixdfdi";
1202    break;
1203  case ISD::FP_TO_UINT:
1204    if (Node->getOperand(0).getValueType() == MVT::f32)
1205      LibCallName = "__fixunssfdi";
1206    else
1207      LibCallName = "__fixunsdfdi";
1208    break;
1209
1210  case ISD::ADD:  LibCallName = "__adddi3"; break;
1211  case ISD::SUB:  LibCallName = "__subdi3"; break;
1212  case ISD::MUL:  LibCallName = "__muldi3"; break;
1213  case ISD::SDIV: LibCallName = "__divdi3"; break;
1214  case ISD::UDIV: LibCallName = "__udivdi3"; break;
1215  case ISD::SREM: LibCallName = "__moddi3"; break;
1216  case ISD::UREM: LibCallName = "__umoddi3"; break;
1217  case ISD::SHL:  LibCallName = "__ashldi3"; break;
1218  case ISD::SRA:  LibCallName = "__ashrdi3"; break;
1219  case ISD::SRL:  LibCallName = "__lshrdi3"; break;
1220  }
1221
1222  // Int2FP -> __floatdisf/__floatdidf
1223
1224  // If this is to be expanded into a libcall... do so now.
1225  if (LibCallName) {
1226    TargetLowering::ArgListTy Args;
1227    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1228      Args.push_back(std::make_pair(Node->getOperand(i),
1229                 MVT::getTypeForValueType(Node->getOperand(i).getValueType())));
1230    SDOperand Callee = DAG.getExternalSymbol(LibCallName, TLI.getPointerTy());
1231
1232    // We don't care about token chains for libcalls.  We just use the entry
1233    // node as our input and ignore the output chain.  This allows us to place
1234    // calls wherever we need them to satisfy data dependences.
1235    SDOperand Result = TLI.LowerCallTo(DAG.getEntryNode(),
1236                           MVT::getTypeForValueType(Op.getValueType()), Callee,
1237                                       Args, DAG).first;
1238    ExpandOp(Result, Lo, Hi);
1239  }
1240
1241  // Remember in a map if the values will be reused later.
1242  if (!Node->hasOneUse()) {
1243    bool isNew = ExpandedNodes.insert(std::make_pair(Op,
1244                                            std::make_pair(Lo, Hi))).second;
1245    assert(isNew && "Value already expanded?!?");
1246  }
1247}
1248
1249
1250// SelectionDAG::Legalize - This is the entry point for the file.
1251//
1252void SelectionDAG::Legalize(TargetLowering &TLI) {
1253  /// run - This is the main entry point to this class.
1254  ///
1255  SelectionDAGLegalize(TLI, *this).Run();
1256}
1257
1258