LLVM API Documentation

SelectionDAG.cpp

Go to the documentation of this file.
00001 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements the SelectionDAG class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/SelectionDAG.h"
00015 #include "llvm/Constants.h"
00016 #include "llvm/GlobalValue.h"
00017 #include "llvm/Intrinsics.h"
00018 #include "llvm/Assembly/Writer.h"
00019 #include "llvm/CodeGen/MachineBasicBlock.h"
00020 #include "llvm/Support/MathExtras.h"
00021 #include "llvm/Target/MRegisterInfo.h"
00022 #include "llvm/Target/TargetLowering.h"
00023 #include "llvm/Target/TargetInstrInfo.h"
00024 #include "llvm/Target/TargetMachine.h"
00025 #include "llvm/ADT/SetVector.h"
00026 #include "llvm/ADT/StringExtras.h"
00027 #include <iostream>
00028 #include <set>
00029 #include <cmath>
00030 #include <algorithm>
00031 using namespace llvm;
00032 
00033 static bool isCommutativeBinOp(unsigned Opcode) {
00034   switch (Opcode) {
00035   case ISD::ADD:
00036   case ISD::MUL:
00037   case ISD::MULHU:
00038   case ISD::MULHS:
00039   case ISD::FADD:
00040   case ISD::FMUL:
00041   case ISD::AND:
00042   case ISD::OR:
00043   case ISD::XOR: return true;
00044   default: return false; // FIXME: Need commutative info for user ops!
00045   }
00046 }
00047 
00048 // isInvertibleForFree - Return true if there is no cost to emitting the logical
00049 // inverse of this node.
00050 static bool isInvertibleForFree(SDOperand N) {
00051   if (isa<ConstantSDNode>(N.Val)) return true;
00052   if (N.Val->getOpcode() == ISD::SETCC && N.Val->hasOneUse())
00053     return true;
00054   return false;
00055 }
00056 
00057 //===----------------------------------------------------------------------===//
00058 //                              ConstantFPSDNode Class
00059 //===----------------------------------------------------------------------===//
00060 
00061 /// isExactlyValue - We don't rely on operator== working on double values, as
00062 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
00063 /// As such, this method can be used to do an exact bit-for-bit comparison of
00064 /// two floating point values.
00065 bool ConstantFPSDNode::isExactlyValue(double V) const {
00066   return DoubleToBits(V) == DoubleToBits(Value);
00067 }
00068 
00069 //===----------------------------------------------------------------------===//
00070 //                              ISD Namespace
00071 //===----------------------------------------------------------------------===//
00072 
00073 /// isBuildVectorAllOnes - Return true if the specified node is a
00074 /// BUILD_VECTOR where all of the elements are ~0 or undef.
00075 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
00076   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
00077   
00078   unsigned i = 0, e = N->getNumOperands();
00079   
00080   // Skip over all of the undef values.
00081   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
00082     ++i;
00083   
00084   // Do not accept an all-undef vector.
00085   if (i == e) return false;
00086   
00087   // Do not accept build_vectors that aren't all constants or which have non-~0
00088   // elements.
00089   SDOperand NotZero = N->getOperand(i);
00090   if (isa<ConstantSDNode>(NotZero)) {
00091     if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
00092       return false;
00093   } else if (isa<ConstantFPSDNode>(NotZero)) {
00094     MVT::ValueType VT = NotZero.getValueType();
00095     if (VT== MVT::f64) {
00096       if (DoubleToBits(cast<ConstantFPSDNode>(NotZero)->getValue()) !=
00097           (uint64_t)-1)
00098         return false;
00099     } else {
00100       if (FloatToBits(cast<ConstantFPSDNode>(NotZero)->getValue()) !=
00101           (uint32_t)-1)
00102         return false;
00103     }
00104   } else
00105     return false;
00106   
00107   // Okay, we have at least one ~0 value, check to see if the rest match or are
00108   // undefs.
00109   for (++i; i != e; ++i)
00110     if (N->getOperand(i) != NotZero &&
00111         N->getOperand(i).getOpcode() != ISD::UNDEF)
00112       return false;
00113   return true;
00114 }
00115 
00116 
00117 /// isBuildVectorAllZeros - Return true if the specified node is a
00118 /// BUILD_VECTOR where all of the elements are 0 or undef.
00119 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
00120   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
00121   
00122   unsigned i = 0, e = N->getNumOperands();
00123   
00124   // Skip over all of the undef values.
00125   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
00126     ++i;
00127   
00128   // Do not accept an all-undef vector.
00129   if (i == e) return false;
00130   
00131   // Do not accept build_vectors that aren't all constants or which have non-~0
00132   // elements.
00133   SDOperand Zero = N->getOperand(i);
00134   if (isa<ConstantSDNode>(Zero)) {
00135     if (!cast<ConstantSDNode>(Zero)->isNullValue())
00136       return false;
00137   } else if (isa<ConstantFPSDNode>(Zero)) {
00138     if (!cast<ConstantFPSDNode>(Zero)->isExactlyValue(0.0))
00139       return false;
00140   } else
00141     return false;
00142   
00143   // Okay, we have at least one ~0 value, check to see if the rest match or are
00144   // undefs.
00145   for (++i; i != e; ++i)
00146     if (N->getOperand(i) != Zero &&
00147         N->getOperand(i).getOpcode() != ISD::UNDEF)
00148       return false;
00149   return true;
00150 }
00151 
00152 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
00153 /// when given the operation for (X op Y).
00154 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
00155   // To perform this operation, we just need to swap the L and G bits of the
00156   // operation.
00157   unsigned OldL = (Operation >> 2) & 1;
00158   unsigned OldG = (Operation >> 1) & 1;
00159   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
00160                        (OldL << 1) |       // New G bit
00161                        (OldG << 2));        // New L bit.
00162 }
00163 
00164 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
00165 /// 'op' is a valid SetCC operation.
00166 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
00167   unsigned Operation = Op;
00168   if (isInteger)
00169     Operation ^= 7;   // Flip L, G, E bits, but not U.
00170   else
00171     Operation ^= 15;  // Flip all of the condition bits.
00172   if (Operation > ISD::SETTRUE2)
00173     Operation &= ~8;     // Don't let N and U bits get set.
00174   return ISD::CondCode(Operation);
00175 }
00176 
00177 
00178 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
00179 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
00180 /// if the operation does not depend on the sign of the input (setne and seteq).
00181 static int isSignedOp(ISD::CondCode Opcode) {
00182   switch (Opcode) {
00183   default: assert(0 && "Illegal integer setcc operation!");
00184   case ISD::SETEQ:
00185   case ISD::SETNE: return 0;
00186   case ISD::SETLT:
00187   case ISD::SETLE:
00188   case ISD::SETGT:
00189   case ISD::SETGE: return 1;
00190   case ISD::SETULT:
00191   case ISD::SETULE:
00192   case ISD::SETUGT:
00193   case ISD::SETUGE: return 2;
00194   }
00195 }
00196 
00197 /// getSetCCOrOperation - Return the result of a logical OR between different
00198 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
00199 /// returns SETCC_INVALID if it is not possible to represent the resultant
00200 /// comparison.
00201 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
00202                                        bool isInteger) {
00203   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
00204     // Cannot fold a signed integer setcc with an unsigned integer setcc.
00205     return ISD::SETCC_INVALID;
00206 
00207   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
00208 
00209   // If the N and U bits get set then the resultant comparison DOES suddenly
00210   // care about orderedness, and is true when ordered.
00211   if (Op > ISD::SETTRUE2)
00212     Op &= ~16;     // Clear the N bit.
00213   return ISD::CondCode(Op);
00214 }
00215 
00216 /// getSetCCAndOperation - Return the result of a logical AND between different
00217 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
00218 /// function returns zero if it is not possible to represent the resultant
00219 /// comparison.
00220 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
00221                                         bool isInteger) {
00222   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
00223     // Cannot fold a signed setcc with an unsigned setcc.
00224     return ISD::SETCC_INVALID;
00225 
00226   // Combine all of the condition bits.
00227   return ISD::CondCode(Op1 & Op2);
00228 }
00229 
00230 const TargetMachine &SelectionDAG::getTarget() const {
00231   return TLI.getTargetMachine();
00232 }
00233 
00234 //===----------------------------------------------------------------------===//
00235 //                              SelectionDAG Class
00236 //===----------------------------------------------------------------------===//
00237 
00238 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
00239 /// SelectionDAG, including nodes (like loads) that have uses of their token
00240 /// chain but no other uses and no side effect.  If a node is passed in as an
00241 /// argument, it is used as the seed for node deletion.
00242 void SelectionDAG::RemoveDeadNodes(SDNode *N) {
00243   // Create a dummy node (which is not added to allnodes), that adds a reference
00244   // to the root node, preventing it from being deleted.
00245   HandleSDNode Dummy(getRoot());
00246 
00247   bool MadeChange = false;
00248   
00249   // If we have a hint to start from, use it.
00250   if (N && N->use_empty()) {
00251     DestroyDeadNode(N);
00252     MadeChange = true;
00253   }
00254 
00255   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
00256     if (I->use_empty() && I->getOpcode() != 65535) {
00257       // Node is dead, recursively delete newly dead uses.
00258       DestroyDeadNode(I);
00259       MadeChange = true;
00260     }
00261   
00262   // Walk the nodes list, removing the nodes we've marked as dead.
00263   if (MadeChange) {
00264     for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ) {
00265       SDNode *N = I++;
00266       if (N->use_empty())
00267         AllNodes.erase(N);
00268     }
00269   }
00270   
00271   // If the root changed (e.g. it was a dead load, update the root).
00272   setRoot(Dummy.getValue());
00273 }
00274 
00275 /// DestroyDeadNode - We know that N is dead.  Nuke it from the CSE maps for the
00276 /// graph.  If it is the last user of any of its operands, recursively process
00277 /// them the same way.
00278 /// 
00279 void SelectionDAG::DestroyDeadNode(SDNode *N) {
00280   // Okay, we really are going to delete this node.  First take this out of the
00281   // appropriate CSE map.
00282   RemoveNodeFromCSEMaps(N);
00283   
00284   // Next, brutally remove the operand list.  This is safe to do, as there are
00285   // no cycles in the graph.
00286   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
00287     SDNode *O = I->Val;
00288     O->removeUser(N);
00289     
00290     // Now that we removed this operand, see if there are no uses of it left.
00291     if (O->use_empty())
00292       DestroyDeadNode(O);
00293   }
00294   delete[] N->OperandList;
00295   N->OperandList = 0;
00296   N->NumOperands = 0;
00297 
00298   // Mark the node as dead.
00299   N->MorphNodeTo(65535);
00300 }
00301 
00302 void SelectionDAG::DeleteNode(SDNode *N) {
00303   assert(N->use_empty() && "Cannot delete a node that is not dead!");
00304 
00305   // First take this out of the appropriate CSE map.
00306   RemoveNodeFromCSEMaps(N);
00307 
00308   // Finally, remove uses due to operands of this node, remove from the 
00309   // AllNodes list, and delete the node.
00310   DeleteNodeNotInCSEMaps(N);
00311 }
00312 
00313 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
00314 
00315   // Remove it from the AllNodes list.
00316   AllNodes.remove(N);
00317     
00318   // Drop all of the operands and decrement used nodes use counts.
00319   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
00320     I->Val->removeUser(N);
00321   delete[] N->OperandList;
00322   N->OperandList = 0;
00323   N->NumOperands = 0;
00324   
00325   delete N;
00326 }
00327 
00328 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
00329 /// correspond to it.  This is useful when we're about to delete or repurpose
00330 /// the node.  We don't want future request for structurally identical nodes
00331 /// to return N anymore.
00332 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
00333   bool Erased = false;
00334   switch (N->getOpcode()) {
00335   case ISD::HANDLENODE: return;  // noop.
00336   case ISD::Constant:
00337     Erased = Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
00338                                             N->getValueType(0)));
00339     break;
00340   case ISD::TargetConstant:
00341     Erased = TargetConstants.erase(std::make_pair(
00342                                     cast<ConstantSDNode>(N)->getValue(),
00343                                                   N->getValueType(0)));
00344     break;
00345   case ISD::ConstantFP: {
00346     uint64_t V = DoubleToBits(cast<ConstantFPSDNode>(N)->getValue());
00347     Erased = ConstantFPs.erase(std::make_pair(V, N->getValueType(0)));
00348     break;
00349   }
00350   case ISD::TargetConstantFP: {
00351     uint64_t V = DoubleToBits(cast<ConstantFPSDNode>(N)->getValue());
00352     Erased = TargetConstantFPs.erase(std::make_pair(V, N->getValueType(0)));
00353     break;
00354   }
00355   case ISD::STRING:
00356     Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
00357     break;
00358   case ISD::CONDCODE:
00359     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
00360            "Cond code doesn't exist!");
00361     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
00362     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
00363     break;
00364   case ISD::GlobalAddress: {
00365     GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(N);
00366     Erased = GlobalValues.erase(std::make_pair(GN->getGlobal(),
00367                                                GN->getOffset()));
00368     break;
00369   }
00370   case ISD::TargetGlobalAddress: {
00371     GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(N);
00372     Erased =TargetGlobalValues.erase(std::make_pair(GN->getGlobal(),
00373                                                     GN->getOffset()));
00374     break;
00375   }
00376   case ISD::FrameIndex:
00377     Erased = FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
00378     break;
00379   case ISD::TargetFrameIndex:
00380     Erased = TargetFrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
00381     break;
00382   case ISD::ConstantPool:
00383     Erased = ConstantPoolIndices.
00384       erase(std::make_pair(cast<ConstantPoolSDNode>(N)->get(),
00385                         std::make_pair(cast<ConstantPoolSDNode>(N)->getOffset(),
00386                                  cast<ConstantPoolSDNode>(N)->getAlignment())));
00387     break;
00388   case ISD::TargetConstantPool:
00389     Erased = TargetConstantPoolIndices.
00390       erase(std::make_pair(cast<ConstantPoolSDNode>(N)->get(),
00391                         std::make_pair(cast<ConstantPoolSDNode>(N)->getOffset(),
00392                                  cast<ConstantPoolSDNode>(N)->getAlignment())));
00393     break;
00394   case ISD::BasicBlock:
00395     Erased = BBNodes.erase(cast<BasicBlockSDNode>(N)->getBasicBlock());
00396     break;
00397   case ISD::ExternalSymbol:
00398     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
00399     break;
00400   case ISD::TargetExternalSymbol:
00401     Erased =
00402       TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
00403     break;
00404   case ISD::VALUETYPE:
00405     Erased = ValueTypeNodes[cast<VTSDNode>(N)->getVT()] != 0;
00406     ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
00407     break;
00408   case ISD::Register:
00409     Erased = RegNodes.erase(std::make_pair(cast<RegisterSDNode>(N)->getReg(),
00410                                            N->getValueType(0)));
00411     break;
00412   case ISD::SRCVALUE: {
00413     SrcValueSDNode *SVN = cast<SrcValueSDNode>(N);
00414     Erased =ValueNodes.erase(std::make_pair(SVN->getValue(), SVN->getOffset()));
00415     break;
00416   }    
00417   case ISD::LOAD:
00418     Erased = Loads.erase(std::make_pair(N->getOperand(1),
00419                                         std::make_pair(N->getOperand(0),
00420                                                        N->getValueType(0))));
00421     break;
00422   default:
00423     if (N->getNumValues() == 1) {
00424       if (N->getNumOperands() == 0) {
00425         Erased = NullaryOps.erase(std::make_pair(N->getOpcode(),
00426                                                  N->getValueType(0)));
00427       } else if (N->getNumOperands() == 1) {
00428         Erased = 
00429           UnaryOps.erase(std::make_pair(N->getOpcode(),
00430                                         std::make_pair(N->getOperand(0),
00431                                                        N->getValueType(0))));
00432       } else if (N->getNumOperands() == 2) {
00433         Erased = 
00434           BinaryOps.erase(std::make_pair(N->getOpcode(),
00435                                          std::make_pair(N->getOperand(0),
00436                                                         N->getOperand(1))));
00437       } else { 
00438         std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
00439         Erased = 
00440           OneResultNodes.erase(std::make_pair(N->getOpcode(),
00441                                               std::make_pair(N->getValueType(0),
00442                                                              Ops)));
00443       }
00444     } else {
00445       // Remove the node from the ArbitraryNodes map.
00446       std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
00447       std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
00448       Erased =
00449         ArbitraryNodes.erase(std::make_pair(N->getOpcode(),
00450                                             std::make_pair(RV, Ops)));
00451     }
00452     break;
00453   }
00454 #ifndef NDEBUG
00455   // Verify that the node was actually in one of the CSE maps, unless it has a 
00456   // flag result (which cannot be CSE'd) or is one of the special cases that are
00457   // not subject to CSE.
00458   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
00459       !N->isTargetOpcode()) {
00460     N->dump();
00461     assert(0 && "Node is not in map!");
00462   }
00463 #endif
00464 }
00465 
00466 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
00467 /// has been taken out and modified in some way.  If the specified node already
00468 /// exists in the CSE maps, do not modify the maps, but return the existing node
00469 /// instead.  If it doesn't exist, add it and return null.
00470 ///
00471 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
00472   assert(N->getNumOperands() && "This is a leaf node!");
00473   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
00474     return 0;    // Never add these nodes.
00475   
00476   // Check that remaining values produced are not flags.
00477   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
00478     if (N->getValueType(i) == MVT::Flag)
00479       return 0;   // Never CSE anything that produces a flag.
00480   
00481   if (N->getNumValues() == 1) {
00482     if (N->getNumOperands() == 1) {
00483       SDNode *&U = UnaryOps[std::make_pair(N->getOpcode(),
00484                                            std::make_pair(N->getOperand(0),
00485                                                           N->getValueType(0)))];
00486       if (U) return U;
00487       U = N;
00488     } else if (N->getNumOperands() == 2) {
00489       SDNode *&B = BinaryOps[std::make_pair(N->getOpcode(),
00490                                             std::make_pair(N->getOperand(0),
00491                                                            N->getOperand(1)))];
00492       if (B) return B;
00493       B = N;
00494     } else {
00495       std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
00496       SDNode *&ORN = OneResultNodes[std::make_pair(N->getOpcode(),
00497                                       std::make_pair(N->getValueType(0), Ops))];
00498       if (ORN) return ORN;
00499       ORN = N;
00500     }
00501   } else {  
00502     if (N->getOpcode() == ISD::LOAD) {
00503       SDNode *&L = Loads[std::make_pair(N->getOperand(1),
00504                                         std::make_pair(N->getOperand(0),
00505                                                        N->getValueType(0)))];
00506       if (L) return L;
00507       L = N;
00508     } else {
00509       // Remove the node from the ArbitraryNodes map.
00510       std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
00511       std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
00512       SDNode *&AN = ArbitraryNodes[std::make_pair(N->getOpcode(),
00513                                                   std::make_pair(RV, Ops))];
00514       if (AN) return AN;
00515       AN = N;
00516     }
00517   }
00518   return 0;
00519 }
00520 
00521 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
00522 /// were replaced with those specified.  If this node is never memoized, 
00523 /// return null, otherwise return a pointer to the slot it would take.  If a
00524 /// node already exists with these operands, the slot will be non-null.
00525 SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op) {
00526   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
00527     return 0;    // Never add these nodes.
00528   
00529   // Check that remaining values produced are not flags.
00530   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
00531     if (N->getValueType(i) == MVT::Flag)
00532       return 0;   // Never CSE anything that produces a flag.
00533   
00534   if (N->getNumValues() == 1) {
00535     return &UnaryOps[std::make_pair(N->getOpcode(),
00536                                     std::make_pair(Op, N->getValueType(0)))];
00537   } else {  
00538     // Remove the node from the ArbitraryNodes map.
00539     std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
00540     std::vector<SDOperand> Ops;
00541     Ops.push_back(Op);
00542     return &ArbitraryNodes[std::make_pair(N->getOpcode(),
00543                                           std::make_pair(RV, Ops))];
00544   }
00545   return 0;
00546 }
00547 
00548 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
00549 /// were replaced with those specified.  If this node is never memoized, 
00550 /// return null, otherwise return a pointer to the slot it would take.  If a
00551 /// node already exists with these operands, the slot will be non-null.
00552 SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
00553                                             SDOperand Op1, SDOperand Op2) {
00554   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
00555     return 0;    // Never add these nodes.
00556   
00557   // Check that remaining values produced are not flags.
00558   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
00559     if (N->getValueType(i) == MVT::Flag)
00560       return 0;   // Never CSE anything that produces a flag.
00561   
00562   if (N->getNumValues() == 1) {
00563     return &BinaryOps[std::make_pair(N->getOpcode(),
00564                                      std::make_pair(Op1, Op2))];
00565   } else {  
00566     std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
00567     std::vector<SDOperand> Ops;
00568     Ops.push_back(Op1);
00569     Ops.push_back(Op2);
00570     return &ArbitraryNodes[std::make_pair(N->getOpcode(),
00571                                           std::make_pair(RV, Ops))];
00572   }
00573   return 0;
00574 }
00575 
00576 
00577 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
00578 /// were replaced with those specified.  If this node is never memoized, 
00579 /// return null, otherwise return a pointer to the slot it would take.  If a
00580 /// node already exists with these operands, the slot will be non-null.
00581 SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
00582                                             const std::vector<SDOperand> &Ops) {
00583   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
00584     return 0;    // Never add these nodes.
00585   
00586   // Check that remaining values produced are not flags.
00587   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
00588     if (N->getValueType(i) == MVT::Flag)
00589       return 0;   // Never CSE anything that produces a flag.
00590   
00591   if (N->getNumValues() == 1) {
00592     if (N->getNumOperands() == 1) {
00593       return &UnaryOps[std::make_pair(N->getOpcode(),
00594                                       std::make_pair(Ops[0],
00595                                                      N->getValueType(0)))];
00596     } else if (N->getNumOperands() == 2) {
00597       return &BinaryOps[std::make_pair(N->getOpcode(),
00598                                        std::make_pair(Ops[0], Ops[1]))];
00599     } else {
00600       return &OneResultNodes[std::make_pair(N->getOpcode(),
00601                                             std::make_pair(N->getValueType(0),
00602                                                            Ops))];
00603     }
00604   } else {  
00605     if (N->getOpcode() == ISD::LOAD) {
00606       return &Loads[std::make_pair(Ops[1],
00607                                    std::make_pair(Ops[0], N->getValueType(0)))];
00608     } else {
00609       std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
00610       return &ArbitraryNodes[std::make_pair(N->getOpcode(),
00611                                             std::make_pair(RV, Ops))];
00612     }
00613   }
00614   return 0;
00615 }
00616 
00617 
00618 SelectionDAG::~SelectionDAG() {
00619   while (!AllNodes.empty()) {
00620     SDNode *N = AllNodes.begin();
00621     delete [] N->OperandList;
00622     N->OperandList = 0;
00623     N->NumOperands = 0;
00624     AllNodes.pop_front();
00625   }
00626 }
00627 
00628 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
00629   if (Op.getValueType() == VT) return Op;
00630   int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
00631   return getNode(ISD::AND, Op.getValueType(), Op,
00632                  getConstant(Imm, Op.getValueType()));
00633 }
00634 
00635 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
00636   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
00637   assert(!MVT::isVector(VT) && "Cannot create Vector ConstantSDNodes!");
00638   
00639   // Mask out any bits that are not valid for this constant.
00640   if (VT != MVT::i64)
00641     Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
00642 
00643   SDNode *&N = Constants[std::make_pair(Val, VT)];
00644   if (N) return SDOperand(N, 0);
00645   N = new ConstantSDNode(false, Val, VT);
00646   AllNodes.push_back(N);
00647   return SDOperand(N, 0);
00648 }
00649 
00650 SDOperand SelectionDAG::getString(const std::string &Val) {
00651   StringSDNode *&N = StringNodes[Val];
00652   if (!N) {
00653     N = new StringSDNode(Val);
00654     AllNodes.push_back(N);
00655   }
00656   return SDOperand(N, 0);
00657 }
00658 
00659 SDOperand SelectionDAG::getTargetConstant(uint64_t Val, MVT::ValueType VT) {
00660   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
00661   // Mask out any bits that are not valid for this constant.
00662   if (VT != MVT::i64)
00663     Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
00664   
00665   SDNode *&N = TargetConstants[std::make_pair(Val, VT)];
00666   if (N) return SDOperand(N, 0);
00667   N = new ConstantSDNode(true, Val, VT);
00668   AllNodes.push_back(N);
00669   return SDOperand(N, 0);
00670 }
00671 
00672 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
00673   assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
00674   if (VT == MVT::f32)
00675     Val = (float)Val;  // Mask out extra precision.
00676 
00677   // Do the map lookup using the actual bit pattern for the floating point
00678   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
00679   // we don't have issues with SNANs.
00680   SDNode *&N = ConstantFPs[std::make_pair(DoubleToBits(Val), VT)];
00681   if (N) return SDOperand(N, 0);
00682   N = new ConstantFPSDNode(false, Val, VT);
00683   AllNodes.push_back(N);
00684   return SDOperand(N, 0);
00685 }
00686 
00687 SDOperand SelectionDAG::getTargetConstantFP(double Val, MVT::ValueType VT) {
00688   assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
00689   if (VT == MVT::f32)
00690     Val = (float)Val;  // Mask out extra precision.
00691   
00692   // Do the map lookup using the actual bit pattern for the floating point
00693   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
00694   // we don't have issues with SNANs.
00695   SDNode *&N = TargetConstantFPs[std::make_pair(DoubleToBits(Val), VT)];
00696   if (N) return SDOperand(N, 0);
00697   N = new ConstantFPSDNode(true, Val, VT);
00698   AllNodes.push_back(N);
00699   return SDOperand(N, 0);
00700 }
00701 
00702 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
00703                                          MVT::ValueType VT, int offset) {
00704   SDNode *&N = GlobalValues[std::make_pair(GV, offset)];
00705   if (N) return SDOperand(N, 0);
00706   N = new GlobalAddressSDNode(false, GV, VT, offset);
00707   AllNodes.push_back(N);
00708   return SDOperand(N, 0);
00709 }
00710 
00711 SDOperand SelectionDAG::getTargetGlobalAddress(const GlobalValue *GV,
00712                                                MVT::ValueType VT, int offset) {
00713   SDNode *&N = TargetGlobalValues[std::make_pair(GV, offset)];
00714   if (N) return SDOperand(N, 0);
00715   N = new GlobalAddressSDNode(true, GV, VT, offset);
00716   AllNodes.push_back(N);
00717   return SDOperand(N, 0);
00718 }
00719 
00720 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
00721   SDNode *&N = FrameIndices[FI];
00722   if (N) return SDOperand(N, 0);
00723   N = new FrameIndexSDNode(FI, VT, false);
00724   AllNodes.push_back(N);
00725   return SDOperand(N, 0);
00726 }
00727 
00728 SDOperand SelectionDAG::getTargetFrameIndex(int FI, MVT::ValueType VT) {
00729   SDNode *&N = TargetFrameIndices[FI];
00730   if (N) return SDOperand(N, 0);
00731   N = new FrameIndexSDNode(FI, VT, true);
00732   AllNodes.push_back(N);
00733   return SDOperand(N, 0);
00734 }
00735 
00736 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
00737                                         unsigned Alignment,  int Offset) {
00738   SDNode *&N = ConstantPoolIndices[std::make_pair(C,
00739                                             std::make_pair(Offset, Alignment))];
00740   if (N) return SDOperand(N, 0);
00741   N = new ConstantPoolSDNode(false, C, VT, Offset, Alignment);
00742   AllNodes.push_back(N);
00743   return SDOperand(N, 0);
00744 }
00745 
00746 SDOperand SelectionDAG::getTargetConstantPool(Constant *C, MVT::ValueType VT,
00747                                              unsigned Alignment,  int Offset) {
00748   SDNode *&N = TargetConstantPoolIndices[std::make_pair(C,
00749                                             std::make_pair(Offset, Alignment))];
00750   if (N) return SDOperand(N, 0);
00751   N = new ConstantPoolSDNode(true, C, VT, Offset, Alignment);
00752   AllNodes.push_back(N);
00753   return SDOperand(N, 0);
00754 }
00755 
00756 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
00757   SDNode *&N = BBNodes[MBB];
00758   if (N) return SDOperand(N, 0);
00759   N = new BasicBlockSDNode(MBB);
00760   AllNodes.push_back(N);
00761   return SDOperand(N, 0);
00762 }
00763 
00764 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
00765   if ((unsigned)VT >= ValueTypeNodes.size())
00766     ValueTypeNodes.resize(VT+1);
00767   if (ValueTypeNodes[VT] == 0) {
00768     ValueTypeNodes[VT] = new VTSDNode(VT);
00769     AllNodes.push_back(ValueTypeNodes[VT]);
00770   }
00771 
00772   return SDOperand(ValueTypeNodes[VT], 0);
00773 }
00774 
00775 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
00776   SDNode *&N = ExternalSymbols[Sym];
00777   if (N) return SDOperand(N, 0);
00778   N = new ExternalSymbolSDNode(false, Sym, VT);
00779   AllNodes.push_back(N);
00780   return SDOperand(N, 0);
00781 }
00782 
00783 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
00784                                                 MVT::ValueType VT) {
00785   SDNode *&N = TargetExternalSymbols[Sym];
00786   if (N) return SDOperand(N, 0);
00787   N = new ExternalSymbolSDNode(true, Sym, VT);
00788   AllNodes.push_back(N);
00789   return SDOperand(N, 0);
00790 }
00791 
00792 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
00793   if ((unsigned)Cond >= CondCodeNodes.size())
00794     CondCodeNodes.resize(Cond+1);
00795   
00796   if (CondCodeNodes[Cond] == 0) {
00797     CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
00798     AllNodes.push_back(CondCodeNodes[Cond]);
00799   }
00800   return SDOperand(CondCodeNodes[Cond], 0);
00801 }
00802 
00803 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
00804   RegisterSDNode *&Reg = RegNodes[std::make_pair(RegNo, VT)];
00805   if (!Reg) {
00806     Reg = new RegisterSDNode(RegNo, VT);
00807     AllNodes.push_back(Reg);
00808   }
00809   return SDOperand(Reg, 0);
00810 }
00811 
00812 SDOperand SelectionDAG::SimplifySetCC(MVT::ValueType VT, SDOperand N1,
00813                                       SDOperand N2, ISD::CondCode Cond) {
00814   // These setcc operations always fold.
00815   switch (Cond) {
00816   default: break;
00817   case ISD::SETFALSE:
00818   case ISD::SETFALSE2: return getConstant(0, VT);
00819   case ISD::SETTRUE:
00820   case ISD::SETTRUE2:  return getConstant(1, VT);
00821   }
00822 
00823   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
00824     uint64_t C2 = N2C->getValue();
00825     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
00826       uint64_t C1 = N1C->getValue();
00827 
00828       // Sign extend the operands if required
00829       if (ISD::isSignedIntSetCC(Cond)) {
00830         C1 = N1C->getSignExtended();
00831         C2 = N2C->getSignExtended();
00832       }
00833 
00834       switch (Cond) {
00835       default: assert(0 && "Unknown integer setcc!");
00836       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
00837       case ISD::SETNE:  return getConstant(C1 != C2, VT);
00838       case ISD::SETULT: return getConstant(C1 <  C2, VT);
00839       case ISD::SETUGT: return getConstant(C1 >  C2, VT);
00840       case ISD::SETULE: return getConstant(C1 <= C2, VT);
00841       case ISD::SETUGE: return getConstant(C1 >= C2, VT);
00842       case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
00843       case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
00844       case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
00845       case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
00846       }
00847     } else {
00848       // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
00849       if (N1.getOpcode() == ISD::ZERO_EXTEND) {
00850         unsigned InSize = MVT::getSizeInBits(N1.getOperand(0).getValueType());
00851 
00852         // If the comparison constant has bits in the upper part, the
00853         // zero-extended value could never match.
00854         if (C2 & (~0ULL << InSize)) {
00855           unsigned VSize = MVT::getSizeInBits(N1.getValueType());
00856           switch (Cond) {
00857           case ISD::SETUGT:
00858           case ISD::SETUGE:
00859           case ISD::SETEQ: return getConstant(0, VT);
00860           case ISD::SETULT:
00861           case ISD::SETULE:
00862           case ISD::SETNE: return getConstant(1, VT);
00863           case ISD::SETGT:
00864           case ISD::SETGE:
00865             // True if the sign bit of C2 is set.
00866             return getConstant((C2 & (1ULL << VSize)) != 0, VT);
00867           case ISD::SETLT:
00868           case ISD::SETLE:
00869             // True if the sign bit of C2 isn't set.
00870             return getConstant((C2 & (1ULL << VSize)) == 0, VT);
00871           default:
00872             break;
00873           }
00874         }
00875 
00876         // Otherwise, we can perform the comparison with the low bits.
00877         switch (Cond) {
00878         case ISD::SETEQ:
00879         case ISD::SETNE:
00880         case ISD::SETUGT:
00881         case ISD::SETUGE:
00882         case ISD::SETULT:
00883         case ISD::SETULE:
00884           return getSetCC(VT, N1.getOperand(0),
00885                           getConstant(C2, N1.getOperand(0).getValueType()),
00886                           Cond);
00887         default:
00888           break;   // todo, be more careful with signed comparisons
00889         }
00890       } else if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
00891                  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
00892         MVT::ValueType ExtSrcTy = cast<VTSDNode>(N1.getOperand(1))->getVT();
00893         unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
00894         MVT::ValueType ExtDstTy = N1.getValueType();
00895         unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
00896 
00897         // If the extended part has any inconsistent bits, it cannot ever
00898         // compare equal.  In other words, they have to be all ones or all
00899         // zeros.
00900         uint64_t ExtBits =
00901           (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
00902         if ((C2 & ExtBits) != 0 && (C2 & ExtBits) != ExtBits)
00903           return getConstant(Cond == ISD::SETNE, VT);
00904         
00905         // Otherwise, make this a use of a zext.
00906         return getSetCC(VT, getZeroExtendInReg(N1.getOperand(0), ExtSrcTy),
00907                         getConstant(C2 & (~0ULL>>(64-ExtSrcTyBits)), ExtDstTy),
00908                         Cond);
00909       }
00910 
00911       uint64_t MinVal, MaxVal;
00912       unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
00913       if (ISD::isSignedIntSetCC(Cond)) {
00914         MinVal = 1ULL << (OperandBitSize-1);
00915         if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
00916           MaxVal = ~0ULL >> (65-OperandBitSize);
00917         else
00918           MaxVal = 0;
00919       } else {
00920         MinVal = 0;
00921         MaxVal = ~0ULL >> (64-OperandBitSize);
00922       }
00923 
00924       // Canonicalize GE/LE comparisons to use GT/LT comparisons.
00925       if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
00926         if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
00927         --C2;                                          // X >= C1 --> X > (C1-1)
00928         return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
00929                         (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
00930       }
00931 
00932       if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
00933         if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
00934         ++C2;                                          // X <= C1 --> X < (C1+1)
00935         return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
00936                         (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
00937       }
00938 
00939       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
00940         return getConstant(0, VT);      // X < MIN --> false
00941 
00942       // Canonicalize setgt X, Min --> setne X, Min
00943       if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
00944         return getSetCC(VT, N1, N2, ISD::SETNE);
00945 
00946       // If we have setult X, 1, turn it into seteq X, 0
00947       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
00948         return getSetCC(VT, N1, getConstant(MinVal, N1.getValueType()),
00949                         ISD::SETEQ);
00950       // If we have setugt X, Max-1, turn it into seteq X, Max
00951       else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
00952         return getSetCC(VT, N1, getConstant(MaxVal, N1.getValueType()),
00953                         ISD::SETEQ);
00954 
00955       // If we have "setcc X, C1", check to see if we can shrink the immediate
00956       // by changing cc.
00957 
00958       // SETUGT X, SINTMAX  -> SETLT X, 0
00959       if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
00960           C2 == (~0ULL >> (65-OperandBitSize)))
00961         return getSetCC(VT, N1, getConstant(0, N2.getValueType()), ISD::SETLT);
00962 
00963       // FIXME: Implement the rest of these.
00964 
00965 
00966       // Fold bit comparisons when we can.
00967       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
00968           VT == N1.getValueType() && N1.getOpcode() == ISD::AND)
00969         if (ConstantSDNode *AndRHS =
00970                     dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
00971           if (Cond == ISD::SETNE && C2 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
00972             // Perform the xform if the AND RHS is a single bit.
00973             if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
00974               return getNode(ISD::SRL, VT, N1,
00975                              getConstant(Log2_64(AndRHS->getValue()),
00976                                                    TLI.getShiftAmountTy()));
00977             }
00978           } else if (Cond == ISD::SETEQ && C2 == AndRHS->getValue()) {
00979             // (X & 8) == 8  -->  (X & 8) >> 3
00980             // Perform the xform if C2 is a single bit.
00981             if ((C2 & (C2-1)) == 0) {
00982               return getNode(ISD::SRL, VT, N1,
00983                              getConstant(Log2_64(C2),TLI.getShiftAmountTy()));
00984             }
00985           }
00986         }
00987     }
00988   } else if (isa<ConstantSDNode>(N1.Val)) {
00989       // Ensure that the constant occurs on the RHS.
00990     return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
00991   }
00992 
00993   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
00994     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
00995       double C1 = N1C->getValue(), C2 = N2C->getValue();
00996 
00997       switch (Cond) {
00998       default: break; // FIXME: Implement the rest of these!
00999       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
01000       case ISD::SETNE:  return getConstant(C1 != C2, VT);
01001       case ISD::SETLT:  return getConstant(C1 < C2, VT);
01002       case ISD::SETGT:  return getConstant(C1 > C2, VT);
01003       case ISD::SETLE:  return getConstant(C1 <= C2, VT);
01004       case ISD::SETGE:  return getConstant(C1 >= C2, VT);
01005       }
01006     } else {
01007       // Ensure that the constant occurs on the RHS.
01008       return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
01009     }
01010 
01011   // Could not fold it.
01012   return SDOperand();
01013 }
01014 
01015 /// getNode - Gets or creates the specified node.
01016 ///
01017 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
01018   SDNode *&N = NullaryOps[std::make_pair(Opcode, VT)];
01019   if (!N) {
01020     N = new SDNode(Opcode, VT);
01021     AllNodes.push_back(N);
01022   }
01023   return SDOperand(N, 0);
01024 }
01025 
01026 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
01027                                 SDOperand Operand) {
01028   unsigned Tmp1;
01029   // Constant fold unary operations with an integer constant operand.
01030   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
01031     uint64_t Val = C->getValue();
01032     switch (Opcode) {
01033     default: break;
01034     case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
01035     case ISD::ANY_EXTEND:
01036     case ISD::ZERO_EXTEND: return getConstant(Val, VT);
01037     case ISD::TRUNCATE:    return getConstant(Val, VT);
01038     case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
01039     case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
01040     case ISD::BIT_CONVERT:
01041       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
01042         return getConstantFP(BitsToFloat(Val), VT);
01043       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
01044         return getConstantFP(BitsToDouble(Val), VT);
01045       break;
01046     case ISD::BSWAP:
01047       switch(VT) {
01048       default: assert(0 && "Invalid bswap!"); break;
01049       case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
01050       case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
01051       case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
01052       }
01053       break;
01054     case ISD::CTPOP:
01055       switch(VT) {
01056       default: assert(0 && "Invalid ctpop!"); break;
01057       case MVT::i1: return getConstant(Val != 0, VT);
01058       case MVT::i8: 
01059         Tmp1 = (unsigned)Val & 0xFF;
01060         return getConstant(CountPopulation_32(Tmp1), VT);
01061       case MVT::i16:
01062         Tmp1 = (unsigned)Val & 0xFFFF;
01063         return getConstant(CountPopulation_32(Tmp1), VT);
01064       case MVT::i32:
01065         return getConstant(CountPopulation_32((unsigned)Val), VT);
01066       case MVT::i64:
01067         return getConstant(CountPopulation_64(Val), VT);
01068       }
01069     case ISD::CTLZ:
01070       switch(VT) {
01071       default: assert(0 && "Invalid ctlz!"); break;
01072       case MVT::i1: return getConstant(Val == 0, VT);
01073       case MVT::i8: 
01074         Tmp1 = (unsigned)Val & 0xFF;
01075         return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
01076       case MVT::i16:
01077         Tmp1 = (unsigned)Val & 0xFFFF;
01078         return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
01079       case MVT::i32:
01080         return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
01081       case MVT::i64:
01082         return getConstant(CountLeadingZeros_64(Val), VT);
01083       }
01084     case ISD::CTTZ:
01085       switch(VT) {
01086       default: assert(0 && "Invalid cttz!"); break;
01087       case MVT::i1: return getConstant(Val == 0, VT);
01088       case MVT::i8: 
01089         Tmp1 = (unsigned)Val | 0x100;
01090         return getConstant(CountTrailingZeros_32(Tmp1), VT);
01091       case MVT::i16:
01092         Tmp1 = (unsigned)Val | 0x10000;
01093         return getConstant(CountTrailingZeros_32(Tmp1), VT);
01094       case MVT::i32:
01095         return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
01096       case MVT::i64:
01097         return getConstant(CountTrailingZeros_64(Val), VT);
01098       }
01099     }
01100   }
01101 
01102   // Constant fold unary operations with an floating point constant operand.
01103   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
01104     switch (Opcode) {
01105     case ISD::FNEG:
01106       return getConstantFP(-C->getValue(), VT);
01107     case ISD::FABS:
01108       return getConstantFP(fabs(C->getValue()), VT);
01109     case ISD::FP_ROUND:
01110     case ISD::FP_EXTEND:
01111       return getConstantFP(C->getValue(), VT);
01112     case ISD::FP_TO_SINT:
01113       return getConstant((int64_t)C->getValue(), VT);
01114     case ISD::FP_TO_UINT:
01115       return getConstant((uint64_t)C->getValue(), VT);
01116     case ISD::BIT_CONVERT:
01117       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
01118         return getConstant(FloatToBits(C->getValue()), VT);
01119       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
01120         return getConstant(DoubleToBits(C->getValue()), VT);
01121       break;
01122     }
01123 
01124   unsigned OpOpcode = Operand.Val->getOpcode();
01125   switch (Opcode) {
01126   case ISD::TokenFactor:
01127     return Operand;         // Factor of one node?  No factor.
01128   case ISD::SIGN_EXTEND:
01129     if (Operand.getValueType() == VT) return Operand;   // noop extension
01130     assert(Operand.getValueType() < VT && "Invalid sext node, dst < src!");
01131     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
01132       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
01133     break;
01134   case ISD::ZERO_EXTEND:
01135     if (Operand.getValueType() == VT) return Operand;   // noop extension
01136     assert(Operand.getValueType() < VT && "Invalid zext node, dst < src!");
01137     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
01138       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
01139     break;
01140   case ISD::ANY_EXTEND:
01141     if (Operand.getValueType() == VT) return Operand;   // noop extension
01142     assert(Operand.getValueType() < VT && "Invalid anyext node, dst < src!");
01143     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
01144       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
01145       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
01146     break;
01147   case ISD::TRUNCATE:
01148     if (Operand.getValueType() == VT) return Operand;   // noop truncate
01149     assert(Operand.getValueType() > VT && "Invalid truncate node, src < dst!");
01150     if (OpOpcode == ISD::TRUNCATE)
01151       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
01152     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
01153              OpOpcode == ISD::ANY_EXTEND) {
01154       // If the source is smaller than the dest, we still need an extend.
01155       if (Operand.Val->getOperand(0).getValueType() < VT)
01156         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
01157       else if (Operand.Val->getOperand(0).getValueType() > VT)
01158         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
01159       else
01160         return Operand.Val->getOperand(0);
01161     }
01162     break;
01163   case ISD::BIT_CONVERT:
01164     // Basic sanity checking.
01165     assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
01166            && "Cannot BIT_CONVERT between two different types!");
01167     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
01168     if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
01169       return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
01170     if (OpOpcode == ISD::UNDEF)
01171       return getNode(ISD::UNDEF, VT);
01172     break;
01173   case ISD::SCALAR_TO_VECTOR:
01174     assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
01175            MVT::getVectorBaseType(VT) == Operand.getValueType() &&
01176            "Illegal SCALAR_TO_VECTOR node!");
01177     break;
01178   case ISD::FNEG:
01179     if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
01180       return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
01181                      Operand.Val->getOperand(0));
01182     if (OpOpcode == ISD::FNEG)  // --X -> X
01183       return Operand.Val->getOperand(0);
01184     break;
01185   case ISD::FABS:
01186     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
01187       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
01188     break;
01189   }
01190 
01191   SDNode *N;
01192   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
01193     SDNode *&E = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
01194     if (E) return SDOperand(E, 0);
01195     E = N = new SDNode(Opcode, Operand);
01196   } else {
01197     N = new SDNode(Opcode, Operand);
01198   }
01199   N->setValueTypes(VT);
01200   AllNodes.push_back(N);
01201   return SDOperand(N, 0);
01202 }
01203 
01204 
01205 
01206 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
01207                                 SDOperand N1, SDOperand N2) {
01208 #ifndef NDEBUG
01209   switch (Opcode) {
01210   case ISD::TokenFactor:
01211     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
01212            N2.getValueType() == MVT::Other && "Invalid token factor!");
01213     break;
01214   case ISD::AND:
01215   case ISD::OR:
01216   case ISD::XOR:
01217   case ISD::UDIV:
01218   case ISD::UREM:
01219   case ISD::MULHU:
01220   case ISD::MULHS:
01221     assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
01222     // fall through
01223   case ISD::ADD:
01224   case ISD::SUB:
01225   case ISD::MUL:
01226   case ISD::SDIV:
01227   case ISD::SREM:
01228     assert(MVT::isInteger(N1.getValueType()) && "Should use F* for FP ops");
01229     // fall through.
01230   case ISD::FADD:
01231   case ISD::FSUB:
01232   case ISD::FMUL:
01233   case ISD::FDIV:
01234   case ISD::FREM:
01235     assert(N1.getValueType() == N2.getValueType() &&
01236            N1.getValueType() == VT && "Binary operator types must match!");
01237     break;
01238   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
01239     assert(N1.getValueType() == VT &&
01240            MVT::isFloatingPoint(N1.getValueType()) && 
01241            MVT::isFloatingPoint(N2.getValueType()) &&
01242            "Invalid FCOPYSIGN!");
01243     break;
01244   case ISD::SHL:
01245   case ISD::SRA:
01246   case ISD::SRL:
01247   case ISD::ROTL:
01248   case ISD::ROTR:
01249     assert(VT == N1.getValueType() &&
01250            "Shift operators return type must be the same as their first arg");
01251     assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
01252            VT != MVT::i1 && "Shifts only work on integers");
01253     break;
01254   case ISD::FP_ROUND_INREG: {
01255     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
01256     assert(VT == N1.getValueType() && "Not an inreg round!");
01257     assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
01258            "Cannot FP_ROUND_INREG integer types");
01259     assert(EVT <= VT && "Not rounding down!");
01260     break;
01261   }
01262   case ISD::AssertSext:
01263   case ISD::AssertZext:
01264   case ISD::SIGN_EXTEND_INREG: {
01265     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
01266     assert(VT == N1.getValueType() && "Not an inreg extend!");
01267     assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
01268            "Cannot *_EXTEND_INREG FP types");
01269     assert(EVT <= VT && "Not extending!");
01270   }
01271 
01272   default: break;
01273   }
01274 #endif
01275 
01276   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
01277   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
01278   if (N1C) {
01279     if (N2C) {
01280       uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
01281       switch (Opcode) {
01282       case ISD::ADD: return getConstant(C1 + C2, VT);
01283       case ISD::SUB: return getConstant(C1 - C2, VT);
01284       case ISD::MUL: return getConstant(C1 * C2, VT);
01285       case ISD::UDIV:
01286         if (C2) return getConstant(C1 / C2, VT);
01287         break;
01288       case ISD::UREM :
01289         if (C2) return getConstant(C1 % C2, VT);
01290         break;
01291       case ISD::SDIV :
01292         if (C2) return getConstant(N1C->getSignExtended() /
01293                                    N2C->getSignExtended(), VT);
01294         break;
01295       case ISD::SREM :
01296         if (C2) return getConstant(N1C->getSignExtended() %
01297                                    N2C->getSignExtended(), VT);
01298         break;
01299       case ISD::AND  : return getConstant(C1 & C2, VT);
01300       case ISD::OR   : return getConstant(C1 | C2, VT);
01301       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
01302       case ISD::SHL  : return getConstant(C1 << C2, VT);
01303       case ISD::SRL  : return getConstant(C1 >> C2, VT);
01304       case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
01305       case ISD::ROTL : 
01306         return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
01307                            VT);
01308       case ISD::ROTR : 
01309         return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)), 
01310                            VT);
01311       default: break;
01312       }
01313     } else {      // Cannonicalize constant to RHS if commutative
01314       if (isCommutativeBinOp(Opcode)) {
01315         std::swap(N1C, N2C);
01316         std::swap(N1, N2);
01317       }
01318     }
01319   }
01320 
01321   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
01322   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
01323   if (N1CFP) {
01324     if (N2CFP) {
01325       double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
01326       switch (Opcode) {
01327       case ISD::FADD: return getConstantFP(C1 + C2, VT);
01328       case ISD::FSUB: return getConstantFP(C1 - C2, VT);
01329       case ISD::FMUL: return getConstantFP(C1 * C2, VT);
01330       case ISD::FDIV:
01331         if (C2) return getConstantFP(C1 / C2, VT);
01332         break;
01333       case ISD::FREM :
01334         if (C2) return getConstantFP(fmod(C1, C2), VT);
01335         break;
01336       case ISD::FCOPYSIGN: {
01337         union {
01338           double   F;
01339           uint64_t I;
01340         } u1;
01341         union {
01342           double  F;
01343           int64_t I;
01344         } u2;
01345         u1.F = C1;
01346         u2.F = C2;
01347         if (u2.I < 0)  // Sign bit of RHS set?
01348           u1.I |= 1ULL << 63;      // Set the sign bit of the LHS.
01349         else 
01350           u1.I &= (1ULL << 63)-1;  // Clear the sign bit of the LHS.
01351         return getConstantFP(u1.F, VT);
01352       }
01353       default: break;
01354       }
01355     } else {      // Cannonicalize constant to RHS if commutative
01356       if (isCommutativeBinOp(Opcode)) {
01357         std::swap(N1CFP, N2CFP);
01358         std::swap(N1, N2);
01359       }
01360     }
01361   }
01362 
01363   // Finally, fold operations that do not require constants.
01364   switch (Opcode) {
01365   case ISD::FP_ROUND_INREG:
01366     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
01367     break;
01368   case ISD::SIGN_EXTEND_INREG: {
01369     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
01370     if (EVT == VT) return N1;  // Not actually extending
01371     break;
01372   }
01373 
01374   // FIXME: figure out how to safely handle things like
01375   // int foo(int x) { return 1 << (x & 255); }
01376   // int bar() { return foo(256); }
01377 #if 0
01378   case ISD::SHL:
01379   case ISD::SRL:
01380   case ISD::SRA:
01381     if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
01382         cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
01383       return getNode(Opcode, VT, N1, N2.getOperand(0));
01384     else if (N2.getOpcode() == ISD::AND)
01385       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
01386         // If the and is only masking out bits that cannot effect the shift,
01387         // eliminate the and.
01388         unsigned NumBits = MVT::getSizeInBits(VT);
01389         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
01390           return getNode(Opcode, VT, N1, N2.getOperand(0));
01391       }
01392     break;
01393 #endif
01394   }
01395 
01396   // Memoize this node if possible.
01397   SDNode *N;
01398   if (VT != MVT::Flag) {
01399     SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
01400     if (BON) return SDOperand(BON, 0);
01401 
01402     BON = N = new SDNode(Opcode, N1, N2);
01403   } else {
01404     N = new SDNode(Opcode, N1, N2);
01405   }
01406 
01407   N->setValueTypes(VT);
01408   AllNodes.push_back(N);
01409   return SDOperand(N, 0);
01410 }
01411 
01412 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
01413                                 SDOperand N1, SDOperand N2, SDOperand N3) {
01414   // Perform various simplifications.
01415   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
01416   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
01417   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
01418   switch (Opcode) {
01419   case ISD::SETCC: {
01420     // Use SimplifySetCC  to simplify SETCC's.
01421     SDOperand Simp = SimplifySetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
01422     if (Simp.Val) return Simp;
01423     break;
01424   }
01425   case ISD::SELECT:
01426     if (N1C)
01427       if (N1C->getValue())
01428         return N2;             // select true, X, Y -> X
01429       else
01430         return N3;             // select false, X, Y -> Y
01431 
01432     if (N2 == N3) return N2;   // select C, X, X -> X
01433     break;
01434   case ISD::BRCOND:
01435     if (N2C)
01436       if (N2C->getValue()) // Unconditional branch
01437         return getNode(ISD::BR, MVT::Other, N1, N3);
01438       else
01439         return N1;         // Never-taken branch
01440     break;
01441   case ISD::VECTOR_SHUFFLE:
01442     assert(VT == N1.getValueType() && VT == N2.getValueType() &&
01443            MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
01444            N3.getOpcode() == ISD::BUILD_VECTOR &&
01445            MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
01446            "Illegal VECTOR_SHUFFLE node!");
01447     break;
01448   }
01449 
01450   std::vector<SDOperand> Ops;
01451   Ops.reserve(3);
01452   Ops.push_back(N1);
01453   Ops.push_back(N2);
01454   Ops.push_back(N3);
01455 
01456   // Memoize node if it doesn't produce a flag.
01457   SDNode *N;
01458   if (VT != MVT::Flag) {
01459     SDNode *&E = OneResultNodes[std::make_pair(Opcode,std::make_pair(VT, Ops))];
01460     if (E) return SDOperand(E, 0);
01461     E = N = new SDNode(Opcode, N1, N2, N3);
01462   } else {
01463     N = new SDNode(Opcode, N1, N2, N3);
01464   }
01465   N->setValueTypes(VT);
01466   AllNodes.push_back(N);
01467   return SDOperand(N, 0);
01468 }
01469 
01470 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
01471                                 SDOperand N1, SDOperand N2, SDOperand N3,
01472                                 SDOperand N4) {
01473   std::vector<SDOperand> Ops;
01474   Ops.reserve(4);
01475   Ops.push_back(N1);
01476   Ops.push_back(N2);
01477   Ops.push_back(N3);
01478   Ops.push_back(N4);
01479   return getNode(Opcode, VT, Ops);
01480 }
01481 
01482 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
01483                                 SDOperand N1, SDOperand N2, SDOperand N3,
01484                                 SDOperand N4, SDOperand N5) {
01485   std::vector<SDOperand> Ops;
01486   Ops.reserve(5);
01487   Ops.push_back(N1);
01488   Ops.push_back(N2);
01489   Ops.push_back(N3);
01490   Ops.push_back(N4);
01491   Ops.push_back(N5);
01492   return getNode(Opcode, VT, Ops);
01493 }
01494 
01495 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
01496                                 SDOperand Chain, SDOperand Ptr,
01497                                 SDOperand SV) {
01498   SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
01499   if (N) return SDOperand(N, 0);
01500   N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
01501 
01502   // Loads have a token chain.
01503   setNodeValueTypes(N, VT, MVT::Other);
01504   AllNodes.push_back(N);
01505   return SDOperand(N, 0);
01506 }
01507 
01508 SDOperand SelectionDAG::getVecLoad(unsigned Count, MVT::ValueType EVT,
01509                                    SDOperand Chain, SDOperand Ptr,
01510                                    SDOperand SV) {
01511   std::vector<SDOperand> Ops;
01512   Ops.reserve(5);
01513   Ops.push_back(Chain);
01514   Ops.push_back(Ptr);
01515   Ops.push_back(SV);
01516   Ops.push_back(getConstant(Count, MVT::i32));
01517   Ops.push_back(getValueType(EVT));
01518   std::vector<MVT::ValueType> VTs;
01519   VTs.reserve(2);
01520   VTs.push_back(MVT::Vector); VTs.push_back(MVT::Other);  // Add token chain.
01521   return getNode(ISD::VLOAD, VTs, Ops);
01522 }
01523 
01524 SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT,
01525                                    SDOperand Chain, SDOperand Ptr, SDOperand SV,
01526                                    MVT::ValueType EVT) {
01527   std::vector<SDOperand> Ops;
01528   Ops.reserve(4);
01529   Ops.push_back(Chain);
01530   Ops.push_back(Ptr);
01531   Ops.push_back(SV);
01532   Ops.push_back(getValueType(EVT));
01533   std::vector<MVT::ValueType> VTs;
01534   VTs.reserve(2);
01535   VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
01536   return getNode(Opcode, VTs, Ops);
01537 }
01538 
01539 SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
01540   assert((!V || isa<PointerType>(V->getType())) &&
01541          "SrcValue is not a pointer?");
01542   SDNode *&N = ValueNodes[std::make_pair(V, Offset)];
01543   if (N) return SDOperand(N, 0);
01544 
01545   N = new SrcValueSDNode(V, Offset);
01546   AllNodes.push_back(N);
01547   return SDOperand(N, 0);
01548 }
01549 
01550 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
01551                                  SDOperand Chain, SDOperand Ptr,
01552                                  SDOperand SV) {
01553   std::vector<SDOperand> Ops;
01554   Ops.reserve(3);
01555   Ops.push_back(Chain);
01556   Ops.push_back(Ptr);
01557   Ops.push_back(SV);
01558   std::vector<MVT::ValueType> VTs;
01559   VTs.reserve(2);
01560   VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
01561   return getNode(ISD::VAARG, VTs, Ops);
01562 }
01563 
01564 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
01565                                 std::vector<SDOperand> &Ops) {
01566   switch (Ops.size()) {
01567   case 0: return getNode(Opcode, VT);
01568   case 1: return getNode(Opcode, VT, Ops[0]);
01569   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
01570   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
01571   default: break;
01572   }
01573   
01574   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Ops[1].Val);
01575   switch (Opcode) {
01576   default: break;
01577   case ISD::TRUNCSTORE: {
01578     assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
01579     MVT::ValueType EVT = cast<VTSDNode>(Ops[4])->getVT();
01580 #if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
01581     // If this is a truncating store of a constant, convert to the desired type
01582     // and store it instead.
01583     if (isa<Constant>(Ops[0])) {
01584       SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
01585       if (isa<Constant>(Op))
01586         N1 = Op;
01587     }
01588     // Also for ConstantFP?
01589 #endif
01590     if (Ops[0].getValueType() == EVT)       // Normal store?
01591       return getNode(ISD::STORE, VT, Ops[0], Ops[1], Ops[2], Ops[3]);
01592     assert(Ops[1].getValueType() > EVT && "Not a truncation?");
01593     assert(MVT::isInteger(Ops[1].getValueType()) == MVT::isInteger(EVT) &&
01594            "Can't do FP-INT conversion!");
01595     break;
01596   }
01597   case ISD::SELECT_CC: {
01598     assert(Ops.size() == 5 && "SELECT_CC takes 5 operands!");
01599     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
01600            "LHS and RHS of condition must have same type!");
01601     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
01602            "True and False arms of SelectCC must have same type!");
01603     assert(Ops[2].getValueType() == VT &&
01604            "select_cc node must be of same type as true and false value!");
01605     break;
01606   }
01607   case ISD::BR_CC: {
01608     assert(Ops.size() == 5 && "BR_CC takes 5 operands!");
01609     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
01610            "LHS/RHS of comparison should match types!");
01611     break;
01612   }
01613   }
01614 
01615   // Memoize nodes.
01616   SDNode *N;
01617   if (VT != MVT::Flag) {
01618     SDNode *&E =
01619       OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
01620     if (E) return SDOperand(E, 0);
01621     E = N = new SDNode(Opcode, Ops);
01622   } else {
01623     N = new SDNode(Opcode, Ops);
01624   }
01625   N->setValueTypes(VT);
01626   AllNodes.push_back(N);
01627   return SDOperand(N, 0);
01628 }
01629 
01630 SDOperand SelectionDAG::getNode(unsigned Opcode,
01631                                 std::vector<MVT::ValueType> &ResultTys,
01632                                 std::vector<SDOperand> &Ops) {
01633   if (ResultTys.size() == 1)
01634     return getNode(Opcode, ResultTys[0], Ops);
01635 
01636   switch (Opcode) {
01637   case ISD::EXTLOAD:
01638   case ISD::SEXTLOAD:
01639   case ISD::ZEXTLOAD: {
01640     MVT::ValueType EVT = cast<VTSDNode>(Ops[3])->getVT();
01641     assert(Ops.size() == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!");
01642     // If they are asking for an extending load from/to the same thing, return a
01643     // normal load.
01644     if (ResultTys[0] == EVT)
01645       return getLoad(ResultTys[0], Ops[0], Ops[1], Ops[2]);
01646     if (MVT::isVector(ResultTys[0])) {
01647       assert(EVT == MVT::getVectorBaseType(ResultTys[0]) &&
01648              "Invalid vector extload!");
01649     } else {
01650       assert(EVT < ResultTys[0] &&
01651              "Should only be an extending load, not truncating!");
01652     }
01653     assert((Opcode == ISD::EXTLOAD || MVT::isInteger(ResultTys[0])) &&
01654            "Cannot sign/zero extend a FP/Vector load!");
01655     assert(MVT::isInteger(ResultTys[0]) == MVT::isInteger(EVT) &&
01656            "Cannot convert from FP to Int or Int -> FP!");
01657     break;
01658   }
01659 
01660   // FIXME: figure out how to safely handle things like
01661   // int foo(int x) { return 1 << (x & 255); }
01662   // int bar() { return foo(256); }
01663 #if 0
01664   case ISD::SRA_PARTS:
01665   case ISD::SRL_PARTS:
01666   case ISD::SHL_PARTS:
01667     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
01668         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
01669       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
01670     else if (N3.getOpcode() == ISD::AND)
01671       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
01672         // If the and is only masking out bits that cannot effect the shift,
01673         // eliminate the and.
01674         unsigned NumBits = MVT::getSizeInBits(VT)*2;
01675         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
01676           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
01677       }
01678     break;
01679 #endif
01680   }
01681 
01682   // Memoize the node unless it returns a flag.
01683   SDNode *N;
01684   if (ResultTys.back() != MVT::Flag) {
01685     SDNode *&E =
01686       ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys, Ops))];
01687     if (E) return SDOperand(E, 0);
01688     E = N = new SDNode(Opcode, Ops);
01689   } else {
01690     N = new SDNode(Opcode, Ops);
01691   }
01692   setNodeValueTypes(N, ResultTys);
01693   AllNodes.push_back(N);
01694   return SDOperand(N, 0);
01695 }
01696 
01697 void SelectionDAG::setNodeValueTypes(SDNode *N, 
01698                                      std::vector<MVT::ValueType> &RetVals) {
01699   switch (RetVals.size()) {
01700   case 0: return;
01701   case 1: N->setValueTypes(RetVals[0]); return;
01702   case 2: setNodeValueTypes(N, RetVals[0], RetVals[1]); return;
01703   default: break;
01704   }
01705   
01706   std::list<std::vector<MVT::ValueType> >::iterator I =
01707     std::find(VTList.begin(), VTList.end(), RetVals);
01708   if (I == VTList.end()) {
01709     VTList.push_front(RetVals);
01710     I = VTList.begin();
01711   }
01712 
01713   N->setValueTypes(&(*I)[0], I->size());
01714 }
01715 
01716 void SelectionDAG::setNodeValueTypes(SDNode *N, MVT::ValueType VT1, 
01717                                      MVT::ValueType VT2) {
01718   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
01719        E = VTList.end(); I != E; ++I) {
01720     if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2) {
01721       N->setValueTypes(&(*I)[0], 2);
01722       return;
01723     }
01724   }
01725   std::vector<MVT::ValueType> V;
01726   V.push_back(VT1);
01727   V.push_back(VT2);
01728   VTList.push_front(V);
01729   N->setValueTypes(&(*VTList.begin())[0], 2);
01730 }
01731 
01732 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
01733 /// specified operands.  If the resultant node already exists in the DAG,
01734 /// this does not modify the specified node, instead it returns the node that
01735 /// already exists.  If the resultant node does not exist in the DAG, the
01736 /// input node is returned.  As a degenerate case, if you specify the same
01737 /// input operands as the node already has, the input node is returned.
01738 SDOperand SelectionDAG::
01739 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
01740   SDNode *N = InN.Val;
01741   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
01742   
01743   // Check to see if there is no change.
01744   if (Op == N->getOperand(0)) return InN;
01745   
01746   // See if the modified node already exists.
01747   SDNode **NewSlot = FindModifiedNodeSlot(N, Op);
01748   if (NewSlot && *NewSlot)
01749     return SDOperand(*NewSlot, InN.ResNo);
01750   
01751   // Nope it doesn't.  Remove the node from it's current place in the maps.
01752   if (NewSlot)
01753     RemoveNodeFromCSEMaps(N);
01754   
01755   // Now we update the operands.
01756   N->OperandList[0].Val->removeUser(N);
01757   Op.Val->addUser(N);
01758   N->OperandList[0] = Op;
01759   
01760   // If this gets put into a CSE map, add it.
01761   if (NewSlot) *NewSlot = N;
01762   return InN;
01763 }
01764 
01765 SDOperand SelectionDAG::
01766 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
01767   SDNode *N = InN.Val;
01768   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
01769   
01770   // Check to see if there is no change.
01771   bool AnyChange = false;
01772   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
01773     return InN;   // No operands changed, just return the input node.
01774   
01775   // See if the modified node already exists.
01776   SDNode **NewSlot = FindModifiedNodeSlot(N, Op1, Op2);
01777   if (NewSlot && *NewSlot)
01778     return SDOperand(*NewSlot, InN.ResNo);
01779   
01780   // Nope it doesn't.  Remove the node from it's current place in the maps.
01781   if (NewSlot)
01782     RemoveNodeFromCSEMaps(N);
01783   
01784   // Now we update the operands.
01785   if (N->OperandList[0] != Op1) {
01786     N->OperandList[0].Val->removeUser(N);
01787     Op1.Val->addUser(N);
01788     N->OperandList[0] = Op1;
01789   }
01790   if (N->OperandList[1] != Op2) {
01791     N->OperandList[1].Val->removeUser(N);
01792     Op2.Val->addUser(N);
01793     N->OperandList[1] = Op2;
01794   }
01795   
01796   // If this gets put into a CSE map, add it.
01797   if (NewSlot) *NewSlot = N;
01798   return InN;
01799 }
01800 
01801 SDOperand SelectionDAG::
01802 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
01803   std::vector<SDOperand> Ops;
01804   Ops.push_back(Op1);
01805   Ops.push_back(Op2);
01806   Ops.push_back(Op3);
01807   return UpdateNodeOperands(N, Ops);
01808 }
01809 
01810 SDOperand SelectionDAG::
01811 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, 
01812                    SDOperand Op3, SDOperand Op4) {
01813   std::vector<SDOperand> Ops;
01814   Ops.push_back(Op1);
01815   Ops.push_back(Op2);
01816   Ops.push_back(Op3);
01817   Ops.push_back(Op4);
01818   return UpdateNodeOperands(N, Ops);
01819 }
01820 
01821 SDOperand SelectionDAG::
01822 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
01823                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
01824   std::vector<SDOperand> Ops;
01825   Ops.push_back(Op1);
01826   Ops.push_back(Op2);
01827   Ops.push_back(Op3);
01828   Ops.push_back(Op4);
01829   Ops.push_back(Op5);
01830   return UpdateNodeOperands(N, Ops);
01831 }
01832 
01833 
01834 SDOperand SelectionDAG::
01835 UpdateNodeOperands(SDOperand InN, const std::vector<SDOperand> &Ops) {
01836   SDNode *N = InN.Val;
01837   assert(N->getNumOperands() == Ops.size() &&
01838          "Update with wrong number of operands");
01839   
01840   // Check to see if there is no change.
01841   unsigned NumOps = Ops.size();
01842   bool AnyChange = false;
01843   for (unsigned i = 0; i != NumOps; ++i) {
01844     if (Ops[i] != N->getOperand(i)) {
01845       AnyChange = true;
01846       break;
01847     }
01848   }
01849   
01850   // No operands changed, just return the input node.
01851   if (!AnyChange) return InN;
01852   
01853   // See if the modified node already exists.
01854   SDNode **NewSlot = FindModifiedNodeSlot(N, Ops);
01855   if (NewSlot && *NewSlot)
01856     return SDOperand(*NewSlot, InN.ResNo);
01857   
01858   // Nope it doesn't.  Remove the node from it's current place in the maps.
01859   if (NewSlot)
01860     RemoveNodeFromCSEMaps(N);
01861   
01862   // Now we update the operands.
01863   for (unsigned i = 0; i != NumOps; ++i) {
01864     if (N->OperandList[i] != Ops[i]) {
01865       N->OperandList[i].Val->removeUser(N);
01866       Ops[i].Val->addUser(N);
01867       N->OperandList[i] = Ops[i];
01868     }
01869   }
01870 
01871   // If this gets put into a CSE map, add it.
01872   if (NewSlot) *NewSlot = N;
01873   return InN;
01874 }
01875 
01876 
01877 
01878 
01879 /// SelectNodeTo - These are used for target selectors to *mutate* the
01880 /// specified node to have the specified return type, Target opcode, and
01881 /// operands.  Note that target opcodes are stored as
01882 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
01883 ///
01884 /// Note that SelectNodeTo returns the resultant node.  If there is already a
01885 /// node of the specified opcode and operands, it returns that node instead of
01886 /// the current one.
01887 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
01888                                      MVT::ValueType VT) {
01889   // If an identical node already exists, use it.
01890   SDNode *&ON = NullaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, VT)];
01891   if (ON) return SDOperand(ON, 0);
01892   
01893   RemoveNodeFromCSEMaps(N);
01894   
01895   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
01896   N->setValueTypes(VT);
01897 
01898   ON = N;   // Memoize the new node.
01899   return SDOperand(N, 0);
01900 }
01901 
01902 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
01903                                      MVT::ValueType VT, SDOperand Op1) {
01904   // If an identical node already exists, use it.
01905   SDNode *&ON = UnaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
01906                                         std::make_pair(Op1, VT))];
01907   if (ON) return SDOperand(ON, 0);
01908   
01909   RemoveNodeFromCSEMaps(N);
01910   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
01911   N->setValueTypes(VT);
01912   N->setOperands(Op1);
01913   
01914   ON = N;   // Memoize the new node.
01915   return SDOperand(N, 0);
01916 }
01917 
01918 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
01919                                      MVT::ValueType VT, SDOperand Op1,
01920                                      SDOperand Op2) {
01921   // If an identical node already exists, use it.
01922   SDNode *&ON = BinaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
01923                                          std::make_pair(Op1, Op2))];
01924   if (ON) return SDOperand(ON, 0);
01925   
01926   RemoveNodeFromCSEMaps(N);
01927   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
01928   N->setValueTypes(VT);
01929   N->setOperands(Op1, Op2);
01930   
01931   ON = N;   // Memoize the new node.
01932   return SDOperand(N, 0);
01933 }
01934 
01935 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
01936                                      MVT::ValueType VT, SDOperand Op1,
01937                                      SDOperand Op2, SDOperand Op3) {
01938   // If an identical node already exists, use it.
01939   std::vector<SDOperand> OpList;
01940   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
01941   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
01942                                               std::make_pair(VT, OpList))];
01943   if (ON) return SDOperand(ON, 0);
01944   
01945   RemoveNodeFromCSEMaps(N);
01946   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
01947   N->setValueTypes(VT);
01948   N->setOperands(Op1, Op2, Op3);
01949 
01950   ON = N;   // Memoize the new node.
01951   return SDOperand(N, 0);
01952 }
01953 
01954 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
01955                                      MVT::ValueType VT, SDOperand Op1,
01956                                      SDOperand Op2, SDOperand Op3,
01957                                      SDOperand Op4) {
01958   // If an identical node already exists, use it.
01959   std::vector<SDOperand> OpList;
01960   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
01961   OpList.push_back(Op4);
01962   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
01963                                               std::make_pair(VT, OpList))];
01964   if (ON) return SDOperand(ON, 0);
01965   
01966   RemoveNodeFromCSEMaps(N);
01967   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
01968   N->setValueTypes(VT);
01969   N->setOperands(Op1, Op2, Op3, Op4);
01970 
01971   ON = N;   // Memoize the new node.
01972   return SDOperand(N, 0);
01973 }
01974 
01975 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
01976                                      MVT::ValueType VT, SDOperand Op1,
01977                                      SDOperand Op2, SDOperand Op3,SDOperand Op4,
01978                                      SDOperand Op5) {
01979   // If an identical node already exists, use it.
01980   std::vector<SDOperand> OpList;
01981   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
01982   OpList.push_back(Op4); OpList.push_back(Op5);
01983   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
01984                                               std::make_pair(VT, OpList))];
01985   if (ON) return SDOperand(ON, 0);
01986   
01987   RemoveNodeFromCSEMaps(N);
01988   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
01989   N->setValueTypes(VT);
01990   N->setOperands(Op1, Op2, Op3, Op4, Op5);
01991   
01992   ON = N;   // Memoize the new node.
01993   return SDOperand(N, 0);
01994 }
01995 
01996 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
01997                                      MVT::ValueType VT, SDOperand Op1,
01998                                      SDOperand Op2, SDOperand Op3,SDOperand Op4,
01999                                      SDOperand Op5, SDOperand Op6) {
02000   // If an identical node already exists, use it.
02001   std::vector<SDOperand> OpList;
02002   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
02003   OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
02004   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
02005                                               std::make_pair(VT, OpList))];
02006   if (ON) return SDOperand(ON, 0);
02007 
02008   RemoveNodeFromCSEMaps(N);
02009   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
02010   N->setValueTypes(VT);
02011   N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6);
02012   
02013   ON = N;   // Memoize the new node.
02014   return SDOperand(N, 0);
02015 }
02016 
02017 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
02018                                      MVT::ValueType VT, SDOperand Op1,
02019                                      SDOperand Op2, SDOperand Op3,SDOperand Op4,
02020                                      SDOperand Op5, SDOperand Op6,
02021              SDOperand Op7) {
02022   // If an identical node already exists, use it.
02023   std::vector<SDOperand> OpList;
02024   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
02025   OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
02026   OpList.push_back(Op7);
02027   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
02028                                               std::make_pair(VT, OpList))];
02029   if (ON) return SDOperand(ON, 0);
02030 
02031   RemoveNodeFromCSEMaps(N);
02032   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
02033   N->setValueTypes(VT);
02034   N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6, Op7);
02035   
02036   ON = N;   // Memoize the new node.
02037   return SDOperand(N, 0);
02038 }
02039 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
02040                                      MVT::ValueType VT, SDOperand Op1,
02041                                      SDOperand Op2, SDOperand Op3,SDOperand Op4,
02042                                      SDOperand Op5, SDOperand Op6,
02043              SDOperand Op7, SDOperand Op8) {
02044   // If an identical node already exists, use it.
02045   std::vector<SDOperand> OpList;
02046   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
02047   OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
02048   OpList.push_back(Op7); OpList.push_back(Op8);
02049   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
02050                                               std::make_pair(VT, OpList))];
02051   if (ON) return SDOperand(ON, 0);
02052 
02053   RemoveNodeFromCSEMaps(N);
02054   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
02055   N->setValueTypes(VT);
02056   N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6, Op7, Op8);
02057   
02058   ON = N;   // Memoize the new node.
02059   return SDOperand(N, 0);
02060 }
02061 
02062 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
02063                                      MVT::ValueType VT1, MVT::ValueType VT2,
02064                                      SDOperand Op1, SDOperand Op2) {
02065   // If an identical node already exists, use it.
02066   std::vector<SDOperand> OpList;
02067   OpList.push_back(Op1); OpList.push_back(Op2); 
02068   std::vector<MVT::ValueType> VTList;
02069   VTList.push_back(VT1); VTList.push_back(VT2);
02070   SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
02071                                               std::make_pair(VTList, OpList))];
02072   if (ON) return SDOperand(ON, 0);
02073 
02074   RemoveNodeFromCSEMaps(N);
02075   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
02076   setNodeValueTypes(N, VT1, VT2);
02077   N->setOperands(Op1, Op2);
02078   
02079   ON = N;   // Memoize the new node.
02080   return SDOperand(N, 0);
02081 }
02082 
02083 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
02084                                      MVT::ValueType VT1, MVT::ValueType VT2,
02085                                      SDOperand Op1, SDOperand Op2, 
02086                                      SDOperand Op3) {
02087   // If an identical node already exists, use it.
02088   std::vector<SDOperand> OpList;
02089   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
02090   std::vector<MVT::ValueType> VTList;
02091   VTList.push_back(VT1); VTList.push_back(VT2);
02092   SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
02093                                               std::make_pair(VTList, OpList))];
02094   if (ON) return SDOperand(ON, 0);
02095 
02096   RemoveNodeFromCSEMaps(N);
02097   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
02098   setNodeValueTypes(N, VT1, VT2);
02099   N->setOperands(Op1, Op2, Op3);
02100   
02101   ON = N;   // Memoize the new node.
02102   return SDOperand(N, 0);
02103 }
02104 
02105 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
02106                                      MVT::ValueType VT1, MVT::ValueType VT2,
02107                                      SDOperand Op1, SDOperand Op2,
02108                                      SDOperand Op3, SDOperand Op4) {
02109   // If an identical node already exists, use it.
02110   std::vector<SDOperand> OpList;
02111   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
02112   OpList.push_back(Op4);
02113   std::vector<MVT::ValueType> VTList;
02114   VTList.push_back(VT1); VTList.push_back(VT2);
02115   SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
02116                                               std::make_pair(VTList, OpList))];
02117   if (ON) return SDOperand(ON, 0);
02118 
02119   RemoveNodeFromCSEMaps(N);
02120   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
02121   setNodeValueTypes(N, VT1, VT2);
02122   N->setOperands(Op1, Op2, Op3, Op4);
02123 
02124   ON = N;   // Memoize the new node.
02125   return SDOperand(N, 0);
02126 }
02127 
02128 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
02129                                      MVT::ValueType VT1, MVT::ValueType VT2,
02130                                      SDOperand Op1, SDOperand Op2,
02131                                      SDOperand Op3, SDOperand Op4, 
02132                                      SDOperand Op5) {
02133   // If an identical node already exists, use it.
02134   std::vector<SDOperand> OpList;
02135   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
02136   OpList.push_back(Op4); OpList.push_back(Op5);
02137   std::vector<MVT::ValueType> VTList;
02138   VTList.push_back(VT1); VTList.push_back(VT2);
02139   SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
02140                                               std::make_pair(VTList, OpList))];
02141   if (ON) return SDOperand(ON, 0);
02142 
02143   RemoveNodeFromCSEMaps(N);
02144   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
02145   setNodeValueTypes(N, VT1, VT2);
02146   N->setOperands(Op1, Op2, Op3, Op4, Op5);
02147   
02148   ON = N;   // Memoize the new node.
02149   return SDOperand(N, 0);
02150 }
02151 
02152 /// getTargetNode - These are used for target selectors to create a new node
02153 /// with specified return type(s), target opcode, and operands.
02154 ///
02155 /// Note that getTargetNode returns the resultant node.  If there is already a
02156 /// node of the specified opcode and operands, it returns that node instead of
02157 /// the current one.
02158 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
02159   return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
02160 }
02161 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
02162                                     SDOperand Op1) {
02163   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
02164 }
02165 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
02166                                     SDOperand Op1, SDOperand Op2) {
02167   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
02168 }
02169 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
02170                                     SDOperand Op1, SDOperand Op2, SDOperand Op3) {
02171   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
02172 }
02173 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
02174                                     SDOperand Op1, SDOperand Op2, SDOperand Op3,
02175                                     SDOperand Op4) {
02176   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3, Op4).Val;
02177 }
02178 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
02179                                     SDOperand Op1, SDOperand Op2, SDOperand Op3,
02180                                     SDOperand Op4, SDOperand Op5) {
02181   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3, Op4, Op5).Val;
02182 }
02183 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
02184                                     SDOperand Op1, SDOperand Op2, SDOperand Op3,
02185                                     SDOperand Op4, SDOperand Op5, SDOperand Op6) {
02186   std::vector<SDOperand> Ops;
02187   Ops.reserve(6);
02188   Ops.push_back(Op1);
02189   Ops.push_back(Op2);
02190   Ops.push_back(Op3);
02191   Ops.push_back(Op4);
02192   Ops.push_back(Op5);
02193   Ops.push_back(Op6);
02194   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
02195 }
02196 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
02197                                     SDOperand Op1, SDOperand Op2, SDOperand Op3,
02198                                     SDOperand Op4, SDOperand Op5, SDOperand Op6,
02199                                     SDOperand Op7) {
02200   std::vector<SDOperand> Ops;
02201   Ops.reserve(7);
02202   Ops.push_back(Op1);
02203   Ops.push_back(Op2);
02204   Ops.push_back(Op3);
02205   Ops.push_back(Op4);
02206   Ops.push_back(Op5);
02207   Ops.push_back(Op6);
02208   Ops.push_back(Op7);
02209   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
02210 }
02211 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
02212                                     SDOperand Op1, SDOperand Op2, SDOperand Op3,
02213                                     SDOperand Op4, SDOperand Op5, SDOperand Op6,
02214                                     SDOperand Op7, SDOperand Op8) {
02215   std::vector<SDOperand> Ops;
02216   Ops.reserve(8);
02217   Ops.push_back(Op1);
02218   Ops.push_back(Op2);
02219   Ops.push_back(Op3);
02220   Ops.push_back(Op4);
02221   Ops.push_back(Op5);
02222   Ops.push_back(Op6);
02223   Ops.push_back(Op7);
02224   Ops.push_back(Op8);
02225   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
02226 }
02227 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
02228                                     std::vector<SDOperand> &Ops) {
02229   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
02230 }
02231 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02232                                     MVT::ValueType VT2, SDOperand Op1) {
02233   std::vector<MVT::ValueType> ResultTys;
02234   ResultTys.push_back(VT1);
02235   ResultTys.push_back(VT2);
02236   std::vector<SDOperand> Ops;
02237   Ops.push_back(Op1);
02238   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02239 }
02240 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02241                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2) {
02242   std::vector<MVT::ValueType> ResultTys;
02243   ResultTys.push_back(VT1);
02244   ResultTys.push_back(VT2);
02245   std::vector<SDOperand> Ops;
02246   Ops.push_back(Op1);
02247   Ops.push_back(Op2);
02248   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02249 }
02250 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02251                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
02252                                     SDOperand Op3) {
02253   std::vector<MVT::ValueType> ResultTys;
02254   ResultTys.push_back(VT1);
02255   ResultTys.push_back(VT2);
02256   std::vector<SDOperand> Ops;
02257   Ops.push_back(Op1);
02258   Ops.push_back(Op2);
02259   Ops.push_back(Op3);
02260   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02261 }
02262 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02263                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
02264                                     SDOperand Op3, SDOperand Op4) {
02265   std::vector<MVT::ValueType> ResultTys;
02266   ResultTys.push_back(VT1);
02267   ResultTys.push_back(VT2);
02268   std::vector<SDOperand> Ops;
02269   Ops.push_back(Op1);
02270   Ops.push_back(Op2);
02271   Ops.push_back(Op3);
02272   Ops.push_back(Op4);
02273   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02274 }
02275 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02276                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
02277                                     SDOperand Op3, SDOperand Op4, SDOperand Op5) {
02278   std::vector<MVT::ValueType> ResultTys;
02279   ResultTys.push_back(VT1);
02280   ResultTys.push_back(VT2);
02281   std::vector<SDOperand> Ops;
02282   Ops.push_back(Op1);
02283   Ops.push_back(Op2);
02284   Ops.push_back(Op3);
02285   Ops.push_back(Op4);
02286   Ops.push_back(Op5);
02287   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02288 }
02289 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02290                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
02291                                     SDOperand Op3, SDOperand Op4, SDOperand Op5,
02292                                     SDOperand Op6) {
02293   std::vector<MVT::ValueType> ResultTys;
02294   ResultTys.push_back(VT1);
02295   ResultTys.push_back(VT2);
02296   std::vector<SDOperand> Ops;
02297   Ops.push_back(Op1);
02298   Ops.push_back(Op2);
02299   Ops.push_back(Op3);
02300   Ops.push_back(Op4);
02301   Ops.push_back(Op5);
02302   Ops.push_back(Op6);
02303   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02304 }
02305 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02306                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
02307                                     SDOperand Op3, SDOperand Op4, SDOperand Op5,
02308                                     SDOperand Op6, SDOperand Op7) {
02309   std::vector<MVT::ValueType> ResultTys;
02310   ResultTys.push_back(VT1);
02311   ResultTys.push_back(VT2);
02312   std::vector<SDOperand> Ops;
02313   Ops.push_back(Op1);
02314   Ops.push_back(Op2);
02315   Ops.push_back(Op3);
02316   Ops.push_back(Op4);
02317   Ops.push_back(Op5);
02318   Ops.push_back(Op6); 
02319   Ops.push_back(Op7);
02320   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02321 }
02322 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02323                                     MVT::ValueType VT2, MVT::ValueType VT3,
02324                                     SDOperand Op1, SDOperand Op2) {
02325   std::vector<MVT::ValueType> ResultTys;
02326   ResultTys.push_back(VT1);
02327   ResultTys.push_back(VT2);
02328   ResultTys.push_back(VT3);
02329   std::vector<SDOperand> Ops;
02330   Ops.push_back(Op1);
02331   Ops.push_back(Op2);
02332   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02333 }
02334 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02335                                     MVT::ValueType VT2, MVT::ValueType VT3,
02336                                     SDOperand Op1, SDOperand Op2,
02337                                     SDOperand Op3, SDOperand Op4, SDOperand Op5) {
02338   std::vector<MVT::ValueType> ResultTys;
02339   ResultTys.push_back(VT1);
02340   ResultTys.push_back(VT2);
02341   ResultTys.push_back(VT3);
02342   std::vector<SDOperand> Ops;
02343   Ops.push_back(Op1);
02344   Ops.push_back(Op2);
02345   Ops.push_back(Op3);
02346   Ops.push_back(Op4);
02347   Ops.push_back(Op5);
02348   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02349 }
02350 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02351                                     MVT::ValueType VT2, MVT::ValueType VT3,
02352                                     SDOperand Op1, SDOperand Op2,
02353                                     SDOperand Op3, SDOperand Op4, SDOperand Op5,
02354                                     SDOperand Op6) {
02355   std::vector<MVT::ValueType> ResultTys;
02356   ResultTys.push_back(VT1);
02357   ResultTys.push_back(VT2);
02358   ResultTys.push_back(VT3);
02359   std::vector<SDOperand> Ops;
02360   Ops.push_back(Op1);
02361   Ops.push_back(Op2);
02362   Ops.push_back(Op3);
02363   Ops.push_back(Op4);
02364   Ops.push_back(Op5);
02365   Ops.push_back(Op6);
02366   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02367 }
02368 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
02369                                     MVT::ValueType VT2, MVT::ValueType VT3,
02370                                     SDOperand Op1, SDOperand Op2,
02371                                     SDOperand Op3, SDOperand Op4, SDOperand Op5,
02372                                     SDOperand Op6, SDOperand Op7) {
02373   std::vector<MVT::ValueType> ResultTys;
02374   ResultTys.push_back(VT1);
02375   ResultTys.push_back(VT2);
02376   ResultTys.push_back(VT3);
02377   std::vector<SDOperand> Ops;
02378   Ops.push_back(Op1);
02379   Ops.push_back(Op2);
02380   Ops.push_back(Op3);
02381   Ops.push_back(Op4);
02382   Ops.push_back(Op5);
02383   Ops.push_back(Op6);
02384   Ops.push_back(Op7);
02385   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02386 }
02387 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
02388                                     MVT::ValueType VT2, std::vector<SDOperand> &Ops) {
02389   std::vector<MVT::ValueType> ResultTys;
02390   ResultTys.push_back(VT1);
02391   ResultTys.push_back(VT2);
02392   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
02393 }
02394 
02395 // ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
02396 /// This can cause recursive merging of nodes in the DAG.
02397 ///
02398 /// This version assumes From/To have a single result value.
02399 ///
02400 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
02401                                       std::vector<SDNode*> *Deleted) {
02402   SDNode *From = FromN.Val, *To = ToN.Val;
02403   assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
02404          "Cannot replace with this method!");
02405   assert(From != To && "Cannot replace uses of with self");
02406   
02407   while (!From->use_empty()) {
02408     // Process users until they are all gone.
02409     SDNode *U = *From->use_begin();
02410     
02411     // This node is about to morph, remove its old self from the CSE maps.
02412     RemoveNodeFromCSEMaps(U);
02413     
02414     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
02415          I != E; ++I)
02416       if (I->Val == From) {
02417         From->removeUser(U);
02418         I->Val = To;
02419         To->addUser(U);
02420       }
02421 
02422     // Now that we have modified U, add it back to the CSE maps.  If it already
02423     // exists there, recursively merge the results together.
02424     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
02425       ReplaceAllUsesWith(U, Existing, Deleted);
02426       // U is now dead.
02427       if (Deleted) Deleted->push_back(U);
02428       DeleteNodeNotInCSEMaps(U);
02429     }
02430   }
02431 }
02432 
02433 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
02434 /// This can cause recursive merging of nodes in the DAG.
02435 ///
02436 /// This version assumes From/To have matching types and numbers of result
02437 /// values.
02438 ///
02439 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
02440                                       std::vector<SDNode*> *Deleted) {
02441   assert(From != To && "Cannot replace uses of with self");
02442   assert(From->getNumValues() == To->getNumValues() &&
02443          "Cannot use this version of ReplaceAllUsesWith!");
02444   if (From->getNumValues() == 1) {  // If possible, use the faster version.
02445     ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
02446     return;
02447   }
02448   
02449   while (!From->use_empty()) {
02450     // Process users until they are all gone.
02451     SDNode *U = *From->use_begin();
02452     
02453     // This node is about to morph, remove its old self from the CSE maps.
02454     RemoveNodeFromCSEMaps(U);
02455     
02456     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
02457          I != E; ++I)
02458       if (I->Val == From) {
02459         From->removeUser(U);
02460         I->Val = To;
02461         To->addUser(U);
02462       }
02463         
02464     // Now that we have modified U, add it back to the CSE maps.  If it already
02465     // exists there, recursively merge the results together.
02466     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
02467       ReplaceAllUsesWith(U, Existing, Deleted);
02468       // U is now dead.
02469       if (Deleted) Deleted->push_back(U);
02470       DeleteNodeNotInCSEMaps(U);
02471     }
02472   }
02473 }
02474 
02475 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
02476 /// This can cause recursive merging of nodes in the DAG.
02477 ///
02478 /// This version can replace From with any result values.  To must match the
02479 /// number and types of values returned by From.
02480 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
02481                                       const std::vector<SDOperand> &To,
02482                                       std::vector<SDNode*> *Deleted) {
02483   assert(From->getNumValues() == To.size() &&
02484          "Incorrect number of values to replace with!");
02485   if (To.size() == 1 && To[0].Val->getNumValues() == 1) {
02486     // Degenerate case handled above.
02487     ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
02488     return;
02489   }
02490 
02491   while (!From->use_empty()) {
02492     // Process users until they are all gone.
02493     SDNode *U = *From->use_begin();
02494     
02495     // This node is about to morph, remove its old self from the CSE maps.
02496     RemoveNodeFromCSEMaps(U);
02497     
02498     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
02499          I != E; ++I)
02500       if (I->Val == From) {
02501         const SDOperand &ToOp = To[I->ResNo];
02502         From->removeUser(U);
02503         *I = ToOp;
02504         ToOp.Val->addUser(U);
02505       }
02506         
02507     // Now that we have modified U, add it back to the CSE maps.  If it already
02508     // exists there, recursively merge the results together.
02509     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
02510       ReplaceAllUsesWith(U, Existing, Deleted);
02511       // U is now dead.
02512       if (Deleted) Deleted->push_back(U);
02513       DeleteNodeNotInCSEMaps(U);
02514     }
02515   }
02516 }
02517 
02518 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
02519 /// uses of other values produced by From.Val alone.  The Deleted vector is
02520 /// handled the same was as for ReplaceAllUsesWith.
02521 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
02522                                              std::vector<SDNode*> &Deleted) {
02523   assert(From != To && "Cannot replace a value with itself");
02524   // Handle the simple, trivial, case efficiently.
02525   if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
02526     ReplaceAllUsesWith(From, To, &Deleted);
02527     return;
02528   }
02529   
02530   // Get all of the users in a nice, deterministically ordered, uniqued set.
02531   SetVector<SDNode*> Users(From.Val->use_begin(), From.Val->use_end());
02532 
02533   while (!Users.empty()) {
02534     // We know that this user uses some value of From.  If it is the right
02535     // value, update it.
02536     SDNode *User = Users.back();
02537     Users.pop_back();
02538     
02539     for (SDOperand *Op = User->OperandList,
02540          *E = User->OperandList+User->NumOperands; Op != E; ++Op) {
02541       if (*Op == From) {
02542         // Okay, we know this user needs to be updated.  Remove its old self
02543         // from the CSE maps.
02544         RemoveNodeFromCSEMaps(User);
02545         
02546         // Update all operands that match "From".
02547         for (; Op != E; ++Op) {
02548           if (*Op == From) {
02549             From.Val->removeUser(User);
02550             *Op = To;
02551             To.Val->addUser(User);
02552           }
02553         }
02554                    
02555         // Now that we have modified User, add it back to the CSE maps.  If it
02556         // already exists there, recursively merge the results together.
02557         if (SDNode *Existing = AddNonLeafNodeToCSEMaps(User)) {
02558           unsigned NumDeleted = Deleted.size();
02559           ReplaceAllUsesWith(User, Existing, &Deleted);
02560           
02561           // User is now dead.
02562           Deleted.push_back(User);
02563           DeleteNodeNotInCSEMaps(User);
02564           
02565           // We have to be careful here, because ReplaceAllUsesWith could have
02566           // deleted a user of From, which means there may be dangling pointers
02567           // in the "Users" setvector.  Scan over the deleted node pointers and
02568           // remove them from the setvector.
02569           for (unsigned i = NumDeleted, e = Deleted.size(); i != e; ++i)
02570             Users.remove(Deleted[i]);
02571         }
02572         break;   // Exit the operand scanning loop.
02573       }
02574     }
02575   }
02576 }
02577 
02578 
02579 //===----------------------------------------------------------------------===//
02580 //                              SDNode Class
02581 //===----------------------------------------------------------------------===//
02582 
02583 
02584 /// getValueTypeList - Return a pointer to the specified value type.
02585 ///
02586 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
02587   static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
02588   VTs[VT] = VT;
02589   return &VTs[VT];
02590 }
02591 
02592 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
02593 /// indicated value.  This method ignores uses of other values defined by this
02594 /// operation.
02595 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
02596   assert(Value < getNumValues() && "Bad value!");
02597 
02598   // If there is only one value, this is easy.
02599   if (getNumValues() == 1)
02600     return use_size() == NUses;
02601   if (Uses.size() < NUses) return false;
02602 
02603   SDOperand TheValue(const_cast<SDNode *>(this), Value);
02604 
02605   std::set<SDNode*> UsersHandled;
02606 
02607   for (std::vector<SDNode*>::const_iterator UI = Uses.begin(), E = Uses.end();
02608        UI != E; ++UI) {
02609     SDNode *User = *UI;
02610     if (User->getNumOperands() == 1 ||
02611         UsersHandled.insert(User).second)     // First time we've seen this?
02612       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
02613         if (User->getOperand(i) == TheValue) {
02614           if (NUses == 0)
02615             return false;   // too many uses
02616           --NUses;
02617         }
02618   }
02619 
02620   // Found exactly the right number of uses?
02621   return NUses == 0;
02622 }
02623 
02624 
02625 // isOnlyUse - Return true if this node is the only use of N.
02626 bool SDNode::isOnlyUse(SDNode *N) const {
02627   bool Seen = false;
02628   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
02629     SDNode *User = *I;
02630     if (User == this)
02631       Seen = true;
02632     else
02633       return false;
02634   }
02635 
02636   return Seen;
02637 }
02638 
02639 // isOperand - Return true if this node is an operand of N.
02640 bool SDOperand::isOperand(SDNode *N) const {
02641   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
02642     if (*this == N->getOperand(i))
02643       return true;
02644   return false;
02645 }
02646 
02647 bool SDNode::isOperand(SDNode *N) const {
02648   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
02649     if (this == N->OperandList[i].Val)
02650       return true;
02651   return false;
02652 }
02653 
02654 const char *SDNode::getOperationName(const SelectionDAG *G) const {
02655   switch (getOpcode()) {
02656   default:
02657     if (getOpcode() < ISD::BUILTIN_OP_END)
02658       return "<<Unknown DAG Node>>";
02659     else {
02660       if (G) {
02661         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
02662           if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
02663             return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
02664 
02665         TargetLowering &TLI = G->getTargetLoweringInfo();
02666         const char *Name =
02667           TLI.getTargetNodeName(getOpcode());
02668         if (Name) return Name;
02669       }
02670 
02671       return "<<Unknown Target Node>>";
02672     }
02673    
02674   case ISD::PCMARKER:      return "PCMarker";
02675   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
02676   case ISD::SRCVALUE:      return "SrcValue";
02677   case ISD::EntryToken:    return "EntryToken";
02678   case ISD::TokenFactor:   return "TokenFactor";
02679   case ISD::AssertSext:    return "AssertSext";
02680   case ISD::AssertZext:    return "AssertZext";
02681 
02682   case ISD::STRING:        return "String";
02683   case ISD::BasicBlock:    return "BasicBlock";
02684   case ISD::VALUETYPE:     return "ValueType";
02685   case ISD::Register:      return "Register";
02686 
02687   case ISD::Constant:      return "Constant";
02688   case ISD::ConstantFP:    return "ConstantFP";
02689   case ISD::GlobalAddress: return "GlobalAddress";
02690   case ISD::FrameIndex:    return "FrameIndex";
02691   case ISD::ConstantPool:  return "ConstantPool";
02692   case ISD::ExternalSymbol: return "ExternalSymbol";
02693   case ISD::INTRINSIC_WO_CHAIN: {
02694     unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
02695     return Intrinsic::getName((Intrinsic::ID)IID);
02696   }
02697   case ISD::INTRINSIC_VOID:
02698   case ISD::INTRINSIC_W_CHAIN: {
02699     unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
02700     return Intrinsic::getName((Intrinsic::ID)IID);
02701   }
02702 
02703   case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
02704   case ISD::TargetConstant: return "TargetConstant";
02705   case ISD::TargetConstantFP:return "TargetConstantFP";
02706   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
02707   case ISD::TargetFrameIndex: return "TargetFrameIndex";
02708   case ISD::TargetConstantPool:  return "TargetConstantPool";
02709   case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
02710 
02711   case ISD::CopyToReg:     return "CopyToReg";
02712   case ISD::CopyFromReg:   return "CopyFromReg";
02713   case ISD::UNDEF:         return "undef";
02714   case ISD::MERGE_VALUES:  return "mergevalues";
02715   case ISD::INLINEASM:     return "inlineasm";
02716   case ISD::HANDLENODE:    return "handlenode";
02717   case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
02718     
02719   // Unary operators
02720   case ISD::FABS:   return "fabs";
02721   case ISD::FNEG:   return "fneg";
02722   case ISD::FSQRT:  return "fsqrt";
02723   case ISD::FSIN:   return "fsin";
02724   case ISD::FCOS:   return "fcos";
02725 
02726   // Binary operators
02727   case ISD::ADD:    return "add";
02728   case ISD::SUB:    return "sub";
02729   case ISD::MUL:    return "mul";
02730   case ISD::MULHU:  return "mulhu";
02731   case ISD::MULHS:  return "mulhs";
02732   case ISD::SDIV:   return "sdiv";
02733   case ISD::UDIV:   return "udiv";
02734   case ISD::SREM:   return "srem";
02735   case ISD::UREM:   return "urem";
02736   case ISD::AND:    return "and";
02737   case ISD::OR:     return "or";
02738   case ISD::XOR:    return "xor";
02739   case ISD::SHL:    return "shl";
02740   case ISD::SRA:    return "sra";
02741   case ISD::SRL:    return "srl";
02742   case ISD::ROTL:   return "rotl";
02743   case ISD::ROTR:   return "rotr";
02744   case ISD::FADD:   return "fadd";
02745   case ISD::FSUB:   return "fsub";
02746   case ISD::FMUL:   return "fmul";
02747   case ISD::FDIV:   return "fdiv";
02748   case ISD::FREM:   return "frem";
02749   case ISD::FCOPYSIGN: return "fcopysign";
02750   case ISD::VADD:   return "vadd";
02751   case ISD::VSUB:   return "vsub";
02752   case ISD::VMUL:   return "vmul";
02753   case ISD::VSDIV:  return "vsdiv";
02754   case ISD::VUDIV:  return "vudiv";
02755   case ISD::VAND:   return "vand";
02756   case ISD::VOR:    return "vor";
02757   case ISD::VXOR:   return "vxor";
02758 
02759   case ISD::SETCC:       return "setcc";
02760   case ISD::SELECT:      return "select";
02761   case ISD::SELECT_CC:   return "select_cc";
02762   case ISD::VSELECT:     return "vselect";
02763   case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
02764   case ISD::VINSERT_VECTOR_ELT:  return "vinsert_vector_elt";
02765   case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
02766   case ISD::VEXTRACT_VECTOR_ELT: return "vextract_vector_elt";
02767   case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
02768   case ISD::VBUILD_VECTOR:       return "vbuild_vector";
02769   case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
02770   case ISD::VVECTOR_SHUFFLE:     return "vvector_shuffle";
02771   case ISD::VBIT_CONVERT:        return "vbit_convert";
02772   case ISD::ADDC:        return "addc";
02773   case ISD::ADDE:        return "adde";
02774   case ISD::SUBC:        return "subc";
02775   case ISD::SUBE:        return "sube";
02776   case ISD::SHL_PARTS:   return "shl_parts";
02777   case ISD::SRA_PARTS:   return "sra_parts";
02778   case ISD::SRL_PARTS:   return "srl_parts";
02779 
02780   // Conversion operators.
02781   case ISD::SIGN_EXTEND: return "sign_extend";
02782   case ISD::ZERO_EXTEND: return "zero_extend";
02783   case ISD::ANY_EXTEND:  return "any_extend";
02784   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
02785   case ISD::TRUNCATE:    return "truncate";
02786   case ISD::FP_ROUND:    return "fp_round";
02787   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
02788   case ISD::FP_EXTEND:   return "fp_extend";
02789 
02790   case ISD::SINT_TO_FP:  return "sint_to_fp";
02791   case ISD::UINT_TO_FP:  return "uint_to_fp";
02792   case ISD::FP_TO_SINT:  return "fp_to_sint";
02793   case ISD::FP_TO_UINT:  return "fp_to_uint";
02794   case ISD::BIT_CONVERT: return "bit_convert";
02795 
02796     // Control flow instructions
02797   case ISD::BR:      return "br";
02798   case ISD::BRCOND:  return "brcond";
02799   case ISD::BR_CC:   return "br_cc";
02800   case ISD::RET:     return "ret";
02801   case ISD::CALLSEQ_START:  return "callseq_start";
02802   case ISD::CALLSEQ_END:    return "callseq_end";
02803 
02804     // Other operators
02805   case ISD::LOAD:               return "load";
02806   case ISD::STORE:              return "store";
02807   case ISD::VLOAD:              return "vload";
02808   case ISD::EXTLOAD:            return "extload";
02809   case ISD::SEXTLOAD:           return "sextload";
02810   case ISD::ZEXTLOAD:           return "zextload";
02811   case ISD::TRUNCSTORE:         return "truncstore";
02812   case ISD::VAARG:              return "vaarg";
02813   case ISD::VACOPY:             return "vacopy";
02814   case ISD::VAEND:              return "vaend";
02815   case ISD::VASTART:            return "vastart";
02816   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
02817   case ISD::EXTRACT_ELEMENT:    return "extract_element";
02818   case ISD::BUILD_PAIR:         return "build_pair";
02819   case ISD::STACKSAVE:          return "stacksave";
02820   case ISD::STACKRESTORE:       return "stackrestore";
02821     
02822   // Block memory operations.
02823   case ISD::MEMSET:  return "memset";
02824   case ISD::MEMCPY:  return "memcpy";
02825   case ISD::MEMMOVE: return "memmove";
02826 
02827   // Bit manipulation
02828   case ISD::BSWAP:   return "bswap";
02829   case ISD::CTPOP:   return "ctpop";
02830   case ISD::CTTZ:    return "cttz";
02831   case ISD::CTLZ:    return "ctlz";
02832 
02833   // Debug info
02834   case ISD::LOCATION: return "location";
02835   case ISD::DEBUG_LOC: return "debug_loc";
02836   case ISD::DEBUG_LABEL: return "debug_label";
02837 
02838   case ISD::CONDCODE:
02839     switch (cast<CondCodeSDNode>(this)->get()) {
02840     default: assert(0 && "Unknown setcc condition!");
02841     case ISD::SETOEQ:  return "setoeq";
02842     case ISD::SETOGT:  return "setogt";
02843     case ISD::SETOGE:  return "setoge";
02844     case ISD::SETOLT:  return "setolt";
02845     case ISD::SETOLE:  return "setole";
02846     case ISD::SETONE:  return "setone";
02847 
02848     case ISD::SETO:    return "seto";
02849     case ISD::SETUO:   return "setuo";
02850     case ISD::SETUEQ:  return "setue";
02851     case ISD::SETUGT:  return "setugt";
02852     case ISD::SETUGE:  return "setuge";
02853     case ISD::SETULT:  return "setult";
02854     case ISD::SETULE:  return "setule";
02855     case ISD::SETUNE:  return "setune";
02856 
02857     case ISD::SETEQ:   return "seteq";
02858     case ISD::SETGT:   return "setgt";
02859     case ISD::SETGE:   return "setge";
02860     case ISD::SETLT:   return "setlt";
02861     case ISD::SETLE:   return "setle";
02862     case ISD::SETNE:   return "setne";
02863     }
02864   }
02865 }
02866 
02867 void SDNode::dump() const { dump(0); }
02868 void SDNode::dump(const SelectionDAG *G) const {
02869   std::cerr << (void*)this << ": ";
02870 
02871   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
02872     if (i) std::cerr << ",";
02873     if (getValueType(i) == MVT::Other)
02874       std::cerr << "ch";
02875     else
02876       std::cerr << MVT::getValueTypeString(getValueType(i));
02877   }
02878   std::cerr << " = " << getOperationName(G);
02879 
02880   std::cerr << " ";
02881   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
02882     if (i) std::cerr << ", ";
02883     std::cerr << (void*)getOperand(i).Val;
02884     if (unsigned RN = getOperand(i).ResNo)
02885       std::cerr << ":" << RN;
02886   }
02887 
02888   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
02889     std::cerr << "<" << CSDN->getValue() << ">";
02890   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
02891     std::cerr << "<" << CSDN->getValue() << ">";
02892   } else if (const GlobalAddressSDNode *GADN =
02893              dyn_cast<GlobalAddressSDNode>(this)) {
02894     int offset = GADN->getOffset();
02895     std::cerr << "<";
02896     WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
02897     if (offset > 0)
02898       std::cerr << " + " << offset;
02899     else
02900       std::cerr << " " << offset;
02901   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
02902     std::cerr << "<" << FIDN->getIndex() << ">";
02903   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
02904     int offset = CP->getOffset();
02905     std::cerr << "<" << *CP->get() << ">";
02906     if (offset > 0)
02907       std::cerr << " + " << offset;
02908     else
02909       std::cerr << " " << offset;
02910   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
02911     std::cerr << "<";
02912     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
02913     if (LBB)
02914       std::cerr << LBB->getName() << " ";
02915     std::cerr << (const void*)BBDN->getBasicBlock() << ">";
02916   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
02917     if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
02918       std::cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
02919     } else {
02920       std::cerr << " #" << R->getReg();
02921     }
02922   } else if (const ExternalSymbolSDNode *ES =
02923              dyn_cast<ExternalSymbolSDNode>(this)) {
02924     std::cerr << "'" << ES->getSymbol() << "'";
02925   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
02926     if (M->getValue())
02927       std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
02928     else
02929       std::cerr << "<null:" << M->getOffset() << ">";
02930   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
02931     std::cerr << ":" << getValueTypeString(N->getVT());
02932   }
02933 }
02934 
02935 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
02936   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
02937     if (N->getOperand(i).Val->hasOneUse())
02938       DumpNodes(N->getOperand(i).Val, indent+2, G);
02939     else
02940       std::cerr << "\n" << std::string(indent+2, ' ')
02941                 << (void*)N->getOperand(i).Val << ": <multiple use>";
02942 
02943 
02944   std::cerr << "\n" << std::string(indent, ' ');
02945   N->dump(G);
02946 }
02947 
02948 void SelectionDAG::dump() const {
02949   std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
02950   std::vector<const SDNode*> Nodes;
02951   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
02952        I != E; ++I)
02953     Nodes.push_back(I);
02954   
02955   std::sort(Nodes.begin(), Nodes.end());
02956 
02957   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
02958     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
02959       DumpNodes(Nodes[i], 2, this);
02960   }
02961 
02962   DumpNodes(getRoot().Val, 2, this);
02963 
02964   std::cerr << "\n\n";
02965 }
02966 
02967 /// InsertISelMapEntry - A helper function to insert a key / element pair
02968 /// into a SDOperand to SDOperand map. This is added to avoid the map
02969 /// insertion operator from being inlined.
02970 void SelectionDAG::InsertISelMapEntry(std::map<SDOperand, SDOperand> &Map,
02971                                       SDNode *Key, unsigned KeyResNo,
02972                                       SDNode *Element, unsigned ElementResNo) {
02973   Map.insert(std::make_pair(SDOperand(Key, KeyResNo),
02974                             SDOperand(Element, ElementResNo)));
02975 }