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