]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.cpp
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / contrib / llvm / 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/ADT/SetVector.h"
18 #include "llvm/IR/CallingConv.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 using namespace llvm;
24
25 static cl::opt<bool>
26 EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
27
28 /// PerformExpensiveChecks - Do extensive, expensive, sanity checking.
29 void DAGTypeLegalizer::PerformExpensiveChecks() {
30   // If a node is not processed, then none of its values should be mapped by any
31   // of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
32
33   // If a node is processed, then each value with an illegal type must be mapped
34   // by exactly one of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
35   // Values with a legal type may be mapped by ReplacedValues, but not by any of
36   // the other maps.
37
38   // Note that these invariants may not hold momentarily when processing a node:
39   // the node being processed may be put in a map before being marked Processed.
40
41   // Note that it is possible to have nodes marked NewNode in the DAG.  This can
42   // occur in two ways.  Firstly, a node may be created during legalization but
43   // never passed to the legalization core.  This is usually due to the implicit
44   // folding that occurs when using the DAG.getNode operators.  Secondly, a new
45   // node may be passed to the legalization core, but when analyzed may morph
46   // into a different node, leaving the original node as a NewNode in the DAG.
47   // A node may morph if one of its operands changes during analysis.  Whether
48   // it actually morphs or not depends on whether, after updating its operands,
49   // it is equivalent to an existing node: if so, it morphs into that existing
50   // node (CSE).  An operand can change during analysis if the operand is a new
51   // node that morphs, or it is a processed value that was mapped to some other
52   // value (as recorded in ReplacedValues) in which case the operand is turned
53   // into that other value.  If a node morphs then the node it morphed into will
54   // be used instead of it for legalization, however the original node continues
55   // to live on in the DAG.
56   // The conclusion is that though there may be nodes marked NewNode in the DAG,
57   // all uses of such nodes are also marked NewNode: the result is a fungus of
58   // NewNodes growing on top of the useful nodes, and perhaps using them, but
59   // not used by them.
60
61   // If a value is mapped by ReplacedValues, then it must have no uses, except
62   // by nodes marked NewNode (see above).
63
64   // The final node obtained by mapping by ReplacedValues is not marked NewNode.
65   // Note that ReplacedValues should be applied iteratively.
66
67   // Note that the ReplacedValues map may also map deleted nodes (by iterating
68   // over the DAG we never dereference deleted nodes).  This means that it may
69   // also map nodes marked NewNode if the deallocated memory was reallocated as
70   // another node, and that new node was not seen by the LegalizeTypes machinery
71   // (for example because it was created but not used).  In general, we cannot
72   // distinguish between new nodes and deleted nodes.
73   SmallVector<SDNode*, 16> NewNodes;
74   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
75        E = DAG.allnodes_end(); I != E; ++I) {
76     // Remember nodes marked NewNode - they are subject to extra checking below.
77     if (I->getNodeId() == NewNode)
78       NewNodes.push_back(I);
79
80     for (unsigned i = 0, e = I->getNumValues(); i != e; ++i) {
81       SDValue Res(I, i);
82       bool Failed = false;
83
84       unsigned Mapped = 0;
85       if (ReplacedValues.find(Res) != ReplacedValues.end()) {
86         Mapped |= 1;
87         // Check that remapped values are only used by nodes marked NewNode.
88         for (SDNode::use_iterator UI = I->use_begin(), UE = I->use_end();
89              UI != UE; ++UI)
90           if (UI.getUse().getResNo() == i)
91             assert(UI->getNodeId() == NewNode &&
92                    "Remapped value has non-trivial use!");
93
94         // Check that the final result of applying ReplacedValues is not
95         // marked NewNode.
96         SDValue NewVal = ReplacedValues[Res];
97         DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal);
98         while (I != ReplacedValues.end()) {
99           NewVal = I->second;
100           I = ReplacedValues.find(NewVal);
101         }
102         assert(NewVal.getNode()->getNodeId() != NewNode &&
103                "ReplacedValues maps to a new node!");
104       }
105       if (PromotedIntegers.find(Res) != PromotedIntegers.end())
106         Mapped |= 2;
107       if (SoftenedFloats.find(Res) != SoftenedFloats.end())
108         Mapped |= 4;
109       if (ScalarizedVectors.find(Res) != ScalarizedVectors.end())
110         Mapped |= 8;
111       if (ExpandedIntegers.find(Res) != ExpandedIntegers.end())
112         Mapped |= 16;
113       if (ExpandedFloats.find(Res) != ExpandedFloats.end())
114         Mapped |= 32;
115       if (SplitVectors.find(Res) != SplitVectors.end())
116         Mapped |= 64;
117       if (WidenedVectors.find(Res) != WidenedVectors.end())
118         Mapped |= 128;
119
120       if (I->getNodeId() != Processed) {
121         // Since we allow ReplacedValues to map deleted nodes, it may map nodes
122         // marked NewNode too, since a deleted node may have been reallocated as
123         // another node that has not been seen by the LegalizeTypes machinery.
124         if ((I->getNodeId() == NewNode && Mapped > 1) ||
125             (I->getNodeId() != NewNode && Mapped != 0)) {
126           dbgs() << "Unprocessed value in a map!";
127           Failed = true;
128         }
129       } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) {
130         if (Mapped > 1) {
131           dbgs() << "Value with legal type was transformed!";
132           Failed = true;
133         }
134       } else {
135         if (Mapped == 0) {
136           dbgs() << "Processed value not in any map!";
137           Failed = true;
138         } else if (Mapped & (Mapped - 1)) {
139           dbgs() << "Value in multiple maps!";
140           Failed = true;
141         }
142       }
143
144       if (Failed) {
145         if (Mapped & 1)
146           dbgs() << " ReplacedValues";
147         if (Mapped & 2)
148           dbgs() << " PromotedIntegers";
149         if (Mapped & 4)
150           dbgs() << " SoftenedFloats";
151         if (Mapped & 8)
152           dbgs() << " ScalarizedVectors";
153         if (Mapped & 16)
154           dbgs() << " ExpandedIntegers";
155         if (Mapped & 32)
156           dbgs() << " ExpandedFloats";
157         if (Mapped & 64)
158           dbgs() << " SplitVectors";
159         if (Mapped & 128)
160           dbgs() << " WidenedVectors";
161         dbgs() << "\n";
162         llvm_unreachable(0);
163       }
164     }
165   }
166
167   // Checked that NewNodes are only used by other NewNodes.
168   for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
169     SDNode *N = NewNodes[i];
170     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
171          UI != UE; ++UI)
172       assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
173   }
174 }
175
176 /// run - This is the main entry point for the type legalizer.  This does a
177 /// top-down traversal of the dag, legalizing types as it goes.  Returns "true"
178 /// if it made any changes.
179 bool DAGTypeLegalizer::run() {
180   bool Changed = false;
181
182   // Create a dummy node (which is not added to allnodes), that adds a reference
183   // to the root node, preventing it from being deleted, and tracking any
184   // changes of the root.
185   HandleSDNode Dummy(DAG.getRoot());
186   Dummy.setNodeId(Unanalyzed);
187
188   // The root of the dag may dangle to deleted nodes until the type legalizer is
189   // done.  Set it to null to avoid confusion.
190   DAG.setRoot(SDValue());
191
192   // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
193   // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
194   // non-leaves.
195   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
196        E = DAG.allnodes_end(); I != E; ++I) {
197     if (I->getNumOperands() == 0) {
198       I->setNodeId(ReadyToProcess);
199       Worklist.push_back(I);
200     } else {
201       I->setNodeId(Unanalyzed);
202     }
203   }
204
205   // Now that we have a set of nodes to process, handle them all.
206   while (!Worklist.empty()) {
207 #ifndef XDEBUG
208     if (EnableExpensiveChecks)
209 #endif
210       PerformExpensiveChecks();
211
212     SDNode *N = Worklist.back();
213     Worklist.pop_back();
214     assert(N->getNodeId() == ReadyToProcess &&
215            "Node should be ready if on worklist!");
216
217     if (IgnoreNodeResults(N))
218       goto ScanOperands;
219
220     // Scan the values produced by the node, checking to see if any result
221     // types are illegal.
222     for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
223       EVT ResultVT = N->getValueType(i);
224       switch (getTypeAction(ResultVT)) {
225       case TargetLowering::TypeLegal:
226         break;
227       // The following calls must take care of *all* of the node's results,
228       // not just the illegal result they were passed (this includes results
229       // with a legal type).  Results can be remapped using ReplaceValueWith,
230       // or their promoted/expanded/etc values registered in PromotedIntegers,
231       // ExpandedIntegers etc.
232       case TargetLowering::TypePromoteInteger:
233         PromoteIntegerResult(N, i);
234         Changed = true;
235         goto NodeDone;
236       case TargetLowering::TypeExpandInteger:
237         ExpandIntegerResult(N, i);
238         Changed = true;
239         goto NodeDone;
240       case TargetLowering::TypeSoftenFloat:
241         SoftenFloatResult(N, i);
242         Changed = true;
243         goto NodeDone;
244       case TargetLowering::TypeExpandFloat:
245         ExpandFloatResult(N, i);
246         Changed = true;
247         goto NodeDone;
248       case TargetLowering::TypeScalarizeVector:
249         ScalarizeVectorResult(N, i);
250         Changed = true;
251         goto NodeDone;
252       case TargetLowering::TypeSplitVector:
253         SplitVectorResult(N, i);
254         Changed = true;
255         goto NodeDone;
256       case TargetLowering::TypeWidenVector:
257         WidenVectorResult(N, i);
258         Changed = true;
259         goto NodeDone;
260       }
261     }
262
263 ScanOperands:
264     // Scan the operand list for the node, handling any nodes with operands that
265     // are illegal.
266     {
267     unsigned NumOperands = N->getNumOperands();
268     bool NeedsReanalyzing = false;
269     unsigned i;
270     for (i = 0; i != NumOperands; ++i) {
271       if (IgnoreNodeResults(N->getOperand(i).getNode()))
272         continue;
273
274       EVT OpVT = N->getOperand(i).getValueType();
275       switch (getTypeAction(OpVT)) {
276       case TargetLowering::TypeLegal:
277         continue;
278       // The following calls must either replace all of the node's results
279       // using ReplaceValueWith, and return "false"; or update the node's
280       // operands in place, and return "true".
281       case TargetLowering::TypePromoteInteger:
282         NeedsReanalyzing = PromoteIntegerOperand(N, i);
283         Changed = true;
284         break;
285       case TargetLowering::TypeExpandInteger:
286         NeedsReanalyzing = ExpandIntegerOperand(N, i);
287         Changed = true;
288         break;
289       case TargetLowering::TypeSoftenFloat:
290         NeedsReanalyzing = SoftenFloatOperand(N, i);
291         Changed = true;
292         break;
293       case TargetLowering::TypeExpandFloat:
294         NeedsReanalyzing = ExpandFloatOperand(N, i);
295         Changed = true;
296         break;
297       case TargetLowering::TypeScalarizeVector:
298         NeedsReanalyzing = ScalarizeVectorOperand(N, i);
299         Changed = true;
300         break;
301       case TargetLowering::TypeSplitVector:
302         NeedsReanalyzing = SplitVectorOperand(N, i);
303         Changed = true;
304         break;
305       case TargetLowering::TypeWidenVector:
306         NeedsReanalyzing = WidenVectorOperand(N, i);
307         Changed = true;
308         break;
309       }
310       break;
311     }
312
313     // The sub-method updated N in place.  Check to see if any operands are new,
314     // and if so, mark them.  If the node needs revisiting, don't add all users
315     // to the worklist etc.
316     if (NeedsReanalyzing) {
317       assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
318       N->setNodeId(NewNode);
319       // Recompute the NodeId and correct processed operands, adding the node to
320       // the worklist if ready.
321       SDNode *M = AnalyzeNewNode(N);
322       if (M == N)
323         // The node didn't morph - nothing special to do, it will be revisited.
324         continue;
325
326       // The node morphed - this is equivalent to legalizing by replacing every
327       // value of N with the corresponding value of M.  So do that now.
328       assert(N->getNumValues() == M->getNumValues() &&
329              "Node morphing changed the number of results!");
330       for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
331         // Replacing the value takes care of remapping the new value.
332         ReplaceValueWith(SDValue(N, i), SDValue(M, i));
333       assert(N->getNodeId() == NewNode && "Unexpected node state!");
334       // The node continues to live on as part of the NewNode fungus that
335       // grows on top of the useful nodes.  Nothing more needs to be done
336       // with it - move on to the next node.
337       continue;
338     }
339
340     if (i == NumOperands) {
341       DEBUG(dbgs() << "Legally typed node: "; N->dump(&DAG); dbgs() << "\n");
342     }
343     }
344 NodeDone:
345
346     // If we reach here, the node was processed, potentially creating new nodes.
347     // Mark it as processed and add its users to the worklist as appropriate.
348     assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
349     N->setNodeId(Processed);
350
351     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
352          UI != E; ++UI) {
353       SDNode *User = *UI;
354       int NodeId = User->getNodeId();
355
356       // This node has two options: it can either be a new node or its Node ID
357       // may be a count of the number of operands it has that are not ready.
358       if (NodeId > 0) {
359         User->setNodeId(NodeId-1);
360
361         // If this was the last use it was waiting on, add it to the ready list.
362         if (NodeId-1 == ReadyToProcess)
363           Worklist.push_back(User);
364         continue;
365       }
366
367       // If this is an unreachable new node, then ignore it.  If it ever becomes
368       // reachable by being used by a newly created node then it will be handled
369       // by AnalyzeNewNode.
370       if (NodeId == NewNode)
371         continue;
372
373       // Otherwise, this node is new: this is the first operand of it that
374       // became ready.  Its new NodeId is the number of operands it has minus 1
375       // (as this node is now processed).
376       assert(NodeId == Unanalyzed && "Unknown node ID!");
377       User->setNodeId(User->getNumOperands() - 1);
378
379       // If the node only has a single operand, it is now ready.
380       if (User->getNumOperands() == 1)
381         Worklist.push_back(User);
382     }
383   }
384
385 #ifndef XDEBUG
386   if (EnableExpensiveChecks)
387 #endif
388     PerformExpensiveChecks();
389
390   // If the root changed (e.g. it was a dead load) update the root.
391   DAG.setRoot(Dummy.getValue());
392
393   // Remove dead nodes.  This is important to do for cleanliness but also before
394   // the checking loop below.  Implicit folding by the DAG.getNode operators and
395   // node morphing can cause unreachable nodes to be around with their flags set
396   // to new.
397   DAG.RemoveDeadNodes();
398
399   // In a debug build, scan all the nodes to make sure we found them all.  This
400   // ensures that there are no cycles and that everything got processed.
401 #ifndef NDEBUG
402   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
403        E = DAG.allnodes_end(); I != E; ++I) {
404     bool Failed = false;
405
406     // Check that all result types are legal.
407     if (!IgnoreNodeResults(I))
408       for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
409         if (!isTypeLegal(I->getValueType(i))) {
410           dbgs() << "Result type " << i << " illegal!\n";
411           Failed = true;
412         }
413
414     // Check that all operand types are legal.
415     for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
416       if (!IgnoreNodeResults(I->getOperand(i).getNode()) &&
417           !isTypeLegal(I->getOperand(i).getValueType())) {
418         dbgs() << "Operand type " << i << " illegal!\n";
419         Failed = true;
420       }
421
422     if (I->getNodeId() != Processed) {
423        if (I->getNodeId() == NewNode)
424          dbgs() << "New node not analyzed?\n";
425        else if (I->getNodeId() == Unanalyzed)
426          dbgs() << "Unanalyzed node not noticed?\n";
427        else if (I->getNodeId() > 0)
428          dbgs() << "Operand not processed?\n";
429        else if (I->getNodeId() == ReadyToProcess)
430          dbgs() << "Not added to worklist?\n";
431        Failed = true;
432     }
433
434     if (Failed) {
435       I->dump(&DAG); dbgs() << "\n";
436       llvm_unreachable(0);
437     }
438   }
439 #endif
440
441   return Changed;
442 }
443
444 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
445 /// new nodes.  Correct any processed operands (this may change the node) and
446 /// calculate the NodeId.  If the node itself changes to a processed node, it
447 /// is not remapped - the caller needs to take care of this.
448 /// Returns the potentially changed node.
449 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
450   // If this was an existing node that is already done, we're done.
451   if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
452     return N;
453
454   // Remove any stale map entries.
455   ExpungeNode(N);
456
457   // Okay, we know that this node is new.  Recursively walk all of its operands
458   // to see if they are new also.  The depth of this walk is bounded by the size
459   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
460   // about revisiting of nodes.
461   //
462   // As we walk the operands, keep track of the number of nodes that are
463   // processed.  If non-zero, this will become the new nodeid of this node.
464   // Operands may morph when they are analyzed.  If so, the node will be
465   // updated after all operands have been analyzed.  Since this is rare,
466   // the code tries to minimize overhead in the non-morphing case.
467
468   SmallVector<SDValue, 8> NewOps;
469   unsigned NumProcessed = 0;
470   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
471     SDValue OrigOp = N->getOperand(i);
472     SDValue Op = OrigOp;
473
474     AnalyzeNewValue(Op); // Op may morph.
475
476     if (Op.getNode()->getNodeId() == Processed)
477       ++NumProcessed;
478
479     if (!NewOps.empty()) {
480       // Some previous operand changed.  Add this one to the list.
481       NewOps.push_back(Op);
482     } else if (Op != OrigOp) {
483       // This is the first operand to change - add all operands so far.
484       NewOps.append(N->op_begin(), N->op_begin() + i);
485       NewOps.push_back(Op);
486     }
487   }
488
489   // Some operands changed - update the node.
490   if (!NewOps.empty()) {
491     SDNode *M = DAG.UpdateNodeOperands(N, &NewOps[0], NewOps.size());
492     if (M != N) {
493       // The node morphed into a different node.  Normally for this to happen
494       // the original node would have to be marked NewNode.  However this can
495       // in theory momentarily not be the case while ReplaceValueWith is doing
496       // its stuff.  Mark the original node NewNode to help sanity checking.
497       N->setNodeId(NewNode);
498       if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
499         // It morphed into a previously analyzed node - nothing more to do.
500         return M;
501
502       // It morphed into a different new node.  Do the equivalent of passing
503       // it to AnalyzeNewNode: expunge it and calculate the NodeId.  No need
504       // to remap the operands, since they are the same as the operands we
505       // remapped above.
506       N = M;
507       ExpungeNode(N);
508     }
509   }
510
511   // Calculate the NodeId.
512   N->setNodeId(N->getNumOperands() - NumProcessed);
513   if (N->getNodeId() == ReadyToProcess)
514     Worklist.push_back(N);
515
516   return N;
517 }
518
519 /// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed.
520 /// If the node changes to a processed node, then remap it.
521 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
522   Val.setNode(AnalyzeNewNode(Val.getNode()));
523   if (Val.getNode()->getNodeId() == Processed)
524     // We were passed a processed node, or it morphed into one - remap it.
525     RemapValue(Val);
526 }
527
528 /// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it.
529 /// This can occur when a node is deleted then reallocated as a new node -
530 /// the mapping in ReplacedValues applies to the deleted node, not the new
531 /// one.
532 /// The only map that can have a deleted node as a source is ReplacedValues.
533 /// Other maps can have deleted nodes as targets, but since their looked-up
534 /// values are always immediately remapped using RemapValue, resulting in a
535 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
536 /// always performs correct mappings.  In order to keep the mapping correct,
537 /// ExpungeNode should be called on any new nodes *before* adding them as
538 /// either source or target to ReplacedValues (which typically means calling
539 /// Expunge when a new node is first seen, since it may no longer be marked
540 /// NewNode by the time it is added to ReplacedValues).
541 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
542   if (N->getNodeId() != NewNode)
543     return;
544
545   // If N is not remapped by ReplacedValues then there is nothing to do.
546   unsigned i, e;
547   for (i = 0, e = N->getNumValues(); i != e; ++i)
548     if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
549       break;
550
551   if (i == e)
552     return;
553
554   // Remove N from all maps - this is expensive but rare.
555
556   for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
557        E = PromotedIntegers.end(); I != E; ++I) {
558     assert(I->first.getNode() != N);
559     RemapValue(I->second);
560   }
561
562   for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
563        E = SoftenedFloats.end(); I != E; ++I) {
564     assert(I->first.getNode() != N);
565     RemapValue(I->second);
566   }
567
568   for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
569        E = ScalarizedVectors.end(); I != E; ++I) {
570     assert(I->first.getNode() != N);
571     RemapValue(I->second);
572   }
573
574   for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(),
575        E = WidenedVectors.end(); I != E; ++I) {
576     assert(I->first.getNode() != N);
577     RemapValue(I->second);
578   }
579
580   for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
581        I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
582     assert(I->first.getNode() != N);
583     RemapValue(I->second.first);
584     RemapValue(I->second.second);
585   }
586
587   for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
588        I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
589     assert(I->first.getNode() != N);
590     RemapValue(I->second.first);
591     RemapValue(I->second.second);
592   }
593
594   for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
595        I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
596     assert(I->first.getNode() != N);
597     RemapValue(I->second.first);
598     RemapValue(I->second.second);
599   }
600
601   for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
602        E = ReplacedValues.end(); I != E; ++I)
603     RemapValue(I->second);
604
605   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
606     ReplacedValues.erase(SDValue(N, i));
607 }
608
609 /// RemapValue - If the specified value was already legalized to another value,
610 /// replace it by that value.
611 void DAGTypeLegalizer::RemapValue(SDValue &N) {
612   DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
613   if (I != ReplacedValues.end()) {
614     // Use path compression to speed up future lookups if values get multiply
615     // replaced with other values.
616     RemapValue(I->second);
617     N = I->second;
618     assert(N.getNode()->getNodeId() != NewNode && "Mapped to new node!");
619   }
620 }
621
622 namespace {
623   /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
624   /// updates to nodes and recomputes their ready state.
625   class NodeUpdateListener : public SelectionDAG::DAGUpdateListener {
626     DAGTypeLegalizer &DTL;
627     SmallSetVector<SDNode*, 16> &NodesToAnalyze;
628   public:
629     explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
630                                 SmallSetVector<SDNode*, 16> &nta)
631       : SelectionDAG::DAGUpdateListener(dtl.getDAG()),
632         DTL(dtl), NodesToAnalyze(nta) {}
633
634     virtual void NodeDeleted(SDNode *N, SDNode *E) {
635       assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
636              N->getNodeId() != DAGTypeLegalizer::Processed &&
637              "Invalid node ID for RAUW deletion!");
638       // It is possible, though rare, for the deleted node N to occur as a
639       // target in a map, so note the replacement N -> E in ReplacedValues.
640       assert(E && "Node not replaced?");
641       DTL.NoteDeletion(N, E);
642
643       // In theory the deleted node could also have been scheduled for analysis.
644       // So remove it from the set of nodes which will be analyzed.
645       NodesToAnalyze.remove(N);
646
647       // In general nothing needs to be done for E, since it didn't change but
648       // only gained new uses.  However N -> E was just added to ReplacedValues,
649       // and the result of a ReplacedValues mapping is not allowed to be marked
650       // NewNode.  So if E is marked NewNode, then it needs to be analyzed.
651       if (E->getNodeId() == DAGTypeLegalizer::NewNode)
652         NodesToAnalyze.insert(E);
653     }
654
655     virtual void NodeUpdated(SDNode *N) {
656       // Node updates can mean pretty much anything.  It is possible that an
657       // operand was set to something already processed (f.e.) in which case
658       // this node could become ready.  Recompute its flags.
659       assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
660              N->getNodeId() != DAGTypeLegalizer::Processed &&
661              "Invalid node ID for RAUW deletion!");
662       N->setNodeId(DAGTypeLegalizer::NewNode);
663       NodesToAnalyze.insert(N);
664     }
665   };
666 }
667
668
669 /// ReplaceValueWith - The specified value was legalized to the specified other
670 /// value.  Update the DAG and NodeIds replacing any uses of From to use To
671 /// instead.
672 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
673   assert(From.getNode() != To.getNode() && "Potential legalization loop!");
674
675   // If expansion produced new nodes, make sure they are properly marked.
676   ExpungeNode(From.getNode());
677   AnalyzeNewValue(To); // Expunges To.
678
679   // Anything that used the old node should now use the new one.  Note that this
680   // can potentially cause recursive merging.
681   SmallSetVector<SDNode*, 16> NodesToAnalyze;
682   NodeUpdateListener NUL(*this, NodesToAnalyze);
683   do {
684     DAG.ReplaceAllUsesOfValueWith(From, To);
685
686     // The old node may still be present in a map like ExpandedIntegers or
687     // PromotedIntegers.  Inform maps about the replacement.
688     ReplacedValues[From] = To;
689
690     // Process the list of nodes that need to be reanalyzed.
691     while (!NodesToAnalyze.empty()) {
692       SDNode *N = NodesToAnalyze.back();
693       NodesToAnalyze.pop_back();
694       if (N->getNodeId() != DAGTypeLegalizer::NewNode)
695         // The node was analyzed while reanalyzing an earlier node - it is safe
696         // to skip.  Note that this is not a morphing node - otherwise it would
697         // still be marked NewNode.
698         continue;
699
700       // Analyze the node's operands and recalculate the node ID.
701       SDNode *M = AnalyzeNewNode(N);
702       if (M != N) {
703         // The node morphed into a different node.  Make everyone use the new
704         // node instead.
705         assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
706         assert(N->getNumValues() == M->getNumValues() &&
707                "Node morphing changed the number of results!");
708         for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
709           SDValue OldVal(N, i);
710           SDValue NewVal(M, i);
711           if (M->getNodeId() == Processed)
712             RemapValue(NewVal);
713           DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal);
714           // OldVal may be a target of the ReplacedValues map which was marked
715           // NewNode to force reanalysis because it was updated.  Ensure that
716           // anything that ReplacedValues mapped to OldVal will now be mapped
717           // all the way to NewVal.
718           ReplacedValues[OldVal] = NewVal;
719         }
720         // The original node continues to exist in the DAG, marked NewNode.
721       }
722     }
723     // When recursively update nodes with new nodes, it is possible to have
724     // new uses of From due to CSE. If this happens, replace the new uses of
725     // From with To.
726   } while (!From.use_empty());
727 }
728
729 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
730   assert(Result.getValueType() ==
731          TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
732          "Invalid type for promoted integer");
733   AnalyzeNewValue(Result);
734
735   SDValue &OpEntry = PromotedIntegers[Op];
736   assert(OpEntry.getNode() == 0 && "Node is already promoted!");
737   OpEntry = Result;
738
739   // Propagate node ordering
740   DAG.AssignOrdering(Result.getNode(), DAG.GetOrdering(Op.getNode()));
741 }
742
743 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
744   assert(Result.getValueType() ==
745          TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
746          "Invalid type for softened float");
747   AnalyzeNewValue(Result);
748
749   SDValue &OpEntry = SoftenedFloats[Op];
750   assert(OpEntry.getNode() == 0 && "Node is already converted to integer!");
751   OpEntry = Result;
752
753   // Propagate node ordering
754   DAG.AssignOrdering(Result.getNode(), DAG.GetOrdering(Op.getNode()));
755 }
756
757 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
758   // Note that in some cases vector operation operands may be greater than
759   // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
760   // a constant i8 operand.
761   assert(Result.getValueType().getSizeInBits() >=
762          Op.getValueType().getVectorElementType().getSizeInBits() &&
763          "Invalid type for scalarized vector");
764   AnalyzeNewValue(Result);
765
766   SDValue &OpEntry = ScalarizedVectors[Op];
767   assert(OpEntry.getNode() == 0 && "Node is already scalarized!");
768   OpEntry = Result;
769
770   // Propagate node ordering
771   DAG.AssignOrdering(Result.getNode(), DAG.GetOrdering(Op.getNode()));
772 }
773
774 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
775                                           SDValue &Hi) {
776   std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
777   RemapValue(Entry.first);
778   RemapValue(Entry.second);
779   assert(Entry.first.getNode() && "Operand isn't expanded");
780   Lo = Entry.first;
781   Hi = Entry.second;
782 }
783
784 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
785                                           SDValue Hi) {
786   assert(Lo.getValueType() ==
787          TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
788          Hi.getValueType() == Lo.getValueType() &&
789          "Invalid type for expanded integer");
790   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
791   AnalyzeNewValue(Lo);
792   AnalyzeNewValue(Hi);
793
794   // Remember that this is the result of the node.
795   std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
796   assert(Entry.first.getNode() == 0 && "Node already expanded");
797   Entry.first = Lo;
798   Entry.second = Hi;
799
800   // Propagate ordering
801   DAG.AssignOrdering(Lo.getNode(), DAG.GetOrdering(Op.getNode()));
802   DAG.AssignOrdering(Hi.getNode(), DAG.GetOrdering(Op.getNode()));
803 }
804
805 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
806                                         SDValue &Hi) {
807   std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
808   RemapValue(Entry.first);
809   RemapValue(Entry.second);
810   assert(Entry.first.getNode() && "Operand isn't expanded");
811   Lo = Entry.first;
812   Hi = Entry.second;
813 }
814
815 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
816                                         SDValue Hi) {
817   assert(Lo.getValueType() ==
818          TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
819          Hi.getValueType() == Lo.getValueType() &&
820          "Invalid type for expanded float");
821   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
822   AnalyzeNewValue(Lo);
823   AnalyzeNewValue(Hi);
824
825   // Remember that this is the result of the node.
826   std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
827   assert(Entry.first.getNode() == 0 && "Node already expanded");
828   Entry.first = Lo;
829   Entry.second = Hi;
830
831   // Propagate ordering
832   DAG.AssignOrdering(Lo.getNode(), DAG.GetOrdering(Op.getNode()));
833   DAG.AssignOrdering(Hi.getNode(), DAG.GetOrdering(Op.getNode()));
834 }
835
836 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
837                                       SDValue &Hi) {
838   std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
839   RemapValue(Entry.first);
840   RemapValue(Entry.second);
841   assert(Entry.first.getNode() && "Operand isn't split");
842   Lo = Entry.first;
843   Hi = Entry.second;
844 }
845
846 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
847                                       SDValue Hi) {
848   assert(Lo.getValueType().getVectorElementType() ==
849          Op.getValueType().getVectorElementType() &&
850          2*Lo.getValueType().getVectorNumElements() ==
851          Op.getValueType().getVectorNumElements() &&
852          Hi.getValueType() == Lo.getValueType() &&
853          "Invalid type for split vector");
854   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
855   AnalyzeNewValue(Lo);
856   AnalyzeNewValue(Hi);
857
858   // Remember that this is the result of the node.
859   std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
860   assert(Entry.first.getNode() == 0 && "Node already split");
861   Entry.first = Lo;
862   Entry.second = Hi;
863
864   // Propagate ordering
865   DAG.AssignOrdering(Lo.getNode(), DAG.GetOrdering(Op.getNode()));
866   DAG.AssignOrdering(Hi.getNode(), DAG.GetOrdering(Op.getNode()));
867 }
868
869 void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
870   assert(Result.getValueType() ==
871          TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
872          "Invalid type for widened vector");
873   AnalyzeNewValue(Result);
874
875   SDValue &OpEntry = WidenedVectors[Op];
876   assert(OpEntry.getNode() == 0 && "Node already widened!");
877   OpEntry = Result;
878
879   // Propagate node ordering
880   DAG.AssignOrdering(Result.getNode(), DAG.GetOrdering(Op.getNode()));
881 }
882
883
884 //===----------------------------------------------------------------------===//
885 // Utilities.
886 //===----------------------------------------------------------------------===//
887
888 /// BitConvertToInteger - Convert to an integer of the same size.
889 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
890   unsigned BitWidth = Op.getValueType().getSizeInBits();
891   return DAG.getNode(ISD::BITCAST, Op.getDebugLoc(),
892                      EVT::getIntegerVT(*DAG.getContext(), BitWidth), Op);
893 }
894
895 /// BitConvertVectorToIntegerVector - Convert to a vector of integers of the
896 /// same size.
897 SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
898   assert(Op.getValueType().isVector() && "Only applies to vectors!");
899   unsigned EltWidth = Op.getValueType().getVectorElementType().getSizeInBits();
900   EVT EltNVT = EVT::getIntegerVT(*DAG.getContext(), EltWidth);
901   unsigned NumElts = Op.getValueType().getVectorNumElements();
902   return DAG.getNode(ISD::BITCAST, Op.getDebugLoc(),
903                      EVT::getVectorVT(*DAG.getContext(), EltNVT, NumElts), Op);
904 }
905
906 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
907                                                EVT DestVT) {
908   DebugLoc dl = Op.getDebugLoc();
909   // Create the stack frame object.  Make sure it is aligned for both
910   // the source and destination types.
911   SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
912   // Emit a store to the stack slot.
913   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr,
914                                MachinePointerInfo(), false, false, 0);
915   // Result is a load from the stack slot.
916   return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo(),
917                      false, false, false, 0);
918 }
919
920 /// CustomLowerNode - Replace the node's results with custom code provided
921 /// by the target and return "true", or do nothing and return "false".
922 /// The last parameter is FALSE if we are dealing with a node with legal
923 /// result types and illegal operand. The second parameter denotes the type of
924 /// illegal OperandNo in that case.
925 /// The last parameter being TRUE means we are dealing with a
926 /// node with illegal result types. The second parameter denotes the type of
927 /// illegal ResNo in that case.
928 bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
929   // See if the target wants to custom lower this node.
930   if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
931     return false;
932
933   SmallVector<SDValue, 8> Results;
934   if (LegalizeResult)
935     TLI.ReplaceNodeResults(N, Results, DAG);
936   else
937     TLI.LowerOperationWrapper(N, Results, DAG);
938
939   if (Results.empty())
940     // The target didn't want to custom lower it after all.
941     return false;
942
943   // Make everything that once used N's values now use those in Results instead.
944   assert(Results.size() == N->getNumValues() &&
945          "Custom lowering returned the wrong number of results!");
946   for (unsigned i = 0, e = Results.size(); i != e; ++i) {
947     ReplaceValueWith(SDValue(N, i), Results[i]);
948     // Propagate node ordering
949     DAG.AssignOrdering(Results[i].getNode(), DAG.GetOrdering(N));
950   }
951   return true;
952 }
953
954
955 /// CustomWidenLowerNode - Widen the node's results with custom code provided
956 /// by the target and return "true", or do nothing and return "false".
957 bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
958   // See if the target wants to custom lower this node.
959   if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
960     return false;
961
962   SmallVector<SDValue, 8> Results;
963   TLI.ReplaceNodeResults(N, Results, DAG);
964
965   if (Results.empty())
966     // The target didn't want to custom widen lower its result  after all.
967     return false;
968
969   // Update the widening map.
970   assert(Results.size() == N->getNumValues() &&
971          "Custom lowering returned the wrong number of results!");
972   for (unsigned i = 0, e = Results.size(); i != e; ++i)
973     SetWidenedVector(SDValue(N, i), Results[i]);
974   return true;
975 }
976
977 SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
978   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
979     if (i != ResNo)
980       ReplaceValueWith(SDValue(N, i), SDValue(N->getOperand(i)));
981   return SDValue(N->getOperand(ResNo));
982 }
983
984 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
985 /// which is split into two not necessarily identical pieces.
986 void DAGTypeLegalizer::GetSplitDestVTs(EVT InVT, EVT &LoVT, EVT &HiVT) {
987   // Currently all types are split in half.
988   if (!InVT.isVector()) {
989     LoVT = HiVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
990   } else {
991     unsigned NumElements = InVT.getVectorNumElements();
992     assert(!(NumElements & 1) && "Splitting vector, but not in half!");
993     LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
994                                    InVT.getVectorElementType(), NumElements/2);
995   }
996 }
997
998 /// GetPairElements - Use ISD::EXTRACT_ELEMENT nodes to extract the low and
999 /// high parts of the given value.
1000 void DAGTypeLegalizer::GetPairElements(SDValue Pair,
1001                                        SDValue &Lo, SDValue &Hi) {
1002   DebugLoc dl = Pair.getDebugLoc();
1003   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), Pair.getValueType());
1004   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
1005                    DAG.getIntPtrConstant(0));
1006   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
1007                    DAG.getIntPtrConstant(1));
1008 }
1009
1010 SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, EVT EltVT,
1011                                                   SDValue Index) {
1012   DebugLoc dl = Index.getDebugLoc();
1013   // Make sure the index type is big enough to compute in.
1014   if (Index.getValueType().bitsGT(TLI.getPointerTy()))
1015     Index = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Index);
1016   else
1017     Index = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Index);
1018
1019   // Calculate the element offset and add it to the pointer.
1020   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
1021
1022   Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
1023                       DAG.getConstant(EltSize, Index.getValueType()));
1024   return DAG.getNode(ISD::ADD, dl, Index.getValueType(), Index, VecPtr);
1025 }
1026
1027 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
1028 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
1029   // Arbitrarily use dlHi for result DebugLoc
1030   DebugLoc dlHi = Hi.getDebugLoc();
1031   DebugLoc dlLo = Lo.getDebugLoc();
1032   EVT LVT = Lo.getValueType();
1033   EVT HVT = Hi.getValueType();
1034   EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1035                               LVT.getSizeInBits() + HVT.getSizeInBits());
1036
1037   Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
1038   Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
1039   Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
1040                    DAG.getConstant(LVT.getSizeInBits(), TLI.getPointerTy()));
1041   return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
1042 }
1043
1044 /// LibCallify - Convert the node into a libcall with the same prototype.
1045 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
1046                                      bool isSigned) {
1047   unsigned NumOps = N->getNumOperands();
1048   DebugLoc dl = N->getDebugLoc();
1049   if (NumOps == 0) {
1050     return TLI.makeLibCall(DAG, LC, N->getValueType(0), 0, 0, isSigned, dl);
1051   } else if (NumOps == 1) {
1052     SDValue Op = N->getOperand(0);
1053     return TLI.makeLibCall(DAG, LC, N->getValueType(0), &Op, 1, isSigned, dl);
1054   } else if (NumOps == 2) {
1055     SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1056     return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, 2, isSigned, dl);
1057   }
1058   SmallVector<SDValue, 8> Ops(NumOps);
1059   for (unsigned i = 0; i < NumOps; ++i)
1060     Ops[i] = N->getOperand(i);
1061
1062   return TLI.makeLibCall(DAG, LC, N->getValueType(0),
1063                          &Ops[0], NumOps, isSigned, dl);
1064 }
1065
1066 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
1067 // ExpandLibCall except that the first operand is the in-chain.
1068 std::pair<SDValue, SDValue>
1069 DAGTypeLegalizer::ExpandChainLibCall(RTLIB::Libcall LC,
1070                                          SDNode *Node,
1071                                          bool isSigned) {
1072   SDValue InChain = Node->getOperand(0);
1073
1074   TargetLowering::ArgListTy Args;
1075   TargetLowering::ArgListEntry Entry;
1076   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
1077     EVT ArgVT = Node->getOperand(i).getValueType();
1078     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1079     Entry.Node = Node->getOperand(i);
1080     Entry.Ty = ArgTy;
1081     Entry.isSExt = isSigned;
1082     Entry.isZExt = !isSigned;
1083     Args.push_back(Entry);
1084   }
1085   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1086                                          TLI.getPointerTy());
1087
1088   Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1089   TargetLowering::
1090   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, false,
1091                     0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
1092                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
1093                     Callee, Args, DAG, Node->getDebugLoc());
1094   std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
1095
1096   return CallInfo;
1097 }
1098
1099 /// PromoteTargetBoolean - Promote the given target boolean to a target boolean
1100 /// of the given type.  A target boolean is an integer value, not necessarily of
1101 /// type i1, the bits of which conform to getBooleanContents.
1102 SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT VT) {
1103   DebugLoc dl = Bool.getDebugLoc();
1104   ISD::NodeType ExtendCode =
1105     TargetLowering::getExtendForContent(TLI.getBooleanContents(VT.isVector()));
1106   return DAG.getNode(ExtendCode, dl, VT, Bool);
1107 }
1108
1109 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
1110 /// bits in Hi.
1111 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1112                                     EVT LoVT, EVT HiVT,
1113                                     SDValue &Lo, SDValue &Hi) {
1114   DebugLoc dl = Op.getDebugLoc();
1115   assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
1116          Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
1117   Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
1118   Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
1119                    DAG.getConstant(LoVT.getSizeInBits(), TLI.getPointerTy()));
1120   Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
1121 }
1122
1123 /// SplitInteger - Return the lower and upper halves of Op's bits in a value
1124 /// type half the size of Op's.
1125 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1126                                     SDValue &Lo, SDValue &Hi) {
1127   EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(),
1128                                  Op.getValueType().getSizeInBits()/2);
1129   SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
1130 }
1131
1132
1133 //===----------------------------------------------------------------------===//
1134 //  Entry Point
1135 //===----------------------------------------------------------------------===//
1136
1137 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
1138 /// only uses types natively supported by the target.  Returns "true" if it made
1139 /// any changes.
1140 ///
1141 /// Note that this is an involved process that may invalidate pointers into
1142 /// the graph.
1143 bool SelectionDAG::LegalizeTypes() {
1144   return DAGTypeLegalizer(*this).run();
1145 }