- Use a faster priority comparison function if -fast.
[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   // Okay, we know that this node is new.  Recursively walk all of its operands
233   // to see if they are new also.  The depth of this walk is bounded by the size
234   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
235   // about revisiting of nodes.
236   //
237   // As we walk the operands, keep track of the number of nodes that are
238   // processed.  If non-zero, this will become the new nodeid of this node.
239   // Already processed operands may need to be remapped to the node that
240   // replaced them, which can result in our node changing.  Since remapping
241   // is rare, the code tries to minimize overhead in the non-remapping case.
242
243   SmallVector<SDOperand, 8> NewOps;
244   unsigned NumProcessed = 0;
245   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
246     SDOperand OrigOp = N->getOperand(i);
247     SDOperand Op = OrigOp;
248
249     if (Op.Val->getNodeId() == Processed)
250       RemapNode(Op);
251
252     if (Op.Val->getNodeId() == NewNode)
253       AnalyzeNewNode(Op.Val);
254     else if (Op.Val->getNodeId() == Processed)
255       ++NumProcessed;
256
257     if (!NewOps.empty()) {
258       // Some previous operand changed.  Add this one to the list.
259       NewOps.push_back(Op);
260     } else if (Op != OrigOp) {
261       // This is the first operand to change - add all operands so far.
262       for (unsigned j = 0; j < i; ++j)
263         NewOps.push_back(N->getOperand(j));
264       NewOps.push_back(Op);
265     }
266   }
267
268   // Some operands changed - update the node.
269   if (!NewOps.empty())
270     N = DAG.UpdateNodeOperands(SDOperand(N, 0), &NewOps[0], NewOps.size()).Val;
271
272   N->setNodeId(N->getNumOperands()-NumProcessed);
273   if (N->getNodeId() == ReadyToProcess)
274     Worklist.push_back(N);
275 }
276
277 namespace {
278   /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
279   /// updates to nodes and recomputes their ready state.
280   class VISIBILITY_HIDDEN NodeUpdateListener :
281     public SelectionDAG::DAGUpdateListener {
282     DAGTypeLegalizer &DTL;
283   public:
284     NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
285
286     virtual void NodeDeleted(SDNode *N, SDNode *E) {
287       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
288              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
289              "RAUW deleted processed node!");
290       // It is possible, though rare, for the deleted node N to occur as a
291       // target in a map, so note the replacement N -> E in ReplacedNodes.
292       assert(E && "Node not replaced?");
293       for (unsigned i = 0, e = E->getNumValues(); i != e; ++i)
294         DTL.NoteReplacement(SDOperand(N, i), SDOperand(E, i));
295     }
296
297     virtual void NodeUpdated(SDNode *N) {
298       // Node updates can mean pretty much anything.  It is possible that an
299       // operand was set to something already processed (f.e.) in which case
300       // this node could become ready.  Recompute its flags.
301       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
302              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
303              "RAUW updated processed node!");
304       DTL.ReanalyzeNode(N);
305     }
306   };
307 }
308
309
310 /// ReplaceValueWith - The specified value was legalized to the specified other
311 /// value.  If they are different, update the DAG and NodeIDs replacing any uses
312 /// of From to use To instead.
313 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
314   if (From == To) return;
315
316   // If expansion produced new nodes, make sure they are properly marked.
317   AnalyzeNewNode(To.Val);
318
319   // Anything that used the old node should now use the new one.  Note that this
320   // can potentially cause recursive merging.
321   NodeUpdateListener NUL(*this);
322   DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
323
324   // The old node may still be present in a map like ExpandedIntegers or
325   // PromotedIntegers.  Inform maps about the replacement.
326   NoteReplacement(From, To);
327 }
328
329 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
330 /// node's results.  The from and to node must define identical result types.
331 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
332   if (From == To) return;
333
334   // If expansion produced new nodes, make sure they are properly marked.
335   AnalyzeNewNode(To);
336
337   assert(From->getNumValues() == To->getNumValues() &&
338          "Node results don't match");
339
340   // Anything that used the old node should now use the new one.  Note that this
341   // can potentially cause recursive merging.
342   NodeUpdateListener NUL(*this);
343   DAG.ReplaceAllUsesWith(From, To, &NUL);
344
345   // The old node may still be present in a map like ExpandedIntegers or
346   // PromotedIntegers.  Inform maps about the replacement.
347   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
348     assert(From->getValueType(i) == To->getValueType(i) &&
349            "Node results don't match");
350     NoteReplacement(SDOperand(From, i), SDOperand(To, i));
351   }
352 }
353
354
355 /// RemapNode - If the specified value was already legalized to another value,
356 /// replace it by that value.
357 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
358   DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.find(N);
359   if (I != ReplacedNodes.end()) {
360     // Use path compression to speed up future lookups if values get multiply
361     // replaced with other values.
362     RemapNode(I->second);
363     N = I->second;
364   }
365 }
366
367 /// ExpungeNode - If this is a reincarnation of a deleted value that was kept
368 /// around to speed up remapping, remove it from all maps now.  The only map
369 /// that can have a deleted node as a source is ReplacedNodes.  Other maps can
370 /// have deleted nodes as targets, but since their looked-up values are always
371 /// immediately remapped using RemapNode, resulting in a not-deleted node, this
372 /// is harmless as long as ReplacedNodes/RemapNode always performs correct
373 /// mappings.  The mapping will always be correct as long as ExpungeNode is
374 /// called on the source when adding a new node to ReplacedNodes, and called on
375 /// the target when adding a new node to any map.
376 void DAGTypeLegalizer::ExpungeNode(SDOperand N) {
377   if (N.Val->getNodeId() != NewNode)
378     return;
379
380   SDOperand Replacement = N;
381   RemapNode(Replacement);
382   if (Replacement != N) {
383     // Remove N from all maps - this is expensive but extremely rare.
384     ReplacedNodes.erase(N);
385
386     for (DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.begin(),
387          E = ReplacedNodes.end(); I != E; ++I) {
388       if (I->second == N)
389         I->second = Replacement;
390     }
391
392     for (DenseMap<SDOperand, SDOperand>::iterator I = PromotedIntegers.begin(),
393          E = PromotedIntegers.end(); I != E; ++I) {
394       assert(I->first != N);
395       if (I->second == N)
396         I->second = Replacement;
397     }
398
399     for (DenseMap<SDOperand, SDOperand>::iterator I = SoftenedFloats.begin(),
400          E = SoftenedFloats.end(); I != E; ++I) {
401       assert(I->first != N);
402       if (I->second == N)
403         I->second = Replacement;
404     }
405
406     for (DenseMap<SDOperand, SDOperand>::iterator I = ScalarizedVectors.begin(),
407          E = ScalarizedVectors.end(); I != E; ++I) {
408       assert(I->first != N);
409       if (I->second == N)
410         I->second = Replacement;
411     }
412
413     for (DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator
414          I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
415       assert(I->first != N);
416       if (I->second.first == N)
417         I->second.first = Replacement;
418       if (I->second.second == N)
419         I->second.second = Replacement;
420     }
421
422     for (DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator
423          I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
424       assert(I->first != N);
425       if (I->second.first == N)
426         I->second.first = Replacement;
427       if (I->second.second == N)
428         I->second.second = Replacement;
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 != N);
434       if (I->second.first == N)
435         I->second.first = Replacement;
436       if (I->second.second == N)
437         I->second.second = Replacement;
438     }
439   }
440 }
441
442
443 void DAGTypeLegalizer::SetPromotedInteger(SDOperand Op, SDOperand Result) {
444   ExpungeNode(Result);
445   AnalyzeNewNode(Result.Val);
446
447   SDOperand &OpEntry = PromotedIntegers[Op];
448   assert(OpEntry.Val == 0 && "Node is already promoted!");
449   OpEntry = Result;
450 }
451
452 void DAGTypeLegalizer::SetSoftenedFloat(SDOperand Op, SDOperand Result) {
453   ExpungeNode(Result);
454   AnalyzeNewNode(Result.Val);
455
456   SDOperand &OpEntry = SoftenedFloats[Op];
457   assert(OpEntry.Val == 0 && "Node is already converted to integer!");
458   OpEntry = Result;
459 }
460
461 void DAGTypeLegalizer::SetScalarizedVector(SDOperand Op, SDOperand Result) {
462   ExpungeNode(Result);
463   AnalyzeNewNode(Result.Val);
464
465   SDOperand &OpEntry = ScalarizedVectors[Op];
466   assert(OpEntry.Val == 0 && "Node is already scalarized!");
467   OpEntry = Result;
468 }
469
470 void DAGTypeLegalizer::GetExpandedInteger(SDOperand Op, SDOperand &Lo,
471                                           SDOperand &Hi) {
472   std::pair<SDOperand, SDOperand> &Entry = ExpandedIntegers[Op];
473   RemapNode(Entry.first);
474   RemapNode(Entry.second);
475   assert(Entry.first.Val && "Operand isn't expanded");
476   Lo = Entry.first;
477   Hi = Entry.second;
478 }
479
480 void DAGTypeLegalizer::SetExpandedInteger(SDOperand Op, SDOperand Lo,
481                                           SDOperand Hi) {
482   ExpungeNode(Lo);
483   ExpungeNode(Hi);
484
485   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
486   AnalyzeNewNode(Lo.Val);
487   AnalyzeNewNode(Hi.Val);
488
489   // Remember that this is the result of the node.
490   std::pair<SDOperand, SDOperand> &Entry = ExpandedIntegers[Op];
491   assert(Entry.first.Val == 0 && "Node already expanded");
492   Entry.first = Lo;
493   Entry.second = Hi;
494 }
495
496 void DAGTypeLegalizer::GetExpandedFloat(SDOperand Op, SDOperand &Lo,
497                                         SDOperand &Hi) {
498   std::pair<SDOperand, SDOperand> &Entry = ExpandedFloats[Op];
499   RemapNode(Entry.first);
500   RemapNode(Entry.second);
501   assert(Entry.first.Val && "Operand isn't expanded");
502   Lo = Entry.first;
503   Hi = Entry.second;
504 }
505
506 void DAGTypeLegalizer::SetExpandedFloat(SDOperand Op, SDOperand Lo,
507                                         SDOperand Hi) {
508   ExpungeNode(Lo);
509   ExpungeNode(Hi);
510
511   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
512   AnalyzeNewNode(Lo.Val);
513   AnalyzeNewNode(Hi.Val);
514
515   // Remember that this is the result of the node.
516   std::pair<SDOperand, SDOperand> &Entry = ExpandedFloats[Op];
517   assert(Entry.first.Val == 0 && "Node already expanded");
518   Entry.first = Lo;
519   Entry.second = Hi;
520 }
521
522 void DAGTypeLegalizer::GetSplitVector(SDOperand Op, SDOperand &Lo,
523                                       SDOperand &Hi) {
524   std::pair<SDOperand, SDOperand> &Entry = SplitVectors[Op];
525   RemapNode(Entry.first);
526   RemapNode(Entry.second);
527   assert(Entry.first.Val && "Operand isn't split");
528   Lo = Entry.first;
529   Hi = Entry.second;
530 }
531
532 void DAGTypeLegalizer::SetSplitVector(SDOperand Op, SDOperand Lo,
533                                       SDOperand Hi) {
534   ExpungeNode(Lo);
535   ExpungeNode(Hi);
536
537   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
538   AnalyzeNewNode(Lo.Val);
539   AnalyzeNewNode(Hi.Val);
540
541   // Remember that this is the result of the node.
542   std::pair<SDOperand, SDOperand> &Entry = SplitVectors[Op];
543   assert(Entry.first.Val == 0 && "Node already split");
544   Entry.first = Lo;
545   Entry.second = Hi;
546 }
547
548
549 //===----------------------------------------------------------------------===//
550 // Utilities.
551 //===----------------------------------------------------------------------===//
552
553 /// BitConvertToInteger - Convert to an integer of the same size.
554 SDOperand DAGTypeLegalizer::BitConvertToInteger(SDOperand Op) {
555   unsigned BitWidth = Op.getValueType().getSizeInBits();
556   return DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerVT(BitWidth), Op);
557 }
558
559 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op,
560                                                  MVT DestVT) {
561   // Create the stack frame object.
562   SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
563
564   // Emit a store to the stack slot.
565   SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
566   // Result is a load from the stack slot.
567   return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
568 }
569
570 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
571 SDOperand DAGTypeLegalizer::JoinIntegers(SDOperand Lo, SDOperand Hi) {
572   MVT LVT = Lo.getValueType();
573   MVT HVT = Hi.getValueType();
574   MVT NVT = MVT::getIntegerVT(LVT.getSizeInBits() + HVT.getSizeInBits());
575
576   Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
577   Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
578   Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(LVT.getSizeInBits(),
579                                                       TLI.getShiftAmountTy()));
580   return DAG.getNode(ISD::OR, NVT, Lo, Hi);
581 }
582
583 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
584 /// bits in Hi.
585 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
586                                     MVT LoVT, MVT HiVT,
587                                     SDOperand &Lo, SDOperand &Hi) {
588   assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
589          Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
590   Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
591   Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
592                    DAG.getConstant(LoVT.getSizeInBits(),
593                                    TLI.getShiftAmountTy()));
594   Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
595 }
596
597 /// SplitInteger - Return the lower and upper halves of Op's bits in a value type
598 /// half the size of Op's.
599 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
600                                     SDOperand &Lo, SDOperand &Hi) {
601   MVT HalfVT = MVT::getIntegerVT(Op.getValueType().getSizeInBits()/2);
602   SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
603 }
604
605 /// MakeLibCall - Generate a libcall taking the given operands as arguments and
606 /// returning a result of type RetVT.
607 SDOperand DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, MVT RetVT,
608                                         const SDOperand *Ops, unsigned NumOps,
609                                         bool isSigned) {
610   TargetLowering::ArgListTy Args;
611   Args.reserve(NumOps);
612
613   TargetLowering::ArgListEntry Entry;
614   for (unsigned i = 0; i != NumOps; ++i) {
615     Entry.Node = Ops[i];
616     Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
617     Entry.isSExt = isSigned;
618     Entry.isZExt = !isSigned;
619     Args.push_back(Entry);
620   }
621   SDOperand Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
622                                            TLI.getPointerTy());
623
624   const Type *RetTy = RetVT.getTypeForMVT();
625   std::pair<SDOperand,SDOperand> CallInfo =
626     TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
627                     CallingConv::C, false, Callee, Args, DAG);
628   return CallInfo.first;
629 }
630
631 SDOperand DAGTypeLegalizer::GetVectorElementPointer(SDOperand VecPtr, MVT EltVT,
632                                                     SDOperand Index) {
633   // Make sure the index type is big enough to compute in.
634   if (Index.getValueType().bitsGT(TLI.getPointerTy()))
635     Index = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), Index);
636   else
637     Index = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Index);
638
639   // Calculate the element offset and add it to the pointer.
640   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
641
642   Index = DAG.getNode(ISD::MUL, Index.getValueType(), Index,
643                       DAG.getConstant(EltSize, Index.getValueType()));
644   return DAG.getNode(ISD::ADD, Index.getValueType(), Index, VecPtr);
645 }
646
647 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
648 /// which is split into two not necessarily identical pieces.
649 void DAGTypeLegalizer::GetSplitDestVTs(MVT InVT, MVT &LoVT, MVT &HiVT) {
650   if (!InVT.isVector()) {
651     LoVT = HiVT = TLI.getTypeToTransformTo(InVT);
652   } else {
653     MVT NewEltVT = InVT.getVectorElementType();
654     unsigned NumElements = InVT.getVectorNumElements();
655     if ((NumElements & (NumElements-1)) == 0) {  // Simple power of two vector.
656       NumElements >>= 1;
657       LoVT = HiVT =  MVT::getVectorVT(NewEltVT, NumElements);
658     } else {                                     // Non-power-of-two vectors.
659       unsigned NewNumElts_Lo = 1 << Log2_32(NumElements);
660       unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
661       LoVT = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
662       HiVT = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
663     }
664   }
665 }
666
667
668 //===----------------------------------------------------------------------===//
669 //  Entry Point
670 //===----------------------------------------------------------------------===//
671
672 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
673 /// only uses types natively supported by the target.
674 ///
675 /// Note that this is an involved process that may invalidate pointers into
676 /// the graph.
677 void SelectionDAG::LegalizeTypes() {
678   if (ViewLegalizeTypesDAGs) viewGraph();
679
680   DAGTypeLegalizer(*this).run();
681 }