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