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