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 if (OldValId != NewValId)
691 ReplacedValues[OldValId] = NewValId;
692 }
693 // The original node continues to exist in the DAG, marked NewNode.
694 }
695 }
696 // When recursively update nodes with new nodes, it is possible to have
697 // new uses of From due to CSE. If this happens, replace the new uses of
698 // From with To.
699 } while (!From.use_empty());
700}
701
702void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
703 assert(Result.getValueType() ==
704 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
705 "Invalid type for promoted integer");
706 AnalyzeNewValue(Val&: Result);
707
708 auto &OpIdEntry = PromotedIntegers[getTableId(V: Op)];
709 assert((OpIdEntry == 0) && "Node is already promoted!");
710 OpIdEntry = getTableId(V: Result);
711
712 DAG.transferDbgValues(From: Op, To: Result);
713}
714
715void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
716#ifndef NDEBUG
717 EVT VT = Result.getValueType();
718 LLVMContext &Ctx = *DAG.getContext();
719 assert((VT == EVT::getIntegerVT(Ctx, 80) ||
720 VT == TLI.getTypeToTransformTo(Ctx, Op.getValueType())) &&
721 "Invalid type for softened float");
722#endif
723 AnalyzeNewValue(Val&: Result);
724
725 auto &OpIdEntry = SoftenedFloats[getTableId(V: Op)];
726 assert((OpIdEntry == 0) && "Node is already converted to integer!");
727 OpIdEntry = getTableId(V: Result);
728}
729
730void DAGTypeLegalizer::SetPromotedFloat(SDValue Op, SDValue Result) {
731 assert(Result.getValueType() ==
732 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
733 "Invalid type for promoted float");
734 AnalyzeNewValue(Val&: Result);
735
736 auto &OpIdEntry = PromotedFloats[getTableId(V: Op)];
737 assert((OpIdEntry == 0) && "Node is already promoted!");
738 OpIdEntry = getTableId(V: Result);
739}
740
741void DAGTypeLegalizer::SetSoftPromotedHalf(SDValue Op, SDValue Result) {
742 assert(Result.getValueType() == MVT::i16 &&
743 "Invalid type for soft-promoted half");
744 AnalyzeNewValue(Val&: Result);
745
746 auto &OpIdEntry = SoftPromotedHalfs[getTableId(V: Op)];
747 assert((OpIdEntry == 0) && "Node is already promoted!");
748 OpIdEntry = getTableId(V: Result);
749}
750
751void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
752 // Note that in some cases vector operation operands may be greater than
753 // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
754 // a constant i8 operand.
755
756 // We don't currently support the scalarization of scalable vector types.
757 assert(Result.getValueSizeInBits().getFixedValue() >=
758 Op.getScalarValueSizeInBits() &&
759 "Invalid type for scalarized vector");
760 AnalyzeNewValue(Val&: Result);
761
762 auto &OpIdEntry = ScalarizedVectors[getTableId(V: Op)];
763 assert((OpIdEntry == 0) && "Node is already scalarized!");
764 OpIdEntry = getTableId(V: Result);
765}
766
767void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
768 SDValue &Hi) {
769 std::pair<TableId, TableId> &Entry = ExpandedIntegers[getTableId(V: Op)];
770 assert((Entry.first != 0) && "Operand isn't expanded");
771 Lo = getSDValue(Id&: Entry.first);
772 Hi = getSDValue(Id&: Entry.second);
773}
774
775void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
776 SDValue Hi) {
777 assert(Lo.getValueType() ==
778 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
779 Hi.getValueType() == Lo.getValueType() &&
780 "Invalid type for expanded integer");
781 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
782 AnalyzeNewValue(Val&: Lo);
783 AnalyzeNewValue(Val&: Hi);
784
785 // Transfer debug values. Don't invalidate the source debug value until it's
786 // been transferred to the high and low bits.
787 if (DAG.getDataLayout().isBigEndian()) {
788 DAG.transferDbgValues(From: Op, To: Hi, OffsetInBits: 0, SizeInBits: Hi.getValueSizeInBits(), InvalidateDbg: false);
789 DAG.transferDbgValues(From: Op, To: Lo, OffsetInBits: Hi.getValueSizeInBits(),
790 SizeInBits: Lo.getValueSizeInBits());
791 } else {
792 DAG.transferDbgValues(From: Op, To: Lo, OffsetInBits: 0, SizeInBits: Lo.getValueSizeInBits(), InvalidateDbg: false);
793 DAG.transferDbgValues(From: Op, To: Hi, OffsetInBits: Lo.getValueSizeInBits(),
794 SizeInBits: Hi.getValueSizeInBits());
795 }
796
797 // Remember that this is the result of the node.
798 std::pair<TableId, TableId> &Entry = ExpandedIntegers[getTableId(V: Op)];
799 assert((Entry.first == 0) && "Node already expanded");
800 Entry.first = getTableId(V: Lo);
801 Entry.second = getTableId(V: Hi);
802}
803
804void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
805 SDValue &Hi) {
806 std::pair<TableId, TableId> &Entry = ExpandedFloats[getTableId(V: Op)];
807 assert((Entry.first != 0) && "Operand isn't expanded");
808 Lo = getSDValue(Id&: Entry.first);
809 Hi = getSDValue(Id&: Entry.second);
810}
811
812void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
813 SDValue Hi) {
814 assert(Lo.getValueType() ==
815 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
816 Hi.getValueType() == Lo.getValueType() &&
817 "Invalid type for expanded float");
818 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
819 AnalyzeNewValue(Val&: Lo);
820 AnalyzeNewValue(Val&: Hi);
821
822 std::pair<TableId, TableId> &Entry = ExpandedFloats[getTableId(V: Op)];
823 assert((Entry.first == 0) && "Node already expanded");
824 Entry.first = getTableId(V: Lo);
825 Entry.second = getTableId(V: Hi);
826}
827
828void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
829 SDValue &Hi) {
830 std::pair<TableId, TableId> &Entry = SplitVectors[getTableId(V: Op)];
831 Lo = getSDValue(Id&: Entry.first);
832 Hi = getSDValue(Id&: Entry.second);
833 assert(Lo.getNode() && "Operand isn't split");
834 ;
835}
836
837void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
838 SDValue Hi) {
839 assert(Lo.getValueType().getVectorElementType() ==
840 Op.getValueType().getVectorElementType() &&
841 Lo.getValueType().getVectorElementCount() * 2 ==
842 Op.getValueType().getVectorElementCount() &&
843 Hi.getValueType() == Lo.getValueType() &&
844 "Invalid type for split vector");
845 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
846 AnalyzeNewValue(Val&: Lo);
847 AnalyzeNewValue(Val&: Hi);
848
849 // Remember that this is the result of the node.
850 std::pair<TableId, TableId> &Entry = SplitVectors[getTableId(V: Op)];
851 assert((Entry.first == 0) && "Node already split");
852 Entry.first = getTableId(V: Lo);
853 Entry.second = getTableId(V: Hi);
854}
855
856void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
857 assert(Result.getValueType() ==
858 TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
859 "Invalid type for widened vector");
860 AnalyzeNewValue(Val&: Result);
861
862 auto &OpIdEntry = WidenedVectors[getTableId(V: Op)];
863 assert((OpIdEntry == 0) && "Node already widened!");
864 OpIdEntry = getTableId(V: Result);
865}
866
867
868//===----------------------------------------------------------------------===//
869// Utilities.
870//===----------------------------------------------------------------------===//
871
872/// Convert to an integer of the same size.
873SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
874 unsigned BitWidth = Op.getValueSizeInBits();
875 return DAG.getNode(Opcode: ISD::BITCAST, DL: SDLoc(Op),
876 VT: EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth), Operand: Op);
877}
878
879/// Convert to a vector of integers of the same size.
880SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
881 assert(Op.getValueType().isVector() && "Only applies to vectors!");
882 unsigned EltWidth = Op.getScalarValueSizeInBits();
883 EVT EltNVT = EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: EltWidth);
884 auto EltCnt = Op.getValueType().getVectorElementCount();
885 return DAG.getNode(Opcode: ISD::BITCAST, DL: SDLoc(Op),
886 VT: EVT::getVectorVT(Context&: *DAG.getContext(), VT: EltNVT, EC: EltCnt), Operand: Op);
887}
888
889SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
890 EVT DestVT) {
891 SDLoc dl(Op);
892 // Create the stack frame object. Make sure it is aligned for both
893 // the source and destination types.
894
895 // In cases where the vector is illegal it will be broken down into parts
896 // and stored in parts - we should use the alignment for the smallest part.
897 Align DestAlign = DAG.getReducedAlign(VT: DestVT, /*UseABI=*/false);
898 Align OpAlign = DAG.getReducedAlign(VT: Op.getValueType(), /*UseABI=*/false);
899 Align Align = std::max(a: DestAlign, b: OpAlign);
900 SDValue StackPtr =
901 DAG.CreateStackTemporary(Bytes: Op.getValueType().getStoreSize(), Alignment: Align);
902 // Emit a store to the stack slot.
903 SDValue Store = DAG.getStore(Chain: DAG.getEntryNode(), dl, Val: Op, Ptr: StackPtr,
904 PtrInfo: MachinePointerInfo(), Alignment: Align);
905 // Result is a load from the stack slot.
906 return DAG.getLoad(VT: DestVT, dl, Chain: Store, Ptr: StackPtr, PtrInfo: MachinePointerInfo(), Alignment: Align);
907}
908
909/// Replace the node's results with custom code provided by the target and
910/// return "true", or do nothing and return "false".
911/// The last parameter is FALSE if we are dealing with a node with legal
912/// result types and illegal operand. The second parameter denotes the type of
913/// illegal OperandNo in that case.
914/// The last parameter being TRUE means we are dealing with a
915/// node with illegal result types. The second parameter denotes the type of
916/// illegal ResNo in that case.
917bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
918 // See if the target wants to custom lower this node.
919 if (TLI.getOperationAction(Op: N->getOpcode(), VT) != TargetLowering::Custom)
920 return false;
921
922 SmallVector<SDValue, 8> Results;
923 if (LegalizeResult)
924 TLI.ReplaceNodeResults(N, Results, DAG);
925 else
926 TLI.LowerOperationWrapper(N, Results, DAG);
927
928 if (Results.empty())
929 // The target didn't want to custom lower it after all.
930 return false;
931
932 // Make everything that once used N's values now use those in Results instead.
933 assert(Results.size() == N->getNumValues() &&
934 "Custom lowering returned the wrong number of results!");
935 for (unsigned i = 0, e = Results.size(); i != e; ++i) {
936 ReplaceValueWith(From: SDValue(N, i), To: Results[i]);
937 }
938 return true;
939}
940
941
942/// Widen the node's results with custom code provided by the target and return
943/// "true", or do nothing and return "false".
944bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
945 // See if the target wants to custom lower this node.
946 if (TLI.getOperationAction(Op: N->getOpcode(), VT) != TargetLowering::Custom)
947 return false;
948
949 SmallVector<SDValue, 8> Results;
950 TLI.ReplaceNodeResults(N, Results, DAG);
951
952 if (Results.empty())
953 // The target didn't want to custom widen lower its result after all.
954 return false;
955
956 // Update the widening map.
957 assert(Results.size() == N->getNumValues() &&
958 "Custom lowering returned the wrong number of results!");
959 for (unsigned i = 0, e = Results.size(); i != e; ++i) {
960 // If this is a chain output or already widened just replace it.
961 bool WasWidened = SDValue(N, i).getValueType() != Results[i].getValueType();
962 if (WasWidened)
963 SetWidenedVector(Op: SDValue(N, i), Result: Results[i]);
964 else
965 ReplaceValueWith(From: SDValue(N, i), To: Results[i]);
966 }
967 return true;
968}
969
970SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
971 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
972 if (i != ResNo)
973 ReplaceValueWith(From: SDValue(N, i), To: SDValue(N->getOperand(Num: i)));
974 return SDValue(N->getOperand(Num: ResNo));
975}
976
977/// Use ISD::EXTRACT_ELEMENT nodes to extract the low and high parts of the
978/// given value.
979void DAGTypeLegalizer::GetPairElements(SDValue Pair,
980 SDValue &Lo, SDValue &Hi) {
981 SDLoc dl(Pair);
982 EVT NVT = TLI.getTypeToTransformTo(Context&: *DAG.getContext(), VT: Pair.getValueType());
983 std::tie(args&: Lo, args&: Hi) = DAG.SplitScalar(N: Pair, DL: dl, LoVT: NVT, HiVT: NVT);
984}
985
986/// Build an integer with low bits Lo and high bits Hi.
987SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
988 // Arbitrarily use dlHi for result SDLoc
989 SDLoc dlHi(Hi);
990 SDLoc dlLo(Lo);
991 EVT LVT = Lo.getValueType();
992 EVT HVT = Hi.getValueType();
993 EVT NVT = EVT::getIntegerVT(Context&: *DAG.getContext(),
994 BitWidth: LVT.getSizeInBits() + HVT.getSizeInBits());
995
996 Lo = DAG.getNode(Opcode: ISD::ZERO_EXTEND, DL: dlLo, VT: NVT, Operand: Lo);
997 Hi = DAG.getNode(Opcode: ISD::ANY_EXTEND, DL: dlHi, VT: NVT, Operand: Hi);
998 Hi = DAG.getNode(Opcode: ISD::SHL, DL: dlHi, VT: NVT, N1: Hi,
999 N2: DAG.getShiftAmountConstant(Val: LVT.getSizeInBits(), VT: NVT, DL: dlHi));
1000 return DAG.getNode(Opcode: ISD::OR, DL: dlHi, VT: NVT, N1: Lo, N2: Hi);
1001}
1002
1003/// Promote the given target boolean to a target boolean of the given type.
1004/// A target boolean is an integer value, not necessarily of type i1, the bits
1005/// of which conform to getBooleanContents.
1006///
1007/// ValVT is the type of values that produced the boolean.
1008SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT ValVT) {
1009 return TLI.promoteTargetBoolean(DAG, Bool, ValVT);
1010}
1011
1012/// Return the lower LoVT bits of Op in Lo and the upper HiVT bits in Hi.
1013void DAGTypeLegalizer::SplitInteger(SDValue Op,
1014 EVT LoVT, EVT HiVT,
1015 SDValue &Lo, SDValue &Hi) {
1016 SDLoc dl(Op);
1017 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
1018 Op.getValueSizeInBits() && "Invalid integer splitting!");
1019 Lo = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: LoVT, Operand: Op);
1020 Hi = DAG.getNode(
1021 Opcode: ISD::SRL, DL: dl, VT: Op.getValueType(), N1: Op,
1022 N2: DAG.getShiftAmountConstant(Val: LoVT.getSizeInBits(), VT: Op.getValueType(), DL: dl));
1023 Hi = DAG.getNode(Opcode: ISD::TRUNCATE, DL: dl, VT: HiVT, Operand: Hi);
1024}
1025
1026/// Return the lower and upper halves of Op's bits in a value type half the
1027/// size of Op's.
1028void DAGTypeLegalizer::SplitInteger(SDValue Op,
1029 SDValue &Lo, SDValue &Hi) {
1030 EVT HalfVT =
1031 EVT::getIntegerVT(Context&: *DAG.getContext(), BitWidth: Op.getValueSizeInBits() / 2);
1032 SplitInteger(Op, LoVT: HalfVT, HiVT: HalfVT, Lo, Hi);
1033}
1034
1035
1036//===----------------------------------------------------------------------===//
1037// Entry Point
1038//===----------------------------------------------------------------------===//
1039
1040/// This transforms the SelectionDAG into a SelectionDAG that only uses types
1041/// natively supported by the target. Returns "true" if it made any changes.
1042///
1043/// Note that this is an involved process that may invalidate pointers into
1044/// the graph.
1045bool SelectionDAG::LegalizeTypes() {
1046 return DAGTypeLegalizer(*this).run();
1047}
1048