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