LegalizeTypes.cpp revision 193323
1226048Sobrien//===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
268349Sobrien//
3267843Sdelphij//                     The LLVM Compiler Infrastructure
468349Sobrien//
568349Sobrien// This file is distributed under the University of Illinois Open Source
668349Sobrien// License. See LICENSE.TXT for details.
768349Sobrien//
868349Sobrien//===----------------------------------------------------------------------===//
968349Sobrien//
1068349Sobrien// This file implements the SelectionDAG::LegalizeTypes method.  It transforms
1168349Sobrien// an arbitrary well-formed SelectionDAG to only consist of legal types.  This
1268349Sobrien// is common code shared among the LegalizeTypes*.cpp files.
1368349Sobrien//
1468349Sobrien//===----------------------------------------------------------------------===//
1568349Sobrien
1668349Sobrien#include "LegalizeTypes.h"
1768349Sobrien#include "llvm/CallingConv.h"
1868349Sobrien#include "llvm/ADT/SetVector.h"
1968349Sobrien#include "llvm/Support/CommandLine.h"
2068349Sobrien#include "llvm/Target/TargetData.h"
2168349Sobrienusing namespace llvm;
2268349Sobrien
2368349Sobrienstatic cl::opt<bool>
2468349SobrienEnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
2568349Sobrien
2668349Sobrien/// PerformExpensiveChecks - Do extensive, expensive, sanity checking.
2768349Sobrienvoid DAGTypeLegalizer::PerformExpensiveChecks() {
2868349Sobrien  // If a node is not processed, then none of its values should be mapped by any
2968349Sobrien  // of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
3068349Sobrien
3168349Sobrien  // If a node is processed, then each value with an illegal type must be mapped
3268349Sobrien  // by exactly one of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
3368349Sobrien  // Values with a legal type may be mapped by ReplacedValues, but not by any of
3468349Sobrien  // the other maps.
3568349Sobrien
3668349Sobrien  // Note that these invariants may not hold momentarily when processing a node:
3768349Sobrien  // the node being processed may be put in a map before being marked Processed.
3868349Sobrien
3968349Sobrien  // Note that it is possible to have nodes marked NewNode in the DAG.  This can
4068349Sobrien  // occur in two ways.  Firstly, a node may be created during legalization but
4168349Sobrien  // never passed to the legalization core.  This is usually due to the implicit
4268349Sobrien  // folding that occurs when using the DAG.getNode operators.  Secondly, a new
4368349Sobrien  // node may be passed to the legalization core, but when analyzed may morph
44267843Sdelphij  // into a different node, leaving the original node as a NewNode in the DAG.
4568349Sobrien  // A node may morph if one of its operands changes during analysis.  Whether
4668349Sobrien  // it actually morphs or not depends on whether, after updating its operands,
47267843Sdelphij  // it is equivalent to an existing node: if so, it morphs into that existing
4868349Sobrien  // node (CSE).  An operand can change during analysis if the operand is a new
4968349Sobrien  // node that morphs, or it is a processed value that was mapped to some other
5068349Sobrien  // value (as recorded in ReplacedValues) in which case the operand is turned
5168349Sobrien  // into that other value.  If a node morphs then the node it morphed into will
5268349Sobrien  // be used instead of it for legalization, however the original node continues
5368349Sobrien  // to live on in the DAG.
5468349Sobrien  // The conclusion is that though there may be nodes marked NewNode in the DAG,
5568349Sobrien  // all uses of such nodes are also marked NewNode: the result is a fungus of
5668349Sobrien  // NewNodes growing on top of the useful nodes, and perhaps using them, but
5768349Sobrien  // not used by them.
5868349Sobrien
5968349Sobrien  // If a value is mapped by ReplacedValues, then it must have no uses, except
6068349Sobrien  // by nodes marked NewNode (see above).
6168349Sobrien
6268349Sobrien  // The final node obtained by mapping by ReplacedValues is not marked NewNode.
6368349Sobrien  // Note that ReplacedValues should be applied iteratively.
6468349Sobrien
6568349Sobrien  // Note that the ReplacedValues map may also map deleted nodes.  By iterating
6668349Sobrien  // over the DAG we only consider non-deleted nodes.
6768349Sobrien  SmallVector<SDNode*, 16> NewNodes;
6868349Sobrien  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
6968349Sobrien       E = DAG.allnodes_end(); I != E; ++I) {
7068349Sobrien    // Remember nodes marked NewNode - they are subject to extra checking below.
7168349Sobrien    if (I->getNodeId() == NewNode)
7268349Sobrien      NewNodes.push_back(I);
7368349Sobrien
7468349Sobrien    for (unsigned i = 0, e = I->getNumValues(); i != e; ++i) {
7568349Sobrien      SDValue Res(I, i);
7668349Sobrien      bool Failed = false;
7768349Sobrien
7868349Sobrien      unsigned Mapped = 0;
7968349Sobrien      if (ReplacedValues.find(Res) != ReplacedValues.end()) {
8068349Sobrien        Mapped |= 1;
8168349Sobrien        // Check that remapped values are only used by nodes marked NewNode.
8268349Sobrien        for (SDNode::use_iterator UI = I->use_begin(), UE = I->use_end();
8368349Sobrien             UI != UE; ++UI)
8468349Sobrien          if (UI.getUse().getResNo() == i)
8568349Sobrien            assert(UI->getNodeId() == NewNode &&
8668349Sobrien                   "Remapped value has non-trivial use!");
8768349Sobrien
8868349Sobrien        // Check that the final result of applying ReplacedValues is not
8968349Sobrien        // marked NewNode.
9068349Sobrien        SDValue NewVal = ReplacedValues[Res];
9168349Sobrien        DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal);
9268349Sobrien        while (I != ReplacedValues.end()) {
9368349Sobrien          NewVal = I->second;
9468349Sobrien          I = ReplacedValues.find(NewVal);
9568349Sobrien        }
9668349Sobrien        assert(NewVal.getNode()->getNodeId() != NewNode &&
9768349Sobrien               "ReplacedValues maps to a new node!");
9868349Sobrien      }
9968349Sobrien      if (PromotedIntegers.find(Res) != PromotedIntegers.end())
10068349Sobrien        Mapped |= 2;
10168349Sobrien      if (SoftenedFloats.find(Res) != SoftenedFloats.end())
10268349Sobrien        Mapped |= 4;
10368349Sobrien      if (ScalarizedVectors.find(Res) != ScalarizedVectors.end())
10468349Sobrien        Mapped |= 8;
10568349Sobrien      if (ExpandedIntegers.find(Res) != ExpandedIntegers.end())
10668349Sobrien        Mapped |= 16;
10768349Sobrien      if (ExpandedFloats.find(Res) != ExpandedFloats.end())
10868349Sobrien        Mapped |= 32;
10968349Sobrien      if (SplitVectors.find(Res) != SplitVectors.end())
11068349Sobrien        Mapped |= 64;
11168349Sobrien      if (WidenedVectors.find(Res) != WidenedVectors.end())
11268349Sobrien        Mapped |= 128;
11368349Sobrien
11468349Sobrien      if (I->getNodeId() != Processed) {
11568349Sobrien        if (Mapped != 0) {
11668349Sobrien          cerr << "Unprocessed value in a map!";
11768349Sobrien          Failed = true;
11868349Sobrien        }
11968349Sobrien      } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) {
12068349Sobrien        if (Mapped > 1) {
12168349Sobrien          cerr << "Value with legal type was transformed!";
12268349Sobrien          Failed = true;
12368349Sobrien        }
12468349Sobrien      } else {
12568349Sobrien        if (Mapped == 0) {
12668349Sobrien          cerr << "Processed value not in any map!";
12768349Sobrien          Failed = true;
12868349Sobrien        } else if (Mapped & (Mapped - 1)) {
12968349Sobrien          cerr << "Value in multiple maps!";
13068349Sobrien          Failed = true;
131267843Sdelphij        }
13268349Sobrien      }
13368349Sobrien
134267843Sdelphij      if (Failed) {
13568349Sobrien        if (Mapped & 1)
13668349Sobrien          cerr << " ReplacedValues";
137267843Sdelphij        if (Mapped & 2)
13868349Sobrien          cerr << " PromotedIntegers";
13968349Sobrien        if (Mapped & 4)
14068349Sobrien          cerr << " SoftenedFloats";
141267843Sdelphij        if (Mapped & 8)
14268349Sobrien          cerr << " ScalarizedVectors";
14368349Sobrien        if (Mapped & 16)
14468349Sobrien          cerr << " ExpandedIntegers";
14568349Sobrien        if (Mapped & 32)
14668349Sobrien          cerr << " ExpandedFloats";
14768349Sobrien        if (Mapped & 64)
148267843Sdelphij          cerr << " SplitVectors";
14968349Sobrien        if (Mapped & 128)
15068349Sobrien          cerr << " WidenedVectors";
15168349Sobrien        cerr << "\n";
15268349Sobrien        abort();
15368349Sobrien      }
15468349Sobrien    }
155267843Sdelphij  }
15668349Sobrien
15768349Sobrien  // Checked that NewNodes are only used by other NewNodes.
15868349Sobrien  for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
15968349Sobrien    SDNode *N = NewNodes[i];
16068349Sobrien    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16168349Sobrien         UI != UE; ++UI)
162267843Sdelphij      assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
16368349Sobrien  }
16468349Sobrien}
16568349Sobrien
16668349Sobrien/// run - This is the main entry point for the type legalizer.  This does a
16768349Sobrien/// top-down traversal of the dag, legalizing types as it goes.  Returns "true"
16868349Sobrien/// if it made any changes.
169267843Sdelphijbool DAGTypeLegalizer::run() {
17068349Sobrien  bool Changed = false;
17168349Sobrien
17268349Sobrien  // Create a dummy node (which is not added to allnodes), that adds a reference
173267843Sdelphij  // to the root node, preventing it from being deleted, and tracking any
17468349Sobrien  // changes of the root.
17568349Sobrien  HandleSDNode Dummy(DAG.getRoot());
17668349Sobrien  Dummy.setNodeId(Unanalyzed);
177267843Sdelphij
17868349Sobrien  // The root of the dag may dangle to deleted nodes until the type legalizer is
17968349Sobrien  // done.  Set it to null to avoid confusion.
18068349Sobrien  DAG.setRoot(SDValue());
18168349Sobrien
182267843Sdelphij  // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
18368349Sobrien  // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
18468349Sobrien  // non-leaves.
18568349Sobrien  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
18668349Sobrien       E = DAG.allnodes_end(); I != E; ++I) {
18768349Sobrien    if (I->getNumOperands() == 0) {
18868349Sobrien      I->setNodeId(ReadyToProcess);
18968349Sobrien      Worklist.push_back(I);
19068349Sobrien    } else {
19168349Sobrien      I->setNodeId(Unanalyzed);
19268349Sobrien    }
19368349Sobrien  }
19468349Sobrien
195267843Sdelphij  // Now that we have a set of nodes to process, handle them all.
19668349Sobrien  while (!Worklist.empty()) {
19768349Sobrien#ifndef XDEBUG
19868349Sobrien    if (EnableExpensiveChecks)
19968349Sobrien#endif
20068349Sobrien      PerformExpensiveChecks();
20168349Sobrien
20268349Sobrien    SDNode *N = Worklist.back();
20368349Sobrien    Worklist.pop_back();
20468349Sobrien    assert(N->getNodeId() == ReadyToProcess &&
20568349Sobrien           "Node should be ready if on worklist!");
206186690Sobrien
207186690Sobrien    if (IgnoreNodeResults(N))
208186690Sobrien      goto ScanOperands;
209186690Sobrien
210186690Sobrien    // Scan the values produced by the node, checking to see if any result
211186690Sobrien    // types are illegal.
212186690Sobrien    for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
213186690Sobrien      MVT ResultVT = N->getValueType(i);
214186690Sobrien      switch (getTypeAction(ResultVT)) {
215186690Sobrien      default:
216186690Sobrien        assert(false && "Unknown action!");
217186690Sobrien      case Legal:
218186690Sobrien        break;
219186690Sobrien      // The following calls must take care of *all* of the node's results,
220186690Sobrien      // not just the illegal result they were passed (this includes results
221186690Sobrien      // with a legal type).  Results can be remapped using ReplaceValueWith,
222186690Sobrien      // or their promoted/expanded/etc values registered in PromotedIntegers,
223186690Sobrien      // ExpandedIntegers etc.
224186690Sobrien      case PromoteInteger:
225186690Sobrien        PromoteIntegerResult(N, i);
226186690Sobrien        Changed = true;
227186690Sobrien        goto NodeDone;
228186690Sobrien      case ExpandInteger:
229186690Sobrien        ExpandIntegerResult(N, i);
230186690Sobrien        Changed = true;
231186690Sobrien        goto NodeDone;
232186690Sobrien      case SoftenFloat:
233186690Sobrien        SoftenFloatResult(N, i);
234186690Sobrien        Changed = true;
235186690Sobrien        goto NodeDone;
236186690Sobrien      case ExpandFloat:
237186690Sobrien        ExpandFloatResult(N, i);
238186690Sobrien        Changed = true;
239186690Sobrien        goto NodeDone;
24068349Sobrien      case ScalarizeVector:
24168349Sobrien        ScalarizeVectorResult(N, i);
24268349Sobrien        Changed = true;
24368349Sobrien        goto NodeDone;
24468349Sobrien      case SplitVector:
24568349Sobrien        SplitVectorResult(N, i);
24668349Sobrien        Changed = true;
24768349Sobrien        goto NodeDone;
24868349Sobrien      case WidenVector:
24968349Sobrien        WidenVectorResult(N, i);
250186690Sobrien        Changed = true;
251186690Sobrien        goto NodeDone;
252186690Sobrien      }
253186690Sobrien    }
254186690Sobrien
255186690SobrienScanOperands:
256186690Sobrien    // Scan the operand list for the node, handling any nodes with operands that
257186690Sobrien    // are illegal.
258186690Sobrien    {
259186690Sobrien    unsigned NumOperands = N->getNumOperands();
260186690Sobrien    bool NeedsReanalyzing = false;
261186690Sobrien    unsigned i;
262186690Sobrien    for (i = 0; i != NumOperands; ++i) {
263186690Sobrien      if (IgnoreNodeResults(N->getOperand(i).getNode()))
264186690Sobrien        continue;
265186690Sobrien
266186690Sobrien      MVT OpVT = N->getOperand(i).getValueType();
267186690Sobrien      switch (getTypeAction(OpVT)) {
268186690Sobrien      default:
269186690Sobrien        assert(false && "Unknown action!");
270186690Sobrien      case Legal:
271186690Sobrien        continue;
272186690Sobrien      // The following calls must either replace all of the node's results
273186690Sobrien      // using ReplaceValueWith, and return "false"; or update the node's
274186690Sobrien      // operands in place, and return "true".
275186690Sobrien      case PromoteInteger:
276186690Sobrien        NeedsReanalyzing = PromoteIntegerOperand(N, i);
277186690Sobrien        Changed = true;
278186690Sobrien        break;
279186690Sobrien      case ExpandInteger:
280186690Sobrien        NeedsReanalyzing = ExpandIntegerOperand(N, i);
281186690Sobrien        Changed = true;
282186690Sobrien        break;
283186690Sobrien      case SoftenFloat:
284186690Sobrien        NeedsReanalyzing = SoftenFloatOperand(N, i);
285186690Sobrien        Changed = true;
286186690Sobrien        break;
287186690Sobrien      case ExpandFloat:
288186690Sobrien        NeedsReanalyzing = ExpandFloatOperand(N, i);
28968349Sobrien        Changed = true;
29068349Sobrien        break;
29168349Sobrien      case ScalarizeVector:
29268349Sobrien        NeedsReanalyzing = ScalarizeVectorOperand(N, i);
29368349Sobrien        Changed = true;
29468349Sobrien        break;
29568349Sobrien      case SplitVector:
29668349Sobrien        NeedsReanalyzing = SplitVectorOperand(N, i);
29768349Sobrien        Changed = true;
29874784Sobrien        break;
29974784Sobrien      case WidenVector:
30074784Sobrien        NeedsReanalyzing = WidenVectorOperand(N, i);
30174784Sobrien        Changed = true;
30274784Sobrien        break;
30374784Sobrien      }
30474784Sobrien      break;
30574784Sobrien    }
30674784Sobrien
30774784Sobrien    // The sub-method updated N in place.  Check to see if any operands are new,
30874784Sobrien    // and if so, mark them.  If the node needs revisiting, don't add all users
30974784Sobrien    // to the worklist etc.
31074784Sobrien    if (NeedsReanalyzing) {
31174784Sobrien      assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
31274784Sobrien      N->setNodeId(NewNode);
31374784Sobrien      // Recompute the NodeId and correct processed operands, adding the node to
31474784Sobrien      // the worklist if ready.
31574784Sobrien      SDNode *M = AnalyzeNewNode(N);
31674784Sobrien      if (M == N)
31774784Sobrien        // The node didn't morph - nothing special to do, it will be revisited.
31874784Sobrien        continue;
31974784Sobrien
32074784Sobrien      // The node morphed - this is equivalent to legalizing by replacing every
32174784Sobrien      // value of N with the corresponding value of M.  So do that now.  However
32274784Sobrien      // there is no need to remember the replacement - morphing will make sure
32374784Sobrien      // it is never used non-trivially.
32474784Sobrien      assert(N->getNumValues() == M->getNumValues() &&
32574784Sobrien             "Node morphing changed the number of results!");
32674784Sobrien      for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
32774784Sobrien        // Replacing the value takes care of remapping the new value.  Do the
32874784Sobrien        // replacement without recording it in ReplacedValues.  This does not
32974784Sobrien        // expunge From but that is fine - it is not really a new node.
33074784Sobrien        ReplaceValueWithHelper(SDValue(N, i), SDValue(M, i));
33174784Sobrien      assert(N->getNodeId() == NewNode && "Unexpected node state!");
33274784Sobrien      // The node continues to live on as part of the NewNode fungus that
33374784Sobrien      // grows on top of the useful nodes.  Nothing more needs to be done
33474784Sobrien      // with it - move on to the next node.
33574784Sobrien      continue;
33674784Sobrien    }
33774784Sobrien
33874784Sobrien    if (i == NumOperands) {
33974784Sobrien      DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
34074784Sobrien    }
34174784Sobrien    }
34274784SobrienNodeDone:
34374784Sobrien
34474784Sobrien    // If we reach here, the node was processed, potentially creating new nodes.
34574784Sobrien    // Mark it as processed and add its users to the worklist as appropriate.
34674784Sobrien    assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
34774784Sobrien    N->setNodeId(Processed);
34874784Sobrien
34974784Sobrien    for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
35074784Sobrien         UI != E; ++UI) {
35174784Sobrien      SDNode *User = *UI;
35274784Sobrien      int NodeId = User->getNodeId();
35374784Sobrien
35474784Sobrien      // This node has two options: it can either be a new node or its Node ID
35574784Sobrien      // may be a count of the number of operands it has that are not ready.
35674784Sobrien      if (NodeId > 0) {
35774784Sobrien        User->setNodeId(NodeId-1);
35874784Sobrien
35974784Sobrien        // If this was the last use it was waiting on, add it to the ready list.
36074784Sobrien        if (NodeId-1 == ReadyToProcess)
36174784Sobrien          Worklist.push_back(User);
36274784Sobrien        continue;
36374784Sobrien      }
36474784Sobrien
36574784Sobrien      // If this is an unreachable new node, then ignore it.  If it ever becomes
36674784Sobrien      // reachable by being used by a newly created node then it will be handled
36774784Sobrien      // by AnalyzeNewNode.
36874784Sobrien      if (NodeId == NewNode)
36974784Sobrien        continue;
37074784Sobrien
37174784Sobrien      // Otherwise, this node is new: this is the first operand of it that
37274784Sobrien      // became ready.  Its new NodeId is the number of operands it has minus 1
37374784Sobrien      // (as this node is now processed).
37474784Sobrien      assert(NodeId == Unanalyzed && "Unknown node ID!");
37574784Sobrien      User->setNodeId(User->getNumOperands() - 1);
37674784Sobrien
37774784Sobrien      // If the node only has a single operand, it is now ready.
37874784Sobrien      if (User->getNumOperands() == 1)
37974784Sobrien        Worklist.push_back(User);
38074784Sobrien    }
38174784Sobrien  }
38274784Sobrien
38374784Sobrien#ifndef XDEBUG
38474784Sobrien  if (EnableExpensiveChecks)
38574784Sobrien#endif
38674784Sobrien    PerformExpensiveChecks();
38774784Sobrien
38874784Sobrien  // If the root changed (e.g. it was a dead load) update the root.
38974784Sobrien  DAG.setRoot(Dummy.getValue());
39074784Sobrien
39174784Sobrien  // Remove dead nodes.  This is important to do for cleanliness but also before
39274784Sobrien  // the checking loop below.  Implicit folding by the DAG.getNode operators and
39374784Sobrien  // node morphing can cause unreachable nodes to be around with their flags set
39474784Sobrien  // to new.
39574784Sobrien  DAG.RemoveDeadNodes();
39674784Sobrien
39774784Sobrien  // In a debug build, scan all the nodes to make sure we found them all.  This
39874784Sobrien  // ensures that there are no cycles and that everything got processed.
39974784Sobrien#ifndef NDEBUG
40074784Sobrien  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
40174784Sobrien       E = DAG.allnodes_end(); I != E; ++I) {
40274784Sobrien    bool Failed = false;
40374784Sobrien
40474784Sobrien    // Check that all result types are legal.
40574784Sobrien    if (!IgnoreNodeResults(I))
40674784Sobrien      for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
40774784Sobrien        if (!isTypeLegal(I->getValueType(i))) {
40874784Sobrien          cerr << "Result type " << i << " illegal!\n";
40974784Sobrien          Failed = true;
41074784Sobrien        }
41174784Sobrien
41274784Sobrien    // Check that all operand types are legal.
41374784Sobrien    for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
41474784Sobrien      if (!IgnoreNodeResults(I->getOperand(i).getNode()) &&
41574784Sobrien          !isTypeLegal(I->getOperand(i).getValueType())) {
41674784Sobrien        cerr << "Operand type " << i << " illegal!\n";
41774784Sobrien        Failed = true;
41874784Sobrien      }
41974784Sobrien
42074784Sobrien    if (I->getNodeId() != Processed) {
42174784Sobrien       if (I->getNodeId() == NewNode)
42274784Sobrien         cerr << "New node not analyzed?\n";
42374784Sobrien       else if (I->getNodeId() == Unanalyzed)
42474784Sobrien         cerr << "Unanalyzed node not noticed?\n";
42574784Sobrien       else if (I->getNodeId() > 0)
42674784Sobrien         cerr << "Operand not processed?\n";
42774784Sobrien       else if (I->getNodeId() == ReadyToProcess)
42874784Sobrien         cerr << "Not added to worklist?\n";
42974784Sobrien       Failed = true;
43074784Sobrien    }
43174784Sobrien
43274784Sobrien    if (Failed) {
43374784Sobrien      I->dump(&DAG); cerr << "\n";
43474784Sobrien      abort();
43574784Sobrien    }
43674784Sobrien  }
43774784Sobrien#endif
438110949Sobrien
439110949Sobrien  return Changed;
440}
441
442/// AnalyzeNewNode - The specified node is the root of a subtree of potentially
443/// new nodes.  Correct any processed operands (this may change the node) and
444/// calculate the NodeId.  If the node itself changes to a processed node, it
445/// is not remapped - the caller needs to take care of this.
446/// Returns the potentially changed node.
447SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
448  // If this was an existing node that is already done, we're done.
449  if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
450    return N;
451
452  // Remove any stale map entries.
453  ExpungeNode(N);
454
455  // Okay, we know that this node is new.  Recursively walk all of its operands
456  // to see if they are new also.  The depth of this walk is bounded by the size
457  // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
458  // about revisiting of nodes.
459  //
460  // As we walk the operands, keep track of the number of nodes that are
461  // processed.  If non-zero, this will become the new nodeid of this node.
462  // Operands may morph when they are analyzed.  If so, the node will be
463  // updated after all operands have been analyzed.  Since this is rare,
464  // the code tries to minimize overhead in the non-morphing case.
465
466  SmallVector<SDValue, 8> NewOps;
467  unsigned NumProcessed = 0;
468  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
469    SDValue OrigOp = N->getOperand(i);
470    SDValue Op = OrigOp;
471
472    AnalyzeNewValue(Op); // Op may morph.
473
474    if (Op.getNode()->getNodeId() == Processed)
475      ++NumProcessed;
476
477    if (!NewOps.empty()) {
478      // Some previous operand changed.  Add this one to the list.
479      NewOps.push_back(Op);
480    } else if (Op != OrigOp) {
481      // This is the first operand to change - add all operands so far.
482      for (unsigned j = 0; j < i; ++j)
483        NewOps.push_back(N->getOperand(j));
484      NewOps.push_back(Op);
485    }
486  }
487
488  // Some operands changed - update the node.
489  if (!NewOps.empty()) {
490    SDNode *M = DAG.UpdateNodeOperands(SDValue(N, 0), &NewOps[0],
491                                       NewOps.size()).getNode();
492    if (M != N) {
493      // The node morphed into a different node.  Normally for this to happen
494      // the original node would have to be marked NewNode.  However this can
495      // in theory momentarily not be the case while ReplaceValueWith is doing
496      // its stuff.  Mark the original node NewNode to help sanity checking.
497      N->setNodeId(NewNode);
498      if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
499        // It morphed into a previously analyzed node - nothing more to do.
500        return M;
501
502      // It morphed into a different new node.  Do the equivalent of passing
503      // it to AnalyzeNewNode: expunge it and calculate the NodeId.  No need
504      // to remap the operands, since they are the same as the operands we
505      // remapped above.
506      N = M;
507      ExpungeNode(N);
508    }
509  }
510
511  // Calculate the NodeId.
512  N->setNodeId(N->getNumOperands() - NumProcessed);
513  if (N->getNodeId() == ReadyToProcess)
514    Worklist.push_back(N);
515
516  return N;
517}
518
519/// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed.
520/// If the node changes to a processed node, then remap it.
521void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
522  Val.setNode(AnalyzeNewNode(Val.getNode()));
523  if (Val.getNode()->getNodeId() == Processed)
524    // We were passed a processed node, or it morphed into one - remap it.
525    RemapValue(Val);
526}
527
528/// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it.
529/// This can occur when a node is deleted then reallocated as a new node -
530/// the mapping in ReplacedValues applies to the deleted node, not the new
531/// one.
532/// The only map that can have a deleted node as a source is ReplacedValues.
533/// Other maps can have deleted nodes as targets, but since their looked-up
534/// values are always immediately remapped using RemapValue, resulting in a
535/// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
536/// always performs correct mappings.  In order to keep the mapping correct,
537/// ExpungeNode should be called on any new nodes *before* adding them as
538/// either source or target to ReplacedValues (which typically means calling
539/// Expunge when a new node is first seen, since it may no longer be marked
540/// NewNode by the time it is added to ReplacedValues).
541void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
542  if (N->getNodeId() != NewNode)
543    return;
544
545  // If N is not remapped by ReplacedValues then there is nothing to do.
546  unsigned i, e;
547  for (i = 0, e = N->getNumValues(); i != e; ++i)
548    if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
549      break;
550
551  if (i == e)
552    return;
553
554  // Remove N from all maps - this is expensive but rare.
555
556  for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
557       E = PromotedIntegers.end(); I != E; ++I) {
558    assert(I->first.getNode() != N);
559    RemapValue(I->second);
560  }
561
562  for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
563       E = SoftenedFloats.end(); I != E; ++I) {
564    assert(I->first.getNode() != N);
565    RemapValue(I->second);
566  }
567
568  for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
569       E = ScalarizedVectors.end(); I != E; ++I) {
570    assert(I->first.getNode() != N);
571    RemapValue(I->second);
572  }
573
574  for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(),
575       E = WidenedVectors.end(); I != E; ++I) {
576    assert(I->first.getNode() != N);
577    RemapValue(I->second);
578  }
579
580  for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
581       I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
582    assert(I->first.getNode() != N);
583    RemapValue(I->second.first);
584    RemapValue(I->second.second);
585  }
586
587  for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
588       I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
589    assert(I->first.getNode() != N);
590    RemapValue(I->second.first);
591    RemapValue(I->second.second);
592  }
593
594  for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
595       I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
596    assert(I->first.getNode() != N);
597    RemapValue(I->second.first);
598    RemapValue(I->second.second);
599  }
600
601  for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
602       E = ReplacedValues.end(); I != E; ++I)
603    RemapValue(I->second);
604
605  for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
606    ReplacedValues.erase(SDValue(N, i));
607}
608
609/// RemapValue - If the specified value was already legalized to another value,
610/// replace it by that value.
611void DAGTypeLegalizer::RemapValue(SDValue &N) {
612  DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
613  if (I != ReplacedValues.end()) {
614    // Use path compression to speed up future lookups if values get multiply
615    // replaced with other values.
616    RemapValue(I->second);
617    N = I->second;
618    assert(N.getNode()->getNodeId() != NewNode && "Mapped to new node!");
619  }
620}
621
622namespace {
623  /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
624  /// updates to nodes and recomputes their ready state.
625  class VISIBILITY_HIDDEN NodeUpdateListener :
626    public SelectionDAG::DAGUpdateListener {
627    DAGTypeLegalizer &DTL;
628    SmallSetVector<SDNode*, 16> &NodesToAnalyze;
629  public:
630    explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
631                                SmallSetVector<SDNode*, 16> &nta)
632      : DTL(dtl), NodesToAnalyze(nta) {}
633
634    virtual void NodeDeleted(SDNode *N, SDNode *E) {
635      assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
636             N->getNodeId() != DAGTypeLegalizer::Processed &&
637             "Invalid node ID for RAUW deletion!");
638      // It is possible, though rare, for the deleted node N to occur as a
639      // target in a map, so note the replacement N -> E in ReplacedValues.
640      assert(E && "Node not replaced?");
641      DTL.NoteDeletion(N, E);
642
643      // In theory the deleted node could also have been scheduled for analysis.
644      // So remove it from the set of nodes which will be analyzed.
645      NodesToAnalyze.remove(N);
646
647      // In general nothing needs to be done for E, since it didn't change but
648      // only gained new uses.  However N -> E was just added to ReplacedValues,
649      // and the result of a ReplacedValues mapping is not allowed to be marked
650      // NewNode.  So if E is marked NewNode, then it needs to be analyzed.
651      if (E->getNodeId() == DAGTypeLegalizer::NewNode)
652        NodesToAnalyze.insert(E);
653    }
654
655    virtual void NodeUpdated(SDNode *N) {
656      // Node updates can mean pretty much anything.  It is possible that an
657      // operand was set to something already processed (f.e.) in which case
658      // this node could become ready.  Recompute its flags.
659      assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
660             N->getNodeId() != DAGTypeLegalizer::Processed &&
661             "Invalid node ID for RAUW deletion!");
662      N->setNodeId(DAGTypeLegalizer::NewNode);
663      NodesToAnalyze.insert(N);
664    }
665  };
666}
667
668
669/// ReplaceValueWithHelper - Internal helper for ReplaceValueWith.  Updates the
670/// DAG causing any uses of From to use To instead, but without expunging From
671/// or recording the replacement in ReplacedValues.  Do not call directly unless
672/// you really know what you are doing!
673void DAGTypeLegalizer::ReplaceValueWithHelper(SDValue From, SDValue To) {
674  assert(From.getNode() != To.getNode() && "Potential legalization loop!");
675
676  // If expansion produced new nodes, make sure they are properly marked.
677  AnalyzeNewValue(To); // Expunges To.
678
679  // Anything that used the old node should now use the new one.  Note that this
680  // can potentially cause recursive merging.
681  SmallSetVector<SDNode*, 16> NodesToAnalyze;
682  NodeUpdateListener NUL(*this, NodesToAnalyze);
683  DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
684
685  // Process the list of nodes that need to be reanalyzed.
686  while (!NodesToAnalyze.empty()) {
687    SDNode *N = NodesToAnalyze.back();
688    NodesToAnalyze.pop_back();
689    if (N->getNodeId() != DAGTypeLegalizer::NewNode)
690      // The node was analyzed while reanalyzing an earlier node - it is safe to
691      // skip.  Note that this is not a morphing node - otherwise it would still
692      // be marked NewNode.
693      continue;
694
695    // Analyze the node's operands and recalculate the node ID.
696    SDNode *M = AnalyzeNewNode(N);
697    if (M != N) {
698      // The node morphed into a different node.  Make everyone use the new node
699      // instead.
700      assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
701      assert(N->getNumValues() == M->getNumValues() &&
702             "Node morphing changed the number of results!");
703      for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
704        SDValue OldVal(N, i);
705        SDValue NewVal(M, i);
706        if (M->getNodeId() == Processed)
707          RemapValue(NewVal);
708        DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal, &NUL);
709      }
710      // The original node continues to exist in the DAG, marked NewNode.
711    }
712  }
713}
714
715/// ReplaceValueWith - The specified value was legalized to the specified other
716/// value.  Update the DAG and NodeIds replacing any uses of From to use To
717/// instead.
718void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
719  assert(From.getNode()->getNodeId() == ReadyToProcess &&
720         "Only the node being processed may be remapped!");
721
722  // If expansion produced new nodes, make sure they are properly marked.
723  ExpungeNode(From.getNode());
724  AnalyzeNewValue(To); // Expunges To.
725
726  // The old node may still be present in a map like ExpandedIntegers or
727  // PromotedIntegers.  Inform maps about the replacement.
728  ReplacedValues[From] = To;
729
730  // Do the replacement.
731  ReplaceValueWithHelper(From, To);
732}
733
734void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
735  AnalyzeNewValue(Result);
736
737  SDValue &OpEntry = PromotedIntegers[Op];
738  assert(OpEntry.getNode() == 0 && "Node is already promoted!");
739  OpEntry = Result;
740}
741
742void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
743  AnalyzeNewValue(Result);
744
745  SDValue &OpEntry = SoftenedFloats[Op];
746  assert(OpEntry.getNode() == 0 && "Node is already converted to integer!");
747  OpEntry = Result;
748}
749
750void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
751  AnalyzeNewValue(Result);
752
753  SDValue &OpEntry = ScalarizedVectors[Op];
754  assert(OpEntry.getNode() == 0 && "Node is already scalarized!");
755  OpEntry = Result;
756}
757
758void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
759                                          SDValue &Hi) {
760  std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
761  RemapValue(Entry.first);
762  RemapValue(Entry.second);
763  assert(Entry.first.getNode() && "Operand isn't expanded");
764  Lo = Entry.first;
765  Hi = Entry.second;
766}
767
768void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
769                                          SDValue Hi) {
770  // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
771  AnalyzeNewValue(Lo);
772  AnalyzeNewValue(Hi);
773
774  // Remember that this is the result of the node.
775  std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
776  assert(Entry.first.getNode() == 0 && "Node already expanded");
777  Entry.first = Lo;
778  Entry.second = Hi;
779}
780
781void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
782                                        SDValue &Hi) {
783  std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
784  RemapValue(Entry.first);
785  RemapValue(Entry.second);
786  assert(Entry.first.getNode() && "Operand isn't expanded");
787  Lo = Entry.first;
788  Hi = Entry.second;
789}
790
791void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
792                                        SDValue Hi) {
793  // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
794  AnalyzeNewValue(Lo);
795  AnalyzeNewValue(Hi);
796
797  // Remember that this is the result of the node.
798  std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
799  assert(Entry.first.getNode() == 0 && "Node already expanded");
800  Entry.first = Lo;
801  Entry.second = Hi;
802}
803
804void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
805                                      SDValue &Hi) {
806  std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
807  RemapValue(Entry.first);
808  RemapValue(Entry.second);
809  assert(Entry.first.getNode() && "Operand isn't split");
810  Lo = Entry.first;
811  Hi = Entry.second;
812}
813
814void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
815                                      SDValue Hi) {
816  // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
817  AnalyzeNewValue(Lo);
818  AnalyzeNewValue(Hi);
819
820  // Remember that this is the result of the node.
821  std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
822  assert(Entry.first.getNode() == 0 && "Node already split");
823  Entry.first = Lo;
824  Entry.second = Hi;
825}
826
827void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
828  AnalyzeNewValue(Result);
829
830  SDValue &OpEntry = WidenedVectors[Op];
831  assert(OpEntry.getNode() == 0 && "Node already widened!");
832  OpEntry = Result;
833}
834
835
836//===----------------------------------------------------------------------===//
837// Utilities.
838//===----------------------------------------------------------------------===//
839
840/// BitConvertToInteger - Convert to an integer of the same size.
841SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
842  unsigned BitWidth = Op.getValueType().getSizeInBits();
843  return DAG.getNode(ISD::BIT_CONVERT, Op.getDebugLoc(),
844                     MVT::getIntegerVT(BitWidth), Op);
845}
846
847/// BitConvertVectorToIntegerVector - Convert to a vector of integers of the
848/// same size.
849SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
850  assert(Op.getValueType().isVector() && "Only applies to vectors!");
851  unsigned EltWidth = Op.getValueType().getVectorElementType().getSizeInBits();
852  MVT EltNVT = MVT::getIntegerVT(EltWidth);
853  unsigned NumElts = Op.getValueType().getVectorNumElements();
854  return DAG.getNode(ISD::BIT_CONVERT, Op.getDebugLoc(),
855                     MVT::getVectorVT(EltNVT, NumElts), Op);
856}
857
858SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
859                                               MVT DestVT) {
860  DebugLoc dl = Op.getDebugLoc();
861  // Create the stack frame object.  Make sure it is aligned for both
862  // the source and destination types.
863  SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
864  // Emit a store to the stack slot.
865  SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr, NULL, 0);
866  // Result is a load from the stack slot.
867  return DAG.getLoad(DestVT, dl, Store, StackPtr, NULL, 0);
868}
869
870/// CustomLowerNode - Replace the node's results with custom code provided
871/// by the target and return "true", or do nothing and return "false".
872/// The last parameter is FALSE if we are dealing with a node with legal
873/// result types and illegal operand. The second parameter denotes the type of
874/// illegal OperandNo in that case.
875/// The last parameter being TRUE means we are dealing with a
876/// node with illegal result types. The second parameter denotes the type of
877/// illegal ResNo in that case.
878bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, MVT VT, bool LegalizeResult) {
879  // See if the target wants to custom lower this node.
880  if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
881    return false;
882
883  SmallVector<SDValue, 8> Results;
884  if (LegalizeResult)
885    TLI.ReplaceNodeResults(N, Results, DAG);
886  else
887    TLI.LowerOperationWrapper(N, Results, DAG);
888
889  if (Results.empty())
890    // The target didn't want to custom lower it after all.
891    return false;
892
893  // Make everything that once used N's values now use those in Results instead.
894  assert(Results.size() == N->getNumValues() &&
895         "Custom lowering returned the wrong number of results!");
896  for (unsigned i = 0, e = Results.size(); i != e; ++i)
897    ReplaceValueWith(SDValue(N, i), Results[i]);
898  return true;
899}
900
901/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
902/// which is split into two not necessarily identical pieces.
903void DAGTypeLegalizer::GetSplitDestVTs(MVT InVT, MVT &LoVT, MVT &HiVT) {
904  if (!InVT.isVector()) {
905    LoVT = HiVT = TLI.getTypeToTransformTo(InVT);
906  } else {
907    MVT NewEltVT = InVT.getVectorElementType();
908    unsigned NumElements = InVT.getVectorNumElements();
909    if ((NumElements & (NumElements-1)) == 0) {  // Simple power of two vector.
910      NumElements >>= 1;
911      LoVT = HiVT =  MVT::getVectorVT(NewEltVT, NumElements);
912    } else {                                     // Non-power-of-two vectors.
913      unsigned NewNumElts_Lo = 1 << Log2_32(NumElements);
914      unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
915      LoVT = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
916      HiVT = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
917    }
918  }
919}
920
921/// GetPairElements - Use ISD::EXTRACT_ELEMENT nodes to extract the low and
922/// high parts of the given value.
923void DAGTypeLegalizer::GetPairElements(SDValue Pair,
924                                       SDValue &Lo, SDValue &Hi) {
925  DebugLoc dl = Pair.getDebugLoc();
926  MVT NVT = TLI.getTypeToTransformTo(Pair.getValueType());
927  Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
928                   DAG.getIntPtrConstant(0));
929  Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
930                   DAG.getIntPtrConstant(1));
931}
932
933SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, MVT EltVT,
934                                                  SDValue Index) {
935  DebugLoc dl = Index.getDebugLoc();
936  // Make sure the index type is big enough to compute in.
937  if (Index.getValueType().bitsGT(TLI.getPointerTy()))
938    Index = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Index);
939  else
940    Index = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Index);
941
942  // Calculate the element offset and add it to the pointer.
943  unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
944
945  Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
946                      DAG.getConstant(EltSize, Index.getValueType()));
947  return DAG.getNode(ISD::ADD, dl, Index.getValueType(), Index, VecPtr);
948}
949
950/// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
951SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
952  // Arbitrarily use dlHi for result DebugLoc
953  DebugLoc dlHi = Hi.getDebugLoc();
954  DebugLoc dlLo = Lo.getDebugLoc();
955  MVT LVT = Lo.getValueType();
956  MVT HVT = Hi.getValueType();
957  MVT NVT = MVT::getIntegerVT(LVT.getSizeInBits() + HVT.getSizeInBits());
958
959  Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
960  Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
961  Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
962                   DAG.getConstant(LVT.getSizeInBits(), TLI.getPointerTy()));
963  return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
964}
965
966/// LibCallify - Convert the node into a libcall with the same prototype.
967SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
968                                     bool isSigned) {
969  unsigned NumOps = N->getNumOperands();
970  DebugLoc dl = N->getDebugLoc();
971  if (NumOps == 0) {
972    return MakeLibCall(LC, N->getValueType(0), 0, 0, isSigned, dl);
973  } else if (NumOps == 1) {
974    SDValue Op = N->getOperand(0);
975    return MakeLibCall(LC, N->getValueType(0), &Op, 1, isSigned, dl);
976  } else if (NumOps == 2) {
977    SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
978    return MakeLibCall(LC, N->getValueType(0), Ops, 2, isSigned, dl);
979  }
980  SmallVector<SDValue, 8> Ops(NumOps);
981  for (unsigned i = 0; i < NumOps; ++i)
982    Ops[i] = N->getOperand(i);
983
984  return MakeLibCall(LC, N->getValueType(0), &Ops[0], NumOps, isSigned, dl);
985}
986
987/// MakeLibCall - Generate a libcall taking the given operands as arguments and
988/// returning a result of type RetVT.
989SDValue DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, MVT RetVT,
990                                      const SDValue *Ops, unsigned NumOps,
991                                      bool isSigned, DebugLoc dl) {
992  TargetLowering::ArgListTy Args;
993  Args.reserve(NumOps);
994
995  TargetLowering::ArgListEntry Entry;
996  for (unsigned i = 0; i != NumOps; ++i) {
997    Entry.Node = Ops[i];
998    Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
999    Entry.isSExt = isSigned;
1000    Entry.isZExt = !isSigned;
1001    Args.push_back(Entry);
1002  }
1003  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1004                                         TLI.getPointerTy());
1005
1006  const Type *RetTy = RetVT.getTypeForMVT();
1007  std::pair<SDValue,SDValue> CallInfo =
1008    TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
1009                    false, CallingConv::C, false, Callee, Args, DAG, dl);
1010  return CallInfo.first;
1011}
1012
1013/// PromoteTargetBoolean - Promote the given target boolean to a target boolean
1014/// of the given type.  A target boolean is an integer value, not necessarily of
1015/// type i1, the bits of which conform to getBooleanContents.
1016SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, MVT VT) {
1017  DebugLoc dl = Bool.getDebugLoc();
1018  ISD::NodeType ExtendCode;
1019  switch (TLI.getBooleanContents()) {
1020  default:
1021    assert(false && "Unknown BooleanContent!");
1022  case TargetLowering::UndefinedBooleanContent:
1023    // Extend to VT by adding rubbish bits.
1024    ExtendCode = ISD::ANY_EXTEND;
1025    break;
1026  case TargetLowering::ZeroOrOneBooleanContent:
1027    // Extend to VT by adding zero bits.
1028    ExtendCode = ISD::ZERO_EXTEND;
1029    break;
1030  case TargetLowering::ZeroOrNegativeOneBooleanContent: {
1031    // Extend to VT by copying the sign bit.
1032    ExtendCode = ISD::SIGN_EXTEND;
1033    break;
1034  }
1035  }
1036  return DAG.getNode(ExtendCode, dl, VT, Bool);
1037}
1038
1039/// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
1040/// bits in Hi.
1041void DAGTypeLegalizer::SplitInteger(SDValue Op,
1042                                    MVT LoVT, MVT HiVT,
1043                                    SDValue &Lo, SDValue &Hi) {
1044  DebugLoc dl = Op.getDebugLoc();
1045  assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
1046         Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
1047  Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
1048  Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
1049                   DAG.getConstant(LoVT.getSizeInBits(), TLI.getPointerTy()));
1050  Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
1051}
1052
1053/// SplitInteger - Return the lower and upper halves of Op's bits in a value
1054/// type half the size of Op's.
1055void DAGTypeLegalizer::SplitInteger(SDValue Op,
1056                                    SDValue &Lo, SDValue &Hi) {
1057  MVT HalfVT = MVT::getIntegerVT(Op.getValueType().getSizeInBits()/2);
1058  SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
1059}
1060
1061
1062//===----------------------------------------------------------------------===//
1063//  Entry Point
1064//===----------------------------------------------------------------------===//
1065
1066/// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
1067/// only uses types natively supported by the target.  Returns "true" if it made
1068/// any changes.
1069///
1070/// Note that this is an involved process that may invalidate pointers into
1071/// the graph.
1072bool SelectionDAG::LegalizeTypes() {
1073  return DAGTypeLegalizer(*this).run();
1074}
1075