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