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