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