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