Implement expansion of SINT_TO_FP and UINT_TO_FP operands.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAGTypes.cpp
1 //===-- LegalizeDAGTypes.cpp - Implement SelectionDAG::LegalizeTypes ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner 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::LegalizeTypes method.  It transforms
11 // an arbitrary well-formed SelectionDAG to only consist of legal types.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "legalize-types"
16 #include "llvm/CodeGen/SelectionDAG.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Target/TargetLowering.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 /// DAGTypeLegalizer - 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 ///
37 namespace {
38 class VISIBILITY_HIDDEN DAGTypeLegalizer {
39   TargetLowering &TLI;
40   SelectionDAG &DAG;
41   
42   // NodeIDFlags - This pass uses the NodeID on the SDNodes to hold information
43   // about the state of the node.  The enum has all the values.
44   enum NodeIDFlags {
45     /// ReadyToProcess - All operands have been processed, so this node is ready
46     /// to be handled.
47     ReadyToProcess = 0,
48     
49     /// NewNode - This is a new node that was created in the process of
50     /// legalizing some other node.
51     NewNode = -1,
52     
53     /// Processed - This is a node that has already been processed.
54     Processed = -2
55     
56     // 1+ - This is a node which has this many unlegalized operands.
57   };
58   
59   enum LegalizeAction {
60     Legal,      // The target natively supports this type.
61     Promote,    // This type should be executed in a larger type.
62     Expand      // This type should be split into two types of half the size.
63   };
64   
65   /// ValueTypeActions - This is a bitvector that contains two bits for each
66   /// simple value type, where the two bits correspond to the LegalizeAction
67   /// enum.  This can be queried with "getTypeAction(VT)".
68   TargetLowering::ValueTypeActionImpl ValueTypeActions;
69   
70   /// getTypeAction - Return how we should legalize values of this type, either
71   /// it is already legal or we need to expand it into multiple registers of
72   /// smaller integer type, or we need to promote it to a larger type.
73   LegalizeAction getTypeAction(MVT::ValueType VT) const {
74     return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
75   }
76   
77   /// isTypeLegal - Return true if this type is legal on this target.
78   ///
79   bool isTypeLegal(MVT::ValueType VT) const {
80     return getTypeAction(VT) == Legal;
81   }
82   
83   SDOperand getIntPtrConstant(uint64_t Val) {
84     return DAG.getConstant(Val, TLI.getPointerTy());
85   }
86   
87   /// PromotedNodes - For nodes that are below legal width, and that have more
88   /// than one use, this map indicates what promoted value to use.
89   DenseMap<SDOperand, SDOperand> PromotedNodes;
90   
91   /// ExpandedNodes - For nodes that need to be expanded this map indicates
92   /// which operands are the expanded version of the input.
93   DenseMap<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
94   
95   /// Worklist - This defines a worklist of nodes to process.  In order to be
96   /// pushed onto this worklist, all operands of a node must have already been
97   /// processed.
98   SmallVector<SDNode*, 128> Worklist;
99   
100 public:
101   DAGTypeLegalizer(SelectionDAG &dag)
102     : TLI(dag.getTargetLoweringInfo()), DAG(dag),
103     ValueTypeActions(TLI.getValueTypeActions()) {
104     assert(MVT::LAST_VALUETYPE <= 32 &&
105            "Too many value types for ValueTypeActions to hold!");
106   }      
107   
108   void run();
109   
110 private:
111   void MarkNewNodes(SDNode *N);
112   
113   void ReplaceLegalValueWith(SDOperand From, SDOperand To);
114   
115   SDOperand GetPromotedOp(SDOperand Op) {
116     Op = PromotedNodes[Op];
117     assert(Op.Val && "Operand wasn't promoted?");
118     return Op;
119   }    
120   void SetPromotedOp(SDOperand Op, SDOperand Result);
121
122   void GetExpandedOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi);
123   void SetExpandedOp(SDOperand Op, SDOperand Lo, SDOperand Hi);
124   
125   SDOperand CreateStackStoreLoad(SDOperand Op, MVT::ValueType DestVT);
126   
127   // Result Promotion.
128   void PromoteResult(SDNode *N, unsigned ResNo);
129   SDOperand PromoteResult_UNDEF(SDNode *N);
130   SDOperand PromoteResult_Constant(SDNode *N);
131   SDOperand PromoteResult_TRUNCATE(SDNode *N);
132   SDOperand PromoteResult_INT_EXTEND(SDNode *N);
133   SDOperand PromoteResult_FP_ROUND(SDNode *N);
134   SDOperand PromoteResult_SETCC(SDNode *N);
135   SDOperand PromoteResult_LOAD(LoadSDNode *N);
136   SDOperand PromoteResult_SimpleIntBinOp(SDNode *N);
137   SDOperand PromoteResult_SELECT   (SDNode *N);
138   SDOperand PromoteResult_SELECT_CC(SDNode *N);
139   
140   // Result Expansion.
141   void ExpandResult(SDNode *N, unsigned ResNo);
142   void ExpandResult_UNDEF      (SDNode *N, SDOperand &Lo, SDOperand &Hi);
143   void ExpandResult_Constant   (SDNode *N, SDOperand &Lo, SDOperand &Hi);
144   void ExpandResult_BUILD_PAIR (SDNode *N, SDOperand &Lo, SDOperand &Hi);
145   void ExpandResult_ANY_EXTEND (SDNode *N, SDOperand &Lo, SDOperand &Hi);
146   void ExpandResult_ZERO_EXTEND(SDNode *N, SDOperand &Lo, SDOperand &Hi);
147   void ExpandResult_SIGN_EXTEND(SDNode *N, SDOperand &Lo, SDOperand &Hi);
148   void ExpandResult_BIT_CONVERT(SDNode *N, SDOperand &Lo, SDOperand &Hi);
149   void ExpandResult_LOAD       (LoadSDNode *N, SDOperand &Lo, SDOperand &Hi);
150
151   void ExpandResult_Logical    (SDNode *N, SDOperand &Lo, SDOperand &Hi);
152   void ExpandResult_ADDSUB     (SDNode *N, SDOperand &Lo, SDOperand &Hi);
153   void ExpandResult_ADDSUBC    (SDNode *N, SDOperand &Lo, SDOperand &Hi);
154   void ExpandResult_SELECT     (SDNode *N, SDOperand &Lo, SDOperand &Hi);
155   void ExpandResult_SELECT_CC  (SDNode *N, SDOperand &Lo, SDOperand &Hi);
156   void ExpandResult_MUL        (SDNode *N, SDOperand &Lo, SDOperand &Hi);
157   void ExpandResult_Shift      (SDNode *N, SDOperand &Lo, SDOperand &Hi);
158   
159   void ExpandShiftByConstant(SDNode *N, unsigned Amt, 
160                              SDOperand &Lo, SDOperand &Hi);
161   bool ExpandShiftWithKnownAmountBit(SDNode *N, SDOperand &Lo, SDOperand &Hi);
162
163   // Operand Promotion.
164   bool PromoteOperand(SDNode *N, unsigned OperandNo);
165   SDOperand PromoteOperand_ANY_EXTEND(SDNode *N);
166   SDOperand PromoteOperand_ZERO_EXTEND(SDNode *N);
167   SDOperand PromoteOperand_SIGN_EXTEND(SDNode *N);
168   SDOperand PromoteOperand_FP_EXTEND(SDNode *N);
169   SDOperand PromoteOperand_FP_ROUND(SDNode *N);
170   SDOperand PromoteOperand_SELECT(SDNode *N, unsigned OpNo);
171   SDOperand PromoteOperand_BRCOND(SDNode *N, unsigned OpNo);
172   SDOperand PromoteOperand_BR_CC(SDNode *N, unsigned OpNo);
173   SDOperand PromoteOperand_STORE(StoreSDNode *N, unsigned OpNo);
174   
175   void PromoteSetCCOperands(SDOperand &LHS,SDOperand &RHS, ISD::CondCode Code);
176
177   // Operand Expansion.
178   bool ExpandOperand(SDNode *N, unsigned OperandNo);
179   SDOperand ExpandOperand_TRUNCATE(SDNode *N);
180   SDOperand ExpandOperand_UINT_TO_FP(SDOperand Source, MVT::ValueType DestTy);
181   SDOperand ExpandOperand_SINT_TO_FP(SDOperand Source, MVT::ValueType DestTy);
182   SDOperand ExpandOperand_EXTRACT_ELEMENT(SDNode *N);
183   SDOperand ExpandOperand_SETCC(SDNode *N);
184   SDOperand ExpandOperand_STORE(StoreSDNode *N, unsigned OpNo);
185
186   void ExpandSetCCOperands(SDOperand &NewLHS, SDOperand &NewRHS,
187                            ISD::CondCode &CCCode);
188 };
189 }  // end anonymous namespace
190
191
192
193 /// run - This is the main entry point for the type legalizer.  This does a
194 /// top-down traversal of the dag, legalizing types as it goes.
195 void DAGTypeLegalizer::run() {
196   // Create a dummy node (which is not added to allnodes), that adds a reference
197   // to the root node, preventing it from being deleted, and tracking any
198   // changes of the root.
199   HandleSDNode Dummy(DAG.getRoot());
200
201   // The root of the dag may dangle to deleted nodes until the type legalizer is
202   // done.  Set it to null to avoid confusion.
203   DAG.setRoot(SDOperand());
204   
205   // Walk all nodes in the graph, assigning them a NodeID of 'ReadyToProcess'
206   // (and remembering them) if they are leaves and assigning 'NewNode' if
207   // non-leaves.
208   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
209        E = DAG.allnodes_end(); I != E; ++I) {
210     if (I->getNumOperands() == 0) {
211       I->setNodeId(ReadyToProcess);
212       Worklist.push_back(I);
213     } else {
214       I->setNodeId(NewNode);
215     }
216   }
217   
218   // Now that we have a set of nodes to process, handle them all.
219   while (!Worklist.empty()) {
220     SDNode *N = Worklist.back();
221     Worklist.pop_back();
222     assert(N->getNodeId() == ReadyToProcess &&
223            "Node should be ready if on worklist!");
224     
225     // Scan the values produced by the node, checking to see if any result
226     // types are illegal.
227     unsigned i = 0;
228     unsigned NumResults = N->getNumValues();
229     do {
230       LegalizeAction Action = getTypeAction(N->getValueType(i));
231       if (Action == Promote) {
232         PromoteResult(N, i);
233         goto NodeDone;
234       } else if (Action == Expand) {
235         ExpandResult(N, i);
236         goto NodeDone;
237       } else {
238         assert(Action == Legal && "Unknown action!");
239       }
240     } while (++i < NumResults);
241     
242     // Scan the operand list for the node, handling any nodes with operands that
243     // are illegal.
244     {
245     unsigned NumOperands = N->getNumOperands();
246     bool NeedsRevisit = false;
247     for (i = 0; i != NumOperands; ++i) {
248       LegalizeAction Action = getTypeAction(N->getOperand(i).getValueType());
249       if (Action == Promote) {
250         NeedsRevisit = PromoteOperand(N, i);
251         break;
252       } else if (Action == Expand) {
253         NeedsRevisit = ExpandOperand(N, i);
254         break;
255       } else {
256         assert(Action == Legal && "Unknown action!");
257       }
258     }
259
260     // If the node needs revisiting, don't add all users to the worklist etc.
261     if (NeedsRevisit)
262       continue;
263     
264     if (i == NumOperands)
265       DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
266     }
267 NodeDone:
268
269     // If we reach here, the node was processed, potentially creating new nodes.
270     // Mark it as processed and add its users to the worklist as appropriate.
271     N->setNodeId(Processed);
272     
273     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
274          UI != E; ++UI) {
275       SDNode *User = *UI;
276       int NodeID = User->getNodeId();
277       assert(NodeID != ReadyToProcess && NodeID != Processed &&
278              "Invalid node id for user of unprocessed node!");
279       
280       // This node has two options: it can either be a new node or its Node ID
281       // may be a count of the number of operands it has that are not ready.
282       if (NodeID > 0) {
283         User->setNodeId(NodeID-1);
284         
285         // If this was the last use it was waiting on, add it to the ready list.
286         if (NodeID-1 == ReadyToProcess)
287           Worklist.push_back(User);
288         continue;
289       }
290       
291       // Otherwise, this node is new: this is the first operand of it that
292       // became ready.  Its new NodeID is the number of operands it has minus 1
293       // (as this node is now processed).
294       assert(NodeID == NewNode && "Unknown node ID!");
295       User->setNodeId(User->getNumOperands()-1);
296       
297       // If the node only has a single operand, it is now ready.
298       if (User->getNumOperands() == 1)
299         Worklist.push_back(User);
300     }
301   }
302   
303   // If the root changed (e.g. it was a dead load, update the root).
304   DAG.setRoot(Dummy.getValue());
305
306   //DAG.viewGraph();
307
308   // Remove dead nodes.  This is important to do for cleanliness but also before
309   // the checking loop below.  Implicit folding by the DAG.getNode operators can
310   // cause unreachable nodes to be around with their flags set to new.
311   DAG.RemoveDeadNodes();
312
313   // In a debug build, scan all the nodes to make sure we found them all.  This
314   // ensures that there are no cycles and that everything got processed.
315 #ifndef NDEBUG
316   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
317        E = DAG.allnodes_end(); I != E; ++I) {
318     if (I->getNodeId() == Processed)
319       continue;
320     cerr << "Unprocessed node: ";
321     I->dump(&DAG); cerr << "\n";
322
323     if (I->getNodeId() == NewNode)
324       cerr << "New node not 'noticed'?\n";
325     else if (I->getNodeId() > 0)
326       cerr << "Operand not processed?\n";
327     else if (I->getNodeId() == ReadyToProcess)
328       cerr << "Not added to worklist?\n";
329     abort();
330   }
331 #endif
332 }
333
334 /// MarkNewNodes - The specified node is the root of a subtree of potentially
335 /// new nodes.  Add the correct NodeId to mark it.
336 void DAGTypeLegalizer::MarkNewNodes(SDNode *N) {
337   // If this was an existing node that is already done, we're done.
338   if (N->getNodeId() != NewNode)
339     return;
340
341   // Okay, we know that this node is new.  Recursively walk all of its operands
342   // to see if they are new also.  The depth of this walk is bounded by the size
343   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
344   // about revisiting of nodes.
345   //
346   // As we walk the operands, keep track of the number of nodes that are
347   // processed.  If non-zero, this will become the new nodeid of this node.
348   unsigned NumProcessed = 0;
349   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
350     int OpId = N->getOperand(i).Val->getNodeId();
351     if (OpId == NewNode)
352       MarkNewNodes(N->getOperand(i).Val);
353     else if (OpId == Processed)
354       ++NumProcessed;
355   }
356   
357   N->setNodeId(N->getNumOperands()-NumProcessed);
358   if (N->getNodeId() == ReadyToProcess)
359     Worklist.push_back(N);
360 }
361
362 /// ReplaceLegalValueWith - The specified value with a legal type was legalized
363 /// to the specified other value.  If they are different, update the DAG and
364 /// NodeIDs replacing any uses of From to use To instead.
365 void DAGTypeLegalizer::ReplaceLegalValueWith(SDOperand From, SDOperand To) {
366   if (From == To) return;
367   
368   // If expansion produced new nodes, make sure they are properly marked.
369   if (To.Val->getNodeId() == NewNode)
370     MarkNewNodes(To.Val);
371   
372   // Anything that used the old node should now use the new one.  Note that this
373   // can potentially cause recursive merging.
374   DAG.ReplaceAllUsesOfValueWith(From, To);
375   
376   // Since we just made an unstructured update to the DAG, which could wreak
377   // general havoc on anything that once used N and now uses Res, walk all users
378   // of the result, updating their flags.
379   for (SDNode::use_iterator I = To.Val->use_begin(), E = To.Val->use_end();
380        I != E; ++I) {
381     SDNode *User = *I;
382     // If the node isn't already processed or in the worklist, mark it as new,
383     // then use MarkNewNodes to recompute its ID.
384     int NodeId = User->getNodeId();
385     if (NodeId != ReadyToProcess && NodeId != Processed) {
386       User->setNodeId(NewNode);
387       MarkNewNodes(User);
388     }
389   }
390 }
391
392 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
393   if (Result.Val->getNodeId() == NewNode) 
394     MarkNewNodes(Result.Val);
395
396   SDOperand &OpEntry = PromotedNodes[Op];
397   assert(OpEntry.Val == 0 && "Node is already promoted!");
398   OpEntry = Result;
399 }
400
401 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo, 
402                                      SDOperand &Hi) {
403   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
404   assert(Entry.first.Val && "Operand isn't expanded");
405   Lo = Entry.first;
406   Hi = Entry.second;
407 }
408
409 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo, 
410                                      SDOperand Hi) {
411   // Remember that this is the result of the node.
412   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
413   assert(Entry.first.Val == 0 && "Node already expanded");
414   Entry.first = Lo;
415   Entry.second = Hi;
416   
417   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
418   if (Lo.Val->getNodeId() == NewNode) 
419     MarkNewNodes(Lo.Val);
420   if (Hi.Val->getNodeId() == NewNode) 
421     MarkNewNodes(Hi.Val);
422 }
423
424 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op, 
425                                                  MVT::ValueType DestVT) {
426   // Create the stack frame object.
427   SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
428   
429   // Emit a store to the stack slot.
430   SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
431   // Result is a load from the stack slot.
432   return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
433 }
434
435 //===----------------------------------------------------------------------===//
436 //  Result Promotion
437 //===----------------------------------------------------------------------===//
438
439 /// PromoteResult - This method is called when a result of a node is found to be
440 /// in need of promotion to a larger type.  At this point, the node may also
441 /// have invalid operands or may have other results that need expansion, we just
442 /// know that (at least) one result needs promotion.
443 void DAGTypeLegalizer::PromoteResult(SDNode *N, unsigned ResNo) {
444   DEBUG(cerr << "Promote node result: "; N->dump(&DAG); cerr << "\n");
445   SDOperand Result = SDOperand();
446   
447   switch (N->getOpcode()) {
448   default:
449 #ifndef NDEBUG
450     cerr << "PromoteResult #" << ResNo << ": ";
451     N->dump(&DAG); cerr << "\n";
452 #endif
453     assert(0 && "Do not know how to promote this operator!");
454     abort();
455   case ISD::UNDEF:    Result = PromoteResult_UNDEF(N); break;
456   case ISD::Constant: Result = PromoteResult_Constant(N); break;
457     
458   case ISD::TRUNCATE:    Result = PromoteResult_TRUNCATE(N); break;
459   case ISD::SIGN_EXTEND:
460   case ISD::ZERO_EXTEND:
461   case ISD::ANY_EXTEND:  Result = PromoteResult_INT_EXTEND(N); break;
462   case ISD::FP_ROUND:    Result = PromoteResult_FP_ROUND(N); break;
463     
464   case ISD::SETCC:    Result = PromoteResult_SETCC(N); break;
465   case ISD::LOAD:     Result = PromoteResult_LOAD(cast<LoadSDNode>(N)); break;
466     
467   case ISD::AND:
468   case ISD::OR:
469   case ISD::XOR:
470   case ISD::ADD:
471   case ISD::SUB:
472   case ISD::MUL:      Result = PromoteResult_SimpleIntBinOp(N); break;
473     
474   case ISD::SELECT:    Result = PromoteResult_SELECT(N); break;
475   case ISD::SELECT_CC: Result = PromoteResult_SELECT_CC(N); break;
476
477   }      
478   
479   // If Result is null, the sub-method took care of registering the result.
480   if (Result.Val)
481     SetPromotedOp(SDOperand(N, ResNo), Result);
482 }
483
484 SDOperand DAGTypeLegalizer::PromoteResult_UNDEF(SDNode *N) {
485   return DAG.getNode(ISD::UNDEF, TLI.getTypeToTransformTo(N->getValueType(0)));
486 }
487
488 SDOperand DAGTypeLegalizer::PromoteResult_Constant(SDNode *N) {
489   MVT::ValueType VT = N->getValueType(0);
490   // Zero extend things like i1, sign extend everything else.  It shouldn't
491   // matter in theory which one we pick, but this tends to give better code?
492   unsigned Opc = VT != MVT::i1 ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
493   SDOperand Result = DAG.getNode(Opc, TLI.getTypeToTransformTo(VT),
494                                  SDOperand(N, 0));
495   assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
496   return Result;
497 }
498
499 SDOperand DAGTypeLegalizer::PromoteResult_TRUNCATE(SDNode *N) {
500   SDOperand Res;
501
502   switch (getTypeAction(N->getOperand(0).getValueType())) {
503   default: assert(0 && "Unknown type action!");
504   case Legal:
505   case Expand:
506     Res = N->getOperand(0);
507     break;
508   case Promote:
509     Res = GetPromotedOp(N->getOperand(0));
510     break;
511   }
512
513   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
514   assert(MVT::getSizeInBits(Res.getValueType()) >= MVT::getSizeInBits(NVT) &&
515          "Truncation doesn't make sense!");
516   if (Res.getValueType() == NVT)
517     return Res;
518
519   // Truncate to NVT instead of VT
520   return DAG.getNode(ISD::TRUNCATE, NVT, Res);
521 }
522
523 SDOperand DAGTypeLegalizer::PromoteResult_INT_EXTEND(SDNode *N) {
524   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
525
526   if (getTypeAction(N->getOperand(0).getValueType()) == Promote) {
527     SDOperand Res = GetPromotedOp(N->getOperand(0));
528     assert(MVT::getSizeInBits(Res.getValueType()) <= MVT::getSizeInBits(NVT) &&
529            "Extension doesn't make sense!");
530
531     // If the result and operand types are the same after promotion, simplify
532     // to an in-register extension.
533     if (NVT == Res.getValueType()) {
534       // The high bits are not guaranteed to be anything.  Insert an extend.
535       if (N->getOpcode() == ISD::SIGN_EXTEND)
536         return DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Res,
537                            DAG.getValueType(N->getOperand(0).getValueType()));
538       if (N->getOpcode() == ISD::ZERO_EXTEND)
539         return DAG.getZeroExtendInReg(Res, N->getOperand(0).getValueType());
540       assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
541       return Res;
542     }
543   }
544
545   // Otherwise, just extend the original operand all the way to the larger type.
546   return DAG.getNode(N->getOpcode(), NVT, N->getOperand(0));
547 }
548
549 SDOperand DAGTypeLegalizer::PromoteResult_FP_ROUND(SDNode *N) {
550   // NOTE: Assumes input is legal.
551   return DAG.getNode(ISD::FP_ROUND_INREG, N->getOperand(0).getValueType(),
552                      N->getOperand(0), DAG.getValueType(N->getValueType(0)));
553 }
554
555 SDOperand DAGTypeLegalizer::PromoteResult_SETCC(SDNode *N) {
556   assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
557   return DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), N->getOperand(0),
558                      N->getOperand(1), N->getOperand(2));
559 }
560
561 SDOperand DAGTypeLegalizer::PromoteResult_LOAD(LoadSDNode *N) {
562   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
563   ISD::LoadExtType ExtType =
564     ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
565   SDOperand Res = DAG.getExtLoad(ExtType, NVT, N->getChain(), N->getBasePtr(),
566                                  N->getSrcValue(), N->getSrcValueOffset(),
567                                  N->getLoadedVT(), N->isVolatile(),
568                                  N->getAlignment());
569
570   // Legalized the chain result - switch anything that used the old chain to
571   // use the new one.
572   ReplaceLegalValueWith(SDOperand(N, 1), Res.getValue(1));
573   return Res;
574 }
575
576 SDOperand DAGTypeLegalizer::PromoteResult_SimpleIntBinOp(SDNode *N) {
577   // The input may have strange things in the top bits of the registers, but
578   // these operations don't care.  They may have weird bits going out, but
579   // that too is okay if they are integer operations.
580   SDOperand LHS = GetPromotedOp(N->getOperand(0));
581   SDOperand RHS = GetPromotedOp(N->getOperand(1));
582   return DAG.getNode(N->getOpcode(), LHS.getValueType(), LHS, RHS);
583 }
584
585 SDOperand DAGTypeLegalizer::PromoteResult_SELECT(SDNode *N) {
586   SDOperand LHS = GetPromotedOp(N->getOperand(1));
587   SDOperand RHS = GetPromotedOp(N->getOperand(2));
588   return DAG.getNode(ISD::SELECT, LHS.getValueType(), N->getOperand(0),LHS,RHS);
589 }
590
591 SDOperand DAGTypeLegalizer::PromoteResult_SELECT_CC(SDNode *N) {
592   SDOperand LHS = GetPromotedOp(N->getOperand(2));
593   SDOperand RHS = GetPromotedOp(N->getOperand(3));
594   return DAG.getNode(ISD::SELECT_CC, LHS.getValueType(), N->getOperand(0),
595                      N->getOperand(1), LHS, RHS, N->getOperand(4));
596 }
597
598 //===----------------------------------------------------------------------===//
599 //  Result Expansion
600 //===----------------------------------------------------------------------===//
601
602 /// ExpandResult - This method is called when the specified result of the
603 /// specified node is found to need expansion.  At this point, the node may also
604 /// have invalid operands or may have other results that need promotion, we just
605 /// know that (at least) one result needs expansion.
606 void DAGTypeLegalizer::ExpandResult(SDNode *N, unsigned ResNo) {
607   DEBUG(cerr << "Expand node result: "; N->dump(&DAG); cerr << "\n");
608   SDOperand Lo, Hi;
609   Lo = Hi = SDOperand();
610
611   // If this is a single-result node, see if the target wants to custom expand
612   // it.
613   if (N->getNumValues() == 1 &&
614       TLI.getOperationAction(N->getOpcode(),
615                              N->getValueType(0)) == TargetLowering::Custom) {
616     // If the target wants to, allow it to lower this itself.
617     std::pair<SDOperand,SDOperand> P =
618       TLI.ExpandOperation(SDOperand(N, 0), DAG);
619     if (P.first.Val) {
620       Lo = P.first;
621       Hi = P.second;
622       return;
623     }
624   }
625   
626   switch (N->getOpcode()) {
627   default:
628 #ifndef NDEBUG
629     cerr << "ExpandResult #" << ResNo << ": ";
630     N->dump(&DAG); cerr << "\n";
631 #endif
632     assert(0 && "Do not know how to expand this operator!");
633     abort();
634       
635   case ISD::UNDEF:       ExpandResult_UNDEF(N, Lo, Hi); break;
636   case ISD::Constant:    ExpandResult_Constant(N, Lo, Hi); break;
637   case ISD::BUILD_PAIR:  ExpandResult_BUILD_PAIR(N, Lo, Hi); break;
638   case ISD::ANY_EXTEND:  ExpandResult_ANY_EXTEND(N, Lo, Hi); break;
639   case ISD::ZERO_EXTEND: ExpandResult_ZERO_EXTEND(N, Lo, Hi); break;
640   case ISD::SIGN_EXTEND: ExpandResult_SIGN_EXTEND(N, Lo, Hi); break;
641   case ISD::BIT_CONVERT: ExpandResult_BIT_CONVERT(N, Lo, Hi); break;
642   case ISD::LOAD:        ExpandResult_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
643     
644   case ISD::AND:
645   case ISD::OR:
646   case ISD::XOR:         ExpandResult_Logical(N, Lo, Hi); break;
647   case ISD::ADD:
648   case ISD::SUB:         ExpandResult_ADDSUB(N, Lo, Hi); break;
649   case ISD::ADDC:
650   case ISD::SUBC:        ExpandResult_ADDSUBC(N, Lo, Hi); break;
651   case ISD::SELECT:      ExpandResult_SELECT(N, Lo, Hi); break;
652   case ISD::SELECT_CC:   ExpandResult_SELECT_CC(N, Lo, Hi); break;
653   case ISD::MUL:         ExpandResult_MUL(N, Lo, Hi); break;
654   case ISD::SHL:
655   case ISD::SRA:
656   case ISD::SRL:         ExpandResult_Shift(N, Lo, Hi); break;
657
658   }
659   
660   // If Lo/Hi is null, the sub-method took care of registering results etc.
661   if (Lo.Val)
662     SetExpandedOp(SDOperand(N, ResNo), Lo, Hi);
663 }
664
665 void DAGTypeLegalizer::ExpandResult_UNDEF(SDNode *N,
666                                           SDOperand &Lo, SDOperand &Hi) {
667   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
668   Lo = Hi = DAG.getNode(ISD::UNDEF, NVT);
669 }
670
671 void DAGTypeLegalizer::ExpandResult_Constant(SDNode *N,
672                                              SDOperand &Lo, SDOperand &Hi) {
673   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
674   uint64_t Cst = cast<ConstantSDNode>(N)->getValue();
675   Lo = DAG.getConstant(Cst, NVT);
676   Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
677 }
678
679 void DAGTypeLegalizer::ExpandResult_BUILD_PAIR(SDNode *N,
680                                                SDOperand &Lo, SDOperand &Hi) {
681   // Return the operands.
682   Lo = N->getOperand(0);
683   Hi = N->getOperand(1);
684 }
685
686 void DAGTypeLegalizer::ExpandResult_ANY_EXTEND(SDNode *N, 
687                                                SDOperand &Lo, SDOperand &Hi) {
688   
689   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
690   // The low part is any extension of the input (which degenerates to a copy).
691   Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, N->getOperand(0));
692   Hi = DAG.getNode(ISD::UNDEF, NVT);   // The high part is undefined.
693 }
694
695 void DAGTypeLegalizer::ExpandResult_ZERO_EXTEND(SDNode *N,
696                                                 SDOperand &Lo, SDOperand &Hi) {
697   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
698   // The low part is zero extension of the input (which degenerates to a copy).
699   Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, N->getOperand(0));
700   Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
701 }
702
703 void DAGTypeLegalizer::ExpandResult_SIGN_EXTEND(SDNode *N,
704                                                 SDOperand &Lo, SDOperand &Hi) {
705   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
706   // The low part is sign extension of the input (which degenerates to a copy).
707   Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, N->getOperand(0));
708
709   // The high part is obtained by SRA'ing all but one of the bits of low part.
710   unsigned LoSize = MVT::getSizeInBits(NVT);
711   Hi = DAG.getNode(ISD::SRA, NVT, Lo,
712                    DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
713 }
714
715 void DAGTypeLegalizer::ExpandResult_BIT_CONVERT(SDNode *N,
716                                                 SDOperand &Lo, SDOperand &Hi) {
717   // Lower the bit-convert to a store/load from the stack, then expand the load.
718   SDOperand Op = CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
719   ExpandResult_LOAD(cast<LoadSDNode>(Op.Val), Lo, Hi);
720 }
721
722 void DAGTypeLegalizer::ExpandResult_LOAD(LoadSDNode *N,
723                                          SDOperand &Lo, SDOperand &Hi) {
724   MVT::ValueType VT = N->getValueType(0);
725   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
726   SDOperand Ch  = N->getChain();    // Legalize the chain.
727   SDOperand Ptr = N->getBasePtr();  // Legalize the pointer.
728   ISD::LoadExtType ExtType = N->getExtensionType();
729   int SVOffset = N->getSrcValueOffset();
730   unsigned Alignment = N->getAlignment();
731   bool isVolatile = N->isVolatile();
732   
733   if (ExtType == ISD::NON_EXTLOAD) {
734     Lo = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(), SVOffset,
735                      isVolatile, Alignment);
736     // Increment the pointer to the other half.
737     unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
738     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
739                       getIntPtrConstant(IncrementSize));
740     Hi = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(), SVOffset+IncrementSize,
741                      isVolatile, std::max(Alignment, IncrementSize));
742     
743     // Build a factor node to remember that this load is independent of the
744     // other one.
745     Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
746                      Hi.getValue(1));
747
748     // Handle endianness of the load.
749     if (!TLI.isLittleEndian())
750       std::swap(Lo, Hi);
751   } else {
752     MVT::ValueType EVT = N->getLoadedVT();
753     
754     if (EVT == NVT)
755       Lo = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(),
756                        SVOffset, isVolatile, Alignment);
757     else
758       Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, N->getSrcValue(),
759                           SVOffset, EVT, isVolatile,
760                           Alignment);
761     // Remember the chain.
762     Ch = Lo.getValue(1);
763     
764     if (ExtType == ISD::SEXTLOAD) {
765       // The high part is obtained by SRA'ing all but one of the bits of the
766       // lo part.
767       unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
768       Hi = DAG.getNode(ISD::SRA, NVT, Lo,
769                        DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
770     } else if (ExtType == ISD::ZEXTLOAD) {
771       // The high part is just a zero.
772       Hi = DAG.getConstant(0, NVT);
773     } else {
774       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
775       // The high part is undefined.
776       Hi = DAG.getNode(ISD::UNDEF, NVT);
777     }
778   }
779   
780   // Legalized the chain result - switch anything that used the old chain to
781   // use the new one.
782   ReplaceLegalValueWith(SDOperand(N, 1), Ch);
783 }  
784
785
786 void DAGTypeLegalizer::ExpandResult_Logical(SDNode *N,
787                                             SDOperand &Lo, SDOperand &Hi) {
788   SDOperand LL, LH, RL, RH;
789   GetExpandedOp(N->getOperand(0), LL, LH);
790   GetExpandedOp(N->getOperand(1), RL, RH);
791   Lo = DAG.getNode(N->getOpcode(), LL.getValueType(), LL, RL);
792   Hi = DAG.getNode(N->getOpcode(), LL.getValueType(), LH, RH);
793 }
794
795 void DAGTypeLegalizer::ExpandResult_SELECT(SDNode *N,
796                                            SDOperand &Lo, SDOperand &Hi) {
797   SDOperand LL, LH, RL, RH;
798   GetExpandedOp(N->getOperand(1), LL, LH);
799   GetExpandedOp(N->getOperand(2), RL, RH);
800   Lo = DAG.getNode(ISD::SELECT, LL.getValueType(), N->getOperand(0), LL, RL);
801   
802   assert(N->getOperand(0).getValueType() != MVT::f32 &&
803          "FIXME: softfp shouldn't use expand!");
804   Hi = DAG.getNode(ISD::SELECT, LL.getValueType(), N->getOperand(0), LH, RH);
805 }
806
807 void DAGTypeLegalizer::ExpandResult_SELECT_CC(SDNode *N,
808                                               SDOperand &Lo, SDOperand &Hi) {
809   SDOperand LL, LH, RL, RH;
810   GetExpandedOp(N->getOperand(2), LL, LH);
811   GetExpandedOp(N->getOperand(3), RL, RH);
812   Lo = DAG.getNode(ISD::SELECT_CC, LL.getValueType(), N->getOperand(0), 
813                    N->getOperand(1), LL, RL, N->getOperand(4));
814   
815   assert(N->getOperand(0).getValueType() != MVT::f32 &&
816          "FIXME: softfp shouldn't use expand!");
817   Hi = DAG.getNode(ISD::SELECT_CC, LL.getValueType(), N->getOperand(0), 
818                    N->getOperand(1), LH, RH, N->getOperand(4));
819 }
820
821 void DAGTypeLegalizer::ExpandResult_ADDSUB(SDNode *N,
822                                            SDOperand &Lo, SDOperand &Hi) {
823   MVT::ValueType VT = N->getValueType(0);
824   
825   // If the target wants to custom expand this, let them.
826   if (TLI.getOperationAction(N->getOpcode(), VT) ==
827       TargetLowering::Custom) {
828     std::pair<SDOperand,SDOperand> Ret = 
829       TLI.ExpandOperation(SDOperand(N, 0), DAG);
830     if (Ret.first.Val) {
831       Lo = Ret.first;
832       Hi = Ret.second;
833       return;
834     }
835   }
836   
837   // Expand the subcomponents.
838   SDOperand LHSL, LHSH, RHSL, RHSH;
839   GetExpandedOp(N->getOperand(0), LHSL, LHSH);
840   GetExpandedOp(N->getOperand(1), RHSL, RHSH);
841   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
842   SDOperand LoOps[2] = { LHSL, RHSL };
843   SDOperand HiOps[3] = { LHSH, RHSH };
844
845   if (N->getOpcode() == ISD::ADD) {
846     Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
847     HiOps[2] = Lo.getValue(1);
848     Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
849   } else {
850     Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
851     HiOps[2] = Lo.getValue(1);
852     Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
853   }
854 }
855
856 void DAGTypeLegalizer::ExpandResult_ADDSUBC(SDNode *N,
857                                             SDOperand &Lo, SDOperand &Hi) {
858   // Expand the subcomponents.
859   SDOperand LHSL, LHSH, RHSL, RHSH;
860   GetExpandedOp(N->getOperand(0), LHSL, LHSH);
861   GetExpandedOp(N->getOperand(1), RHSL, RHSH);
862   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
863   SDOperand LoOps[2] = { LHSL, RHSL };
864   SDOperand HiOps[3] = { LHSH, RHSH };
865
866   if (N->getOpcode() == ISD::ADDC) {
867     Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
868     HiOps[2] = Lo.getValue(1);
869     Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
870   } else {
871     Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
872     HiOps[2] = Lo.getValue(1);
873     Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
874   }
875
876   // Legalized the flag result - switch anything that used the old flag to
877   // use the new one.
878   ReplaceLegalValueWith(SDOperand(N, 1), Hi.getValue(1));
879 }
880
881 void DAGTypeLegalizer::ExpandResult_MUL(SDNode *N,
882                                         SDOperand &Lo, SDOperand &Hi) {
883   MVT::ValueType VT = N->getValueType(0);
884   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
885   
886   bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
887   bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
888   bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, NVT);
889   bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, NVT);
890   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
891     SDOperand LL, LH, RL, RH;
892     GetExpandedOp(N->getOperand(0), LL, LH);
893     GetExpandedOp(N->getOperand(1), RL, RH);
894     unsigned BitSize = MVT::getSizeInBits(RH.getValueType());
895     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
896     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
897     
898     // FIXME: generalize this to handle other bit sizes
899     if (LHSSB == 32 && RHSSB == 32 &&
900         DAG.MaskedValueIsZero(N->getOperand(0), 0xFFFFFFFF00000000ULL) &&
901         DAG.MaskedValueIsZero(N->getOperand(1), 0xFFFFFFFF00000000ULL)) {
902       // The inputs are both zero-extended.
903       if (HasUMUL_LOHI) {
904         // We can emit a umul_lohi.
905         Lo = DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
906         Hi = SDOperand(Lo.Val, 1);
907         return;
908       }
909       if (HasMULHU) {
910         // We can emit a mulhu+mul.
911         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
912         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
913         return;
914       }
915     }
916     if (LHSSB > BitSize && RHSSB > BitSize) {
917       // The input values are both sign-extended.
918       if (HasSMUL_LOHI) {
919         // We can emit a smul_lohi.
920         Lo = DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
921         Hi = SDOperand(Lo.Val, 1);
922         return;
923       }
924       if (HasMULHS) {
925         // We can emit a mulhs+mul.
926         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
927         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
928         return;
929       }
930     }
931     if (HasUMUL_LOHI) {
932       // Lo,Hi = umul LHS, RHS.
933       SDOperand UMulLOHI = DAG.getNode(ISD::UMUL_LOHI,
934                                        DAG.getVTList(NVT, NVT), LL, RL);
935       Lo = UMulLOHI;
936       Hi = UMulLOHI.getValue(1);
937       RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
938       LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
939       Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
940       Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
941       return;
942     }
943   }
944   
945   abort();
946 #if 0 // FIXME!
947   // If nothing else, we can make a libcall.
948   Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::MUL_I64), N,
949                      false/*sign irrelevant*/, Hi);
950 #endif
951 }  
952
953
954 void DAGTypeLegalizer::ExpandResult_Shift(SDNode *N,
955                                           SDOperand &Lo, SDOperand &Hi) {
956   MVT::ValueType VT = N->getValueType(0);
957   
958   // If we can emit an efficient shift operation, do so now.  Check to see if 
959   // the RHS is a constant.
960   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
961     return ExpandShiftByConstant(N, CN->getValue(), Lo, Hi);
962
963   // If we can determine that the high bit of the shift is zero or one, even if
964   // the low bits are variable, emit this shift in an optimized form.
965   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
966     return;
967   
968   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
969   unsigned PartsOpc;
970   if (N->getOpcode() == ISD::SHL)
971     PartsOpc = ISD::SHL_PARTS;
972   else if (N->getOpcode() == ISD::SRL)
973     PartsOpc = ISD::SRL_PARTS;
974   else {
975     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
976     PartsOpc = ISD::SRA_PARTS;
977   }
978   
979   // Next check to see if the target supports this SHL_PARTS operation or if it
980   // will custom expand it.
981   MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
982   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
983   if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
984       Action == TargetLowering::Custom) {
985     // Expand the subcomponents.
986     SDOperand LHSL, LHSH;
987     GetExpandedOp(N->getOperand(0), LHSL, LHSH);
988     
989     SDOperand Ops[] = { LHSL, LHSH, N->getOperand(1) };
990     MVT::ValueType VT = LHSL.getValueType();
991     Lo = DAG.getNode(PartsOpc, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
992     Hi = Lo.getValue(1);
993     return;
994   }
995   
996   abort();
997 #if 0 // FIXME!
998   // Otherwise, emit a libcall.
999   unsigned RuntimeCode = ; // SRL -> SRL_I64 etc.
1000   bool Signed = ;
1001   Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SRL_I64), N,
1002                      false/*lshr is unsigned*/, Hi);
1003 #endif
1004 }  
1005
1006
1007 /// ExpandShiftByConstant - N is a shift by a value that needs to be expanded,
1008 /// and the shift amount is a constant 'Amt'.  Expand the operation.
1009 void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, unsigned Amt, 
1010                                              SDOperand &Lo, SDOperand &Hi) {
1011   // Expand the incoming operand to be shifted, so that we have its parts
1012   SDOperand InL, InH;
1013   GetExpandedOp(N->getOperand(0), InL, InH);
1014   
1015   MVT::ValueType NVT = InL.getValueType();
1016   unsigned VTBits = MVT::getSizeInBits(N->getValueType(0));
1017   unsigned NVTBits = MVT::getSizeInBits(NVT);
1018   MVT::ValueType ShTy = N->getOperand(1).getValueType();
1019
1020   if (N->getOpcode() == ISD::SHL) {
1021     if (Amt > VTBits) {
1022       Lo = Hi = DAG.getConstant(0, NVT);
1023     } else if (Amt > NVTBits) {
1024       Lo = DAG.getConstant(0, NVT);
1025       Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Amt-NVTBits,ShTy));
1026     } else if (Amt == NVTBits) {
1027       Lo = DAG.getConstant(0, NVT);
1028       Hi = InL;
1029     } else {
1030       Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Amt, ShTy));
1031       Hi = DAG.getNode(ISD::OR, NVT,
1032                        DAG.getNode(ISD::SHL, NVT, InH,
1033                                    DAG.getConstant(Amt, ShTy)),
1034                        DAG.getNode(ISD::SRL, NVT, InL,
1035                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1036     }
1037     return;
1038   }
1039   
1040   if (N->getOpcode() == ISD::SRL) {
1041     if (Amt > VTBits) {
1042       Lo = DAG.getConstant(0, NVT);
1043       Hi = DAG.getConstant(0, NVT);
1044     } else if (Amt > NVTBits) {
1045       Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1046       Hi = DAG.getConstant(0, NVT);
1047     } else if (Amt == NVTBits) {
1048       Lo = InH;
1049       Hi = DAG.getConstant(0, NVT);
1050     } else {
1051       Lo = DAG.getNode(ISD::OR, NVT,
1052                        DAG.getNode(ISD::SRL, NVT, InL,
1053                                    DAG.getConstant(Amt, ShTy)),
1054                        DAG.getNode(ISD::SHL, NVT, InH,
1055                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1056       Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Amt, ShTy));
1057     }
1058     return;
1059   }
1060   
1061   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1062   if (Amt > VTBits) {
1063     Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
1064                           DAG.getConstant(NVTBits-1, ShTy));
1065   } else if (Amt > NVTBits) {
1066     Lo = DAG.getNode(ISD::SRA, NVT, InH,
1067                      DAG.getConstant(Amt-NVTBits, ShTy));
1068     Hi = DAG.getNode(ISD::SRA, NVT, InH,
1069                      DAG.getConstant(NVTBits-1, ShTy));
1070   } else if (Amt == NVTBits) {
1071     Lo = InH;
1072     Hi = DAG.getNode(ISD::SRA, NVT, InH,
1073                      DAG.getConstant(NVTBits-1, ShTy));
1074   } else {
1075     Lo = DAG.getNode(ISD::OR, NVT,
1076                      DAG.getNode(ISD::SRL, NVT, InL,
1077                                  DAG.getConstant(Amt, ShTy)),
1078                      DAG.getNode(ISD::SHL, NVT, InH,
1079                                  DAG.getConstant(NVTBits-Amt, ShTy)));
1080     Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Amt, ShTy));
1081   }
1082 }
1083
1084 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1085 /// this shift based on knowledge of the high bit of the shift amount.  If we
1086 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1087 /// shift amount.
1088 bool DAGTypeLegalizer::
1089 ExpandShiftWithKnownAmountBit(SDNode *N, SDOperand &Lo, SDOperand &Hi) {
1090   MVT::ValueType NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1091   unsigned NVTBits = MVT::getSizeInBits(NVT);
1092
1093   uint64_t HighBitMask = NVTBits, KnownZero, KnownOne;
1094   DAG.ComputeMaskedBits(N->getOperand(1), HighBitMask, KnownZero, KnownOne);
1095   
1096   // If we don't know anything about the high bit, exit.
1097   if (((KnownZero|KnownOne) & HighBitMask) == 0)
1098     return false;
1099
1100   // Get the incoming operand to be shifted.
1101   SDOperand InL, InH;
1102   GetExpandedOp(N->getOperand(0), InL, InH);
1103   SDOperand Amt = N->getOperand(1);
1104
1105   // If we know that the high bit of the shift amount is one, then we can do
1106   // this as a couple of simple shifts.
1107   if (KnownOne & HighBitMask) {
1108     // Mask out the high bit, which we know is set.
1109     Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
1110                       DAG.getConstant(NVTBits-1, Amt.getValueType()));
1111     
1112     switch (N->getOpcode()) {
1113     default: assert(0 && "Unknown shift");
1114     case ISD::SHL:
1115       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1116       Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
1117       return true;
1118     case ISD::SRL:
1119       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1120       Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
1121       return true;
1122     case ISD::SRA:
1123       Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
1124                        DAG.getConstant(NVTBits-1, Amt.getValueType()));
1125       Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
1126       return true;
1127     }
1128   }
1129   
1130   // If we know that the high bit of the shift amount is zero, then we can do
1131   // this as a couple of simple shifts.
1132   assert((KnownZero & HighBitMask) && "Bad mask computation above");
1133
1134   // Compute 32-amt.
1135   SDOperand Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
1136                                DAG.getConstant(NVTBits, Amt.getValueType()),
1137                                Amt);
1138   unsigned Op1, Op2;
1139   switch (N->getOpcode()) {
1140   default: assert(0 && "Unknown shift");
1141   case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1142   case ISD::SRL:
1143   case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1144   }
1145     
1146   Lo = DAG.getNode(N->getOpcode(), NVT, InL, Amt);
1147   Hi = DAG.getNode(ISD::OR, NVT,
1148                    DAG.getNode(Op1, NVT, InH, Amt),
1149                    DAG.getNode(Op2, NVT, InL, Amt2));
1150   return true;
1151 }
1152
1153 //===----------------------------------------------------------------------===//
1154 //  Operand Promotion
1155 //===----------------------------------------------------------------------===//
1156
1157 /// PromoteOperand - This method is called when the specified operand of the
1158 /// specified node is found to need promotion.  At this point, all of the result
1159 /// types of the node are known to be legal, but other operands of the node may
1160 /// need promotion or expansion as well as the specified one.
1161 bool DAGTypeLegalizer::PromoteOperand(SDNode *N, unsigned OpNo) {
1162   DEBUG(cerr << "Promote node operand: "; N->dump(&DAG); cerr << "\n");
1163   SDOperand Res;
1164   switch (N->getOpcode()) {
1165     default:
1166 #ifndef NDEBUG
1167     cerr << "PromoteOperand Op #" << OpNo << ": ";
1168     N->dump(&DAG); cerr << "\n";
1169 #endif
1170     assert(0 && "Do not know how to promote this operator's operand!");
1171     abort();
1172     
1173   case ISD::ANY_EXTEND:  Res = PromoteOperand_ANY_EXTEND(N); break;
1174   case ISD::ZERO_EXTEND: Res = PromoteOperand_ZERO_EXTEND(N); break;
1175   case ISD::SIGN_EXTEND: Res = PromoteOperand_SIGN_EXTEND(N); break;
1176   case ISD::FP_EXTEND:   Res = PromoteOperand_FP_EXTEND(N); break;
1177   case ISD::FP_ROUND:    Res = PromoteOperand_FP_ROUND(N); break;
1178     
1179   case ISD::SELECT:      Res = PromoteOperand_SELECT(N, OpNo); break;
1180   case ISD::BRCOND:      Res = PromoteOperand_BRCOND(N, OpNo); break;
1181   case ISD::BR_CC:       Res = PromoteOperand_BR_CC(N, OpNo); break;
1182
1183   case ISD::STORE:       Res = PromoteOperand_STORE(cast<StoreSDNode>(N),
1184                                                     OpNo); break;
1185   }
1186   
1187   // If the result is null, the sub-method took care of registering results etc.
1188   if (!Res.Val) return false;
1189   // If the result is N, the sub-method updated N in place.
1190   if (Res.Val == N) {
1191     // Mark N as new and remark N and its operands.  This allows us to correctly
1192     // revisit N if it needs another step of promotion and allows us to visit
1193     // any new operands to N.
1194     N->setNodeId(NewNode);
1195     MarkNewNodes(N);
1196     return true;
1197   }
1198   
1199   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1200          "Invalid operand expansion");
1201   
1202   ReplaceLegalValueWith(SDOperand(N, 0), Res);
1203   return false;
1204 }
1205
1206 SDOperand DAGTypeLegalizer::PromoteOperand_ANY_EXTEND(SDNode *N) {
1207   SDOperand Op = GetPromotedOp(N->getOperand(0));
1208   return DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
1209 }
1210
1211 SDOperand DAGTypeLegalizer::PromoteOperand_ZERO_EXTEND(SDNode *N) {
1212   SDOperand Op = GetPromotedOp(N->getOperand(0));
1213   Op = DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
1214   return DAG.getZeroExtendInReg(Op, N->getOperand(0).getValueType());
1215 }
1216
1217 SDOperand DAGTypeLegalizer::PromoteOperand_SIGN_EXTEND(SDNode *N) {
1218   SDOperand Op = GetPromotedOp(N->getOperand(0));
1219   Op = DAG.getNode(ISD::ANY_EXTEND, N->getValueType(0), Op);
1220   return DAG.getNode(ISD::SIGN_EXTEND_INREG, Op.getValueType(),
1221                      Op, DAG.getValueType(N->getOperand(0).getValueType()));
1222 }
1223
1224 SDOperand DAGTypeLegalizer::PromoteOperand_FP_EXTEND(SDNode *N) {
1225   SDOperand Op = GetPromotedOp(N->getOperand(0));
1226   return DAG.getNode(ISD::FP_EXTEND, N->getValueType(0), Op);
1227 }
1228 SDOperand DAGTypeLegalizer::PromoteOperand_FP_ROUND(SDNode *N) {
1229   SDOperand Op = GetPromotedOp(N->getOperand(0));
1230   return DAG.getNode(ISD::FP_ROUND, N->getValueType(0), Op);
1231 }
1232
1233
1234 SDOperand DAGTypeLegalizer::PromoteOperand_SELECT(SDNode *N, unsigned OpNo) {
1235   assert(OpNo == 0 && "Only know how to promote condition");
1236   SDOperand Cond = GetPromotedOp(N->getOperand(0));  // Promote the condition.
1237
1238   // The top bits of the promoted condition are not necessarily zero, ensure
1239   // that the value is properly zero extended.
1240   if (!DAG.MaskedValueIsZero(Cond, 
1241                              MVT::getIntVTBitMask(Cond.getValueType())^1)) {
1242     Cond = DAG.getZeroExtendInReg(Cond, MVT::i1);
1243     MarkNewNodes(Cond.Val); 
1244   }
1245
1246   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
1247   return DAG.UpdateNodeOperands(SDOperand(N, 0), Cond, N->getOperand(1),
1248                                 N->getOperand(2));
1249 }
1250
1251
1252 SDOperand DAGTypeLegalizer::PromoteOperand_BRCOND(SDNode *N, unsigned OpNo) {
1253   assert(OpNo == 1 && "only know how to promote condition");
1254   SDOperand Cond = GetPromotedOp(N->getOperand(1));  // Promote the condition.
1255   
1256   // The top bits of the promoted condition are not necessarily zero, ensure
1257   // that the value is properly zero extended.
1258   if (!DAG.MaskedValueIsZero(Cond, 
1259                              MVT::getIntVTBitMask(Cond.getValueType())^1)) {
1260     Cond = DAG.getZeroExtendInReg(Cond, MVT::i1);
1261     MarkNewNodes(Cond.Val); 
1262   }
1263   
1264   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
1265   return DAG.UpdateNodeOperands(SDOperand(N, 0), N->getOperand(0), Cond,
1266                                 N->getOperand(2));
1267 }
1268
1269 SDOperand DAGTypeLegalizer::PromoteOperand_BR_CC(SDNode *N, unsigned OpNo) {
1270   assert(OpNo == 2 && "Don't know how to promote this operand");
1271   
1272   SDOperand LHS = N->getOperand(2);
1273   SDOperand RHS = N->getOperand(3);
1274   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
1275   
1276   // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
1277   // legal types.
1278   return DAG.UpdateNodeOperands(SDOperand(N, 0), N->getOperand(0),
1279                                 N->getOperand(1), LHS, RHS, N->getOperand(4));
1280 }
1281
1282 /// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
1283 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
1284 void DAGTypeLegalizer::PromoteSetCCOperands(SDOperand &NewLHS,SDOperand &NewRHS,
1285                                             ISD::CondCode CCCode) {
1286   MVT::ValueType VT = NewLHS.getValueType();
1287   
1288   // Get the promoted values.
1289   NewLHS = GetPromotedOp(NewLHS);
1290   NewRHS = GetPromotedOp(NewRHS);
1291   
1292   // If this is an FP compare, the operands have already been extended.
1293   if (!MVT::isInteger(NewLHS.getValueType()))
1294     return;
1295   
1296   // Otherwise, we have to insert explicit sign or zero extends.  Note
1297   // that we could insert sign extends for ALL conditions, but zero extend
1298   // is cheaper on many machines (an AND instead of two shifts), so prefer
1299   // it.
1300   switch (CCCode) {
1301   default: assert(0 && "Unknown integer comparison!");
1302   case ISD::SETEQ:
1303   case ISD::SETNE:
1304   case ISD::SETUGE:
1305   case ISD::SETUGT:
1306   case ISD::SETULE:
1307   case ISD::SETULT:
1308     // ALL of these operations will work if we either sign or zero extend
1309     // the operands (including the unsigned comparisons!).  Zero extend is
1310     // usually a simpler/cheaper operation, so prefer it.
1311     NewLHS = DAG.getZeroExtendInReg(NewLHS, VT);
1312     NewRHS = DAG.getZeroExtendInReg(NewRHS, VT);
1313     return;
1314   case ISD::SETGE:
1315   case ISD::SETGT:
1316   case ISD::SETLT:
1317   case ISD::SETLE:
1318     NewLHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, NewLHS.getValueType(), NewLHS,
1319                          DAG.getValueType(VT));
1320     NewRHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, NewRHS.getValueType(), NewRHS,
1321                          DAG.getValueType(VT));
1322     return;
1323   }
1324 }
1325   
1326
1327 SDOperand DAGTypeLegalizer::PromoteOperand_STORE(StoreSDNode *N, unsigned OpNo){
1328   SDOperand Ch = N->getChain(), Ptr = N->getBasePtr();
1329   int SVOffset = N->getSrcValueOffset();
1330   unsigned Alignment = N->getAlignment();
1331   bool isVolatile = N->isVolatile();
1332   
1333   SDOperand Val = GetPromotedOp(N->getValue());  // Get promoted value.
1334
1335   assert(!N->isTruncatingStore() && "Cannot promote this store operand!");
1336   
1337   // Truncate the value and store the result.
1338   return DAG.getTruncStore(Ch, Val, Ptr, N->getSrcValue(),
1339                            SVOffset, N->getStoredVT(),
1340                            isVolatile, Alignment);
1341 }
1342
1343
1344 //===----------------------------------------------------------------------===//
1345 //  Operand Expansion
1346 //===----------------------------------------------------------------------===//
1347
1348 /// ExpandOperand - This method is called when the specified operand of the
1349 /// specified node is found to need expansion.  At this point, all of the result
1350 /// types of the node are known to be legal, but other operands of the node may
1351 /// need promotion or expansion as well as the specified one.
1352 bool DAGTypeLegalizer::ExpandOperand(SDNode *N, unsigned OpNo) {
1353   DEBUG(cerr << "Expand node operand: "; N->dump(&DAG); cerr << "\n");
1354   SDOperand Res;
1355   switch (N->getOpcode()) {
1356   default:
1357 #ifndef NDEBUG
1358     cerr << "ExpandOperand Op #" << OpNo << ": ";
1359     N->dump(&DAG); cerr << "\n";
1360 #endif
1361     assert(0 && "Do not know how to expand this operator's operand!");
1362     abort();
1363     
1364   case ISD::TRUNCATE:        Res = ExpandOperand_TRUNCATE(N); break;
1365   case ISD::SINT_TO_FP:
1366     Res = ExpandOperand_SINT_TO_FP(N->getOperand(0), N->getValueType(0));
1367     break;
1368   case ISD::UINT_TO_FP:
1369     Res = ExpandOperand_UINT_TO_FP(N->getOperand(0), N->getValueType(0)); 
1370     break;
1371   case ISD::EXTRACT_ELEMENT: Res = ExpandOperand_EXTRACT_ELEMENT(N); break;
1372   case ISD::SETCC:           Res = ExpandOperand_SETCC(N); break;
1373
1374   case ISD::STORE: Res = ExpandOperand_STORE(cast<StoreSDNode>(N), OpNo); break;
1375   }
1376   
1377   // If the result is null, the sub-method took care of registering results etc.
1378   if (!Res.Val) return false;
1379   // If the result is N, the sub-method updated N in place.  Check to see if any
1380   // operands are new, and if so, mark them.
1381   if (Res.Val == N) {
1382     // Mark N as new and remark N and its operands.  This allows us to correctly
1383     // revisit N if it needs another step of promotion and allows us to visit
1384     // any new operands to N.
1385     N->setNodeId(NewNode);
1386     MarkNewNodes(N);
1387     return true;
1388   }
1389
1390   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1391          "Invalid operand expansion");
1392   
1393   ReplaceLegalValueWith(SDOperand(N, 0), Res);
1394   return false;
1395 }
1396
1397 SDOperand DAGTypeLegalizer::ExpandOperand_TRUNCATE(SDNode *N) {
1398   SDOperand InL, InH;
1399   GetExpandedOp(N->getOperand(0), InL, InH);
1400   // Just truncate the low part of the source.
1401   return DAG.getNode(ISD::TRUNCATE, N->getValueType(0), InL);
1402 }
1403
1404 SDOperand DAGTypeLegalizer::ExpandOperand_SINT_TO_FP(SDOperand Source, 
1405                                                      MVT::ValueType DestTy) {
1406   // We know the destination is legal, but that the input needs to be expanded.
1407   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1408   
1409   // Check to see if the target has a custom way to lower this.  If so, use it.
1410   switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
1411   default: assert(0 && "This action not implemented for this operation!");
1412   case TargetLowering::Legal:
1413   case TargetLowering::Expand:
1414     break;   // This case is handled below.
1415   case TargetLowering::Custom:
1416     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
1417                                                   Source), DAG);
1418     if (NV.Val) return NV;
1419     break;   // The target lowered this.
1420   }
1421   
1422   RTLIB::Libcall LC;
1423   if (DestTy == MVT::f32)
1424     LC = RTLIB::SINTTOFP_I64_F32;
1425   else {
1426     assert(DestTy == MVT::f64 && "Unknown fp value type!");
1427     LC = RTLIB::SINTTOFP_I64_F64;
1428   }
1429   
1430   assert(0 && "FIXME: no libcalls yet!");
1431   abort();
1432 #if 0
1433   assert(TLI.getLibcallName(LC) && "Don't know how to expand this SINT_TO_FP!");
1434   Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
1435   SDOperand UnusedHiPart;
1436   return ExpandLibCall(TLI.getLibcallName(LC), Source.Val, true, UnusedHiPart);
1437 #endif
1438 }
1439
1440 SDOperand DAGTypeLegalizer::ExpandOperand_UINT_TO_FP(SDOperand Source, 
1441                                                      MVT::ValueType DestTy) {
1442   // We know the destination is legal, but that the input needs to be expanded.
1443   assert(getTypeAction(Source.getValueType()) == Expand &&
1444          "This is not an expansion!");
1445   assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1446   
1447   // If this is unsigned, and not supported, first perform the conversion to
1448   // signed, then adjust the result if the sign bit is set.
1449   SDOperand SignedConv = ExpandOperand_SINT_TO_FP(Source, DestTy);
1450
1451   // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
1452   // incoming integer is set.  To handle this, we dynamically test to see if
1453   // it is set, and, if so, add a fudge factor.
1454   SDOperand Lo, Hi;
1455   GetExpandedOp(Source, Lo, Hi);
1456   
1457   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
1458                                    DAG.getConstant(0, Hi.getValueType()),
1459                                    ISD::SETLT);
1460   SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
1461   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
1462                                     SignSet, Four, Zero);
1463   uint64_t FF = 0x5f800000ULL;
1464   if (TLI.isLittleEndian()) FF <<= 32;
1465   Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
1466   
1467   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
1468   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
1469   SDOperand FudgeInReg;
1470   if (DestTy == MVT::f32)
1471     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx, NULL, 0);
1472   else if (MVT::getSizeInBits(DestTy) > MVT::getSizeInBits(MVT::f32))
1473     // FIXME: Avoid the extend by construction the right constantpool?
1474     FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, DestTy, DAG.getEntryNode(),
1475                                 CPIdx, NULL, 0, MVT::f32);
1476   else 
1477     assert(0 && "Unexpected conversion");
1478   
1479   return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
1480 }
1481
1482
1483 SDOperand DAGTypeLegalizer::ExpandOperand_EXTRACT_ELEMENT(SDNode *N) {
1484   SDOperand Lo, Hi;
1485   GetExpandedOp(N->getOperand(0), Lo, Hi);
1486   return cast<ConstantSDNode>(N->getOperand(1))->getValue() ? Hi : Lo;
1487 }
1488
1489 SDOperand DAGTypeLegalizer::ExpandOperand_SETCC(SDNode *N) {
1490   SDOperand NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
1491   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
1492   ExpandSetCCOperands(NewLHS, NewRHS, CCCode);
1493   
1494   // If ExpandSetCCOperands returned a scalar, use it.
1495   if (NewRHS.Val == 0) return NewLHS;
1496
1497   // Otherwise, update N to have the operands specified.
1498   return DAG.UpdateNodeOperands(SDOperand(N, 0), NewLHS, NewRHS,
1499                                 DAG.getCondCode(CCCode));
1500 }
1501
1502 /// ExpandSetCCOperands - Expand the operands of a comparison.  This code is
1503 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
1504 void DAGTypeLegalizer::ExpandSetCCOperands(SDOperand &NewLHS, SDOperand &NewRHS,
1505                                            ISD::CondCode &CCCode) {
1506   SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
1507   GetExpandedOp(NewLHS, LHSLo, LHSHi);
1508   GetExpandedOp(NewRHS, RHSLo, RHSHi);
1509   
1510   MVT::ValueType VT = NewLHS.getValueType();
1511   if (VT == MVT::f32 || VT == MVT::f64) {
1512     assert(0 && "FIXME: softfp not implemented yet! should be promote not exp");
1513   }
1514   
1515   if (VT == MVT::ppcf128) {
1516     // FIXME:  This generated code sucks.  We want to generate
1517     //         FCMP crN, hi1, hi2
1518     //         BNE crN, L:
1519     //         FCMP crN, lo1, lo2
1520     // The following can be improved, but not that much.
1521     SDOperand Tmp1, Tmp2, Tmp3;
1522     Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
1523     Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, CCCode);
1524     Tmp3 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
1525     Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETNE);
1526     Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, CCCode);
1527     Tmp1 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
1528     NewLHS = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp3);
1529     NewRHS = SDOperand();   // LHS is the result, not a compare.
1530     return;
1531   }
1532   
1533   
1534   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
1535     if (RHSLo == RHSHi)
1536       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
1537         if (RHSCST->isAllOnesValue()) {
1538           // Equality comparison to -1.
1539           NewLHS = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
1540           NewRHS = RHSLo;
1541           return;
1542         }
1543           
1544     NewLHS = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
1545     NewRHS = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
1546     NewLHS = DAG.getNode(ISD::OR, NewLHS.getValueType(), NewLHS, NewRHS);
1547     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
1548     return;
1549   }
1550   
1551   // If this is a comparison of the sign bit, just look at the top part.
1552   // X > -1,  x < 0
1553   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
1554     if ((CCCode == ISD::SETLT && CST->getValue() == 0) ||   // X < 0
1555         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
1556       NewLHS = LHSHi;
1557       NewRHS = RHSHi;
1558       return;
1559     }
1560       
1561   // FIXME: This generated code sucks.
1562   ISD::CondCode LowCC;
1563   switch (CCCode) {
1564   default: assert(0 && "Unknown integer setcc!");
1565   case ISD::SETLT:
1566   case ISD::SETULT: LowCC = ISD::SETULT; break;
1567   case ISD::SETGT:
1568   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
1569   case ISD::SETLE:
1570   case ISD::SETULE: LowCC = ISD::SETULE; break;
1571   case ISD::SETGE:
1572   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
1573   }
1574   
1575   // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
1576   // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
1577   // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
1578   
1579   // NOTE: on targets without efficient SELECT of bools, we can always use
1580   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
1581   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
1582   SDOperand Tmp1, Tmp2;
1583   Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC,
1584                            false, DagCombineInfo);
1585   if (!Tmp1.Val)
1586     Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
1587   Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi,
1588                            CCCode, false, DagCombineInfo);
1589   if (!Tmp2.Val)
1590     Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi,
1591                        DAG.getCondCode(CCCode));
1592   
1593   ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.Val);
1594   ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.Val);
1595   if ((Tmp1C && Tmp1C->getValue() == 0) ||
1596       (Tmp2C && Tmp2C->getValue() == 0 &&
1597        (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
1598         CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
1599       (Tmp2C && Tmp2C->getValue() == 1 &&
1600        (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
1601         CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
1602     // low part is known false, returns high part.
1603     // For LE / GE, if high part is known false, ignore the low part.
1604     // For LT / GT, if high part is known true, ignore the low part.
1605     NewLHS = Tmp2;
1606     NewRHS = SDOperand();
1607     return;
1608   }
1609   
1610   NewLHS = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi,
1611                              ISD::SETEQ, false, DagCombineInfo);
1612   if (!NewLHS.Val)
1613     NewLHS = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
1614   NewLHS = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
1615                        NewLHS, Tmp1, Tmp2);
1616   NewRHS = SDOperand();
1617 }
1618
1619
1620 SDOperand DAGTypeLegalizer::ExpandOperand_STORE(StoreSDNode *N, unsigned OpNo) {
1621   assert(OpNo == 1 && "Can only expand the stored value so far");
1622   assert(!N->isTruncatingStore() && "Can't expand truncstore!");
1623
1624   unsigned IncrementSize = 0;
1625   SDOperand Lo, Hi;
1626   
1627   // If this is a vector type, then we have to calculate the increment as
1628   // the product of the element size in bytes, and the number of elements
1629   // in the high half of the vector.
1630   if (MVT::isVector(N->getValue().getValueType())) {
1631     assert(0 && "Vectors not supported yet");
1632 #if 0
1633     SDNode *InVal = ST->getValue().Val;
1634     unsigned NumElems = MVT::getVectorNumElements(InVal->getValueType(0));
1635     MVT::ValueType EVT = MVT::getVectorElementType(InVal->getValueType(0));
1636     
1637     // Figure out if there is a simple type corresponding to this Vector
1638     // type.  If so, convert to the vector type.
1639     MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1640     if (TLI.isTypeLegal(TVT)) {
1641       // Turn this into a normal store of the vector type.
1642       Tmp3 = LegalizeOp(Node->getOperand(1));
1643       Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1644                             SVOffset, isVolatile, Alignment);
1645       Result = LegalizeOp(Result);
1646       break;
1647     } else if (NumElems == 1) {
1648       // Turn this into a normal store of the scalar type.
1649       Tmp3 = ScalarizeVectorOp(Node->getOperand(1));
1650       Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
1651                             SVOffset, isVolatile, Alignment);
1652       // The scalarized value type may not be legal, e.g. it might require
1653       // promotion or expansion.  Relegalize the scalar store.
1654       return LegalizeOp(Result);
1655     } else {
1656       SplitVectorOp(Node->getOperand(1), Lo, Hi);
1657       IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
1658     }
1659 #endif
1660   } else {
1661     GetExpandedOp(N->getValue(), Lo, Hi);
1662     IncrementSize = Hi.Val ? MVT::getSizeInBits(Hi.getValueType())/8 : 0;
1663     
1664     if (!TLI.isLittleEndian())
1665       std::swap(Lo, Hi);
1666   }
1667   
1668   SDOperand Chain    = N->getChain();
1669   SDOperand Ptr      = N->getBasePtr();
1670   int SVOffset       = N->getSrcValueOffset();
1671   unsigned Alignment = N->getAlignment();
1672   bool isVolatile    = N->isVolatile();
1673   
1674   Lo = DAG.getStore(Chain, Lo, Ptr, N->getSrcValue(),
1675                     SVOffset, isVolatile, Alignment);
1676   
1677   assert(Hi.Val && "FIXME: int <-> float should be handled with promote!");
1678 #if 0
1679   if (Hi.Val == NULL) {
1680     // Must be int <-> float one-to-one expansion.
1681     return Lo;
1682   }
1683 #endif
1684   
1685   Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1686                     getIntPtrConstant(IncrementSize));
1687   assert(isTypeLegal(Ptr.getValueType()) && "Pointers must be legal!");
1688   Hi = DAG.getStore(Chain, Hi, Ptr, N->getSrcValue(), SVOffset+IncrementSize,
1689                     isVolatile, std::max(Alignment, IncrementSize));
1690   return DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1691 }
1692
1693 //===----------------------------------------------------------------------===//
1694 //  Entry Point
1695 //===----------------------------------------------------------------------===//
1696
1697 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
1698 /// only uses types natively supported by the target.
1699 ///
1700 /// Note that this is an involved process that may invalidate pointers into
1701 /// the graph.
1702 void SelectionDAG::LegalizeTypes() {
1703   DAGTypeLegalizer(*this).run();
1704 }
1705