Disable attempts to constant fold PPC f128.
[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/GlobalVariable.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include <algorithm>
35 #include <cmath>
36 using namespace llvm;
37
38 /// makeVTList - Return an instance of the SDVTList struct initialized with the
39 /// specified members.
40 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
41   SDVTList Res = {VTs, NumVTs};
42   return Res;
43 }
44
45 //===----------------------------------------------------------------------===//
46 //                              ConstantFPSDNode Class
47 //===----------------------------------------------------------------------===//
48
49 /// isExactlyValue - We don't rely on operator== working on double values, as
50 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
51 /// As such, this method can be used to do an exact bit-for-bit comparison of
52 /// two floating point values.
53 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
54   return Value.bitwiseIsEqual(V);
55 }
56
57 bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT, 
58                                            const APFloat& Val) {
59   // convert modifies in place, so make a copy.
60   APFloat Val2 = APFloat(Val);
61   switch (VT) {
62   default:
63     return false;         // These can't be represented as floating point!
64
65   // FIXME rounding mode needs to be more flexible
66   case MVT::f32:
67     return &Val2.getSemantics() == &APFloat::IEEEsingle ||
68            Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) == 
69               APFloat::opOK;
70   case MVT::f64:
71     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
72            &Val2.getSemantics() == &APFloat::IEEEdouble ||
73            Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) == 
74              APFloat::opOK;
75   // TODO: Figure out how to test if we can use a shorter type instead!
76   case MVT::f80:
77   case MVT::f128:
78   case MVT::ppcf128:
79     return true;
80   }
81 }
82
83 //===----------------------------------------------------------------------===//
84 //                              ISD Namespace
85 //===----------------------------------------------------------------------===//
86
87 /// isBuildVectorAllOnes - Return true if the specified node is a
88 /// BUILD_VECTOR where all of the elements are ~0 or undef.
89 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
90   // Look through a bit convert.
91   if (N->getOpcode() == ISD::BIT_CONVERT)
92     N = N->getOperand(0).Val;
93   
94   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
95   
96   unsigned i = 0, e = N->getNumOperands();
97   
98   // Skip over all of the undef values.
99   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
100     ++i;
101   
102   // Do not accept an all-undef vector.
103   if (i == e) return false;
104   
105   // Do not accept build_vectors that aren't all constants or which have non-~0
106   // elements.
107   SDOperand NotZero = N->getOperand(i);
108   if (isa<ConstantSDNode>(NotZero)) {
109     if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
110       return false;
111   } else if (isa<ConstantFPSDNode>(NotZero)) {
112     MVT::ValueType VT = NotZero.getValueType();
113     if (VT== MVT::f64) {
114       if (((cast<ConstantFPSDNode>(NotZero)->getValueAPF().
115                   convertToAPInt().getZExtValue())) != (uint64_t)-1)
116         return false;
117     } else {
118       if ((uint32_t)cast<ConstantFPSDNode>(NotZero)->
119                       getValueAPF().convertToAPInt().getZExtValue() != 
120           (uint32_t)-1)
121         return false;
122     }
123   } else
124     return false;
125   
126   // Okay, we have at least one ~0 value, check to see if the rest match or are
127   // undefs.
128   for (++i; i != e; ++i)
129     if (N->getOperand(i) != NotZero &&
130         N->getOperand(i).getOpcode() != ISD::UNDEF)
131       return false;
132   return true;
133 }
134
135
136 /// isBuildVectorAllZeros - Return true if the specified node is a
137 /// BUILD_VECTOR where all of the elements are 0 or undef.
138 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
139   // Look through a bit convert.
140   if (N->getOpcode() == ISD::BIT_CONVERT)
141     N = N->getOperand(0).Val;
142   
143   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
144   
145   unsigned i = 0, e = N->getNumOperands();
146   
147   // Skip over all of the undef values.
148   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
149     ++i;
150   
151   // Do not accept an all-undef vector.
152   if (i == e) return false;
153   
154   // Do not accept build_vectors that aren't all constants or which have non-~0
155   // elements.
156   SDOperand Zero = N->getOperand(i);
157   if (isa<ConstantSDNode>(Zero)) {
158     if (!cast<ConstantSDNode>(Zero)->isNullValue())
159       return false;
160   } else if (isa<ConstantFPSDNode>(Zero)) {
161     if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
162       return false;
163   } else
164     return false;
165   
166   // Okay, we have at least one ~0 value, check to see if the rest match or are
167   // undefs.
168   for (++i; i != e; ++i)
169     if (N->getOperand(i) != Zero &&
170         N->getOperand(i).getOpcode() != ISD::UNDEF)
171       return false;
172   return true;
173 }
174
175 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
176 /// when given the operation for (X op Y).
177 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
178   // To perform this operation, we just need to swap the L and G bits of the
179   // operation.
180   unsigned OldL = (Operation >> 2) & 1;
181   unsigned OldG = (Operation >> 1) & 1;
182   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
183                        (OldL << 1) |       // New G bit
184                        (OldG << 2));        // New L bit.
185 }
186
187 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
188 /// 'op' is a valid SetCC operation.
189 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
190   unsigned Operation = Op;
191   if (isInteger)
192     Operation ^= 7;   // Flip L, G, E bits, but not U.
193   else
194     Operation ^= 15;  // Flip all of the condition bits.
195   if (Operation > ISD::SETTRUE2)
196     Operation &= ~8;     // Don't let N and U bits get set.
197   return ISD::CondCode(Operation);
198 }
199
200
201 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
202 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
203 /// if the operation does not depend on the sign of the input (setne and seteq).
204 static int isSignedOp(ISD::CondCode Opcode) {
205   switch (Opcode) {
206   default: assert(0 && "Illegal integer setcc operation!");
207   case ISD::SETEQ:
208   case ISD::SETNE: return 0;
209   case ISD::SETLT:
210   case ISD::SETLE:
211   case ISD::SETGT:
212   case ISD::SETGE: return 1;
213   case ISD::SETULT:
214   case ISD::SETULE:
215   case ISD::SETUGT:
216   case ISD::SETUGE: return 2;
217   }
218 }
219
220 /// getSetCCOrOperation - Return the result of a logical OR between different
221 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
222 /// returns SETCC_INVALID if it is not possible to represent the resultant
223 /// comparison.
224 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
225                                        bool isInteger) {
226   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
227     // Cannot fold a signed integer setcc with an unsigned integer setcc.
228     return ISD::SETCC_INVALID;
229
230   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
231
232   // If the N and U bits get set then the resultant comparison DOES suddenly
233   // care about orderedness, and is true when ordered.
234   if (Op > ISD::SETTRUE2)
235     Op &= ~16;     // Clear the U bit if the N bit is set.
236   
237   // Canonicalize illegal integer setcc's.
238   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
239     Op = ISD::SETNE;
240   
241   return ISD::CondCode(Op);
242 }
243
244 /// getSetCCAndOperation - Return the result of a logical AND between different
245 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
246 /// function returns zero if it is not possible to represent the resultant
247 /// comparison.
248 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
249                                         bool isInteger) {
250   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
251     // Cannot fold a signed setcc with an unsigned setcc.
252     return ISD::SETCC_INVALID;
253
254   // Combine all of the condition bits.
255   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
256   
257   // Canonicalize illegal integer setcc's.
258   if (isInteger) {
259     switch (Result) {
260     default: break;
261     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
262     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
263     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
264     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
265     }
266   }
267   
268   return Result;
269 }
270
271 const TargetMachine &SelectionDAG::getTarget() const {
272   return TLI.getTargetMachine();
273 }
274
275 //===----------------------------------------------------------------------===//
276 //                           SDNode Profile Support
277 //===----------------------------------------------------------------------===//
278
279 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
280 ///
281 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
282   ID.AddInteger(OpC);
283 }
284
285 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
286 /// solely with their pointer.
287 void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
288   ID.AddPointer(VTList.VTs);  
289 }
290
291 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
292 ///
293 static void AddNodeIDOperands(FoldingSetNodeID &ID,
294                               const SDOperand *Ops, unsigned NumOps) {
295   for (; NumOps; --NumOps, ++Ops) {
296     ID.AddPointer(Ops->Val);
297     ID.AddInteger(Ops->ResNo);
298   }
299 }
300
301 static void AddNodeIDNode(FoldingSetNodeID &ID,
302                           unsigned short OpC, SDVTList VTList, 
303                           const SDOperand *OpList, unsigned N) {
304   AddNodeIDOpcode(ID, OpC);
305   AddNodeIDValueTypes(ID, VTList);
306   AddNodeIDOperands(ID, OpList, N);
307 }
308
309 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
310 /// data.
311 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
312   AddNodeIDOpcode(ID, N->getOpcode());
313   // Add the return value info.
314   AddNodeIDValueTypes(ID, N->getVTList());
315   // Add the operand info.
316   AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
317
318   // Handle SDNode leafs with special info.
319   switch (N->getOpcode()) {
320   default: break;  // Normal nodes don't need extra info.
321   case ISD::TargetConstant:
322   case ISD::Constant:
323     ID.AddInteger(cast<ConstantSDNode>(N)->getValue());
324     break;
325   case ISD::TargetConstantFP:
326   case ISD::ConstantFP: {
327     ID.AddAPFloat(cast<ConstantFPSDNode>(N)->getValueAPF());
328     break;
329   }
330   case ISD::TargetGlobalAddress:
331   case ISD::GlobalAddress:
332   case ISD::TargetGlobalTLSAddress:
333   case ISD::GlobalTLSAddress: {
334     GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
335     ID.AddPointer(GA->getGlobal());
336     ID.AddInteger(GA->getOffset());
337     break;
338   }
339   case ISD::BasicBlock:
340     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
341     break;
342   case ISD::Register:
343     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
344     break;
345   case ISD::SRCVALUE: {
346     SrcValueSDNode *SV = cast<SrcValueSDNode>(N);
347     ID.AddPointer(SV->getValue());
348     ID.AddInteger(SV->getOffset());
349     break;
350   }
351   case ISD::FrameIndex:
352   case ISD::TargetFrameIndex:
353     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
354     break;
355   case ISD::JumpTable:
356   case ISD::TargetJumpTable:
357     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
358     break;
359   case ISD::ConstantPool:
360   case ISD::TargetConstantPool: {
361     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
362     ID.AddInteger(CP->getAlignment());
363     ID.AddInteger(CP->getOffset());
364     if (CP->isMachineConstantPoolEntry())
365       CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
366     else
367       ID.AddPointer(CP->getConstVal());
368     break;
369   }
370   case ISD::LOAD: {
371     LoadSDNode *LD = cast<LoadSDNode>(N);
372     ID.AddInteger(LD->getAddressingMode());
373     ID.AddInteger(LD->getExtensionType());
374     ID.AddInteger((unsigned int)(LD->getLoadedVT()));
375     ID.AddPointer(LD->getSrcValue());
376     ID.AddInteger(LD->getSrcValueOffset());
377     ID.AddInteger(LD->getAlignment());
378     ID.AddInteger(LD->isVolatile());
379     break;
380   }
381   case ISD::STORE: {
382     StoreSDNode *ST = cast<StoreSDNode>(N);
383     ID.AddInteger(ST->getAddressingMode());
384     ID.AddInteger(ST->isTruncatingStore());
385     ID.AddInteger((unsigned int)(ST->getStoredVT()));
386     ID.AddPointer(ST->getSrcValue());
387     ID.AddInteger(ST->getSrcValueOffset());
388     ID.AddInteger(ST->getAlignment());
389     ID.AddInteger(ST->isVolatile());
390     break;
391   }
392   }
393 }
394
395 //===----------------------------------------------------------------------===//
396 //                              SelectionDAG Class
397 //===----------------------------------------------------------------------===//
398
399 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
400 /// SelectionDAG.
401 void SelectionDAG::RemoveDeadNodes() {
402   // Create a dummy node (which is not added to allnodes), that adds a reference
403   // to the root node, preventing it from being deleted.
404   HandleSDNode Dummy(getRoot());
405
406   SmallVector<SDNode*, 128> DeadNodes;
407   
408   // Add all obviously-dead nodes to the DeadNodes worklist.
409   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
410     if (I->use_empty())
411       DeadNodes.push_back(I);
412
413   // Process the worklist, deleting the nodes and adding their uses to the
414   // worklist.
415   while (!DeadNodes.empty()) {
416     SDNode *N = DeadNodes.back();
417     DeadNodes.pop_back();
418     
419     // Take the node out of the appropriate CSE map.
420     RemoveNodeFromCSEMaps(N);
421
422     // Next, brutally remove the operand list.  This is safe to do, as there are
423     // no cycles in the graph.
424     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
425       SDNode *Operand = I->Val;
426       Operand->removeUser(N);
427       
428       // Now that we removed this operand, see if there are no uses of it left.
429       if (Operand->use_empty())
430         DeadNodes.push_back(Operand);
431     }
432     if (N->OperandsNeedDelete)
433       delete[] N->OperandList;
434     N->OperandList = 0;
435     N->NumOperands = 0;
436     
437     // Finally, remove N itself.
438     AllNodes.erase(N);
439   }
440   
441   // If the root changed (e.g. it was a dead load, update the root).
442   setRoot(Dummy.getValue());
443 }
444
445 void SelectionDAG::RemoveDeadNode(SDNode *N, std::vector<SDNode*> &Deleted) {
446   SmallVector<SDNode*, 16> DeadNodes;
447   DeadNodes.push_back(N);
448
449   // Process the worklist, deleting the nodes and adding their uses to the
450   // worklist.
451   while (!DeadNodes.empty()) {
452     SDNode *N = DeadNodes.back();
453     DeadNodes.pop_back();
454     
455     // Take the node out of the appropriate CSE map.
456     RemoveNodeFromCSEMaps(N);
457
458     // Next, brutally remove the operand list.  This is safe to do, as there are
459     // no cycles in the graph.
460     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
461       SDNode *Operand = I->Val;
462       Operand->removeUser(N);
463       
464       // Now that we removed this operand, see if there are no uses of it left.
465       if (Operand->use_empty())
466         DeadNodes.push_back(Operand);
467     }
468     if (N->OperandsNeedDelete)
469       delete[] N->OperandList;
470     N->OperandList = 0;
471     N->NumOperands = 0;
472     
473     // Finally, remove N itself.
474     Deleted.push_back(N);
475     AllNodes.erase(N);
476   }
477 }
478
479 void SelectionDAG::DeleteNode(SDNode *N) {
480   assert(N->use_empty() && "Cannot delete a node that is not dead!");
481
482   // First take this out of the appropriate CSE map.
483   RemoveNodeFromCSEMaps(N);
484
485   // Finally, remove uses due to operands of this node, remove from the 
486   // AllNodes list, and delete the node.
487   DeleteNodeNotInCSEMaps(N);
488 }
489
490 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
491
492   // Remove it from the AllNodes list.
493   AllNodes.remove(N);
494     
495   // Drop all of the operands and decrement used nodes use counts.
496   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
497     I->Val->removeUser(N);
498   if (N->OperandsNeedDelete)
499     delete[] N->OperandList;
500   N->OperandList = 0;
501   N->NumOperands = 0;
502   
503   delete N;
504 }
505
506 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
507 /// correspond to it.  This is useful when we're about to delete or repurpose
508 /// the node.  We don't want future request for structurally identical nodes
509 /// to return N anymore.
510 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
511   bool Erased = false;
512   switch (N->getOpcode()) {
513   case ISD::HANDLENODE: return;  // noop.
514   case ISD::STRING:
515     Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
516     break;
517   case ISD::CONDCODE:
518     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
519            "Cond code doesn't exist!");
520     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
521     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
522     break;
523   case ISD::ExternalSymbol:
524     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
525     break;
526   case ISD::TargetExternalSymbol:
527     Erased =
528       TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
529     break;
530   case ISD::VALUETYPE:
531     Erased = ValueTypeNodes[cast<VTSDNode>(N)->getVT()] != 0;
532     ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
533     break;
534   default:
535     // Remove it from the CSE Map.
536     Erased = CSEMap.RemoveNode(N);
537     break;
538   }
539 #ifndef NDEBUG
540   // Verify that the node was actually in one of the CSE maps, unless it has a 
541   // flag result (which cannot be CSE'd) or is one of the special cases that are
542   // not subject to CSE.
543   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
544       !N->isTargetOpcode()) {
545     N->dump(this);
546     cerr << "\n";
547     assert(0 && "Node is not in map!");
548   }
549 #endif
550 }
551
552 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
553 /// has been taken out and modified in some way.  If the specified node already
554 /// exists in the CSE maps, do not modify the maps, but return the existing node
555 /// instead.  If it doesn't exist, add it and return null.
556 ///
557 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
558   assert(N->getNumOperands() && "This is a leaf node!");
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   SDNode *New = CSEMap.GetOrInsertNode(N);
568   if (New != N) return New;  // Node already existed.
569   return 0;
570 }
571
572 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
573 /// were replaced with those specified.  If this node is never memoized, 
574 /// return null, otherwise return a pointer to the slot it would take.  If a
575 /// node already exists with these operands, the slot will be non-null.
576 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
577                                            void *&InsertPos) {
578   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
579     return 0;    // Never add these nodes.
580   
581   // Check that remaining values produced are not flags.
582   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
583     if (N->getValueType(i) == MVT::Flag)
584       return 0;   // Never CSE anything that produces a flag.
585   
586   SDOperand Ops[] = { Op };
587   FoldingSetNodeID ID;
588   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
589   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
590 }
591
592 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
593 /// were replaced with those specified.  If this node is never memoized, 
594 /// return null, otherwise return a pointer to the slot it would take.  If a
595 /// node already exists with these operands, the slot will be non-null.
596 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
597                                            SDOperand Op1, SDOperand Op2,
598                                            void *&InsertPos) {
599   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
600     return 0;    // Never add these nodes.
601   
602   // Check that remaining values produced are not flags.
603   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
604     if (N->getValueType(i) == MVT::Flag)
605       return 0;   // Never CSE anything that produces a flag.
606                                               
607   SDOperand Ops[] = { Op1, Op2 };
608   FoldingSetNodeID ID;
609   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
610   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
611 }
612
613
614 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
615 /// were replaced with those specified.  If this node is never memoized, 
616 /// return null, otherwise return a pointer to the slot it would take.  If a
617 /// node already exists with these operands, the slot will be non-null.
618 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
619                                            const SDOperand *Ops,unsigned NumOps,
620                                            void *&InsertPos) {
621   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
622     return 0;    // Never add these nodes.
623   
624   // Check that remaining values produced are not flags.
625   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
626     if (N->getValueType(i) == MVT::Flag)
627       return 0;   // Never CSE anything that produces a flag.
628   
629   FoldingSetNodeID ID;
630   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
631   
632   if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
633     ID.AddInteger(LD->getAddressingMode());
634     ID.AddInteger(LD->getExtensionType());
635     ID.AddInteger((unsigned int)(LD->getLoadedVT()));
636     ID.AddPointer(LD->getSrcValue());
637     ID.AddInteger(LD->getSrcValueOffset());
638     ID.AddInteger(LD->getAlignment());
639     ID.AddInteger(LD->isVolatile());
640   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
641     ID.AddInteger(ST->getAddressingMode());
642     ID.AddInteger(ST->isTruncatingStore());
643     ID.AddInteger((unsigned int)(ST->getStoredVT()));
644     ID.AddPointer(ST->getSrcValue());
645     ID.AddInteger(ST->getSrcValueOffset());
646     ID.AddInteger(ST->getAlignment());
647     ID.AddInteger(ST->isVolatile());
648   }
649   
650   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
651 }
652
653
654 SelectionDAG::~SelectionDAG() {
655   while (!AllNodes.empty()) {
656     SDNode *N = AllNodes.begin();
657     N->SetNextInBucket(0);
658     if (N->OperandsNeedDelete)
659       delete [] N->OperandList;
660     N->OperandList = 0;
661     N->NumOperands = 0;
662     AllNodes.pop_front();
663   }
664 }
665
666 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
667   if (Op.getValueType() == VT) return Op;
668   int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
669   return getNode(ISD::AND, Op.getValueType(), Op,
670                  getConstant(Imm, Op.getValueType()));
671 }
672
673 SDOperand SelectionDAG::getString(const std::string &Val) {
674   StringSDNode *&N = StringNodes[Val];
675   if (!N) {
676     N = new StringSDNode(Val);
677     AllNodes.push_back(N);
678   }
679   return SDOperand(N, 0);
680 }
681
682 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
683   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
684   assert(!MVT::isVector(VT) && "Cannot create Vector ConstantSDNodes!");
685   
686   // Mask out any bits that are not valid for this constant.
687   Val &= MVT::getIntVTBitMask(VT);
688
689   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
690   FoldingSetNodeID ID;
691   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
692   ID.AddInteger(Val);
693   void *IP = 0;
694   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
695     return SDOperand(E, 0);
696   SDNode *N = new ConstantSDNode(isT, Val, VT);
697   CSEMap.InsertNode(N, IP);
698   AllNodes.push_back(N);
699   return SDOperand(N, 0);
700 }
701
702 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
703                                       bool isTarget) {
704   assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
705                                 
706   MVT::ValueType EltVT =
707     MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
708
709   // Do the map lookup using the actual bit pattern for the floating point
710   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
711   // we don't have issues with SNANs.
712   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
713   FoldingSetNodeID ID;
714   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
715   ID.AddAPFloat(V);
716   void *IP = 0;
717   SDNode *N = NULL;
718   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
719     if (!MVT::isVector(VT))
720       return SDOperand(N, 0);
721   if (!N) {
722     N = new ConstantFPSDNode(isTarget, V, EltVT);
723     CSEMap.InsertNode(N, IP);
724     AllNodes.push_back(N);
725   }
726
727   SDOperand Result(N, 0);
728   if (MVT::isVector(VT)) {
729     SmallVector<SDOperand, 8> Ops;
730     Ops.assign(MVT::getVectorNumElements(VT), Result);
731     Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
732   }
733   return Result;
734 }
735
736 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
737                                       bool isTarget) {
738   MVT::ValueType EltVT =
739     MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
740   if (EltVT==MVT::f32)
741     return getConstantFP(APFloat((float)Val), VT, isTarget);
742   else
743     return getConstantFP(APFloat(Val), VT, isTarget);
744 }
745
746 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
747                                          MVT::ValueType VT, int Offset,
748                                          bool isTargetGA) {
749   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
750   unsigned Opc;
751   if (GVar && GVar->isThreadLocal())
752     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
753   else
754     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
755   FoldingSetNodeID ID;
756   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
757   ID.AddPointer(GV);
758   ID.AddInteger(Offset);
759   void *IP = 0;
760   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
761    return SDOperand(E, 0);
762   SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
763   CSEMap.InsertNode(N, IP);
764   AllNodes.push_back(N);
765   return SDOperand(N, 0);
766 }
767
768 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
769                                       bool isTarget) {
770   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
771   FoldingSetNodeID ID;
772   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
773   ID.AddInteger(FI);
774   void *IP = 0;
775   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
776     return SDOperand(E, 0);
777   SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
778   CSEMap.InsertNode(N, IP);
779   AllNodes.push_back(N);
780   return SDOperand(N, 0);
781 }
782
783 SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
784   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
785   FoldingSetNodeID ID;
786   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
787   ID.AddInteger(JTI);
788   void *IP = 0;
789   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
790     return SDOperand(E, 0);
791   SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
792   CSEMap.InsertNode(N, IP);
793   AllNodes.push_back(N);
794   return SDOperand(N, 0);
795 }
796
797 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
798                                         unsigned Alignment, int Offset,
799                                         bool isTarget) {
800   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
801   FoldingSetNodeID ID;
802   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
803   ID.AddInteger(Alignment);
804   ID.AddInteger(Offset);
805   ID.AddPointer(C);
806   void *IP = 0;
807   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
808     return SDOperand(E, 0);
809   SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
810   CSEMap.InsertNode(N, IP);
811   AllNodes.push_back(N);
812   return SDOperand(N, 0);
813 }
814
815
816 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
817                                         MVT::ValueType VT,
818                                         unsigned Alignment, int Offset,
819                                         bool isTarget) {
820   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
821   FoldingSetNodeID ID;
822   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
823   ID.AddInteger(Alignment);
824   ID.AddInteger(Offset);
825   C->AddSelectionDAGCSEId(ID);
826   void *IP = 0;
827   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
828     return SDOperand(E, 0);
829   SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
830   CSEMap.InsertNode(N, IP);
831   AllNodes.push_back(N);
832   return SDOperand(N, 0);
833 }
834
835
836 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
837   FoldingSetNodeID ID;
838   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
839   ID.AddPointer(MBB);
840   void *IP = 0;
841   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
842     return SDOperand(E, 0);
843   SDNode *N = new BasicBlockSDNode(MBB);
844   CSEMap.InsertNode(N, IP);
845   AllNodes.push_back(N);
846   return SDOperand(N, 0);
847 }
848
849 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
850   assert(!MVT::isExtendedVT(VT) && "Expecting a simple value type!");
851   if ((unsigned)VT >= ValueTypeNodes.size())
852     ValueTypeNodes.resize(VT+1);
853   if (ValueTypeNodes[VT] == 0) {
854     ValueTypeNodes[VT] = new VTSDNode(VT);
855     AllNodes.push_back(ValueTypeNodes[VT]);
856   }
857
858   return SDOperand(ValueTypeNodes[VT], 0);
859 }
860
861 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
862   SDNode *&N = ExternalSymbols[Sym];
863   if (N) return SDOperand(N, 0);
864   N = new ExternalSymbolSDNode(false, Sym, VT);
865   AllNodes.push_back(N);
866   return SDOperand(N, 0);
867 }
868
869 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
870                                                 MVT::ValueType VT) {
871   SDNode *&N = TargetExternalSymbols[Sym];
872   if (N) return SDOperand(N, 0);
873   N = new ExternalSymbolSDNode(true, Sym, VT);
874   AllNodes.push_back(N);
875   return SDOperand(N, 0);
876 }
877
878 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
879   if ((unsigned)Cond >= CondCodeNodes.size())
880     CondCodeNodes.resize(Cond+1);
881   
882   if (CondCodeNodes[Cond] == 0) {
883     CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
884     AllNodes.push_back(CondCodeNodes[Cond]);
885   }
886   return SDOperand(CondCodeNodes[Cond], 0);
887 }
888
889 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
890   FoldingSetNodeID ID;
891   AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
892   ID.AddInteger(RegNo);
893   void *IP = 0;
894   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
895     return SDOperand(E, 0);
896   SDNode *N = new RegisterSDNode(RegNo, VT);
897   CSEMap.InsertNode(N, IP);
898   AllNodes.push_back(N);
899   return SDOperand(N, 0);
900 }
901
902 SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
903   assert((!V || isa<PointerType>(V->getType())) &&
904          "SrcValue is not a pointer?");
905
906   FoldingSetNodeID ID;
907   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
908   ID.AddPointer(V);
909   ID.AddInteger(Offset);
910   void *IP = 0;
911   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
912     return SDOperand(E, 0);
913   SDNode *N = new SrcValueSDNode(V, Offset);
914   CSEMap.InsertNode(N, IP);
915   AllNodes.push_back(N);
916   return SDOperand(N, 0);
917 }
918
919 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
920 /// specified value type.
921 SDOperand SelectionDAG::CreateStackTemporary(MVT::ValueType VT) {
922   MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
923   unsigned ByteSize = MVT::getSizeInBits(VT)/8;
924   const Type *Ty = MVT::getTypeForValueType(VT);
925   unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
926   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
927   return getFrameIndex(FrameIdx, TLI.getPointerTy());
928 }
929
930
931 SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
932                                   SDOperand N2, ISD::CondCode Cond) {
933   // These setcc operations always fold.
934   switch (Cond) {
935   default: break;
936   case ISD::SETFALSE:
937   case ISD::SETFALSE2: return getConstant(0, VT);
938   case ISD::SETTRUE:
939   case ISD::SETTRUE2:  return getConstant(1, VT);
940     
941   case ISD::SETOEQ:
942   case ISD::SETOGT:
943   case ISD::SETOGE:
944   case ISD::SETOLT:
945   case ISD::SETOLE:
946   case ISD::SETONE:
947   case ISD::SETO:
948   case ISD::SETUO:
949   case ISD::SETUEQ:
950   case ISD::SETUNE:
951     assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
952     break;
953   }
954   
955   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
956     uint64_t C2 = N2C->getValue();
957     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
958       uint64_t C1 = N1C->getValue();
959       
960       // Sign extend the operands if required
961       if (ISD::isSignedIntSetCC(Cond)) {
962         C1 = N1C->getSignExtended();
963         C2 = N2C->getSignExtended();
964       }
965       
966       switch (Cond) {
967       default: assert(0 && "Unknown integer setcc!");
968       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
969       case ISD::SETNE:  return getConstant(C1 != C2, VT);
970       case ISD::SETULT: return getConstant(C1 <  C2, VT);
971       case ISD::SETUGT: return getConstant(C1 >  C2, VT);
972       case ISD::SETULE: return getConstant(C1 <= C2, VT);
973       case ISD::SETUGE: return getConstant(C1 >= C2, VT);
974       case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
975       case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
976       case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
977       case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
978       }
979     }
980   }
981   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
982     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
983       // No compile time operations on this type yet.
984       if (N1C->getValueType(0) == MVT::ppcf128)
985         return SDOperand();
986
987       APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
988       switch (Cond) {
989       default: break;
990       case ISD::SETEQ:  if (R==APFloat::cmpUnordered) 
991                           return getNode(ISD::UNDEF, VT);
992                         // fall through
993       case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
994       case ISD::SETNE:  if (R==APFloat::cmpUnordered) 
995                           return getNode(ISD::UNDEF, VT);
996                         // fall through
997       case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
998                                            R==APFloat::cmpLessThan, VT);
999       case ISD::SETLT:  if (R==APFloat::cmpUnordered) 
1000                           return getNode(ISD::UNDEF, VT);
1001                         // fall through
1002       case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1003       case ISD::SETGT:  if (R==APFloat::cmpUnordered) 
1004                           return getNode(ISD::UNDEF, VT);
1005                         // fall through
1006       case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1007       case ISD::SETLE:  if (R==APFloat::cmpUnordered) 
1008                           return getNode(ISD::UNDEF, VT);
1009                         // fall through
1010       case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1011                                            R==APFloat::cmpEqual, VT);
1012       case ISD::SETGE:  if (R==APFloat::cmpUnordered) 
1013                           return getNode(ISD::UNDEF, VT);
1014                         // fall through
1015       case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1016                                            R==APFloat::cmpEqual, VT);
1017       case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
1018       case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
1019       case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1020                                            R==APFloat::cmpEqual, VT);
1021       case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1022       case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1023                                            R==APFloat::cmpLessThan, VT);
1024       case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1025                                            R==APFloat::cmpUnordered, VT);
1026       case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1027       case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1028       }
1029     } else {
1030       // Ensure that the constant occurs on the RHS.
1031       return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1032     }
1033       
1034   // Could not fold it.
1035   return SDOperand();
1036 }
1037
1038 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1039 /// this predicate to simplify operations downstream.  Mask is known to be zero
1040 /// for bits that V cannot have.
1041 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, uint64_t Mask, 
1042                                      unsigned Depth) const {
1043   // The masks are not wide enough to represent this type!  Should use APInt.
1044   if (Op.getValueType() == MVT::i128)
1045     return false;
1046   
1047   uint64_t KnownZero, KnownOne;
1048   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1049   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1050   return (KnownZero & Mask) == Mask;
1051 }
1052
1053 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1054 /// known to be either zero or one and return them in the KnownZero/KnownOne
1055 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
1056 /// processing.
1057 void SelectionDAG::ComputeMaskedBits(SDOperand Op, uint64_t Mask, 
1058                                      uint64_t &KnownZero, uint64_t &KnownOne,
1059                                      unsigned Depth) const {
1060   KnownZero = KnownOne = 0;   // Don't know anything.
1061   if (Depth == 6 || Mask == 0)
1062     return;  // Limit search depth.
1063   
1064   // The masks are not wide enough to represent this type!  Should use APInt.
1065   if (Op.getValueType() == MVT::i128)
1066     return;
1067   
1068   uint64_t KnownZero2, KnownOne2;
1069
1070   switch (Op.getOpcode()) {
1071   case ISD::Constant:
1072     // We know all of the bits for a constant!
1073     KnownOne = cast<ConstantSDNode>(Op)->getValue() & Mask;
1074     KnownZero = ~KnownOne & Mask;
1075     return;
1076   case ISD::AND:
1077     // If either the LHS or the RHS are Zero, the result is zero.
1078     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1079     Mask &= ~KnownZero;
1080     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1081     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1082     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1083
1084     // Output known-1 bits are only known if set in both the LHS & RHS.
1085     KnownOne &= KnownOne2;
1086     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1087     KnownZero |= KnownZero2;
1088     return;
1089   case ISD::OR:
1090     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1091     Mask &= ~KnownOne;
1092     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1093     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1094     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1095     
1096     // Output known-0 bits are only known if clear in both the LHS & RHS.
1097     KnownZero &= KnownZero2;
1098     // Output known-1 are known to be set if set in either the LHS | RHS.
1099     KnownOne |= KnownOne2;
1100     return;
1101   case ISD::XOR: {
1102     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1103     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1104     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1105     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1106     
1107     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1108     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1109     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1110     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1111     KnownZero = KnownZeroOut;
1112     return;
1113   }
1114   case ISD::SELECT:
1115     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1116     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1117     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1118     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1119     
1120     // Only known if known in both the LHS and RHS.
1121     KnownOne &= KnownOne2;
1122     KnownZero &= KnownZero2;
1123     return;
1124   case ISD::SELECT_CC:
1125     ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1126     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1127     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1128     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1129     
1130     // Only known if known in both the LHS and RHS.
1131     KnownOne &= KnownOne2;
1132     KnownZero &= KnownZero2;
1133     return;
1134   case ISD::SETCC:
1135     // If we know the result of a setcc has the top bits zero, use this info.
1136     if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
1137       KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
1138     return;
1139   case ISD::SHL:
1140     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1141     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1142       ComputeMaskedBits(Op.getOperand(0), Mask >> SA->getValue(),
1143                         KnownZero, KnownOne, Depth+1);
1144       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1145       KnownZero <<= SA->getValue();
1146       KnownOne  <<= SA->getValue();
1147       KnownZero |= (1ULL << SA->getValue())-1;  // low bits known zero.
1148     }
1149     return;
1150   case ISD::SRL:
1151     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1152     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1153       MVT::ValueType VT = Op.getValueType();
1154       unsigned ShAmt = SA->getValue();
1155
1156       uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1157       ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt) & TypeMask,
1158                         KnownZero, KnownOne, Depth+1);
1159       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1160       KnownZero &= TypeMask;
1161       KnownOne  &= TypeMask;
1162       KnownZero >>= ShAmt;
1163       KnownOne  >>= ShAmt;
1164
1165       uint64_t HighBits = (1ULL << ShAmt)-1;
1166       HighBits <<= MVT::getSizeInBits(VT)-ShAmt;
1167       KnownZero |= HighBits;  // High bits known zero.
1168     }
1169     return;
1170   case ISD::SRA:
1171     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1172       MVT::ValueType VT = Op.getValueType();
1173       unsigned ShAmt = SA->getValue();
1174
1175       // Compute the new bits that are at the top now.
1176       uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1177
1178       uint64_t InDemandedMask = (Mask << ShAmt) & TypeMask;
1179       // If any of the demanded bits are produced by the sign extension, we also
1180       // demand the input sign bit.
1181       uint64_t HighBits = (1ULL << ShAmt)-1;
1182       HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
1183       if (HighBits & Mask)
1184         InDemandedMask |= MVT::getIntVTSignBit(VT);
1185       
1186       ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1187                         Depth+1);
1188       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1189       KnownZero &= TypeMask;
1190       KnownOne  &= TypeMask;
1191       KnownZero >>= ShAmt;
1192       KnownOne  >>= ShAmt;
1193       
1194       // Handle the sign bits.
1195       uint64_t SignBit = MVT::getIntVTSignBit(VT);
1196       SignBit >>= ShAmt;  // Adjust to where it is now in the mask.
1197       
1198       if (KnownZero & SignBit) {       
1199         KnownZero |= HighBits;  // New bits are known zero.
1200       } else if (KnownOne & SignBit) {
1201         KnownOne  |= HighBits;  // New bits are known one.
1202       }
1203     }
1204     return;
1205   case ISD::SIGN_EXTEND_INREG: {
1206     MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1207     
1208     // Sign extension.  Compute the demanded bits in the result that are not 
1209     // present in the input.
1210     uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & Mask;
1211
1212     uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
1213     int64_t InputDemandedBits = Mask & MVT::getIntVTBitMask(EVT);
1214     
1215     // If the sign extended bits are demanded, we know that the sign
1216     // bit is demanded.
1217     if (NewBits)
1218       InputDemandedBits |= InSignBit;
1219     
1220     ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1221                       KnownZero, KnownOne, Depth+1);
1222     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1223     
1224     // If the sign bit of the input is known set or clear, then we know the
1225     // top bits of the result.
1226     if (KnownZero & InSignBit) {          // Input sign bit known clear
1227       KnownZero |= NewBits;
1228       KnownOne  &= ~NewBits;
1229     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1230       KnownOne  |= NewBits;
1231       KnownZero &= ~NewBits;
1232     } else {                              // Input sign bit unknown
1233       KnownZero &= ~NewBits;
1234       KnownOne  &= ~NewBits;
1235     }
1236     return;
1237   }
1238   case ISD::CTTZ:
1239   case ISD::CTLZ:
1240   case ISD::CTPOP: {
1241     MVT::ValueType VT = Op.getValueType();
1242     unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
1243     KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
1244     KnownOne  = 0;
1245     return;
1246   }
1247   case ISD::LOAD: {
1248     if (ISD::isZEXTLoad(Op.Val)) {
1249       LoadSDNode *LD = cast<LoadSDNode>(Op);
1250       MVT::ValueType VT = LD->getLoadedVT();
1251       KnownZero |= ~MVT::getIntVTBitMask(VT) & Mask;
1252     }
1253     return;
1254   }
1255   case ISD::ZERO_EXTEND: {
1256     uint64_t InMask  = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
1257     uint64_t NewBits = (~InMask) & Mask;
1258     ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero, 
1259                       KnownOne, Depth+1);
1260     KnownZero |= NewBits & Mask;
1261     KnownOne  &= ~NewBits;
1262     return;
1263   }
1264   case ISD::SIGN_EXTEND: {
1265     MVT::ValueType InVT = Op.getOperand(0).getValueType();
1266     unsigned InBits    = MVT::getSizeInBits(InVT);
1267     uint64_t InMask    = MVT::getIntVTBitMask(InVT);
1268     uint64_t InSignBit = 1ULL << (InBits-1);
1269     uint64_t NewBits   = (~InMask) & Mask;
1270     uint64_t InDemandedBits = Mask & InMask;
1271
1272     // If any of the sign extended bits are demanded, we know that the sign
1273     // bit is demanded.
1274     if (NewBits & Mask)
1275       InDemandedBits |= InSignBit;
1276     
1277     ComputeMaskedBits(Op.getOperand(0), InDemandedBits, KnownZero, 
1278                       KnownOne, Depth+1);
1279     // If the sign bit is known zero or one, the  top bits match.
1280     if (KnownZero & InSignBit) {
1281       KnownZero |= NewBits;
1282       KnownOne  &= ~NewBits;
1283     } else if (KnownOne & InSignBit) {
1284       KnownOne  |= NewBits;
1285       KnownZero &= ~NewBits;
1286     } else {   // Otherwise, top bits aren't known.
1287       KnownOne  &= ~NewBits;
1288       KnownZero &= ~NewBits;
1289     }
1290     return;
1291   }
1292   case ISD::ANY_EXTEND: {
1293     MVT::ValueType VT = Op.getOperand(0).getValueType();
1294     ComputeMaskedBits(Op.getOperand(0), Mask & MVT::getIntVTBitMask(VT),
1295                       KnownZero, KnownOne, Depth+1);
1296     return;
1297   }
1298   case ISD::TRUNCATE: {
1299     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1300     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1301     uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
1302     KnownZero &= OutMask;
1303     KnownOne &= OutMask;
1304     break;
1305   }
1306   case ISD::AssertZext: {
1307     MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1308     uint64_t InMask = MVT::getIntVTBitMask(VT);
1309     ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero, 
1310                       KnownOne, Depth+1);
1311     KnownZero |= (~InMask) & Mask;
1312     return;
1313   }
1314   case ISD::ADD: {
1315     // If either the LHS or the RHS are Zero, the result is zero.
1316     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1317     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1318     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1319     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1320     
1321     // Output known-0 bits are known if clear or set in both the low clear bits
1322     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
1323     // low 3 bits clear.
1324     uint64_t KnownZeroOut = std::min(CountTrailingZeros_64(~KnownZero), 
1325                                      CountTrailingZeros_64(~KnownZero2));
1326     
1327     KnownZero = (1ULL << KnownZeroOut) - 1;
1328     KnownOne = 0;
1329     return;
1330   }
1331   case ISD::SUB: {
1332     ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1333     if (!CLHS) return;
1334
1335     // We know that the top bits of C-X are clear if X contains less bits
1336     // than C (i.e. no wrap-around can happen).  For example, 20-X is
1337     // positive if we can prove that X is >= 0 and < 16.
1338     MVT::ValueType VT = CLHS->getValueType(0);
1339     if ((CLHS->getValue() & MVT::getIntVTSignBit(VT)) == 0) {  // sign bit clear
1340       unsigned NLZ = CountLeadingZeros_64(CLHS->getValue()+1);
1341       uint64_t MaskV = (1ULL << (63-NLZ))-1; // NLZ can't be 64 with no sign bit
1342       MaskV = ~MaskV & MVT::getIntVTBitMask(VT);
1343       ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
1344
1345       // If all of the MaskV bits are known to be zero, then we know the output
1346       // top bits are zero, because we now know that the output is from [0-C].
1347       if ((KnownZero & MaskV) == MaskV) {
1348         unsigned NLZ2 = CountLeadingZeros_64(CLHS->getValue());
1349         KnownZero = ~((1ULL << (64-NLZ2))-1) & Mask;  // Top bits known zero.
1350         KnownOne = 0;   // No one bits known.
1351       } else {
1352         KnownZero = KnownOne = 0;  // Otherwise, nothing known.
1353       }
1354     }
1355     return;
1356   }
1357   default:
1358     // Allow the target to implement this method for its nodes.
1359     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1360   case ISD::INTRINSIC_WO_CHAIN:
1361   case ISD::INTRINSIC_W_CHAIN:
1362   case ISD::INTRINSIC_VOID:
1363       TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1364     }
1365     return;
1366   }
1367 }
1368
1369 /// ComputeNumSignBits - Return the number of times the sign bit of the
1370 /// register is replicated into the other bits.  We know that at least 1 bit
1371 /// is always equal to the sign bit (itself), but other cases can give us
1372 /// information.  For example, immediately after an "SRA X, 2", we know that
1373 /// the top 3 bits are all equal to each other, so we return 3.
1374 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1375   MVT::ValueType VT = Op.getValueType();
1376   assert(MVT::isInteger(VT) && "Invalid VT!");
1377   unsigned VTBits = MVT::getSizeInBits(VT);
1378   unsigned Tmp, Tmp2;
1379   
1380   if (Depth == 6)
1381     return 1;  // Limit search depth.
1382
1383   switch (Op.getOpcode()) {
1384   default: break;
1385   case ISD::AssertSext:
1386     Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1387     return VTBits-Tmp+1;
1388   case ISD::AssertZext:
1389     Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1390     return VTBits-Tmp;
1391     
1392   case ISD::Constant: {
1393     uint64_t Val = cast<ConstantSDNode>(Op)->getValue();
1394     // If negative, invert the bits, then look at it.
1395     if (Val & MVT::getIntVTSignBit(VT))
1396       Val = ~Val;
1397     
1398     // Shift the bits so they are the leading bits in the int64_t.
1399     Val <<= 64-VTBits;
1400     
1401     // Return # leading zeros.  We use 'min' here in case Val was zero before
1402     // shifting.  We don't want to return '64' as for an i32 "0".
1403     return std::min(VTBits, CountLeadingZeros_64(Val));
1404   }
1405     
1406   case ISD::SIGN_EXTEND:
1407     Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1408     return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1409     
1410   case ISD::SIGN_EXTEND_INREG:
1411     // Max of the input and what this extends.
1412     Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1413     Tmp = VTBits-Tmp+1;
1414     
1415     Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1416     return std::max(Tmp, Tmp2);
1417
1418   case ISD::SRA:
1419     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1420     // SRA X, C   -> adds C sign bits.
1421     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1422       Tmp += C->getValue();
1423       if (Tmp > VTBits) Tmp = VTBits;
1424     }
1425     return Tmp;
1426   case ISD::SHL:
1427     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1428       // shl destroys sign bits.
1429       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1430       if (C->getValue() >= VTBits ||      // Bad shift.
1431           C->getValue() >= Tmp) break;    // Shifted all sign bits out.
1432       return Tmp - C->getValue();
1433     }
1434     break;
1435   case ISD::AND:
1436   case ISD::OR:
1437   case ISD::XOR:    // NOT is handled here.
1438     // Logical binary ops preserve the number of sign bits.
1439     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1440     if (Tmp == 1) return 1;  // Early out.
1441     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1442     return std::min(Tmp, Tmp2);
1443
1444   case ISD::SELECT:
1445     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1446     if (Tmp == 1) return 1;  // Early out.
1447     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1448     return std::min(Tmp, Tmp2);
1449     
1450   case ISD::SETCC:
1451     // If setcc returns 0/-1, all bits are sign bits.
1452     if (TLI.getSetCCResultContents() ==
1453         TargetLowering::ZeroOrNegativeOneSetCCResult)
1454       return VTBits;
1455     break;
1456   case ISD::ROTL:
1457   case ISD::ROTR:
1458     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1459       unsigned RotAmt = C->getValue() & (VTBits-1);
1460       
1461       // Handle rotate right by N like a rotate left by 32-N.
1462       if (Op.getOpcode() == ISD::ROTR)
1463         RotAmt = (VTBits-RotAmt) & (VTBits-1);
1464
1465       // If we aren't rotating out all of the known-in sign bits, return the
1466       // number that are left.  This handles rotl(sext(x), 1) for example.
1467       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1468       if (Tmp > RotAmt+1) return Tmp-RotAmt;
1469     }
1470     break;
1471   case ISD::ADD:
1472     // Add can have at most one carry bit.  Thus we know that the output
1473     // is, at worst, one more bit than the inputs.
1474     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1475     if (Tmp == 1) return 1;  // Early out.
1476       
1477     // Special case decrementing a value (ADD X, -1):
1478     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1479       if (CRHS->isAllOnesValue()) {
1480         uint64_t KnownZero, KnownOne;
1481         uint64_t Mask = MVT::getIntVTBitMask(VT);
1482         ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1483         
1484         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1485         // sign bits set.
1486         if ((KnownZero|1) == Mask)
1487           return VTBits;
1488         
1489         // If we are subtracting one from a positive number, there is no carry
1490         // out of the result.
1491         if (KnownZero & MVT::getIntVTSignBit(VT))
1492           return Tmp;
1493       }
1494       
1495     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1496     if (Tmp2 == 1) return 1;
1497       return std::min(Tmp, Tmp2)-1;
1498     break;
1499     
1500   case ISD::SUB:
1501     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1502     if (Tmp2 == 1) return 1;
1503       
1504     // Handle NEG.
1505     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1506       if (CLHS->getValue() == 0) {
1507         uint64_t KnownZero, KnownOne;
1508         uint64_t Mask = MVT::getIntVTBitMask(VT);
1509         ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1510         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1511         // sign bits set.
1512         if ((KnownZero|1) == Mask)
1513           return VTBits;
1514         
1515         // If the input is known to be positive (the sign bit is known clear),
1516         // the output of the NEG has the same number of sign bits as the input.
1517         if (KnownZero & MVT::getIntVTSignBit(VT))
1518           return Tmp2;
1519         
1520         // Otherwise, we treat this like a SUB.
1521       }
1522     
1523     // Sub can have at most one carry bit.  Thus we know that the output
1524     // is, at worst, one more bit than the inputs.
1525     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1526     if (Tmp == 1) return 1;  // Early out.
1527       return std::min(Tmp, Tmp2)-1;
1528     break;
1529   case ISD::TRUNCATE:
1530     // FIXME: it's tricky to do anything useful for this, but it is an important
1531     // case for targets like X86.
1532     break;
1533   }
1534   
1535   // Handle LOADX separately here. EXTLOAD case will fallthrough.
1536   if (Op.getOpcode() == ISD::LOAD) {
1537     LoadSDNode *LD = cast<LoadSDNode>(Op);
1538     unsigned ExtType = LD->getExtensionType();
1539     switch (ExtType) {
1540     default: break;
1541     case ISD::SEXTLOAD:    // '17' bits known
1542       Tmp = MVT::getSizeInBits(LD->getLoadedVT());
1543       return VTBits-Tmp+1;
1544     case ISD::ZEXTLOAD:    // '16' bits known
1545       Tmp = MVT::getSizeInBits(LD->getLoadedVT());
1546       return VTBits-Tmp;
1547     }
1548   }
1549
1550   // Allow the target to implement this method for its nodes.
1551   if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1552       Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 
1553       Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1554       Op.getOpcode() == ISD::INTRINSIC_VOID) {
1555     unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1556     if (NumBits > 1) return NumBits;
1557   }
1558   
1559   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1560   // use this information.
1561   uint64_t KnownZero, KnownOne;
1562   uint64_t Mask = MVT::getIntVTBitMask(VT);
1563   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1564   
1565   uint64_t SignBit = MVT::getIntVTSignBit(VT);
1566   if (KnownZero & SignBit) {        // SignBit is 0
1567     Mask = KnownZero;
1568   } else if (KnownOne & SignBit) {  // SignBit is 1;
1569     Mask = KnownOne;
1570   } else {
1571     // Nothing known.
1572     return 1;
1573   }
1574   
1575   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1576   // the number of identical bits in the top of the input value.
1577   Mask ^= ~0ULL;
1578   Mask <<= 64-VTBits;
1579   // Return # leading zeros.  We use 'min' here in case Val was zero before
1580   // shifting.  We don't want to return '64' as for an i32 "0".
1581   return std::min(VTBits, CountLeadingZeros_64(Mask));
1582 }
1583
1584
1585 /// getNode - Gets or creates the specified node.
1586 ///
1587 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1588   FoldingSetNodeID ID;
1589   AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1590   void *IP = 0;
1591   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1592     return SDOperand(E, 0);
1593   SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1594   CSEMap.InsertNode(N, IP);
1595   
1596   AllNodes.push_back(N);
1597   return SDOperand(N, 0);
1598 }
1599
1600 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1601                                 SDOperand Operand) {
1602   unsigned Tmp1;
1603   // Constant fold unary operations with an integer constant operand.
1604   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1605     uint64_t Val = C->getValue();
1606     switch (Opcode) {
1607     default: break;
1608     case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
1609     case ISD::ANY_EXTEND:
1610     case ISD::ZERO_EXTEND: return getConstant(Val, VT);
1611     case ISD::TRUNCATE:    return getConstant(Val, VT);
1612     case ISD::UINT_TO_FP:
1613     case ISD::SINT_TO_FP: {
1614       const uint64_t zero[] = {0, 0};
1615       // No compile time operations on this type.
1616       if (VT==MVT::ppcf128)
1617         break;
1618       APFloat apf = APFloat(APInt(MVT::getSizeInBits(VT), 2, zero));
1619       (void)apf.convertFromZeroExtendedInteger(&Val, 
1620                                MVT::getSizeInBits(Operand.getValueType()), 
1621                                Opcode==ISD::SINT_TO_FP,
1622                                APFloat::rmNearestTiesToEven);
1623       return getConstantFP(apf, VT);
1624     }
1625     case ISD::BIT_CONVERT:
1626       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1627         return getConstantFP(BitsToFloat(Val), VT);
1628       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1629         return getConstantFP(BitsToDouble(Val), VT);
1630       break;
1631     case ISD::BSWAP:
1632       switch(VT) {
1633       default: assert(0 && "Invalid bswap!"); break;
1634       case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
1635       case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
1636       case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
1637       }
1638       break;
1639     case ISD::CTPOP:
1640       switch(VT) {
1641       default: assert(0 && "Invalid ctpop!"); break;
1642       case MVT::i1: return getConstant(Val != 0, VT);
1643       case MVT::i8: 
1644         Tmp1 = (unsigned)Val & 0xFF;
1645         return getConstant(CountPopulation_32(Tmp1), VT);
1646       case MVT::i16:
1647         Tmp1 = (unsigned)Val & 0xFFFF;
1648         return getConstant(CountPopulation_32(Tmp1), VT);
1649       case MVT::i32:
1650         return getConstant(CountPopulation_32((unsigned)Val), VT);
1651       case MVT::i64:
1652         return getConstant(CountPopulation_64(Val), VT);
1653       }
1654     case ISD::CTLZ:
1655       switch(VT) {
1656       default: assert(0 && "Invalid ctlz!"); break;
1657       case MVT::i1: return getConstant(Val == 0, VT);
1658       case MVT::i8: 
1659         Tmp1 = (unsigned)Val & 0xFF;
1660         return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
1661       case MVT::i16:
1662         Tmp1 = (unsigned)Val & 0xFFFF;
1663         return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
1664       case MVT::i32:
1665         return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
1666       case MVT::i64:
1667         return getConstant(CountLeadingZeros_64(Val), VT);
1668       }
1669     case ISD::CTTZ:
1670       switch(VT) {
1671       default: assert(0 && "Invalid cttz!"); break;
1672       case MVT::i1: return getConstant(Val == 0, VT);
1673       case MVT::i8: 
1674         Tmp1 = (unsigned)Val | 0x100;
1675         return getConstant(CountTrailingZeros_32(Tmp1), VT);
1676       case MVT::i16:
1677         Tmp1 = (unsigned)Val | 0x10000;
1678         return getConstant(CountTrailingZeros_32(Tmp1), VT);
1679       case MVT::i32:
1680         return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
1681       case MVT::i64:
1682         return getConstant(CountTrailingZeros_64(Val), VT);
1683       }
1684     }
1685   }
1686
1687   // Constant fold unary operations with a floating point constant operand.
1688   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1689     APFloat V = C->getValueAPF();    // make copy
1690     if (VT!=MVT::ppcf128 && Operand.getValueType()!=MVT::ppcf128) {
1691       switch (Opcode) {
1692       case ISD::FNEG:
1693         V.changeSign();
1694         return getConstantFP(V, VT);
1695       case ISD::FABS:
1696         V.clearSign();
1697         return getConstantFP(V, VT);
1698       case ISD::FP_ROUND:
1699       case ISD::FP_EXTEND:
1700         // This can return overflow, underflow, or inexact; we don't care.
1701         // FIXME need to be more flexible about rounding mode.
1702         (void) V.convert(VT==MVT::f32 ? APFloat::IEEEsingle : 
1703                          VT==MVT::f64 ? APFloat::IEEEdouble :
1704                          VT==MVT::f80 ? APFloat::x87DoubleExtended :
1705                          VT==MVT::f128 ? APFloat::IEEEquad :
1706                          APFloat::Bogus,
1707                          APFloat::rmNearestTiesToEven);
1708         return getConstantFP(V, VT);
1709       case ISD::FP_TO_SINT:
1710       case ISD::FP_TO_UINT: {
1711         integerPart x;
1712         assert(integerPartWidth >= 64);
1713         // FIXME need to be more flexible about rounding mode.
1714         APFloat::opStatus s = V.convertToInteger(&x, 64U,
1715                               Opcode==ISD::FP_TO_SINT,
1716                               APFloat::rmTowardZero);
1717         if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
1718           break;
1719         return getConstant(x, VT);
1720       }
1721       case ISD::BIT_CONVERT:
1722         if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1723           return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1724         else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1725           return getConstant(V.convertToAPInt().getZExtValue(), VT);
1726         break;
1727       }
1728     }
1729   }
1730
1731   unsigned OpOpcode = Operand.Val->getOpcode();
1732   switch (Opcode) {
1733   case ISD::TokenFactor:
1734     return Operand;         // Factor of one node?  No factor.
1735   case ISD::FP_ROUND:
1736   case ISD::FP_EXTEND:
1737     assert(MVT::isFloatingPoint(VT) &&
1738            MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1739     break;
1740   case ISD::SIGN_EXTEND:
1741     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1742            "Invalid SIGN_EXTEND!");
1743     if (Operand.getValueType() == VT) return Operand;   // noop extension
1744     assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1745            && "Invalid sext node, dst < src!");
1746     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1747       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1748     break;
1749   case ISD::ZERO_EXTEND:
1750     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1751            "Invalid ZERO_EXTEND!");
1752     if (Operand.getValueType() == VT) return Operand;   // noop extension
1753     assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1754            && "Invalid zext node, dst < src!");
1755     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
1756       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1757     break;
1758   case ISD::ANY_EXTEND:
1759     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1760            "Invalid ANY_EXTEND!");
1761     if (Operand.getValueType() == VT) return Operand;   // noop extension
1762     assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1763            && "Invalid anyext node, dst < src!");
1764     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1765       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
1766       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1767     break;
1768   case ISD::TRUNCATE:
1769     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1770            "Invalid TRUNCATE!");
1771     if (Operand.getValueType() == VT) return Operand;   // noop truncate
1772     assert(MVT::getSizeInBits(Operand.getValueType()) > MVT::getSizeInBits(VT)
1773            && "Invalid truncate node, src < dst!");
1774     if (OpOpcode == ISD::TRUNCATE)
1775       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1776     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1777              OpOpcode == ISD::ANY_EXTEND) {
1778       // If the source is smaller than the dest, we still need an extend.
1779       if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1780           < MVT::getSizeInBits(VT))
1781         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1782       else if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1783                > MVT::getSizeInBits(VT))
1784         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1785       else
1786         return Operand.Val->getOperand(0);
1787     }
1788     break;
1789   case ISD::BIT_CONVERT:
1790     // Basic sanity checking.
1791     assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1792            && "Cannot BIT_CONVERT between types of different sizes!");
1793     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
1794     if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
1795       return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1796     if (OpOpcode == ISD::UNDEF)
1797       return getNode(ISD::UNDEF, VT);
1798     break;
1799   case ISD::SCALAR_TO_VECTOR:
1800     assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1801            MVT::getVectorElementType(VT) == Operand.getValueType() &&
1802            "Illegal SCALAR_TO_VECTOR node!");
1803     break;
1804   case ISD::FNEG:
1805     if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
1806       return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1807                      Operand.Val->getOperand(0));
1808     if (OpOpcode == ISD::FNEG)  // --X -> X
1809       return Operand.Val->getOperand(0);
1810     break;
1811   case ISD::FABS:
1812     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
1813       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1814     break;
1815   }
1816
1817   SDNode *N;
1818   SDVTList VTs = getVTList(VT);
1819   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1820     FoldingSetNodeID ID;
1821     SDOperand Ops[1] = { Operand };
1822     AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
1823     void *IP = 0;
1824     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1825       return SDOperand(E, 0);
1826     N = new UnarySDNode(Opcode, VTs, Operand);
1827     CSEMap.InsertNode(N, IP);
1828   } else {
1829     N = new UnarySDNode(Opcode, VTs, Operand);
1830   }
1831   AllNodes.push_back(N);
1832   return SDOperand(N, 0);
1833 }
1834
1835
1836
1837 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1838                                 SDOperand N1, SDOperand N2) {
1839 #ifndef NDEBUG
1840   switch (Opcode) {
1841   case ISD::TokenFactor:
1842     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1843            N2.getValueType() == MVT::Other && "Invalid token factor!");
1844     break;
1845   case ISD::AND:
1846   case ISD::OR:
1847   case ISD::XOR:
1848   case ISD::UDIV:
1849   case ISD::UREM:
1850   case ISD::MULHU:
1851   case ISD::MULHS:
1852     assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1853     // fall through
1854   case ISD::ADD:
1855   case ISD::SUB:
1856   case ISD::MUL:
1857   case ISD::SDIV:
1858   case ISD::SREM:
1859     assert(MVT::isInteger(N1.getValueType()) && "Should use F* for FP ops");
1860     // fall through.
1861   case ISD::FADD:
1862   case ISD::FSUB:
1863   case ISD::FMUL:
1864   case ISD::FDIV:
1865   case ISD::FREM:
1866     assert(N1.getValueType() == N2.getValueType() &&
1867            N1.getValueType() == VT && "Binary operator types must match!");
1868     break;
1869   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
1870     assert(N1.getValueType() == VT &&
1871            MVT::isFloatingPoint(N1.getValueType()) && 
1872            MVT::isFloatingPoint(N2.getValueType()) &&
1873            "Invalid FCOPYSIGN!");
1874     break;
1875   case ISD::SHL:
1876   case ISD::SRA:
1877   case ISD::SRL:
1878   case ISD::ROTL:
1879   case ISD::ROTR:
1880     assert(VT == N1.getValueType() &&
1881            "Shift operators return type must be the same as their first arg");
1882     assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1883            VT != MVT::i1 && "Shifts only work on integers");
1884     break;
1885   case ISD::FP_ROUND_INREG: {
1886     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1887     assert(VT == N1.getValueType() && "Not an inreg round!");
1888     assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1889            "Cannot FP_ROUND_INREG integer types");
1890     assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1891            "Not rounding down!");
1892     break;
1893   }
1894   case ISD::AssertSext:
1895   case ISD::AssertZext:
1896   case ISD::SIGN_EXTEND_INREG: {
1897     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1898     assert(VT == N1.getValueType() && "Not an inreg extend!");
1899     assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1900            "Cannot *_EXTEND_INREG FP types");
1901     assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1902            "Not extending!");
1903   }
1904
1905   default: break;
1906   }
1907 #endif
1908
1909   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1910   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1911   if (N1C) {
1912     if (Opcode == ISD::SIGN_EXTEND_INREG) {
1913       int64_t Val = N1C->getValue();
1914       unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
1915       Val <<= 64-FromBits;
1916       Val >>= 64-FromBits;
1917       return getConstant(Val, VT);
1918     }
1919     
1920     if (N2C) {
1921       uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
1922       switch (Opcode) {
1923       case ISD::ADD: return getConstant(C1 + C2, VT);
1924       case ISD::SUB: return getConstant(C1 - C2, VT);
1925       case ISD::MUL: return getConstant(C1 * C2, VT);
1926       case ISD::UDIV:
1927         if (C2) return getConstant(C1 / C2, VT);
1928         break;
1929       case ISD::UREM :
1930         if (C2) return getConstant(C1 % C2, VT);
1931         break;
1932       case ISD::SDIV :
1933         if (C2) return getConstant(N1C->getSignExtended() /
1934                                    N2C->getSignExtended(), VT);
1935         break;
1936       case ISD::SREM :
1937         if (C2) return getConstant(N1C->getSignExtended() %
1938                                    N2C->getSignExtended(), VT);
1939         break;
1940       case ISD::AND  : return getConstant(C1 & C2, VT);
1941       case ISD::OR   : return getConstant(C1 | C2, VT);
1942       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
1943       case ISD::SHL  : return getConstant(C1 << C2, VT);
1944       case ISD::SRL  : return getConstant(C1 >> C2, VT);
1945       case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
1946       case ISD::ROTL : 
1947         return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
1948                            VT);
1949       case ISD::ROTR : 
1950         return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)), 
1951                            VT);
1952       default: break;
1953       }
1954     } else {      // Cannonicalize constant to RHS if commutative
1955       if (isCommutativeBinOp(Opcode)) {
1956         std::swap(N1C, N2C);
1957         std::swap(N1, N2);
1958       }
1959     }
1960   }
1961
1962   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1963   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1964   if (N1CFP) {
1965     if (N2CFP && VT!=MVT::ppcf128) {
1966       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
1967       APFloat::opStatus s;
1968       switch (Opcode) {
1969       case ISD::FADD: 
1970         s = V1.add(V2, APFloat::rmNearestTiesToEven);
1971         if (s!=APFloat::opInvalidOp)
1972           return getConstantFP(V1, VT);
1973         break;
1974       case ISD::FSUB: 
1975         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
1976         if (s!=APFloat::opInvalidOp)
1977           return getConstantFP(V1, VT);
1978         break;
1979       case ISD::FMUL:
1980         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
1981         if (s!=APFloat::opInvalidOp)
1982           return getConstantFP(V1, VT);
1983         break;
1984       case ISD::FDIV:
1985         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
1986         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
1987           return getConstantFP(V1, VT);
1988         break;
1989       case ISD::FREM :
1990         s = V1.mod(V2, APFloat::rmNearestTiesToEven);
1991         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
1992           return getConstantFP(V1, VT);
1993         break;
1994       case ISD::FCOPYSIGN:
1995         V1.copySign(V2);
1996         return getConstantFP(V1, VT);
1997       default: break;
1998       }
1999     } else {      // Cannonicalize constant to RHS if commutative
2000       if (isCommutativeBinOp(Opcode)) {
2001         std::swap(N1CFP, N2CFP);
2002         std::swap(N1, N2);
2003       }
2004     }
2005   }
2006   
2007   // Canonicalize an UNDEF to the RHS, even over a constant.
2008   if (N1.getOpcode() == ISD::UNDEF) {
2009     if (isCommutativeBinOp(Opcode)) {
2010       std::swap(N1, N2);
2011     } else {
2012       switch (Opcode) {
2013       case ISD::FP_ROUND_INREG:
2014       case ISD::SIGN_EXTEND_INREG:
2015       case ISD::SUB:
2016       case ISD::FSUB:
2017       case ISD::FDIV:
2018       case ISD::FREM:
2019       case ISD::SRA:
2020         return N1;     // fold op(undef, arg2) -> undef
2021       case ISD::UDIV:
2022       case ISD::SDIV:
2023       case ISD::UREM:
2024       case ISD::SREM:
2025       case ISD::SRL:
2026       case ISD::SHL:
2027         if (!MVT::isVector(VT)) 
2028           return getConstant(0, VT);    // fold op(undef, arg2) -> 0
2029         // For vectors, we can't easily build an all zero vector, just return
2030         // the LHS.
2031         return N2;
2032       }
2033     }
2034   }
2035   
2036   // Fold a bunch of operators when the RHS is undef. 
2037   if (N2.getOpcode() == ISD::UNDEF) {
2038     switch (Opcode) {
2039     case ISD::ADD:
2040     case ISD::ADDC:
2041     case ISD::ADDE:
2042     case ISD::SUB:
2043     case ISD::FADD:
2044     case ISD::FSUB:
2045     case ISD::FMUL:
2046     case ISD::FDIV:
2047     case ISD::FREM:
2048     case ISD::UDIV:
2049     case ISD::SDIV:
2050     case ISD::UREM:
2051     case ISD::SREM:
2052     case ISD::XOR:
2053       return N2;       // fold op(arg1, undef) -> undef
2054     case ISD::MUL: 
2055     case ISD::AND:
2056     case ISD::SRL:
2057     case ISD::SHL:
2058       if (!MVT::isVector(VT)) 
2059         return getConstant(0, VT);  // fold op(arg1, undef) -> 0
2060       // For vectors, we can't easily build an all zero vector, just return
2061       // the LHS.
2062       return N1;
2063     case ISD::OR:
2064       if (!MVT::isVector(VT)) 
2065         return getConstant(MVT::getIntVTBitMask(VT), VT);
2066       // For vectors, we can't easily build an all one vector, just return
2067       // the LHS.
2068       return N1;
2069     case ISD::SRA:
2070       return N1;
2071     }
2072   }
2073
2074   // Fold operations.
2075   switch (Opcode) {
2076   case ISD::TokenFactor:
2077     // Fold trivial token factors.
2078     if (N1.getOpcode() == ISD::EntryToken) return N2;
2079     if (N2.getOpcode() == ISD::EntryToken) return N1;
2080     break;
2081       
2082   case ISD::AND:
2083     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
2084     // worth handling here.
2085     if (N2C && N2C->getValue() == 0)
2086       return N2;
2087     break;
2088   case ISD::OR:
2089   case ISD::XOR:
2090     // (X ^| 0) -> X.  This commonly occurs when legalizing i64 values, so it's
2091     // worth handling here.
2092     if (N2C && N2C->getValue() == 0)
2093       return N1;
2094     break;
2095   case ISD::FP_ROUND_INREG:
2096     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
2097     break;
2098   case ISD::SIGN_EXTEND_INREG: {
2099     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2100     if (EVT == VT) return N1;  // Not actually extending
2101     break;
2102   }
2103   case ISD::EXTRACT_VECTOR_ELT:
2104     assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2105
2106     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2107     // expanding copies of large vectors from registers.
2108     if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2109         N1.getNumOperands() > 0) {
2110       unsigned Factor =
2111         MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2112       return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2113                      N1.getOperand(N2C->getValue() / Factor),
2114                      getConstant(N2C->getValue() % Factor, N2.getValueType()));
2115     }
2116
2117     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2118     // expanding large vector constants.
2119     if (N1.getOpcode() == ISD::BUILD_VECTOR)
2120       return N1.getOperand(N2C->getValue());
2121
2122     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2123     // operations are lowered to scalars.
2124     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2125       if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2126         if (IEC == N2C)
2127           return N1.getOperand(1);
2128         else
2129           return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2130       }
2131     break;
2132   case ISD::EXTRACT_ELEMENT:
2133     assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2134     
2135     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2136     // 64-bit integers into 32-bit parts.  Instead of building the extract of
2137     // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 
2138     if (N1.getOpcode() == ISD::BUILD_PAIR)
2139       return N1.getOperand(N2C->getValue());
2140     
2141     // EXTRACT_ELEMENT of a constant int is also very common.
2142     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2143       unsigned Shift = MVT::getSizeInBits(VT) * N2C->getValue();
2144       return getConstant(C->getValue() >> Shift, VT);
2145     }
2146     break;
2147
2148   // FIXME: figure out how to safely handle things like
2149   // int foo(int x) { return 1 << (x & 255); }
2150   // int bar() { return foo(256); }
2151 #if 0
2152   case ISD::SHL:
2153   case ISD::SRL:
2154   case ISD::SRA:
2155     if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2156         cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
2157       return getNode(Opcode, VT, N1, N2.getOperand(0));
2158     else if (N2.getOpcode() == ISD::AND)
2159       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
2160         // If the and is only masking out bits that cannot effect the shift,
2161         // eliminate the and.
2162         unsigned NumBits = MVT::getSizeInBits(VT);
2163         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2164           return getNode(Opcode, VT, N1, N2.getOperand(0));
2165       }
2166     break;
2167 #endif
2168   }
2169
2170   // Memoize this node if possible.
2171   SDNode *N;
2172   SDVTList VTs = getVTList(VT);
2173   if (VT != MVT::Flag) {
2174     SDOperand Ops[] = { N1, N2 };
2175     FoldingSetNodeID ID;
2176     AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2177     void *IP = 0;
2178     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2179       return SDOperand(E, 0);
2180     N = new BinarySDNode(Opcode, VTs, N1, N2);
2181     CSEMap.InsertNode(N, IP);
2182   } else {
2183     N = new BinarySDNode(Opcode, VTs, N1, N2);
2184   }
2185
2186   AllNodes.push_back(N);
2187   return SDOperand(N, 0);
2188 }
2189
2190 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2191                                 SDOperand N1, SDOperand N2, SDOperand N3) {
2192   // Perform various simplifications.
2193   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2194   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2195   switch (Opcode) {
2196   case ISD::SETCC: {
2197     // Use FoldSetCC to simplify SETCC's.
2198     SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2199     if (Simp.Val) return Simp;
2200     break;
2201   }
2202   case ISD::SELECT:
2203     if (N1C)
2204       if (N1C->getValue())
2205         return N2;             // select true, X, Y -> X
2206       else
2207         return N3;             // select false, X, Y -> Y
2208
2209     if (N2 == N3) return N2;   // select C, X, X -> X
2210     break;
2211   case ISD::BRCOND:
2212     if (N2C)
2213       if (N2C->getValue()) // Unconditional branch
2214         return getNode(ISD::BR, MVT::Other, N1, N3);
2215       else
2216         return N1;         // Never-taken branch
2217     break;
2218   case ISD::VECTOR_SHUFFLE:
2219     assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2220            MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2221            N3.getOpcode() == ISD::BUILD_VECTOR &&
2222            MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2223            "Illegal VECTOR_SHUFFLE node!");
2224     break;
2225   case ISD::BIT_CONVERT:
2226     // Fold bit_convert nodes from a type to themselves.
2227     if (N1.getValueType() == VT)
2228       return N1;
2229     break;
2230   }
2231
2232   // Memoize node if it doesn't produce a flag.
2233   SDNode *N;
2234   SDVTList VTs = getVTList(VT);
2235   if (VT != MVT::Flag) {
2236     SDOperand Ops[] = { N1, N2, N3 };
2237     FoldingSetNodeID ID;
2238     AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2239     void *IP = 0;
2240     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2241       return SDOperand(E, 0);
2242     N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2243     CSEMap.InsertNode(N, IP);
2244   } else {
2245     N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2246   }
2247   AllNodes.push_back(N);
2248   return SDOperand(N, 0);
2249 }
2250
2251 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2252                                 SDOperand N1, SDOperand N2, SDOperand N3,
2253                                 SDOperand N4) {
2254   SDOperand Ops[] = { N1, N2, N3, N4 };
2255   return getNode(Opcode, VT, Ops, 4);
2256 }
2257
2258 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2259                                 SDOperand N1, SDOperand N2, SDOperand N3,
2260                                 SDOperand N4, SDOperand N5) {
2261   SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2262   return getNode(Opcode, VT, Ops, 5);
2263 }
2264
2265 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2266                                 SDOperand Chain, SDOperand Ptr,
2267                                 const Value *SV, int SVOffset,
2268                                 bool isVolatile, unsigned Alignment) {
2269   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2270     const Type *Ty = 0;
2271     if (VT != MVT::iPTR) {
2272       Ty = MVT::getTypeForValueType(VT);
2273     } else if (SV) {
2274       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2275       assert(PT && "Value for load must be a pointer");
2276       Ty = PT->getElementType();
2277     }  
2278     assert(Ty && "Could not get type information for load");
2279     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2280   }
2281   SDVTList VTs = getVTList(VT, MVT::Other);
2282   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2283   SDOperand Ops[] = { Chain, Ptr, Undef };
2284   FoldingSetNodeID ID;
2285   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2286   ID.AddInteger(ISD::UNINDEXED);
2287   ID.AddInteger(ISD::NON_EXTLOAD);
2288   ID.AddInteger((unsigned int)VT);
2289   ID.AddPointer(SV);
2290   ID.AddInteger(SVOffset);
2291   ID.AddInteger(Alignment);
2292   ID.AddInteger(isVolatile);
2293   void *IP = 0;
2294   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2295     return SDOperand(E, 0);
2296   SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED,
2297                              ISD::NON_EXTLOAD, VT, SV, SVOffset, Alignment,
2298                              isVolatile);
2299   CSEMap.InsertNode(N, IP);
2300   AllNodes.push_back(N);
2301   return SDOperand(N, 0);
2302 }
2303
2304 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2305                                    SDOperand Chain, SDOperand Ptr,
2306                                    const Value *SV,
2307                                    int SVOffset, MVT::ValueType EVT,
2308                                    bool isVolatile, unsigned Alignment) {
2309   // If they are asking for an extending load from/to the same thing, return a
2310   // normal load.
2311   if (VT == EVT)
2312     ExtType = ISD::NON_EXTLOAD;
2313
2314   if (MVT::isVector(VT))
2315     assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2316   else
2317     assert(MVT::getSizeInBits(EVT) < MVT::getSizeInBits(VT) &&
2318            "Should only be an extending load, not truncating!");
2319   assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2320          "Cannot sign/zero extend a FP/Vector load!");
2321   assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2322          "Cannot convert from FP to Int or Int -> FP!");
2323
2324   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2325     const Type *Ty = 0;
2326     if (VT != MVT::iPTR) {
2327       Ty = MVT::getTypeForValueType(VT);
2328     } else if (SV) {
2329       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2330       assert(PT && "Value for load must be a pointer");
2331       Ty = PT->getElementType();
2332     }  
2333     assert(Ty && "Could not get type information for load");
2334     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2335   }
2336   SDVTList VTs = getVTList(VT, MVT::Other);
2337   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2338   SDOperand Ops[] = { Chain, Ptr, Undef };
2339   FoldingSetNodeID ID;
2340   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2341   ID.AddInteger(ISD::UNINDEXED);
2342   ID.AddInteger(ExtType);
2343   ID.AddInteger((unsigned int)EVT);
2344   ID.AddPointer(SV);
2345   ID.AddInteger(SVOffset);
2346   ID.AddInteger(Alignment);
2347   ID.AddInteger(isVolatile);
2348   void *IP = 0;
2349   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2350     return SDOperand(E, 0);
2351   SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED, ExtType, EVT,
2352                              SV, SVOffset, Alignment, isVolatile);
2353   CSEMap.InsertNode(N, IP);
2354   AllNodes.push_back(N);
2355   return SDOperand(N, 0);
2356 }
2357
2358 SDOperand
2359 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2360                              SDOperand Offset, ISD::MemIndexedMode AM) {
2361   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2362   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2363          "Load is already a indexed load!");
2364   MVT::ValueType VT = OrigLoad.getValueType();
2365   SDVTList VTs = getVTList(VT, Base.getValueType(), MVT::Other);
2366   SDOperand Ops[] = { LD->getChain(), Base, Offset };
2367   FoldingSetNodeID ID;
2368   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2369   ID.AddInteger(AM);
2370   ID.AddInteger(LD->getExtensionType());
2371   ID.AddInteger((unsigned int)(LD->getLoadedVT()));
2372   ID.AddPointer(LD->getSrcValue());
2373   ID.AddInteger(LD->getSrcValueOffset());
2374   ID.AddInteger(LD->getAlignment());
2375   ID.AddInteger(LD->isVolatile());
2376   void *IP = 0;
2377   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2378     return SDOperand(E, 0);
2379   SDNode *N = new LoadSDNode(Ops, VTs, AM,
2380                              LD->getExtensionType(), LD->getLoadedVT(),
2381                              LD->getSrcValue(), LD->getSrcValueOffset(),
2382                              LD->getAlignment(), LD->isVolatile());
2383   CSEMap.InsertNode(N, IP);
2384   AllNodes.push_back(N);
2385   return SDOperand(N, 0);
2386 }
2387
2388 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2389                                  SDOperand Ptr, const Value *SV, int SVOffset,
2390                                  bool isVolatile, unsigned Alignment) {
2391   MVT::ValueType VT = Val.getValueType();
2392
2393   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2394     const Type *Ty = 0;
2395     if (VT != MVT::iPTR) {
2396       Ty = MVT::getTypeForValueType(VT);
2397     } else if (SV) {
2398       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2399       assert(PT && "Value for store must be a pointer");
2400       Ty = PT->getElementType();
2401     }
2402     assert(Ty && "Could not get type information for store");
2403     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2404   }
2405   SDVTList VTs = getVTList(MVT::Other);
2406   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2407   SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2408   FoldingSetNodeID ID;
2409   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2410   ID.AddInteger(ISD::UNINDEXED);
2411   ID.AddInteger(false);
2412   ID.AddInteger((unsigned int)VT);
2413   ID.AddPointer(SV);
2414   ID.AddInteger(SVOffset);
2415   ID.AddInteger(Alignment);
2416   ID.AddInteger(isVolatile);
2417   void *IP = 0;
2418   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2419     return SDOperand(E, 0);
2420   SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
2421                               VT, SV, SVOffset, Alignment, isVolatile);
2422   CSEMap.InsertNode(N, IP);
2423   AllNodes.push_back(N);
2424   return SDOperand(N, 0);
2425 }
2426
2427 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
2428                                       SDOperand Ptr, const Value *SV,
2429                                       int SVOffset, MVT::ValueType SVT,
2430                                       bool isVolatile, unsigned Alignment) {
2431   MVT::ValueType VT = Val.getValueType();
2432   bool isTrunc = VT != SVT;
2433
2434   assert(MVT::getSizeInBits(VT) > MVT::getSizeInBits(SVT) &&
2435          "Not a truncation?");
2436   assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
2437          "Can't do FP-INT conversion!");
2438
2439   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2440     const Type *Ty = 0;
2441     if (VT != MVT::iPTR) {
2442       Ty = MVT::getTypeForValueType(VT);
2443     } else if (SV) {
2444       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2445       assert(PT && "Value for store must be a pointer");
2446       Ty = PT->getElementType();
2447     }
2448     assert(Ty && "Could not get type information for store");
2449     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2450   }
2451   SDVTList VTs = getVTList(MVT::Other);
2452   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2453   SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2454   FoldingSetNodeID ID;
2455   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2456   ID.AddInteger(ISD::UNINDEXED);
2457   ID.AddInteger(isTrunc);
2458   ID.AddInteger((unsigned int)SVT);
2459   ID.AddPointer(SV);
2460   ID.AddInteger(SVOffset);
2461   ID.AddInteger(Alignment);
2462   ID.AddInteger(isVolatile);
2463   void *IP = 0;
2464   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2465     return SDOperand(E, 0);
2466   SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, isTrunc,
2467                               SVT, SV, SVOffset, Alignment, isVolatile);
2468   CSEMap.InsertNode(N, IP);
2469   AllNodes.push_back(N);
2470   return SDOperand(N, 0);
2471 }
2472
2473 SDOperand
2474 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
2475                               SDOperand Offset, ISD::MemIndexedMode AM) {
2476   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
2477   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
2478          "Store is already a indexed store!");
2479   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
2480   SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
2481   FoldingSetNodeID ID;
2482   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2483   ID.AddInteger(AM);
2484   ID.AddInteger(ST->isTruncatingStore());
2485   ID.AddInteger((unsigned int)(ST->getStoredVT()));
2486   ID.AddPointer(ST->getSrcValue());
2487   ID.AddInteger(ST->getSrcValueOffset());
2488   ID.AddInteger(ST->getAlignment());
2489   ID.AddInteger(ST->isVolatile());
2490   void *IP = 0;
2491   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2492     return SDOperand(E, 0);
2493   SDNode *N = new StoreSDNode(Ops, VTs, AM,
2494                               ST->isTruncatingStore(), ST->getStoredVT(),
2495                               ST->getSrcValue(), ST->getSrcValueOffset(),
2496                               ST->getAlignment(), ST->isVolatile());
2497   CSEMap.InsertNode(N, IP);
2498   AllNodes.push_back(N);
2499   return SDOperand(N, 0);
2500 }
2501
2502 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
2503                                  SDOperand Chain, SDOperand Ptr,
2504                                  SDOperand SV) {
2505   SDOperand Ops[] = { Chain, Ptr, SV };
2506   return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
2507 }
2508
2509 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2510                                 const SDOperand *Ops, unsigned NumOps) {
2511   switch (NumOps) {
2512   case 0: return getNode(Opcode, VT);
2513   case 1: return getNode(Opcode, VT, Ops[0]);
2514   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
2515   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
2516   default: break;
2517   }
2518   
2519   switch (Opcode) {
2520   default: break;
2521   case ISD::SELECT_CC: {
2522     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
2523     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
2524            "LHS and RHS of condition must have same type!");
2525     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2526            "True and False arms of SelectCC must have same type!");
2527     assert(Ops[2].getValueType() == VT &&
2528            "select_cc node must be of same type as true and false value!");
2529     break;
2530   }
2531   case ISD::BR_CC: {
2532     assert(NumOps == 5 && "BR_CC takes 5 operands!");
2533     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2534            "LHS/RHS of comparison should match types!");
2535     break;
2536   }
2537   }
2538
2539   // Memoize nodes.
2540   SDNode *N;
2541   SDVTList VTs = getVTList(VT);
2542   if (VT != MVT::Flag) {
2543     FoldingSetNodeID ID;
2544     AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
2545     void *IP = 0;
2546     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2547       return SDOperand(E, 0);
2548     N = new SDNode(Opcode, VTs, Ops, NumOps);
2549     CSEMap.InsertNode(N, IP);
2550   } else {
2551     N = new SDNode(Opcode, VTs, Ops, NumOps);
2552   }
2553   AllNodes.push_back(N);
2554   return SDOperand(N, 0);
2555 }
2556
2557 SDOperand SelectionDAG::getNode(unsigned Opcode,
2558                                 std::vector<MVT::ValueType> &ResultTys,
2559                                 const SDOperand *Ops, unsigned NumOps) {
2560   return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
2561                  Ops, NumOps);
2562 }
2563
2564 SDOperand SelectionDAG::getNode(unsigned Opcode,
2565                                 const MVT::ValueType *VTs, unsigned NumVTs,
2566                                 const SDOperand *Ops, unsigned NumOps) {
2567   if (NumVTs == 1)
2568     return getNode(Opcode, VTs[0], Ops, NumOps);
2569   return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
2570 }  
2571   
2572 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2573                                 const SDOperand *Ops, unsigned NumOps) {
2574   if (VTList.NumVTs == 1)
2575     return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
2576
2577   switch (Opcode) {
2578   // FIXME: figure out how to safely handle things like
2579   // int foo(int x) { return 1 << (x & 255); }
2580   // int bar() { return foo(256); }
2581 #if 0
2582   case ISD::SRA_PARTS:
2583   case ISD::SRL_PARTS:
2584   case ISD::SHL_PARTS:
2585     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2586         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
2587       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2588     else if (N3.getOpcode() == ISD::AND)
2589       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
2590         // If the and is only masking out bits that cannot effect the shift,
2591         // eliminate the and.
2592         unsigned NumBits = MVT::getSizeInBits(VT)*2;
2593         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2594           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2595       }
2596     break;
2597 #endif
2598   }
2599
2600   // Memoize the node unless it returns a flag.
2601   SDNode *N;
2602   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
2603     FoldingSetNodeID ID;
2604     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
2605     void *IP = 0;
2606     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2607       return SDOperand(E, 0);
2608     if (NumOps == 1)
2609       N = new UnarySDNode(Opcode, VTList, Ops[0]);
2610     else if (NumOps == 2)
2611       N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2612     else if (NumOps == 3)
2613       N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2614     else
2615       N = new SDNode(Opcode, VTList, Ops, NumOps);
2616     CSEMap.InsertNode(N, IP);
2617   } else {
2618     if (NumOps == 1)
2619       N = new UnarySDNode(Opcode, VTList, Ops[0]);
2620     else if (NumOps == 2)
2621       N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2622     else if (NumOps == 3)
2623       N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2624     else
2625       N = new SDNode(Opcode, VTList, Ops, NumOps);
2626   }
2627   AllNodes.push_back(N);
2628   return SDOperand(N, 0);
2629 }
2630
2631 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
2632   return getNode(Opcode, VTList, 0, 0);
2633 }
2634
2635 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2636                                 SDOperand N1) {
2637   SDOperand Ops[] = { N1 };
2638   return getNode(Opcode, VTList, Ops, 1);
2639 }
2640
2641 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2642                                 SDOperand N1, SDOperand N2) {
2643   SDOperand Ops[] = { N1, N2 };
2644   return getNode(Opcode, VTList, Ops, 2);
2645 }
2646
2647 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2648                                 SDOperand N1, SDOperand N2, SDOperand N3) {
2649   SDOperand Ops[] = { N1, N2, N3 };
2650   return getNode(Opcode, VTList, Ops, 3);
2651 }
2652
2653 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2654                                 SDOperand N1, SDOperand N2, SDOperand N3,
2655                                 SDOperand N4) {
2656   SDOperand Ops[] = { N1, N2, N3, N4 };
2657   return getNode(Opcode, VTList, Ops, 4);
2658 }
2659
2660 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2661                                 SDOperand N1, SDOperand N2, SDOperand N3,
2662                                 SDOperand N4, SDOperand N5) {
2663   SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2664   return getNode(Opcode, VTList, Ops, 5);
2665 }
2666
2667 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
2668   return makeVTList(SDNode::getValueTypeList(VT), 1);
2669 }
2670
2671 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
2672   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2673        E = VTList.end(); I != E; ++I) {
2674     if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
2675       return makeVTList(&(*I)[0], 2);
2676   }
2677   std::vector<MVT::ValueType> V;
2678   V.push_back(VT1);
2679   V.push_back(VT2);
2680   VTList.push_front(V);
2681   return makeVTList(&(*VTList.begin())[0], 2);
2682 }
2683 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
2684                                  MVT::ValueType VT3) {
2685   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2686        E = VTList.end(); I != E; ++I) {
2687     if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
2688         (*I)[2] == VT3)
2689       return makeVTList(&(*I)[0], 3);
2690   }
2691   std::vector<MVT::ValueType> V;
2692   V.push_back(VT1);
2693   V.push_back(VT2);
2694   V.push_back(VT3);
2695   VTList.push_front(V);
2696   return makeVTList(&(*VTList.begin())[0], 3);
2697 }
2698
2699 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
2700   switch (NumVTs) {
2701     case 0: assert(0 && "Cannot have nodes without results!");
2702     case 1: return getVTList(VTs[0]);
2703     case 2: return getVTList(VTs[0], VTs[1]);
2704     case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
2705     default: break;
2706   }
2707
2708   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2709        E = VTList.end(); I != E; ++I) {
2710     if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
2711    
2712     bool NoMatch = false;
2713     for (unsigned i = 2; i != NumVTs; ++i)
2714       if (VTs[i] != (*I)[i]) {
2715         NoMatch = true;
2716         break;
2717       }
2718     if (!NoMatch)
2719       return makeVTList(&*I->begin(), NumVTs);
2720   }
2721   
2722   VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
2723   return makeVTList(&*VTList.begin()->begin(), NumVTs);
2724 }
2725
2726
2727 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
2728 /// specified operands.  If the resultant node already exists in the DAG,
2729 /// this does not modify the specified node, instead it returns the node that
2730 /// already exists.  If the resultant node does not exist in the DAG, the
2731 /// input node is returned.  As a degenerate case, if you specify the same
2732 /// input operands as the node already has, the input node is returned.
2733 SDOperand SelectionDAG::
2734 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
2735   SDNode *N = InN.Val;
2736   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
2737   
2738   // Check to see if there is no change.
2739   if (Op == N->getOperand(0)) return InN;
2740   
2741   // See if the modified node already exists.
2742   void *InsertPos = 0;
2743   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
2744     return SDOperand(Existing, InN.ResNo);
2745   
2746   // Nope it doesn't.  Remove the node from it's current place in the maps.
2747   if (InsertPos)
2748     RemoveNodeFromCSEMaps(N);
2749   
2750   // Now we update the operands.
2751   N->OperandList[0].Val->removeUser(N);
2752   Op.Val->addUser(N);
2753   N->OperandList[0] = Op;
2754   
2755   // If this gets put into a CSE map, add it.
2756   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2757   return InN;
2758 }
2759
2760 SDOperand SelectionDAG::
2761 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
2762   SDNode *N = InN.Val;
2763   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
2764   
2765   // Check to see if there is no change.
2766   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
2767     return InN;   // No operands changed, just return the input node.
2768   
2769   // See if the modified node already exists.
2770   void *InsertPos = 0;
2771   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
2772     return SDOperand(Existing, InN.ResNo);
2773   
2774   // Nope it doesn't.  Remove the node from it's current place in the maps.
2775   if (InsertPos)
2776     RemoveNodeFromCSEMaps(N);
2777   
2778   // Now we update the operands.
2779   if (N->OperandList[0] != Op1) {
2780     N->OperandList[0].Val->removeUser(N);
2781     Op1.Val->addUser(N);
2782     N->OperandList[0] = Op1;
2783   }
2784   if (N->OperandList[1] != Op2) {
2785     N->OperandList[1].Val->removeUser(N);
2786     Op2.Val->addUser(N);
2787     N->OperandList[1] = Op2;
2788   }
2789   
2790   // If this gets put into a CSE map, add it.
2791   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2792   return InN;
2793 }
2794
2795 SDOperand SelectionDAG::
2796 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2797   SDOperand Ops[] = { Op1, Op2, Op3 };
2798   return UpdateNodeOperands(N, Ops, 3);
2799 }
2800
2801 SDOperand SelectionDAG::
2802 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, 
2803                    SDOperand Op3, SDOperand Op4) {
2804   SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
2805   return UpdateNodeOperands(N, Ops, 4);
2806 }
2807
2808 SDOperand SelectionDAG::
2809 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2810                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2811   SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
2812   return UpdateNodeOperands(N, Ops, 5);
2813 }
2814
2815
2816 SDOperand SelectionDAG::
2817 UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
2818   SDNode *N = InN.Val;
2819   assert(N->getNumOperands() == NumOps &&
2820          "Update with wrong number of operands");
2821   
2822   // Check to see if there is no change.
2823   bool AnyChange = false;
2824   for (unsigned i = 0; i != NumOps; ++i) {
2825     if (Ops[i] != N->getOperand(i)) {
2826       AnyChange = true;
2827       break;
2828     }
2829   }
2830   
2831   // No operands changed, just return the input node.
2832   if (!AnyChange) return InN;
2833   
2834   // See if the modified node already exists.
2835   void *InsertPos = 0;
2836   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
2837     return SDOperand(Existing, InN.ResNo);
2838   
2839   // Nope it doesn't.  Remove the node from it's current place in the maps.
2840   if (InsertPos)
2841     RemoveNodeFromCSEMaps(N);
2842   
2843   // Now we update the operands.
2844   for (unsigned i = 0; i != NumOps; ++i) {
2845     if (N->OperandList[i] != Ops[i]) {
2846       N->OperandList[i].Val->removeUser(N);
2847       Ops[i].Val->addUser(N);
2848       N->OperandList[i] = Ops[i];
2849     }
2850   }
2851
2852   // If this gets put into a CSE map, add it.
2853   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2854   return InN;
2855 }
2856
2857
2858 /// MorphNodeTo - This frees the operands of the current node, resets the
2859 /// opcode, types, and operands to the specified value.  This should only be
2860 /// used by the SelectionDAG class.
2861 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
2862                          const SDOperand *Ops, unsigned NumOps) {
2863   NodeType = Opc;
2864   ValueList = L.VTs;
2865   NumValues = L.NumVTs;
2866   
2867   // Clear the operands list, updating used nodes to remove this from their
2868   // use list.
2869   for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2870     I->Val->removeUser(this);
2871   
2872   // If NumOps is larger than the # of operands we currently have, reallocate
2873   // the operand list.
2874   if (NumOps > NumOperands) {
2875     if (OperandsNeedDelete)
2876       delete [] OperandList;
2877     OperandList = new SDOperand[NumOps];
2878     OperandsNeedDelete = true;
2879   }
2880   
2881   // Assign the new operands.
2882   NumOperands = NumOps;
2883   
2884   for (unsigned i = 0, e = NumOps; i != e; ++i) {
2885     OperandList[i] = Ops[i];
2886     SDNode *N = OperandList[i].Val;
2887     N->Uses.push_back(this);
2888   }
2889 }
2890
2891 /// SelectNodeTo - These are used for target selectors to *mutate* the
2892 /// specified node to have the specified return type, Target opcode, and
2893 /// operands.  Note that target opcodes are stored as
2894 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
2895 ///
2896 /// Note that SelectNodeTo returns the resultant node.  If there is already a
2897 /// node of the specified opcode and operands, it returns that node instead of
2898 /// the current one.
2899 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2900                                    MVT::ValueType VT) {
2901   SDVTList VTs = getVTList(VT);
2902   FoldingSetNodeID ID;
2903   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2904   void *IP = 0;
2905   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2906     return ON;
2907    
2908   RemoveNodeFromCSEMaps(N);
2909   
2910   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2911
2912   CSEMap.InsertNode(N, IP);
2913   return N;
2914 }
2915
2916 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2917                                    MVT::ValueType VT, SDOperand Op1) {
2918   // If an identical node already exists, use it.
2919   SDVTList VTs = getVTList(VT);
2920   SDOperand Ops[] = { Op1 };
2921   
2922   FoldingSetNodeID ID;
2923   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2924   void *IP = 0;
2925   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2926     return ON;
2927                                        
2928   RemoveNodeFromCSEMaps(N);
2929   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2930   CSEMap.InsertNode(N, IP);
2931   return N;
2932 }
2933
2934 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2935                                    MVT::ValueType VT, SDOperand Op1,
2936                                    SDOperand Op2) {
2937   // If an identical node already exists, use it.
2938   SDVTList VTs = getVTList(VT);
2939   SDOperand Ops[] = { Op1, Op2 };
2940   
2941   FoldingSetNodeID ID;
2942   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2943   void *IP = 0;
2944   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2945     return ON;
2946                                        
2947   RemoveNodeFromCSEMaps(N);
2948   
2949   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2950   
2951   CSEMap.InsertNode(N, IP);   // Memoize the new node.
2952   return N;
2953 }
2954
2955 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2956                                    MVT::ValueType VT, SDOperand Op1,
2957                                    SDOperand Op2, SDOperand Op3) {
2958   // If an identical node already exists, use it.
2959   SDVTList VTs = getVTList(VT);
2960   SDOperand Ops[] = { Op1, Op2, Op3 };
2961   FoldingSetNodeID ID;
2962   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2963   void *IP = 0;
2964   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2965     return ON;
2966                                        
2967   RemoveNodeFromCSEMaps(N);
2968   
2969   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2970
2971   CSEMap.InsertNode(N, IP);   // Memoize the new node.
2972   return N;
2973 }
2974
2975 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2976                                    MVT::ValueType VT, const SDOperand *Ops,
2977                                    unsigned NumOps) {
2978   // If an identical node already exists, use it.
2979   SDVTList VTs = getVTList(VT);
2980   FoldingSetNodeID ID;
2981   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
2982   void *IP = 0;
2983   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2984     return ON;
2985                                        
2986   RemoveNodeFromCSEMaps(N);
2987   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
2988   
2989   CSEMap.InsertNode(N, IP);   // Memoize the new node.
2990   return N;
2991 }
2992
2993 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
2994                                    MVT::ValueType VT1, MVT::ValueType VT2,
2995                                    SDOperand Op1, SDOperand Op2) {
2996   SDVTList VTs = getVTList(VT1, VT2);
2997   FoldingSetNodeID ID;
2998   SDOperand Ops[] = { Op1, Op2 };
2999   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3000   void *IP = 0;
3001   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3002     return ON;
3003
3004   RemoveNodeFromCSEMaps(N);
3005   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3006   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3007   return N;
3008 }
3009
3010 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3011                                    MVT::ValueType VT1, MVT::ValueType VT2,
3012                                    SDOperand Op1, SDOperand Op2, 
3013                                    SDOperand Op3) {
3014   // If an identical node already exists, use it.
3015   SDVTList VTs = getVTList(VT1, VT2);
3016   SDOperand Ops[] = { Op1, Op2, Op3 };
3017   FoldingSetNodeID ID;
3018   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3019   void *IP = 0;
3020   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3021     return ON;
3022
3023   RemoveNodeFromCSEMaps(N);
3024
3025   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3026   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3027   return N;
3028 }
3029
3030
3031 /// getTargetNode - These are used for target selectors to create a new node
3032 /// with specified return type(s), target opcode, and operands.
3033 ///
3034 /// Note that getTargetNode returns the resultant node.  If there is already a
3035 /// node of the specified opcode and operands, it returns that node instead of
3036 /// the current one.
3037 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
3038   return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3039 }
3040 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3041                                     SDOperand Op1) {
3042   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3043 }
3044 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3045                                     SDOperand Op1, SDOperand Op2) {
3046   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3047 }
3048 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3049                                     SDOperand Op1, SDOperand Op2,
3050                                     SDOperand Op3) {
3051   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3052 }
3053 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3054                                     const SDOperand *Ops, unsigned NumOps) {
3055   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3056 }
3057 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3058                                     MVT::ValueType VT2) {
3059   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3060   SDOperand Op;
3061   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3062 }
3063 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3064                                     MVT::ValueType VT2, SDOperand Op1) {
3065   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3066   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3067 }
3068 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3069                                     MVT::ValueType VT2, SDOperand Op1,
3070                                     SDOperand Op2) {
3071   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3072   SDOperand Ops[] = { Op1, Op2 };
3073   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3074 }
3075 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3076                                     MVT::ValueType VT2, SDOperand Op1,
3077                                     SDOperand Op2, SDOperand Op3) {
3078   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3079   SDOperand Ops[] = { Op1, Op2, Op3 };
3080   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3081 }
3082 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
3083                                     MVT::ValueType VT2,
3084                                     const SDOperand *Ops, unsigned NumOps) {
3085   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3086   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3087 }
3088 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3089                                     MVT::ValueType VT2, MVT::ValueType VT3,
3090                                     SDOperand Op1, SDOperand Op2) {
3091   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3092   SDOperand Ops[] = { Op1, Op2 };
3093   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3094 }
3095 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3096                                     MVT::ValueType VT2, MVT::ValueType VT3,
3097                                     SDOperand Op1, SDOperand Op2,
3098                                     SDOperand Op3) {
3099   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3100   SDOperand Ops[] = { Op1, Op2, Op3 };
3101   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3102 }
3103 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
3104                                     MVT::ValueType VT2, MVT::ValueType VT3,
3105                                     const SDOperand *Ops, unsigned NumOps) {
3106   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3107   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3108 }
3109 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
3110                                     MVT::ValueType VT2, MVT::ValueType VT3,
3111                                     MVT::ValueType VT4,
3112                                     const SDOperand *Ops, unsigned NumOps) {
3113   std::vector<MVT::ValueType> VTList;
3114   VTList.push_back(VT1);
3115   VTList.push_back(VT2);
3116   VTList.push_back(VT3);
3117   VTList.push_back(VT4);
3118   const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3119   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3120 }
3121 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3122                                     std::vector<MVT::ValueType> &ResultTys,
3123                                     const SDOperand *Ops, unsigned NumOps) {
3124   const MVT::ValueType *VTs = getNodeValueTypes(ResultTys);
3125   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3126                  Ops, NumOps).Val;
3127 }
3128
3129 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3130 /// This can cause recursive merging of nodes in the DAG.
3131 ///
3132 /// This version assumes From/To have a single result value.
3133 ///
3134 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
3135                                       std::vector<SDNode*> *Deleted) {
3136   SDNode *From = FromN.Val, *To = ToN.Val;
3137   assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
3138          "Cannot replace with this method!");
3139   assert(From != To && "Cannot replace uses of with self");
3140   
3141   while (!From->use_empty()) {
3142     // Process users until they are all gone.
3143     SDNode *U = *From->use_begin();
3144     
3145     // This node is about to morph, remove its old self from the CSE maps.
3146     RemoveNodeFromCSEMaps(U);
3147     
3148     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3149          I != E; ++I)
3150       if (I->Val == From) {
3151         From->removeUser(U);
3152         I->Val = To;
3153         To->addUser(U);
3154       }
3155
3156     // Now that we have modified U, add it back to the CSE maps.  If it already
3157     // exists there, recursively merge the results together.
3158     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3159       ReplaceAllUsesWith(U, Existing, Deleted);
3160       // U is now dead.
3161       if (Deleted) Deleted->push_back(U);
3162       DeleteNodeNotInCSEMaps(U);
3163     }
3164   }
3165 }
3166
3167 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3168 /// This can cause recursive merging of nodes in the DAG.
3169 ///
3170 /// This version assumes From/To have matching types and numbers of result
3171 /// values.
3172 ///
3173 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3174                                       std::vector<SDNode*> *Deleted) {
3175   assert(From != To && "Cannot replace uses of with self");
3176   assert(From->getNumValues() == To->getNumValues() &&
3177          "Cannot use this version of ReplaceAllUsesWith!");
3178   if (From->getNumValues() == 1) {  // If possible, use the faster version.
3179     ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
3180     return;
3181   }
3182   
3183   while (!From->use_empty()) {
3184     // Process users until they are all gone.
3185     SDNode *U = *From->use_begin();
3186     
3187     // This node is about to morph, remove its old self from the CSE maps.
3188     RemoveNodeFromCSEMaps(U);
3189     
3190     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3191          I != E; ++I)
3192       if (I->Val == From) {
3193         From->removeUser(U);
3194         I->Val = To;
3195         To->addUser(U);
3196       }
3197         
3198     // Now that we have modified U, add it back to the CSE maps.  If it already
3199     // exists there, recursively merge the results together.
3200     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3201       ReplaceAllUsesWith(U, Existing, Deleted);
3202       // U is now dead.
3203       if (Deleted) Deleted->push_back(U);
3204       DeleteNodeNotInCSEMaps(U);
3205     }
3206   }
3207 }
3208
3209 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3210 /// This can cause recursive merging of nodes in the DAG.
3211 ///
3212 /// This version can replace From with any result values.  To must match the
3213 /// number and types of values returned by From.
3214 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3215                                       const SDOperand *To,
3216                                       std::vector<SDNode*> *Deleted) {
3217   if (From->getNumValues() == 1 && To[0].Val->getNumValues() == 1) {
3218     // Degenerate case handled above.
3219     ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
3220     return;
3221   }
3222
3223   while (!From->use_empty()) {
3224     // Process users until they are all gone.
3225     SDNode *U = *From->use_begin();
3226     
3227     // This node is about to morph, remove its old self from the CSE maps.
3228     RemoveNodeFromCSEMaps(U);
3229     
3230     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3231          I != E; ++I)
3232       if (I->Val == From) {
3233         const SDOperand &ToOp = To[I->ResNo];
3234         From->removeUser(U);
3235         *I = ToOp;
3236         ToOp.Val->addUser(U);
3237       }
3238         
3239     // Now that we have modified U, add it back to the CSE maps.  If it already
3240     // exists there, recursively merge the results together.
3241     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3242       ReplaceAllUsesWith(U, Existing, Deleted);
3243       // U is now dead.
3244       if (Deleted) Deleted->push_back(U);
3245       DeleteNodeNotInCSEMaps(U);
3246     }
3247   }
3248 }
3249
3250 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3251 /// uses of other values produced by From.Val alone.  The Deleted vector is
3252 /// handled the same was as for ReplaceAllUsesWith.
3253 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3254                                              std::vector<SDNode*> *Deleted) {
3255   assert(From != To && "Cannot replace a value with itself");
3256   // Handle the simple, trivial, case efficiently.
3257   if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
3258     ReplaceAllUsesWith(From, To, Deleted);
3259     return;
3260   }
3261   
3262   // Get all of the users of From.Val.  We want these in a nice,
3263   // deterministically ordered and uniqued set, so we use a SmallSetVector.
3264   SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
3265
3266   std::vector<SDNode*> LocalDeletionVector;
3267   
3268   // Pick a deletion vector to use.  If the user specified one, use theirs,
3269   // otherwise use a local one.
3270   std::vector<SDNode*> *DeleteVector = Deleted ? Deleted : &LocalDeletionVector;
3271   while (!Users.empty()) {
3272     // We know that this user uses some value of From.  If it is the right
3273     // value, update it.
3274     SDNode *User = Users.back();
3275     Users.pop_back();
3276     
3277     // Scan for an operand that matches From.
3278     SDOperand *Op = User->OperandList, *E = User->OperandList+User->NumOperands;
3279     for (; Op != E; ++Op)
3280       if (*Op == From) break;
3281     
3282     // If there are no matches, the user must use some other result of From.
3283     if (Op == E) continue;
3284       
3285     // Okay, we know this user needs to be updated.  Remove its old self
3286     // from the CSE maps.
3287     RemoveNodeFromCSEMaps(User);
3288     
3289     // Update all operands that match "From".
3290     for (; Op != E; ++Op) {
3291       if (*Op == From) {
3292         From.Val->removeUser(User);
3293         *Op = To;
3294         To.Val->addUser(User);
3295       }
3296     }
3297                
3298     // Now that we have modified User, add it back to the CSE maps.  If it
3299     // already exists there, recursively merge the results together.
3300     SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
3301     if (!Existing) continue;  // Continue on to next user.
3302     
3303     // If there was already an existing matching node, use ReplaceAllUsesWith
3304     // to replace the dead one with the existing one.  However, this can cause
3305     // recursive merging of other unrelated nodes down the line.  The merging
3306     // can cause deletion of nodes that used the old value.  In this case,
3307     // we have to be certain to remove them from the Users set.
3308     unsigned NumDeleted = DeleteVector->size();
3309     ReplaceAllUsesWith(User, Existing, DeleteVector);
3310     
3311     // User is now dead.
3312     DeleteVector->push_back(User);
3313     DeleteNodeNotInCSEMaps(User);
3314     
3315     // We have to be careful here, because ReplaceAllUsesWith could have
3316     // deleted a user of From, which means there may be dangling pointers
3317     // in the "Users" setvector.  Scan over the deleted node pointers and
3318     // remove them from the setvector.
3319     for (unsigned i = NumDeleted, e = DeleteVector->size(); i != e; ++i)
3320       Users.remove((*DeleteVector)[i]);
3321
3322     // If the user doesn't need the set of deleted elements, don't retain them
3323     // to the next loop iteration.
3324     if (Deleted == 0)
3325       LocalDeletionVector.clear();
3326   }
3327 }
3328
3329
3330 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3331 /// their allnodes order. It returns the maximum id.
3332 unsigned SelectionDAG::AssignNodeIds() {
3333   unsigned Id = 0;
3334   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3335     SDNode *N = I;
3336     N->setNodeId(Id++);
3337   }
3338   return Id;
3339 }
3340
3341 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
3342 /// based on their topological order. It returns the maximum id and a vector
3343 /// of the SDNodes* in assigned order by reference.
3344 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
3345   unsigned DAGSize = AllNodes.size();
3346   std::vector<unsigned> InDegree(DAGSize);
3347   std::vector<SDNode*> Sources;
3348
3349   // Use a two pass approach to avoid using a std::map which is slow.
3350   unsigned Id = 0;
3351   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
3352     SDNode *N = I;
3353     N->setNodeId(Id++);
3354     unsigned Degree = N->use_size();
3355     InDegree[N->getNodeId()] = Degree;
3356     if (Degree == 0)
3357       Sources.push_back(N);
3358   }
3359
3360   TopOrder.clear();
3361   while (!Sources.empty()) {
3362     SDNode *N = Sources.back();
3363     Sources.pop_back();
3364     TopOrder.push_back(N);
3365     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
3366       SDNode *P = I->Val;
3367       unsigned Degree = --InDegree[P->getNodeId()];
3368       if (Degree == 0)
3369         Sources.push_back(P);
3370     }
3371   }
3372
3373   // Second pass, assign the actual topological order as node ids.
3374   Id = 0;
3375   for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
3376        TI != TE; ++TI)
3377     (*TI)->setNodeId(Id++);
3378
3379   return Id;
3380 }
3381
3382
3383
3384 //===----------------------------------------------------------------------===//
3385 //                              SDNode Class
3386 //===----------------------------------------------------------------------===//
3387
3388 // Out-of-line virtual method to give class a home.
3389 void SDNode::ANCHOR() {}
3390 void UnarySDNode::ANCHOR() {}
3391 void BinarySDNode::ANCHOR() {}
3392 void TernarySDNode::ANCHOR() {}
3393 void HandleSDNode::ANCHOR() {}
3394 void StringSDNode::ANCHOR() {}
3395 void ConstantSDNode::ANCHOR() {}
3396 void ConstantFPSDNode::ANCHOR() {}
3397 void GlobalAddressSDNode::ANCHOR() {}
3398 void FrameIndexSDNode::ANCHOR() {}
3399 void JumpTableSDNode::ANCHOR() {}
3400 void ConstantPoolSDNode::ANCHOR() {}
3401 void BasicBlockSDNode::ANCHOR() {}
3402 void SrcValueSDNode::ANCHOR() {}
3403 void RegisterSDNode::ANCHOR() {}
3404 void ExternalSymbolSDNode::ANCHOR() {}
3405 void CondCodeSDNode::ANCHOR() {}
3406 void VTSDNode::ANCHOR() {}
3407 void LoadSDNode::ANCHOR() {}
3408 void StoreSDNode::ANCHOR() {}
3409
3410 HandleSDNode::~HandleSDNode() {
3411   SDVTList VTs = { 0, 0 };
3412   MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0);  // Drops operand uses.
3413 }
3414
3415 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
3416                                          MVT::ValueType VT, int o)
3417   : SDNode(isa<GlobalVariable>(GA) &&
3418            cast<GlobalVariable>(GA)->isThreadLocal() ?
3419            // Thread Local
3420            (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
3421            // Non Thread Local
3422            (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
3423            getSDVTList(VT)), Offset(o) {
3424   TheGlobal = const_cast<GlobalValue*>(GA);
3425 }
3426
3427 /// Profile - Gather unique data for the node.
3428 ///
3429 void SDNode::Profile(FoldingSetNodeID &ID) {
3430   AddNodeIDNode(ID, this);
3431 }
3432
3433 /// getValueTypeList - Return a pointer to the specified value type.
3434 ///
3435 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
3436   if (MVT::isExtendedVT(VT)) {
3437     static std::set<MVT::ValueType> EVTs;
3438     return (MVT::ValueType *)&(*EVTs.insert(VT).first);
3439   } else {
3440     static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
3441     VTs[VT] = VT;
3442     return &VTs[VT];
3443   }
3444 }
3445
3446 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
3447 /// indicated value.  This method ignores uses of other values defined by this
3448 /// operation.
3449 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
3450   assert(Value < getNumValues() && "Bad value!");
3451
3452   // If there is only one value, this is easy.
3453   if (getNumValues() == 1)
3454     return use_size() == NUses;
3455   if (use_size() < NUses) return false;
3456
3457   SDOperand TheValue(const_cast<SDNode *>(this), Value);
3458
3459   SmallPtrSet<SDNode*, 32> UsersHandled;
3460
3461   for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3462     SDNode *User = *UI;
3463     if (User->getNumOperands() == 1 ||
3464         UsersHandled.insert(User))     // First time we've seen this?
3465       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3466         if (User->getOperand(i) == TheValue) {
3467           if (NUses == 0)
3468             return false;   // too many uses
3469           --NUses;
3470         }
3471   }
3472
3473   // Found exactly the right number of uses?
3474   return NUses == 0;
3475 }
3476
3477
3478 /// hasAnyUseOfValue - Return true if there are any use of the indicated
3479 /// value. This method ignores uses of other values defined by this operation.
3480 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
3481   assert(Value < getNumValues() && "Bad value!");
3482
3483   if (use_size() == 0) return false;
3484
3485   SDOperand TheValue(const_cast<SDNode *>(this), Value);
3486
3487   SmallPtrSet<SDNode*, 32> UsersHandled;
3488
3489   for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3490     SDNode *User = *UI;
3491     if (User->getNumOperands() == 1 ||
3492         UsersHandled.insert(User))     // First time we've seen this?
3493       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3494         if (User->getOperand(i) == TheValue) {
3495           return true;
3496         }
3497   }
3498
3499   return false;
3500 }
3501
3502
3503 /// isOnlyUse - Return true if this node is the only use of N.
3504 ///
3505 bool SDNode::isOnlyUse(SDNode *N) const {
3506   bool Seen = false;
3507   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
3508     SDNode *User = *I;
3509     if (User == this)
3510       Seen = true;
3511     else
3512       return false;
3513   }
3514
3515   return Seen;
3516 }
3517
3518 /// isOperand - Return true if this node is an operand of N.
3519 ///
3520 bool SDOperand::isOperand(SDNode *N) const {
3521   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3522     if (*this == N->getOperand(i))
3523       return true;
3524   return false;
3525 }
3526
3527 bool SDNode::isOperand(SDNode *N) const {
3528   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
3529     if (this == N->OperandList[i].Val)
3530       return true;
3531   return false;
3532 }
3533
3534 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
3535                             SmallPtrSet<SDNode *, 32> &Visited) {
3536   if (found || !Visited.insert(N))
3537     return;
3538
3539   for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
3540     SDNode *Op = N->getOperand(i).Val;
3541     if (Op == P) {
3542       found = true;
3543       return;
3544     }
3545     findPredecessor(Op, P, found, Visited);
3546   }
3547 }
3548
3549 /// isPredecessor - Return true if this node is a predecessor of N. This node
3550 /// is either an operand of N or it can be reached by recursively traversing
3551 /// up the operands.
3552 /// NOTE: this is an expensive method. Use it carefully.
3553 bool SDNode::isPredecessor(SDNode *N) const {
3554   SmallPtrSet<SDNode *, 32> Visited;
3555   bool found = false;
3556   findPredecessor(N, this, found, Visited);
3557   return found;
3558 }
3559
3560 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
3561   assert(Num < NumOperands && "Invalid child # of SDNode!");
3562   return cast<ConstantSDNode>(OperandList[Num])->getValue();
3563 }
3564
3565 std::string SDNode::getOperationName(const SelectionDAG *G) const {
3566   switch (getOpcode()) {
3567   default:
3568     if (getOpcode() < ISD::BUILTIN_OP_END)
3569       return "<<Unknown DAG Node>>";
3570     else {
3571       if (G) {
3572         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
3573           if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
3574             return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
3575
3576         TargetLowering &TLI = G->getTargetLoweringInfo();
3577         const char *Name =
3578           TLI.getTargetNodeName(getOpcode());
3579         if (Name) return Name;
3580       }
3581
3582       return "<<Unknown Target Node>>";
3583     }
3584    
3585   case ISD::PCMARKER:      return "PCMarker";
3586   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
3587   case ISD::SRCVALUE:      return "SrcValue";
3588   case ISD::EntryToken:    return "EntryToken";
3589   case ISD::TokenFactor:   return "TokenFactor";
3590   case ISD::AssertSext:    return "AssertSext";
3591   case ISD::AssertZext:    return "AssertZext";
3592
3593   case ISD::STRING:        return "String";
3594   case ISD::BasicBlock:    return "BasicBlock";
3595   case ISD::VALUETYPE:     return "ValueType";
3596   case ISD::Register:      return "Register";
3597
3598   case ISD::Constant:      return "Constant";
3599   case ISD::ConstantFP:    return "ConstantFP";
3600   case ISD::GlobalAddress: return "GlobalAddress";
3601   case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
3602   case ISD::FrameIndex:    return "FrameIndex";
3603   case ISD::JumpTable:     return "JumpTable";
3604   case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
3605   case ISD::RETURNADDR: return "RETURNADDR";
3606   case ISD::FRAMEADDR: return "FRAMEADDR";
3607   case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
3608   case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
3609   case ISD::EHSELECTION: return "EHSELECTION";
3610   case ISD::EH_RETURN: return "EH_RETURN";
3611   case ISD::ConstantPool:  return "ConstantPool";
3612   case ISD::ExternalSymbol: return "ExternalSymbol";
3613   case ISD::INTRINSIC_WO_CHAIN: {
3614     unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
3615     return Intrinsic::getName((Intrinsic::ID)IID);
3616   }
3617   case ISD::INTRINSIC_VOID:
3618   case ISD::INTRINSIC_W_CHAIN: {
3619     unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
3620     return Intrinsic::getName((Intrinsic::ID)IID);
3621   }
3622
3623   case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
3624   case ISD::TargetConstant: return "TargetConstant";
3625   case ISD::TargetConstantFP:return "TargetConstantFP";
3626   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
3627   case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
3628   case ISD::TargetFrameIndex: return "TargetFrameIndex";
3629   case ISD::TargetJumpTable:  return "TargetJumpTable";
3630   case ISD::TargetConstantPool:  return "TargetConstantPool";
3631   case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
3632
3633   case ISD::CopyToReg:     return "CopyToReg";
3634   case ISD::CopyFromReg:   return "CopyFromReg";
3635   case ISD::UNDEF:         return "undef";
3636   case ISD::MERGE_VALUES:  return "merge_values";
3637   case ISD::INLINEASM:     return "inlineasm";
3638   case ISD::LABEL:         return "label";
3639   case ISD::HANDLENODE:    return "handlenode";
3640   case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
3641   case ISD::CALL:          return "call";
3642     
3643   // Unary operators
3644   case ISD::FABS:   return "fabs";
3645   case ISD::FNEG:   return "fneg";
3646   case ISD::FSQRT:  return "fsqrt";
3647   case ISD::FSIN:   return "fsin";
3648   case ISD::FCOS:   return "fcos";
3649   case ISD::FPOWI:  return "fpowi";
3650   case ISD::FPOW:   return "fpow";
3651
3652   // Binary operators
3653   case ISD::ADD:    return "add";
3654   case ISD::SUB:    return "sub";
3655   case ISD::MUL:    return "mul";
3656   case ISD::MULHU:  return "mulhu";
3657   case ISD::MULHS:  return "mulhs";
3658   case ISD::SDIV:   return "sdiv";
3659   case ISD::UDIV:   return "udiv";
3660   case ISD::SREM:   return "srem";
3661   case ISD::UREM:   return "urem";
3662   case ISD::SMUL_LOHI:  return "smul_lohi";
3663   case ISD::UMUL_LOHI:  return "umul_lohi";
3664   case ISD::SDIVREM:    return "sdivrem";
3665   case ISD::UDIVREM:    return "divrem";
3666   case ISD::AND:    return "and";
3667   case ISD::OR:     return "or";
3668   case ISD::XOR:    return "xor";
3669   case ISD::SHL:    return "shl";
3670   case ISD::SRA:    return "sra";
3671   case ISD::SRL:    return "srl";
3672   case ISD::ROTL:   return "rotl";
3673   case ISD::ROTR:   return "rotr";
3674   case ISD::FADD:   return "fadd";
3675   case ISD::FSUB:   return "fsub";
3676   case ISD::FMUL:   return "fmul";
3677   case ISD::FDIV:   return "fdiv";
3678   case ISD::FREM:   return "frem";
3679   case ISD::FCOPYSIGN: return "fcopysign";
3680
3681   case ISD::SETCC:       return "setcc";
3682   case ISD::SELECT:      return "select";
3683   case ISD::SELECT_CC:   return "select_cc";
3684   case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
3685   case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
3686   case ISD::CONCAT_VECTORS:      return "concat_vectors";
3687   case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
3688   case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
3689   case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
3690   case ISD::CARRY_FALSE:         return "carry_false";
3691   case ISD::ADDC:        return "addc";
3692   case ISD::ADDE:        return "adde";
3693   case ISD::SUBC:        return "subc";
3694   case ISD::SUBE:        return "sube";
3695   case ISD::SHL_PARTS:   return "shl_parts";
3696   case ISD::SRA_PARTS:   return "sra_parts";
3697   case ISD::SRL_PARTS:   return "srl_parts";
3698   
3699   case ISD::EXTRACT_SUBREG:     return "extract_subreg";
3700   case ISD::INSERT_SUBREG:      return "insert_subreg";
3701   
3702   // Conversion operators.
3703   case ISD::SIGN_EXTEND: return "sign_extend";
3704   case ISD::ZERO_EXTEND: return "zero_extend";
3705   case ISD::ANY_EXTEND:  return "any_extend";
3706   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
3707   case ISD::TRUNCATE:    return "truncate";
3708   case ISD::FP_ROUND:    return "fp_round";
3709   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
3710   case ISD::FP_EXTEND:   return "fp_extend";
3711
3712   case ISD::SINT_TO_FP:  return "sint_to_fp";
3713   case ISD::UINT_TO_FP:  return "uint_to_fp";
3714   case ISD::FP_TO_SINT:  return "fp_to_sint";
3715   case ISD::FP_TO_UINT:  return "fp_to_uint";
3716   case ISD::BIT_CONVERT: return "bit_convert";
3717
3718     // Control flow instructions
3719   case ISD::BR:      return "br";
3720   case ISD::BRIND:   return "brind";
3721   case ISD::BR_JT:   return "br_jt";
3722   case ISD::BRCOND:  return "brcond";
3723   case ISD::BR_CC:   return "br_cc";
3724   case ISD::RET:     return "ret";
3725   case ISD::CALLSEQ_START:  return "callseq_start";
3726   case ISD::CALLSEQ_END:    return "callseq_end";
3727
3728     // Other operators
3729   case ISD::LOAD:               return "load";
3730   case ISD::STORE:              return "store";
3731   case ISD::VAARG:              return "vaarg";
3732   case ISD::VACOPY:             return "vacopy";
3733   case ISD::VAEND:              return "vaend";
3734   case ISD::VASTART:            return "vastart";
3735   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
3736   case ISD::EXTRACT_ELEMENT:    return "extract_element";
3737   case ISD::BUILD_PAIR:         return "build_pair";
3738   case ISD::STACKSAVE:          return "stacksave";
3739   case ISD::STACKRESTORE:       return "stackrestore";
3740     
3741   // Block memory operations.
3742   case ISD::MEMSET:  return "memset";
3743   case ISD::MEMCPY:  return "memcpy";
3744   case ISD::MEMMOVE: return "memmove";
3745
3746   // Bit manipulation
3747   case ISD::BSWAP:   return "bswap";
3748   case ISD::CTPOP:   return "ctpop";
3749   case ISD::CTTZ:    return "cttz";
3750   case ISD::CTLZ:    return "ctlz";
3751
3752   // Debug info
3753   case ISD::LOCATION: return "location";
3754   case ISD::DEBUG_LOC: return "debug_loc";
3755
3756   // Trampolines
3757   case ISD::TRAMPOLINE: return "trampoline";
3758
3759   case ISD::CONDCODE:
3760     switch (cast<CondCodeSDNode>(this)->get()) {
3761     default: assert(0 && "Unknown setcc condition!");
3762     case ISD::SETOEQ:  return "setoeq";
3763     case ISD::SETOGT:  return "setogt";
3764     case ISD::SETOGE:  return "setoge";
3765     case ISD::SETOLT:  return "setolt";
3766     case ISD::SETOLE:  return "setole";
3767     case ISD::SETONE:  return "setone";
3768
3769     case ISD::SETO:    return "seto";
3770     case ISD::SETUO:   return "setuo";
3771     case ISD::SETUEQ:  return "setue";
3772     case ISD::SETUGT:  return "setugt";
3773     case ISD::SETUGE:  return "setuge";
3774     case ISD::SETULT:  return "setult";
3775     case ISD::SETULE:  return "setule";
3776     case ISD::SETUNE:  return "setune";
3777
3778     case ISD::SETEQ:   return "seteq";
3779     case ISD::SETGT:   return "setgt";
3780     case ISD::SETGE:   return "setge";
3781     case ISD::SETLT:   return "setlt";
3782     case ISD::SETLE:   return "setle";
3783     case ISD::SETNE:   return "setne";
3784     }
3785   }
3786 }
3787
3788 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
3789   switch (AM) {
3790   default:
3791     return "";
3792   case ISD::PRE_INC:
3793     return "<pre-inc>";
3794   case ISD::PRE_DEC:
3795     return "<pre-dec>";
3796   case ISD::POST_INC:
3797     return "<post-inc>";
3798   case ISD::POST_DEC:
3799     return "<post-dec>";
3800   }
3801 }
3802
3803 void SDNode::dump() const { dump(0); }
3804 void SDNode::dump(const SelectionDAG *G) const {
3805   cerr << (void*)this << ": ";
3806
3807   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
3808     if (i) cerr << ",";
3809     if (getValueType(i) == MVT::Other)
3810       cerr << "ch";
3811     else
3812       cerr << MVT::getValueTypeString(getValueType(i));
3813   }
3814   cerr << " = " << getOperationName(G);
3815
3816   cerr << " ";
3817   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3818     if (i) cerr << ", ";
3819     cerr << (void*)getOperand(i).Val;
3820     if (unsigned RN = getOperand(i).ResNo)
3821       cerr << ":" << RN;
3822   }
3823
3824   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
3825     cerr << "<" << CSDN->getValue() << ">";
3826   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
3827     if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
3828       cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
3829     else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
3830       cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
3831     else {
3832       cerr << "<APFloat(";
3833       CSDN->getValueAPF().convertToAPInt().dump();
3834       cerr << ")>";
3835     }
3836   } else if (const GlobalAddressSDNode *GADN =
3837              dyn_cast<GlobalAddressSDNode>(this)) {
3838     int offset = GADN->getOffset();
3839     cerr << "<";
3840     WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
3841     if (offset > 0)
3842       cerr << " + " << offset;
3843     else
3844       cerr << " " << offset;
3845   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
3846     cerr << "<" << FIDN->getIndex() << ">";
3847   } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
3848     cerr << "<" << JTDN->getIndex() << ">";
3849   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
3850     int offset = CP->getOffset();
3851     if (CP->isMachineConstantPoolEntry())
3852       cerr << "<" << *CP->getMachineCPVal() << ">";
3853     else
3854       cerr << "<" << *CP->getConstVal() << ">";
3855     if (offset > 0)
3856       cerr << " + " << offset;
3857     else
3858       cerr << " " << offset;
3859   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
3860     cerr << "<";
3861     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
3862     if (LBB)
3863       cerr << LBB->getName() << " ";
3864     cerr << (const void*)BBDN->getBasicBlock() << ">";
3865   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
3866     if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
3867       cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
3868     } else {
3869       cerr << " #" << R->getReg();
3870     }
3871   } else if (const ExternalSymbolSDNode *ES =
3872              dyn_cast<ExternalSymbolSDNode>(this)) {
3873     cerr << "'" << ES->getSymbol() << "'";
3874   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
3875     if (M->getValue())
3876       cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
3877     else
3878       cerr << "<null:" << M->getOffset() << ">";
3879   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
3880     cerr << ":" << MVT::getValueTypeString(N->getVT());
3881   } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
3882     bool doExt = true;
3883     switch (LD->getExtensionType()) {
3884     default: doExt = false; break;
3885     case ISD::EXTLOAD:
3886       cerr << " <anyext ";
3887       break;
3888     case ISD::SEXTLOAD:
3889       cerr << " <sext ";
3890       break;
3891     case ISD::ZEXTLOAD:
3892       cerr << " <zext ";
3893       break;
3894     }
3895     if (doExt)
3896       cerr << MVT::getValueTypeString(LD->getLoadedVT()) << ">";
3897
3898     const char *AM = getIndexedModeName(LD->getAddressingMode());
3899     if (*AM)
3900       cerr << " " << AM;
3901   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
3902     if (ST->isTruncatingStore())
3903       cerr << " <trunc "
3904            << MVT::getValueTypeString(ST->getStoredVT()) << ">";
3905
3906     const char *AM = getIndexedModeName(ST->getAddressingMode());
3907     if (*AM)
3908       cerr << " " << AM;
3909   }
3910 }
3911
3912 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
3913   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3914     if (N->getOperand(i).Val->hasOneUse())
3915       DumpNodes(N->getOperand(i).Val, indent+2, G);
3916     else
3917       cerr << "\n" << std::string(indent+2, ' ')
3918            << (void*)N->getOperand(i).Val << ": <multiple use>";
3919
3920
3921   cerr << "\n" << std::string(indent, ' ');
3922   N->dump(G);
3923 }
3924
3925 void SelectionDAG::dump() const {
3926   cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
3927   std::vector<const SDNode*> Nodes;
3928   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
3929        I != E; ++I)
3930     Nodes.push_back(I);
3931   
3932   std::sort(Nodes.begin(), Nodes.end());
3933
3934   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3935     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
3936       DumpNodes(Nodes[i], 2, this);
3937   }
3938
3939   if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
3940
3941   cerr << "\n\n";
3942 }
3943
3944 const Type *ConstantPoolSDNode::getType() const {
3945   if (isMachineConstantPoolEntry())
3946     return Val.MachineCPVal->getType();
3947   return Val.ConstVal->getType();
3948 }