Add ISD::isBuildVectorAllZeros predicate
[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 "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include <iostream>
27 #include <set>
28 #include <cmath>
29 #include <algorithm>
30 using namespace llvm;
31
32 static bool isCommutativeBinOp(unsigned Opcode) {
33   switch (Opcode) {
34   case ISD::ADD:
35   case ISD::MUL:
36   case ISD::MULHU:
37   case ISD::MULHS:
38   case ISD::FADD:
39   case ISD::FMUL:
40   case ISD::AND:
41   case ISD::OR:
42   case ISD::XOR: return true;
43   default: return false; // FIXME: Need commutative info for user ops!
44   }
45 }
46
47 // isInvertibleForFree - Return true if there is no cost to emitting the logical
48 // inverse of this node.
49 static bool isInvertibleForFree(SDOperand N) {
50   if (isa<ConstantSDNode>(N.Val)) return true;
51   if (N.Val->getOpcode() == ISD::SETCC && N.Val->hasOneUse())
52     return true;
53   return false;
54 }
55
56 //===----------------------------------------------------------------------===//
57 //                              ConstantFPSDNode Class
58 //===----------------------------------------------------------------------===//
59
60 /// isExactlyValue - We don't rely on operator== working on double values, as
61 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
62 /// As such, this method can be used to do an exact bit-for-bit comparison of
63 /// two floating point values.
64 bool ConstantFPSDNode::isExactlyValue(double V) const {
65   return DoubleToBits(V) == DoubleToBits(Value);
66 }
67
68 //===----------------------------------------------------------------------===//
69 //                              ISD Namespace
70 //===----------------------------------------------------------------------===//
71
72 /// isBuildVectorAllOnesInteger - Return true if the specified node is a
73 /// BUILD_VECTOR where all of the elements are ~0 or undef.
74 bool ISD::isBuildVectorAllOnesInteger(const SDNode *N) {
75   if (N->getOpcode() != ISD::BUILD_VECTOR ||
76       !MVT::isInteger(N->getOperand(0).getValueType())) return false;
77   
78   unsigned i = 0, e = N->getNumOperands();
79   
80   // Skip over all of the undef values.
81   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
82     ++i;
83   
84   // Do not accept an all-undef vector.
85   if (i == e) return false;
86   
87   // Do not accept build_vectors that aren't all constants or which have non-~0
88   // elements.
89   SDOperand NotZero = N->getOperand(i);
90   if (!isa<ConstantSDNode>(NotZero) ||
91       !cast<ConstantSDNode>(NotZero)->isAllOnesValue())
92     return false;
93   
94   // Okay, we have at least one ~0 value, check to see if the rest match or are
95   // undefs.
96   for (++i; i != e; ++i)
97     if (N->getOperand(i) != NotZero &&
98         N->getOperand(i).getOpcode() != ISD::UNDEF)
99       return false;
100   return true;
101 }
102
103
104 /// isBuildVectorAllZeros - Return true if the specified node is a
105 /// BUILD_VECTOR where all of the elements are 0 or undef.
106 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
107   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
108
109   bool AllUndef = true;
110   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
111     SDOperand Elt = N->getOperand(i);
112     if (Elt.getOpcode() != ISD::UNDEF) {
113       AllUndef = false;
114       if (isa<ConstantSDNode>(Elt)) {
115         if (!cast<ConstantSDNode>(Elt)->isNullValue())
116           return false;
117       } else if (isa<ConstantFPSDNode>(Elt)) {
118         if (!cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0))
119           return false;
120       } else
121         return false;
122     }
123   }
124
125   return !AllUndef;
126 }
127
128 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
129 /// when given the operation for (X op Y).
130 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
131   // To perform this operation, we just need to swap the L and G bits of the
132   // operation.
133   unsigned OldL = (Operation >> 2) & 1;
134   unsigned OldG = (Operation >> 1) & 1;
135   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
136                        (OldL << 1) |       // New G bit
137                        (OldG << 2));        // New L bit.
138 }
139
140 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
141 /// 'op' is a valid SetCC operation.
142 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
143   unsigned Operation = Op;
144   if (isInteger)
145     Operation ^= 7;   // Flip L, G, E bits, but not U.
146   else
147     Operation ^= 15;  // Flip all of the condition bits.
148   if (Operation > ISD::SETTRUE2)
149     Operation &= ~8;     // Don't let N and U bits get set.
150   return ISD::CondCode(Operation);
151 }
152
153
154 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
155 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
156 /// if the operation does not depend on the sign of the input (setne and seteq).
157 static int isSignedOp(ISD::CondCode Opcode) {
158   switch (Opcode) {
159   default: assert(0 && "Illegal integer setcc operation!");
160   case ISD::SETEQ:
161   case ISD::SETNE: return 0;
162   case ISD::SETLT:
163   case ISD::SETLE:
164   case ISD::SETGT:
165   case ISD::SETGE: return 1;
166   case ISD::SETULT:
167   case ISD::SETULE:
168   case ISD::SETUGT:
169   case ISD::SETUGE: return 2;
170   }
171 }
172
173 /// getSetCCOrOperation - Return the result of a logical OR between different
174 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
175 /// returns SETCC_INVALID if it is not possible to represent the resultant
176 /// comparison.
177 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
178                                        bool isInteger) {
179   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
180     // Cannot fold a signed integer setcc with an unsigned integer setcc.
181     return ISD::SETCC_INVALID;
182
183   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
184
185   // If the N and U bits get set then the resultant comparison DOES suddenly
186   // care about orderedness, and is true when ordered.
187   if (Op > ISD::SETTRUE2)
188     Op &= ~16;     // Clear the N bit.
189   return ISD::CondCode(Op);
190 }
191
192 /// getSetCCAndOperation - Return the result of a logical AND between different
193 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
194 /// function returns zero if it is not possible to represent the resultant
195 /// comparison.
196 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
197                                         bool isInteger) {
198   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
199     // Cannot fold a signed setcc with an unsigned setcc.
200     return ISD::SETCC_INVALID;
201
202   // Combine all of the condition bits.
203   return ISD::CondCode(Op1 & Op2);
204 }
205
206 const TargetMachine &SelectionDAG::getTarget() const {
207   return TLI.getTargetMachine();
208 }
209
210 //===----------------------------------------------------------------------===//
211 //                              SelectionDAG Class
212 //===----------------------------------------------------------------------===//
213
214 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
215 /// SelectionDAG, including nodes (like loads) that have uses of their token
216 /// chain but no other uses and no side effect.  If a node is passed in as an
217 /// argument, it is used as the seed for node deletion.
218 void SelectionDAG::RemoveDeadNodes(SDNode *N) {
219   // Create a dummy node (which is not added to allnodes), that adds a reference
220   // to the root node, preventing it from being deleted.
221   HandleSDNode Dummy(getRoot());
222
223   bool MadeChange = false;
224   
225   // If we have a hint to start from, use it.
226   if (N && N->use_empty()) {
227     DestroyDeadNode(N);
228     MadeChange = true;
229   }
230
231   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
232     if (I->use_empty() && I->getOpcode() != 65535) {
233       // Node is dead, recursively delete newly dead uses.
234       DestroyDeadNode(I);
235       MadeChange = true;
236     }
237   
238   // Walk the nodes list, removing the nodes we've marked as dead.
239   if (MadeChange) {
240     for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ) {
241       SDNode *N = I++;
242       if (N->use_empty())
243         AllNodes.erase(N);
244     }
245   }
246   
247   // If the root changed (e.g. it was a dead load, update the root).
248   setRoot(Dummy.getValue());
249 }
250
251 /// DestroyDeadNode - We know that N is dead.  Nuke it from the CSE maps for the
252 /// graph.  If it is the last user of any of its operands, recursively process
253 /// them the same way.
254 /// 
255 void SelectionDAG::DestroyDeadNode(SDNode *N) {
256   // Okay, we really are going to delete this node.  First take this out of the
257   // appropriate CSE map.
258   RemoveNodeFromCSEMaps(N);
259   
260   // Next, brutally remove the operand list.  This is safe to do, as there are
261   // no cycles in the graph.
262   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
263     SDNode *O = I->Val;
264     O->removeUser(N);
265     
266     // Now that we removed this operand, see if there are no uses of it left.
267     if (O->use_empty())
268       DestroyDeadNode(O);
269   }
270   delete[] N->OperandList;
271   N->OperandList = 0;
272   N->NumOperands = 0;
273
274   // Mark the node as dead.
275   N->MorphNodeTo(65535);
276 }
277
278 void SelectionDAG::DeleteNode(SDNode *N) {
279   assert(N->use_empty() && "Cannot delete a node that is not dead!");
280
281   // First take this out of the appropriate CSE map.
282   RemoveNodeFromCSEMaps(N);
283
284   // Finally, remove uses due to operands of this node, remove from the 
285   // AllNodes list, and delete the node.
286   DeleteNodeNotInCSEMaps(N);
287 }
288
289 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
290
291   // Remove it from the AllNodes list.
292   AllNodes.remove(N);
293     
294   // Drop all of the operands and decrement used nodes use counts.
295   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
296     I->Val->removeUser(N);
297   delete[] N->OperandList;
298   N->OperandList = 0;
299   N->NumOperands = 0;
300   
301   delete N;
302 }
303
304 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
305 /// correspond to it.  This is useful when we're about to delete or repurpose
306 /// the node.  We don't want future request for structurally identical nodes
307 /// to return N anymore.
308 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
309   bool Erased = false;
310   switch (N->getOpcode()) {
311   case ISD::HANDLENODE: return;  // noop.
312   case ISD::Constant:
313     Erased = Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
314                                             N->getValueType(0)));
315     break;
316   case ISD::TargetConstant:
317     Erased = TargetConstants.erase(std::make_pair(
318                                     cast<ConstantSDNode>(N)->getValue(),
319                                                   N->getValueType(0)));
320     break;
321   case ISD::ConstantFP: {
322     uint64_t V = DoubleToBits(cast<ConstantFPSDNode>(N)->getValue());
323     Erased = ConstantFPs.erase(std::make_pair(V, N->getValueType(0)));
324     break;
325   }
326   case ISD::TargetConstantFP: {
327     uint64_t V = DoubleToBits(cast<ConstantFPSDNode>(N)->getValue());
328     Erased = TargetConstantFPs.erase(std::make_pair(V, N->getValueType(0)));
329     break;
330   }
331   case ISD::STRING:
332     Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
333     break;
334   case ISD::CONDCODE:
335     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
336            "Cond code doesn't exist!");
337     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
338     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
339     break;
340   case ISD::GlobalAddress: {
341     GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(N);
342     Erased = GlobalValues.erase(std::make_pair(GN->getGlobal(),
343                                                GN->getOffset()));
344     break;
345   }
346   case ISD::TargetGlobalAddress: {
347     GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(N);
348     Erased =TargetGlobalValues.erase(std::make_pair(GN->getGlobal(),
349                                                     GN->getOffset()));
350     break;
351   }
352   case ISD::FrameIndex:
353     Erased = FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
354     break;
355   case ISD::TargetFrameIndex:
356     Erased = TargetFrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
357     break;
358   case ISD::ConstantPool:
359     Erased = ConstantPoolIndices.
360       erase(std::make_pair(cast<ConstantPoolSDNode>(N)->get(),
361                         std::make_pair(cast<ConstantPoolSDNode>(N)->getOffset(),
362                                  cast<ConstantPoolSDNode>(N)->getAlignment())));
363     break;
364   case ISD::TargetConstantPool:
365     Erased = TargetConstantPoolIndices.
366       erase(std::make_pair(cast<ConstantPoolSDNode>(N)->get(),
367                         std::make_pair(cast<ConstantPoolSDNode>(N)->getOffset(),
368                                  cast<ConstantPoolSDNode>(N)->getAlignment())));
369     break;
370   case ISD::BasicBlock:
371     Erased = BBNodes.erase(cast<BasicBlockSDNode>(N)->getBasicBlock());
372     break;
373   case ISD::ExternalSymbol:
374     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
375     break;
376   case ISD::TargetExternalSymbol:
377     Erased =
378       TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
379     break;
380   case ISD::VALUETYPE:
381     Erased = ValueTypeNodes[cast<VTSDNode>(N)->getVT()] != 0;
382     ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
383     break;
384   case ISD::Register:
385     Erased = RegNodes.erase(std::make_pair(cast<RegisterSDNode>(N)->getReg(),
386                                            N->getValueType(0)));
387     break;
388   case ISD::SRCVALUE: {
389     SrcValueSDNode *SVN = cast<SrcValueSDNode>(N);
390     Erased =ValueNodes.erase(std::make_pair(SVN->getValue(), SVN->getOffset()));
391     break;
392   }    
393   case ISD::LOAD:
394     Erased = Loads.erase(std::make_pair(N->getOperand(1),
395                                         std::make_pair(N->getOperand(0),
396                                                        N->getValueType(0))));
397     break;
398   default:
399     if (N->getNumValues() == 1) {
400       if (N->getNumOperands() == 0) {
401         Erased = NullaryOps.erase(std::make_pair(N->getOpcode(),
402                                                  N->getValueType(0)));
403       } else if (N->getNumOperands() == 1) {
404         Erased = 
405           UnaryOps.erase(std::make_pair(N->getOpcode(),
406                                         std::make_pair(N->getOperand(0),
407                                                        N->getValueType(0))));
408       } else if (N->getNumOperands() == 2) {
409         Erased = 
410           BinaryOps.erase(std::make_pair(N->getOpcode(),
411                                          std::make_pair(N->getOperand(0),
412                                                         N->getOperand(1))));
413       } else { 
414         std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
415         Erased = 
416           OneResultNodes.erase(std::make_pair(N->getOpcode(),
417                                               std::make_pair(N->getValueType(0),
418                                                              Ops)));
419       }
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       Erased =
425         ArbitraryNodes.erase(std::make_pair(N->getOpcode(),
426                                             std::make_pair(RV, Ops)));
427     }
428     break;
429   }
430 #ifndef NDEBUG
431   // Verify that the node was actually in one of the CSE maps, unless it has a 
432   // flag result (which cannot be CSE'd) or is one of the special cases that are
433   // not subject to CSE.
434   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
435       !N->isTargetOpcode()) {
436     N->dump();
437     assert(0 && "Node is not in map!");
438   }
439 #endif
440 }
441
442 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
443 /// has been taken out and modified in some way.  If the specified node already
444 /// exists in the CSE maps, do not modify the maps, but return the existing node
445 /// instead.  If it doesn't exist, add it and return null.
446 ///
447 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
448   assert(N->getNumOperands() && "This is a leaf node!");
449   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
450     return 0;    // Never add these nodes.
451   
452   // Check that remaining values produced are not flags.
453   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
454     if (N->getValueType(i) == MVT::Flag)
455       return 0;   // Never CSE anything that produces a flag.
456   
457   if (N->getNumValues() == 1) {
458     if (N->getNumOperands() == 1) {
459       SDNode *&U = UnaryOps[std::make_pair(N->getOpcode(),
460                                            std::make_pair(N->getOperand(0),
461                                                           N->getValueType(0)))];
462       if (U) return U;
463       U = N;
464     } else if (N->getNumOperands() == 2) {
465       SDNode *&B = BinaryOps[std::make_pair(N->getOpcode(),
466                                             std::make_pair(N->getOperand(0),
467                                                            N->getOperand(1)))];
468       if (B) return B;
469       B = N;
470     } else {
471       std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
472       SDNode *&ORN = OneResultNodes[std::make_pair(N->getOpcode(),
473                                       std::make_pair(N->getValueType(0), Ops))];
474       if (ORN) return ORN;
475       ORN = N;
476     }
477   } else {  
478     if (N->getOpcode() == ISD::LOAD) {
479       SDNode *&L = Loads[std::make_pair(N->getOperand(1),
480                                         std::make_pair(N->getOperand(0),
481                                                        N->getValueType(0)))];
482       if (L) return L;
483       L = N;
484     } else {
485       // Remove the node from the ArbitraryNodes map.
486       std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
487       std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
488       SDNode *&AN = ArbitraryNodes[std::make_pair(N->getOpcode(),
489                                                   std::make_pair(RV, Ops))];
490       if (AN) return AN;
491       AN = N;
492     }
493   }
494   return 0;
495 }
496
497 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
498 /// were replaced with those specified.  If this node is never memoized, 
499 /// return null, otherwise return a pointer to the slot it would take.  If a
500 /// node already exists with these operands, the slot will be non-null.
501 SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op) {
502   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
503     return 0;    // Never add these nodes.
504   
505   // Check that remaining values produced are not flags.
506   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
507     if (N->getValueType(i) == MVT::Flag)
508       return 0;   // Never CSE anything that produces a flag.
509   
510   if (N->getNumValues() == 1) {
511     return &UnaryOps[std::make_pair(N->getOpcode(),
512                                     std::make_pair(Op, N->getValueType(0)))];
513   } else {  
514     // Remove the node from the ArbitraryNodes map.
515     std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
516     std::vector<SDOperand> Ops;
517     Ops.push_back(Op);
518     return &ArbitraryNodes[std::make_pair(N->getOpcode(),
519                                           std::make_pair(RV, Ops))];
520   }
521   return 0;
522 }
523
524 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
525 /// were replaced with those specified.  If this node is never memoized, 
526 /// return null, otherwise return a pointer to the slot it would take.  If a
527 /// node already exists with these operands, the slot will be non-null.
528 SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
529                                             SDOperand Op1, SDOperand Op2) {
530   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
531     return 0;    // Never add these nodes.
532   
533   // Check that remaining values produced are not flags.
534   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
535     if (N->getValueType(i) == MVT::Flag)
536       return 0;   // Never CSE anything that produces a flag.
537   
538   if (N->getNumValues() == 1) {
539     return &BinaryOps[std::make_pair(N->getOpcode(),
540                                      std::make_pair(Op1, Op2))];
541   } else {  
542     std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
543     std::vector<SDOperand> Ops;
544     Ops.push_back(Op1);
545     Ops.push_back(Op2);
546     return &ArbitraryNodes[std::make_pair(N->getOpcode(),
547                                           std::make_pair(RV, Ops))];
548   }
549   return 0;
550 }
551
552
553 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
554 /// were replaced with those specified.  If this node is never memoized, 
555 /// return null, otherwise return a pointer to the slot it would take.  If a
556 /// node already exists with these operands, the slot will be non-null.
557 SDNode **SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
558                                             const std::vector<SDOperand> &Ops) {
559   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
560     return 0;    // Never add these nodes.
561   
562   // Check that remaining values produced are not flags.
563   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
564     if (N->getValueType(i) == MVT::Flag)
565       return 0;   // Never CSE anything that produces a flag.
566   
567   if (N->getNumValues() == 1) {
568     if (N->getNumOperands() == 1) {
569       return &UnaryOps[std::make_pair(N->getOpcode(),
570                                       std::make_pair(Ops[0],
571                                                      N->getValueType(0)))];
572     } else if (N->getNumOperands() == 2) {
573       return &BinaryOps[std::make_pair(N->getOpcode(),
574                                        std::make_pair(Ops[0], Ops[1]))];
575     } else {
576       return &OneResultNodes[std::make_pair(N->getOpcode(),
577                                             std::make_pair(N->getValueType(0),
578                                                            Ops))];
579     }
580   } else {  
581     if (N->getOpcode() == ISD::LOAD) {
582       return &Loads[std::make_pair(Ops[1],
583                                    std::make_pair(Ops[0], N->getValueType(0)))];
584     } else {
585       std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
586       return &ArbitraryNodes[std::make_pair(N->getOpcode(),
587                                             std::make_pair(RV, Ops))];
588     }
589   }
590   return 0;
591 }
592
593
594 SelectionDAG::~SelectionDAG() {
595   while (!AllNodes.empty()) {
596     SDNode *N = AllNodes.begin();
597     delete [] N->OperandList;
598     N->OperandList = 0;
599     N->NumOperands = 0;
600     AllNodes.pop_front();
601   }
602 }
603
604 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
605   if (Op.getValueType() == VT) return Op;
606   int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
607   return getNode(ISD::AND, Op.getValueType(), Op,
608                  getConstant(Imm, Op.getValueType()));
609 }
610
611 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
612   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
613   // Mask out any bits that are not valid for this constant.
614   if (VT != MVT::i64)
615     Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
616
617   SDNode *&N = Constants[std::make_pair(Val, VT)];
618   if (N) return SDOperand(N, 0);
619   N = new ConstantSDNode(false, Val, VT);
620   AllNodes.push_back(N);
621   return SDOperand(N, 0);
622 }
623
624 SDOperand SelectionDAG::getString(const std::string &Val) {
625   StringSDNode *&N = StringNodes[Val];
626   if (!N) {
627     N = new StringSDNode(Val);
628     AllNodes.push_back(N);
629   }
630   return SDOperand(N, 0);
631 }
632
633 SDOperand SelectionDAG::getTargetConstant(uint64_t Val, MVT::ValueType VT) {
634   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
635   // Mask out any bits that are not valid for this constant.
636   if (VT != MVT::i64)
637     Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
638   
639   SDNode *&N = TargetConstants[std::make_pair(Val, VT)];
640   if (N) return SDOperand(N, 0);
641   N = new ConstantSDNode(true, Val, VT);
642   AllNodes.push_back(N);
643   return SDOperand(N, 0);
644 }
645
646 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
647   assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
648   if (VT == MVT::f32)
649     Val = (float)Val;  // Mask out extra precision.
650
651   // Do the map lookup using the actual bit pattern for the floating point
652   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
653   // we don't have issues with SNANs.
654   SDNode *&N = ConstantFPs[std::make_pair(DoubleToBits(Val), VT)];
655   if (N) return SDOperand(N, 0);
656   N = new ConstantFPSDNode(false, Val, VT);
657   AllNodes.push_back(N);
658   return SDOperand(N, 0);
659 }
660
661 SDOperand SelectionDAG::getTargetConstantFP(double Val, MVT::ValueType VT) {
662   assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
663   if (VT == MVT::f32)
664     Val = (float)Val;  // Mask out extra precision.
665   
666   // Do the map lookup using the actual bit pattern for the floating point
667   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
668   // we don't have issues with SNANs.
669   SDNode *&N = TargetConstantFPs[std::make_pair(DoubleToBits(Val), VT)];
670   if (N) return SDOperand(N, 0);
671   N = new ConstantFPSDNode(true, Val, VT);
672   AllNodes.push_back(N);
673   return SDOperand(N, 0);
674 }
675
676 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
677                                          MVT::ValueType VT, int offset) {
678   SDNode *&N = GlobalValues[std::make_pair(GV, offset)];
679   if (N) return SDOperand(N, 0);
680   N = new GlobalAddressSDNode(false, GV, VT, offset);
681   AllNodes.push_back(N);
682   return SDOperand(N, 0);
683 }
684
685 SDOperand SelectionDAG::getTargetGlobalAddress(const GlobalValue *GV,
686                                                MVT::ValueType VT, int offset) {
687   SDNode *&N = TargetGlobalValues[std::make_pair(GV, offset)];
688   if (N) return SDOperand(N, 0);
689   N = new GlobalAddressSDNode(true, GV, VT, offset);
690   AllNodes.push_back(N);
691   return SDOperand(N, 0);
692 }
693
694 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
695   SDNode *&N = FrameIndices[FI];
696   if (N) return SDOperand(N, 0);
697   N = new FrameIndexSDNode(FI, VT, false);
698   AllNodes.push_back(N);
699   return SDOperand(N, 0);
700 }
701
702 SDOperand SelectionDAG::getTargetFrameIndex(int FI, MVT::ValueType VT) {
703   SDNode *&N = TargetFrameIndices[FI];
704   if (N) return SDOperand(N, 0);
705   N = new FrameIndexSDNode(FI, VT, true);
706   AllNodes.push_back(N);
707   return SDOperand(N, 0);
708 }
709
710 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
711                                         unsigned Alignment,  int Offset) {
712   SDNode *&N = ConstantPoolIndices[std::make_pair(C,
713                                             std::make_pair(Offset, Alignment))];
714   if (N) return SDOperand(N, 0);
715   N = new ConstantPoolSDNode(false, C, VT, Offset, Alignment);
716   AllNodes.push_back(N);
717   return SDOperand(N, 0);
718 }
719
720 SDOperand SelectionDAG::getTargetConstantPool(Constant *C, MVT::ValueType VT,
721                                              unsigned Alignment,  int Offset) {
722   SDNode *&N = TargetConstantPoolIndices[std::make_pair(C,
723                                             std::make_pair(Offset, Alignment))];
724   if (N) return SDOperand(N, 0);
725   N = new ConstantPoolSDNode(true, C, VT, Offset, Alignment);
726   AllNodes.push_back(N);
727   return SDOperand(N, 0);
728 }
729
730 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
731   SDNode *&N = BBNodes[MBB];
732   if (N) return SDOperand(N, 0);
733   N = new BasicBlockSDNode(MBB);
734   AllNodes.push_back(N);
735   return SDOperand(N, 0);
736 }
737
738 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
739   if ((unsigned)VT >= ValueTypeNodes.size())
740     ValueTypeNodes.resize(VT+1);
741   if (ValueTypeNodes[VT] == 0) {
742     ValueTypeNodes[VT] = new VTSDNode(VT);
743     AllNodes.push_back(ValueTypeNodes[VT]);
744   }
745
746   return SDOperand(ValueTypeNodes[VT], 0);
747 }
748
749 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
750   SDNode *&N = ExternalSymbols[Sym];
751   if (N) return SDOperand(N, 0);
752   N = new ExternalSymbolSDNode(false, Sym, VT);
753   AllNodes.push_back(N);
754   return SDOperand(N, 0);
755 }
756
757 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
758                                                 MVT::ValueType VT) {
759   SDNode *&N = TargetExternalSymbols[Sym];
760   if (N) return SDOperand(N, 0);
761   N = new ExternalSymbolSDNode(true, Sym, VT);
762   AllNodes.push_back(N);
763   return SDOperand(N, 0);
764 }
765
766 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
767   if ((unsigned)Cond >= CondCodeNodes.size())
768     CondCodeNodes.resize(Cond+1);
769   
770   if (CondCodeNodes[Cond] == 0) {
771     CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
772     AllNodes.push_back(CondCodeNodes[Cond]);
773   }
774   return SDOperand(CondCodeNodes[Cond], 0);
775 }
776
777 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
778   RegisterSDNode *&Reg = RegNodes[std::make_pair(RegNo, VT)];
779   if (!Reg) {
780     Reg = new RegisterSDNode(RegNo, VT);
781     AllNodes.push_back(Reg);
782   }
783   return SDOperand(Reg, 0);
784 }
785
786 SDOperand SelectionDAG::SimplifySetCC(MVT::ValueType VT, SDOperand N1,
787                                       SDOperand N2, ISD::CondCode Cond) {
788   // These setcc operations always fold.
789   switch (Cond) {
790   default: break;
791   case ISD::SETFALSE:
792   case ISD::SETFALSE2: return getConstant(0, VT);
793   case ISD::SETTRUE:
794   case ISD::SETTRUE2:  return getConstant(1, VT);
795   }
796
797   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
798     uint64_t C2 = N2C->getValue();
799     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
800       uint64_t C1 = N1C->getValue();
801
802       // Sign extend the operands if required
803       if (ISD::isSignedIntSetCC(Cond)) {
804         C1 = N1C->getSignExtended();
805         C2 = N2C->getSignExtended();
806       }
807
808       switch (Cond) {
809       default: assert(0 && "Unknown integer setcc!");
810       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
811       case ISD::SETNE:  return getConstant(C1 != C2, VT);
812       case ISD::SETULT: return getConstant(C1 <  C2, VT);
813       case ISD::SETUGT: return getConstant(C1 >  C2, VT);
814       case ISD::SETULE: return getConstant(C1 <= C2, VT);
815       case ISD::SETUGE: return getConstant(C1 >= C2, VT);
816       case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
817       case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
818       case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
819       case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
820       }
821     } else {
822       // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
823       if (N1.getOpcode() == ISD::ZERO_EXTEND) {
824         unsigned InSize = MVT::getSizeInBits(N1.getOperand(0).getValueType());
825
826         // If the comparison constant has bits in the upper part, the
827         // zero-extended value could never match.
828         if (C2 & (~0ULL << InSize)) {
829           unsigned VSize = MVT::getSizeInBits(N1.getValueType());
830           switch (Cond) {
831           case ISD::SETUGT:
832           case ISD::SETUGE:
833           case ISD::SETEQ: return getConstant(0, VT);
834           case ISD::SETULT:
835           case ISD::SETULE:
836           case ISD::SETNE: return getConstant(1, VT);
837           case ISD::SETGT:
838           case ISD::SETGE:
839             // True if the sign bit of C2 is set.
840             return getConstant((C2 & (1ULL << VSize)) != 0, VT);
841           case ISD::SETLT:
842           case ISD::SETLE:
843             // True if the sign bit of C2 isn't set.
844             return getConstant((C2 & (1ULL << VSize)) == 0, VT);
845           default:
846             break;
847           }
848         }
849
850         // Otherwise, we can perform the comparison with the low bits.
851         switch (Cond) {
852         case ISD::SETEQ:
853         case ISD::SETNE:
854         case ISD::SETUGT:
855         case ISD::SETUGE:
856         case ISD::SETULT:
857         case ISD::SETULE:
858           return getSetCC(VT, N1.getOperand(0),
859                           getConstant(C2, N1.getOperand(0).getValueType()),
860                           Cond);
861         default:
862           break;   // todo, be more careful with signed comparisons
863         }
864       } else if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
865                  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
866         MVT::ValueType ExtSrcTy = cast<VTSDNode>(N1.getOperand(1))->getVT();
867         unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
868         MVT::ValueType ExtDstTy = N1.getValueType();
869         unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
870
871         // If the extended part has any inconsistent bits, it cannot ever
872         // compare equal.  In other words, they have to be all ones or all
873         // zeros.
874         uint64_t ExtBits =
875           (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
876         if ((C2 & ExtBits) != 0 && (C2 & ExtBits) != ExtBits)
877           return getConstant(Cond == ISD::SETNE, VT);
878         
879         // Otherwise, make this a use of a zext.
880         return getSetCC(VT, getZeroExtendInReg(N1.getOperand(0), ExtSrcTy),
881                         getConstant(C2 & (~0ULL>>(64-ExtSrcTyBits)), ExtDstTy),
882                         Cond);
883       }
884
885       uint64_t MinVal, MaxVal;
886       unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
887       if (ISD::isSignedIntSetCC(Cond)) {
888         MinVal = 1ULL << (OperandBitSize-1);
889         if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
890           MaxVal = ~0ULL >> (65-OperandBitSize);
891         else
892           MaxVal = 0;
893       } else {
894         MinVal = 0;
895         MaxVal = ~0ULL >> (64-OperandBitSize);
896       }
897
898       // Canonicalize GE/LE comparisons to use GT/LT comparisons.
899       if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
900         if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
901         --C2;                                          // X >= C1 --> X > (C1-1)
902         return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
903                         (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
904       }
905
906       if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
907         if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
908         ++C2;                                          // X <= C1 --> X < (C1+1)
909         return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
910                         (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
911       }
912
913       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
914         return getConstant(0, VT);      // X < MIN --> false
915
916       // Canonicalize setgt X, Min --> setne X, Min
917       if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
918         return getSetCC(VT, N1, N2, ISD::SETNE);
919
920       // If we have setult X, 1, turn it into seteq X, 0
921       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
922         return getSetCC(VT, N1, getConstant(MinVal, N1.getValueType()),
923                         ISD::SETEQ);
924       // If we have setugt X, Max-1, turn it into seteq X, Max
925       else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
926         return getSetCC(VT, N1, getConstant(MaxVal, N1.getValueType()),
927                         ISD::SETEQ);
928
929       // If we have "setcc X, C1", check to see if we can shrink the immediate
930       // by changing cc.
931
932       // SETUGT X, SINTMAX  -> SETLT X, 0
933       if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
934           C2 == (~0ULL >> (65-OperandBitSize)))
935         return getSetCC(VT, N1, getConstant(0, N2.getValueType()), ISD::SETLT);
936
937       // FIXME: Implement the rest of these.
938
939
940       // Fold bit comparisons when we can.
941       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
942           VT == N1.getValueType() && N1.getOpcode() == ISD::AND)
943         if (ConstantSDNode *AndRHS =
944                     dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
945           if (Cond == ISD::SETNE && C2 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
946             // Perform the xform if the AND RHS is a single bit.
947             if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
948               return getNode(ISD::SRL, VT, N1,
949                              getConstant(Log2_64(AndRHS->getValue()),
950                                                    TLI.getShiftAmountTy()));
951             }
952           } else if (Cond == ISD::SETEQ && C2 == AndRHS->getValue()) {
953             // (X & 8) == 8  -->  (X & 8) >> 3
954             // Perform the xform if C2 is a single bit.
955             if ((C2 & (C2-1)) == 0) {
956               return getNode(ISD::SRL, VT, N1,
957                              getConstant(Log2_64(C2),TLI.getShiftAmountTy()));
958             }
959           }
960         }
961     }
962   } else if (isa<ConstantSDNode>(N1.Val)) {
963       // Ensure that the constant occurs on the RHS.
964     return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
965   }
966
967   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
968     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
969       double C1 = N1C->getValue(), C2 = N2C->getValue();
970
971       switch (Cond) {
972       default: break; // FIXME: Implement the rest of these!
973       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
974       case ISD::SETNE:  return getConstant(C1 != C2, VT);
975       case ISD::SETLT:  return getConstant(C1 < C2, VT);
976       case ISD::SETGT:  return getConstant(C1 > C2, VT);
977       case ISD::SETLE:  return getConstant(C1 <= C2, VT);
978       case ISD::SETGE:  return getConstant(C1 >= C2, VT);
979       }
980     } else {
981       // Ensure that the constant occurs on the RHS.
982       return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
983     }
984
985   // Could not fold it.
986   return SDOperand();
987 }
988
989 /// getNode - Gets or creates the specified node.
990 ///
991 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
992   SDNode *&N = NullaryOps[std::make_pair(Opcode, VT)];
993   if (!N) {
994     N = new SDNode(Opcode, VT);
995     AllNodes.push_back(N);
996   }
997   return SDOperand(N, 0);
998 }
999
1000 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1001                                 SDOperand Operand) {
1002   unsigned Tmp1;
1003   // Constant fold unary operations with an integer constant operand.
1004   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1005     uint64_t Val = C->getValue();
1006     switch (Opcode) {
1007     default: break;
1008     case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
1009     case ISD::ANY_EXTEND:
1010     case ISD::ZERO_EXTEND: return getConstant(Val, VT);
1011     case ISD::TRUNCATE:    return getConstant(Val, VT);
1012     case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
1013     case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
1014     case ISD::BIT_CONVERT:
1015       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1016         return getConstantFP(BitsToFloat(Val), VT);
1017       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1018         return getConstantFP(BitsToDouble(Val), VT);
1019       break;
1020     case ISD::BSWAP:
1021       switch(VT) {
1022       default: assert(0 && "Invalid bswap!"); break;
1023       case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
1024       case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
1025       case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
1026       }
1027       break;
1028     case ISD::CTPOP:
1029       switch(VT) {
1030       default: assert(0 && "Invalid ctpop!"); break;
1031       case MVT::i1: return getConstant(Val != 0, VT);
1032       case MVT::i8: 
1033         Tmp1 = (unsigned)Val & 0xFF;
1034         return getConstant(CountPopulation_32(Tmp1), VT);
1035       case MVT::i16:
1036         Tmp1 = (unsigned)Val & 0xFFFF;
1037         return getConstant(CountPopulation_32(Tmp1), VT);
1038       case MVT::i32:
1039         return getConstant(CountPopulation_32((unsigned)Val), VT);
1040       case MVT::i64:
1041         return getConstant(CountPopulation_64(Val), VT);
1042       }
1043     case ISD::CTLZ:
1044       switch(VT) {
1045       default: assert(0 && "Invalid ctlz!"); break;
1046       case MVT::i1: return getConstant(Val == 0, VT);
1047       case MVT::i8: 
1048         Tmp1 = (unsigned)Val & 0xFF;
1049         return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
1050       case MVT::i16:
1051         Tmp1 = (unsigned)Val & 0xFFFF;
1052         return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
1053       case MVT::i32:
1054         return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
1055       case MVT::i64:
1056         return getConstant(CountLeadingZeros_64(Val), VT);
1057       }
1058     case ISD::CTTZ:
1059       switch(VT) {
1060       default: assert(0 && "Invalid cttz!"); break;
1061       case MVT::i1: return getConstant(Val == 0, VT);
1062       case MVT::i8: 
1063         Tmp1 = (unsigned)Val | 0x100;
1064         return getConstant(CountTrailingZeros_32(Tmp1), VT);
1065       case MVT::i16:
1066         Tmp1 = (unsigned)Val | 0x10000;
1067         return getConstant(CountTrailingZeros_32(Tmp1), VT);
1068       case MVT::i32:
1069         return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
1070       case MVT::i64:
1071         return getConstant(CountTrailingZeros_64(Val), VT);
1072       }
1073     }
1074   }
1075
1076   // Constant fold unary operations with an floating point constant operand.
1077   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
1078     switch (Opcode) {
1079     case ISD::FNEG:
1080       return getConstantFP(-C->getValue(), VT);
1081     case ISD::FABS:
1082       return getConstantFP(fabs(C->getValue()), VT);
1083     case ISD::FP_ROUND:
1084     case ISD::FP_EXTEND:
1085       return getConstantFP(C->getValue(), VT);
1086     case ISD::FP_TO_SINT:
1087       return getConstant((int64_t)C->getValue(), VT);
1088     case ISD::FP_TO_UINT:
1089       return getConstant((uint64_t)C->getValue(), VT);
1090     case ISD::BIT_CONVERT:
1091       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1092         return getConstant(FloatToBits(C->getValue()), VT);
1093       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1094         return getConstant(DoubleToBits(C->getValue()), VT);
1095       break;
1096     }
1097
1098   unsigned OpOpcode = Operand.Val->getOpcode();
1099   switch (Opcode) {
1100   case ISD::TokenFactor:
1101     return Operand;         // Factor of one node?  No factor.
1102   case ISD::SIGN_EXTEND:
1103     if (Operand.getValueType() == VT) return Operand;   // noop extension
1104     assert(Operand.getValueType() < VT && "Invalid sext node, dst < src!");
1105     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1106       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1107     break;
1108   case ISD::ZERO_EXTEND:
1109     if (Operand.getValueType() == VT) return Operand;   // noop extension
1110     assert(Operand.getValueType() < VT && "Invalid zext node, dst < src!");
1111     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
1112       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1113     break;
1114   case ISD::ANY_EXTEND:
1115     if (Operand.getValueType() == VT) return Operand;   // noop extension
1116     assert(Operand.getValueType() < VT && "Invalid anyext node, dst < src!");
1117     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1118       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
1119       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1120     break;
1121   case ISD::TRUNCATE:
1122     if (Operand.getValueType() == VT) return Operand;   // noop truncate
1123     assert(Operand.getValueType() > VT && "Invalid truncate node, src < dst!");
1124     if (OpOpcode == ISD::TRUNCATE)
1125       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1126     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1127              OpOpcode == ISD::ANY_EXTEND) {
1128       // If the source is smaller than the dest, we still need an extend.
1129       if (Operand.Val->getOperand(0).getValueType() < VT)
1130         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1131       else if (Operand.Val->getOperand(0).getValueType() > VT)
1132         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1133       else
1134         return Operand.Val->getOperand(0);
1135     }
1136     break;
1137   case ISD::BIT_CONVERT:
1138     // Basic sanity checking.
1139     assert((Operand.getValueType() == MVT::Vector ||   // FIXME: This is a hack.
1140            MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType()))
1141            && "Cannot BIT_CONVERT between two different types!");
1142     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
1143     if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
1144       return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1145     break;
1146   case ISD::SCALAR_TO_VECTOR:
1147     assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1148            MVT::getVectorBaseType(VT) == Operand.getValueType() &&
1149            "Illegal SCALAR_TO_VECTOR node!");
1150     break;
1151   case ISD::FNEG:
1152     if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
1153       return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1154                      Operand.Val->getOperand(0));
1155     if (OpOpcode == ISD::FNEG)  // --X -> X
1156       return Operand.Val->getOperand(0);
1157     break;
1158   case ISD::FABS:
1159     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
1160       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1161     break;
1162   }
1163
1164   SDNode *N;
1165   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1166     SDNode *&E = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
1167     if (E) return SDOperand(E, 0);
1168     E = N = new SDNode(Opcode, Operand);
1169   } else {
1170     N = new SDNode(Opcode, Operand);
1171   }
1172   N->setValueTypes(VT);
1173   AllNodes.push_back(N);
1174   return SDOperand(N, 0);
1175 }
1176
1177
1178
1179 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1180                                 SDOperand N1, SDOperand N2) {
1181 #ifndef NDEBUG
1182   switch (Opcode) {
1183   case ISD::TokenFactor:
1184     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1185            N2.getValueType() == MVT::Other && "Invalid token factor!");
1186     break;
1187   case ISD::AND:
1188   case ISD::OR:
1189   case ISD::XOR:
1190   case ISD::UDIV:
1191   case ISD::UREM:
1192   case ISD::MULHU:
1193   case ISD::MULHS:
1194     assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1195     // fall through
1196   case ISD::ADD:
1197   case ISD::SUB:
1198   case ISD::MUL:
1199   case ISD::SDIV:
1200   case ISD::SREM:
1201     assert(MVT::isInteger(N1.getValueType()) && "Should use F* for FP ops");
1202     // fall through.
1203   case ISD::FADD:
1204   case ISD::FSUB:
1205   case ISD::FMUL:
1206   case ISD::FDIV:
1207   case ISD::FREM:
1208     assert(N1.getValueType() == N2.getValueType() &&
1209            N1.getValueType() == VT && "Binary operator types must match!");
1210     break;
1211   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
1212     assert(N1.getValueType() == VT &&
1213            MVT::isFloatingPoint(N1.getValueType()) && 
1214            MVT::isFloatingPoint(N2.getValueType()) &&
1215            "Invalid FCOPYSIGN!");
1216     break;
1217   case ISD::SHL:
1218   case ISD::SRA:
1219   case ISD::SRL:
1220   case ISD::ROTL:
1221   case ISD::ROTR:
1222     assert(VT == N1.getValueType() &&
1223            "Shift operators return type must be the same as their first arg");
1224     assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1225            VT != MVT::i1 && "Shifts only work on integers");
1226     break;
1227   case ISD::FP_ROUND_INREG: {
1228     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1229     assert(VT == N1.getValueType() && "Not an inreg round!");
1230     assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1231            "Cannot FP_ROUND_INREG integer types");
1232     assert(EVT <= VT && "Not rounding down!");
1233     break;
1234   }
1235   case ISD::AssertSext:
1236   case ISD::AssertZext:
1237   case ISD::SIGN_EXTEND_INREG: {
1238     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1239     assert(VT == N1.getValueType() && "Not an inreg extend!");
1240     assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1241            "Cannot *_EXTEND_INREG FP types");
1242     assert(EVT <= VT && "Not extending!");
1243   }
1244
1245   default: break;
1246   }
1247 #endif
1248
1249   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1250   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1251   if (N1C) {
1252     if (N2C) {
1253       uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
1254       switch (Opcode) {
1255       case ISD::ADD: return getConstant(C1 + C2, VT);
1256       case ISD::SUB: return getConstant(C1 - C2, VT);
1257       case ISD::MUL: return getConstant(C1 * C2, VT);
1258       case ISD::UDIV:
1259         if (C2) return getConstant(C1 / C2, VT);
1260         break;
1261       case ISD::UREM :
1262         if (C2) return getConstant(C1 % C2, VT);
1263         break;
1264       case ISD::SDIV :
1265         if (C2) return getConstant(N1C->getSignExtended() /
1266                                    N2C->getSignExtended(), VT);
1267         break;
1268       case ISD::SREM :
1269         if (C2) return getConstant(N1C->getSignExtended() %
1270                                    N2C->getSignExtended(), VT);
1271         break;
1272       case ISD::AND  : return getConstant(C1 & C2, VT);
1273       case ISD::OR   : return getConstant(C1 | C2, VT);
1274       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
1275       case ISD::SHL  : return getConstant(C1 << C2, VT);
1276       case ISD::SRL  : return getConstant(C1 >> C2, VT);
1277       case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
1278       case ISD::ROTL : 
1279         return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
1280                            VT);
1281       case ISD::ROTR : 
1282         return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)), 
1283                            VT);
1284       default: break;
1285       }
1286     } else {      // Cannonicalize constant to RHS if commutative
1287       if (isCommutativeBinOp(Opcode)) {
1288         std::swap(N1C, N2C);
1289         std::swap(N1, N2);
1290       }
1291     }
1292   }
1293
1294   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1295   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1296   if (N1CFP) {
1297     if (N2CFP) {
1298       double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1299       switch (Opcode) {
1300       case ISD::FADD: return getConstantFP(C1 + C2, VT);
1301       case ISD::FSUB: return getConstantFP(C1 - C2, VT);
1302       case ISD::FMUL: return getConstantFP(C1 * C2, VT);
1303       case ISD::FDIV:
1304         if (C2) return getConstantFP(C1 / C2, VT);
1305         break;
1306       case ISD::FREM :
1307         if (C2) return getConstantFP(fmod(C1, C2), VT);
1308         break;
1309       case ISD::FCOPYSIGN: {
1310         union {
1311           double   F;
1312           uint64_t I;
1313         } u1;
1314         union {
1315           double  F;
1316           int64_t I;
1317         } u2;
1318         u1.F = C1;
1319         u2.F = C2;
1320         if (u2.I < 0)  // Sign bit of RHS set?
1321           u1.I |= 1ULL << 63;      // Set the sign bit of the LHS.
1322         else 
1323           u1.I &= (1ULL << 63)-1;  // Clear the sign bit of the LHS.
1324         return getConstantFP(u1.F, VT);
1325       }
1326       default: break;
1327       }
1328     } else {      // Cannonicalize constant to RHS if commutative
1329       if (isCommutativeBinOp(Opcode)) {
1330         std::swap(N1CFP, N2CFP);
1331         std::swap(N1, N2);
1332       }
1333     }
1334   }
1335
1336   // Finally, fold operations that do not require constants.
1337   switch (Opcode) {
1338   case ISD::FP_ROUND_INREG:
1339     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
1340     break;
1341   case ISD::SIGN_EXTEND_INREG: {
1342     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1343     if (EVT == VT) return N1;  // Not actually extending
1344     break;
1345   }
1346
1347   // FIXME: figure out how to safely handle things like
1348   // int foo(int x) { return 1 << (x & 255); }
1349   // int bar() { return foo(256); }
1350 #if 0
1351   case ISD::SHL:
1352   case ISD::SRL:
1353   case ISD::SRA:
1354     if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1355         cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
1356       return getNode(Opcode, VT, N1, N2.getOperand(0));
1357     else if (N2.getOpcode() == ISD::AND)
1358       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1359         // If the and is only masking out bits that cannot effect the shift,
1360         // eliminate the and.
1361         unsigned NumBits = MVT::getSizeInBits(VT);
1362         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1363           return getNode(Opcode, VT, N1, N2.getOperand(0));
1364       }
1365     break;
1366 #endif
1367   }
1368
1369   // Memoize this node if possible.
1370   SDNode *N;
1371   if (VT != MVT::Flag) {
1372     SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
1373     if (BON) return SDOperand(BON, 0);
1374
1375     BON = N = new SDNode(Opcode, N1, N2);
1376   } else {
1377     N = new SDNode(Opcode, N1, N2);
1378   }
1379
1380   N->setValueTypes(VT);
1381   AllNodes.push_back(N);
1382   return SDOperand(N, 0);
1383 }
1384
1385 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1386                                 SDOperand N1, SDOperand N2, SDOperand N3) {
1387   // Perform various simplifications.
1388   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1389   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1390   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1391   switch (Opcode) {
1392   case ISD::SETCC: {
1393     // Use SimplifySetCC  to simplify SETCC's.
1394     SDOperand Simp = SimplifySetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
1395     if (Simp.Val) return Simp;
1396     break;
1397   }
1398   case ISD::SELECT:
1399     if (N1C)
1400       if (N1C->getValue())
1401         return N2;             // select true, X, Y -> X
1402       else
1403         return N3;             // select false, X, Y -> Y
1404
1405     if (N2 == N3) return N2;   // select C, X, X -> X
1406     break;
1407   case ISD::BRCOND:
1408     if (N2C)
1409       if (N2C->getValue()) // Unconditional branch
1410         return getNode(ISD::BR, MVT::Other, N1, N3);
1411       else
1412         return N1;         // Never-taken branch
1413     break;
1414   case ISD::VECTOR_SHUFFLE:
1415     assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1416            MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
1417            N3.getOpcode() == ISD::BUILD_VECTOR &&
1418            MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
1419            "Illegal VECTOR_SHUFFLE node!");
1420     break;
1421   }
1422
1423   std::vector<SDOperand> Ops;
1424   Ops.reserve(3);
1425   Ops.push_back(N1);
1426   Ops.push_back(N2);
1427   Ops.push_back(N3);
1428
1429   // Memoize node if it doesn't produce a flag.
1430   SDNode *N;
1431   if (VT != MVT::Flag) {
1432     SDNode *&E = OneResultNodes[std::make_pair(Opcode,std::make_pair(VT, Ops))];
1433     if (E) return SDOperand(E, 0);
1434     E = N = new SDNode(Opcode, N1, N2, N3);
1435   } else {
1436     N = new SDNode(Opcode, N1, N2, N3);
1437   }
1438   N->setValueTypes(VT);
1439   AllNodes.push_back(N);
1440   return SDOperand(N, 0);
1441 }
1442
1443 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1444                                 SDOperand N1, SDOperand N2, SDOperand N3,
1445                                 SDOperand N4) {
1446   std::vector<SDOperand> Ops;
1447   Ops.reserve(4);
1448   Ops.push_back(N1);
1449   Ops.push_back(N2);
1450   Ops.push_back(N3);
1451   Ops.push_back(N4);
1452   return getNode(Opcode, VT, Ops);
1453 }
1454
1455 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1456                                 SDOperand N1, SDOperand N2, SDOperand N3,
1457                                 SDOperand N4, SDOperand N5) {
1458   std::vector<SDOperand> Ops;
1459   Ops.reserve(5);
1460   Ops.push_back(N1);
1461   Ops.push_back(N2);
1462   Ops.push_back(N3);
1463   Ops.push_back(N4);
1464   Ops.push_back(N5);
1465   return getNode(Opcode, VT, Ops);
1466 }
1467
1468 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1469                                 SDOperand Chain, SDOperand Ptr,
1470                                 SDOperand SV) {
1471   SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
1472   if (N) return SDOperand(N, 0);
1473   N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
1474
1475   // Loads have a token chain.
1476   setNodeValueTypes(N, VT, MVT::Other);
1477   AllNodes.push_back(N);
1478   return SDOperand(N, 0);
1479 }
1480
1481 SDOperand SelectionDAG::getVecLoad(unsigned Count, MVT::ValueType EVT,
1482                                    SDOperand Chain, SDOperand Ptr,
1483                                    SDOperand SV) {
1484   SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, EVT))];
1485   if (N) return SDOperand(N, 0);
1486   std::vector<SDOperand> Ops;
1487   Ops.reserve(5);
1488   Ops.push_back(Chain);
1489   Ops.push_back(Ptr);
1490   Ops.push_back(SV);
1491   Ops.push_back(getConstant(Count, MVT::i32));
1492   Ops.push_back(getValueType(EVT));
1493   std::vector<MVT::ValueType> VTs;
1494   VTs.reserve(2);
1495   VTs.push_back(MVT::Vector); VTs.push_back(MVT::Other);  // Add token chain.
1496   return getNode(ISD::VLOAD, VTs, Ops);
1497 }
1498
1499 SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT,
1500                                    SDOperand Chain, SDOperand Ptr, SDOperand SV,
1501                                    MVT::ValueType EVT) {
1502   std::vector<SDOperand> Ops;
1503   Ops.reserve(4);
1504   Ops.push_back(Chain);
1505   Ops.push_back(Ptr);
1506   Ops.push_back(SV);
1507   Ops.push_back(getValueType(EVT));
1508   std::vector<MVT::ValueType> VTs;
1509   VTs.reserve(2);
1510   VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1511   return getNode(Opcode, VTs, Ops);
1512 }
1513
1514 SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
1515   assert((!V || isa<PointerType>(V->getType())) &&
1516          "SrcValue is not a pointer?");
1517   SDNode *&N = ValueNodes[std::make_pair(V, Offset)];
1518   if (N) return SDOperand(N, 0);
1519
1520   N = new SrcValueSDNode(V, Offset);
1521   AllNodes.push_back(N);
1522   return SDOperand(N, 0);
1523 }
1524
1525 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
1526                                  SDOperand Chain, SDOperand Ptr,
1527                                  SDOperand SV) {
1528   std::vector<SDOperand> Ops;
1529   Ops.reserve(3);
1530   Ops.push_back(Chain);
1531   Ops.push_back(Ptr);
1532   Ops.push_back(SV);
1533   std::vector<MVT::ValueType> VTs;
1534   VTs.reserve(2);
1535   VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1536   return getNode(ISD::VAARG, VTs, Ops);
1537 }
1538
1539 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1540                                 std::vector<SDOperand> &Ops) {
1541   switch (Ops.size()) {
1542   case 0: return getNode(Opcode, VT);
1543   case 1: return getNode(Opcode, VT, Ops[0]);
1544   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
1545   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
1546   default: break;
1547   }
1548   
1549   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Ops[1].Val);
1550   switch (Opcode) {
1551   default: break;
1552   case ISD::TRUNCSTORE: {
1553     assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
1554     MVT::ValueType EVT = cast<VTSDNode>(Ops[4])->getVT();
1555 #if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1556     // If this is a truncating store of a constant, convert to the desired type
1557     // and store it instead.
1558     if (isa<Constant>(Ops[0])) {
1559       SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1560       if (isa<Constant>(Op))
1561         N1 = Op;
1562     }
1563     // Also for ConstantFP?
1564 #endif
1565     if (Ops[0].getValueType() == EVT)       // Normal store?
1566       return getNode(ISD::STORE, VT, Ops[0], Ops[1], Ops[2], Ops[3]);
1567     assert(Ops[1].getValueType() > EVT && "Not a truncation?");
1568     assert(MVT::isInteger(Ops[1].getValueType()) == MVT::isInteger(EVT) &&
1569            "Can't do FP-INT conversion!");
1570     break;
1571   }
1572   case ISD::SELECT_CC: {
1573     assert(Ops.size() == 5 && "SELECT_CC takes 5 operands!");
1574     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
1575            "LHS and RHS of condition must have same type!");
1576     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1577            "True and False arms of SelectCC must have same type!");
1578     assert(Ops[2].getValueType() == VT &&
1579            "select_cc node must be of same type as true and false value!");
1580     break;
1581   }
1582   case ISD::BR_CC: {
1583     assert(Ops.size() == 5 && "BR_CC takes 5 operands!");
1584     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1585            "LHS/RHS of comparison should match types!");
1586     break;
1587   }
1588   }
1589
1590   // Memoize nodes.
1591   SDNode *N;
1592   if (VT != MVT::Flag) {
1593     SDNode *&E =
1594       OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
1595     if (E) return SDOperand(E, 0);
1596     E = N = new SDNode(Opcode, Ops);
1597   } else {
1598     N = new SDNode(Opcode, Ops);
1599   }
1600   N->setValueTypes(VT);
1601   AllNodes.push_back(N);
1602   return SDOperand(N, 0);
1603 }
1604
1605 SDOperand SelectionDAG::getNode(unsigned Opcode,
1606                                 std::vector<MVT::ValueType> &ResultTys,
1607                                 std::vector<SDOperand> &Ops) {
1608   if (ResultTys.size() == 1)
1609     return getNode(Opcode, ResultTys[0], Ops);
1610
1611   switch (Opcode) {
1612   case ISD::EXTLOAD:
1613   case ISD::SEXTLOAD:
1614   case ISD::ZEXTLOAD: {
1615     MVT::ValueType EVT = cast<VTSDNode>(Ops[3])->getVT();
1616     assert(Ops.size() == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!");
1617     // If they are asking for an extending load from/to the same thing, return a
1618     // normal load.
1619     if (ResultTys[0] == EVT)
1620       return getLoad(ResultTys[0], Ops[0], Ops[1], Ops[2]);
1621     if (MVT::isVector(ResultTys[0])) {
1622       assert(EVT == MVT::getVectorBaseType(ResultTys[0]) &&
1623              "Invalid vector extload!");
1624     } else {
1625       assert(EVT < ResultTys[0] &&
1626              "Should only be an extending load, not truncating!");
1627     }
1628     assert((Opcode == ISD::EXTLOAD || MVT::isInteger(ResultTys[0])) &&
1629            "Cannot sign/zero extend a FP/Vector load!");
1630     assert(MVT::isInteger(ResultTys[0]) == MVT::isInteger(EVT) &&
1631            "Cannot convert from FP to Int or Int -> FP!");
1632     break;
1633   }
1634
1635   // FIXME: figure out how to safely handle things like
1636   // int foo(int x) { return 1 << (x & 255); }
1637   // int bar() { return foo(256); }
1638 #if 0
1639   case ISD::SRA_PARTS:
1640   case ISD::SRL_PARTS:
1641   case ISD::SHL_PARTS:
1642     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1643         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
1644       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1645     else if (N3.getOpcode() == ISD::AND)
1646       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1647         // If the and is only masking out bits that cannot effect the shift,
1648         // eliminate the and.
1649         unsigned NumBits = MVT::getSizeInBits(VT)*2;
1650         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1651           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1652       }
1653     break;
1654 #endif
1655   }
1656
1657   // Memoize the node unless it returns a flag.
1658   SDNode *N;
1659   if (ResultTys.back() != MVT::Flag) {
1660     SDNode *&E =
1661       ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys, Ops))];
1662     if (E) return SDOperand(E, 0);
1663     E = N = new SDNode(Opcode, Ops);
1664   } else {
1665     N = new SDNode(Opcode, Ops);
1666   }
1667   setNodeValueTypes(N, ResultTys);
1668   AllNodes.push_back(N);
1669   return SDOperand(N, 0);
1670 }
1671
1672 void SelectionDAG::setNodeValueTypes(SDNode *N, 
1673                                      std::vector<MVT::ValueType> &RetVals) {
1674   switch (RetVals.size()) {
1675   case 0: return;
1676   case 1: N->setValueTypes(RetVals[0]); return;
1677   case 2: setNodeValueTypes(N, RetVals[0], RetVals[1]); return;
1678   default: break;
1679   }
1680   
1681   std::list<std::vector<MVT::ValueType> >::iterator I =
1682     std::find(VTList.begin(), VTList.end(), RetVals);
1683   if (I == VTList.end()) {
1684     VTList.push_front(RetVals);
1685     I = VTList.begin();
1686   }
1687
1688   N->setValueTypes(&(*I)[0], I->size());
1689 }
1690
1691 void SelectionDAG::setNodeValueTypes(SDNode *N, MVT::ValueType VT1, 
1692                                      MVT::ValueType VT2) {
1693   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
1694        E = VTList.end(); I != E; ++I) {
1695     if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2) {
1696       N->setValueTypes(&(*I)[0], 2);
1697       return;
1698     }
1699   }
1700   std::vector<MVT::ValueType> V;
1701   V.push_back(VT1);
1702   V.push_back(VT2);
1703   VTList.push_front(V);
1704   N->setValueTypes(&(*VTList.begin())[0], 2);
1705 }
1706
1707 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
1708 /// specified operands.  If the resultant node already exists in the DAG,
1709 /// this does not modify the specified node, instead it returns the node that
1710 /// already exists.  If the resultant node does not exist in the DAG, the
1711 /// input node is returned.  As a degenerate case, if you specify the same
1712 /// input operands as the node already has, the input node is returned.
1713 SDOperand SelectionDAG::
1714 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
1715   SDNode *N = InN.Val;
1716   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
1717   
1718   // Check to see if there is no change.
1719   if (Op == N->getOperand(0)) return InN;
1720   
1721   // See if the modified node already exists.
1722   SDNode **NewSlot = FindModifiedNodeSlot(N, Op);
1723   if (NewSlot && *NewSlot)
1724     return SDOperand(*NewSlot, InN.ResNo);
1725   
1726   // Nope it doesn't.  Remove the node from it's current place in the maps.
1727   if (NewSlot)
1728     RemoveNodeFromCSEMaps(N);
1729   
1730   // Now we update the operands.
1731   N->OperandList[0].Val->removeUser(N);
1732   Op.Val->addUser(N);
1733   N->OperandList[0] = Op;
1734   
1735   // If this gets put into a CSE map, add it.
1736   if (NewSlot) *NewSlot = N;
1737   return InN;
1738 }
1739
1740 SDOperand SelectionDAG::
1741 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
1742   SDNode *N = InN.Val;
1743   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
1744   
1745   // Check to see if there is no change.
1746   bool AnyChange = false;
1747   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
1748     return InN;   // No operands changed, just return the input node.
1749   
1750   // See if the modified node already exists.
1751   SDNode **NewSlot = FindModifiedNodeSlot(N, Op1, Op2);
1752   if (NewSlot && *NewSlot)
1753     return SDOperand(*NewSlot, InN.ResNo);
1754   
1755   // Nope it doesn't.  Remove the node from it's current place in the maps.
1756   if (NewSlot)
1757     RemoveNodeFromCSEMaps(N);
1758   
1759   // Now we update the operands.
1760   if (N->OperandList[0] != Op1) {
1761     N->OperandList[0].Val->removeUser(N);
1762     Op1.Val->addUser(N);
1763     N->OperandList[0] = Op1;
1764   }
1765   if (N->OperandList[1] != Op2) {
1766     N->OperandList[1].Val->removeUser(N);
1767     Op2.Val->addUser(N);
1768     N->OperandList[1] = Op2;
1769   }
1770   
1771   // If this gets put into a CSE map, add it.
1772   if (NewSlot) *NewSlot = N;
1773   return InN;
1774 }
1775
1776 SDOperand SelectionDAG::
1777 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
1778   std::vector<SDOperand> Ops;
1779   Ops.push_back(Op1);
1780   Ops.push_back(Op2);
1781   Ops.push_back(Op3);
1782   return UpdateNodeOperands(N, Ops);
1783 }
1784
1785 SDOperand SelectionDAG::
1786 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, 
1787                    SDOperand Op3, SDOperand Op4) {
1788   std::vector<SDOperand> Ops;
1789   Ops.push_back(Op1);
1790   Ops.push_back(Op2);
1791   Ops.push_back(Op3);
1792   Ops.push_back(Op4);
1793   return UpdateNodeOperands(N, Ops);
1794 }
1795
1796 SDOperand SelectionDAG::
1797 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
1798                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
1799   std::vector<SDOperand> Ops;
1800   Ops.push_back(Op1);
1801   Ops.push_back(Op2);
1802   Ops.push_back(Op3);
1803   Ops.push_back(Op4);
1804   Ops.push_back(Op5);
1805   return UpdateNodeOperands(N, Ops);
1806 }
1807
1808
1809 SDOperand SelectionDAG::
1810 UpdateNodeOperands(SDOperand InN, const std::vector<SDOperand> &Ops) {
1811   SDNode *N = InN.Val;
1812   assert(N->getNumOperands() == Ops.size() &&
1813          "Update with wrong number of operands");
1814   
1815   // Check to see if there is no change.
1816   unsigned NumOps = Ops.size();
1817   bool AnyChange = false;
1818   for (unsigned i = 0; i != NumOps; ++i) {
1819     if (Ops[i] != N->getOperand(i)) {
1820       AnyChange = true;
1821       break;
1822     }
1823   }
1824   
1825   // No operands changed, just return the input node.
1826   if (!AnyChange) return InN;
1827   
1828   // See if the modified node already exists.
1829   SDNode **NewSlot = FindModifiedNodeSlot(N, Ops);
1830   if (NewSlot && *NewSlot)
1831     return SDOperand(*NewSlot, InN.ResNo);
1832   
1833   // Nope it doesn't.  Remove the node from it's current place in the maps.
1834   if (NewSlot)
1835     RemoveNodeFromCSEMaps(N);
1836   
1837   // Now we update the operands.
1838   for (unsigned i = 0; i != NumOps; ++i) {
1839     if (N->OperandList[i] != Ops[i]) {
1840       N->OperandList[i].Val->removeUser(N);
1841       Ops[i].Val->addUser(N);
1842       N->OperandList[i] = Ops[i];
1843     }
1844   }
1845
1846   // If this gets put into a CSE map, add it.
1847   if (NewSlot) *NewSlot = N;
1848   return InN;
1849 }
1850
1851
1852
1853
1854 /// SelectNodeTo - These are used for target selectors to *mutate* the
1855 /// specified node to have the specified return type, Target opcode, and
1856 /// operands.  Note that target opcodes are stored as
1857 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
1858 ///
1859 /// Note that SelectNodeTo returns the resultant node.  If there is already a
1860 /// node of the specified opcode and operands, it returns that node instead of
1861 /// the current one.
1862 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1863                                      MVT::ValueType VT) {
1864   // If an identical node already exists, use it.
1865   SDNode *&ON = NullaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc, VT)];
1866   if (ON) return SDOperand(ON, 0);
1867   
1868   RemoveNodeFromCSEMaps(N);
1869   
1870   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1871   N->setValueTypes(VT);
1872
1873   ON = N;   // Memoize the new node.
1874   return SDOperand(N, 0);
1875 }
1876
1877 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1878                                      MVT::ValueType VT, SDOperand Op1) {
1879   // If an identical node already exists, use it.
1880   SDNode *&ON = UnaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1881                                         std::make_pair(Op1, VT))];
1882   if (ON) return SDOperand(ON, 0);
1883   
1884   RemoveNodeFromCSEMaps(N);
1885   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1886   N->setValueTypes(VT);
1887   N->setOperands(Op1);
1888   
1889   ON = N;   // Memoize the new node.
1890   return SDOperand(N, 0);
1891 }
1892
1893 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1894                                      MVT::ValueType VT, SDOperand Op1,
1895                                      SDOperand Op2) {
1896   // If an identical node already exists, use it.
1897   SDNode *&ON = BinaryOps[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1898                                          std::make_pair(Op1, Op2))];
1899   if (ON) return SDOperand(ON, 0);
1900   
1901   RemoveNodeFromCSEMaps(N);
1902   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1903   N->setValueTypes(VT);
1904   N->setOperands(Op1, Op2);
1905   
1906   ON = N;   // Memoize the new node.
1907   return SDOperand(N, 0);
1908 }
1909
1910 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1911                                      MVT::ValueType VT, SDOperand Op1,
1912                                      SDOperand Op2, SDOperand Op3) {
1913   // If an identical node already exists, use it.
1914   std::vector<SDOperand> OpList;
1915   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1916   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1917                                               std::make_pair(VT, OpList))];
1918   if (ON) return SDOperand(ON, 0);
1919   
1920   RemoveNodeFromCSEMaps(N);
1921   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1922   N->setValueTypes(VT);
1923   N->setOperands(Op1, Op2, Op3);
1924
1925   ON = N;   // Memoize the new node.
1926   return SDOperand(N, 0);
1927 }
1928
1929 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1930                                      MVT::ValueType VT, SDOperand Op1,
1931                                      SDOperand Op2, SDOperand Op3,
1932                                      SDOperand Op4) {
1933   // If an identical node already exists, use it.
1934   std::vector<SDOperand> OpList;
1935   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1936   OpList.push_back(Op4);
1937   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1938                                               std::make_pair(VT, OpList))];
1939   if (ON) return SDOperand(ON, 0);
1940   
1941   RemoveNodeFromCSEMaps(N);
1942   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1943   N->setValueTypes(VT);
1944   N->setOperands(Op1, Op2, Op3, Op4);
1945
1946   ON = N;   // Memoize the new node.
1947   return SDOperand(N, 0);
1948 }
1949
1950 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1951                                      MVT::ValueType VT, SDOperand Op1,
1952                                      SDOperand Op2, SDOperand Op3,SDOperand Op4,
1953                                      SDOperand Op5) {
1954   // If an identical node already exists, use it.
1955   std::vector<SDOperand> OpList;
1956   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1957   OpList.push_back(Op4); OpList.push_back(Op5);
1958   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1959                                               std::make_pair(VT, OpList))];
1960   if (ON) return SDOperand(ON, 0);
1961   
1962   RemoveNodeFromCSEMaps(N);
1963   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1964   N->setValueTypes(VT);
1965   N->setOperands(Op1, Op2, Op3, Op4, Op5);
1966   
1967   ON = N;   // Memoize the new node.
1968   return SDOperand(N, 0);
1969 }
1970
1971 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1972                                      MVT::ValueType VT, SDOperand Op1,
1973                                      SDOperand Op2, SDOperand Op3,SDOperand Op4,
1974                                      SDOperand Op5, SDOperand Op6) {
1975   // If an identical node already exists, use it.
1976   std::vector<SDOperand> OpList;
1977   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
1978   OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
1979   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
1980                                               std::make_pair(VT, OpList))];
1981   if (ON) return SDOperand(ON, 0);
1982
1983   RemoveNodeFromCSEMaps(N);
1984   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
1985   N->setValueTypes(VT);
1986   N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6);
1987   
1988   ON = N;   // Memoize the new node.
1989   return SDOperand(N, 0);
1990 }
1991
1992 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
1993                                      MVT::ValueType VT, SDOperand Op1,
1994                                      SDOperand Op2, SDOperand Op3,SDOperand Op4,
1995                                      SDOperand Op5, SDOperand Op6,
1996                                      SDOperand Op7) {
1997   // If an identical node already exists, use it.
1998   std::vector<SDOperand> OpList;
1999   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2000   OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
2001   OpList.push_back(Op7);
2002   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2003                                               std::make_pair(VT, OpList))];
2004   if (ON) return SDOperand(ON, 0);
2005
2006   RemoveNodeFromCSEMaps(N);
2007   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2008   N->setValueTypes(VT);
2009   N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6, Op7);
2010   
2011   ON = N;   // Memoize the new node.
2012   return SDOperand(N, 0);
2013 }
2014 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2015                                      MVT::ValueType VT, SDOperand Op1,
2016                                      SDOperand Op2, SDOperand Op3,SDOperand Op4,
2017                                      SDOperand Op5, SDOperand Op6,
2018                                      SDOperand Op7, SDOperand Op8) {
2019   // If an identical node already exists, use it.
2020   std::vector<SDOperand> OpList;
2021   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2022   OpList.push_back(Op4); OpList.push_back(Op5); OpList.push_back(Op6);
2023   OpList.push_back(Op7); OpList.push_back(Op8);
2024   SDNode *&ON = OneResultNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2025                                               std::make_pair(VT, OpList))];
2026   if (ON) return SDOperand(ON, 0);
2027
2028   RemoveNodeFromCSEMaps(N);
2029   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2030   N->setValueTypes(VT);
2031   N->setOperands(Op1, Op2, Op3, Op4, Op5, Op6, Op7, Op8);
2032   
2033   ON = N;   // Memoize the new node.
2034   return SDOperand(N, 0);
2035 }
2036
2037 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
2038                                      MVT::ValueType VT1, MVT::ValueType VT2,
2039                                      SDOperand Op1, SDOperand Op2) {
2040   // If an identical node already exists, use it.
2041   std::vector<SDOperand> OpList;
2042   OpList.push_back(Op1); OpList.push_back(Op2); 
2043   std::vector<MVT::ValueType> VTList;
2044   VTList.push_back(VT1); VTList.push_back(VT2);
2045   SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2046                                               std::make_pair(VTList, OpList))];
2047   if (ON) return SDOperand(ON, 0);
2048
2049   RemoveNodeFromCSEMaps(N);
2050   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2051   setNodeValueTypes(N, VT1, VT2);
2052   N->setOperands(Op1, Op2);
2053   
2054   ON = N;   // Memoize the new node.
2055   return SDOperand(N, 0);
2056 }
2057
2058 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2059                                      MVT::ValueType VT1, MVT::ValueType VT2,
2060                                      SDOperand Op1, SDOperand Op2, 
2061                                      SDOperand Op3) {
2062   // If an identical node already exists, use it.
2063   std::vector<SDOperand> OpList;
2064   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2065   std::vector<MVT::ValueType> VTList;
2066   VTList.push_back(VT1); VTList.push_back(VT2);
2067   SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2068                                               std::make_pair(VTList, OpList))];
2069   if (ON) return SDOperand(ON, 0);
2070
2071   RemoveNodeFromCSEMaps(N);
2072   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2073   setNodeValueTypes(N, VT1, VT2);
2074   N->setOperands(Op1, Op2, Op3);
2075   
2076   ON = N;   // Memoize the new node.
2077   return SDOperand(N, 0);
2078 }
2079
2080 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2081                                      MVT::ValueType VT1, MVT::ValueType VT2,
2082                                      SDOperand Op1, SDOperand Op2,
2083                                      SDOperand Op3, SDOperand Op4) {
2084   // If an identical node already exists, use it.
2085   std::vector<SDOperand> OpList;
2086   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2087   OpList.push_back(Op4);
2088   std::vector<MVT::ValueType> VTList;
2089   VTList.push_back(VT1); VTList.push_back(VT2);
2090   SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2091                                               std::make_pair(VTList, OpList))];
2092   if (ON) return SDOperand(ON, 0);
2093
2094   RemoveNodeFromCSEMaps(N);
2095   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2096   setNodeValueTypes(N, VT1, VT2);
2097   N->setOperands(Op1, Op2, Op3, Op4);
2098
2099   ON = N;   // Memoize the new node.
2100   return SDOperand(N, 0);
2101 }
2102
2103 SDOperand SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2104                                      MVT::ValueType VT1, MVT::ValueType VT2,
2105                                      SDOperand Op1, SDOperand Op2,
2106                                      SDOperand Op3, SDOperand Op4, 
2107                                      SDOperand Op5) {
2108   // If an identical node already exists, use it.
2109   std::vector<SDOperand> OpList;
2110   OpList.push_back(Op1); OpList.push_back(Op2); OpList.push_back(Op3);
2111   OpList.push_back(Op4); OpList.push_back(Op5);
2112   std::vector<MVT::ValueType> VTList;
2113   VTList.push_back(VT1); VTList.push_back(VT2);
2114   SDNode *&ON = ArbitraryNodes[std::make_pair(ISD::BUILTIN_OP_END+TargetOpc,
2115                                               std::make_pair(VTList, OpList))];
2116   if (ON) return SDOperand(ON, 0);
2117
2118   RemoveNodeFromCSEMaps(N);
2119   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2120   setNodeValueTypes(N, VT1, VT2);
2121   N->setOperands(Op1, Op2, Op3, Op4, Op5);
2122   
2123   ON = N;   // Memoize the new node.
2124   return SDOperand(N, 0);
2125 }
2126
2127 /// getTargetNode - These are used for target selectors to create a new node
2128 /// with specified return type(s), target opcode, and operands.
2129 ///
2130 /// Note that getTargetNode returns the resultant node.  If there is already a
2131 /// node of the specified opcode and operands, it returns that node instead of
2132 /// the current one.
2133 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
2134   return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
2135 }
2136 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2137                                     SDOperand Op1) {
2138   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
2139 }
2140 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2141                                     SDOperand Op1, SDOperand Op2) {
2142   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
2143 }
2144 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2145                                     SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2146   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
2147 }
2148 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2149                                     SDOperand Op1, SDOperand Op2, SDOperand Op3,
2150                                     SDOperand Op4) {
2151   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3, Op4).Val;
2152 }
2153 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2154                                     SDOperand Op1, SDOperand Op2, SDOperand Op3,
2155                                     SDOperand Op4, SDOperand Op5) {
2156   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3, Op4, Op5).Val;
2157 }
2158 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2159                                     SDOperand Op1, SDOperand Op2, SDOperand Op3,
2160                                     SDOperand Op4, SDOperand Op5, SDOperand Op6) {
2161   std::vector<SDOperand> Ops;
2162   Ops.reserve(6);
2163   Ops.push_back(Op1);
2164   Ops.push_back(Op2);
2165   Ops.push_back(Op3);
2166   Ops.push_back(Op4);
2167   Ops.push_back(Op5);
2168   Ops.push_back(Op6);
2169   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2170 }
2171 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2172                                     SDOperand Op1, SDOperand Op2, SDOperand Op3,
2173                                     SDOperand Op4, SDOperand Op5, SDOperand Op6,
2174                                     SDOperand Op7) {
2175   std::vector<SDOperand> Ops;
2176   Ops.reserve(7);
2177   Ops.push_back(Op1);
2178   Ops.push_back(Op2);
2179   Ops.push_back(Op3);
2180   Ops.push_back(Op4);
2181   Ops.push_back(Op5);
2182   Ops.push_back(Op6);
2183   Ops.push_back(Op7);
2184   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2185 }
2186 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2187                                     SDOperand Op1, SDOperand Op2, SDOperand Op3,
2188                                     SDOperand Op4, SDOperand Op5, SDOperand Op6,
2189                                     SDOperand Op7, SDOperand Op8) {
2190   std::vector<SDOperand> Ops;
2191   Ops.reserve(8);
2192   Ops.push_back(Op1);
2193   Ops.push_back(Op2);
2194   Ops.push_back(Op3);
2195   Ops.push_back(Op4);
2196   Ops.push_back(Op5);
2197   Ops.push_back(Op6);
2198   Ops.push_back(Op7);
2199   Ops.push_back(Op8);
2200   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2201 }
2202 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2203                                     std::vector<SDOperand> &Ops) {
2204   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops).Val;
2205 }
2206 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2207                                     MVT::ValueType VT2, SDOperand Op1) {
2208   std::vector<MVT::ValueType> ResultTys;
2209   ResultTys.push_back(VT1);
2210   ResultTys.push_back(VT2);
2211   std::vector<SDOperand> Ops;
2212   Ops.push_back(Op1);
2213   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2214 }
2215 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2216                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2) {
2217   std::vector<MVT::ValueType> ResultTys;
2218   ResultTys.push_back(VT1);
2219   ResultTys.push_back(VT2);
2220   std::vector<SDOperand> Ops;
2221   Ops.push_back(Op1);
2222   Ops.push_back(Op2);
2223   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2224 }
2225 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2226                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2227                                     SDOperand Op3) {
2228   std::vector<MVT::ValueType> ResultTys;
2229   ResultTys.push_back(VT1);
2230   ResultTys.push_back(VT2);
2231   std::vector<SDOperand> Ops;
2232   Ops.push_back(Op1);
2233   Ops.push_back(Op2);
2234   Ops.push_back(Op3);
2235   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2236 }
2237 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2238                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2239                                     SDOperand Op3, SDOperand Op4) {
2240   std::vector<MVT::ValueType> ResultTys;
2241   ResultTys.push_back(VT1);
2242   ResultTys.push_back(VT2);
2243   std::vector<SDOperand> Ops;
2244   Ops.push_back(Op1);
2245   Ops.push_back(Op2);
2246   Ops.push_back(Op3);
2247   Ops.push_back(Op4);
2248   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2249 }
2250 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2251                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2252                                     SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2253   std::vector<MVT::ValueType> ResultTys;
2254   ResultTys.push_back(VT1);
2255   ResultTys.push_back(VT2);
2256   std::vector<SDOperand> Ops;
2257   Ops.push_back(Op1);
2258   Ops.push_back(Op2);
2259   Ops.push_back(Op3);
2260   Ops.push_back(Op4);
2261   Ops.push_back(Op5);
2262   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2263 }
2264 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2265                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2266                                     SDOperand Op3, SDOperand Op4, SDOperand Op5,
2267                                     SDOperand Op6) {
2268   std::vector<MVT::ValueType> ResultTys;
2269   ResultTys.push_back(VT1);
2270   ResultTys.push_back(VT2);
2271   std::vector<SDOperand> Ops;
2272   Ops.push_back(Op1);
2273   Ops.push_back(Op2);
2274   Ops.push_back(Op3);
2275   Ops.push_back(Op4);
2276   Ops.push_back(Op5);
2277   Ops.push_back(Op6);
2278   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2279 }
2280 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2281                                     MVT::ValueType VT2, SDOperand Op1, SDOperand Op2,
2282                                     SDOperand Op3, SDOperand Op4, SDOperand Op5,
2283                                     SDOperand Op6, SDOperand Op7) {
2284   std::vector<MVT::ValueType> ResultTys;
2285   ResultTys.push_back(VT1);
2286   ResultTys.push_back(VT2);
2287   std::vector<SDOperand> Ops;
2288   Ops.push_back(Op1);
2289   Ops.push_back(Op2);
2290   Ops.push_back(Op3);
2291   Ops.push_back(Op4);
2292   Ops.push_back(Op5);
2293   Ops.push_back(Op6); 
2294   Ops.push_back(Op7);
2295   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2296 }
2297 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2298                                     MVT::ValueType VT2, MVT::ValueType VT3,
2299                                     SDOperand Op1, SDOperand Op2) {
2300   std::vector<MVT::ValueType> ResultTys;
2301   ResultTys.push_back(VT1);
2302   ResultTys.push_back(VT2);
2303   ResultTys.push_back(VT3);
2304   std::vector<SDOperand> Ops;
2305   Ops.push_back(Op1);
2306   Ops.push_back(Op2);
2307   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2308 }
2309 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2310                                     MVT::ValueType VT2, MVT::ValueType VT3,
2311                                     SDOperand Op1, SDOperand Op2,
2312                                     SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2313   std::vector<MVT::ValueType> ResultTys;
2314   ResultTys.push_back(VT1);
2315   ResultTys.push_back(VT2);
2316   ResultTys.push_back(VT3);
2317   std::vector<SDOperand> Ops;
2318   Ops.push_back(Op1);
2319   Ops.push_back(Op2);
2320   Ops.push_back(Op3);
2321   Ops.push_back(Op4);
2322   Ops.push_back(Op5);
2323   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2324 }
2325 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2326                                     MVT::ValueType VT2, MVT::ValueType VT3,
2327                                     SDOperand Op1, SDOperand Op2,
2328                                     SDOperand Op3, SDOperand Op4, SDOperand Op5,
2329                                     SDOperand Op6) {
2330   std::vector<MVT::ValueType> ResultTys;
2331   ResultTys.push_back(VT1);
2332   ResultTys.push_back(VT2);
2333   ResultTys.push_back(VT3);
2334   std::vector<SDOperand> Ops;
2335   Ops.push_back(Op1);
2336   Ops.push_back(Op2);
2337   Ops.push_back(Op3);
2338   Ops.push_back(Op4);
2339   Ops.push_back(Op5);
2340   Ops.push_back(Op6);
2341   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2342 }
2343 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2344                                     MVT::ValueType VT2, MVT::ValueType VT3,
2345                                     SDOperand Op1, SDOperand Op2,
2346                                     SDOperand Op3, SDOperand Op4, SDOperand Op5,
2347                                     SDOperand Op6, SDOperand Op7) {
2348   std::vector<MVT::ValueType> ResultTys;
2349   ResultTys.push_back(VT1);
2350   ResultTys.push_back(VT2);
2351   ResultTys.push_back(VT3);
2352   std::vector<SDOperand> Ops;
2353   Ops.push_back(Op1);
2354   Ops.push_back(Op2);
2355   Ops.push_back(Op3);
2356   Ops.push_back(Op4);
2357   Ops.push_back(Op5);
2358   Ops.push_back(Op6);
2359   Ops.push_back(Op7);
2360   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2361 }
2362 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
2363                                     MVT::ValueType VT2, std::vector<SDOperand> &Ops) {
2364   std::vector<MVT::ValueType> ResultTys;
2365   ResultTys.push_back(VT1);
2366   ResultTys.push_back(VT2);
2367   return getNode(ISD::BUILTIN_OP_END+Opcode, ResultTys, Ops).Val;
2368 }
2369
2370 // ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2371 /// This can cause recursive merging of nodes in the DAG.
2372 ///
2373 /// This version assumes From/To have a single result value.
2374 ///
2375 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
2376                                       std::vector<SDNode*> *Deleted) {
2377   SDNode *From = FromN.Val, *To = ToN.Val;
2378   assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
2379          "Cannot replace with this method!");
2380   assert(From != To && "Cannot replace uses of with self");
2381   
2382   while (!From->use_empty()) {
2383     // Process users until they are all gone.
2384     SDNode *U = *From->use_begin();
2385     
2386     // This node is about to morph, remove its old self from the CSE maps.
2387     RemoveNodeFromCSEMaps(U);
2388     
2389     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2390          I != E; ++I)
2391       if (I->Val == From) {
2392         From->removeUser(U);
2393         I->Val = To;
2394         To->addUser(U);
2395       }
2396
2397     // Now that we have modified U, add it back to the CSE maps.  If it already
2398     // exists there, recursively merge the results together.
2399     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2400       ReplaceAllUsesWith(U, Existing, Deleted);
2401       // U is now dead.
2402       if (Deleted) Deleted->push_back(U);
2403       DeleteNodeNotInCSEMaps(U);
2404     }
2405   }
2406 }
2407
2408 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2409 /// This can cause recursive merging of nodes in the DAG.
2410 ///
2411 /// This version assumes From/To have matching types and numbers of result
2412 /// values.
2413 ///
2414 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
2415                                       std::vector<SDNode*> *Deleted) {
2416   assert(From != To && "Cannot replace uses of with self");
2417   assert(From->getNumValues() == To->getNumValues() &&
2418          "Cannot use this version of ReplaceAllUsesWith!");
2419   if (From->getNumValues() == 1) {  // If possible, use the faster version.
2420     ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
2421     return;
2422   }
2423   
2424   while (!From->use_empty()) {
2425     // Process users until they are all gone.
2426     SDNode *U = *From->use_begin();
2427     
2428     // This node is about to morph, remove its old self from the CSE maps.
2429     RemoveNodeFromCSEMaps(U);
2430     
2431     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2432          I != E; ++I)
2433       if (I->Val == From) {
2434         From->removeUser(U);
2435         I->Val = To;
2436         To->addUser(U);
2437       }
2438         
2439     // Now that we have modified U, add it back to the CSE maps.  If it already
2440     // exists there, recursively merge the results together.
2441     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2442       ReplaceAllUsesWith(U, Existing, Deleted);
2443       // U is now dead.
2444       if (Deleted) Deleted->push_back(U);
2445       DeleteNodeNotInCSEMaps(U);
2446     }
2447   }
2448 }
2449
2450 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2451 /// This can cause recursive merging of nodes in the DAG.
2452 ///
2453 /// This version can replace From with any result values.  To must match the
2454 /// number and types of values returned by From.
2455 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
2456                                       const std::vector<SDOperand> &To,
2457                                       std::vector<SDNode*> *Deleted) {
2458   assert(From->getNumValues() == To.size() &&
2459          "Incorrect number of values to replace with!");
2460   if (To.size() == 1 && To[0].Val->getNumValues() == 1) {
2461     // Degenerate case handled above.
2462     ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
2463     return;
2464   }
2465
2466   while (!From->use_empty()) {
2467     // Process users until they are all gone.
2468     SDNode *U = *From->use_begin();
2469     
2470     // This node is about to morph, remove its old self from the CSE maps.
2471     RemoveNodeFromCSEMaps(U);
2472     
2473     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
2474          I != E; ++I)
2475       if (I->Val == From) {
2476         const SDOperand &ToOp = To[I->ResNo];
2477         From->removeUser(U);
2478         *I = ToOp;
2479         ToOp.Val->addUser(U);
2480       }
2481         
2482     // Now that we have modified U, add it back to the CSE maps.  If it already
2483     // exists there, recursively merge the results together.
2484     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2485       ReplaceAllUsesWith(U, Existing, Deleted);
2486       // U is now dead.
2487       if (Deleted) Deleted->push_back(U);
2488       DeleteNodeNotInCSEMaps(U);
2489     }
2490   }
2491 }
2492
2493 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
2494 /// uses of other values produced by From.Val alone.  The Deleted vector is
2495 /// handled the same was as for ReplaceAllUsesWith.
2496 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
2497                                              std::vector<SDNode*> &Deleted) {
2498   assert(From != To && "Cannot replace a value with itself");
2499   // Handle the simple, trivial, case efficiently.
2500   if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
2501     ReplaceAllUsesWith(From, To, &Deleted);
2502     return;
2503   }
2504   
2505   // Get all of the users in a nice, deterministically ordered, uniqued set.
2506   SetVector<SDNode*> Users(From.Val->use_begin(), From.Val->use_end());
2507
2508   while (!Users.empty()) {
2509     // We know that this user uses some value of From.  If it is the right
2510     // value, update it.
2511     SDNode *User = Users.back();
2512     Users.pop_back();
2513     
2514     for (SDOperand *Op = User->OperandList,
2515          *E = User->OperandList+User->NumOperands; Op != E; ++Op) {
2516       if (*Op == From) {
2517         // Okay, we know this user needs to be updated.  Remove its old self
2518         // from the CSE maps.
2519         RemoveNodeFromCSEMaps(User);
2520         
2521         // Update all operands that match "From".
2522         for (; Op != E; ++Op) {
2523           if (*Op == From) {
2524             From.Val->removeUser(User);
2525             *Op = To;
2526             To.Val->addUser(User);
2527           }
2528         }
2529                    
2530         // Now that we have modified User, add it back to the CSE maps.  If it
2531         // already exists there, recursively merge the results together.
2532         if (SDNode *Existing = AddNonLeafNodeToCSEMaps(User)) {
2533           unsigned NumDeleted = Deleted.size();
2534           ReplaceAllUsesWith(User, Existing, &Deleted);
2535           
2536           // User is now dead.
2537           Deleted.push_back(User);
2538           DeleteNodeNotInCSEMaps(User);
2539           
2540           // We have to be careful here, because ReplaceAllUsesWith could have
2541           // deleted a user of From, which means there may be dangling pointers
2542           // in the "Users" setvector.  Scan over the deleted node pointers and
2543           // remove them from the setvector.
2544           for (unsigned i = NumDeleted, e = Deleted.size(); i != e; ++i)
2545             Users.remove(Deleted[i]);
2546         }
2547         break;   // Exit the operand scanning loop.
2548       }
2549     }
2550   }
2551 }
2552
2553
2554 //===----------------------------------------------------------------------===//
2555 //                              SDNode Class
2556 //===----------------------------------------------------------------------===//
2557
2558
2559 /// getValueTypeList - Return a pointer to the specified value type.
2560 ///
2561 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
2562   static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
2563   VTs[VT] = VT;
2564   return &VTs[VT];
2565 }
2566
2567 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
2568 /// indicated value.  This method ignores uses of other values defined by this
2569 /// operation.
2570 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
2571   assert(Value < getNumValues() && "Bad value!");
2572
2573   // If there is only one value, this is easy.
2574   if (getNumValues() == 1)
2575     return use_size() == NUses;
2576   if (Uses.size() < NUses) return false;
2577
2578   SDOperand TheValue(const_cast<SDNode *>(this), Value);
2579
2580   std::set<SDNode*> UsersHandled;
2581
2582   for (std::vector<SDNode*>::const_iterator UI = Uses.begin(), E = Uses.end();
2583        UI != E; ++UI) {
2584     SDNode *User = *UI;
2585     if (User->getNumOperands() == 1 ||
2586         UsersHandled.insert(User).second)     // First time we've seen this?
2587       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
2588         if (User->getOperand(i) == TheValue) {
2589           if (NUses == 0)
2590             return false;   // too many uses
2591           --NUses;
2592         }
2593   }
2594
2595   // Found exactly the right number of uses?
2596   return NUses == 0;
2597 }
2598
2599
2600 // isOnlyUse - Return true if this node is the only use of N.
2601 bool SDNode::isOnlyUse(SDNode *N) const {
2602   bool Seen = false;
2603   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2604     SDNode *User = *I;
2605     if (User == this)
2606       Seen = true;
2607     else
2608       return false;
2609   }
2610
2611   return Seen;
2612 }
2613
2614 // isOperand - Return true if this node is an operand of N.
2615 bool SDOperand::isOperand(SDNode *N) const {
2616   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2617     if (*this == N->getOperand(i))
2618       return true;
2619   return false;
2620 }
2621
2622 bool SDNode::isOperand(SDNode *N) const {
2623   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
2624     if (this == N->OperandList[i].Val)
2625       return true;
2626   return false;
2627 }
2628
2629 const char *SDNode::getOperationName(const SelectionDAG *G) const {
2630   switch (getOpcode()) {
2631   default:
2632     if (getOpcode() < ISD::BUILTIN_OP_END)
2633       return "<<Unknown DAG Node>>";
2634     else {
2635       if (G) {
2636         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
2637           if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
2638             return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
2639
2640         TargetLowering &TLI = G->getTargetLoweringInfo();
2641         const char *Name =
2642           TLI.getTargetNodeName(getOpcode());
2643         if (Name) return Name;
2644       }
2645
2646       return "<<Unknown Target Node>>";
2647     }
2648    
2649   case ISD::PCMARKER:      return "PCMarker";
2650   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
2651   case ISD::SRCVALUE:      return "SrcValue";
2652   case ISD::EntryToken:    return "EntryToken";
2653   case ISD::TokenFactor:   return "TokenFactor";
2654   case ISD::AssertSext:    return "AssertSext";
2655   case ISD::AssertZext:    return "AssertZext";
2656
2657   case ISD::STRING:        return "String";
2658   case ISD::BasicBlock:    return "BasicBlock";
2659   case ISD::VALUETYPE:     return "ValueType";
2660   case ISD::Register:      return "Register";
2661
2662   case ISD::Constant:      return "Constant";
2663   case ISD::ConstantFP:    return "ConstantFP";
2664   case ISD::GlobalAddress: return "GlobalAddress";
2665   case ISD::FrameIndex:    return "FrameIndex";
2666   case ISD::ConstantPool:  return "ConstantPool";
2667   case ISD::ExternalSymbol: return "ExternalSymbol";
2668   case ISD::INTRINSIC:     return "INTRINSIC";
2669
2670   case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
2671   case ISD::TargetConstant: return "TargetConstant";
2672   case ISD::TargetConstantFP:return "TargetConstantFP";
2673   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
2674   case ISD::TargetFrameIndex: return "TargetFrameIndex";
2675   case ISD::TargetConstantPool:  return "TargetConstantPool";
2676   case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
2677
2678   case ISD::CopyToReg:     return "CopyToReg";
2679   case ISD::CopyFromReg:   return "CopyFromReg";
2680   case ISD::UNDEF:         return "undef";
2681   case ISD::MERGE_VALUES:  return "mergevalues";
2682   case ISD::INLINEASM:     return "inlineasm";
2683   case ISD::HANDLENODE:    return "handlenode";
2684     
2685   // Unary operators
2686   case ISD::FABS:   return "fabs";
2687   case ISD::FNEG:   return "fneg";
2688   case ISD::FSQRT:  return "fsqrt";
2689   case ISD::FSIN:   return "fsin";
2690   case ISD::FCOS:   return "fcos";
2691
2692   // Binary operators
2693   case ISD::ADD:    return "add";
2694   case ISD::SUB:    return "sub";
2695   case ISD::MUL:    return "mul";
2696   case ISD::MULHU:  return "mulhu";
2697   case ISD::MULHS:  return "mulhs";
2698   case ISD::SDIV:   return "sdiv";
2699   case ISD::UDIV:   return "udiv";
2700   case ISD::SREM:   return "srem";
2701   case ISD::UREM:   return "urem";
2702   case ISD::AND:    return "and";
2703   case ISD::OR:     return "or";
2704   case ISD::XOR:    return "xor";
2705   case ISD::SHL:    return "shl";
2706   case ISD::SRA:    return "sra";
2707   case ISD::SRL:    return "srl";
2708   case ISD::ROTL:   return "rotl";
2709   case ISD::ROTR:   return "rotr";
2710   case ISD::FADD:   return "fadd";
2711   case ISD::FSUB:   return "fsub";
2712   case ISD::FMUL:   return "fmul";
2713   case ISD::FDIV:   return "fdiv";
2714   case ISD::FREM:   return "frem";
2715   case ISD::FCOPYSIGN: return "fcopysign";
2716   case ISD::VADD:   return "vadd";
2717   case ISD::VSUB:   return "vsub";
2718   case ISD::VMUL:   return "vmul";
2719
2720   case ISD::SETCC:       return "setcc";
2721   case ISD::SELECT:      return "select";
2722   case ISD::SELECT_CC:   return "select_cc";
2723   case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
2724   case ISD::VINSERT_VECTOR_ELT: return "vinsert_vector_elt";
2725   case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
2726   case ISD::VEXTRACT_VECTOR_ELT: return "vextract_vector_elt";
2727   case ISD::SCALAR_TO_VECTOR:   return "scalar_to_vector";
2728   case ISD::VBUILD_VECTOR: return "vbuild_vector";
2729   case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
2730   case ISD::VBIT_CONVERT: return "vbit_convert";
2731   case ISD::ADDC:        return "addc";
2732   case ISD::ADDE:        return "adde";
2733   case ISD::SUBC:        return "subc";
2734   case ISD::SUBE:        return "sube";
2735   case ISD::SHL_PARTS:   return "shl_parts";
2736   case ISD::SRA_PARTS:   return "sra_parts";
2737   case ISD::SRL_PARTS:   return "srl_parts";
2738
2739   // Conversion operators.
2740   case ISD::SIGN_EXTEND: return "sign_extend";
2741   case ISD::ZERO_EXTEND: return "zero_extend";
2742   case ISD::ANY_EXTEND:  return "any_extend";
2743   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
2744   case ISD::TRUNCATE:    return "truncate";
2745   case ISD::FP_ROUND:    return "fp_round";
2746   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
2747   case ISD::FP_EXTEND:   return "fp_extend";
2748
2749   case ISD::SINT_TO_FP:  return "sint_to_fp";
2750   case ISD::UINT_TO_FP:  return "uint_to_fp";
2751   case ISD::FP_TO_SINT:  return "fp_to_sint";
2752   case ISD::FP_TO_UINT:  return "fp_to_uint";
2753   case ISD::BIT_CONVERT: return "bit_convert";
2754
2755     // Control flow instructions
2756   case ISD::BR:      return "br";
2757   case ISD::BRCOND:  return "brcond";
2758   case ISD::BR_CC:   return "br_cc";
2759   case ISD::RET:     return "ret";
2760   case ISD::CALLSEQ_START:  return "callseq_start";
2761   case ISD::CALLSEQ_END:    return "callseq_end";
2762
2763     // Other operators
2764   case ISD::LOAD:               return "load";
2765   case ISD::STORE:              return "store";
2766   case ISD::VLOAD:              return "vload";
2767   case ISD::EXTLOAD:            return "extload";
2768   case ISD::SEXTLOAD:           return "sextload";
2769   case ISD::ZEXTLOAD:           return "zextload";
2770   case ISD::TRUNCSTORE:         return "truncstore";
2771   case ISD::VAARG:              return "vaarg";
2772   case ISD::VACOPY:             return "vacopy";
2773   case ISD::VAEND:              return "vaend";
2774   case ISD::VASTART:            return "vastart";
2775   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
2776   case ISD::EXTRACT_ELEMENT:    return "extract_element";
2777   case ISD::BUILD_PAIR:         return "build_pair";
2778   case ISD::STACKSAVE:          return "stacksave";
2779   case ISD::STACKRESTORE:       return "stackrestore";
2780     
2781   // Block memory operations.
2782   case ISD::MEMSET:  return "memset";
2783   case ISD::MEMCPY:  return "memcpy";
2784   case ISD::MEMMOVE: return "memmove";
2785
2786   // Bit manipulation
2787   case ISD::BSWAP:   return "bswap";
2788   case ISD::CTPOP:   return "ctpop";
2789   case ISD::CTTZ:    return "cttz";
2790   case ISD::CTLZ:    return "ctlz";
2791
2792   // Debug info
2793   case ISD::LOCATION: return "location";
2794   case ISD::DEBUG_LOC: return "debug_loc";
2795   case ISD::DEBUG_LABEL: return "debug_label";
2796
2797   case ISD::CONDCODE:
2798     switch (cast<CondCodeSDNode>(this)->get()) {
2799     default: assert(0 && "Unknown setcc condition!");
2800     case ISD::SETOEQ:  return "setoeq";
2801     case ISD::SETOGT:  return "setogt";
2802     case ISD::SETOGE:  return "setoge";
2803     case ISD::SETOLT:  return "setolt";
2804     case ISD::SETOLE:  return "setole";
2805     case ISD::SETONE:  return "setone";
2806
2807     case ISD::SETO:    return "seto";
2808     case ISD::SETUO:   return "setuo";
2809     case ISD::SETUEQ:  return "setue";
2810     case ISD::SETUGT:  return "setugt";
2811     case ISD::SETUGE:  return "setuge";
2812     case ISD::SETULT:  return "setult";
2813     case ISD::SETULE:  return "setule";
2814     case ISD::SETUNE:  return "setune";
2815
2816     case ISD::SETEQ:   return "seteq";
2817     case ISD::SETGT:   return "setgt";
2818     case ISD::SETGE:   return "setge";
2819     case ISD::SETLT:   return "setlt";
2820     case ISD::SETLE:   return "setle";
2821     case ISD::SETNE:   return "setne";
2822     }
2823   }
2824 }
2825
2826 void SDNode::dump() const { dump(0); }
2827 void SDNode::dump(const SelectionDAG *G) const {
2828   std::cerr << (void*)this << ": ";
2829
2830   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
2831     if (i) std::cerr << ",";
2832     if (getValueType(i) == MVT::Other)
2833       std::cerr << "ch";
2834     else
2835       std::cerr << MVT::getValueTypeString(getValueType(i));
2836   }
2837   std::cerr << " = " << getOperationName(G);
2838
2839   std::cerr << " ";
2840   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2841     if (i) std::cerr << ", ";
2842     std::cerr << (void*)getOperand(i).Val;
2843     if (unsigned RN = getOperand(i).ResNo)
2844       std::cerr << ":" << RN;
2845   }
2846
2847   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
2848     std::cerr << "<" << CSDN->getValue() << ">";
2849   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
2850     std::cerr << "<" << CSDN->getValue() << ">";
2851   } else if (const GlobalAddressSDNode *GADN =
2852              dyn_cast<GlobalAddressSDNode>(this)) {
2853     int offset = GADN->getOffset();
2854     std::cerr << "<";
2855     WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
2856     if (offset > 0)
2857       std::cerr << " + " << offset;
2858     else
2859       std::cerr << " " << offset;
2860   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
2861     std::cerr << "<" << FIDN->getIndex() << ">";
2862   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
2863     int offset = CP->getOffset();
2864     std::cerr << "<" << *CP->get() << ">";
2865     if (offset > 0)
2866       std::cerr << " + " << offset;
2867     else
2868       std::cerr << " " << offset;
2869   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
2870     std::cerr << "<";
2871     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
2872     if (LBB)
2873       std::cerr << LBB->getName() << " ";
2874     std::cerr << (const void*)BBDN->getBasicBlock() << ">";
2875   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
2876     if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
2877       std::cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
2878     } else {
2879       std::cerr << " #" << R->getReg();
2880     }
2881   } else if (const ExternalSymbolSDNode *ES =
2882              dyn_cast<ExternalSymbolSDNode>(this)) {
2883     std::cerr << "'" << ES->getSymbol() << "'";
2884   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
2885     if (M->getValue())
2886       std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
2887     else
2888       std::cerr << "<null:" << M->getOffset() << ">";
2889   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
2890     std::cerr << ":" << getValueTypeString(N->getVT());
2891   }
2892 }
2893
2894 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
2895   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2896     if (N->getOperand(i).Val->hasOneUse())
2897       DumpNodes(N->getOperand(i).Val, indent+2, G);
2898     else
2899       std::cerr << "\n" << std::string(indent+2, ' ')
2900                 << (void*)N->getOperand(i).Val << ": <multiple use>";
2901
2902
2903   std::cerr << "\n" << std::string(indent, ' ');
2904   N->dump(G);
2905 }
2906
2907 void SelectionDAG::dump() const {
2908   std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
2909   std::vector<const SDNode*> Nodes;
2910   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
2911        I != E; ++I)
2912     Nodes.push_back(I);
2913   
2914   std::sort(Nodes.begin(), Nodes.end());
2915
2916   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2917     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
2918       DumpNodes(Nodes[i], 2, this);
2919   }
2920
2921   DumpNodes(getRoot().Val, 2, this);
2922
2923   std::cerr << "\n\n";
2924 }
2925
2926 /// InsertISelMapEntry - A helper function to insert a key / element pair
2927 /// into a SDOperand to SDOperand map. This is added to avoid the map
2928 /// insertion operator from being inlined.
2929 void SelectionDAG::InsertISelMapEntry(std::map<SDOperand, SDOperand> &Map,
2930                                       SDNode *Key, unsigned KeyResNo,
2931                                       SDNode *Element, unsigned ElementResNo) {
2932   Map.insert(std::make_pair(SDOperand(Key, KeyResNo),
2933                             SDOperand(Element, ElementResNo)));
2934 }