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