CALLSEQ_START/END nodes don't get memoized, do not add them in when
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAG class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/Constants.h"
16 #include "llvm/GlobalValue.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Target/MRegisterInfo.h"
21 #include "llvm/Target/TargetLowering.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include <iostream>
25 #include <set>
26 #include <cmath>
27 #include <algorithm>
28 using namespace llvm;
29
30 static bool isCommutativeBinOp(unsigned Opcode) {
31   switch (Opcode) {
32   case ISD::ADD:
33   case ISD::MUL:
34   case ISD::FADD:
35   case ISD::FMUL:
36   case ISD::AND:
37   case ISD::OR:
38   case ISD::XOR: return true;
39   default: return false; // FIXME: Need commutative info for user ops!
40   }
41 }
42
43 static bool isAssociativeBinOp(unsigned Opcode) {
44   switch (Opcode) {
45   case ISD::ADD:
46   case ISD::MUL:
47   case ISD::AND:
48   case ISD::OR:
49   case ISD::XOR: return true;
50   default: return false; // FIXME: Need associative info for user ops!
51   }
52 }
53
54 // isInvertibleForFree - Return true if there is no cost to emitting the logical
55 // inverse of this node.
56 static bool isInvertibleForFree(SDOperand N) {
57   if (isa<ConstantSDNode>(N.Val)) return true;
58   if (N.Val->getOpcode() == ISD::SETCC && N.Val->hasOneUse())
59     return true;
60   return false;
61 }
62
63 //===----------------------------------------------------------------------===//
64 //                              ConstantFPSDNode Class
65 //===----------------------------------------------------------------------===//
66
67 /// isExactlyValue - We don't rely on operator== working on double values, as
68 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
69 /// As such, this method can be used to do an exact bit-for-bit comparison of
70 /// two floating point values.
71 bool ConstantFPSDNode::isExactlyValue(double V) const {
72   return DoubleToBits(V) == DoubleToBits(Value);
73 }
74
75 //===----------------------------------------------------------------------===//
76 //                              ISD Class
77 //===----------------------------------------------------------------------===//
78
79 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
80 /// when given the operation for (X op Y).
81 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
82   // To perform this operation, we just need to swap the L and G bits of the
83   // operation.
84   unsigned OldL = (Operation >> 2) & 1;
85   unsigned OldG = (Operation >> 1) & 1;
86   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
87                        (OldL << 1) |       // New G bit
88                        (OldG << 2));        // New L bit.
89 }
90
91 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
92 /// 'op' is a valid SetCC operation.
93 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
94   unsigned Operation = Op;
95   if (isInteger)
96     Operation ^= 7;   // Flip L, G, E bits, but not U.
97   else
98     Operation ^= 15;  // Flip all of the condition bits.
99   if (Operation > ISD::SETTRUE2)
100     Operation &= ~8;     // Don't let N and U bits get set.
101   return ISD::CondCode(Operation);
102 }
103
104
105 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
106 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
107 /// if the operation does not depend on the sign of the input (setne and seteq).
108 static int isSignedOp(ISD::CondCode Opcode) {
109   switch (Opcode) {
110   default: assert(0 && "Illegal integer setcc operation!");
111   case ISD::SETEQ:
112   case ISD::SETNE: return 0;
113   case ISD::SETLT:
114   case ISD::SETLE:
115   case ISD::SETGT:
116   case ISD::SETGE: return 1;
117   case ISD::SETULT:
118   case ISD::SETULE:
119   case ISD::SETUGT:
120   case ISD::SETUGE: return 2;
121   }
122 }
123
124 /// getSetCCOrOperation - Return the result of a logical OR between different
125 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
126 /// returns SETCC_INVALID if it is not possible to represent the resultant
127 /// comparison.
128 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
129                                        bool isInteger) {
130   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
131     // Cannot fold a signed integer setcc with an unsigned integer setcc.
132     return ISD::SETCC_INVALID;
133
134   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
135
136   // If the N and U bits get set then the resultant comparison DOES suddenly
137   // care about orderedness, and is true when ordered.
138   if (Op > ISD::SETTRUE2)
139     Op &= ~16;     // Clear the N bit.
140   return ISD::CondCode(Op);
141 }
142
143 /// getSetCCAndOperation - Return the result of a logical AND between different
144 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
145 /// function returns zero if it is not possible to represent the resultant
146 /// comparison.
147 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
148                                         bool isInteger) {
149   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
150     // Cannot fold a signed setcc with an unsigned setcc.
151     return ISD::SETCC_INVALID;
152
153   // Combine all of the condition bits.
154   return ISD::CondCode(Op1 & Op2);
155 }
156
157 const TargetMachine &SelectionDAG::getTarget() const {
158   return TLI.getTargetMachine();
159 }
160
161 //===----------------------------------------------------------------------===//
162 //                              SelectionDAG Class
163 //===----------------------------------------------------------------------===//
164
165 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
166 /// SelectionDAG, including nodes (like loads) that have uses of their token
167 /// chain but no other uses and no side effect.  If a node is passed in as an
168 /// argument, it is used as the seed for node deletion.
169 void SelectionDAG::RemoveDeadNodes(SDNode *N) {
170   // Create a dummy node (which is not added to allnodes), that adds a reference
171   // to the root node, preventing it from being deleted.
172   HandleSDNode Dummy(getRoot());
173
174   bool MadeChange = false;
175   
176   // If we have a hint to start from, use it.
177   if (N && N->use_empty()) {
178     DestroyDeadNode(N);
179     MadeChange = true;
180   }
181
182   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
183     if (I->use_empty() && I->getOpcode() != 65535) {
184       // Node is dead, recursively delete newly dead uses.
185       DestroyDeadNode(I);
186       MadeChange = true;
187     }
188   
189   // Walk the nodes list, removing the nodes we've marked as dead.
190   if (MadeChange) {
191     for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ) {
192       SDNode *N = I++;
193       if (N->use_empty())
194         AllNodes.erase(N);
195     }
196   }
197   
198   // If the root changed (e.g. it was a dead load, update the root).
199   setRoot(Dummy.getValue());
200 }
201
202 /// DestroyDeadNode - We know that N is dead.  Nuke it from the CSE maps for the
203 /// graph.  If it is the last user of any of its operands, recursively process
204 /// them the same way.
205 /// 
206 void SelectionDAG::DestroyDeadNode(SDNode *N) {
207   // Okay, we really are going to delete this node.  First take this out of the
208   // appropriate CSE map.
209   RemoveNodeFromCSEMaps(N);
210   
211   // Next, brutally remove the operand list.  This is safe to do, as there are
212   // no cycles in the graph.
213   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
214     SDNode *O = I->Val;
215     O->removeUser(N);
216     
217     // Now that we removed this operand, see if there are no uses of it left.
218     if (O->use_empty())
219       DestroyDeadNode(O);
220   }
221   delete[] N->OperandList;
222   N->OperandList = 0;
223   N->NumOperands = 0;
224
225   // Mark the node as dead.
226   N->MorphNodeTo(65535);
227 }
228
229 void SelectionDAG::DeleteNode(SDNode *N) {
230   assert(N->use_empty() && "Cannot delete a node that is not dead!");
231
232   // First take this out of the appropriate CSE map.
233   RemoveNodeFromCSEMaps(N);
234
235   // Finally, remove uses due to operands of this node, remove from the 
236   // AllNodes list, and delete the node.
237   DeleteNodeNotInCSEMaps(N);
238 }
239
240 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
241
242   // Remove it from the AllNodes list.
243   AllNodes.remove(N);
244     
245   // Drop all of the operands and decrement used nodes use counts.
246   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
247     I->Val->removeUser(N);
248   delete[] N->OperandList;
249   N->OperandList = 0;
250   N->NumOperands = 0;
251   
252   delete N;
253 }
254
255 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
256 /// correspond to it.  This is useful when we're about to delete or repurpose
257 /// the node.  We don't want future request for structurally identical nodes
258 /// to return N anymore.
259 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
260   bool Erased = false;
261   switch (N->getOpcode()) {
262   case ISD::HANDLENODE: return;  // noop.
263   case ISD::Constant:
264     Erased = Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
265                                             N->getValueType(0)));
266     break;
267   case ISD::TargetConstant:
268     Erased = TargetConstants.erase(std::make_pair(
269                                     cast<ConstantSDNode>(N)->getValue(),
270                                                   N->getValueType(0)));
271     break;
272   case ISD::ConstantFP: {
273     uint64_t V = DoubleToBits(cast<ConstantFPSDNode>(N)->getValue());
274     Erased = ConstantFPs.erase(std::make_pair(V, N->getValueType(0)));
275     break;
276   }
277   case ISD::STRING:
278     Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
279     break;
280   case ISD::CONDCODE:
281     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
282            "Cond code doesn't exist!");
283     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
284     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
285     break;
286   case ISD::GlobalAddress: {
287     GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(N);
288     Erased = GlobalValues.erase(std::make_pair(GN->getGlobal(),
289                                                GN->getOffset()));
290     break;
291   }
292   case ISD::TargetGlobalAddress: {
293     GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(N);
294     Erased =TargetGlobalValues.erase(std::make_pair(GN->getGlobal(),
295                                                     GN->getOffset()));
296     break;
297   }
298   case ISD::FrameIndex:
299     Erased = FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
300     break;
301   case ISD::TargetFrameIndex:
302     Erased = TargetFrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
303     break;
304   case ISD::ConstantPool:
305     Erased = ConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->get());
306     break;
307   case ISD::TargetConstantPool:
308     Erased =TargetConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->get());
309     break;
310   case ISD::BasicBlock:
311     Erased = BBNodes.erase(cast<BasicBlockSDNode>(N)->getBasicBlock());
312     break;
313   case ISD::ExternalSymbol:
314     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
315     break;
316   case ISD::TargetExternalSymbol:
317     Erased = TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
318     break;
319   case ISD::VALUETYPE:
320     Erased = ValueTypeNodes[cast<VTSDNode>(N)->getVT()] != 0;
321     ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
322     break;
323   case ISD::Register:
324     Erased = RegNodes.erase(std::make_pair(cast<RegisterSDNode>(N)->getReg(),
325                                            N->getValueType(0)));
326     break;
327   case ISD::SRCVALUE: {
328     SrcValueSDNode *SVN = cast<SrcValueSDNode>(N);
329     Erased =ValueNodes.erase(std::make_pair(SVN->getValue(), SVN->getOffset()));
330     break;
331   }    
332   case ISD::LOAD:
333     Erased = Loads.erase(std::make_pair(N->getOperand(1),
334                                         std::make_pair(N->getOperand(0),
335                                                        N->getValueType(0))));
336     break;
337   default:
338     if (N->getNumValues() == 1) {
339       if (N->getNumOperands() == 0) {
340         Erased = NullaryOps.erase(std::make_pair(N->getOpcode(),
341                                                  N->getValueType(0)));
342       } else if (N->getNumOperands() == 1) {
343         Erased = 
344           UnaryOps.erase(std::make_pair(N->getOpcode(),
345                                         std::make_pair(N->getOperand(0),
346                                                        N->getValueType(0))));
347       } else if (N->getNumOperands() == 2) {
348         Erased = 
349           BinaryOps.erase(std::make_pair(N->getOpcode(),
350                                          std::make_pair(N->getOperand(0),
351                                                         N->getOperand(1))));
352       } else { 
353         std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
354         Erased = 
355           OneResultNodes.erase(std::make_pair(N->getOpcode(),
356                                               std::make_pair(N->getValueType(0),
357                                                              Ops)));
358       }
359     } else {
360       // Remove the node from the ArbitraryNodes map.
361       std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
362       std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
363       Erased =
364         ArbitraryNodes.erase(std::make_pair(N->getOpcode(),
365                                             std::make_pair(RV, Ops)));
366     }
367     break;
368   }
369 #ifndef NDEBUG
370   // Verify that the node was actually in one of the CSE maps, unless it has a 
371   // flag result (which cannot be CSE'd) or is one of the special cases that are
372   // not subject to CSE.
373   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
374       N->getOpcode() != ISD::CALL && N->getOpcode() != ISD::CALLSEQ_START &&
375       N->getOpcode() != ISD::CALLSEQ_END && !N->isTargetOpcode()) {
376     
377     N->dump();
378     assert(0 && "Node is not in map!");
379   }
380 #endif
381 }
382
383 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
384 /// has been taken out and modified in some way.  If the specified node already
385 /// exists in the CSE maps, do not modify the maps, but return the existing node
386 /// instead.  If it doesn't exist, add it and return null.
387 ///
388 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
389   assert(N->getNumOperands() && "This is a leaf node!");
390   if (N->getOpcode() == ISD::CALLSEQ_START || 
391       N->getOpcode() == ISD::CALLSEQ_END)
392     return 0;
393   
394   if (N->getOpcode() == ISD::LOAD) {
395     SDNode *&L = Loads[std::make_pair(N->getOperand(1),
396                                       std::make_pair(N->getOperand(0),
397                                                      N->getValueType(0)))];
398     if (L) return L;
399     L = N;
400   } else if (N->getOpcode() == ISD::HANDLENODE) {
401     return 0;  // never add it.
402   } else if (N->getNumOperands() == 1) {
403     SDNode *&U = UnaryOps[std::make_pair(N->getOpcode(),
404                                          std::make_pair(N->getOperand(0),
405                                                         N->getValueType(0)))];
406     if (U) return U;
407     U = N;
408   } else if (N->getNumOperands() == 2) {
409     SDNode *&B = BinaryOps[std::make_pair(N->getOpcode(),
410                                           std::make_pair(N->getOperand(0),
411                                                          N->getOperand(1)))];
412     if (B) return B;
413     B = N;
414   } else if (N->getNumValues() == 1) {
415     std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
416     SDNode *&ORN = OneResultNodes[std::make_pair(N->getOpcode(),
417                                   std::make_pair(N->getValueType(0), Ops))];
418     if (ORN) return ORN;
419     ORN = N;
420   } else {
421     // Remove the node from the ArbitraryNodes map.
422     std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
423     std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
424     SDNode *&AN = ArbitraryNodes[std::make_pair(N->getOpcode(),
425                                                 std::make_pair(RV, Ops))];
426     if (AN) return AN;
427     AN = N;
428   }
429   return 0;
430 }
431
432
433
434 SelectionDAG::~SelectionDAG() {
435   while (!AllNodes.empty()) {
436     SDNode *N = AllNodes.begin();
437     delete [] N->OperandList;
438     N->OperandList = 0;
439     N->NumOperands = 0;
440     AllNodes.pop_front();
441   }
442 }
443
444 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
445   if (Op.getValueType() == VT) return Op;
446   int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
447   return getNode(ISD::AND, Op.getValueType(), Op,
448                  getConstant(Imm, Op.getValueType()));
449 }
450
451 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
452   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
453   // Mask out any bits that are not valid for this constant.
454   if (VT != MVT::i64)
455     Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
456
457   SDNode *&N = Constants[std::make_pair(Val, VT)];
458   if (N) return SDOperand(N, 0);
459   N = new ConstantSDNode(false, Val, VT);
460   AllNodes.push_back(N);
461   return SDOperand(N, 0);
462 }
463
464 SDOperand SelectionDAG::getString(const std::string &Val) {
465   StringSDNode *&N = StringNodes[Val];
466   if (!N) {
467     N = new StringSDNode(Val);
468     AllNodes.push_back(N);
469   }
470   return SDOperand(N, 0);
471 }
472
473 SDOperand SelectionDAG::getTargetConstant(uint64_t Val, MVT::ValueType VT) {
474   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
475   // Mask out any bits that are not valid for this constant.
476   if (VT != MVT::i64)
477     Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
478   
479   SDNode *&N = TargetConstants[std::make_pair(Val, VT)];
480   if (N) return SDOperand(N, 0);
481   N = new ConstantSDNode(true, Val, VT);
482   AllNodes.push_back(N);
483   return SDOperand(N, 0);
484 }
485
486 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
487   assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
488   if (VT == MVT::f32)
489     Val = (float)Val;  // Mask out extra precision.
490
491   // Do the map lookup using the actual bit pattern for the floating point
492   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
493   // we don't have issues with SNANs.
494   SDNode *&N = ConstantFPs[std::make_pair(DoubleToBits(Val), VT)];
495   if (N) return SDOperand(N, 0);
496   N = new ConstantFPSDNode(Val, VT);
497   AllNodes.push_back(N);
498   return SDOperand(N, 0);
499 }
500
501
502
503 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
504                                          MVT::ValueType VT, int offset) {
505   SDNode *&N = GlobalValues[std::make_pair(GV, offset)];
506   if (N) return SDOperand(N, 0);
507   N = new GlobalAddressSDNode(false, GV, VT);
508   AllNodes.push_back(N);
509   return SDOperand(N, 0);
510 }
511
512 SDOperand SelectionDAG::getTargetGlobalAddress(const GlobalValue *GV,
513                                                MVT::ValueType VT, int offset) {
514   SDNode *&N = TargetGlobalValues[std::make_pair(GV, offset)];
515   if (N) return SDOperand(N, 0);
516   N = new GlobalAddressSDNode(true, GV, VT, offset);
517   AllNodes.push_back(N);
518   return SDOperand(N, 0);
519 }
520
521 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
522   SDNode *&N = FrameIndices[FI];
523   if (N) return SDOperand(N, 0);
524   N = new FrameIndexSDNode(FI, VT, false);
525   AllNodes.push_back(N);
526   return SDOperand(N, 0);
527 }
528
529 SDOperand SelectionDAG::getTargetFrameIndex(int FI, MVT::ValueType VT) {
530   SDNode *&N = TargetFrameIndices[FI];
531   if (N) return SDOperand(N, 0);
532   N = new FrameIndexSDNode(FI, VT, true);
533   AllNodes.push_back(N);
534   return SDOperand(N, 0);
535 }
536
537 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT) {
538   SDNode *&N = ConstantPoolIndices[C];
539   if (N) return SDOperand(N, 0);
540   N = new ConstantPoolSDNode(C, VT, false);
541   AllNodes.push_back(N);
542   return SDOperand(N, 0);
543 }
544
545 SDOperand SelectionDAG::getTargetConstantPool(Constant *C, MVT::ValueType VT) {
546   SDNode *&N = TargetConstantPoolIndices[C];
547   if (N) return SDOperand(N, 0);
548   N = new ConstantPoolSDNode(C, VT, true);
549   AllNodes.push_back(N);
550   return SDOperand(N, 0);
551 }
552
553 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
554   SDNode *&N = BBNodes[MBB];
555   if (N) return SDOperand(N, 0);
556   N = new BasicBlockSDNode(MBB);
557   AllNodes.push_back(N);
558   return SDOperand(N, 0);
559 }
560
561 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
562   if ((unsigned)VT >= ValueTypeNodes.size())
563     ValueTypeNodes.resize(VT+1);
564   if (ValueTypeNodes[VT] == 0) {
565     ValueTypeNodes[VT] = new VTSDNode(VT);
566     AllNodes.push_back(ValueTypeNodes[VT]);
567   }
568
569   return SDOperand(ValueTypeNodes[VT], 0);
570 }
571
572 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
573   SDNode *&N = ExternalSymbols[Sym];
574   if (N) return SDOperand(N, 0);
575   N = new ExternalSymbolSDNode(false, Sym, VT);
576   AllNodes.push_back(N);
577   return SDOperand(N, 0);
578 }
579
580 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT::ValueType VT) {
581   SDNode *&N = TargetExternalSymbols[Sym];
582   if (N) return SDOperand(N, 0);
583   N = new ExternalSymbolSDNode(true, Sym, VT);
584   AllNodes.push_back(N);
585   return SDOperand(N, 0);
586 }
587
588 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
589   if ((unsigned)Cond >= CondCodeNodes.size())
590     CondCodeNodes.resize(Cond+1);
591   
592   if (CondCodeNodes[Cond] == 0) {
593     CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
594     AllNodes.push_back(CondCodeNodes[Cond]);
595   }
596   return SDOperand(CondCodeNodes[Cond], 0);
597 }
598
599 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
600   RegisterSDNode *&Reg = RegNodes[std::make_pair(RegNo, VT)];
601   if (!Reg) {
602     Reg = new RegisterSDNode(RegNo, VT);
603     AllNodes.push_back(Reg);
604   }
605   return SDOperand(Reg, 0);
606 }
607
608 SDOperand SelectionDAG::SimplifySetCC(MVT::ValueType VT, SDOperand N1,
609                                       SDOperand N2, ISD::CondCode Cond) {
610   // These setcc operations always fold.
611   switch (Cond) {
612   default: break;
613   case ISD::SETFALSE:
614   case ISD::SETFALSE2: return getConstant(0, VT);
615   case ISD::SETTRUE:
616   case ISD::SETTRUE2:  return getConstant(1, VT);
617   }
618
619   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
620     uint64_t C2 = N2C->getValue();
621     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
622       uint64_t C1 = N1C->getValue();
623
624       // Sign extend the operands if required
625       if (ISD::isSignedIntSetCC(Cond)) {
626         C1 = N1C->getSignExtended();
627         C2 = N2C->getSignExtended();
628       }
629
630       switch (Cond) {
631       default: assert(0 && "Unknown integer setcc!");
632       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
633       case ISD::SETNE:  return getConstant(C1 != C2, VT);
634       case ISD::SETULT: return getConstant(C1 <  C2, VT);
635       case ISD::SETUGT: return getConstant(C1 >  C2, VT);
636       case ISD::SETULE: return getConstant(C1 <= C2, VT);
637       case ISD::SETUGE: return getConstant(C1 >= C2, VT);
638       case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
639       case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
640       case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
641       case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
642       }
643     } else {
644       // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
645       if (N1.getOpcode() == ISD::ZERO_EXTEND) {
646         unsigned InSize = MVT::getSizeInBits(N1.getOperand(0).getValueType());
647
648         // If the comparison constant has bits in the upper part, the
649         // zero-extended value could never match.
650         if (C2 & (~0ULL << InSize)) {
651           unsigned VSize = MVT::getSizeInBits(N1.getValueType());
652           switch (Cond) {
653           case ISD::SETUGT:
654           case ISD::SETUGE:
655           case ISD::SETEQ: return getConstant(0, VT);
656           case ISD::SETULT:
657           case ISD::SETULE:
658           case ISD::SETNE: return getConstant(1, VT);
659           case ISD::SETGT:
660           case ISD::SETGE:
661             // True if the sign bit of C2 is set.
662             return getConstant((C2 & (1ULL << VSize)) != 0, VT);
663           case ISD::SETLT:
664           case ISD::SETLE:
665             // True if the sign bit of C2 isn't set.
666             return getConstant((C2 & (1ULL << VSize)) == 0, VT);
667           default:
668             break;
669           }
670         }
671
672         // Otherwise, we can perform the comparison with the low bits.
673         switch (Cond) {
674         case ISD::SETEQ:
675         case ISD::SETNE:
676         case ISD::SETUGT:
677         case ISD::SETUGE:
678         case ISD::SETULT:
679         case ISD::SETULE:
680           return getSetCC(VT, N1.getOperand(0),
681                           getConstant(C2, N1.getOperand(0).getValueType()),
682                           Cond);
683         default:
684           break;   // todo, be more careful with signed comparisons
685         }
686       } else if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
687                  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
688         MVT::ValueType ExtSrcTy = cast<VTSDNode>(N1.getOperand(1))->getVT();
689         unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
690         MVT::ValueType ExtDstTy = N1.getValueType();
691         unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
692
693         // If the extended part has any inconsistent bits, it cannot ever
694         // compare equal.  In other words, they have to be all ones or all
695         // zeros.
696         uint64_t ExtBits =
697           (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
698         if ((C2 & ExtBits) != 0 && (C2 & ExtBits) != ExtBits)
699           return getConstant(Cond == ISD::SETNE, VT);
700         
701         // Otherwise, make this a use of a zext.
702         return getSetCC(VT, getZeroExtendInReg(N1.getOperand(0), ExtSrcTy),
703                         getConstant(C2 & (~0ULL>>(64-ExtSrcTyBits)), ExtDstTy),
704                         Cond);
705       }
706
707       uint64_t MinVal, MaxVal;
708       unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
709       if (ISD::isSignedIntSetCC(Cond)) {
710         MinVal = 1ULL << (OperandBitSize-1);
711         if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
712           MaxVal = ~0ULL >> (65-OperandBitSize);
713         else
714           MaxVal = 0;
715       } else {
716         MinVal = 0;
717         MaxVal = ~0ULL >> (64-OperandBitSize);
718       }
719
720       // Canonicalize GE/LE comparisons to use GT/LT comparisons.
721       if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
722         if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
723         --C2;                                          // X >= C1 --> X > (C1-1)
724         return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
725                         (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
726       }
727
728       if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
729         if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
730         ++C2;                                          // X <= C1 --> X < (C1+1)
731         return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
732                         (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
733       }
734
735       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
736         return getConstant(0, VT);      // X < MIN --> false
737
738       // Canonicalize setgt X, Min --> setne X, Min
739       if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
740         return getSetCC(VT, N1, N2, ISD::SETNE);
741
742       // If we have setult X, 1, turn it into seteq X, 0
743       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
744         return getSetCC(VT, N1, getConstant(MinVal, N1.getValueType()),
745                         ISD::SETEQ);
746       // If we have setugt X, Max-1, turn it into seteq X, Max
747       else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
748         return getSetCC(VT, N1, getConstant(MaxVal, N1.getValueType()),
749                         ISD::SETEQ);
750
751       // If we have "setcc X, C1", check to see if we can shrink the immediate
752       // by changing cc.
753
754       // SETUGT X, SINTMAX  -> SETLT X, 0
755       if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
756           C2 == (~0ULL >> (65-OperandBitSize)))
757         return getSetCC(VT, N1, getConstant(0, N2.getValueType()), ISD::SETLT);
758
759       // FIXME: Implement the rest of these.
760
761
762       // Fold bit comparisons when we can.
763       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
764           VT == N1.getValueType() && N1.getOpcode() == ISD::AND)
765         if (ConstantSDNode *AndRHS =
766                     dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
767           if (Cond == ISD::SETNE && C2 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
768             // Perform the xform if the AND RHS is a single bit.
769             if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
770               return getNode(ISD::SRL, VT, N1,
771                              getConstant(Log2_64(AndRHS->getValue()),
772                                                    TLI.getShiftAmountTy()));
773             }
774           } else if (Cond == ISD::SETEQ && C2 == AndRHS->getValue()) {
775             // (X & 8) == 8  -->  (X & 8) >> 3
776             // Perform the xform if C2 is a single bit.
777             if ((C2 & (C2-1)) == 0) {
778               return getNode(ISD::SRL, VT, N1,
779                              getConstant(Log2_64(C2),TLI.getShiftAmountTy()));
780             }
781           }
782         }
783     }
784   } else if (isa<ConstantSDNode>(N1.Val)) {
785       // Ensure that the constant occurs on the RHS.
786     return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
787   }
788
789   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
790     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
791       double C1 = N1C->getValue(), C2 = N2C->getValue();
792
793       switch (Cond) {
794       default: break; // FIXME: Implement the rest of these!
795       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
796       case ISD::SETNE:  return getConstant(C1 != C2, VT);
797       case ISD::SETLT:  return getConstant(C1 < C2, VT);
798       case ISD::SETGT:  return getConstant(C1 > C2, VT);
799       case ISD::SETLE:  return getConstant(C1 <= C2, VT);
800       case ISD::SETGE:  return getConstant(C1 >= C2, VT);
801       }
802     } else {
803       // Ensure that the constant occurs on the RHS.
804       return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
805     }
806
807   // Could not fold it.
808   return SDOperand();
809 }
810
811 /// getNode - Gets or creates the specified node.
812 ///
813 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
814   SDNode *&N = NullaryOps[std::make_pair(Opcode, VT)];
815   if (!N) {
816     N = new SDNode(Opcode, VT);
817     AllNodes.push_back(N);
818   }
819   return SDOperand(N, 0);
820 }
821
822 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
823                                 SDOperand Operand) {
824   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
825     uint64_t Val = C->getValue();
826     switch (Opcode) {
827     default: break;
828     case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
829     case ISD::ANY_EXTEND:
830     case ISD::ZERO_EXTEND: return getConstant(Val, VT);
831     case ISD::TRUNCATE:    return getConstant(Val, VT);
832     case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
833     case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
834     }
835   }
836
837   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
838     switch (Opcode) {
839     case ISD::FNEG:
840       return getConstantFP(-C->getValue(), VT);
841     case ISD::FP_ROUND:
842     case ISD::FP_EXTEND:
843       return getConstantFP(C->getValue(), VT);
844     case ISD::FP_TO_SINT:
845       return getConstant((int64_t)C->getValue(), VT);
846     case ISD::FP_TO_UINT:
847       return getConstant((uint64_t)C->getValue(), VT);
848     }
849
850   unsigned OpOpcode = Operand.Val->getOpcode();
851   switch (Opcode) {
852   case ISD::TokenFactor:
853     return Operand;         // Factor of one node?  No factor.
854   case ISD::SIGN_EXTEND:
855     if (Operand.getValueType() == VT) return Operand;   // noop extension
856     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
857       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
858     break;
859   case ISD::ZERO_EXTEND:
860     if (Operand.getValueType() == VT) return Operand;   // noop extension
861     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
862       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
863     break;
864   case ISD::ANY_EXTEND:
865     if (Operand.getValueType() == VT) return Operand;   // noop extension
866     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
867       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
868       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
869     break;
870   case ISD::TRUNCATE:
871     if (Operand.getValueType() == VT) return Operand;   // noop truncate
872     if (OpOpcode == ISD::TRUNCATE)
873       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
874     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
875              OpOpcode == ISD::ANY_EXTEND) {
876       // If the source is smaller than the dest, we still need an extend.
877       if (Operand.Val->getOperand(0).getValueType() < VT)
878         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
879       else if (Operand.Val->getOperand(0).getValueType() > VT)
880         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
881       else
882         return Operand.Val->getOperand(0);
883     }
884     break;
885   case ISD::FNEG:
886     if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
887       return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
888                      Operand.Val->getOperand(0));
889     if (OpOpcode == ISD::FNEG)  // --X -> X
890       return Operand.Val->getOperand(0);
891     break;
892   case ISD::FABS:
893     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
894       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
895     break;
896   }
897
898   SDNode *N;
899   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
900     SDNode *&E = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
901     if (E) return SDOperand(E, 0);
902     E = N = new SDNode(Opcode, Operand);
903   } else {
904     N = new SDNode(Opcode, Operand);
905   }
906   N->setValueTypes(VT);
907   AllNodes.push_back(N);
908   return SDOperand(N, 0);
909 }
910
911
912
913 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
914                                 SDOperand N1, SDOperand N2) {
915 #ifndef NDEBUG
916   switch (Opcode) {
917   case ISD::TokenFactor:
918     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
919            N2.getValueType() == MVT::Other && "Invalid token factor!");
920     break;
921   case ISD::AND:
922   case ISD::OR:
923   case ISD::XOR:
924   case ISD::UDIV:
925   case ISD::UREM:
926   case ISD::MULHU:
927   case ISD::MULHS:
928     assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
929     // fall through
930   case ISD::ADD:
931   case ISD::SUB:
932   case ISD::MUL:
933   case ISD::SDIV:
934   case ISD::SREM:
935     assert(MVT::isInteger(N1.getValueType()) && "Should use F* for FP ops");
936     // fall through.
937   case ISD::FADD:
938   case ISD::FSUB:
939   case ISD::FMUL:
940   case ISD::FDIV:
941   case ISD::FREM:
942     assert(N1.getValueType() == N2.getValueType() &&
943            N1.getValueType() == VT && "Binary operator types must match!");
944     break;
945
946   case ISD::SHL:
947   case ISD::SRA:
948   case ISD::SRL:
949     assert(VT == N1.getValueType() &&
950            "Shift operators return type must be the same as their first arg");
951     assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
952            VT != MVT::i1 && "Shifts only work on integers");
953     break;
954   case ISD::FP_ROUND_INREG: {
955     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
956     assert(VT == N1.getValueType() && "Not an inreg round!");
957     assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
958            "Cannot FP_ROUND_INREG integer types");
959     assert(EVT <= VT && "Not rounding down!");
960     break;
961   }
962   case ISD::AssertSext:
963   case ISD::AssertZext:
964   case ISD::SIGN_EXTEND_INREG: {
965     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
966     assert(VT == N1.getValueType() && "Not an inreg extend!");
967     assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
968            "Cannot *_EXTEND_INREG FP types");
969     assert(EVT <= VT && "Not extending!");
970   }
971
972   default: break;
973   }
974 #endif
975
976   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
977   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
978   if (N1C) {
979     if (N2C) {
980       uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
981       switch (Opcode) {
982       case ISD::ADD: return getConstant(C1 + C2, VT);
983       case ISD::SUB: return getConstant(C1 - C2, VT);
984       case ISD::MUL: return getConstant(C1 * C2, VT);
985       case ISD::UDIV:
986         if (C2) return getConstant(C1 / C2, VT);
987         break;
988       case ISD::UREM :
989         if (C2) return getConstant(C1 % C2, VT);
990         break;
991       case ISD::SDIV :
992         if (C2) return getConstant(N1C->getSignExtended() /
993                                    N2C->getSignExtended(), VT);
994         break;
995       case ISD::SREM :
996         if (C2) return getConstant(N1C->getSignExtended() %
997                                    N2C->getSignExtended(), VT);
998         break;
999       case ISD::AND  : return getConstant(C1 & C2, VT);
1000       case ISD::OR   : return getConstant(C1 | C2, VT);
1001       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
1002       case ISD::SHL  : return getConstant(C1 << C2, VT);
1003       case ISD::SRL  : return getConstant(C1 >> C2, VT);
1004       case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
1005       default: break;
1006       }
1007     } else {      // Cannonicalize constant to RHS if commutative
1008       if (isCommutativeBinOp(Opcode)) {
1009         std::swap(N1C, N2C);
1010         std::swap(N1, N2);
1011       }
1012     }
1013   }
1014
1015   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1016   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1017   if (N1CFP) {
1018     if (N2CFP) {
1019       double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1020       switch (Opcode) {
1021       case ISD::FADD: return getConstantFP(C1 + C2, VT);
1022       case ISD::FSUB: return getConstantFP(C1 - C2, VT);
1023       case ISD::FMUL: return getConstantFP(C1 * C2, VT);
1024       case ISD::FDIV:
1025         if (C2) return getConstantFP(C1 / C2, VT);
1026         break;
1027       case ISD::FREM :
1028         if (C2) return getConstantFP(fmod(C1, C2), VT);
1029         break;
1030       default: break;
1031       }
1032     } else {      // Cannonicalize constant to RHS if commutative
1033       if (isCommutativeBinOp(Opcode)) {
1034         std::swap(N1CFP, N2CFP);
1035         std::swap(N1, N2);
1036       }
1037     }
1038   }
1039
1040   // Finally, fold operations that do not require constants.
1041   switch (Opcode) {
1042   case ISD::FP_ROUND_INREG:
1043     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
1044     break;
1045   case ISD::SIGN_EXTEND_INREG: {
1046     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1047     if (EVT == VT) return N1;  // Not actually extending
1048     break;
1049   }
1050
1051   // FIXME: figure out how to safely handle things like
1052   // int foo(int x) { return 1 << (x & 255); }
1053   // int bar() { return foo(256); }
1054 #if 0
1055   case ISD::SHL:
1056   case ISD::SRL:
1057   case ISD::SRA:
1058     if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1059         cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
1060       return getNode(Opcode, VT, N1, N2.getOperand(0));
1061     else if (N2.getOpcode() == ISD::AND)
1062       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1063         // If the and is only masking out bits that cannot effect the shift,
1064         // eliminate the and.
1065         unsigned NumBits = MVT::getSizeInBits(VT);
1066         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1067           return getNode(Opcode, VT, N1, N2.getOperand(0));
1068       }
1069     break;
1070 #endif
1071   }
1072
1073   // Memoize this node if possible.
1074   SDNode *N;
1075   if (Opcode != ISD::CALLSEQ_START && Opcode != ISD::CALLSEQ_END &&
1076       VT != MVT::Flag) {
1077     SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
1078     if (BON) return SDOperand(BON, 0);
1079
1080     BON = N = new SDNode(Opcode, N1, N2);
1081   } else {
1082     N = new SDNode(Opcode, N1, N2);
1083   }
1084
1085   N->setValueTypes(VT);
1086   AllNodes.push_back(N);
1087   return SDOperand(N, 0);
1088 }
1089
1090 // setAdjCallChain - This method changes the token chain of an
1091 // CALLSEQ_START/END node to be the specified operand.
1092 void SDNode::setAdjCallChain(SDOperand N) {
1093   assert(N.getValueType() == MVT::Other);
1094   assert((getOpcode() == ISD::CALLSEQ_START ||
1095           getOpcode() == ISD::CALLSEQ_END) && "Cannot adjust this node!");
1096
1097   OperandList[0].Val->removeUser(this);
1098   OperandList[0] = N;
1099   OperandList[0].Val->Uses.push_back(this);
1100 }
1101
1102
1103
1104 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1105                                 SDOperand Chain, SDOperand Ptr,
1106                                 SDOperand SV) {
1107   SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
1108   if (N) return SDOperand(N, 0);
1109   N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
1110
1111   // Loads have a token chain.
1112   setNodeValueTypes(N, VT, MVT::Other);
1113   AllNodes.push_back(N);
1114   return SDOperand(N, 0);
1115 }
1116
1117 SDOperand SelectionDAG::getVecLoad(unsigned Count, MVT::ValueType EVT,
1118                                    SDOperand Chain, SDOperand Ptr,
1119                                    SDOperand SV) {
1120   SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, EVT))];
1121   if (N) return SDOperand(N, 0);
1122   std::vector<SDOperand> Ops;
1123   Ops.reserve(5);
1124   Ops.push_back(Chain);
1125   Ops.push_back(Ptr);
1126   Ops.push_back(getConstant(Count, MVT::i32));
1127   Ops.push_back(getValueType(EVT));
1128   Ops.push_back(SV);
1129   std::vector<MVT::ValueType> VTs;
1130   VTs.reserve(2);
1131   VTs.push_back(MVT::Vector); VTs.push_back(MVT::Other);  // Add token chain.
1132   return getNode(ISD::VLOAD, VTs, Ops);
1133 }
1134
1135 SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT,
1136                                    SDOperand Chain, SDOperand Ptr, SDOperand SV,
1137                                    MVT::ValueType EVT) {
1138   std::vector<SDOperand> Ops;
1139   Ops.reserve(4);
1140   Ops.push_back(Chain);
1141   Ops.push_back(Ptr);
1142   Ops.push_back(SV);
1143   Ops.push_back(getValueType(EVT));
1144   std::vector<MVT::ValueType> VTs;
1145   VTs.reserve(2);
1146   VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1147   return getNode(Opcode, VTs, Ops);
1148 }
1149
1150 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1151                                 SDOperand N1, SDOperand N2, SDOperand N3) {
1152   // Perform various simplifications.
1153   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1154   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1155   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1156   switch (Opcode) {
1157   case ISD::SETCC: {
1158     // Use SimplifySetCC  to simplify SETCC's.
1159     SDOperand Simp = SimplifySetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
1160     if (Simp.Val) return Simp;
1161     break;
1162   }
1163   case ISD::SELECT:
1164     if (N1C)
1165       if (N1C->getValue())
1166         return N2;             // select true, X, Y -> X
1167       else
1168         return N3;             // select false, X, Y -> Y
1169
1170     if (N2 == N3) return N2;   // select C, X, X -> X
1171     break;
1172   case ISD::BRCOND:
1173     if (N2C)
1174       if (N2C->getValue()) // Unconditional branch
1175         return getNode(ISD::BR, MVT::Other, N1, N3);
1176       else
1177         return N1;         // Never-taken branch
1178     break;
1179   }
1180
1181   std::vector<SDOperand> Ops;
1182   Ops.reserve(3);
1183   Ops.push_back(N1);
1184   Ops.push_back(N2);
1185   Ops.push_back(N3);
1186
1187   // Memoize node if it doesn't produce a flag.
1188   SDNode *N;
1189   if (VT != MVT::Flag) {
1190     SDNode *&E = OneResultNodes[std::make_pair(Opcode,std::make_pair(VT, Ops))];
1191     if (E) return SDOperand(E, 0);
1192     E = N = new SDNode(Opcode, N1, N2, N3);
1193   } else {
1194     N = new SDNode(Opcode, N1, N2, N3);
1195   }
1196   N->setValueTypes(VT);
1197   AllNodes.push_back(N);
1198   return SDOperand(N, 0);
1199 }
1200
1201 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1202                                 SDOperand N1, SDOperand N2, SDOperand N3,
1203                                 SDOperand N4) {
1204   std::vector<SDOperand> Ops;
1205   Ops.reserve(4);
1206   Ops.push_back(N1);
1207   Ops.push_back(N2);
1208   Ops.push_back(N3);
1209   Ops.push_back(N4);
1210   return getNode(Opcode, VT, Ops);
1211 }
1212
1213 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1214                                 SDOperand N1, SDOperand N2, SDOperand N3,
1215                                 SDOperand N4, SDOperand N5) {
1216   std::vector<SDOperand> Ops;
1217   Ops.reserve(5);
1218   Ops.push_back(N1);
1219   Ops.push_back(N2);
1220   Ops.push_back(N3);
1221   Ops.push_back(N4);
1222   Ops.push_back(N5);
1223   return getNode(Opcode, VT, Ops);
1224 }
1225
1226
1227 SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
1228   assert((!V || isa<PointerType>(V->getType())) &&
1229          "SrcValue is not a pointer?");
1230   SDNode *&N = ValueNodes[std::make_pair(V, Offset)];
1231   if (N) return SDOperand(N, 0);
1232
1233   N = new SrcValueSDNode(V, Offset);
1234   AllNodes.push_back(N);
1235   return SDOperand(N, 0);
1236 }
1237
1238 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1239                                 std::vector<SDOperand> &Ops) {
1240   switch (Ops.size()) {
1241   case 0: return getNode(Opcode, VT);
1242   case 1: return getNode(Opcode, VT, Ops[0]);
1243   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
1244   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
1245   default: break;
1246   }
1247   
1248   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Ops[1].Val);
1249   switch (Opcode) {
1250   default: break;
1251   case ISD::BRCONDTWOWAY:
1252     if (N1C)
1253       if (N1C->getValue()) // Unconditional branch to true dest.
1254         return getNode(ISD::BR, MVT::Other, Ops[0], Ops[2]);
1255       else                 // Unconditional branch to false dest.
1256         return getNode(ISD::BR, MVT::Other, Ops[0], Ops[3]);
1257     break;
1258   case ISD::BRTWOWAY_CC:
1259     assert(Ops.size() == 6 && "BRTWOWAY_CC takes 6 operands!");
1260     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1261            "LHS and RHS of comparison must have same type!");
1262     break;
1263   case ISD::TRUNCSTORE: {
1264     assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
1265     MVT::ValueType EVT = cast<VTSDNode>(Ops[4])->getVT();
1266 #if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1267     // If this is a truncating store of a constant, convert to the desired type
1268     // and store it instead.
1269     if (isa<Constant>(Ops[0])) {
1270       SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1271       if (isa<Constant>(Op))
1272         N1 = Op;
1273     }
1274     // Also for ConstantFP?
1275 #endif
1276     if (Ops[0].getValueType() == EVT)       // Normal store?
1277       return getNode(ISD::STORE, VT, Ops[0], Ops[1], Ops[2], Ops[3]);
1278     assert(Ops[1].getValueType() > EVT && "Not a truncation?");
1279     assert(MVT::isInteger(Ops[1].getValueType()) == MVT::isInteger(EVT) &&
1280            "Can't do FP-INT conversion!");
1281     break;
1282   }
1283   case ISD::SELECT_CC: {
1284     assert(Ops.size() == 5 && "SELECT_CC takes 5 operands!");
1285     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
1286            "LHS and RHS of condition must have same type!");
1287     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1288            "True and False arms of SelectCC must have same type!");
1289     assert(Ops[2].getValueType() == VT &&
1290            "select_cc node must be of same type as true and false value!");
1291     break;
1292   }
1293   case ISD::BR_CC: {
1294     assert(Ops.size() == 5 && "BR_CC takes 5 operands!");
1295     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1296            "LHS/RHS of comparison should match types!");
1297     break;
1298   }
1299   }
1300
1301   // Memoize nodes.
1302   SDNode *N;
1303   if (VT != MVT::Flag) {
1304     SDNode *&E =
1305       OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
1306     if (E) return SDOperand(E, 0);
1307     E = N = new SDNode(Opcode, Ops);
1308   } else {
1309     N = new SDNode(Opcode, Ops);
1310   }
1311   N->setValueTypes(VT);
1312   AllNodes.push_back(N);
1313   return SDOperand(N, 0);
1314 }
1315
1316 SDOperand SelectionDAG::getNode(unsigned Opcode,
1317                                 std::vector<MVT::ValueType> &ResultTys,
1318                                 std::vector<SDOperand> &Ops) {
1319   if (ResultTys.size() == 1)
1320     return getNode(Opcode, ResultTys[0], Ops);
1321
1322   switch (Opcode) {
1323   case ISD::EXTLOAD:
1324   case ISD::SEXTLOAD:
1325   case ISD::ZEXTLOAD: {
1326     MVT::ValueType EVT = cast<VTSDNode>(Ops[3])->getVT();
1327     assert(Ops.size() == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!");
1328     // If they are asking for an extending load from/to the same thing, return a
1329     // normal load.
1330     if (ResultTys[0] == EVT)
1331       return getLoad(ResultTys[0], Ops[0], Ops[1], Ops[2]);
1332     assert(EVT < ResultTys[0] &&
1333            "Should only be an extending load, not truncating!");
1334     assert((Opcode == ISD::EXTLOAD || MVT::isInteger(ResultTys[0])) &&
1335            "Cannot sign/zero extend a FP load!");
1336     assert(MVT::isInteger(ResultTys[0]) == MVT::isInteger(EVT) &&
1337            "Cannot convert from FP to Int or Int -> FP!");
1338     break;
1339   }
1340
1341   // FIXME: figure out how to safely handle things like
1342   // int foo(int x) { return 1 << (x & 255); }
1343   // int bar() { return foo(256); }
1344 #if 0
1345   case ISD::SRA_PARTS:
1346   case ISD::SRL_PARTS:
1347   case ISD::SHL_PARTS:
1348     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1349         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
1350       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1351     else if (N3.getOpcode() == ISD::AND)
1352       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1353         // If the and is only masking out bits that cannot effect the shift,
1354         // eliminate the and.
1355         unsigned NumBits = MVT::getSizeInBits(VT)*2;
1356         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1357           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1358       }
1359     break;
1360 #endif
1361   }
1362
1363   // Memoize the node unless it returns a flag.
1364   SDNode *N;
1365   if (ResultTys.back() != MVT::Flag) {
1366     SDNode *&E =
1367       ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys, Ops))];
1368     if (E) return SDOperand(E, 0);
1369     E = N = new SDNode(Opcode, Ops);
1370   } else {
1371     N = new SDNode(Opcode, Ops);
1372   }
1373   setNodeValueTypes(N, ResultTys);
1374   AllNodes.push_back(N);
1375   return SDOperand(N, 0);
1376 }
1377
1378 void SelectionDAG::setNodeValueTypes(SDNode *N, 
1379                                      std::vector<MVT::ValueType> &RetVals) {
1380   switch (RetVals.size()) {
1381   case 0: return;
1382   case 1: N->setValueTypes(RetVals[0]); return;
1383   case 2: setNodeValueTypes(N, RetVals[0], RetVals[1]); return;
1384   default: break;
1385   }
1386   
1387   std::list<std::vector<MVT::ValueType> >::iterator I =
1388     std::find(VTList.begin(), VTList.end(), RetVals);
1389   if (I == VTList.end()) {
1390     VTList.push_front(RetVals);
1391     I = VTList.begin();
1392   }
1393
1394   N->setValueTypes(&(*I)[0], I->size());
1395 }
1396
1397 void SelectionDAG::setNodeValueTypes(SDNode *N, MVT::ValueType VT1, 
1398                                      MVT::ValueType VT2) {
1399   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
1400        E = VTList.end(); I != E; ++I) {
1401     if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2) {
1402       N->setValueTypes(&(*I)[0], 2);
1403       return;
1404     }
1405   }
1406   std::vector<MVT::ValueType> V;
1407   V.push_back(VT1);
1408   V.push_back(VT2);
1409   VTList.push_front(V);
1410   N->setValueTypes(&(*VTList.begin())[0], 2);
1411 }
1412
1413
1414 /// SelectNodeTo - These are used for target selectors to *mutate* the
1415 /// specified node to have the specified return type, Target opcode, and
1416 /// operands.  Note that target opcodes are stored as
1417 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
1418 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1419                                 MVT::ValueType VT) {
1420   RemoveNodeFromCSEMaps(N);
1421   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1422   N->setValueTypes(VT);
1423 }
1424
1425 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1426                                 MVT::ValueType VT, SDOperand Op1) {
1427   RemoveNodeFromCSEMaps(N);
1428   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1429   N->setValueTypes(VT);
1430   N->setOperands(Op1);
1431 }
1432
1433 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1434                                 MVT::ValueType VT, SDOperand Op1,
1435                                 SDOperand Op2) {
1436   RemoveNodeFromCSEMaps(N);
1437   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1438   N->setValueTypes(VT);
1439   N->setOperands(Op1, Op2);
1440 }
1441
1442 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1443                                 MVT::ValueType VT, SDOperand Op1,
1444                                 SDOperand Op2, SDOperand Op3) {
1445   RemoveNodeFromCSEMaps(N);
1446   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1447   N->setValueTypes(VT);
1448   N->setOperands(Op1, Op2, Op3);
1449 }
1450
1451 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1452                                 MVT::ValueType VT, SDOperand Op1,
1453                                 SDOperand Op2, SDOperand Op3, SDOperand Op4) {
1454   RemoveNodeFromCSEMaps(N);
1455   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1456   N->setValueTypes(VT);
1457   N->setOperands(Op1, Op2, Op3, Op4);
1458 }
1459
1460 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1461                                 MVT::ValueType VT, SDOperand Op1,
1462                                 SDOperand Op2, SDOperand Op3, SDOperand Op4,
1463                                 SDOperand Op5) {
1464   RemoveNodeFromCSEMaps(N);
1465   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1466   N->setValueTypes(VT);
1467   N->setOperands(Op1, Op2, Op3, Op4, Op5);
1468 }
1469
1470 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1471                                 MVT::ValueType VT, SDOperand Op1,
1472                                 SDOperand Op2, SDOperand Op3, SDOperand Op4,
1473                                 SDOperand Op5, SDOperand Op6) {
1474   RemoveNodeFromCSEMaps(N);
1475   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1476   N->setValueTypes(VT);
1477   N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6);
1478 }
1479
1480 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
1481                                 MVT::ValueType VT1, MVT::ValueType VT2,
1482                                 SDOperand Op1, SDOperand Op2) {
1483   RemoveNodeFromCSEMaps(N);
1484   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1485   setNodeValueTypes(N, VT1, VT2);
1486   N->setOperands(Op1, Op2);
1487 }
1488
1489 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1490                                 MVT::ValueType VT1, MVT::ValueType VT2,
1491                                 SDOperand Op1, SDOperand Op2, SDOperand Op3) {
1492   RemoveNodeFromCSEMaps(N);
1493   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1494   setNodeValueTypes(N, VT1, VT2);
1495   N->setOperands(Op1, Op2, Op3);
1496 }
1497
1498 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1499                                 MVT::ValueType VT1, MVT::ValueType VT2,
1500                                 SDOperand Op1, SDOperand Op2,
1501                                 SDOperand Op3, SDOperand Op4) {
1502   RemoveNodeFromCSEMaps(N);
1503   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1504   setNodeValueTypes(N, VT1, VT2);
1505   N->setOperands(Op1, Op2, Op3, Op4);
1506 }
1507
1508 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1509                                 MVT::ValueType VT1, MVT::ValueType VT2,
1510                                 SDOperand Op1, SDOperand Op2,
1511                                 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
1512   RemoveNodeFromCSEMaps(N);
1513   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1514   setNodeValueTypes(N, VT1, VT2);
1515   N->setOperands(Op1, Op2, Op3, Op4, Op5);
1516 }
1517
1518 // ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
1519 /// This can cause recursive merging of nodes in the DAG.
1520 ///
1521 /// This version assumes From/To have a single result value.
1522 ///
1523 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
1524                                       std::vector<SDNode*> *Deleted) {
1525   SDNode *From = FromN.Val, *To = ToN.Val;
1526   assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
1527          "Cannot replace with this method!");
1528   assert(From != To && "Cannot replace uses of with self");
1529   
1530   while (!From->use_empty()) {
1531     // Process users until they are all gone.
1532     SDNode *U = *From->use_begin();
1533     
1534     // This node is about to morph, remove its old self from the CSE maps.
1535     RemoveNodeFromCSEMaps(U);
1536     
1537     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
1538          I != E; ++I)
1539       if (I->Val == From) {
1540         From->removeUser(U);
1541         I->Val = To;
1542         To->addUser(U);
1543       }
1544
1545     // Now that we have modified U, add it back to the CSE maps.  If it already
1546     // exists there, recursively merge the results together.
1547     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
1548       ReplaceAllUsesWith(U, Existing, Deleted);
1549       // U is now dead.
1550       if (Deleted) Deleted->push_back(U);
1551       DeleteNodeNotInCSEMaps(U);
1552     }
1553   }
1554 }
1555
1556 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
1557 /// This can cause recursive merging of nodes in the DAG.
1558 ///
1559 /// This version assumes From/To have matching types and numbers of result
1560 /// values.
1561 ///
1562 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
1563                                       std::vector<SDNode*> *Deleted) {
1564   assert(From != To && "Cannot replace uses of with self");
1565   assert(From->getNumValues() == To->getNumValues() &&
1566          "Cannot use this version of ReplaceAllUsesWith!");
1567   if (From->getNumValues() == 1) {  // If possible, use the faster version.
1568     ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
1569     return;
1570   }
1571   
1572   while (!From->use_empty()) {
1573     // Process users until they are all gone.
1574     SDNode *U = *From->use_begin();
1575     
1576     // This node is about to morph, remove its old self from the CSE maps.
1577     RemoveNodeFromCSEMaps(U);
1578     
1579     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
1580          I != E; ++I)
1581       if (I->Val == From) {
1582         From->removeUser(U);
1583         I->Val = To;
1584         To->addUser(U);
1585       }
1586         
1587     // Now that we have modified U, add it back to the CSE maps.  If it already
1588     // exists there, recursively merge the results together.
1589     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
1590       ReplaceAllUsesWith(U, Existing, Deleted);
1591       // U is now dead.
1592       if (Deleted) Deleted->push_back(U);
1593       DeleteNodeNotInCSEMaps(U);
1594     }
1595   }
1596 }
1597
1598 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
1599 /// This can cause recursive merging of nodes in the DAG.
1600 ///
1601 /// This version can replace From with any result values.  To must match the
1602 /// number and types of values returned by From.
1603 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
1604                                       const std::vector<SDOperand> &To,
1605                                       std::vector<SDNode*> *Deleted) {
1606   assert(From->getNumValues() == To.size() &&
1607          "Incorrect number of values to replace with!");
1608   if (To.size() == 1 && To[0].Val->getNumValues() == 1) {
1609     // Degenerate case handled above.
1610     ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
1611     return;
1612   }
1613
1614   while (!From->use_empty()) {
1615     // Process users until they are all gone.
1616     SDNode *U = *From->use_begin();
1617     
1618     // This node is about to morph, remove its old self from the CSE maps.
1619     RemoveNodeFromCSEMaps(U);
1620     
1621     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
1622          I != E; ++I)
1623       if (I->Val == From) {
1624         const SDOperand &ToOp = To[I->ResNo];
1625         From->removeUser(U);
1626         *I = ToOp;
1627         ToOp.Val->addUser(U);
1628       }
1629         
1630     // Now that we have modified U, add it back to the CSE maps.  If it already
1631     // exists there, recursively merge the results together.
1632     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
1633       ReplaceAllUsesWith(U, Existing, Deleted);
1634       // U is now dead.
1635       if (Deleted) Deleted->push_back(U);
1636       DeleteNodeNotInCSEMaps(U);
1637     }
1638   }
1639 }
1640
1641
1642 //===----------------------------------------------------------------------===//
1643 //                              SDNode Class
1644 //===----------------------------------------------------------------------===//
1645
1646
1647 /// getValueTypeList - Return a pointer to the specified value type.
1648 ///
1649 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
1650   static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
1651   VTs[VT] = VT;
1652   return &VTs[VT];
1653 }
1654
1655 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
1656 /// indicated value.  This method ignores uses of other values defined by this
1657 /// operation.
1658 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) {
1659   assert(Value < getNumValues() && "Bad value!");
1660
1661   // If there is only one value, this is easy.
1662   if (getNumValues() == 1)
1663     return use_size() == NUses;
1664   if (Uses.size() < NUses) return false;
1665
1666   SDOperand TheValue(this, Value);
1667
1668   std::set<SDNode*> UsersHandled;
1669
1670   for (std::vector<SDNode*>::iterator UI = Uses.begin(), E = Uses.end();
1671        UI != E; ++UI) {
1672     SDNode *User = *UI;
1673     if (User->getNumOperands() == 1 ||
1674         UsersHandled.insert(User).second)     // First time we've seen this?
1675       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1676         if (User->getOperand(i) == TheValue) {
1677           if (NUses == 0)
1678             return false;   // too many uses
1679           --NUses;
1680         }
1681   }
1682
1683   // Found exactly the right number of uses?
1684   return NUses == 0;
1685 }
1686
1687
1688 const char *SDNode::getOperationName(const SelectionDAG *G) const {
1689   switch (getOpcode()) {
1690   default:
1691     if (getOpcode() < ISD::BUILTIN_OP_END)
1692       return "<<Unknown DAG Node>>";
1693     else {
1694       if (G)
1695         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
1696           if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
1697             return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
1698       return "<<Unknown Target Node>>";
1699     }
1700    
1701   case ISD::PCMARKER:      return "PCMarker";
1702   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
1703   case ISD::SRCVALUE:      return "SrcValue";
1704   case ISD::VALUETYPE:     return "ValueType";
1705   case ISD::STRING:        return "String";
1706   case ISD::EntryToken:    return "EntryToken";
1707   case ISD::TokenFactor:   return "TokenFactor";
1708   case ISD::AssertSext:    return "AssertSext";
1709   case ISD::AssertZext:    return "AssertZext";
1710   case ISD::Constant:      return "Constant";
1711   case ISD::TargetConstant: return "TargetConstant";
1712   case ISD::ConstantFP:    return "ConstantFP";
1713   case ISD::GlobalAddress: return "GlobalAddress";
1714   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
1715   case ISD::FrameIndex:    return "FrameIndex";
1716   case ISD::TargetFrameIndex: return "TargetFrameIndex";
1717   case ISD::BasicBlock:    return "BasicBlock";
1718   case ISD::Register:      return "Register";
1719   case ISD::ExternalSymbol: return "ExternalSymbol";
1720   case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
1721   case ISD::ConstantPool:  return "ConstantPool";
1722   case ISD::TargetConstantPool:  return "TargetConstantPool";
1723   case ISD::CopyToReg:     return "CopyToReg";
1724   case ISD::CopyFromReg:   return "CopyFromReg";
1725   case ISD::ImplicitDef:   return "ImplicitDef";
1726   case ISD::UNDEF:         return "undef";
1727
1728   // Unary operators
1729   case ISD::FABS:   return "fabs";
1730   case ISD::FNEG:   return "fneg";
1731   case ISD::FSQRT:  return "fsqrt";
1732   case ISD::FSIN:   return "fsin";
1733   case ISD::FCOS:   return "fcos";
1734
1735   // Binary operators
1736   case ISD::ADD:    return "add";
1737   case ISD::SUB:    return "sub";
1738   case ISD::MUL:    return "mul";
1739   case ISD::MULHU:  return "mulhu";
1740   case ISD::MULHS:  return "mulhs";
1741   case ISD::SDIV:   return "sdiv";
1742   case ISD::UDIV:   return "udiv";
1743   case ISD::SREM:   return "srem";
1744   case ISD::UREM:   return "urem";
1745   case ISD::AND:    return "and";
1746   case ISD::OR:     return "or";
1747   case ISD::XOR:    return "xor";
1748   case ISD::SHL:    return "shl";
1749   case ISD::SRA:    return "sra";
1750   case ISD::SRL:    return "srl";
1751   case ISD::FADD:   return "fadd";
1752   case ISD::FSUB:   return "fsub";
1753   case ISD::FMUL:   return "fmul";
1754   case ISD::FDIV:   return "fdiv";
1755   case ISD::FREM:   return "frem";
1756   case ISD::VADD:   return "vadd";
1757   case ISD::VSUB:   return "vsub";
1758   case ISD::VMUL:   return "vmul";
1759     
1760   case ISD::SETCC:       return "setcc";
1761   case ISD::SELECT:      return "select";
1762   case ISD::SELECT_CC:   return "select_cc";
1763   case ISD::ADD_PARTS:   return "add_parts";
1764   case ISD::SUB_PARTS:   return "sub_parts";
1765   case ISD::SHL_PARTS:   return "shl_parts";
1766   case ISD::SRA_PARTS:   return "sra_parts";
1767   case ISD::SRL_PARTS:   return "srl_parts";
1768
1769   // Conversion operators.
1770   case ISD::SIGN_EXTEND: return "sign_extend";
1771   case ISD::ZERO_EXTEND: return "zero_extend";
1772   case ISD::ANY_EXTEND:  return "any_extend";
1773   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
1774   case ISD::TRUNCATE:    return "truncate";
1775   case ISD::FP_ROUND:    return "fp_round";
1776   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
1777   case ISD::FP_EXTEND:   return "fp_extend";
1778
1779   case ISD::SINT_TO_FP:  return "sint_to_fp";
1780   case ISD::UINT_TO_FP:  return "uint_to_fp";
1781   case ISD::FP_TO_SINT:  return "fp_to_sint";
1782   case ISD::FP_TO_UINT:  return "fp_to_uint";
1783
1784     // Control flow instructions
1785   case ISD::BR:      return "br";
1786   case ISD::BRCOND:  return "brcond";
1787   case ISD::BRCONDTWOWAY:  return "brcondtwoway";
1788   case ISD::BR_CC:  return "br_cc";
1789   case ISD::BRTWOWAY_CC:  return "brtwoway_cc";
1790   case ISD::RET:     return "ret";
1791   case ISD::CALL:    return "call";
1792   case ISD::TAILCALL:return "tailcall";
1793   case ISD::CALLSEQ_START:  return "callseq_start";
1794   case ISD::CALLSEQ_END:    return "callseq_end";
1795
1796     // Other operators
1797   case ISD::LOAD:    return "load";
1798   case ISD::STORE:   return "store";
1799   case ISD::VLOAD:   return "vload";
1800   case ISD::EXTLOAD:    return "extload";
1801   case ISD::SEXTLOAD:   return "sextload";
1802   case ISD::ZEXTLOAD:   return "zextload";
1803   case ISD::TRUNCSTORE: return "truncstore";
1804
1805   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
1806   case ISD::EXTRACT_ELEMENT: return "extract_element";
1807   case ISD::BUILD_PAIR: return "build_pair";
1808   case ISD::MEMSET:  return "memset";
1809   case ISD::MEMCPY:  return "memcpy";
1810   case ISD::MEMMOVE: return "memmove";
1811
1812   // Bit counting
1813   case ISD::CTPOP:   return "ctpop";
1814   case ISD::CTTZ:    return "cttz";
1815   case ISD::CTLZ:    return "ctlz";
1816
1817   // IO Intrinsics
1818   case ISD::READPORT: return "readport";
1819   case ISD::WRITEPORT: return "writeport";
1820   case ISD::READIO: return "readio";
1821   case ISD::WRITEIO: return "writeio";
1822
1823   // Debug info
1824   case ISD::LOCATION: return "location";
1825
1826   case ISD::CONDCODE:
1827     switch (cast<CondCodeSDNode>(this)->get()) {
1828     default: assert(0 && "Unknown setcc condition!");
1829     case ISD::SETOEQ:  return "setoeq";
1830     case ISD::SETOGT:  return "setogt";
1831     case ISD::SETOGE:  return "setoge";
1832     case ISD::SETOLT:  return "setolt";
1833     case ISD::SETOLE:  return "setole";
1834     case ISD::SETONE:  return "setone";
1835
1836     case ISD::SETO:    return "seto";
1837     case ISD::SETUO:   return "setuo";
1838     case ISD::SETUEQ:  return "setue";
1839     case ISD::SETUGT:  return "setugt";
1840     case ISD::SETUGE:  return "setuge";
1841     case ISD::SETULT:  return "setult";
1842     case ISD::SETULE:  return "setule";
1843     case ISD::SETUNE:  return "setune";
1844
1845     case ISD::SETEQ:   return "seteq";
1846     case ISD::SETGT:   return "setgt";
1847     case ISD::SETGE:   return "setge";
1848     case ISD::SETLT:   return "setlt";
1849     case ISD::SETLE:   return "setle";
1850     case ISD::SETNE:   return "setne";
1851     }
1852   }
1853 }
1854
1855 void SDNode::dump() const { dump(0); }
1856 void SDNode::dump(const SelectionDAG *G) const {
1857   std::cerr << (void*)this << ": ";
1858
1859   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
1860     if (i) std::cerr << ",";
1861     if (getValueType(i) == MVT::Other)
1862       std::cerr << "ch";
1863     else
1864       std::cerr << MVT::getValueTypeString(getValueType(i));
1865   }
1866   std::cerr << " = " << getOperationName(G);
1867
1868   std::cerr << " ";
1869   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1870     if (i) std::cerr << ", ";
1871     std::cerr << (void*)getOperand(i).Val;
1872     if (unsigned RN = getOperand(i).ResNo)
1873       std::cerr << ":" << RN;
1874   }
1875
1876   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
1877     std::cerr << "<" << CSDN->getValue() << ">";
1878   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
1879     std::cerr << "<" << CSDN->getValue() << ">";
1880   } else if (const GlobalAddressSDNode *GADN =
1881              dyn_cast<GlobalAddressSDNode>(this)) {
1882     int offset = GADN->getOffset();
1883     std::cerr << "<";
1884     WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
1885     if (offset > 0)
1886       std::cerr << " + " << offset;
1887     else
1888       std::cerr << " " << offset;
1889   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
1890     std::cerr << "<" << FIDN->getIndex() << ">";
1891   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
1892     std::cerr << "<" << *CP->get() << ">";
1893   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
1894     std::cerr << "<";
1895     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
1896     if (LBB)
1897       std::cerr << LBB->getName() << " ";
1898     std::cerr << (const void*)BBDN->getBasicBlock() << ">";
1899   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
1900     if (G && MRegisterInfo::isPhysicalRegister(R->getReg())) {
1901       std::cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
1902     } else {
1903       std::cerr << " #" << R->getReg();
1904     }
1905   } else if (const ExternalSymbolSDNode *ES =
1906              dyn_cast<ExternalSymbolSDNode>(this)) {
1907     std::cerr << "'" << ES->getSymbol() << "'";
1908   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
1909     if (M->getValue())
1910       std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
1911     else
1912       std::cerr << "<null:" << M->getOffset() << ">";
1913   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
1914     std::cerr << ":" << getValueTypeString(N->getVT());
1915   }
1916 }
1917
1918 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
1919   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1920     if (N->getOperand(i).Val->hasOneUse())
1921       DumpNodes(N->getOperand(i).Val, indent+2, G);
1922     else
1923       std::cerr << "\n" << std::string(indent+2, ' ')
1924                 << (void*)N->getOperand(i).Val << ": <multiple use>";
1925
1926
1927   std::cerr << "\n" << std::string(indent, ' ');
1928   N->dump(G);
1929 }
1930
1931 void SelectionDAG::dump() const {
1932   std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
1933   std::vector<const SDNode*> Nodes;
1934   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
1935        I != E; ++I)
1936     Nodes.push_back(I);
1937   
1938   std::sort(Nodes.begin(), Nodes.end());
1939
1940   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1941     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
1942       DumpNodes(Nodes[i], 2, this);
1943   }
1944
1945   DumpNodes(getRoot().Val, 2, this);
1946
1947   std::cerr << "\n\n";
1948 }
1949