1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
16 #include "LegalizeTypes.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Target/TargetData.h"
24 EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden
);
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.
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
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.
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
59 // If a value is mapped by ReplacedValues, then it must have no uses, except
60 // by nodes marked NewNode (see above).
62 // The final node obtained by mapping by ReplacedValues is not marked NewNode.
63 // Note that ReplacedValues should be applied iteratively.
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
);
74 for (unsigned i
= 0, e
= I
->getNumValues(); i
!= e
; ++i
) {
79 if (ReplacedValues
.find(Res
) != ReplacedValues
.end()) {
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();
84 if (UI
.getUse().getResNo() == i
)
85 assert(UI
->getNodeId() == NewNode
&&
86 "Remapped value has non-trivial use!");
88 // Check that the final result of applying ReplacedValues is not
90 SDValue NewVal
= ReplacedValues
[Res
];
91 DenseMap
<SDValue
, SDValue
>::iterator I
= ReplacedValues
.find(NewVal
);
92 while (I
!= ReplacedValues
.end()) {
94 I
= ReplacedValues
.find(NewVal
);
96 assert(NewVal
.getNode()->getNodeId() != NewNode
&&
97 "ReplacedValues maps to a new node!");
99 if (PromotedIntegers
.find(Res
) != PromotedIntegers
.end())
101 if (SoftenedFloats
.find(Res
) != SoftenedFloats
.end())
103 if (ScalarizedVectors
.find(Res
) != ScalarizedVectors
.end())
105 if (ExpandedIntegers
.find(Res
) != ExpandedIntegers
.end())
107 if (ExpandedFloats
.find(Res
) != ExpandedFloats
.end())
109 if (SplitVectors
.find(Res
) != SplitVectors
.end())
111 if (WidenedVectors
.find(Res
) != WidenedVectors
.end())
114 if (I
->getNodeId() != Processed
) {
116 cerr
<< "Unprocessed value in a map!";
119 } else if (isTypeLegal(Res
.getValueType())) {
121 cerr
<< "Value with legal type was transformed!";
126 cerr
<< "Processed value not in any map!";
128 } else if (Mapped
& (Mapped
- 1)) {
129 cerr
<< "Value in multiple maps!";
136 cerr
<< " ReplacedValues";
138 cerr
<< " PromotedIntegers";
140 cerr
<< " SoftenedFloats";
142 cerr
<< " ScalarizedVectors";
144 cerr
<< " ExpandedIntegers";
146 cerr
<< " ExpandedFloats";
148 cerr
<< " SplitVectors";
150 cerr
<< " WidenedVectors";
157 // Checked that NewNodes are only used by other NewNodes.
158 for (unsigned i
= 0, e
= NewNodes
.size(); i
!= e
; ++i
) {
159 SDNode
*N
= NewNodes
[i
];
160 for (SDNode::use_iterator UI
= N
->use_begin(), UE
= N
->use_end();
162 assert(UI
->getNodeId() == NewNode
&& "NewNode used by non-NewNode!");
166 /// run - This is the main entry point for the type legalizer. This does a
167 /// top-down traversal of the dag, legalizing types as it goes. Returns "true"
168 /// if it made any changes.
169 bool DAGTypeLegalizer::run() {
170 bool Changed
= false;
172 // Create a dummy node (which is not added to allnodes), that adds a reference
173 // to the root node, preventing it from being deleted, and tracking any
174 // changes of the root.
175 HandleSDNode
Dummy(DAG
.getRoot());
176 Dummy
.setNodeId(Unanalyzed
);
178 // The root of the dag may dangle to deleted nodes until the type legalizer is
179 // done. Set it to null to avoid confusion.
180 DAG
.setRoot(SDValue());
182 // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
183 // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
185 for (SelectionDAG::allnodes_iterator I
= DAG
.allnodes_begin(),
186 E
= DAG
.allnodes_end(); I
!= E
; ++I
) {
187 if (I
->getNumOperands() == 0) {
188 I
->setNodeId(ReadyToProcess
);
189 Worklist
.push_back(I
);
191 I
->setNodeId(Unanalyzed
);
195 // Now that we have a set of nodes to process, handle them all.
196 while (!Worklist
.empty()) {
198 if (EnableExpensiveChecks
)
200 PerformExpensiveChecks();
202 SDNode
*N
= Worklist
.back();
204 assert(N
->getNodeId() == ReadyToProcess
&&
205 "Node should be ready if on worklist!");
207 if (IgnoreNodeResults(N
))
210 // Scan the values produced by the node, checking to see if any result
211 // types are illegal.
212 for (unsigned i
= 0, NumResults
= N
->getNumValues(); i
< NumResults
; ++i
) {
213 MVT ResultVT
= N
->getValueType(i
);
214 switch (getTypeAction(ResultVT
)) {
216 assert(false && "Unknown action!");
219 // The following calls must take care of *all* of the node's results,
220 // not just the illegal result they were passed (this includes results
221 // with a legal type). Results can be remapped using ReplaceValueWith,
222 // or their promoted/expanded/etc values registered in PromotedIntegers,
223 // ExpandedIntegers etc.
225 PromoteIntegerResult(N
, i
);
229 ExpandIntegerResult(N
, i
);
233 SoftenFloatResult(N
, i
);
237 ExpandFloatResult(N
, i
);
240 case ScalarizeVector
:
241 ScalarizeVectorResult(N
, i
);
245 SplitVectorResult(N
, i
);
249 WidenVectorResult(N
, i
);
256 // Scan the operand list for the node, handling any nodes with operands that
259 unsigned NumOperands
= N
->getNumOperands();
260 bool NeedsReanalyzing
= false;
262 for (i
= 0; i
!= NumOperands
; ++i
) {
263 if (IgnoreNodeResults(N
->getOperand(i
).getNode()))
266 MVT OpVT
= N
->getOperand(i
).getValueType();
267 switch (getTypeAction(OpVT
)) {
269 assert(false && "Unknown action!");
272 // The following calls must either replace all of the node's results
273 // using ReplaceValueWith, and return "false"; or update the node's
274 // operands in place, and return "true".
276 NeedsReanalyzing
= PromoteIntegerOperand(N
, i
);
280 NeedsReanalyzing
= ExpandIntegerOperand(N
, i
);
284 NeedsReanalyzing
= SoftenFloatOperand(N
, i
);
288 NeedsReanalyzing
= ExpandFloatOperand(N
, i
);
291 case ScalarizeVector
:
292 NeedsReanalyzing
= ScalarizeVectorOperand(N
, i
);
296 NeedsReanalyzing
= SplitVectorOperand(N
, i
);
300 NeedsReanalyzing
= WidenVectorOperand(N
, i
);
307 // The sub-method updated N in place. Check to see if any operands are new,
308 // and if so, mark them. If the node needs revisiting, don't add all users
309 // to the worklist etc.
310 if (NeedsReanalyzing
) {
311 assert(N
->getNodeId() == ReadyToProcess
&& "Node ID recalculated?");
312 N
->setNodeId(NewNode
);
313 // Recompute the NodeId and correct processed operands, adding the node to
314 // the worklist if ready.
315 SDNode
*M
= AnalyzeNewNode(N
);
317 // The node didn't morph - nothing special to do, it will be revisited.
320 // The node morphed - this is equivalent to legalizing by replacing every
321 // value of N with the corresponding value of M. So do that now. However
322 // there is no need to remember the replacement - morphing will make sure
323 // it is never used non-trivially.
324 assert(N
->getNumValues() == M
->getNumValues() &&
325 "Node morphing changed the number of results!");
326 for (unsigned i
= 0, e
= N
->getNumValues(); i
!= e
; ++i
)
327 // Replacing the value takes care of remapping the new value. Do the
328 // replacement without recording it in ReplacedValues. This does not
329 // expunge From but that is fine - it is not really a new node.
330 ReplaceValueWithHelper(SDValue(N
, i
), SDValue(M
, i
));
331 assert(N
->getNodeId() == NewNode
&& "Unexpected node state!");
332 // The node continues to live on as part of the NewNode fungus that
333 // grows on top of the useful nodes. Nothing more needs to be done
334 // with it - move on to the next node.
338 if (i
== NumOperands
) {
339 DEBUG(cerr
<< "Legally typed node: "; N
->dump(&DAG
); cerr
<< "\n");
344 // If we reach here, the node was processed, potentially creating new nodes.
345 // Mark it as processed and add its users to the worklist as appropriate.
346 assert(N
->getNodeId() == ReadyToProcess
&& "Node ID recalculated?");
347 N
->setNodeId(Processed
);
349 for (SDNode::use_iterator UI
= N
->use_begin(), E
= N
->use_end();
352 int NodeId
= User
->getNodeId();
354 // This node has two options: it can either be a new node or its Node ID
355 // may be a count of the number of operands it has that are not ready.
357 User
->setNodeId(NodeId
-1);
359 // If this was the last use it was waiting on, add it to the ready list.
360 if (NodeId
-1 == ReadyToProcess
)
361 Worklist
.push_back(User
);
365 // If this is an unreachable new node, then ignore it. If it ever becomes
366 // reachable by being used by a newly created node then it will be handled
367 // by AnalyzeNewNode.
368 if (NodeId
== NewNode
)
371 // Otherwise, this node is new: this is the first operand of it that
372 // became ready. Its new NodeId is the number of operands it has minus 1
373 // (as this node is now processed).
374 assert(NodeId
== Unanalyzed
&& "Unknown node ID!");
375 User
->setNodeId(User
->getNumOperands() - 1);
377 // If the node only has a single operand, it is now ready.
378 if (User
->getNumOperands() == 1)
379 Worklist
.push_back(User
);
384 if (EnableExpensiveChecks
)
386 PerformExpensiveChecks();
388 // If the root changed (e.g. it was a dead load) update the root.
389 DAG
.setRoot(Dummy
.getValue());
391 // Remove dead nodes. This is important to do for cleanliness but also before
392 // the checking loop below. Implicit folding by the DAG.getNode operators and
393 // node morphing can cause unreachable nodes to be around with their flags set
395 DAG
.RemoveDeadNodes();
397 // In a debug build, scan all the nodes to make sure we found them all. This
398 // ensures that there are no cycles and that everything got processed.
400 for (SelectionDAG::allnodes_iterator I
= DAG
.allnodes_begin(),
401 E
= DAG
.allnodes_end(); I
!= E
; ++I
) {
404 // Check that all result types are legal.
405 if (!IgnoreNodeResults(I
))
406 for (unsigned i
= 0, NumVals
= I
->getNumValues(); i
< NumVals
; ++i
)
407 if (!isTypeLegal(I
->getValueType(i
))) {
408 cerr
<< "Result type " << i
<< " illegal!\n";
412 // Check that all operand types are legal.
413 for (unsigned i
= 0, NumOps
= I
->getNumOperands(); i
< NumOps
; ++i
)
414 if (!IgnoreNodeResults(I
->getOperand(i
).getNode()) &&
415 !isTypeLegal(I
->getOperand(i
).getValueType())) {
416 cerr
<< "Operand type " << i
<< " illegal!\n";
420 if (I
->getNodeId() != Processed
) {
421 if (I
->getNodeId() == NewNode
)
422 cerr
<< "New node not analyzed?\n";
423 else if (I
->getNodeId() == Unanalyzed
)
424 cerr
<< "Unanalyzed node not noticed?\n";
425 else if (I
->getNodeId() > 0)
426 cerr
<< "Operand not processed?\n";
427 else if (I
->getNodeId() == ReadyToProcess
)
428 cerr
<< "Not added to worklist?\n";
433 I
->dump(&DAG
); cerr
<< "\n";
442 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
443 /// new nodes. Correct any processed operands (this may change the node) and
444 /// calculate the NodeId. If the node itself changes to a processed node, it
445 /// is not remapped - the caller needs to take care of this.
446 /// Returns the potentially changed node.
447 SDNode
*DAGTypeLegalizer::AnalyzeNewNode(SDNode
*N
) {
448 // If this was an existing node that is already done, we're done.
449 if (N
->getNodeId() != NewNode
&& N
->getNodeId() != Unanalyzed
)
452 // Remove any stale map entries.
455 // Okay, we know that this node is new. Recursively walk all of its operands
456 // to see if they are new also. The depth of this walk is bounded by the size
457 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
458 // about revisiting of nodes.
460 // As we walk the operands, keep track of the number of nodes that are
461 // processed. If non-zero, this will become the new nodeid of this node.
462 // Operands may morph when they are analyzed. If so, the node will be
463 // updated after all operands have been analyzed. Since this is rare,
464 // the code tries to minimize overhead in the non-morphing case.
466 SmallVector
<SDValue
, 8> NewOps
;
467 unsigned NumProcessed
= 0;
468 for (unsigned i
= 0, e
= N
->getNumOperands(); i
!= e
; ++i
) {
469 SDValue OrigOp
= N
->getOperand(i
);
472 AnalyzeNewValue(Op
); // Op may morph.
474 if (Op
.getNode()->getNodeId() == Processed
)
477 if (!NewOps
.empty()) {
478 // Some previous operand changed. Add this one to the list.
479 NewOps
.push_back(Op
);
480 } else if (Op
!= OrigOp
) {
481 // This is the first operand to change - add all operands so far.
482 for (unsigned j
= 0; j
< i
; ++j
)
483 NewOps
.push_back(N
->getOperand(j
));
484 NewOps
.push_back(Op
);
488 // Some operands changed - update the node.
489 if (!NewOps
.empty()) {
490 SDNode
*M
= DAG
.UpdateNodeOperands(SDValue(N
, 0), &NewOps
[0],
491 NewOps
.size()).getNode();
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.
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
511 // Calculate the NodeId.
512 N
->setNodeId(N
->getNumOperands() - NumProcessed
);
513 if (N
->getNodeId() == ReadyToProcess
)
514 Worklist
.push_back(N
);
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.
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
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
)
545 // If N is not remapped by ReplacedValues then there is nothing to do.
547 for (i
= 0, e
= N
->getNumValues(); i
!= e
; ++i
)
548 if (ReplacedValues
.find(SDValue(N
, i
)) != ReplacedValues
.end())
554 // Remove N from all maps - this is expensive but rare.
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
);
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
);
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
);
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
);
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
);
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
);
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
);
601 for (DenseMap
<SDValue
, SDValue
>::iterator I
= ReplacedValues
.begin(),
602 E
= ReplacedValues
.end(); I
!= E
; ++I
)
603 RemapValue(I
->second
);
605 for (unsigned i
= 0, e
= N
->getNumValues(); i
!= e
; ++i
)
606 ReplacedValues
.erase(SDValue(N
, i
));
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
);
618 assert(N
.getNode()->getNodeId() != NewNode
&& "Mapped to new node!");
623 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
624 /// updates to nodes and recomputes their ready state.
625 class VISIBILITY_HIDDEN NodeUpdateListener
:
626 public SelectionDAG::DAGUpdateListener
{
627 DAGTypeLegalizer
&DTL
;
628 SmallSetVector
<SDNode
*, 16> &NodesToAnalyze
;
630 explicit NodeUpdateListener(DAGTypeLegalizer
&dtl
,
631 SmallSetVector
<SDNode
*, 16> &nta
)
632 : DTL(dtl
), NodesToAnalyze(nta
) {}
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
);
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
);
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
);
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
);
669 /// ReplaceValueWithHelper - Internal helper for ReplaceValueWith. Updates the
670 /// DAG causing any uses of From to use To instead, but without expunging From
671 /// or recording the replacement in ReplacedValues. Do not call directly unless
672 /// you really know what you are doing!
673 void DAGTypeLegalizer::ReplaceValueWithHelper(SDValue From
, SDValue To
) {
674 assert(From
.getNode() != To
.getNode() && "Potential legalization loop!");
676 // If expansion produced new nodes, make sure they are properly marked.
677 AnalyzeNewValue(To
); // Expunges To.
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 DAG
.ReplaceAllUsesOfValueWith(From
, To
, &NUL
);
685 // Process the list of nodes that need to be reanalyzed.
686 while (!NodesToAnalyze
.empty()) {
687 SDNode
*N
= NodesToAnalyze
.back();
688 NodesToAnalyze
.pop_back();
689 if (N
->getNodeId() != DAGTypeLegalizer::NewNode
)
690 // The node was analyzed while reanalyzing an earlier node - it is safe to
691 // skip. Note that this is not a morphing node - otherwise it would still
692 // be marked NewNode.
695 // Analyze the node's operands and recalculate the node ID.
696 SDNode
*M
= AnalyzeNewNode(N
);
698 // The node morphed into a different node. Make everyone use the new node
700 assert(M
->getNodeId() != NewNode
&& "Analysis resulted in NewNode!");
701 assert(N
->getNumValues() == M
->getNumValues() &&
702 "Node morphing changed the number of results!");
703 for (unsigned i
= 0, e
= N
->getNumValues(); i
!= e
; ++i
) {
704 SDValue
OldVal(N
, i
);
705 SDValue
NewVal(M
, i
);
706 if (M
->getNodeId() == Processed
)
708 DAG
.ReplaceAllUsesOfValueWith(OldVal
, NewVal
, &NUL
);
710 // The original node continues to exist in the DAG, marked NewNode.
715 /// ReplaceValueWith - The specified value was legalized to the specified other
716 /// value. Update the DAG and NodeIds replacing any uses of From to use To
718 void DAGTypeLegalizer::ReplaceValueWith(SDValue From
, SDValue To
) {
719 assert(From
.getNode()->getNodeId() == ReadyToProcess
&&
720 "Only the node being processed may be remapped!");
722 // If expansion produced new nodes, make sure they are properly marked.
723 ExpungeNode(From
.getNode());
724 AnalyzeNewValue(To
); // Expunges To.
726 // The old node may still be present in a map like ExpandedIntegers or
727 // PromotedIntegers. Inform maps about the replacement.
728 ReplacedValues
[From
] = To
;
730 // Do the replacement.
731 ReplaceValueWithHelper(From
, To
);
734 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op
, SDValue Result
) {
735 AnalyzeNewValue(Result
);
737 SDValue
&OpEntry
= PromotedIntegers
[Op
];
738 assert(OpEntry
.getNode() == 0 && "Node is already promoted!");
742 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op
, SDValue Result
) {
743 AnalyzeNewValue(Result
);
745 SDValue
&OpEntry
= SoftenedFloats
[Op
];
746 assert(OpEntry
.getNode() == 0 && "Node is already converted to integer!");
750 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op
, SDValue Result
) {
751 AnalyzeNewValue(Result
);
753 SDValue
&OpEntry
= ScalarizedVectors
[Op
];
754 assert(OpEntry
.getNode() == 0 && "Node is already scalarized!");
758 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op
, SDValue
&Lo
,
760 std::pair
<SDValue
, SDValue
> &Entry
= ExpandedIntegers
[Op
];
761 RemapValue(Entry
.first
);
762 RemapValue(Entry
.second
);
763 assert(Entry
.first
.getNode() && "Operand isn't expanded");
768 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op
, SDValue Lo
,
770 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
774 // Remember that this is the result of the node.
775 std::pair
<SDValue
, SDValue
> &Entry
= ExpandedIntegers
[Op
];
776 assert(Entry
.first
.getNode() == 0 && "Node already expanded");
781 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op
, SDValue
&Lo
,
783 std::pair
<SDValue
, SDValue
> &Entry
= ExpandedFloats
[Op
];
784 RemapValue(Entry
.first
);
785 RemapValue(Entry
.second
);
786 assert(Entry
.first
.getNode() && "Operand isn't expanded");
791 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op
, SDValue Lo
,
793 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
797 // Remember that this is the result of the node.
798 std::pair
<SDValue
, SDValue
> &Entry
= ExpandedFloats
[Op
];
799 assert(Entry
.first
.getNode() == 0 && "Node already expanded");
804 void DAGTypeLegalizer::GetSplitVector(SDValue Op
, SDValue
&Lo
,
806 std::pair
<SDValue
, SDValue
> &Entry
= SplitVectors
[Op
];
807 RemapValue(Entry
.first
);
808 RemapValue(Entry
.second
);
809 assert(Entry
.first
.getNode() && "Operand isn't split");
814 void DAGTypeLegalizer::SetSplitVector(SDValue Op
, SDValue Lo
,
816 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
820 // Remember that this is the result of the node.
821 std::pair
<SDValue
, SDValue
> &Entry
= SplitVectors
[Op
];
822 assert(Entry
.first
.getNode() == 0 && "Node already split");
827 void DAGTypeLegalizer::SetWidenedVector(SDValue Op
, SDValue Result
) {
828 AnalyzeNewValue(Result
);
830 SDValue
&OpEntry
= WidenedVectors
[Op
];
831 assert(OpEntry
.getNode() == 0 && "Node already widened!");
836 //===----------------------------------------------------------------------===//
838 //===----------------------------------------------------------------------===//
840 /// BitConvertToInteger - Convert to an integer of the same size.
841 SDValue
DAGTypeLegalizer::BitConvertToInteger(SDValue Op
) {
842 unsigned BitWidth
= Op
.getValueType().getSizeInBits();
843 return DAG
.getNode(ISD::BIT_CONVERT
, Op
.getDebugLoc(),
844 MVT::getIntegerVT(BitWidth
), Op
);
847 /// BitConvertVectorToIntegerVector - Convert to a vector of integers of the
849 SDValue
DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op
) {
850 assert(Op
.getValueType().isVector() && "Only applies to vectors!");
851 unsigned EltWidth
= Op
.getValueType().getVectorElementType().getSizeInBits();
852 MVT EltNVT
= MVT::getIntegerVT(EltWidth
);
853 unsigned NumElts
= Op
.getValueType().getVectorNumElements();
854 return DAG
.getNode(ISD::BIT_CONVERT
, Op
.getDebugLoc(),
855 MVT::getVectorVT(EltNVT
, NumElts
), Op
);
858 SDValue
DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op
,
860 DebugLoc dl
= Op
.getDebugLoc();
861 // Create the stack frame object. Make sure it is aligned for both
862 // the source and destination types.
863 SDValue StackPtr
= DAG
.CreateStackTemporary(Op
.getValueType(), DestVT
);
864 // Emit a store to the stack slot.
865 SDValue Store
= DAG
.getStore(DAG
.getEntryNode(), dl
, Op
, StackPtr
, NULL
, 0);
866 // Result is a load from the stack slot.
867 return DAG
.getLoad(DestVT
, dl
, Store
, StackPtr
, NULL
, 0);
870 /// CustomLowerResults - Replace the node's results with custom code provided
871 /// by the target and return "true", or do nothing and return "false".
872 /// The last parameter is FALSE if we are dealing with a node with legal
873 /// result types and illegal operand. The second parameter denotes the type of
874 /// illegal OperandNo in that case.
875 /// The last parameter being TRUE means we are dealing with a
876 /// node with illegal result types. The second parameter denotes the type of
877 /// illegal ResNo in that case.
878 bool DAGTypeLegalizer::CustomLowerResults(SDNode
*N
, MVT VT
,
879 bool LegalizeResult
) {
880 // See if the target wants to custom lower this node.
881 if (TLI
.getOperationAction(N
->getOpcode(), VT
) != TargetLowering::Custom
)
884 SmallVector
<SDValue
, 8> Results
;
886 TLI
.ReplaceNodeResults(N
, Results
, DAG
);
888 TLI
.LowerOperationWrapper(N
, Results
, DAG
);
891 // The target didn't want to custom lower it after all.
894 // Make everything that once used N's values now use those in Results instead.
895 assert(Results
.size() == N
->getNumValues() &&
896 "Custom lowering returned the wrong number of results!");
897 for (unsigned i
= 0, e
= Results
.size(); i
!= e
; ++i
)
898 ReplaceValueWith(SDValue(N
, i
), Results
[i
]);
902 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
903 /// which is split into two not necessarily identical pieces.
904 void DAGTypeLegalizer::GetSplitDestVTs(MVT InVT
, MVT
&LoVT
, MVT
&HiVT
) {
905 if (!InVT
.isVector()) {
906 LoVT
= HiVT
= TLI
.getTypeToTransformTo(InVT
);
908 MVT NewEltVT
= InVT
.getVectorElementType();
909 unsigned NumElements
= InVT
.getVectorNumElements();
910 if ((NumElements
& (NumElements
-1)) == 0) { // Simple power of two vector.
912 LoVT
= HiVT
= MVT::getVectorVT(NewEltVT
, NumElements
);
913 } else { // Non-power-of-two vectors.
914 unsigned NewNumElts_Lo
= 1 << Log2_32(NumElements
);
915 unsigned NewNumElts_Hi
= NumElements
- NewNumElts_Lo
;
916 LoVT
= MVT::getVectorVT(NewEltVT
, NewNumElts_Lo
);
917 HiVT
= MVT::getVectorVT(NewEltVT
, NewNumElts_Hi
);
922 /// GetPairElements - Use ISD::EXTRACT_ELEMENT nodes to extract the low and
923 /// high parts of the given value.
924 void DAGTypeLegalizer::GetPairElements(SDValue Pair
,
925 SDValue
&Lo
, SDValue
&Hi
) {
926 DebugLoc dl
= Pair
.getDebugLoc();
927 MVT NVT
= TLI
.getTypeToTransformTo(Pair
.getValueType());
928 Lo
= DAG
.getNode(ISD::EXTRACT_ELEMENT
, dl
, NVT
, Pair
,
929 DAG
.getIntPtrConstant(0));
930 Hi
= DAG
.getNode(ISD::EXTRACT_ELEMENT
, dl
, NVT
, Pair
,
931 DAG
.getIntPtrConstant(1));
934 SDValue
DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr
, MVT EltVT
,
936 DebugLoc dl
= Index
.getDebugLoc();
937 // Make sure the index type is big enough to compute in.
938 if (Index
.getValueType().bitsGT(TLI
.getPointerTy()))
939 Index
= DAG
.getNode(ISD::TRUNCATE
, dl
, TLI
.getPointerTy(), Index
);
941 Index
= DAG
.getNode(ISD::ZERO_EXTEND
, dl
, TLI
.getPointerTy(), Index
);
943 // Calculate the element offset and add it to the pointer.
944 unsigned EltSize
= EltVT
.getSizeInBits() / 8; // FIXME: should be ABI size.
946 Index
= DAG
.getNode(ISD::MUL
, dl
, Index
.getValueType(), Index
,
947 DAG
.getConstant(EltSize
, Index
.getValueType()));
948 return DAG
.getNode(ISD::ADD
, dl
, Index
.getValueType(), Index
, VecPtr
);
951 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
952 SDValue
DAGTypeLegalizer::JoinIntegers(SDValue Lo
, SDValue Hi
) {
953 // Arbitrarily use dlHi for result DebugLoc
954 DebugLoc dlHi
= Hi
.getDebugLoc();
955 DebugLoc dlLo
= Lo
.getDebugLoc();
956 MVT LVT
= Lo
.getValueType();
957 MVT HVT
= Hi
.getValueType();
958 MVT NVT
= MVT::getIntegerVT(LVT
.getSizeInBits() + HVT
.getSizeInBits());
960 Lo
= DAG
.getNode(ISD::ZERO_EXTEND
, dlLo
, NVT
, Lo
);
961 Hi
= DAG
.getNode(ISD::ANY_EXTEND
, dlHi
, NVT
, Hi
);
962 Hi
= DAG
.getNode(ISD::SHL
, dlHi
, NVT
, Hi
,
963 DAG
.getConstant(LVT
.getSizeInBits(), TLI
.getPointerTy()));
964 return DAG
.getNode(ISD::OR
, dlHi
, NVT
, Lo
, Hi
);
967 /// LibCallify - Convert the node into a libcall with the same prototype.
968 SDValue
DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC
, SDNode
*N
,
970 unsigned NumOps
= N
->getNumOperands();
971 DebugLoc dl
= N
->getDebugLoc();
973 return MakeLibCall(LC
, N
->getValueType(0), 0, 0, isSigned
, dl
);
974 } else if (NumOps
== 1) {
975 SDValue Op
= N
->getOperand(0);
976 return MakeLibCall(LC
, N
->getValueType(0), &Op
, 1, isSigned
, dl
);
977 } else if (NumOps
== 2) {
978 SDValue Ops
[2] = { N
->getOperand(0), N
->getOperand(1) };
979 return MakeLibCall(LC
, N
->getValueType(0), Ops
, 2, isSigned
, dl
);
981 SmallVector
<SDValue
, 8> Ops(NumOps
);
982 for (unsigned i
= 0; i
< NumOps
; ++i
)
983 Ops
[i
] = N
->getOperand(i
);
985 return MakeLibCall(LC
, N
->getValueType(0), &Ops
[0], NumOps
, isSigned
, dl
);
988 /// MakeLibCall - Generate a libcall taking the given operands as arguments and
989 /// returning a result of type RetVT.
990 SDValue
DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC
, MVT RetVT
,
991 const SDValue
*Ops
, unsigned NumOps
,
992 bool isSigned
, DebugLoc dl
) {
993 TargetLowering::ArgListTy Args
;
994 Args
.reserve(NumOps
);
996 TargetLowering::ArgListEntry Entry
;
997 for (unsigned i
= 0; i
!= NumOps
; ++i
) {
999 Entry
.Ty
= Entry
.Node
.getValueType().getTypeForMVT();
1000 Entry
.isSExt
= isSigned
;
1001 Entry
.isZExt
= !isSigned
;
1002 Args
.push_back(Entry
);
1004 SDValue Callee
= DAG
.getExternalSymbol(TLI
.getLibcallName(LC
),
1005 TLI
.getPointerTy());
1007 const Type
*RetTy
= RetVT
.getTypeForMVT();
1008 std::pair
<SDValue
,SDValue
> CallInfo
=
1009 TLI
.LowerCallTo(DAG
.getEntryNode(), RetTy
, isSigned
, !isSigned
, false,
1010 false, CallingConv::C
, false, Callee
, Args
, DAG
, dl
);
1011 return CallInfo
.first
;
1014 /// PromoteTargetBoolean - Promote the given target boolean to a target boolean
1015 /// of the given type. A target boolean is an integer value, not necessarily of
1016 /// type i1, the bits of which conform to getBooleanContents.
1017 SDValue
DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool
, MVT VT
) {
1018 DebugLoc dl
= Bool
.getDebugLoc();
1019 ISD::NodeType ExtendCode
;
1020 switch (TLI
.getBooleanContents()) {
1022 assert(false && "Unknown BooleanContent!");
1023 case TargetLowering::UndefinedBooleanContent
:
1024 // Extend to VT by adding rubbish bits.
1025 ExtendCode
= ISD::ANY_EXTEND
;
1027 case TargetLowering::ZeroOrOneBooleanContent
:
1028 // Extend to VT by adding zero bits.
1029 ExtendCode
= ISD::ZERO_EXTEND
;
1031 case TargetLowering::ZeroOrNegativeOneBooleanContent
: {
1032 // Extend to VT by copying the sign bit.
1033 ExtendCode
= ISD::SIGN_EXTEND
;
1037 return DAG
.getNode(ExtendCode
, dl
, VT
, Bool
);
1040 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
1042 void DAGTypeLegalizer::SplitInteger(SDValue Op
,
1044 SDValue
&Lo
, SDValue
&Hi
) {
1045 DebugLoc dl
= Op
.getDebugLoc();
1046 assert(LoVT
.getSizeInBits() + HiVT
.getSizeInBits() ==
1047 Op
.getValueType().getSizeInBits() && "Invalid integer splitting!");
1048 Lo
= DAG
.getNode(ISD::TRUNCATE
, dl
, LoVT
, Op
);
1049 Hi
= DAG
.getNode(ISD::SRL
, dl
, Op
.getValueType(), Op
,
1050 DAG
.getConstant(LoVT
.getSizeInBits(), TLI
.getPointerTy()));
1051 Hi
= DAG
.getNode(ISD::TRUNCATE
, dl
, HiVT
, Hi
);
1054 /// SplitInteger - Return the lower and upper halves of Op's bits in a value
1055 /// type half the size of Op's.
1056 void DAGTypeLegalizer::SplitInteger(SDValue Op
,
1057 SDValue
&Lo
, SDValue
&Hi
) {
1058 MVT HalfVT
= MVT::getIntegerVT(Op
.getValueType().getSizeInBits()/2);
1059 SplitInteger(Op
, HalfVT
, HalfVT
, Lo
, Hi
);
1063 //===----------------------------------------------------------------------===//
1065 //===----------------------------------------------------------------------===//
1067 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
1068 /// only uses types natively supported by the target. Returns "true" if it made
1071 /// Note that this is an involved process that may invalidate pointers into
1073 bool SelectionDAG::LegalizeTypes() {
1074 return DAGTypeLegalizer(*this).run();