LLVM  5.0.0
LegalizeTypes.cpp
Go to the documentation of this file.
1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the SelectionDAG::LegalizeTypes method. It transforms
11 // an arbitrary well-formed SelectionDAG to only consist of legal types. This
12 // is common code shared among the LegalizeTypes*.cpp files.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "LegalizeTypes.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/IR/CallingConv.h"
19 #include "llvm/IR/DataLayout.h"
23 using namespace llvm;
24 
25 #define DEBUG_TYPE "legalize-types"
26 
27 static cl::opt<bool>
28 EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
29 
30 /// 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.
34 
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
38  // the other maps.
39 
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.
42 
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
61  // not used by them.
62 
63  // If a value is mapped by ReplacedValues, then it must have no uses, except
64  // by nodes marked NewNode (see above).
65 
66  // The final node obtained by mapping by ReplacedValues is not marked NewNode.
67  // Note that ReplacedValues should be applied iteratively.
68 
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 (SDNode &Node : DAG.allnodes()) {
77  // Remember nodes marked NewNode - they are subject to extra checking below.
78  if (Node.getNodeId() == NewNode)
79  NewNodes.push_back(&Node);
80 
81  for (unsigned i = 0, e = Node.getNumValues(); i != e; ++i) {
82  SDValue Res(&Node, i);
83  EVT VT = Res.getValueType();
84  bool Failed = false;
85 
86  unsigned Mapped = 0;
87  if (ReplacedValues.find(Res) != ReplacedValues.end()) {
88  Mapped |= 1;
89  // Check that remapped values are only used by nodes marked NewNode.
90  for (SDNode::use_iterator UI = Node.use_begin(), UE = Node.use_end();
91  UI != UE; ++UI)
92  if (UI.getUse().getResNo() == i)
93  assert(UI->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  SDValue NewVal = ReplacedValues[Res];
99  DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal);
100  while (I != ReplacedValues.end()) {
101  NewVal = I->second;
102  I = ReplacedValues.find(NewVal);
103  }
104  assert(NewVal.getNode()->getNodeId() != NewNode &&
105  "ReplacedValues maps to a new node!");
106  }
107  if (PromotedIntegers.find(Res) != PromotedIntegers.end())
108  Mapped |= 2;
109  if (SoftenedFloats.find(Res) != SoftenedFloats.end())
110  Mapped |= 4;
111  if (ScalarizedVectors.find(Res) != ScalarizedVectors.end())
112  Mapped |= 8;
113  if (ExpandedIntegers.find(Res) != ExpandedIntegers.end())
114  Mapped |= 16;
115  if (ExpandedFloats.find(Res) != ExpandedFloats.end())
116  Mapped |= 32;
117  if (SplitVectors.find(Res) != SplitVectors.end())
118  Mapped |= 64;
119  if (WidenedVectors.find(Res) != WidenedVectors.end())
120  Mapped |= 128;
121  if (PromotedFloats.find(Res) != PromotedFloats.end())
122  Mapped |= 256;
123 
124  if (Node.getNodeId() != Processed) {
125  // Since we allow ReplacedValues to map deleted nodes, it may map nodes
126  // marked NewNode too, since a deleted node may have been reallocated as
127  // another node that has not been seen by the LegalizeTypes machinery.
128  if ((Node.getNodeId() == NewNode && Mapped > 1) ||
129  (Node.getNodeId() != NewNode && Mapped != 0)) {
130  dbgs() << "Unprocessed value in a map!";
131  Failed = true;
132  }
133  } else if (isTypeLegal(VT) || IgnoreNodeResults(&Node)) {
134  if (Mapped > 1) {
135  dbgs() << "Value with legal type was transformed!";
136  Failed = true;
137  }
138  } else {
139  // If the value can be kept in HW registers, softening machinery can
140  // leave it unchanged and don't put it to any map.
141  if (Mapped == 0 &&
142  !(getTypeAction(VT) == TargetLowering::TypeSoftenFloat &&
143  isLegalInHWReg(VT))) {
144  dbgs() << "Processed value not in any map!";
145  Failed = true;
146  } else if (Mapped & (Mapped - 1)) {
147  dbgs() << "Value in multiple maps!";
148  Failed = true;
149  }
150  }
151 
152  if (Failed) {
153  if (Mapped & 1)
154  dbgs() << " ReplacedValues";
155  if (Mapped & 2)
156  dbgs() << " PromotedIntegers";
157  if (Mapped & 4)
158  dbgs() << " SoftenedFloats";
159  if (Mapped & 8)
160  dbgs() << " ScalarizedVectors";
161  if (Mapped & 16)
162  dbgs() << " ExpandedIntegers";
163  if (Mapped & 32)
164  dbgs() << " ExpandedFloats";
165  if (Mapped & 64)
166  dbgs() << " SplitVectors";
167  if (Mapped & 128)
168  dbgs() << " WidenedVectors";
169  if (Mapped & 256)
170  dbgs() << " PromotedFloats";
171  dbgs() << "\n";
172  llvm_unreachable(nullptr);
173  }
174  }
175  }
176 
177  // Checked that NewNodes are only used by other NewNodes.
178  for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
179  SDNode *N = NewNodes[i];
180  for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
181  UI != UE; ++UI)
182  assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
183  }
184 }
185 
186 /// This is the main entry point for the type legalizer. This does a top-down
187 /// traversal of the dag, legalizing types as it goes. Returns "true" if it made
188 /// any changes.
190  bool Changed = false;
191 
192  // Create a dummy node (which is not added to allnodes), that adds a reference
193  // to the root node, preventing it from being deleted, and tracking any
194  // changes of the root.
195  HandleSDNode Dummy(DAG.getRoot());
196  Dummy.setNodeId(Unanalyzed);
197 
198  // The root of the dag may dangle to deleted nodes until the type legalizer is
199  // done. Set it to null to avoid confusion.
200  DAG.setRoot(SDValue());
201 
202  // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
203  // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
204  // non-leaves.
205  for (SDNode &Node : DAG.allnodes()) {
206  if (Node.getNumOperands() == 0) {
207  AddToWorklist(&Node);
208  } else {
209  Node.setNodeId(Unanalyzed);
210  }
211  }
212 
213  // Now that we have a set of nodes to process, handle them all.
214  while (!Worklist.empty()) {
215 #ifndef EXPENSIVE_CHECKS
217 #endif
218  PerformExpensiveChecks();
219 
220  SDNode *N = Worklist.back();
221  Worklist.pop_back();
222  assert(N->getNodeId() == ReadyToProcess &&
223  "Node should be ready if on worklist!");
224 
225  if (IgnoreNodeResults(N))
226  goto ScanOperands;
227 
228  // Scan the values produced by the node, checking to see if any result
229  // types are illegal.
230  for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
231  EVT ResultVT = N->getValueType(i);
232  switch (getTypeAction(ResultVT)) {
234  break;
235  // The following calls must take care of *all* of the node's results,
236  // not just the illegal result they were passed (this includes results
237  // with a legal type). Results can be remapped using ReplaceValueWith,
238  // or their promoted/expanded/etc values registered in PromotedIntegers,
239  // ExpandedIntegers etc.
241  PromoteIntegerResult(N, i);
242  Changed = true;
243  goto NodeDone;
245  ExpandIntegerResult(N, i);
246  Changed = true;
247  goto NodeDone;
249  Changed = SoftenFloatResult(N, i);
250  if (Changed)
251  goto NodeDone;
252  // If not changed, the result type should be legally in register.
253  assert(isLegalInHWReg(ResultVT) &&
254  "Unchanged SoftenFloatResult should be legal in register!");
255  goto ScanOperands;
257  ExpandFloatResult(N, i);
258  Changed = true;
259  goto NodeDone;
261  ScalarizeVectorResult(N, i);
262  Changed = true;
263  goto NodeDone;
265  SplitVectorResult(N, i);
266  Changed = true;
267  goto NodeDone;
269  WidenVectorResult(N, i);
270  Changed = true;
271  goto NodeDone;
273  PromoteFloatResult(N, i);
274  Changed = true;
275  goto NodeDone;
276  }
277  }
278 
279 ScanOperands:
280  // Scan the operand list for the node, handling any nodes with operands that
281  // are illegal.
282  {
283  unsigned NumOperands = N->getNumOperands();
284  bool NeedsReanalyzing = false;
285  unsigned i;
286  for (i = 0; i != NumOperands; ++i) {
287  if (IgnoreNodeResults(N->getOperand(i).getNode()))
288  continue;
289 
290  EVT OpVT = N->getOperand(i).getValueType();
291  switch (getTypeAction(OpVT)) {
293  continue;
294  // The following calls must either replace all of the node's results
295  // using ReplaceValueWith, and return "false"; or update the node's
296  // operands in place, and return "true".
298  NeedsReanalyzing = PromoteIntegerOperand(N, i);
299  Changed = true;
300  break;
302  NeedsReanalyzing = ExpandIntegerOperand(N, i);
303  Changed = true;
304  break;
306  NeedsReanalyzing = SoftenFloatOperand(N, i);
307  Changed = true;
308  break;
310  NeedsReanalyzing = ExpandFloatOperand(N, i);
311  Changed = true;
312  break;
314  NeedsReanalyzing = ScalarizeVectorOperand(N, i);
315  Changed = true;
316  break;
318  NeedsReanalyzing = SplitVectorOperand(N, i);
319  Changed = true;
320  break;
322  NeedsReanalyzing = WidenVectorOperand(N, i);
323  Changed = true;
324  break;
326  NeedsReanalyzing = PromoteFloatOperand(N, i);
327  Changed = true;
328  break;
329  }
330  break;
331  }
332 
333  // The sub-method updated N in place. Check to see if any operands are new,
334  // and if so, mark them. If the node needs revisiting, don't add all users
335  // to the worklist etc.
336  if (NeedsReanalyzing) {
337  assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
338 
339  N->setNodeId(NewNode);
340  // Recompute the NodeId and correct processed operands, adding the node to
341  // the worklist if ready.
342  SDNode *M = AnalyzeNewNode(N);
343  if (M == N)
344  // The node didn't morph - nothing special to do, it will be revisited.
345  continue;
346 
347  // The node morphed - this is equivalent to legalizing by replacing every
348  // value of N with the corresponding value of M. So do that now.
349  assert(N->getNumValues() == M->getNumValues() &&
350  "Node morphing changed the number of results!");
351  for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
352  // Replacing the value takes care of remapping the new value.
353  ReplaceValueWith(SDValue(N, i), SDValue(M, i));
354  assert(N->getNodeId() == NewNode && "Unexpected node state!");
355  // The node continues to live on as part of the NewNode fungus that
356  // grows on top of the useful nodes. Nothing more needs to be done
357  // with it - move on to the next node.
358  continue;
359  }
360 
361  if (i == NumOperands) {
362  DEBUG(dbgs() << "Legally typed node: "; N->dump(&DAG); dbgs() << "\n");
363  }
364  }
365 NodeDone:
366 
367  // If we reach here, the node was processed, potentially creating new nodes.
368  // Mark it as processed and add its users to the worklist as appropriate.
369  assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
370  N->setNodeId(Processed);
371 
372  for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
373  UI != E; ++UI) {
374  SDNode *User = *UI;
375  int NodeId = User->getNodeId();
376 
377  // This node has two options: it can either be a new node or its Node ID
378  // may be a count of the number of operands it has that are not ready.
379  if (NodeId > 0) {
380  User->setNodeId(NodeId-1);
381 
382  // If this was the last use it was waiting on, add it to the ready list.
383  if (NodeId-1 == ReadyToProcess)
384  Worklist.push_back(User);
385  continue;
386  }
387 
388  // If this is an unreachable new node, then ignore it. If it ever becomes
389  // reachable by being used by a newly created node then it will be handled
390  // by AnalyzeNewNode.
391  if (NodeId == NewNode)
392  continue;
393 
394  // Otherwise, this node is new: this is the first operand of it that
395  // became ready. Its new NodeId is the number of operands it has minus 1
396  // (as this node is now processed).
397  assert(NodeId == Unanalyzed && "Unknown node ID!");
398  User->setNodeId(User->getNumOperands() - 1);
399 
400  // If the node only has a single operand, it is now ready.
401  if (User->getNumOperands() == 1)
402  Worklist.push_back(User);
403  }
404  }
405 
406 #ifndef EXPENSIVE_CHECKS
408 #endif
409  PerformExpensiveChecks();
410 
411  // If the root changed (e.g. it was a dead load) update the root.
412  DAG.setRoot(Dummy.getValue());
413 
414  // Remove dead nodes. This is important to do for cleanliness but also before
415  // the checking loop below. Implicit folding by the DAG.getNode operators and
416  // node morphing can cause unreachable nodes to be around with their flags set
417  // to new.
418  DAG.RemoveDeadNodes();
419 
420  // In a debug build, scan all the nodes to make sure we found them all. This
421  // ensures that there are no cycles and that everything got processed.
422 #ifndef NDEBUG
423  for (SDNode &Node : DAG.allnodes()) {
424  bool Failed = false;
425 
426  // Check that all result types are legal.
427  // A value type is illegal if its TypeAction is not TypeLegal,
428  // and TLI.RegClassForVT does not have a register class for this type.
429  // For example, the x86_64 target has f128 that is not TypeLegal,
430  // to have softened operators, but it also has FR128 register class to
431  // pass and return f128 values. Hence a legalized node can have f128 type.
432  if (!IgnoreNodeResults(&Node))
433  for (unsigned i = 0, NumVals = Node.getNumValues(); i < NumVals; ++i)
434  if (!isTypeLegal(Node.getValueType(i)) &&
435  !TLI.isTypeLegal(Node.getValueType(i))) {
436  dbgs() << "Result type " << i << " illegal: ";
437  Node.dump();
438  Failed = true;
439  }
440 
441  // Check that all operand types are legal.
442  for (unsigned i = 0, NumOps = Node.getNumOperands(); i < NumOps; ++i)
443  if (!IgnoreNodeResults(Node.getOperand(i).getNode()) &&
444  !isTypeLegal(Node.getOperand(i).getValueType()) &&
445  !TLI.isTypeLegal(Node.getOperand(i).getValueType())) {
446  dbgs() << "Operand type " << i << " illegal: ";
447  Node.getOperand(i).dump();
448  Failed = true;
449  }
450 
451  if (Node.getNodeId() != Processed) {
452  if (Node.getNodeId() == NewNode)
453  dbgs() << "New node not analyzed?\n";
454  else if (Node.getNodeId() == Unanalyzed)
455  dbgs() << "Unanalyzed node not noticed?\n";
456  else if (Node.getNodeId() > 0)
457  dbgs() << "Operand not processed?\n";
458  else if (Node.getNodeId() == ReadyToProcess)
459  dbgs() << "Not added to worklist?\n";
460  Failed = true;
461  }
462 
463  if (Failed) {
464  Node.dump(&DAG); dbgs() << "\n";
465  llvm_unreachable(nullptr);
466  }
467  }
468 #endif
469 
470  return Changed;
471 }
472 
473 /// The specified node is the root of a subtree of potentially new nodes.
474 /// Correct any processed operands (this may change the node) and calculate the
475 /// NodeId. If the node itself changes to a processed node, it is not remapped -
476 /// the caller needs to take care of this. Returns the potentially changed node.
477 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
478  // If this was an existing node that is already done, we're done.
479  if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
480  return N;
481 
482  // Remove any stale map entries.
483  ExpungeNode(N);
484 
485  // Okay, we know that this node is new. Recursively walk all of its operands
486  // to see if they are new also. The depth of this walk is bounded by the size
487  // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
488  // about revisiting of nodes.
489  //
490  // As we walk the operands, keep track of the number of nodes that are
491  // processed. If non-zero, this will become the new nodeid of this node.
492  // Operands may morph when they are analyzed. If so, the node will be
493  // updated after all operands have been analyzed. Since this is rare,
494  // the code tries to minimize overhead in the non-morphing case.
495 
496  std::vector<SDValue> NewOps;
497  unsigned NumProcessed = 0;
498  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
499  SDValue OrigOp = N->getOperand(i);
500  SDValue Op = OrigOp;
501 
502  AnalyzeNewValue(Op); // Op may morph.
503 
504  if (Op.getNode()->getNodeId() == Processed)
505  ++NumProcessed;
506 
507  if (!NewOps.empty()) {
508  // Some previous operand changed. Add this one to the list.
509  NewOps.push_back(Op);
510  } else if (Op != OrigOp) {
511  // This is the first operand to change - add all operands so far.
512  NewOps.insert(NewOps.end(), N->op_begin(), N->op_begin() + i);
513  NewOps.push_back(Op);
514  }
515  }
516 
517  // Some operands changed - update the node.
518  if (!NewOps.empty()) {
519  SDNode *M = DAG.UpdateNodeOperands(N, NewOps);
520  if (M != N) {
521  // The node morphed into a different node. Normally for this to happen
522  // the original node would have to be marked NewNode. However this can
523  // in theory momentarily not be the case while ReplaceValueWith is doing
524  // its stuff. Mark the original node NewNode to help sanity checking.
525  N->setNodeId(NewNode);
526  if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
527  // It morphed into a previously analyzed node - nothing more to do.
528  return M;
529 
530  // It morphed into a different new node. Do the equivalent of passing
531  // it to AnalyzeNewNode: expunge it and calculate the NodeId. No need
532  // to remap the operands, since they are the same as the operands we
533  // remapped above.
534  N = M;
535  ExpungeNode(N);
536  }
537  }
538 
539  // Calculate the NodeId.
540  N->setNodeId(N->getNumOperands() - NumProcessed);
541  if (N->getNodeId() == ReadyToProcess)
542  Worklist.push_back(N);
543 
544  return N;
545 }
546 
547 /// Call AnalyzeNewNode, updating the node in Val if needed.
548 /// If the node changes to a processed node, then remap it.
549 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
550  Val.setNode(AnalyzeNewNode(Val.getNode()));
551  if (Val.getNode()->getNodeId() == Processed)
552  // We were passed a processed node, or it morphed into one - remap it.
553  RemapValue(Val);
554 }
555 
556 /// If N has a bogus mapping in ReplacedValues, eliminate it.
557 /// This can occur when a node is deleted then reallocated as a new node -
558 /// the mapping in ReplacedValues applies to the deleted node, not the new
559 /// one.
560 /// The only map that can have a deleted node as a source is ReplacedValues.
561 /// Other maps can have deleted nodes as targets, but since their looked-up
562 /// values are always immediately remapped using RemapValue, resulting in a
563 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
564 /// always performs correct mappings. In order to keep the mapping correct,
565 /// ExpungeNode should be called on any new nodes *before* adding them as
566 /// either source or target to ReplacedValues (which typically means calling
567 /// Expunge when a new node is first seen, since it may no longer be marked
568 /// NewNode by the time it is added to ReplacedValues).
569 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
570  if (N->getNodeId() != NewNode)
571  return;
572 
573  // If N is not remapped by ReplacedValues then there is nothing to do.
574  unsigned i, e;
575  for (i = 0, e = N->getNumValues(); i != e; ++i)
576  if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
577  break;
578 
579  if (i == e)
580  return;
581 
582  // Remove N from all maps - this is expensive but rare.
583 
584  for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
585  E = PromotedIntegers.end(); I != E; ++I) {
586  assert(I->first.getNode() != N);
587  RemapValue(I->second);
588  }
589 
590  for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
591  E = SoftenedFloats.end(); I != E; ++I) {
592  assert(I->first.getNode() != N);
593  RemapValue(I->second);
594  }
595 
596  for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
597  E = ScalarizedVectors.end(); I != E; ++I) {
598  assert(I->first.getNode() != N);
599  RemapValue(I->second);
600  }
601 
602  for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(),
603  E = WidenedVectors.end(); I != E; ++I) {
604  assert(I->first.getNode() != N);
605  RemapValue(I->second);
606  }
607 
608  for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
609  I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
610  assert(I->first.getNode() != N);
611  RemapValue(I->second.first);
612  RemapValue(I->second.second);
613  }
614 
615  for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
616  I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
617  assert(I->first.getNode() != N);
618  RemapValue(I->second.first);
619  RemapValue(I->second.second);
620  }
621 
622  for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
623  I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
624  assert(I->first.getNode() != N);
625  RemapValue(I->second.first);
626  RemapValue(I->second.second);
627  }
628 
629  for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
630  E = ReplacedValues.end(); I != E; ++I)
631  RemapValue(I->second);
632 
633  for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
634  ReplacedValues.erase(SDValue(N, i));
635 }
636 
637 /// If the specified value was already legalized to another value,
638 /// replace it by that value.
639 void DAGTypeLegalizer::RemapValue(SDValue &N) {
640  DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
641  if (I != ReplacedValues.end()) {
642  // Use path compression to speed up future lookups if values get multiply
643  // replaced with other values.
644  RemapValue(I->second);
645  N = I->second;
646 
647  // Note that it is possible to have N.getNode()->getNodeId() == NewNode at
648  // this point because it is possible for a node to be put in the map before
649  // being processed.
650  }
651 }
652 
653 namespace {
654  /// This class is a DAGUpdateListener that listens for updates to nodes and
655  /// recomputes their ready state.
656  class NodeUpdateListener : public SelectionDAG::DAGUpdateListener {
657  DAGTypeLegalizer &DTL;
658  SmallSetVector<SDNode*, 16> &NodesToAnalyze;
659  public:
660  explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
662  : SelectionDAG::DAGUpdateListener(dtl.getDAG()),
663  DTL(dtl), NodesToAnalyze(nta) {}
664 
665  void NodeDeleted(SDNode *N, SDNode *E) override {
668  "Invalid node ID for RAUW deletion!");
669  // It is possible, though rare, for the deleted node N to occur as a
670  // target in a map, so note the replacement N -> E in ReplacedValues.
671  assert(E && "Node not replaced?");
672  DTL.NoteDeletion(N, E);
673 
674  // In theory the deleted node could also have been scheduled for analysis.
675  // So remove it from the set of nodes which will be analyzed.
676  NodesToAnalyze.remove(N);
677 
678  // In general nothing needs to be done for E, since it didn't change but
679  // only gained new uses. However N -> E was just added to ReplacedValues,
680  // and the result of a ReplacedValues mapping is not allowed to be marked
681  // NewNode. So if E is marked NewNode, then it needs to be analyzed.
683  NodesToAnalyze.insert(E);
684  }
685 
686  void NodeUpdated(SDNode *N) override {
687  // Node updates can mean pretty much anything. It is possible that an
688  // operand was set to something already processed (f.e.) in which case
689  // this node could become ready. Recompute its flags.
692  "Invalid node ID for RAUW deletion!");
694  NodesToAnalyze.insert(N);
695  }
696  };
697 }
698 
699 
700 /// The specified value was legalized to the specified other value.
701 /// Update the DAG and NodeIds replacing any uses of From to use To instead.
702 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
703  assert(From.getNode() != To.getNode() && "Potential legalization loop!");
704 
705  // If expansion produced new nodes, make sure they are properly marked.
706  ExpungeNode(From.getNode());
707  AnalyzeNewValue(To); // Expunges To.
708 
709  // Anything that used the old node should now use the new one. Note that this
710  // can potentially cause recursive merging.
711  SmallSetVector<SDNode*, 16> NodesToAnalyze;
712  NodeUpdateListener NUL(*this, NodesToAnalyze);
713  do {
714  DAG.ReplaceAllUsesOfValueWith(From, To);
715 
716  // The old node may still be present in a map like ExpandedIntegers or
717  // PromotedIntegers. Inform maps about the replacement.
718  ReplacedValues[From] = To;
719 
720  // Process the list of nodes that need to be reanalyzed.
721  while (!NodesToAnalyze.empty()) {
722  SDNode *N = NodesToAnalyze.back();
723  NodesToAnalyze.pop_back();
725  // The node was analyzed while reanalyzing an earlier node - it is safe
726  // to skip. Note that this is not a morphing node - otherwise it would
727  // still be marked NewNode.
728  continue;
729 
730  // Analyze the node's operands and recalculate the node ID.
731  SDNode *M = AnalyzeNewNode(N);
732  if (M != N) {
733  // The node morphed into a different node. Make everyone use the new
734  // node instead.
735  assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
736  assert(N->getNumValues() == M->getNumValues() &&
737  "Node morphing changed the number of results!");
738  for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
739  SDValue OldVal(N, i);
740  SDValue NewVal(M, i);
741  if (M->getNodeId() == Processed)
742  RemapValue(NewVal);
743  DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal);
744  // OldVal may be a target of the ReplacedValues map which was marked
745  // NewNode to force reanalysis because it was updated. Ensure that
746  // anything that ReplacedValues mapped to OldVal will now be mapped
747  // all the way to NewVal.
748  ReplacedValues[OldVal] = NewVal;
749  }
750  // The original node continues to exist in the DAG, marked NewNode.
751  }
752  }
753  // When recursively update nodes with new nodes, it is possible to have
754  // new uses of From due to CSE. If this happens, replace the new uses of
755  // From with To.
756  } while (!From.use_empty());
757 }
758 
759 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
760  assert(Result.getValueType() ==
761  TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
762  "Invalid type for promoted integer");
763  AnalyzeNewValue(Result);
764 
765  SDValue &OpEntry = PromotedIntegers[Op];
766  assert(!OpEntry.getNode() && "Node is already promoted!");
767  OpEntry = Result;
768 }
769 
770 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
771  // f128 of x86_64 could be kept in SSE registers,
772  // but sometimes softened to i128.
773  assert((Result.getValueType() ==
774  TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) ||
775  Op.getValueType() ==
776  TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType())) &&
777  "Invalid type for softened float");
778  AnalyzeNewValue(Result);
779 
780  SDValue &OpEntry = SoftenedFloats[Op];
781  // Allow repeated calls to save f128 type nodes
782  // or any node with type that transforms to itself.
783  // Many operations on these types are not softened.
784  assert((!OpEntry.getNode()||
785  Op.getValueType() ==
786  TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType())) &&
787  "Node is already converted to integer!");
788  OpEntry = Result;
789 }
790 
791 void DAGTypeLegalizer::SetPromotedFloat(SDValue Op, SDValue Result) {
792  assert(Result.getValueType() ==
793  TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
794  "Invalid type for promoted float");
795  AnalyzeNewValue(Result);
796 
797  SDValue &OpEntry = PromotedFloats[Op];
798  assert(!OpEntry.getNode() && "Node is already promoted!");
799  OpEntry = Result;
800 }
801 
802 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
803  // Note that in some cases vector operation operands may be greater than
804  // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
805  // a constant i8 operand.
807  "Invalid type for scalarized vector");
808  AnalyzeNewValue(Result);
809 
810  SDValue &OpEntry = ScalarizedVectors[Op];
811  assert(!OpEntry.getNode() && "Node is already scalarized!");
812  OpEntry = Result;
813 }
814 
815 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
816  SDValue &Hi) {
817  std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
818  RemapValue(Entry.first);
819  RemapValue(Entry.second);
820  assert(Entry.first.getNode() && "Operand isn't expanded");
821  Lo = Entry.first;
822  Hi = Entry.second;
823 }
824 
825 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
826  SDValue Hi) {
827  assert(Lo.getValueType() ==
828  TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
829  Hi.getValueType() == Lo.getValueType() &&
830  "Invalid type for expanded integer");
831  // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
832  AnalyzeNewValue(Lo);
833  AnalyzeNewValue(Hi);
834 
835  // Remember that this is the result of the node.
836  std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
837  assert(!Entry.first.getNode() && "Node already expanded");
838  Entry.first = Lo;
839  Entry.second = Hi;
840 }
841 
842 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
843  SDValue &Hi) {
844  std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
845  RemapValue(Entry.first);
846  RemapValue(Entry.second);
847  assert(Entry.first.getNode() && "Operand isn't expanded");
848  Lo = Entry.first;
849  Hi = Entry.second;
850 }
851 
852 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
853  SDValue Hi) {
854  assert(Lo.getValueType() ==
855  TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
856  Hi.getValueType() == Lo.getValueType() &&
857  "Invalid type for expanded float");
858  // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
859  AnalyzeNewValue(Lo);
860  AnalyzeNewValue(Hi);
861 
862  // Remember that this is the result of the node.
863  std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
864  assert(!Entry.first.getNode() && "Node already expanded");
865  Entry.first = Lo;
866  Entry.second = Hi;
867 }
868 
869 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
870  SDValue &Hi) {
871  std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
872  RemapValue(Entry.first);
873  RemapValue(Entry.second);
874  assert(Entry.first.getNode() && "Operand isn't split");
875  Lo = Entry.first;
876  Hi = Entry.second;
877 }
878 
879 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
880  SDValue Hi) {
885  Hi.getValueType() == Lo.getValueType() &&
886  "Invalid type for split vector");
887  // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
888  AnalyzeNewValue(Lo);
889  AnalyzeNewValue(Hi);
890 
891  // Remember that this is the result of the node.
892  std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
893  assert(!Entry.first.getNode() && "Node already split");
894  Entry.first = Lo;
895  Entry.second = Hi;
896 }
897 
898 void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
899  assert(Result.getValueType() ==
900  TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
901  "Invalid type for widened vector");
902  AnalyzeNewValue(Result);
903 
904  SDValue &OpEntry = WidenedVectors[Op];
905  assert(!OpEntry.getNode() && "Node already widened!");
906  OpEntry = Result;
907 }
908 
909 
910 //===----------------------------------------------------------------------===//
911 // Utilities.
912 //===----------------------------------------------------------------------===//
913 
914 /// Convert to an integer of the same size.
915 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
916  unsigned BitWidth = Op.getValueSizeInBits();
917  return DAG.getNode(ISD::BITCAST, SDLoc(Op),
918  EVT::getIntegerVT(*DAG.getContext(), BitWidth), Op);
919 }
920 
921 /// Convert to a vector of integers of the same size.
922 SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
923  assert(Op.getValueType().isVector() && "Only applies to vectors!");
924  unsigned EltWidth = Op.getScalarValueSizeInBits();
925  EVT EltNVT = EVT::getIntegerVT(*DAG.getContext(), EltWidth);
926  auto EltCnt = Op.getValueType().getVectorElementCount();
927  return DAG.getNode(ISD::BITCAST, SDLoc(Op),
928  EVT::getVectorVT(*DAG.getContext(), EltNVT, EltCnt), Op);
929 }
930 
931 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
932  EVT DestVT) {
933  SDLoc dl(Op);
934  // Create the stack frame object. Make sure it is aligned for both
935  // the source and destination types.
936  SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
937  // Emit a store to the stack slot.
938  SDValue Store =
939  DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr, MachinePointerInfo());
940  // Result is a load from the stack slot.
941  return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo());
942 }
943 
944 /// Replace the node's results with custom code provided by the target and
945 /// return "true", or do nothing and return "false".
946 /// The last parameter is FALSE if we are dealing with a node with legal
947 /// result types and illegal operand. The second parameter denotes the type of
948 /// illegal OperandNo in that case.
949 /// The last parameter being TRUE means we are dealing with a
950 /// node with illegal result types. The second parameter denotes the type of
951 /// illegal ResNo in that case.
952 bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
953  // See if the target wants to custom lower this node.
955  return false;
956 
958  if (LegalizeResult)
959  TLI.ReplaceNodeResults(N, Results, DAG);
960  else
961  TLI.LowerOperationWrapper(N, Results, DAG);
962 
963  if (Results.empty())
964  // The target didn't want to custom lower it after all.
965  return false;
966 
967  // When called from DAGTypeLegalizer::ExpandIntegerResult, we might need to
968  // provide the same kind of custom splitting behavior.
969  if (Results.size() == N->getNumValues() + 1 && LegalizeResult) {
970  // We've legalized a return type by splitting it. If there is a chain,
971  // replace that too.
972  SetExpandedInteger(SDValue(N, 0), Results[0], Results[1]);
973  if (N->getNumValues() > 1)
974  ReplaceValueWith(SDValue(N, 1), Results[2]);
975  return true;
976  }
977 
978  // Make everything that once used N's values now use those in Results instead.
979  assert(Results.size() == N->getNumValues() &&
980  "Custom lowering returned the wrong number of results!");
981  for (unsigned i = 0, e = Results.size(); i != e; ++i) {
982  ReplaceValueWith(SDValue(N, i), Results[i]);
983  }
984  return true;
985 }
986 
987 
988 /// Widen the node's results with custom code provided by the target and return
989 /// "true", or do nothing and return "false".
990 bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
991  // See if the target wants to custom lower this node.
993  return false;
994 
996  TLI.ReplaceNodeResults(N, Results, DAG);
997 
998  if (Results.empty())
999  // The target didn't want to custom widen lower its result after all.
1000  return false;
1001 
1002  // Update the widening map.
1003  assert(Results.size() == N->getNumValues() &&
1004  "Custom lowering returned the wrong number of results!");
1005  for (unsigned i = 0, e = Results.size(); i != e; ++i)
1006  SetWidenedVector(SDValue(N, i), Results[i]);
1007  return true;
1008 }
1009 
1010 SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
1011  for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
1012  if (i != ResNo)
1013  ReplaceValueWith(SDValue(N, i), SDValue(N->getOperand(i)));
1014  return SDValue(N->getOperand(ResNo));
1015 }
1016 
1017 /// Use ISD::EXTRACT_ELEMENT nodes to extract the low and high parts of the
1018 /// given value.
1019 void DAGTypeLegalizer::GetPairElements(SDValue Pair,
1020  SDValue &Lo, SDValue &Hi) {
1021  SDLoc dl(Pair);
1022  EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), Pair.getValueType());
1023  Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
1024  DAG.getIntPtrConstant(0, dl));
1025  Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
1026  DAG.getIntPtrConstant(1, dl));
1027 }
1028 
1029 /// Build an integer with low bits Lo and high bits Hi.
1030 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
1031  // Arbitrarily use dlHi for result SDLoc
1032  SDLoc dlHi(Hi);
1033  SDLoc dlLo(Lo);
1034  EVT LVT = Lo.getValueType();
1035  EVT HVT = Hi.getValueType();
1036  EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1037  LVT.getSizeInBits() + HVT.getSizeInBits());
1038 
1039  Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
1040  Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
1041  Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
1042  DAG.getConstant(LVT.getSizeInBits(), dlHi,
1043  TLI.getPointerTy(DAG.getDataLayout())));
1044  return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
1045 }
1046 
1047 /// Convert the node into a libcall with the same prototype.
1048 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
1049  bool isSigned) {
1050  unsigned NumOps = N->getNumOperands();
1051  SDLoc dl(N);
1052  if (NumOps == 0) {
1053  return TLI.makeLibCall(DAG, LC, N->getValueType(0), None, isSigned,
1054  dl).first;
1055  } else if (NumOps == 1) {
1056  SDValue Op = N->getOperand(0);
1057  return TLI.makeLibCall(DAG, LC, N->getValueType(0), Op, isSigned,
1058  dl).first;
1059  } else if (NumOps == 2) {
1060  SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1061  return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, isSigned,
1062  dl).first;
1063  }
1064  SmallVector<SDValue, 8> Ops(NumOps);
1065  for (unsigned i = 0; i < NumOps; ++i)
1066  Ops[i] = N->getOperand(i);
1067 
1068  return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, isSigned, dl).first;
1069 }
1070 
1071 /// Expand a node into a call to a libcall. Similar to ExpandLibCall except that
1072 /// the first operand is the in-chain.
1073 std::pair<SDValue, SDValue>
1074 DAGTypeLegalizer::ExpandChainLibCall(RTLIB::Libcall LC, SDNode *Node,
1075  bool isSigned) {
1076  SDValue InChain = Node->getOperand(0);
1077 
1079  TargetLowering::ArgListEntry Entry;
1080  for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
1081  EVT ArgVT = Node->getOperand(i).getValueType();
1082  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1083  Entry.Node = Node->getOperand(i);
1084  Entry.Ty = ArgTy;
1085  Entry.IsSExt = isSigned;
1086  Entry.IsZExt = !isSigned;
1087  Args.push_back(Entry);
1088  }
1089  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1090  TLI.getPointerTy(DAG.getDataLayout()));
1091 
1092  Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1093 
1095  CLI.setDebugLoc(SDLoc(Node))
1096  .setChain(InChain)
1097  .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
1098  std::move(Args))
1099  .setSExtResult(isSigned)
1100  .setZExtResult(!isSigned);
1101 
1102  std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
1103 
1104  return CallInfo;
1105 }
1106 
1107 /// Promote the given target boolean to a target boolean of the given type.
1108 /// A target boolean is an integer value, not necessarily of type i1, the bits
1109 /// of which conform to getBooleanContents.
1110 ///
1111 /// ValVT is the type of values that produced the boolean.
1112 SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT ValVT) {
1113  SDLoc dl(Bool);
1114  EVT BoolVT = getSetCCResultType(ValVT);
1115  ISD::NodeType ExtendCode =
1117  return DAG.getNode(ExtendCode, dl, BoolVT, Bool);
1118 }
1119 
1120 /// Widen the given target boolean to a target boolean of the given type.
1121 /// The boolean vector is widened and then promoted to match the target boolean
1122 /// type of the given ValVT.
1123 SDValue DAGTypeLegalizer::WidenTargetBoolean(SDValue Bool, EVT ValVT,
1124  bool WithZeroes) {
1125  SDLoc dl(Bool);
1126  EVT BoolVT = Bool.getValueType();
1127 
1128  assert(ValVT.getVectorNumElements() > BoolVT.getVectorNumElements() &&
1129  TLI.isTypeLegal(ValVT) &&
1130  "Unexpected types in WidenTargetBoolean");
1131  EVT WideVT = EVT::getVectorVT(*DAG.getContext(), BoolVT.getScalarType(),
1132  ValVT.getVectorNumElements());
1133  Bool = ModifyToType(Bool, WideVT, WithZeroes);
1134  return PromoteTargetBoolean(Bool, ValVT);
1135 }
1136 
1137 /// Return the lower LoVT bits of Op in Lo and the upper HiVT bits in Hi.
1138 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1139  EVT LoVT, EVT HiVT,
1140  SDValue &Lo, SDValue &Hi) {
1141  SDLoc dl(Op);
1142  assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
1143  Op.getValueSizeInBits() && "Invalid integer splitting!");
1144  Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
1145  Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
1146  DAG.getConstant(LoVT.getSizeInBits(), dl,
1147  TLI.getPointerTy(DAG.getDataLayout())));
1148  Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
1149 }
1150 
1151 /// Return the lower and upper halves of Op's bits in a value type half the
1152 /// size of Op's.
1153 void DAGTypeLegalizer::SplitInteger(SDValue Op,
1154  SDValue &Lo, SDValue &Hi) {
1155  EVT HalfVT =
1157  SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
1158 }
1159 
1160 
1161 //===----------------------------------------------------------------------===//
1162 // Entry Point
1163 //===----------------------------------------------------------------------===//
1164 
1165 /// This transforms the SelectionDAG into a SelectionDAG that only uses types
1166 /// natively supported by the target. Returns "true" if it made any changes.
1167 ///
1168 /// Note that this is an involved process that may invalidate pointers into
1169 /// the graph.
1171  return DAGTypeLegalizer(*this).run();
1172 }
SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes())
Helper function to build ISD::STORE nodes.
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
Definition: ISDOpcodes.h:544
CallingConv::ID getLibcallCallingConv(RTLIB::Libcall Call) const
Get the CallingConv that should be used for the specified libcall.
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant, which is required to be operand #1) half of the integer or float value specified as operand #0.
Definition: ISDOpcodes.h:184
LLVMContext * getContext() const
Definition: SelectionDAG.h:381
bool LegalizeTypes()
This transforms the SelectionDAG into a SelectionDAG that only uses types natively supported by the t...
Clients of various APIs that cause global effects on the DAG can optionally implement this interface...
Definition: SelectionDAG.h:262
Libcall
RTLIB::Libcall enum - This enum defines all of the runtime library calls the backend can emit...
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
static ISD::NodeType getExtendForContent(BooleanContent Content)
Function Alias Analysis Results
Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
Definition: ValueTypes.cpp:205
unsigned getNumOperands() const
Return the number of values used by this operation.
unsigned getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned Num) const
This takes an arbitrary SelectionDAG as input and hacks on it until only value types the target machi...
Definition: LegalizeTypes.h:32
void setNodeId(int Id)
Set unique node id.
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
Definition: SelectionDAG.h:440
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition: ISDOpcodes.h:39
SDValue getExternalSymbol(const char *Sym, EVT VT)
bool isVector() const
Return true if this is a vector value type.
Definition: ValueTypes.h:151
SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
This node's ID needs to be set to the number of its unprocessed operands.
Definition: LegalizeTypes.h:48
Shift and rotation operations.
Definition: ISDOpcodes.h:378
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition: ValueTypes.h:260
void pop_back()
Remove the last element of the SetVector.
Definition: SetVector.h:222
iterator_range< allnodes_iterator > allnodes()
Definition: SelectionDAG.h:423
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition: ValueTypes.h:265
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:73
const DataLayout & getDataLayout() const
Definition: SelectionDAG.h:376
static cl::opt< bool > EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden)
SDNode * getNode() const
get the SDNode which holds the desired result
bool run()
This is the main entry point for the type legalizer.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is a new node, not before seen, that was created in the process of legalizing some other node...
Definition: LegalizeTypes.h:44
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
unsigned getScalarValueSizeInBits() const
void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
This class provides iterator support for SDUse operands that use a specific SDNode.
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
std::vector< ArgListEntry > ArgListTy
Extended Value Type.
Definition: ValueTypes.h:34
This structure contains all information that is necessary for lowering calls.
BooleanContent getBooleanContents(bool isVec, bool isFloat) const
For targets without i1 registers, this gives the nature of the high-bits of boolean values held in ty...
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, ArrayRef< SDValue > Ops, bool isSigned, const SDLoc &dl, bool doesNotReturn=false, bool isReturnValueUsed=true) const
Returns a pair of (return value, chain).
This class contains a discriminated union of information about pointers in memory operands...
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
Definition: SelectionDAG.h:431
SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, unsigned Alignment=0, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr)
Loads are not normal binary operators: their result type is not determined by their operands...
SDValue CreateStackTemporary(EVT VT, unsigned minAlign=1)
Create a stack temporary, suitable for holding the specified value type.
unsigned first
uint32_t NodeId
Definition: RDFGraph.h:263
virtual void ReplaceNodeResults(SDNode *, SmallVectorImpl< SDValue > &, SelectionDAG &) const
This callback is invoked when a node result type is illegal for the target, and the operation was reg...
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:298
#define E
Definition: LargeTest.cpp:27
void dump() const
Dump this node, for debugging.
void setNode(SDNode *N)
set the SDNode
const char * getLibcallName(RTLIB::Libcall Call) const
Get the libcall routine name for the specified libcall.
SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:209
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
const size_t N
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
This is a node that has already been processed.
Definition: LegalizeTypes.h:51
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT...
Definition: ValueTypes.h:73
op_iterator op_begin() const
static use_iterator use_end()
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition: ISDOpcodes.h:444
MVT::ElementCount getVectorElementCount() const
Definition: ValueTypes.h:281
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition: ISDOpcodes.h:447
llvm_unreachable("Unknown RegBank!")
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:292
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
const T & back() const
Return the last element of the SetVector.
Definition: SetVector.h:129
int getNodeId() const
Return the unique node id.
EVT getValueType() const
Return the ValueType of the referenced return value.
SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
This class is used to form a handle around another node that is persistent and is updated across invo...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
All operands have been processed, so this node is ready to be handled.
Definition: LegalizeTypes.h:40
void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.Val alone...
#define DEBUG(X)
Definition: Debug.h:118
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
Definition: SelectionDAG.h:434
TRUNCATE - Completely drop the high bits.
Definition: ISDOpcodes.h:450
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition: ValueTypes.h:64
virtual void LowerOperationWrapper(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const
This callback is invoked by the type legalizer to legalize nodes with an illegal operand type but leg...
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition: ValueTypes.h:273