LLVM API Documentation

LegalizeTypes.cpp
Go to the documentation of this file.
00001 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the SelectionDAG::LegalizeTypes method.  It transforms
00011 // an arbitrary well-formed SelectionDAG to only consist of legal types.  This
00012 // is common code shared among the LegalizeTypes*.cpp files.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "LegalizeTypes.h"
00017 #include "llvm/ADT/SetVector.h"
00018 #include "llvm/IR/CallingConv.h"
00019 #include "llvm/IR/DataLayout.h"
00020 #include "llvm/Support/CommandLine.h"
00021 #include "llvm/Support/ErrorHandling.h"
00022 #include "llvm/Support/raw_ostream.h"
00023 using namespace llvm;
00024 
00025 static cl::opt<bool>
00026 EnableExpensiveChecks("enable-legalize-types-checking", cl::Hidden);
00027 
00028 /// PerformExpensiveChecks - Do extensive, expensive, sanity checking.
00029 void DAGTypeLegalizer::PerformExpensiveChecks() {
00030   // If a node is not processed, then none of its values should be mapped by any
00031   // of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
00032 
00033   // If a node is processed, then each value with an illegal type must be mapped
00034   // by exactly one of PromotedIntegers, ExpandedIntegers, ..., ReplacedValues.
00035   // Values with a legal type may be mapped by ReplacedValues, but not by any of
00036   // the other maps.
00037 
00038   // Note that these invariants may not hold momentarily when processing a node:
00039   // the node being processed may be put in a map before being marked Processed.
00040 
00041   // Note that it is possible to have nodes marked NewNode in the DAG.  This can
00042   // occur in two ways.  Firstly, a node may be created during legalization but
00043   // never passed to the legalization core.  This is usually due to the implicit
00044   // folding that occurs when using the DAG.getNode operators.  Secondly, a new
00045   // node may be passed to the legalization core, but when analyzed may morph
00046   // into a different node, leaving the original node as a NewNode in the DAG.
00047   // A node may morph if one of its operands changes during analysis.  Whether
00048   // it actually morphs or not depends on whether, after updating its operands,
00049   // it is equivalent to an existing node: if so, it morphs into that existing
00050   // node (CSE).  An operand can change during analysis if the operand is a new
00051   // node that morphs, or it is a processed value that was mapped to some other
00052   // value (as recorded in ReplacedValues) in which case the operand is turned
00053   // into that other value.  If a node morphs then the node it morphed into will
00054   // be used instead of it for legalization, however the original node continues
00055   // to live on in the DAG.
00056   // The conclusion is that though there may be nodes marked NewNode in the DAG,
00057   // all uses of such nodes are also marked NewNode: the result is a fungus of
00058   // NewNodes growing on top of the useful nodes, and perhaps using them, but
00059   // not used by them.
00060 
00061   // If a value is mapped by ReplacedValues, then it must have no uses, except
00062   // by nodes marked NewNode (see above).
00063 
00064   // The final node obtained by mapping by ReplacedValues is not marked NewNode.
00065   // Note that ReplacedValues should be applied iteratively.
00066 
00067   // Note that the ReplacedValues map may also map deleted nodes (by iterating
00068   // over the DAG we never dereference deleted nodes).  This means that it may
00069   // also map nodes marked NewNode if the deallocated memory was reallocated as
00070   // another node, and that new node was not seen by the LegalizeTypes machinery
00071   // (for example because it was created but not used).  In general, we cannot
00072   // distinguish between new nodes and deleted nodes.
00073   SmallVector<SDNode*, 16> NewNodes;
00074   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
00075        E = DAG.allnodes_end(); I != E; ++I) {
00076     // Remember nodes marked NewNode - they are subject to extra checking below.
00077     if (I->getNodeId() == NewNode)
00078       NewNodes.push_back(I);
00079 
00080     for (unsigned i = 0, e = I->getNumValues(); i != e; ++i) {
00081       SDValue Res(I, i);
00082       bool Failed = false;
00083 
00084       unsigned Mapped = 0;
00085       if (ReplacedValues.find(Res) != ReplacedValues.end()) {
00086         Mapped |= 1;
00087         // Check that remapped values are only used by nodes marked NewNode.
00088         for (SDNode::use_iterator UI = I->use_begin(), UE = I->use_end();
00089              UI != UE; ++UI)
00090           if (UI.getUse().getResNo() == i)
00091             assert(UI->getNodeId() == NewNode &&
00092                    "Remapped value has non-trivial use!");
00093 
00094         // Check that the final result of applying ReplacedValues is not
00095         // marked NewNode.
00096         SDValue NewVal = ReplacedValues[Res];
00097         DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(NewVal);
00098         while (I != ReplacedValues.end()) {
00099           NewVal = I->second;
00100           I = ReplacedValues.find(NewVal);
00101         }
00102         assert(NewVal.getNode()->getNodeId() != NewNode &&
00103                "ReplacedValues maps to a new node!");
00104       }
00105       if (PromotedIntegers.find(Res) != PromotedIntegers.end())
00106         Mapped |= 2;
00107       if (SoftenedFloats.find(Res) != SoftenedFloats.end())
00108         Mapped |= 4;
00109       if (ScalarizedVectors.find(Res) != ScalarizedVectors.end())
00110         Mapped |= 8;
00111       if (ExpandedIntegers.find(Res) != ExpandedIntegers.end())
00112         Mapped |= 16;
00113       if (ExpandedFloats.find(Res) != ExpandedFloats.end())
00114         Mapped |= 32;
00115       if (SplitVectors.find(Res) != SplitVectors.end())
00116         Mapped |= 64;
00117       if (WidenedVectors.find(Res) != WidenedVectors.end())
00118         Mapped |= 128;
00119 
00120       if (I->getNodeId() != Processed) {
00121         // Since we allow ReplacedValues to map deleted nodes, it may map nodes
00122         // marked NewNode too, since a deleted node may have been reallocated as
00123         // another node that has not been seen by the LegalizeTypes machinery.
00124         if ((I->getNodeId() == NewNode && Mapped > 1) ||
00125             (I->getNodeId() != NewNode && Mapped != 0)) {
00126           dbgs() << "Unprocessed value in a map!";
00127           Failed = true;
00128         }
00129       } else if (isTypeLegal(Res.getValueType()) || IgnoreNodeResults(I)) {
00130         if (Mapped > 1) {
00131           dbgs() << "Value with legal type was transformed!";
00132           Failed = true;
00133         }
00134       } else {
00135         if (Mapped == 0) {
00136           dbgs() << "Processed value not in any map!";
00137           Failed = true;
00138         } else if (Mapped & (Mapped - 1)) {
00139           dbgs() << "Value in multiple maps!";
00140           Failed = true;
00141         }
00142       }
00143 
00144       if (Failed) {
00145         if (Mapped & 1)
00146           dbgs() << " ReplacedValues";
00147         if (Mapped & 2)
00148           dbgs() << " PromotedIntegers";
00149         if (Mapped & 4)
00150           dbgs() << " SoftenedFloats";
00151         if (Mapped & 8)
00152           dbgs() << " ScalarizedVectors";
00153         if (Mapped & 16)
00154           dbgs() << " ExpandedIntegers";
00155         if (Mapped & 32)
00156           dbgs() << " ExpandedFloats";
00157         if (Mapped & 64)
00158           dbgs() << " SplitVectors";
00159         if (Mapped & 128)
00160           dbgs() << " WidenedVectors";
00161         dbgs() << "\n";
00162         llvm_unreachable(0);
00163       }
00164     }
00165   }
00166 
00167   // Checked that NewNodes are only used by other NewNodes.
00168   for (unsigned i = 0, e = NewNodes.size(); i != e; ++i) {
00169     SDNode *N = NewNodes[i];
00170     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
00171          UI != UE; ++UI)
00172       assert(UI->getNodeId() == NewNode && "NewNode used by non-NewNode!");
00173   }
00174 }
00175 
00176 /// run - This is the main entry point for the type legalizer.  This does a
00177 /// top-down traversal of the dag, legalizing types as it goes.  Returns "true"
00178 /// if it made any changes.
00179 bool DAGTypeLegalizer::run() {
00180   bool Changed = false;
00181 
00182   // Create a dummy node (which is not added to allnodes), that adds a reference
00183   // to the root node, preventing it from being deleted, and tracking any
00184   // changes of the root.
00185   HandleSDNode Dummy(DAG.getRoot());
00186   Dummy.setNodeId(Unanalyzed);
00187 
00188   // The root of the dag may dangle to deleted nodes until the type legalizer is
00189   // done.  Set it to null to avoid confusion.
00190   DAG.setRoot(SDValue());
00191 
00192   // Walk all nodes in the graph, assigning them a NodeId of 'ReadyToProcess'
00193   // (and remembering them) if they are leaves and assigning 'Unanalyzed' if
00194   // non-leaves.
00195   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
00196        E = DAG.allnodes_end(); I != E; ++I) {
00197     if (I->getNumOperands() == 0) {
00198       I->setNodeId(ReadyToProcess);
00199       Worklist.push_back(I);
00200     } else {
00201       I->setNodeId(Unanalyzed);
00202     }
00203   }
00204 
00205   // Now that we have a set of nodes to process, handle them all.
00206   while (!Worklist.empty()) {
00207 #ifndef XDEBUG
00208     if (EnableExpensiveChecks)
00209 #endif
00210       PerformExpensiveChecks();
00211 
00212     SDNode *N = Worklist.back();
00213     Worklist.pop_back();
00214     assert(N->getNodeId() == ReadyToProcess &&
00215            "Node should be ready if on worklist!");
00216 
00217     if (IgnoreNodeResults(N))
00218       goto ScanOperands;
00219 
00220     // Scan the values produced by the node, checking to see if any result
00221     // types are illegal.
00222     for (unsigned i = 0, NumResults = N->getNumValues(); i < NumResults; ++i) {
00223       EVT ResultVT = N->getValueType(i);
00224       switch (getTypeAction(ResultVT)) {
00225       case TargetLowering::TypeLegal:
00226         break;
00227       // The following calls must take care of *all* of the node's results,
00228       // not just the illegal result they were passed (this includes results
00229       // with a legal type).  Results can be remapped using ReplaceValueWith,
00230       // or their promoted/expanded/etc values registered in PromotedIntegers,
00231       // ExpandedIntegers etc.
00232       case TargetLowering::TypePromoteInteger:
00233         PromoteIntegerResult(N, i);
00234         Changed = true;
00235         goto NodeDone;
00236       case TargetLowering::TypeExpandInteger:
00237         ExpandIntegerResult(N, i);
00238         Changed = true;
00239         goto NodeDone;
00240       case TargetLowering::TypeSoftenFloat:
00241         SoftenFloatResult(N, i);
00242         Changed = true;
00243         goto NodeDone;
00244       case TargetLowering::TypeExpandFloat:
00245         ExpandFloatResult(N, i);
00246         Changed = true;
00247         goto NodeDone;
00248       case TargetLowering::TypeScalarizeVector:
00249         ScalarizeVectorResult(N, i);
00250         Changed = true;
00251         goto NodeDone;
00252       case TargetLowering::TypeSplitVector:
00253         SplitVectorResult(N, i);
00254         Changed = true;
00255         goto NodeDone;
00256       case TargetLowering::TypeWidenVector:
00257         WidenVectorResult(N, i);
00258         Changed = true;
00259         goto NodeDone;
00260       }
00261     }
00262 
00263 ScanOperands:
00264     // Scan the operand list for the node, handling any nodes with operands that
00265     // are illegal.
00266     {
00267     unsigned NumOperands = N->getNumOperands();
00268     bool NeedsReanalyzing = false;
00269     unsigned i;
00270     for (i = 0; i != NumOperands; ++i) {
00271       if (IgnoreNodeResults(N->getOperand(i).getNode()))
00272         continue;
00273 
00274       EVT OpVT = N->getOperand(i).getValueType();
00275       switch (getTypeAction(OpVT)) {
00276       case TargetLowering::TypeLegal:
00277         continue;
00278       // The following calls must either replace all of the node's results
00279       // using ReplaceValueWith, and return "false"; or update the node's
00280       // operands in place, and return "true".
00281       case TargetLowering::TypePromoteInteger:
00282         NeedsReanalyzing = PromoteIntegerOperand(N, i);
00283         Changed = true;
00284         break;
00285       case TargetLowering::TypeExpandInteger:
00286         NeedsReanalyzing = ExpandIntegerOperand(N, i);
00287         Changed = true;
00288         break;
00289       case TargetLowering::TypeSoftenFloat:
00290         NeedsReanalyzing = SoftenFloatOperand(N, i);
00291         Changed = true;
00292         break;
00293       case TargetLowering::TypeExpandFloat:
00294         NeedsReanalyzing = ExpandFloatOperand(N, i);
00295         Changed = true;
00296         break;
00297       case TargetLowering::TypeScalarizeVector:
00298         NeedsReanalyzing = ScalarizeVectorOperand(N, i);
00299         Changed = true;
00300         break;
00301       case TargetLowering::TypeSplitVector:
00302         NeedsReanalyzing = SplitVectorOperand(N, i);
00303         Changed = true;
00304         break;
00305       case TargetLowering::TypeWidenVector:
00306         NeedsReanalyzing = WidenVectorOperand(N, i);
00307         Changed = true;
00308         break;
00309       }
00310       break;
00311     }
00312 
00313     // The sub-method updated N in place.  Check to see if any operands are new,
00314     // and if so, mark them.  If the node needs revisiting, don't add all users
00315     // to the worklist etc.
00316     if (NeedsReanalyzing) {
00317       assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
00318       N->setNodeId(NewNode);
00319       // Recompute the NodeId and correct processed operands, adding the node to
00320       // the worklist if ready.
00321       SDNode *M = AnalyzeNewNode(N);
00322       if (M == N)
00323         // The node didn't morph - nothing special to do, it will be revisited.
00324         continue;
00325 
00326       // The node morphed - this is equivalent to legalizing by replacing every
00327       // value of N with the corresponding value of M.  So do that now.
00328       assert(N->getNumValues() == M->getNumValues() &&
00329              "Node morphing changed the number of results!");
00330       for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
00331         // Replacing the value takes care of remapping the new value.
00332         ReplaceValueWith(SDValue(N, i), SDValue(M, i));
00333       assert(N->getNodeId() == NewNode && "Unexpected node state!");
00334       // The node continues to live on as part of the NewNode fungus that
00335       // grows on top of the useful nodes.  Nothing more needs to be done
00336       // with it - move on to the next node.
00337       continue;
00338     }
00339 
00340     if (i == NumOperands) {
00341       DEBUG(dbgs() << "Legally typed node: "; N->dump(&DAG); dbgs() << "\n");
00342     }
00343     }
00344 NodeDone:
00345 
00346     // If we reach here, the node was processed, potentially creating new nodes.
00347     // Mark it as processed and add its users to the worklist as appropriate.
00348     assert(N->getNodeId() == ReadyToProcess && "Node ID recalculated?");
00349     N->setNodeId(Processed);
00350 
00351     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
00352          UI != E; ++UI) {
00353       SDNode *User = *UI;
00354       int NodeId = User->getNodeId();
00355 
00356       // This node has two options: it can either be a new node or its Node ID
00357       // may be a count of the number of operands it has that are not ready.
00358       if (NodeId > 0) {
00359         User->setNodeId(NodeId-1);
00360 
00361         // If this was the last use it was waiting on, add it to the ready list.
00362         if (NodeId-1 == ReadyToProcess)
00363           Worklist.push_back(User);
00364         continue;
00365       }
00366 
00367       // If this is an unreachable new node, then ignore it.  If it ever becomes
00368       // reachable by being used by a newly created node then it will be handled
00369       // by AnalyzeNewNode.
00370       if (NodeId == NewNode)
00371         continue;
00372 
00373       // Otherwise, this node is new: this is the first operand of it that
00374       // became ready.  Its new NodeId is the number of operands it has minus 1
00375       // (as this node is now processed).
00376       assert(NodeId == Unanalyzed && "Unknown node ID!");
00377       User->setNodeId(User->getNumOperands() - 1);
00378 
00379       // If the node only has a single operand, it is now ready.
00380       if (User->getNumOperands() == 1)
00381         Worklist.push_back(User);
00382     }
00383   }
00384 
00385 #ifndef XDEBUG
00386   if (EnableExpensiveChecks)
00387 #endif
00388     PerformExpensiveChecks();
00389 
00390   // If the root changed (e.g. it was a dead load) update the root.
00391   DAG.setRoot(Dummy.getValue());
00392 
00393   // Remove dead nodes.  This is important to do for cleanliness but also before
00394   // the checking loop below.  Implicit folding by the DAG.getNode operators and
00395   // node morphing can cause unreachable nodes to be around with their flags set
00396   // to new.
00397   DAG.RemoveDeadNodes();
00398 
00399   // In a debug build, scan all the nodes to make sure we found them all.  This
00400   // ensures that there are no cycles and that everything got processed.
00401 #ifndef NDEBUG
00402   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
00403        E = DAG.allnodes_end(); I != E; ++I) {
00404     bool Failed = false;
00405 
00406     // Check that all result types are legal.
00407     if (!IgnoreNodeResults(I))
00408       for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
00409         if (!isTypeLegal(I->getValueType(i))) {
00410           dbgs() << "Result type " << i << " illegal!\n";
00411           Failed = true;
00412         }
00413 
00414     // Check that all operand types are legal.
00415     for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
00416       if (!IgnoreNodeResults(I->getOperand(i).getNode()) &&
00417           !isTypeLegal(I->getOperand(i).getValueType())) {
00418         dbgs() << "Operand type " << i << " illegal!\n";
00419         Failed = true;
00420       }
00421 
00422     if (I->getNodeId() != Processed) {
00423        if (I->getNodeId() == NewNode)
00424          dbgs() << "New node not analyzed?\n";
00425        else if (I->getNodeId() == Unanalyzed)
00426          dbgs() << "Unanalyzed node not noticed?\n";
00427        else if (I->getNodeId() > 0)
00428          dbgs() << "Operand not processed?\n";
00429        else if (I->getNodeId() == ReadyToProcess)
00430          dbgs() << "Not added to worklist?\n";
00431        Failed = true;
00432     }
00433 
00434     if (Failed) {
00435       I->dump(&DAG); dbgs() << "\n";
00436       llvm_unreachable(0);
00437     }
00438   }
00439 #endif
00440 
00441   return Changed;
00442 }
00443 
00444 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
00445 /// new nodes.  Correct any processed operands (this may change the node) and
00446 /// calculate the NodeId.  If the node itself changes to a processed node, it
00447 /// is not remapped - the caller needs to take care of this.
00448 /// Returns the potentially changed node.
00449 SDNode *DAGTypeLegalizer::AnalyzeNewNode(SDNode *N) {
00450   // If this was an existing node that is already done, we're done.
00451   if (N->getNodeId() != NewNode && N->getNodeId() != Unanalyzed)
00452     return N;
00453 
00454   // Remove any stale map entries.
00455   ExpungeNode(N);
00456 
00457   // Okay, we know that this node is new.  Recursively walk all of its operands
00458   // to see if they are new also.  The depth of this walk is bounded by the size
00459   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
00460   // about revisiting of nodes.
00461   //
00462   // As we walk the operands, keep track of the number of nodes that are
00463   // processed.  If non-zero, this will become the new nodeid of this node.
00464   // Operands may morph when they are analyzed.  If so, the node will be
00465   // updated after all operands have been analyzed.  Since this is rare,
00466   // the code tries to minimize overhead in the non-morphing case.
00467 
00468   SmallVector<SDValue, 8> NewOps;
00469   unsigned NumProcessed = 0;
00470   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00471     SDValue OrigOp = N->getOperand(i);
00472     SDValue Op = OrigOp;
00473 
00474     AnalyzeNewValue(Op); // Op may morph.
00475 
00476     if (Op.getNode()->getNodeId() == Processed)
00477       ++NumProcessed;
00478 
00479     if (!NewOps.empty()) {
00480       // Some previous operand changed.  Add this one to the list.
00481       NewOps.push_back(Op);
00482     } else if (Op != OrigOp) {
00483       // This is the first operand to change - add all operands so far.
00484       NewOps.append(N->op_begin(), N->op_begin() + i);
00485       NewOps.push_back(Op);
00486     }
00487   }
00488 
00489   // Some operands changed - update the node.
00490   if (!NewOps.empty()) {
00491     SDNode *M = DAG.UpdateNodeOperands(N, &NewOps[0], NewOps.size());
00492     if (M != N) {
00493       // The node morphed into a different node.  Normally for this to happen
00494       // the original node would have to be marked NewNode.  However this can
00495       // in theory momentarily not be the case while ReplaceValueWith is doing
00496       // its stuff.  Mark the original node NewNode to help sanity checking.
00497       N->setNodeId(NewNode);
00498       if (M->getNodeId() != NewNode && M->getNodeId() != Unanalyzed)
00499         // It morphed into a previously analyzed node - nothing more to do.
00500         return M;
00501 
00502       // It morphed into a different new node.  Do the equivalent of passing
00503       // it to AnalyzeNewNode: expunge it and calculate the NodeId.  No need
00504       // to remap the operands, since they are the same as the operands we
00505       // remapped above.
00506       N = M;
00507       ExpungeNode(N);
00508     }
00509   }
00510 
00511   // Calculate the NodeId.
00512   N->setNodeId(N->getNumOperands() - NumProcessed);
00513   if (N->getNodeId() == ReadyToProcess)
00514     Worklist.push_back(N);
00515 
00516   return N;
00517 }
00518 
00519 /// AnalyzeNewValue - Call AnalyzeNewNode, updating the node in Val if needed.
00520 /// If the node changes to a processed node, then remap it.
00521 void DAGTypeLegalizer::AnalyzeNewValue(SDValue &Val) {
00522   Val.setNode(AnalyzeNewNode(Val.getNode()));
00523   if (Val.getNode()->getNodeId() == Processed)
00524     // We were passed a processed node, or it morphed into one - remap it.
00525     RemapValue(Val);
00526 }
00527 
00528 /// ExpungeNode - If N has a bogus mapping in ReplacedValues, eliminate it.
00529 /// This can occur when a node is deleted then reallocated as a new node -
00530 /// the mapping in ReplacedValues applies to the deleted node, not the new
00531 /// one.
00532 /// The only map that can have a deleted node as a source is ReplacedValues.
00533 /// Other maps can have deleted nodes as targets, but since their looked-up
00534 /// values are always immediately remapped using RemapValue, resulting in a
00535 /// not-deleted node, this is harmless as long as ReplacedValues/RemapValue
00536 /// always performs correct mappings.  In order to keep the mapping correct,
00537 /// ExpungeNode should be called on any new nodes *before* adding them as
00538 /// either source or target to ReplacedValues (which typically means calling
00539 /// Expunge when a new node is first seen, since it may no longer be marked
00540 /// NewNode by the time it is added to ReplacedValues).
00541 void DAGTypeLegalizer::ExpungeNode(SDNode *N) {
00542   if (N->getNodeId() != NewNode)
00543     return;
00544 
00545   // If N is not remapped by ReplacedValues then there is nothing to do.
00546   unsigned i, e;
00547   for (i = 0, e = N->getNumValues(); i != e; ++i)
00548     if (ReplacedValues.find(SDValue(N, i)) != ReplacedValues.end())
00549       break;
00550 
00551   if (i == e)
00552     return;
00553 
00554   // Remove N from all maps - this is expensive but rare.
00555 
00556   for (DenseMap<SDValue, SDValue>::iterator I = PromotedIntegers.begin(),
00557        E = PromotedIntegers.end(); I != E; ++I) {
00558     assert(I->first.getNode() != N);
00559     RemapValue(I->second);
00560   }
00561 
00562   for (DenseMap<SDValue, SDValue>::iterator I = SoftenedFloats.begin(),
00563        E = SoftenedFloats.end(); I != E; ++I) {
00564     assert(I->first.getNode() != N);
00565     RemapValue(I->second);
00566   }
00567 
00568   for (DenseMap<SDValue, SDValue>::iterator I = ScalarizedVectors.begin(),
00569        E = ScalarizedVectors.end(); I != E; ++I) {
00570     assert(I->first.getNode() != N);
00571     RemapValue(I->second);
00572   }
00573 
00574   for (DenseMap<SDValue, SDValue>::iterator I = WidenedVectors.begin(),
00575        E = WidenedVectors.end(); I != E; ++I) {
00576     assert(I->first.getNode() != N);
00577     RemapValue(I->second);
00578   }
00579 
00580   for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
00581        I = ExpandedIntegers.begin(), E = ExpandedIntegers.end(); I != E; ++I){
00582     assert(I->first.getNode() != N);
00583     RemapValue(I->second.first);
00584     RemapValue(I->second.second);
00585   }
00586 
00587   for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
00588        I = ExpandedFloats.begin(), E = ExpandedFloats.end(); I != E; ++I) {
00589     assert(I->first.getNode() != N);
00590     RemapValue(I->second.first);
00591     RemapValue(I->second.second);
00592   }
00593 
00594   for (DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator
00595        I = SplitVectors.begin(), E = SplitVectors.end(); I != E; ++I) {
00596     assert(I->first.getNode() != N);
00597     RemapValue(I->second.first);
00598     RemapValue(I->second.second);
00599   }
00600 
00601   for (DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.begin(),
00602        E = ReplacedValues.end(); I != E; ++I)
00603     RemapValue(I->second);
00604 
00605   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
00606     ReplacedValues.erase(SDValue(N, i));
00607 }
00608 
00609 /// RemapValue - If the specified value was already legalized to another value,
00610 /// replace it by that value.
00611 void DAGTypeLegalizer::RemapValue(SDValue &N) {
00612   DenseMap<SDValue, SDValue>::iterator I = ReplacedValues.find(N);
00613   if (I != ReplacedValues.end()) {
00614     // Use path compression to speed up future lookups if values get multiply
00615     // replaced with other values.
00616     RemapValue(I->second);
00617     N = I->second;
00618     assert(N.getNode()->getNodeId() != NewNode && "Mapped to new node!");
00619   }
00620 }
00621 
00622 namespace {
00623   /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
00624   /// updates to nodes and recomputes their ready state.
00625   class NodeUpdateListener : public SelectionDAG::DAGUpdateListener {
00626     DAGTypeLegalizer &DTL;
00627     SmallSetVector<SDNode*, 16> &NodesToAnalyze;
00628   public:
00629     explicit NodeUpdateListener(DAGTypeLegalizer &dtl,
00630                                 SmallSetVector<SDNode*, 16> &nta)
00631       : SelectionDAG::DAGUpdateListener(dtl.getDAG()),
00632         DTL(dtl), NodesToAnalyze(nta) {}
00633 
00634     virtual void NodeDeleted(SDNode *N, SDNode *E) {
00635       assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
00636              N->getNodeId() != DAGTypeLegalizer::Processed &&
00637              "Invalid node ID for RAUW deletion!");
00638       // It is possible, though rare, for the deleted node N to occur as a
00639       // target in a map, so note the replacement N -> E in ReplacedValues.
00640       assert(E && "Node not replaced?");
00641       DTL.NoteDeletion(N, E);
00642 
00643       // In theory the deleted node could also have been scheduled for analysis.
00644       // So remove it from the set of nodes which will be analyzed.
00645       NodesToAnalyze.remove(N);
00646 
00647       // In general nothing needs to be done for E, since it didn't change but
00648       // only gained new uses.  However N -> E was just added to ReplacedValues,
00649       // and the result of a ReplacedValues mapping is not allowed to be marked
00650       // NewNode.  So if E is marked NewNode, then it needs to be analyzed.
00651       if (E->getNodeId() == DAGTypeLegalizer::NewNode)
00652         NodesToAnalyze.insert(E);
00653     }
00654 
00655     virtual void NodeUpdated(SDNode *N) {
00656       // Node updates can mean pretty much anything.  It is possible that an
00657       // operand was set to something already processed (f.e.) in which case
00658       // this node could become ready.  Recompute its flags.
00659       assert(N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
00660              N->getNodeId() != DAGTypeLegalizer::Processed &&
00661              "Invalid node ID for RAUW deletion!");
00662       N->setNodeId(DAGTypeLegalizer::NewNode);
00663       NodesToAnalyze.insert(N);
00664     }
00665   };
00666 }
00667 
00668 
00669 /// ReplaceValueWith - The specified value was legalized to the specified other
00670 /// value.  Update the DAG and NodeIds replacing any uses of From to use To
00671 /// instead.
00672 void DAGTypeLegalizer::ReplaceValueWith(SDValue From, SDValue To) {
00673   assert(From.getNode() != To.getNode() && "Potential legalization loop!");
00674 
00675   // If expansion produced new nodes, make sure they are properly marked.
00676   ExpungeNode(From.getNode());
00677   AnalyzeNewValue(To); // Expunges To.
00678 
00679   // Anything that used the old node should now use the new one.  Note that this
00680   // can potentially cause recursive merging.
00681   SmallSetVector<SDNode*, 16> NodesToAnalyze;
00682   NodeUpdateListener NUL(*this, NodesToAnalyze);
00683   do {
00684     DAG.ReplaceAllUsesOfValueWith(From, To);
00685 
00686     // The old node may still be present in a map like ExpandedIntegers or
00687     // PromotedIntegers.  Inform maps about the replacement.
00688     ReplacedValues[From] = To;
00689 
00690     // Process the list of nodes that need to be reanalyzed.
00691     while (!NodesToAnalyze.empty()) {
00692       SDNode *N = NodesToAnalyze.back();
00693       NodesToAnalyze.pop_back();
00694       if (N->getNodeId() != DAGTypeLegalizer::NewNode)
00695         // The node was analyzed while reanalyzing an earlier node - it is safe
00696         // to skip.  Note that this is not a morphing node - otherwise it would
00697         // still be marked NewNode.
00698         continue;
00699 
00700       // Analyze the node's operands and recalculate the node ID.
00701       SDNode *M = AnalyzeNewNode(N);
00702       if (M != N) {
00703         // The node morphed into a different node.  Make everyone use the new
00704         // node instead.
00705         assert(M->getNodeId() != NewNode && "Analysis resulted in NewNode!");
00706         assert(N->getNumValues() == M->getNumValues() &&
00707                "Node morphing changed the number of results!");
00708         for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
00709           SDValue OldVal(N, i);
00710           SDValue NewVal(M, i);
00711           if (M->getNodeId() == Processed)
00712             RemapValue(NewVal);
00713           DAG.ReplaceAllUsesOfValueWith(OldVal, NewVal);
00714           // OldVal may be a target of the ReplacedValues map which was marked
00715           // NewNode to force reanalysis because it was updated.  Ensure that
00716           // anything that ReplacedValues mapped to OldVal will now be mapped
00717           // all the way to NewVal.
00718           ReplacedValues[OldVal] = NewVal;
00719         }
00720         // The original node continues to exist in the DAG, marked NewNode.
00721       }
00722     }
00723     // When recursively update nodes with new nodes, it is possible to have
00724     // new uses of From due to CSE. If this happens, replace the new uses of
00725     // From with To.
00726   } while (!From.use_empty());
00727 }
00728 
00729 void DAGTypeLegalizer::SetPromotedInteger(SDValue Op, SDValue Result) {
00730   assert(Result.getValueType() ==
00731          TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
00732          "Invalid type for promoted integer");
00733   AnalyzeNewValue(Result);
00734 
00735   SDValue &OpEntry = PromotedIntegers[Op];
00736   assert(OpEntry.getNode() == 0 && "Node is already promoted!");
00737   OpEntry = Result;
00738 }
00739 
00740 void DAGTypeLegalizer::SetSoftenedFloat(SDValue Op, SDValue Result) {
00741   assert(Result.getValueType() ==
00742          TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
00743          "Invalid type for softened float");
00744   AnalyzeNewValue(Result);
00745 
00746   SDValue &OpEntry = SoftenedFloats[Op];
00747   assert(OpEntry.getNode() == 0 && "Node is already converted to integer!");
00748   OpEntry = Result;
00749 }
00750 
00751 void DAGTypeLegalizer::SetScalarizedVector(SDValue Op, SDValue Result) {
00752   // Note that in some cases vector operation operands may be greater than
00753   // the vector element type. For example BUILD_VECTOR of type <1 x i1> with
00754   // a constant i8 operand.
00755   assert(Result.getValueType().getSizeInBits() >=
00756          Op.getValueType().getVectorElementType().getSizeInBits() &&
00757          "Invalid type for scalarized vector");
00758   AnalyzeNewValue(Result);
00759 
00760   SDValue &OpEntry = ScalarizedVectors[Op];
00761   assert(OpEntry.getNode() == 0 && "Node is already scalarized!");
00762   OpEntry = Result;
00763 }
00764 
00765 void DAGTypeLegalizer::GetExpandedInteger(SDValue Op, SDValue &Lo,
00766                                           SDValue &Hi) {
00767   std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
00768   RemapValue(Entry.first);
00769   RemapValue(Entry.second);
00770   assert(Entry.first.getNode() && "Operand isn't expanded");
00771   Lo = Entry.first;
00772   Hi = Entry.second;
00773 }
00774 
00775 void DAGTypeLegalizer::SetExpandedInteger(SDValue Op, SDValue Lo,
00776                                           SDValue Hi) {
00777   assert(Lo.getValueType() ==
00778          TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
00779          Hi.getValueType() == Lo.getValueType() &&
00780          "Invalid type for expanded integer");
00781   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
00782   AnalyzeNewValue(Lo);
00783   AnalyzeNewValue(Hi);
00784 
00785   // Remember that this is the result of the node.
00786   std::pair<SDValue, SDValue> &Entry = ExpandedIntegers[Op];
00787   assert(Entry.first.getNode() == 0 && "Node already expanded");
00788   Entry.first = Lo;
00789   Entry.second = Hi;
00790 }
00791 
00792 void DAGTypeLegalizer::GetExpandedFloat(SDValue Op, SDValue &Lo,
00793                                         SDValue &Hi) {
00794   std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
00795   RemapValue(Entry.first);
00796   RemapValue(Entry.second);
00797   assert(Entry.first.getNode() && "Operand isn't expanded");
00798   Lo = Entry.first;
00799   Hi = Entry.second;
00800 }
00801 
00802 void DAGTypeLegalizer::SetExpandedFloat(SDValue Op, SDValue Lo,
00803                                         SDValue Hi) {
00804   assert(Lo.getValueType() ==
00805          TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
00806          Hi.getValueType() == Lo.getValueType() &&
00807          "Invalid type for expanded float");
00808   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
00809   AnalyzeNewValue(Lo);
00810   AnalyzeNewValue(Hi);
00811 
00812   // Remember that this is the result of the node.
00813   std::pair<SDValue, SDValue> &Entry = ExpandedFloats[Op];
00814   assert(Entry.first.getNode() == 0 && "Node already expanded");
00815   Entry.first = Lo;
00816   Entry.second = Hi;
00817 }
00818 
00819 void DAGTypeLegalizer::GetSplitVector(SDValue Op, SDValue &Lo,
00820                                       SDValue &Hi) {
00821   std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
00822   RemapValue(Entry.first);
00823   RemapValue(Entry.second);
00824   assert(Entry.first.getNode() && "Operand isn't split");
00825   Lo = Entry.first;
00826   Hi = Entry.second;
00827 }
00828 
00829 void DAGTypeLegalizer::SetSplitVector(SDValue Op, SDValue Lo,
00830                                       SDValue Hi) {
00831   assert(Lo.getValueType().getVectorElementType() ==
00832          Op.getValueType().getVectorElementType() &&
00833          2*Lo.getValueType().getVectorNumElements() ==
00834          Op.getValueType().getVectorNumElements() &&
00835          Hi.getValueType() == Lo.getValueType() &&
00836          "Invalid type for split vector");
00837   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
00838   AnalyzeNewValue(Lo);
00839   AnalyzeNewValue(Hi);
00840 
00841   // Remember that this is the result of the node.
00842   std::pair<SDValue, SDValue> &Entry = SplitVectors[Op];
00843   assert(Entry.first.getNode() == 0 && "Node already split");
00844   Entry.first = Lo;
00845   Entry.second = Hi;
00846 }
00847 
00848 void DAGTypeLegalizer::SetWidenedVector(SDValue Op, SDValue Result) {
00849   assert(Result.getValueType() ==
00850          TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType()) &&
00851          "Invalid type for widened vector");
00852   AnalyzeNewValue(Result);
00853 
00854   SDValue &OpEntry = WidenedVectors[Op];
00855   assert(OpEntry.getNode() == 0 && "Node already widened!");
00856   OpEntry = Result;
00857 }
00858 
00859 
00860 //===----------------------------------------------------------------------===//
00861 // Utilities.
00862 //===----------------------------------------------------------------------===//
00863 
00864 /// BitConvertToInteger - Convert to an integer of the same size.
00865 SDValue DAGTypeLegalizer::BitConvertToInteger(SDValue Op) {
00866   unsigned BitWidth = Op.getValueType().getSizeInBits();
00867   return DAG.getNode(ISD::BITCAST, SDLoc(Op),
00868                      EVT::getIntegerVT(*DAG.getContext(), BitWidth), Op);
00869 }
00870 
00871 /// BitConvertVectorToIntegerVector - Convert to a vector of integers of the
00872 /// same size.
00873 SDValue DAGTypeLegalizer::BitConvertVectorToIntegerVector(SDValue Op) {
00874   assert(Op.getValueType().isVector() && "Only applies to vectors!");
00875   unsigned EltWidth = Op.getValueType().getVectorElementType().getSizeInBits();
00876   EVT EltNVT = EVT::getIntegerVT(*DAG.getContext(), EltWidth);
00877   unsigned NumElts = Op.getValueType().getVectorNumElements();
00878   return DAG.getNode(ISD::BITCAST, SDLoc(Op),
00879                      EVT::getVectorVT(*DAG.getContext(), EltNVT, NumElts), Op);
00880 }
00881 
00882 SDValue DAGTypeLegalizer::CreateStackStoreLoad(SDValue Op,
00883                                                EVT DestVT) {
00884   SDLoc dl(Op);
00885   // Create the stack frame object.  Make sure it is aligned for both
00886   // the source and destination types.
00887   SDValue StackPtr = DAG.CreateStackTemporary(Op.getValueType(), DestVT);
00888   // Emit a store to the stack slot.
00889   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op, StackPtr,
00890                                MachinePointerInfo(), false, false, 0);
00891   // Result is a load from the stack slot.
00892   return DAG.getLoad(DestVT, dl, Store, StackPtr, MachinePointerInfo(),
00893                      false, false, false, 0);
00894 }
00895 
00896 /// CustomLowerNode - Replace the node's results with custom code provided
00897 /// by the target and return "true", or do nothing and return "false".
00898 /// The last parameter is FALSE if we are dealing with a node with legal
00899 /// result types and illegal operand. The second parameter denotes the type of
00900 /// illegal OperandNo in that case.
00901 /// The last parameter being TRUE means we are dealing with a
00902 /// node with illegal result types. The second parameter denotes the type of
00903 /// illegal ResNo in that case.
00904 bool DAGTypeLegalizer::CustomLowerNode(SDNode *N, EVT VT, bool LegalizeResult) {
00905   // See if the target wants to custom lower this node.
00906   if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
00907     return false;
00908 
00909   SmallVector<SDValue, 8> Results;
00910   if (LegalizeResult)
00911     TLI.ReplaceNodeResults(N, Results, DAG);
00912   else
00913     TLI.LowerOperationWrapper(N, Results, DAG);
00914 
00915   if (Results.empty())
00916     // The target didn't want to custom lower it after all.
00917     return false;
00918 
00919   // Make everything that once used N's values now use those in Results instead.
00920   assert(Results.size() == N->getNumValues() &&
00921          "Custom lowering returned the wrong number of results!");
00922   for (unsigned i = 0, e = Results.size(); i != e; ++i) {
00923     ReplaceValueWith(SDValue(N, i), Results[i]);
00924   }
00925   return true;
00926 }
00927 
00928 
00929 /// CustomWidenLowerNode - Widen the node's results with custom code provided
00930 /// by the target and return "true", or do nothing and return "false".
00931 bool DAGTypeLegalizer::CustomWidenLowerNode(SDNode *N, EVT VT) {
00932   // See if the target wants to custom lower this node.
00933   if (TLI.getOperationAction(N->getOpcode(), VT) != TargetLowering::Custom)
00934     return false;
00935 
00936   SmallVector<SDValue, 8> Results;
00937   TLI.ReplaceNodeResults(N, Results, DAG);
00938 
00939   if (Results.empty())
00940     // The target didn't want to custom widen lower its result  after all.
00941     return false;
00942 
00943   // Update the widening map.
00944   assert(Results.size() == N->getNumValues() &&
00945          "Custom lowering returned the wrong number of results!");
00946   for (unsigned i = 0, e = Results.size(); i != e; ++i)
00947     SetWidenedVector(SDValue(N, i), Results[i]);
00948   return true;
00949 }
00950 
00951 SDValue DAGTypeLegalizer::DisintegrateMERGE_VALUES(SDNode *N, unsigned ResNo) {
00952   for (unsigned i = 0, e = N->getNumValues(); i != e; ++i)
00953     if (i != ResNo)
00954       ReplaceValueWith(SDValue(N, i), SDValue(N->getOperand(i)));
00955   return SDValue(N->getOperand(ResNo));
00956 }
00957 
00958 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
00959 /// which is split into two not necessarily identical pieces.
00960 void DAGTypeLegalizer::GetSplitDestVTs(EVT InVT, EVT &LoVT, EVT &HiVT) {
00961   // Currently all types are split in half.
00962   if (!InVT.isVector()) {
00963     LoVT = HiVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
00964   } else {
00965     unsigned NumElements = InVT.getVectorNumElements();
00966     assert(!(NumElements & 1) && "Splitting vector, but not in half!");
00967     LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
00968                                    InVT.getVectorElementType(), NumElements/2);
00969   }
00970 }
00971 
00972 /// GetPairElements - Use ISD::EXTRACT_ELEMENT nodes to extract the low and
00973 /// high parts of the given value.
00974 void DAGTypeLegalizer::GetPairElements(SDValue Pair,
00975                                        SDValue &Lo, SDValue &Hi) {
00976   SDLoc dl(Pair);
00977   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), Pair.getValueType());
00978   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
00979                    DAG.getIntPtrConstant(0));
00980   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, NVT, Pair,
00981                    DAG.getIntPtrConstant(1));
00982 }
00983 
00984 SDValue DAGTypeLegalizer::GetVectorElementPointer(SDValue VecPtr, EVT EltVT,
00985                                                   SDValue Index) {
00986   SDLoc dl(Index);
00987   // Make sure the index type is big enough to compute in.
00988   if (Index.getValueType().bitsGT(TLI.getPointerTy()))
00989     Index = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Index);
00990   else
00991     Index = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Index);
00992 
00993   // Calculate the element offset and add it to the pointer.
00994   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
00995 
00996   Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
00997                       DAG.getConstant(EltSize, Index.getValueType()));
00998   return DAG.getNode(ISD::ADD, dl, Index.getValueType(), Index, VecPtr);
00999 }
01000 
01001 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
01002 SDValue DAGTypeLegalizer::JoinIntegers(SDValue Lo, SDValue Hi) {
01003   // Arbitrarily use dlHi for result SDLoc
01004   SDLoc dlHi(Hi);
01005   SDLoc dlLo(Lo);
01006   EVT LVT = Lo.getValueType();
01007   EVT HVT = Hi.getValueType();
01008   EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
01009                               LVT.getSizeInBits() + HVT.getSizeInBits());
01010 
01011   Lo = DAG.getNode(ISD::ZERO_EXTEND, dlLo, NVT, Lo);
01012   Hi = DAG.getNode(ISD::ANY_EXTEND, dlHi, NVT, Hi);
01013   Hi = DAG.getNode(ISD::SHL, dlHi, NVT, Hi,
01014                    DAG.getConstant(LVT.getSizeInBits(), TLI.getPointerTy()));
01015   return DAG.getNode(ISD::OR, dlHi, NVT, Lo, Hi);
01016 }
01017 
01018 /// LibCallify - Convert the node into a libcall with the same prototype.
01019 SDValue DAGTypeLegalizer::LibCallify(RTLIB::Libcall LC, SDNode *N,
01020                                      bool isSigned) {
01021   unsigned NumOps = N->getNumOperands();
01022   SDLoc dl(N);
01023   if (NumOps == 0) {
01024     return TLI.makeLibCall(DAG, LC, N->getValueType(0), 0, 0, isSigned, dl);
01025   } else if (NumOps == 1) {
01026     SDValue Op = N->getOperand(0);
01027     return TLI.makeLibCall(DAG, LC, N->getValueType(0), &Op, 1, isSigned, dl);
01028   } else if (NumOps == 2) {
01029     SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
01030     return TLI.makeLibCall(DAG, LC, N->getValueType(0), Ops, 2, isSigned, dl);
01031   }
01032   SmallVector<SDValue, 8> Ops(NumOps);
01033   for (unsigned i = 0; i < NumOps; ++i)
01034     Ops[i] = N->getOperand(i);
01035 
01036   return TLI.makeLibCall(DAG, LC, N->getValueType(0),
01037                          &Ops[0], NumOps, isSigned, dl);
01038 }
01039 
01040 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
01041 // ExpandLibCall except that the first operand is the in-chain.
01042 std::pair<SDValue, SDValue>
01043 DAGTypeLegalizer::ExpandChainLibCall(RTLIB::Libcall LC,
01044                                          SDNode *Node,
01045                                          bool isSigned) {
01046   SDValue InChain = Node->getOperand(0);
01047 
01048   TargetLowering::ArgListTy Args;
01049   TargetLowering::ArgListEntry Entry;
01050   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
01051     EVT ArgVT = Node->getOperand(i).getValueType();
01052     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
01053     Entry.Node = Node->getOperand(i);
01054     Entry.Ty = ArgTy;
01055     Entry.isSExt = isSigned;
01056     Entry.isZExt = !isSigned;
01057     Args.push_back(Entry);
01058   }
01059   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
01060                                          TLI.getPointerTy());
01061 
01062   Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
01063   TargetLowering::
01064   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, false,
01065                     0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
01066                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
01067                     Callee, Args, DAG, SDLoc(Node));
01068   std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
01069 
01070   return CallInfo;
01071 }
01072 
01073 /// PromoteTargetBoolean - Promote the given target boolean to a target boolean
01074 /// of the given type.  A target boolean is an integer value, not necessarily of
01075 /// type i1, the bits of which conform to getBooleanContents.
01076 SDValue DAGTypeLegalizer::PromoteTargetBoolean(SDValue Bool, EVT VT) {
01077   SDLoc dl(Bool);
01078   ISD::NodeType ExtendCode =
01079     TargetLowering::getExtendForContent(TLI.getBooleanContents(VT.isVector()));
01080   return DAG.getNode(ExtendCode, dl, VT, Bool);
01081 }
01082 
01083 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
01084 /// bits in Hi.
01085 void DAGTypeLegalizer::SplitInteger(SDValue Op,
01086                                     EVT LoVT, EVT HiVT,
01087                                     SDValue &Lo, SDValue &Hi) {
01088   SDLoc dl(Op);
01089   assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
01090          Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
01091   Lo = DAG.getNode(ISD::TRUNCATE, dl, LoVT, Op);
01092   Hi = DAG.getNode(ISD::SRL, dl, Op.getValueType(), Op,
01093                    DAG.getConstant(LoVT.getSizeInBits(), TLI.getPointerTy()));
01094   Hi = DAG.getNode(ISD::TRUNCATE, dl, HiVT, Hi);
01095 }
01096 
01097 /// SplitInteger - Return the lower and upper halves of Op's bits in a value
01098 /// type half the size of Op's.
01099 void DAGTypeLegalizer::SplitInteger(SDValue Op,
01100                                     SDValue &Lo, SDValue &Hi) {
01101   EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(),
01102                                  Op.getValueType().getSizeInBits()/2);
01103   SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
01104 }
01105 
01106 
01107 //===----------------------------------------------------------------------===//
01108 //  Entry Point
01109 //===----------------------------------------------------------------------===//
01110 
01111 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
01112 /// only uses types natively supported by the target.  Returns "true" if it made
01113 /// any changes.
01114 ///
01115 /// Note that this is an involved process that may invalidate pointers into
01116 /// the graph.
01117 bool SelectionDAG::LegalizeTypes() {
01118   return DAGTypeLegalizer(*this).run();
01119 }