If the type legalizer actually legalized anything
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeTypes.cpp
1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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.  This
12 // is common code shared among the LegalizeTypes*.cpp files.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "LegalizeTypes.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Target/TargetData.h"
20 using namespace llvm;
21
22 /// run - This is the main entry point for the type legalizer.  This does a
23 /// top-down traversal of the dag, legalizing types as it goes.  Returns "true"
24 /// if it made any changes.
25 bool DAGTypeLegalizer::run() {
26   bool Changed = false;
27
28   // Create a dummy node (which is not added to allnodes), that adds a reference
29   // to the root node, preventing it from being deleted, and tracking any
30   // changes of the root.
31   HandleSDNode Dummy(DAG.getRoot());
32
33   // The root of the dag may dangle to deleted nodes until the type legalizer is
34   // done.  Set it to null to avoid confusion.
35   DAG.setRoot(SDValue());
36
37   // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
38   // (and remembering them) if they are leaves and assigning 'NewNode' if
39   // non-leaves.
40   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
41        E = DAG.allnodes_end(); I != E; ++I) {
42     if (I->getNumOperands() == 0) {
43       I->setNodeId(ReadyToProcess);
44       Worklist.push_back(I);
45     } else {
46       I->setNodeId(NewNode);
47     }
48   }
49
50   // Now that we have a set of nodes to process, handle them all.
51   while (!Worklist.empty()) {
52     SDNode *N = Worklist.back();
53     Worklist.pop_back();
54     assert(N->getNodeId() == ReadyToProcess &&
55            "Node should be ready if on worklist!");
56
57     if (IgnoreNodeResults(N))
58       goto ScanOperands;
59
60     // Scan the values produced by the node, checking to see if any result
61     // types are illegal.
62     for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
63       MVT ResultVT = N->getValueType(i);
64       switch (getTypeAction(ResultVT)) {
65       default:
66         assert(false && "Unknown action!");
67       case Legal:
68         break;
69       case PromoteInteger:
70         PromoteIntegerResult(N, i);
71         Changed = true;
72         goto NodeDone;
73       case ExpandInteger:
74         ExpandIntegerResult(N, i);
75         Changed = true;
76         goto NodeDone;
77       case SoftenFloat:
78         SoftenFloatResult(N, i);
79         Changed = true;
80         goto NodeDone;
81       case ExpandFloat:
82         ExpandFloatResult(N, i);
83         Changed = true;
84         goto NodeDone;
85       case ScalarizeVector:
86         ScalarizeVectorResult(N, i);
87         Changed = true;
88         goto NodeDone;
89       case SplitVector:
90         SplitVectorResult(N, i);
91         Changed = true;
92         goto NodeDone;
93       }
94     }
95
96 ScanOperands:
97     // Scan the operand list for the node, handling any nodes with operands that
98     // are illegal.
99     {
100     unsigned NumOperands = N->getNumOperands();
101     bool NeedsRevisit = false;
102     unsigned i;
103     for (i = 0; i != NumOperands; ++i) {
104       if (IgnoreNodeResults(N->getOperand(i).getNode()))
105         continue;
106
107       MVT OpVT = N->getOperand(i).getValueType();
108       switch (getTypeAction(OpVT)) {
109       default:
110         assert(false && "Unknown action!");
111       case Legal:
112         continue;
113       case PromoteInteger:
114         NeedsRevisit = PromoteIntegerOperand(N, i);
115         Changed = true;
116         break;
117       case ExpandInteger:
118         NeedsRevisit = ExpandIntegerOperand(N, i);
119         Changed = true;
120         break;
121       case SoftenFloat:
122         NeedsRevisit = SoftenFloatOperand(N, i);
123         Changed = true;
124         break;
125       case ExpandFloat:
126         NeedsRevisit = ExpandFloatOperand(N, i);
127         Changed = true;
128         break;
129       case ScalarizeVector:
130         NeedsRevisit = ScalarizeVectorOperand(N, i);
131         Changed = true;
132         break;
133       case SplitVector:
134         NeedsRevisit = SplitVectorOperand(N, i);
135         Changed = true;
136         break;
137       }
138       break;
139     }
140
141     // If the node needs revisiting, don't add all users to the worklist etc.
142     if (NeedsRevisit)
143       continue;
144
145     if (i == NumOperands) {
146       DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
147     }
148     }
149 NodeDone:
150
151     // If we reach here, the node was processed, potentially creating new nodes.
152     // Mark it as processed and add its users to the worklist as appropriate.
153     N->setNodeId(Processed);
154
155     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
156          UI != E; ++UI) {
157       SDNode *User = *UI;
158       int NodeId = User->getNodeId();
159       assert(NodeId != ReadyToProcess && NodeId != Processed &&
160              "Invalid node id for user of unprocessed node!");
161
162       // This node has two options: it can either be a new node or its Node ID
163       // may be a count of the number of operands it has that are not ready.
164       if (NodeId > 0) {
165         User->setNodeId(NodeId-1);
166
167         // If this was the last use it was waiting on, add it to the ready list.
168         if (NodeId-1 == ReadyToProcess)
169           Worklist.push_back(User);
170         continue;
171       }
172
173       // Otherwise, this node is new: this is the first operand of it that
174       // became ready.  Its new NodeId is the number of operands it has minus 1
175       // (as this node is now processed).
176       assert(NodeId == NewNode && "Unknown node ID!");
177       User->setNodeId(User->getNumOperands()-1);
178
179       // If the node only has a single operand, it is now ready.
180       if (User->getNumOperands() == 1)
181         Worklist.push_back(User);
182     }
183   }
184
185   // If the root changed (e.g. it was a dead load, update the root).
186   DAG.setRoot(Dummy.getValue());
187
188   //DAG.viewGraph();
189
190   // Remove dead nodes.  This is important to do for cleanliness but also before
191   // the checking loop below.  Implicit folding by the DAG.getNode operators can
192   // cause unreachable nodes to be around with their flags set to new.
193   DAG.RemoveDeadNodes();
194
195   // In a debug build, scan all the nodes to make sure we found them all.  This
196   // ensures that there are no cycles and that everything got processed.
197 #ifndef NDEBUG
198   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
199        E = DAG.allnodes_end(); I != E; ++I) {
200     bool Failed = false;
201
202     // Check that all result types are legal.
203     if (!IgnoreNodeResults(I))
204       for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
205         if (!isTypeLegal(I->getValueType(i))) {
206           cerr << "Result type " << i << " illegal!\n";
207           Failed = true;
208         }
209
210     // Check that all operand types are legal.
211     for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
212       if (!IgnoreNodeResults(I->getOperand(i).getNode()) &&
213           !isTypeLegal(I->getOperand(i).getValueType())) {
214         cerr << "Operand type " << i << " illegal!\n";
215         Failed = true;
216       }
217
218     if (I->getNodeId() != Processed) {
219        if (I->getNodeId() == NewNode)
220          cerr << "New node not 'noticed'?\n";
221        else if (I->getNodeId() > 0)
222          cerr << "Operand not processed?\n";
223        else if (I->getNodeId() == ReadyToProcess)
224          cerr << "Not added to worklist?\n";
225        Failed = true;
226     }
227
228     if (Failed) {
229       I->dump(&DAG); cerr << "\n";
230       abort();
231     }
232   }
233 #endif
234
235   return Changed;
236 }
237
238 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
239 /// new nodes.  Correct any processed operands (this may change the node) and
240 /// calculate the NodeId.  If the node itself changes to a processed node, it
241 /// is not remapped - the caller needs to take care of this.
242 /// Returns the potentially changed node.
243 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
244   // If this was an existing node that is already done, we're done.
245   if (N->getNodeId() != NewNode)
246     return N;
247
248   // Remove any stale map entries.
249   ExpungeNode(N);
250
251   // Okay, we know that this node is new.  Recursively walk all of its operands
252   // to see if they are new also.  The depth of this walk is bounded by the size
253   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
254   // about revisiting of nodes.
255   //
256   // As we walk the operands, keep track of the number of nodes that are
257   // processed.  If non-zero, this will become the new nodeid of this node.
258   // Already processed operands may need to be remapped to the node that
259   // replaced them, which can result in our node changing.  Since remapping
260   // is rare, the code tries to minimize overhead in the non-remapping case.
261
262   SmallVector<SDValue, 8> NewOps;
263   unsigned NumProcessed = 0;
264   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
265     SDValue OrigOp = N->getOperand(i);
266     SDValue Op = OrigOp;
267
268     if (Op.getNode()->getNodeId() == Processed)
269       RemapValue(Op);
270     else if (Op.getNode()->getNodeId() == NewNode)
271       AnalyzeNewValue(Op);
272
273     if (Op.getNode()->getNodeId() == Processed)
274       ++NumProcessed;
275
276     if (!NewOps.empty()) {
277       // Some previous operand changed.  Add this one to the list.
278       NewOps.push_back(Op);
279     } else if (Op != OrigOp) {
280       // This is the first operand to change - add all operands so far.
281       for (unsigned j = 0; j < i; ++j)
282         NewOps.push_back(N->getOperand(j));
283       NewOps.push_back(Op);
284     }
285   }
286
287   // Some operands changed - update the node.
288   if (!NewOps.empty()) {
289     SDNode *M = DAG.UpdateNodeOperands(SDValue(N, 0), &NewOps[0],
290                                        NewOps.size()).getNode();
291     if (M != N) {
292       if (M->getNodeId() != NewNode)
293         // It morphed into a previously analyzed node - nothing more to do.
294         return M;
295
296       // It morphed into a different new node.  Do the equivalent of passing
297       // it to AnalyzeNewNode: expunge it and calculate the NodeId.
298       N = M;
299       ExpungeNode(N);
300     }
301   }
302
303   // Calculate the NodeId.
304   N->setNodeId(N->getNumOperands()-NumProcessed);
305   if (N->getNodeId() == ReadyToProcess)
306     Worklist.push_back(N);
307
308   return N;
309 }
310
311 /// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed.
312 /// If the node changes to a processed node, then remap it.
313 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
314   SDNode *N(Val.getNode());
315   // If this was an existing node that is already done, avoid remapping it.
316   if (N->getNodeId() != NewNode)
317     return;
318   SDNode *M(AnalyzeNewNode(N));
319   if (M != N)
320     Val.setNode(M);
321   if (M->getNodeId() == Processed)
322     // It morphed into an already processed node - remap it.
323     RemapValue(Val);
324 }
325
326
327 namespace {
328   /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
329   /// updates to nodes and recomputes their ready state.
330   class VISIBILITY_HIDDEN NodeUpdateListener :
331     public SelectionDAG::DAGUpdateListener {
332     DAGTypeLegalizer &DTL;
333   public:
334     explicit NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
335
336     virtual void NodeDeleted(SDNode *N, SDNode *E) {
337       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
338              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
339              "RAUW deleted processed node!");
340       // It is possible, though rare, for the deleted node N to occur as a
341       // target in a map, so note the replacement N -> E in ReplacedValues.
342       assert(E && "Node not replaced?");
343       DTL.NoteDeletion(N, E);
344     }
345
346     virtual void NodeUpdated(SDNode *N) {
347       // Node updates can mean pretty much anything.  It is possible that an
348       // operand was set to something already processed (f.e.) in which case
349       // this node could become ready.  Recompute its flags.
350       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
351              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
352              "RAUW updated processed node!");
353       DTL.ReanalyzeNode(N);
354     }
355   };
356 }
357
358
359 /// ReplaceValueWith - The specified value was legalized to the specified other
360 /// value.  If they are different, update the DAG and NodeIds replacing any uses
361 /// of From to use To instead.
362 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
363   if (From == To) return;
364
365   // If expansion produced new nodes, make sure they are properly marked.
366   ExpungeNode(From.getNode());
367   AnalyzeNewValue(To); // Expunges To.
368
369   // Anything that used the old node should now use the new one.  Note that this
370   // can potentially cause recursive merging.
371   NodeUpdateListener NUL(*this);
372   DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
373
374   // The old node may still be present in a map like ExpandedIntegers or
375   // PromotedIntegers.  Inform maps about the replacement.
376   ReplacedValues[From] = To;
377 }
378
379 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
380 /// node's results.  The from and to node must define identical result types.
381 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
382   if (From == To) return;
383
384   // If expansion produced new nodes, make sure they are properly marked.
385   ExpungeNode(From);
386
387   To = AnalyzeNewNode(To); // Expunges To.
388   // If To morphed into an already processed node, its values may need
389   // remapping.  This is done below.
390
391   assert(From->getNumValues() == To->getNumValues() &&
392          "Node results don't match");
393
394   // Anything that used the old node should now use the new one.  Note that this
395   // can potentially cause recursive merging.
396   NodeUpdateListener NUL(*this);
397   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
398     SDValue FromVal(From, i);
399     SDValue ToVal(To, i);
400
401     // AnalyzeNewNode may have morphed a new node into a processed node.  Remap
402     // values now.
403     if (To->getNodeId() == Processed)
404       RemapValue(ToVal);
405
406     assert(FromVal.getValueType() == ToVal.getValueType() &&
407            "Node results don't match!");
408
409     // Make anything that used the old value use the new value.
410     DAG.ReplaceAllUsesOfValueWith(FromVal, ToVal, &NUL);
411
412     // The old node may still be present in a map like ExpandedIntegers or
413     // PromotedIntegers.  Inform maps about the replacement.
414     ReplacedValues[FromVal] = ToVal;
415   }
416 }
417
418 /// RemapValue - If the specified value was already legalized to another value,
419 /// replace it by that value.
420 void DAGTypeLegalizer::RemapValue(SDValue &N) {
421   DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
422   if (I != ReplacedValues.end()) {
423     // Use path compression to speed up future lookups if values get multiply
424     // replaced with other values.
425     RemapValue(I->second);
426     N = I->second;
427   }
428   assert(N.getNode()->getNodeId() != NewNode && "Mapped to unanalyzed node!");
429 }
430
431 /// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it.
432 /// This can occur when a node is deleted then reallocated as a new node -
433 /// the mapping in ReplacedValues applies to the deleted node, not the new
434 /// one.
435 /// The only map that can have a deleted node as a source is ReplacedValues.
436 /// Other maps can have deleted nodes as targets, but since their looked-up
437 /// values are always immediately remapped using RemapValue, resulting in a
438 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
439 /// always performs correct mappings.  In order to keep the mapping correct,
440 /// ExpungeNode should be called on any new nodes *before* adding them as
441 /// either source or target to ReplacedValues (which typically means calling
442 /// Expunge when a new node is first seen, since it may no longer be marked
443 /// NewNode by the time it is added to ReplacedValues).
444 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
445   if (N->getNodeId() != NewNode)
446     return;
447
448   // If N is not remapped by ReplacedValues then there is nothing to do.
449   unsigned i, e;
450   for (i = 0, e = N->getNumValues(); i != e; ++i)
451     if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
452       break;
453
454   if (i == e)
455     return;
456
457   // Remove N from all maps - this is expensive but rare.
458
459   for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
460        E = PromotedIntegers.end(); I != E; ++I) {
461     assert(I->first.getNode() != N);
462     RemapValue(I->second);
463   }
464
465   for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
466        E = SoftenedFloats.end(); I != E; ++I) {
467     assert(I->first.getNode() != N);
468     RemapValue(I->second);
469   }
470
471   for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
472        E = ScalarizedVectors.end(); I != E; ++I) {
473     assert(I->first.getNode() != N);
474     RemapValue(I->second);
475   }
476
477   for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
478        I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
479     assert(I->first.getNode() != N);
480     RemapValue(I->second.first);
481     RemapValue(I->second.second);
482   }
483
484   for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
485        I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
486     assert(I->first.getNode() != N);
487     RemapValue(I->second.first);
488     RemapValue(I->second.second);
489   }
490
491   for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
492        I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
493     assert(I->first.getNode() != N);
494     RemapValue(I->second.first);
495     RemapValue(I->second.second);
496   }
497
498   for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
499        E = ReplacedValues.end(); I != E; ++I)
500     RemapValue(I->second);
501
502   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
503     ReplacedValues.erase(SDValue(N, i));
504 }
505
506 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
507   AnalyzeNewValue(Result);
508
509   SDValue &OpEntry = PromotedIntegers[Op];
510   assert(OpEntry.getNode() == 0 && "Node is already promoted!");
511   OpEntry = Result;
512 }
513
514 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
515   AnalyzeNewValue(Result);
516
517   SDValue &OpEntry = SoftenedFloats[Op];
518   assert(OpEntry.getNode() == 0 && "Node is already converted to integer!");
519   OpEntry = Result;
520 }
521
522 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
523   AnalyzeNewValue(Result);
524
525   SDValue &OpEntry = ScalarizedVectors[Op];
526   assert(OpEntry.getNode() == 0 && "Node is already scalarized!");
527   OpEntry = Result;
528 }
529
530 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
531                                           SDValue &Hi) {
532   std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
533   RemapValue(Entry.first);
534   RemapValue(Entry.second);
535   assert(Entry.first.getNode() && "Operand isn't expanded");
536   Lo = Entry.first;
537   Hi = Entry.second;
538 }
539
540 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
541                                           SDValue Hi) {
542   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
543   AnalyzeNewValue(Lo);
544   AnalyzeNewValue(Hi);
545
546   // Remember that this is the result of the node.
547   std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
548   assert(Entry.first.getNode() == 0 && "Node already expanded");
549   Entry.first = Lo;
550   Entry.second = Hi;
551 }
552
553 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
554                                         SDValue &Hi) {
555   std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
556   RemapValue(Entry.first);
557   RemapValue(Entry.second);
558   assert(Entry.first.getNode() && "Operand isn't expanded");
559   Lo = Entry.first;
560   Hi = Entry.second;
561 }
562
563 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
564                                         SDValue Hi) {
565   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
566   AnalyzeNewValue(Lo);
567   AnalyzeNewValue(Hi);
568
569   // Remember that this is the result of the node.
570   std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
571   assert(Entry.first.getNode() == 0 && "Node already expanded");
572   Entry.first = Lo;
573   Entry.second = Hi;
574 }
575
576 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
577                                       SDValue &Hi) {
578   std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
579   RemapValue(Entry.first);
580   RemapValue(Entry.second);
581   assert(Entry.first.getNode() && "Operand isn't split");
582   Lo = Entry.first;
583   Hi = Entry.second;
584 }
585
586 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
587                                       SDValue Hi) {
588   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
589   AnalyzeNewValue(Lo);
590   AnalyzeNewValue(Hi);
591
592   // Remember that this is the result of the node.
593   std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
594   assert(Entry.first.getNode() == 0 && "Node already split");
595   Entry.first = Lo;
596   Entry.second = Hi;
597 }
598
599
600 //===----------------------------------------------------------------------===//
601 // Utilities.
602 //===----------------------------------------------------------------------===//
603
604 /// BitConvertToInteger - Convert to an integer of the same size.
605 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
606   unsigned BitWidth = Op.getValueType().getSizeInBits();
607   return DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerVT(BitWidth), Op);
608 }
609
610 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
611                                                MVT DestVT) {
612   // Create the stack frame object.  Make sure it is aligned for both
613   // the source and destination types.
614   unsigned SrcAlign =
615    TLI.getTargetData()->getPrefTypeAlignment(Op.getValueType().getTypeForMVT());
616   SDValue FIPtr = DAG.CreateStackTemporary(DestVT, SrcAlign);
617
618   // Emit a store to the stack slot.
619   SDValue Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
620   // Result is a load from the stack slot.
621   return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
622 }
623
624 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
625 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
626   MVT LVT = Lo.getValueType();
627   MVT HVT = Hi.getValueType();
628   MVT NVT = MVT::getIntegerVT(LVT.getSizeInBits() + HVT.getSizeInBits());
629
630   Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
631   Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
632   Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(LVT.getSizeInBits(),
633                                                       TLI.getShiftAmountTy()));
634   return DAG.getNode(ISD::OR, NVT, Lo, Hi);
635 }
636
637 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
638 /// bits in Hi.
639 void DAGTypeLegalizer::SplitInteger(SDValue Op,
640                                     MVT LoVT, MVT HiVT,
641                                     SDValue &Lo, SDValue &Hi) {
642   assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
643          Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
644   Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
645   Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
646                    DAG.getConstant(LoVT.getSizeInBits(),
647                                    TLI.getShiftAmountTy()));
648   Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
649 }
650
651 /// SplitInteger - Return the lower and upper halves of Op's bits in a value
652 /// type half the size of Op's.
653 void DAGTypeLegalizer::SplitInteger(SDValue Op,
654                                     SDValue &Lo, SDValue &Hi) {
655   MVT HalfVT = MVT::getIntegerVT(Op.getValueType().getSizeInBits()/2);
656   SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
657 }
658
659 /// MakeLibCall - Generate a libcall taking the given operands as arguments and
660 /// returning a result of type RetVT.
661 SDValue DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, MVT RetVT,
662                                       const SDValue *Ops, unsigned NumOps,
663                                       bool isSigned) {
664   TargetLowering::ArgListTy Args;
665   Args.reserve(NumOps);
666
667   TargetLowering::ArgListEntry Entry;
668   for (unsigned i = 0; i != NumOps; ++i) {
669     Entry.Node = Ops[i];
670     Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
671     Entry.isSExt = isSigned;
672     Entry.isZExt = !isSigned;
673     Args.push_back(Entry);
674   }
675   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
676                                          TLI.getPointerTy());
677
678   const Type *RetTy = RetVT.getTypeForMVT();
679   std::pair<SDValue,SDValue> CallInfo =
680     TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
681                     false, CallingConv::C, false, Callee, Args, DAG);
682   return CallInfo.first;
683 }
684
685 /// LibCallify - Convert the node into a libcall with the same prototype.
686 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
687                                      bool isSigned) {
688   unsigned NumOps = N->getNumOperands();
689   if (NumOps == 0) {
690     return MakeLibCall(LC, N->getValueType(0), 0, 0, isSigned);
691   } else if (NumOps == 1) {
692     SDValue Op = N->getOperand(0);
693     return MakeLibCall(LC, N->getValueType(0), &Op, 1, isSigned);
694   } else if (NumOps == 2) {
695     SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
696     return MakeLibCall(LC, N->getValueType(0), Ops, 2, isSigned);
697   }
698   SmallVector<SDValue, 8> Ops(NumOps);
699   for (unsigned i = 0; i < NumOps; ++i)
700     Ops[i] = N->getOperand(i);
701
702   return MakeLibCall(LC, N->getValueType(0), &Ops[0], NumOps, isSigned);
703 }
704
705 SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, MVT EltVT,
706                                                   SDValue Index) {
707   // Make sure the index type is big enough to compute in.
708   if (Index.getValueType().bitsGT(TLI.getPointerTy()))
709     Index = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), Index);
710   else
711     Index = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Index);
712
713   // Calculate the element offset and add it to the pointer.
714   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
715
716   Index = DAG.getNode(ISD::MUL, Index.getValueType(), Index,
717                       DAG.getConstant(EltSize, Index.getValueType()));
718   return DAG.getNode(ISD::ADD, Index.getValueType(), Index, VecPtr);
719 }
720
721 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
722 /// which is split into two not necessarily identical pieces.
723 void DAGTypeLegalizer::GetSplitDestVTs(MVT InVT, MVT &LoVT, MVT &HiVT) {
724   if (!InVT.isVector()) {
725     LoVT = HiVT = TLI.getTypeToTransformTo(InVT);
726   } else {
727     MVT NewEltVT = InVT.getVectorElementType();
728     unsigned NumElements = InVT.getVectorNumElements();
729     if ((NumElements & (NumElements-1)) == 0) {  // Simple power of two vector.
730       NumElements >>= 1;
731       LoVT = HiVT =  MVT::getVectorVT(NewEltVT, NumElements);
732     } else {                                     // Non-power-of-two vectors.
733       unsigned NewNumElts_Lo = 1 << Log2_32(NumElements);
734       unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
735       LoVT = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
736       HiVT = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
737     }
738   }
739 }
740
741
742 //===----------------------------------------------------------------------===//
743 //  Entry Point
744 //===----------------------------------------------------------------------===//
745
746 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
747 /// only uses types natively supported by the target.  Returns "true" if it made
748 /// any changes.
749 ///
750 /// Note that this is an involved process that may invalidate pointers into
751 /// the graph.
752 bool SelectionDAG::LegalizeTypes() {
753   return DAGTypeLegalizer(*this).run();
754 }