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/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"
25 #define DEBUG_TYPE "legalize-types"
28 EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
30 /// PerformExpensiveChecks - Do extensive, expensive, sanity checking.
31 void DAGTypeLegalizer::PerformExpensiveChecks() {
32 // If a node is not processed, then none of its values should be mapped by any
33 // of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
35 // If a node is processed, then each value with an illegal type must be mapped
36 // by exactly one of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
37 // Values with a legal type may be mapped by ReplacedValues, but not by any of
40 // Note that these invariants may not hold momentarily when processing a node:
41 // the node being processed may be put in a map before being marked Processed.
43 // Note that it is possible to have nodes marked NewNode in the DAG. This can
44 // occur in two ways. Firstly, a node may be created during legalization but
45 // never passed to the legalization core. This is usually due to the implicit
46 // folding that occurs when using the DAG.getNode operators. Secondly, a new
47 // node may be passed to the legalization core, but when analyzed may morph
48 // into a different node, leaving the original node as a NewNode in the DAG.
49 // A node may morph if one of its operands changes during analysis. Whether
50 // it actually morphs or not depends on whether, after updating its operands,
51 // it is equivalent to an existing node: if so, it morphs into that existing
52 // node (CSE). An operand can change during analysis if the operand is a new
53 // node that morphs, or it is a processed value that was mapped to some other
54 // value (as recorded in ReplacedValues) in which case the operand is turned
55 // into that other value. If a node morphs then the node it morphed into will
56 // be used instead of it for legalization, however the original node continues
57 // to live on in the DAG.
58 // The conclusion is that though there may be nodes marked NewNode in the DAG,
59 // all uses of such nodes are also marked NewNode: the result is a fungus of
60 // NewNodes growing on top of the useful nodes, and perhaps using them, but
63 // If a value is mapped by ReplacedValues, then it must have no uses, except
64 // by nodes marked NewNode (see above).
66 // The final node obtained by mapping by ReplacedValues is not marked NewNode.
67 // Note that ReplacedValues should be applied iteratively.
69 // Note that the ReplacedValues map may also map deleted nodes (by iterating
70 // over the DAG we never dereference deleted nodes). This means that it may
71 // also map nodes marked NewNode if the deallocated memory was reallocated as
72 // another node, and that new node was not seen by the LegalizeTypes machinery
73 // (for example because it was created but not used). In general, we cannot
74 // distinguish between new nodes and deleted nodes.
75 SmallVector<SDNode*, 16> NewNodes;
76 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
77 E = DAG.allnodes_end(); I != E; ++I) {
78 // Remember nodes marked NewNode - they are subject to extra checking below.
79 if (I->getNodeId() == NewNode)
80 NewNodes.push_back(I);
82 for (unsigned i = 0, e = I->getNumValues(); i != e; ++i) {
87 if (ReplacedValues.find(Res) != ReplacedValues.end()) {
89 // Check that remapped values are only used by nodes marked NewNode.
90 for (SDNode::use_iterator UI = I->use_begin(), UE = I->use_end();
92 if (UI.getUse().getResNo() == i)
93 assert(UI->getNodeId() == NewNode &&
94 "Remapped value has non-trivial use!");
96 // Check that the final result of applying ReplacedValues is not
98 SDValue NewVal = ReplacedValues[Res];
99 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal);
100 while (I != ReplacedValues.end()) {
102 I = ReplacedValues.find(NewVal);
104 assert(NewVal.getNode()->getNodeId() != NewNode &&
105 "ReplacedValues maps to a new node!");
107 if (PromotedIntegers.find(Res) != PromotedIntegers.end())
109 if (SoftenedFloats.find(Res) != SoftenedFloats.end())
111 if (ScalarizedVectors.find(Res) != ScalarizedVectors.end())
113 if (ExpandedIntegers.find(Res) != ExpandedIntegers.end())
115 if (ExpandedFloats.find(Res) != ExpandedFloats.end())
117 if (SplitVectors.find(Res) != SplitVectors.end())
119 if (WidenedVectors.find(Res) != WidenedVectors.end())
122 if (I->getNodeId() != Processed) {
123 // Since we allow ReplacedValues to map deleted nodes, it may map nodes
124 // marked NewNode too, since a deleted node may have been reallocated as
125 // another node that has not been seen by the LegalizeTypes machinery.
126 if ((I->getNodeId() == NewNode && Mapped > 1) ||
127 (I->getNodeId() != NewNode && Mapped != 0)) {
128 dbgs() << "Unprocessed value in a map!";
131 } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) {
133 dbgs() << "Value with legal type was transformed!";
138 dbgs() << "Processed value not in any map!";
140 } else if (Mapped & (Mapped - 1)) {
141 dbgs() << "Value in multiple maps!";
148 dbgs() << " ReplacedValues";
150 dbgs() << " PromotedIntegers";
152 dbgs() << " SoftenedFloats";
154 dbgs() << " ScalarizedVectors";
156 dbgs() << " ExpandedIntegers";
158 dbgs() << " ExpandedFloats";
160 dbgs() << " SplitVectors";
162 dbgs() << " WidenedVectors";
164 llvm_unreachable(nullptr);
169 // Checked that NewNodes are only used by other NewNodes.
170 for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
171 SDNode *N = NewNodes[i];
172 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
174 assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
178 /// run - This is the main entry point for the type legalizer. This does a
179 /// top-down traversal of the dag, legalizing types as it goes. Returns "true"
180 /// if it made any changes.
181 bool DAGTypeLegalizer::run() {
182 bool Changed = false;
184 // Create a dummy node (which is not added to allnodes), that adds a reference
185 // to the root node, preventing it from being deleted, and tracking any
186 // changes of the root.
187 HandleSDNode Dummy(DAG.getRoot());
188 Dummy.setNodeId(Unanalyzed);
190 // The root of the dag may dangle to deleted nodes until the type legalizer is
191 // done. Set it to null to avoid confusion.
192 DAG.setRoot(SDValue());
194 // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
195 // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
197 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
198 E = DAG.allnodes_end(); I != E; ++I) {
199 if (I->getNumOperands() == 0) {
200 I->setNodeId(ReadyToProcess);
201 Worklist.push_back(I);
203 I->setNodeId(Unanalyzed);
207 // Now that we have a set of nodes to process, handle them all.
208 while (!Worklist.empty()) {
210 if (EnableExpensiveChecks)
212 PerformExpensiveChecks();
214 SDNode *N = Worklist.back();
216 assert(N->getNodeId() == ReadyToProcess &&
217 "Node should be ready if on worklist!");
219 if (IgnoreNodeResults(N))
222 // Scan the values produced by the node, checking to see if any result
223 // types are illegal.
224 for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
225 EVT ResultVT = N->getValueType(i);
226 switch (getTypeAction(ResultVT)) {
227 case TargetLowering::TypeLegal:
229 // The following calls must take care of *all* of the node's results,
230 // not just the illegal result they were passed (this includes results
231 // with a legal type). Results can be remapped using ReplaceValueWith,
232 // or their promoted/expanded/etc values registered in PromotedIntegers,
233 // ExpandedIntegers etc.
234 case TargetLowering::TypePromoteInteger:
235 PromoteIntegerResult(N, i);
238 case TargetLowering::TypeExpandInteger:
239 ExpandIntegerResult(N, i);
242 case TargetLowering::TypeSoftenFloat:
243 SoftenFloatResult(N, i);
246 case TargetLowering::TypeExpandFloat:
247 ExpandFloatResult(N, i);
250 case TargetLowering::TypeScalarizeVector:
251 ScalarizeVectorResult(N, i);
254 case TargetLowering::TypeSplitVector:
255 SplitVectorResult(N, i);
258 case TargetLowering::TypeWidenVector:
259 WidenVectorResult(N, i);
266 // Scan the operand list for the node, handling any nodes with operands that
269 unsigned NumOperands = N->getNumOperands();
270 bool NeedsReanalyzing = false;
272 for (i = 0; i != NumOperands; ++i) {
273 if (IgnoreNodeResults(N->getOperand(i).getNode()))
276 EVT OpVT = N->getOperand(i).getValueType();
277 switch (getTypeAction(OpVT)) {
278 case TargetLowering::TypeLegal:
280 // The following calls must either replace all of the node's results
281 // using ReplaceValueWith, and return "false"; or update the node's
282 // operands in place, and return "true".
283 case TargetLowering::TypePromoteInteger:
284 NeedsReanalyzing = PromoteIntegerOperand(N, i);
287 case TargetLowering::TypeExpandInteger:
288 NeedsReanalyzing = ExpandIntegerOperand(N, i);
291 case TargetLowering::TypeSoftenFloat:
292 NeedsReanalyzing = SoftenFloatOperand(N, i);
295 case TargetLowering::TypeExpandFloat:
296 NeedsReanalyzing = ExpandFloatOperand(N, i);
299 case TargetLowering::TypeScalarizeVector:
300 NeedsReanalyzing = ScalarizeVectorOperand(N, i);
303 case TargetLowering::TypeSplitVector:
304 NeedsReanalyzing = SplitVectorOperand(N, i);
307 case TargetLowering::TypeWidenVector:
308 NeedsReanalyzing = WidenVectorOperand(N, i);
315 // The sub-method updated N in place. Check to see if any operands are new,
316 // and if so, mark them. If the node needs revisiting, don't add all users
317 // to the worklist etc.
318 if (NeedsReanalyzing) {
319 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
320 N->setNodeId(NewNode);
321 // Recompute the NodeId and correct processed operands, adding the node to
322 // the worklist if ready.
323 SDNode *M = AnalyzeNewNode(N);
325 // The node didn't morph - nothing special to do, it will be revisited.
328 // The node morphed - this is equivalent to legalizing by replacing every
329 // value of N with the corresponding value of M. So do that now.
330 assert(N->getNumValues() == M->getNumValues() &&
331 "Node morphing changed the number of results!");
332 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
333 // Replacing the value takes care of remapping the new value.
334 ReplaceValueWith(SDValue(N, i), SDValue(M, i));
335 assert(N->getNodeId() == NewNode && "Unexpected node state!");
336 // The node continues to live on as part of the NewNode fungus that
337 // grows on top of the useful nodes. Nothing more needs to be done
338 // with it - move on to the next node.
342 if (i == NumOperands) {
343 DEBUG(dbgs() << "Legally typed node: "; N->dump(&DAG); dbgs() << "\n");
348 // If we reach here, the node was processed, potentially creating new nodes.
349 // Mark it as processed and add its users to the worklist as appropriate.
350 assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
351 N->setNodeId(Processed);
353 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
356 int NodeId = User->getNodeId();
358 // This node has two options: it can either be a new node or its Node ID
359 // may be a count of the number of operands it has that are not ready.
361 User->setNodeId(NodeId-1);
363 // If this was the last use it was waiting on, add it to the ready list.
364 if (NodeId-1 == ReadyToProcess)
365 Worklist.push_back(User);
369 // If this is an unreachable new node, then ignore it. If it ever becomes
370 // reachable by being used by a newly created node then it will be handled
371 // by AnalyzeNewNode.
372 if (NodeId == NewNode)
375 // Otherwise, this node is new: this is the first operand of it that
376 // became ready. Its new NodeId is the number of operands it has minus 1
377 // (as this node is now processed).
378 assert(NodeId == Unanalyzed && "Unknown node ID!");
379 User->setNodeId(User->getNumOperands() - 1);
381 // If the node only has a single operand, it is now ready.
382 if (User->getNumOperands() == 1)
383 Worklist.push_back(User);
388 if (EnableExpensiveChecks)
390 PerformExpensiveChecks();
392 // If the root changed (e.g. it was a dead load) update the root.
393 DAG.setRoot(Dummy.getValue());
395 // Remove dead nodes. This is important to do for cleanliness but also before
396 // the checking loop below. Implicit folding by the DAG.getNode operators and
397 // node morphing can cause unreachable nodes to be around with their flags set
399 DAG.RemoveDeadNodes();
401 // In a debug build, scan all the nodes to make sure we found them all. This
402 // ensures that there are no cycles and that everything got processed.
404 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
405 E = DAG.allnodes_end(); I != E; ++I) {
408 // Check that all result types are legal.
409 if (!IgnoreNodeResults(I))
410 for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
411 if (!isTypeLegal(I->getValueType(i))) {
412 dbgs() << "Result type " << i << " illegal!\n";
416 // Check that all operand types are legal.
417 for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
418 if (!IgnoreNodeResults(I->getOperand(i).getNode()) &&
419 !isTypeLegal(I->getOperand(i).getValueType())) {
420 dbgs() << "Operand type " << i << " illegal!\n";
424 if (I->getNodeId() != Processed) {
425 if (I->getNodeId() == NewNode)
426 dbgs() << "New node not analyzed?\n";
427 else if (I->getNodeId() == Unanalyzed)
428 dbgs() << "Unanalyzed node not noticed?\n";
429 else if (I->getNodeId() > 0)
430 dbgs() << "Operand not processed?\n";
431 else if (I->getNodeId() == ReadyToProcess)
432 dbgs() << "Not added to worklist?\n";
437 I->dump(&DAG); dbgs() << "\n";
438 llvm_unreachable(nullptr);
446 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
447 /// new nodes. Correct any processed operands (this may change the node) and
448 /// calculate the NodeId. If the node itself changes to a processed node, it
449 /// is not remapped - the caller needs to take care of this.
450 /// Returns the potentially changed node.
451 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
452 // If this was an existing node that is already done, we're done.
453 if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
456 // Remove any stale map entries.
459 // Okay, we know that this node is new. Recursively walk all of its operands
460 // to see if they are new also. The depth of this walk is bounded by the size
461 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
462 // about revisiting of nodes.
464 // As we walk the operands, keep track of the number of nodes that are
465 // processed. If non-zero, this will become the new nodeid of this node.
466 // Operands may morph when they are analyzed. If so, the node will be
467 // updated after all operands have been analyzed. Since this is rare,
468 // the code tries to minimize overhead in the non-morphing case.
470 SmallVector<SDValue, 8> NewOps;
471 unsigned NumProcessed = 0;
472 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
473 SDValue OrigOp = N->getOperand(i);
476 AnalyzeNewValue(Op); // Op may morph.
478 if (Op.getNode()->getNodeId() == Processed)
481 if (!NewOps.empty()) {
482 // Some previous operand changed. Add this one to the list.
483 NewOps.push_back(Op);
484 } else if (Op != OrigOp) {
485 // This is the first operand to change - add all operands so far.
486 NewOps.append(N->op_begin(), N->op_begin() + i);
487 NewOps.push_back(Op);
491 // Some operands changed - update the node.
492 if (!NewOps.empty()) {
493 SDNode *M = DAG.UpdateNodeOperands(N, NewOps);
495 // The node morphed into a different node. Normally for this to happen
496 // the original node would have to be marked NewNode. However this can
497 // in theory momentarily not be the case while ReplaceValueWith is doing
498 // its stuff. Mark the original node NewNode to help sanity checking.
499 N->setNodeId(NewNode);
500 if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
501 // It morphed into a previously analyzed node - nothing more to do.
504 // It morphed into a different new node. Do the equivalent of passing
505 // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need
506 // to remap the operands, since they are the same as the operands we
513 // Calculate the NodeId.
514 N->setNodeId(N->getNumOperands() - NumProcessed);
515 if (N->getNodeId() == ReadyToProcess)
516 Worklist.push_back(N);
521 /// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed.
522 /// If the node changes to a processed node, then remap it.
523 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
524 Val.setNode(AnalyzeNewNode(Val.getNode()));
525 if (Val.getNode()->getNodeId() == Processed)
526 // We were passed a processed node, or it morphed into one - remap it.
530 /// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it.
531 /// This can occur when a node is deleted then reallocated as a new node -
532 /// the mapping in ReplacedValues applies to the deleted node, not the new
534 /// The only map that can have a deleted node as a source is ReplacedValues.
535 /// Other maps can have deleted nodes as targets, but since their looked-up
536 /// values are always immediately remapped using RemapValue, resulting in a
537 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
538 /// always performs correct mappings. In order to keep the mapping correct,
539 /// ExpungeNode should be called on any new nodes *before* adding them as
540 /// either source or target to ReplacedValues (which typically means calling
541 /// Expunge when a new node is first seen, since it may no longer be marked
542 /// NewNode by the time it is added to ReplacedValues).
543 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
544 if (N->getNodeId() != NewNode)
547 // If N is not remapped by ReplacedValues then there is nothing to do.
549 for (i = 0, e = N->getNumValues(); i != e; ++i)
550 if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
556 // Remove N from all maps - this is expensive but rare.
558 for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
559 E = PromotedIntegers.end(); I != E; ++I) {
560 assert(I->first.getNode() != N);
561 RemapValue(I->second);
564 for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
565 E = SoftenedFloats.end(); I != E; ++I) {
566 assert(I->first.getNode() != N);
567 RemapValue(I->second);
570 for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
571 E = ScalarizedVectors.end(); I != E; ++I) {
572 assert(I->first.getNode() != N);
573 RemapValue(I->second);
576 for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(),
577 E = WidenedVectors.end(); I != E; ++I) {
578 assert(I->first.getNode() != N);
579 RemapValue(I->second);
582 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
583 I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
584 assert(I->first.getNode() != N);
585 RemapValue(I->second.first);
586 RemapValue(I->second.second);
589 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
590 I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
591 assert(I->first.getNode() != N);
592 RemapValue(I->second.first);
593 RemapValue(I->second.second);
596 for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
597 I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
598 assert(I->first.getNode() != N);
599 RemapValue(I->second.first);
600 RemapValue(I->second.second);
603 for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
604 E = ReplacedValues.end(); I != E; ++I)
605 RemapValue(I->second);
607 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
608 ReplacedValues.erase(SDValue(N, i));
611 /// RemapValue - If the specified value was already legalized to another value,
612 /// replace it by that value.
613 void DAGTypeLegalizer::RemapValue(SDValue &N) {
614 DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
615 if (I != ReplacedValues.end()) {
616 // Use path compression to speed up future lookups if values get multiply
617 // replaced with other values.
618 RemapValue(I->second);
621 // Note that it is possible to have N.getNode()->getNodeId() == NewNode at
622 // this point because it is possible for a node to be put in the map before
628 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
629 /// updates to nodes and recomputes their ready state.
630 class NodeUpdateListener : public SelectionDAG::DAGUpdateListener {
631 DAGTypeLegalizer &DTL;
632 SmallSetVector<SDNode*, 16> &NodesToAnalyze;
634 explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
635 SmallSetVector<SDNode*, 16> &nta)
636 : SelectionDAG::DAGUpdateListener(dtl.getDAG()),
637 DTL(dtl), NodesToAnalyze(nta) {}
639 void NodeDeleted(SDNode *N, SDNode *E) override {
640 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
641 N->getNodeId() != DAGTypeLegalizer::Processed &&
642 "Invalid node ID for RAUW deletion!");
643 // It is possible, though rare, for the deleted node N to occur as a
644 // target in a map, so note the replacement N -> E in ReplacedValues.
645 assert(E && "Node not replaced?");
646 DTL.NoteDeletion(N, E);
648 // In theory the deleted node could also have been scheduled for analysis.
649 // So remove it from the set of nodes which will be analyzed.
650 NodesToAnalyze.remove(N);
652 // In general nothing needs to be done for E, since it didn't change but
653 // only gained new uses. However N -> E was just added to ReplacedValues,
654 // and the result of a ReplacedValues mapping is not allowed to be marked
655 // NewNode. So if E is marked NewNode, then it needs to be analyzed.
656 if (E->getNodeId() == DAGTypeLegalizer::NewNode)
657 NodesToAnalyze.insert(E);
660 void NodeUpdated(SDNode *N) override {
661 // Node updates can mean pretty much anything. It is possible that an
662 // operand was set to something already processed (f.e.) in which case
663 // this node could become ready. Recompute its flags.
664 assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
665 N->getNodeId() != DAGTypeLegalizer::Processed &&
666 "Invalid node ID for RAUW deletion!");
667 N->setNodeId(DAGTypeLegalizer::NewNode);
668 NodesToAnalyze.insert(N);
674 /// ReplaceValueWith - The specified value was legalized to the specified other
675 /// value. Update the DAG and NodeIds replacing any uses of From to use To
677 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
678 assert(From.getNode() != To.getNode() && "Potential legalization loop!");
680 // If expansion produced new nodes, make sure they are properly marked.
681 ExpungeNode(From.getNode());
682 AnalyzeNewValue(To); // Expunges To.
684 // Anything that used the old node should now use the new one. Note that this
685 // can potentially cause recursive merging.
686 SmallSetVector<SDNode*, 16> NodesToAnalyze;
687 NodeUpdateListener NUL(*this, NodesToAnalyze);
689 DAG.ReplaceAllUsesOfValueWith(From, To);
691 // The old node may still be present in a map like ExpandedIntegers or
692 // PromotedIntegers. Inform maps about the replacement.
693 ReplacedValues[From] = To;
695 // Process the list of nodes that need to be reanalyzed.
696 while (!NodesToAnalyze.empty()) {
697 SDNode *N = NodesToAnalyze.back();
698 NodesToAnalyze.pop_back();
699 if (N->getNodeId() != DAGTypeLegalizer::NewNode)
700 // The node was analyzed while reanalyzing an earlier node - it is safe
701 // to skip. Note that this is not a morphing node - otherwise it would
702 // still be marked NewNode.
705 // Analyze the node's operands and recalculate the node ID.
706 SDNode *M = AnalyzeNewNode(N);
708 // The node morphed into a different node. Make everyone use the new
710 assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
711 assert(N->getNumValues() == M->getNumValues() &&
712 "Node morphing changed the number of results!");
713 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
714 SDValue OldVal(N, i);
715 SDValue NewVal(M, i);
716 if (M->getNodeId() == Processed)
718 DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal);
719 // OldVal may be a target of the ReplacedValues map which was marked
720 // NewNode to force reanalysis because it was updated. Ensure that
721 // anything that ReplacedValues mapped to OldVal will now be mapped
722 // all the way to NewVal.
723 ReplacedValues[OldVal] = NewVal;
725 // The original node continues to exist in the DAG, marked NewNode.
728 // When recursively update nodes with new nodes, it is possible to have
729 // new uses of From due to CSE. If this happens, replace the new uses of
731 } while (!From.use_empty());
734 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
735 assert(Result.getValueType() ==
736 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
737 "Invalid type for promoted integer");
738 AnalyzeNewValue(Result);
740 SDValue &OpEntry = PromotedIntegers[Op];
741 assert(!OpEntry.getNode() && "Node is already promoted!");
745 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
746 assert(Result.getValueType() ==
747 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
748 "Invalid type for softened float");
749 AnalyzeNewValue(Result);
751 SDValue &OpEntry = SoftenedFloats[Op];
752 assert(!OpEntry.getNode() && "Node is already converted to integer!");
756 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
757 // Note that in some cases vector operation operands may be greater than
758 // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
759 // a constant i8 operand.
760 assert(Result.getValueType().getSizeInBits() >=
761 Op.getValueType().getVectorElementType().getSizeInBits() &&
762 "Invalid type for scalarized vector");
763 AnalyzeNewValue(Result);
765 SDValue &OpEntry = ScalarizedVectors[Op];
766 assert(!OpEntry.getNode() && "Node is already scalarized!");
770 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
772 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
773 RemapValue(Entry.first);
774 RemapValue(Entry.second);
775 assert(Entry.first.getNode() && "Operand isn't expanded");
780 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
782 assert(Lo.getValueType() ==
783 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
784 Hi.getValueType() == Lo.getValueType() &&
785 "Invalid type for expanded integer");
786 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
790 // Remember that this is the result of the node.
791 std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
792 assert(!Entry.first.getNode() && "Node already expanded");
797 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
799 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
800 RemapValue(Entry.first);
801 RemapValue(Entry.second);
802 assert(Entry.first.getNode() && "Operand isn't expanded");
807 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
809 assert(Lo.getValueType() ==
810 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
811 Hi.getValueType() == Lo.getValueType() &&
812 "Invalid type for expanded float");
813 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
817 // Remember that this is the result of the node.
818 std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
819 assert(!Entry.first.getNode() && "Node already expanded");
824 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
826 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
827 RemapValue(Entry.first);
828 RemapValue(Entry.second);
829 assert(Entry.first.getNode() && "Operand isn't split");
834 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
836 assert(Lo.getValueType().getVectorElementType() ==
837 Op.getValueType().getVectorElementType() &&
838 2*Lo.getValueType().getVectorNumElements() ==
839 Op.getValueType().getVectorNumElements() &&
840 Hi.getValueType() == Lo.getValueType() &&
841 "Invalid type for split vector");
842 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
846 // Remember that this is the result of the node.
847 std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
848 assert(!Entry.first.getNode() && "Node already split");
853 void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
854 assert(Result.getValueType() ==
855 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
856 "Invalid type for widened vector");
857 AnalyzeNewValue(Result);
859 SDValue &OpEntry = WidenedVectors[Op];
860 assert(!OpEntry.getNode() && "Node already widened!");
865 //===----------------------------------------------------------------------===//
867 //===----------------------------------------------------------------------===//
869 /// BitConvertToInteger - Convert to an integer of the same size.
870 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
871 unsigned BitWidth = Op.getValueType().getSizeInBits();
872 return DAG.getNode(ISD::BITCAST, SDLoc(Op),
873 EVT::getIntegerVT(*DAG.getContext(), BitWidth), Op);
876 /// BitConvertVectorToIntegerVector - Convert to a vector of integers of the
878 SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
879 assert(Op.getValueType().isVector() && "Only applies to vectors!");
880 unsigned EltWidth = Op.getValueType().getVectorElementType().getSizeInBits();
881 EVT EltNVT = EVT::getIntegerVT(*DAG.getContext(), EltWidth);
882 unsigned NumElts = Op.getValueType().getVectorNumElements();
883 return DAG.getNode(ISD::BITCAST, SDLoc(Op),
884 EVT::getVectorVT(*DAG.getContext(), EltNVT, NumElts), Op);
887 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
890 // Create the stack frame object. Make sure it is aligned for both
891 // the source and destination types.
892 SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
893 // Emit a store to the stack slot.
894 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr,
895 MachinePointerInfo(), false, false, 0);
896 // Result is a load from the stack slot.
897 return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo(),
898 false, false, false, 0);
901 /// CustomLowerNode - Replace the node's results with custom code provided
902 /// by the target and return "true", or do nothing and return "false".
903 /// The last parameter is FALSE if we are dealing with a node with legal
904 /// result types and illegal operand. The second parameter denotes the type of
905 /// illegal OperandNo in that case.
906 /// The last parameter being TRUE means we are dealing with a
907 /// node with illegal result types. The second parameter denotes the type of
908 /// illegal ResNo in that case.
909 bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
910 // See if the target wants to custom lower this node.
911 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
914 SmallVector<SDValue, 8> Results;
916 TLI.ReplaceNodeResults(N, Results, DAG);
918 TLI.LowerOperationWrapper(N, Results, DAG);
921 // The target didn't want to custom lower it after all.
924 // Make everything that once used N's values now use those in Results instead.
925 assert(Results.size() == N->getNumValues() &&
926 "Custom lowering returned the wrong number of results!");
927 for (unsigned i = 0, e = Results.size(); i != e; ++i) {
928 ReplaceValueWith(SDValue(N, i), Results[i]);
934 /// CustomWidenLowerNode - Widen the node's results with custom code provided
935 /// by the target and return "true", or do nothing and return "false".
936 bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
937 // See if the target wants to custom lower this node.
938 if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
941 SmallVector<SDValue, 8> Results;
942 TLI.ReplaceNodeResults(N, Results, DAG);
945 // The target didn't want to custom widen lower its result after all.
948 // Update the widening map.
949 assert(Results.size() == N->getNumValues() &&
950 "Custom lowering returned the wrong number of results!");
951 for (unsigned i = 0, e = Results.size(); i != e; ++i)
952 SetWidenedVector(SDValue(N, i), Results[i]);
956 SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
957 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
959 ReplaceValueWith(SDValue(N, i), SDValue(N->getOperand(i)));
960 return SDValue(N->getOperand(ResNo));
963 /// GetPairElements - Use ISD::EXTRACT_ELEMENT nodes to extract the low and
964 /// high parts of the given value.
965 void DAGTypeLegalizer::GetPairElements(SDValue Pair,
966 SDValue &Lo, SDValue &Hi) {
968 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), Pair.getValueType());
969 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
970 DAG.getIntPtrConstant(0));
971 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
972 DAG.getIntPtrConstant(1));
975 SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, EVT EltVT,
978 // Make sure the index type is big enough to compute in.
979 Index = DAG.getZExtOrTrunc(Index, dl, TLI.getPointerTy());
981 // Calculate the element offset and add it to the pointer.
982 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
984 Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
985 DAG.getConstant(EltSize, Index.getValueType()));
986 return DAG.getNode(ISD::ADD, dl, Index.getValueType(), Index, VecPtr);
989 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
990 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
991 // Arbitrarily use dlHi for result SDLoc
994 EVT LVT = Lo.getValueType();
995 EVT HVT = Hi.getValueType();
996 EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
997 LVT.getSizeInBits() + HVT.getSizeInBits());
999 Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
1000 Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
1001 Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
1002 DAG.getConstant(LVT.getSizeInBits(), TLI.getPointerTy()));
1003 return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
1006 /// LibCallify - Convert the node into a libcall with the same prototype.
1007 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
1009 unsigned NumOps = N->getNumOperands();
1012 return TLI.makeLibCall(DAG, LC, N->getValueType(0), nullptr, 0, isSigned,
1014 } else if (NumOps == 1) {
1015 SDValue Op = N->getOperand(0);
1016 return TLI.makeLibCall(DAG, LC, N->getValueType(0), &Op, 1, isSigned,
1018 } else if (NumOps == 2) {
1019 SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1020 return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, 2, isSigned,
1023 SmallVector<SDValue, 8> Ops(NumOps);
1024 for (unsigned i = 0; i < NumOps; ++i)
1025 Ops[i] = N->getOperand(i);
1027 return TLI.makeLibCall(DAG, LC, N->getValueType(0),
1028 &Ops[0], NumOps, isSigned, dl).first;
1031 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
1032 // ExpandLibCall except that the first operand is the in-chain.
1033 std::pair<SDValue, SDValue>
1034 DAGTypeLegalizer::ExpandChainLibCall(RTLIB::Libcall LC,
1037 SDValue InChain = Node->getOperand(0);
1039 TargetLowering::ArgListTy Args;
1040 TargetLowering::ArgListEntry Entry;
1041 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
1042 EVT ArgVT = Node->getOperand(i).getValueType();
1043 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1044 Entry.Node = Node->getOperand(i);
1046 Entry.isSExt = isSigned;
1047 Entry.isZExt = !isSigned;
1048 Args.push_back(Entry);
1050 SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1051 TLI.getPointerTy());
1053 Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1055 TargetLowering::CallLoweringInfo CLI(DAG);
1056 CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
1057 .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, &Args, 0)
1058 .setSExtResult(isSigned).setZExtResult(!isSigned);
1060 std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
1065 /// PromoteTargetBoolean - Promote the given target boolean to a target boolean
1066 /// of the given type. A target boolean is an integer value, not necessarily of
1067 /// type i1, the bits of which conform to getBooleanContents.
1068 SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT VT) {
1070 ISD::NodeType ExtendCode =
1071 TargetLowering::getExtendForContent(TLI.getBooleanContents(VT.isVector()));
1072 return DAG.getNode(ExtendCode, dl, VT, Bool);
1075 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
1077 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1079 SDValue &Lo, SDValue &Hi) {
1081 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
1082 Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
1083 Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
1084 Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
1085 DAG.getConstant(LoVT.getSizeInBits(), TLI.getPointerTy()));
1086 Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
1089 /// SplitInteger - Return the lower and upper halves of Op's bits in a value
1090 /// type half the size of Op's.
1091 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1092 SDValue &Lo, SDValue &Hi) {
1093 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(),
1094 Op.getValueType().getSizeInBits()/2);
1095 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
1099 //===----------------------------------------------------------------------===//
1101 //===----------------------------------------------------------------------===//
1103 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
1104 /// only uses types natively supported by the target. Returns "true" if it made
1107 /// Note that this is an involved process that may invalidate pointers into
1109 bool SelectionDAG::LegalizeTypes() {
1110 return DAGTypeLegalizer(*this).run();