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