Silence some compiler warnings.
[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/CallingConv.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/ADT/SetVector.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include <algorithm>
38 #include <cmath>
39 using namespace llvm;
40
41 /// makeVTList - Return an instance of the SDVTList struct initialized with the
42 /// specified members.
43 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
44   SDVTList Res = {VTs, NumVTs};
45   return Res;
46 }
47
48 static const fltSemantics *MVTToAPFloatSemantics(MVT::ValueType VT) {
49   switch (VT) {
50   default: assert(0 && "Unknown FP format");
51   case MVT::f32:     return &APFloat::IEEEsingle;
52   case MVT::f64:     return &APFloat::IEEEdouble;
53   case MVT::f80:     return &APFloat::x87DoubleExtended;
54   case MVT::f128:    return &APFloat::IEEEquad;
55   case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
56   }
57 }
58
59 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
60
61 //===----------------------------------------------------------------------===//
62 //                              ConstantFPSDNode Class
63 //===----------------------------------------------------------------------===//
64
65 /// isExactlyValue - We don't rely on operator== working on double values, as
66 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
67 /// As such, this method can be used to do an exact bit-for-bit comparison of
68 /// two floating point values.
69 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
70   return Value.bitwiseIsEqual(V);
71 }
72
73 bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT, 
74                                            const APFloat& Val) {
75   assert(MVT::isFloatingPoint(VT) && "Can only convert between FP types");
76   
77   // PPC long double cannot be converted to any other type.
78   if (VT == MVT::ppcf128 ||
79       &Val.getSemantics() == &APFloat::PPCDoubleDouble)
80     return false;
81   
82   // convert modifies in place, so make a copy.
83   APFloat Val2 = APFloat(Val);
84   return Val2.convert(*MVTToAPFloatSemantics(VT),
85                       APFloat::rmNearestTiesToEven) == APFloat::opOK;
86 }
87
88 //===----------------------------------------------------------------------===//
89 //                              ISD Namespace
90 //===----------------------------------------------------------------------===//
91
92 /// isBuildVectorAllOnes - Return true if the specified node is a
93 /// BUILD_VECTOR where all of the elements are ~0 or undef.
94 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
95   // Look through a bit convert.
96   if (N->getOpcode() == ISD::BIT_CONVERT)
97     N = N->getOperand(0).Val;
98   
99   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
100   
101   unsigned i = 0, e = N->getNumOperands();
102   
103   // Skip over all of the undef values.
104   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
105     ++i;
106   
107   // Do not accept an all-undef vector.
108   if (i == e) return false;
109   
110   // Do not accept build_vectors that aren't all constants or which have non-~0
111   // elements.
112   SDOperand NotZero = N->getOperand(i);
113   if (isa<ConstantSDNode>(NotZero)) {
114     if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
115       return false;
116   } else if (isa<ConstantFPSDNode>(NotZero)) {
117     if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
118                 convertToAPInt().isAllOnesValue())
119       return false;
120   } else
121     return false;
122   
123   // Okay, we have at least one ~0 value, check to see if the rest match or are
124   // undefs.
125   for (++i; i != e; ++i)
126     if (N->getOperand(i) != NotZero &&
127         N->getOperand(i).getOpcode() != ISD::UNDEF)
128       return false;
129   return true;
130 }
131
132
133 /// isBuildVectorAllZeros - Return true if the specified node is a
134 /// BUILD_VECTOR where all of the elements are 0 or undef.
135 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
136   // Look through a bit convert.
137   if (N->getOpcode() == ISD::BIT_CONVERT)
138     N = N->getOperand(0).Val;
139   
140   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
141   
142   unsigned i = 0, e = N->getNumOperands();
143   
144   // Skip over all of the undef values.
145   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
146     ++i;
147   
148   // Do not accept an all-undef vector.
149   if (i == e) return false;
150   
151   // Do not accept build_vectors that aren't all constants or which have non-~0
152   // elements.
153   SDOperand Zero = N->getOperand(i);
154   if (isa<ConstantSDNode>(Zero)) {
155     if (!cast<ConstantSDNode>(Zero)->isNullValue())
156       return false;
157   } else if (isa<ConstantFPSDNode>(Zero)) {
158     if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
159       return false;
160   } else
161     return false;
162   
163   // Okay, we have at least one ~0 value, check to see if the rest match or are
164   // undefs.
165   for (++i; i != e; ++i)
166     if (N->getOperand(i) != Zero &&
167         N->getOperand(i).getOpcode() != ISD::UNDEF)
168       return false;
169   return true;
170 }
171
172 /// isScalarToVector - Return true if the specified node is a
173 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
174 /// element is not an undef.
175 bool ISD::isScalarToVector(const SDNode *N) {
176   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
177     return true;
178
179   if (N->getOpcode() != ISD::BUILD_VECTOR)
180     return false;
181   if (N->getOperand(0).getOpcode() == ISD::UNDEF)
182     return false;
183   unsigned NumElems = N->getNumOperands();
184   for (unsigned i = 1; i < NumElems; ++i) {
185     SDOperand V = N->getOperand(i);
186     if (V.getOpcode() != ISD::UNDEF)
187       return false;
188   }
189   return true;
190 }
191
192
193 /// isDebugLabel - Return true if the specified node represents a debug
194 /// label (i.e. ISD::LABEL or TargetInstrInfo::LABEL node and third operand
195 /// is 0).
196 bool ISD::isDebugLabel(const SDNode *N) {
197   SDOperand Zero;
198   if (N->getOpcode() == ISD::LABEL)
199     Zero = N->getOperand(2);
200   else if (N->isTargetOpcode() &&
201            N->getTargetOpcode() == TargetInstrInfo::LABEL)
202     // Chain moved to last operand.
203     Zero = N->getOperand(1);
204   else
205     return false;
206   return isa<ConstantSDNode>(Zero) && cast<ConstantSDNode>(Zero)->isNullValue();
207 }
208
209 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
210 /// when given the operation for (X op Y).
211 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
212   // To perform this operation, we just need to swap the L and G bits of the
213   // operation.
214   unsigned OldL = (Operation >> 2) & 1;
215   unsigned OldG = (Operation >> 1) & 1;
216   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
217                        (OldL << 1) |       // New G bit
218                        (OldG << 2));        // New L bit.
219 }
220
221 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
222 /// 'op' is a valid SetCC operation.
223 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
224   unsigned Operation = Op;
225   if (isInteger)
226     Operation ^= 7;   // Flip L, G, E bits, but not U.
227   else
228     Operation ^= 15;  // Flip all of the condition bits.
229   if (Operation > ISD::SETTRUE2)
230     Operation &= ~8;     // Don't let N and U bits get set.
231   return ISD::CondCode(Operation);
232 }
233
234
235 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
236 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
237 /// if the operation does not depend on the sign of the input (setne and seteq).
238 static int isSignedOp(ISD::CondCode Opcode) {
239   switch (Opcode) {
240   default: assert(0 && "Illegal integer setcc operation!");
241   case ISD::SETEQ:
242   case ISD::SETNE: return 0;
243   case ISD::SETLT:
244   case ISD::SETLE:
245   case ISD::SETGT:
246   case ISD::SETGE: return 1;
247   case ISD::SETULT:
248   case ISD::SETULE:
249   case ISD::SETUGT:
250   case ISD::SETUGE: return 2;
251   }
252 }
253
254 /// getSetCCOrOperation - Return the result of a logical OR between different
255 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
256 /// returns SETCC_INVALID if it is not possible to represent the resultant
257 /// comparison.
258 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
259                                        bool isInteger) {
260   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
261     // Cannot fold a signed integer setcc with an unsigned integer setcc.
262     return ISD::SETCC_INVALID;
263
264   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
265
266   // If the N and U bits get set then the resultant comparison DOES suddenly
267   // care about orderedness, and is true when ordered.
268   if (Op > ISD::SETTRUE2)
269     Op &= ~16;     // Clear the U bit if the N bit is set.
270   
271   // Canonicalize illegal integer setcc's.
272   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
273     Op = ISD::SETNE;
274   
275   return ISD::CondCode(Op);
276 }
277
278 /// getSetCCAndOperation - Return the result of a logical AND between different
279 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
280 /// function returns zero if it is not possible to represent the resultant
281 /// comparison.
282 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
283                                         bool isInteger) {
284   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
285     // Cannot fold a signed setcc with an unsigned setcc.
286     return ISD::SETCC_INVALID;
287
288   // Combine all of the condition bits.
289   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
290   
291   // Canonicalize illegal integer setcc's.
292   if (isInteger) {
293     switch (Result) {
294     default: break;
295     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
296     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
297     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
298     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
299     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
300     }
301   }
302   
303   return Result;
304 }
305
306 const TargetMachine &SelectionDAG::getTarget() const {
307   return TLI.getTargetMachine();
308 }
309
310 //===----------------------------------------------------------------------===//
311 //                           SDNode Profile Support
312 //===----------------------------------------------------------------------===//
313
314 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
315 ///
316 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
317   ID.AddInteger(OpC);
318 }
319
320 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
321 /// solely with their pointer.
322 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
323   ID.AddPointer(VTList.VTs);  
324 }
325
326 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
327 ///
328 static void AddNodeIDOperands(FoldingSetNodeID &ID,
329                               SDOperandPtr Ops, unsigned NumOps) {
330   for (; NumOps; --NumOps, ++Ops) {
331     ID.AddPointer(Ops->Val);
332     ID.AddInteger(Ops->ResNo);
333   }
334 }
335
336 static void AddNodeIDNode(FoldingSetNodeID &ID,
337                           unsigned short OpC, SDVTList VTList, 
338                           SDOperandPtr OpList, unsigned N) {
339   AddNodeIDOpcode(ID, OpC);
340   AddNodeIDValueTypes(ID, VTList);
341   AddNodeIDOperands(ID, OpList, N);
342 }
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->getVal();
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->getVal();
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->getVal()->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                                            SDOperandPtr 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), (SDOperand*)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), (SDOperand*)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), (SDOperand*)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), (SDOperand*)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), (SDOperand*)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), (SDOperand*)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), (SDOperand*)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), (SDOperand*)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), (SDOperand*)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), (SDOperand*)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), (SDOperand*)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), (SDOperand*)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::MUL: {
1234     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1235     ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1236     ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1237     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1238     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1239
1240     // If low bits are zero in either operand, output low known-0 bits.
1241     // Also compute a conserative estimate for high known-0 bits.
1242     // More trickiness is possible, but this is sufficient for the
1243     // interesting case of alignment computation.
1244     KnownOne.clear();
1245     unsigned TrailZ = KnownZero.countTrailingOnes() +
1246                       KnownZero2.countTrailingOnes();
1247     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
1248                                KnownZero2.countLeadingOnes(),
1249                                BitWidth) - BitWidth;
1250
1251     TrailZ = std::min(TrailZ, BitWidth);
1252     LeadZ = std::min(LeadZ, BitWidth);
1253     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1254                 APInt::getHighBitsSet(BitWidth, LeadZ);
1255     KnownZero &= Mask;
1256     return;
1257   }
1258   case ISD::UDIV: {
1259     // For the purposes of computing leading zeros we can conservatively
1260     // treat a udiv as a logical right shift by the power of 2 known to
1261     // be less than the denominator.
1262     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1263     ComputeMaskedBits(Op.getOperand(0),
1264                       AllOnes, KnownZero2, KnownOne2, Depth+1);
1265     unsigned LeadZ = KnownZero2.countLeadingOnes();
1266
1267     KnownOne2.clear();
1268     KnownZero2.clear();
1269     ComputeMaskedBits(Op.getOperand(1),
1270                       AllOnes, KnownZero2, KnownOne2, Depth+1);
1271     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1272     if (RHSUnknownLeadingOnes != BitWidth)
1273       LeadZ = std::min(BitWidth,
1274                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1275
1276     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1277     return;
1278   }
1279   case ISD::SELECT:
1280     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1281     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1282     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1283     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1284     
1285     // Only known if known in both the LHS and RHS.
1286     KnownOne &= KnownOne2;
1287     KnownZero &= KnownZero2;
1288     return;
1289   case ISD::SELECT_CC:
1290     ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1291     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1292     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1293     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1294     
1295     // Only known if known in both the LHS and RHS.
1296     KnownOne &= KnownOne2;
1297     KnownZero &= KnownZero2;
1298     return;
1299   case ISD::SETCC:
1300     // If we know the result of a setcc has the top bits zero, use this info.
1301     if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1302         BitWidth > 1)
1303       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1304     return;
1305   case ISD::SHL:
1306     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1307     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1308       unsigned ShAmt = SA->getValue();
1309
1310       // If the shift count is an invalid immediate, don't do anything.
1311       if (ShAmt >= BitWidth)
1312         return;
1313
1314       ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1315                         KnownZero, KnownOne, Depth+1);
1316       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1317       KnownZero <<= ShAmt;
1318       KnownOne  <<= ShAmt;
1319       // low bits known zero.
1320       KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1321     }
1322     return;
1323   case ISD::SRL:
1324     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1325     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1326       unsigned ShAmt = SA->getValue();
1327
1328       // If the shift count is an invalid immediate, don't do anything.
1329       if (ShAmt >= BitWidth)
1330         return;
1331
1332       ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1333                         KnownZero, KnownOne, Depth+1);
1334       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1335       KnownZero = KnownZero.lshr(ShAmt);
1336       KnownOne  = KnownOne.lshr(ShAmt);
1337
1338       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1339       KnownZero |= HighBits;  // High bits known zero.
1340     }
1341     return;
1342   case ISD::SRA:
1343     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1344       unsigned ShAmt = SA->getValue();
1345
1346       // If the shift count is an invalid immediate, don't do anything.
1347       if (ShAmt >= BitWidth)
1348         return;
1349
1350       APInt InDemandedMask = (Mask << ShAmt);
1351       // If any of the demanded bits are produced by the sign extension, we also
1352       // demand the input sign bit.
1353       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1354       if (HighBits.getBoolValue())
1355         InDemandedMask |= APInt::getSignBit(BitWidth);
1356       
1357       ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1358                         Depth+1);
1359       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1360       KnownZero = KnownZero.lshr(ShAmt);
1361       KnownOne  = KnownOne.lshr(ShAmt);
1362       
1363       // Handle the sign bits.
1364       APInt SignBit = APInt::getSignBit(BitWidth);
1365       SignBit = SignBit.lshr(ShAmt);  // Adjust to where it is now in the mask.
1366       
1367       if (KnownZero.intersects(SignBit)) {
1368         KnownZero |= HighBits;  // New bits are known zero.
1369       } else if (KnownOne.intersects(SignBit)) {
1370         KnownOne  |= HighBits;  // New bits are known one.
1371       }
1372     }
1373     return;
1374   case ISD::SIGN_EXTEND_INREG: {
1375     MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1376     unsigned EBits = MVT::getSizeInBits(EVT);
1377     
1378     // Sign extension.  Compute the demanded bits in the result that are not 
1379     // present in the input.
1380     APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1381
1382     APInt InSignBit = APInt::getSignBit(EBits);
1383     APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1384     
1385     // If the sign extended bits are demanded, we know that the sign
1386     // bit is demanded.
1387     InSignBit.zext(BitWidth);
1388     if (NewBits.getBoolValue())
1389       InputDemandedBits |= InSignBit;
1390     
1391     ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1392                       KnownZero, KnownOne, Depth+1);
1393     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1394     
1395     // If the sign bit of the input is known set or clear, then we know the
1396     // top bits of the result.
1397     if (KnownZero.intersects(InSignBit)) {         // Input sign bit known clear
1398       KnownZero |= NewBits;
1399       KnownOne  &= ~NewBits;
1400     } else if (KnownOne.intersects(InSignBit)) {   // Input sign bit known set
1401       KnownOne  |= NewBits;
1402       KnownZero &= ~NewBits;
1403     } else {                              // Input sign bit unknown
1404       KnownZero &= ~NewBits;
1405       KnownOne  &= ~NewBits;
1406     }
1407     return;
1408   }
1409   case ISD::CTTZ:
1410   case ISD::CTLZ:
1411   case ISD::CTPOP: {
1412     unsigned LowBits = Log2_32(BitWidth)+1;
1413     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1414     KnownOne  = APInt(BitWidth, 0);
1415     return;
1416   }
1417   case ISD::LOAD: {
1418     if (ISD::isZEXTLoad(Op.Val)) {
1419       LoadSDNode *LD = cast<LoadSDNode>(Op);
1420       MVT::ValueType VT = LD->getMemoryVT();
1421       unsigned MemBits = MVT::getSizeInBits(VT);
1422       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1423     }
1424     return;
1425   }
1426   case ISD::ZERO_EXTEND: {
1427     MVT::ValueType InVT = Op.getOperand(0).getValueType();
1428     unsigned InBits = MVT::getSizeInBits(InVT);
1429     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1430     APInt InMask    = Mask;
1431     InMask.trunc(InBits);
1432     KnownZero.trunc(InBits);
1433     KnownOne.trunc(InBits);
1434     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1435     KnownZero.zext(BitWidth);
1436     KnownOne.zext(BitWidth);
1437     KnownZero |= NewBits;
1438     return;
1439   }
1440   case ISD::SIGN_EXTEND: {
1441     MVT::ValueType InVT = Op.getOperand(0).getValueType();
1442     unsigned InBits = MVT::getSizeInBits(InVT);
1443     APInt InSignBit = APInt::getSignBit(InBits);
1444     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1445     APInt InMask = Mask;
1446     InMask.trunc(InBits);
1447
1448     // If any of the sign extended bits are demanded, we know that the sign
1449     // bit is demanded. Temporarily set this bit in the mask for our callee.
1450     if (NewBits.getBoolValue())
1451       InMask |= InSignBit;
1452
1453     KnownZero.trunc(InBits);
1454     KnownOne.trunc(InBits);
1455     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1456
1457     // Note if the sign bit is known to be zero or one.
1458     bool SignBitKnownZero = KnownZero.isNegative();
1459     bool SignBitKnownOne  = KnownOne.isNegative();
1460     assert(!(SignBitKnownZero && SignBitKnownOne) &&
1461            "Sign bit can't be known to be both zero and one!");
1462
1463     // If the sign bit wasn't actually demanded by our caller, we don't
1464     // want it set in the KnownZero and KnownOne result values. Reset the
1465     // mask and reapply it to the result values.
1466     InMask = Mask;
1467     InMask.trunc(InBits);
1468     KnownZero &= InMask;
1469     KnownOne  &= InMask;
1470
1471     KnownZero.zext(BitWidth);
1472     KnownOne.zext(BitWidth);
1473
1474     // If the sign bit is known zero or one, the top bits match.
1475     if (SignBitKnownZero)
1476       KnownZero |= NewBits;
1477     else if (SignBitKnownOne)
1478       KnownOne  |= NewBits;
1479     return;
1480   }
1481   case ISD::ANY_EXTEND: {
1482     MVT::ValueType InVT = Op.getOperand(0).getValueType();
1483     unsigned InBits = MVT::getSizeInBits(InVT);
1484     APInt InMask = Mask;
1485     InMask.trunc(InBits);
1486     KnownZero.trunc(InBits);
1487     KnownOne.trunc(InBits);
1488     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1489     KnownZero.zext(BitWidth);
1490     KnownOne.zext(BitWidth);
1491     return;
1492   }
1493   case ISD::TRUNCATE: {
1494     MVT::ValueType InVT = Op.getOperand(0).getValueType();
1495     unsigned InBits = MVT::getSizeInBits(InVT);
1496     APInt InMask = Mask;
1497     InMask.zext(InBits);
1498     KnownZero.zext(InBits);
1499     KnownOne.zext(InBits);
1500     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1501     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1502     KnownZero.trunc(BitWidth);
1503     KnownOne.trunc(BitWidth);
1504     break;
1505   }
1506   case ISD::AssertZext: {
1507     MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1508     APInt InMask = APInt::getLowBitsSet(BitWidth, MVT::getSizeInBits(VT));
1509     ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero, 
1510                       KnownOne, Depth+1);
1511     KnownZero |= (~InMask) & Mask;
1512     return;
1513   }
1514   case ISD::FGETSIGN:
1515     // All bits are zero except the low bit.
1516     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1517     return;
1518   
1519   case ISD::SUB: {
1520     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1521       // We know that the top bits of C-X are clear if X contains less bits
1522       // than C (i.e. no wrap-around can happen).  For example, 20-X is
1523       // positive if we can prove that X is >= 0 and < 16.
1524       if (CLHS->getAPIntValue().isNonNegative()) {
1525         unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1526         // NLZ can't be BitWidth with no sign bit
1527         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1528         ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1529                           Depth+1);
1530
1531         // If all of the MaskV bits are known to be zero, then we know the
1532         // output top bits are zero, because we now know that the output is
1533         // from [0-C].
1534         if ((KnownZero2 & MaskV) == MaskV) {
1535           unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1536           // Top bits known zero.
1537           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1538         }
1539       }
1540     }
1541   }
1542   // fall through
1543   case ISD::ADD: {
1544     // Output known-0 bits are known if clear or set in both the low clear bits
1545     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
1546     // low 3 bits clear.
1547     APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1548     ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1549     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1550     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1551
1552     ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1553     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1554     KnownZeroOut = std::min(KnownZeroOut,
1555                             KnownZero2.countTrailingOnes());
1556
1557     KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1558     return;
1559   }
1560   case ISD::SREM:
1561     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1562       APInt RA = Rem->getAPIntValue();
1563       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1564         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1565         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1566         ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1567
1568         // The sign of a remainder is equal to the sign of the first
1569         // operand (zero being positive).
1570         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1571           KnownZero2 |= ~LowBits;
1572         else if (KnownOne2[BitWidth-1])
1573           KnownOne2 |= ~LowBits;
1574
1575         KnownZero |= KnownZero2 & Mask;
1576         KnownOne |= KnownOne2 & Mask;
1577
1578         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1579       }
1580     }
1581     return;
1582   case ISD::UREM: {
1583     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1584       APInt RA = Rem->getAPIntValue();
1585       if (RA.isPowerOf2()) {
1586         APInt LowBits = (RA - 1);
1587         APInt Mask2 = LowBits & Mask;
1588         KnownZero |= ~LowBits & Mask;
1589         ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1590         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1591         break;
1592       }
1593     }
1594
1595     // Since the result is less than or equal to either operand, any leading
1596     // zero bits in either operand must also exist in the result.
1597     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1598     ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1599                       Depth+1);
1600     ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1601                       Depth+1);
1602
1603     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1604                                 KnownZero2.countLeadingOnes());
1605     KnownOne.clear();
1606     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1607     return;
1608   }
1609   default:
1610     // Allow the target to implement this method for its nodes.
1611     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1612   case ISD::INTRINSIC_WO_CHAIN:
1613   case ISD::INTRINSIC_W_CHAIN:
1614   case ISD::INTRINSIC_VOID:
1615       TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1616     }
1617     return;
1618   }
1619 }
1620
1621 /// ComputeNumSignBits - Return the number of times the sign bit of the
1622 /// register is replicated into the other bits.  We know that at least 1 bit
1623 /// is always equal to the sign bit (itself), but other cases can give us
1624 /// information.  For example, immediately after an "SRA X, 2", we know that
1625 /// the top 3 bits are all equal to each other, so we return 3.
1626 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1627   MVT::ValueType VT = Op.getValueType();
1628   assert(MVT::isInteger(VT) && "Invalid VT!");
1629   unsigned VTBits = MVT::getSizeInBits(VT);
1630   unsigned Tmp, Tmp2;
1631   
1632   if (Depth == 6)
1633     return 1;  // Limit search depth.
1634
1635   switch (Op.getOpcode()) {
1636   default: break;
1637   case ISD::AssertSext:
1638     Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1639     return VTBits-Tmp+1;
1640   case ISD::AssertZext:
1641     Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1642     return VTBits-Tmp;
1643     
1644   case ISD::Constant: {
1645     const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1646     // If negative, return # leading ones.
1647     if (Val.isNegative())
1648       return Val.countLeadingOnes();
1649     
1650     // Return # leading zeros.
1651     return Val.countLeadingZeros();
1652   }
1653     
1654   case ISD::SIGN_EXTEND:
1655     Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1656     return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1657     
1658   case ISD::SIGN_EXTEND_INREG:
1659     // Max of the input and what this extends.
1660     Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1661     Tmp = VTBits-Tmp+1;
1662     
1663     Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1664     return std::max(Tmp, Tmp2);
1665
1666   case ISD::SRA:
1667     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1668     // SRA X, C   -> adds C sign bits.
1669     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1670       Tmp += C->getValue();
1671       if (Tmp > VTBits) Tmp = VTBits;
1672     }
1673     return Tmp;
1674   case ISD::SHL:
1675     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1676       // shl destroys sign bits.
1677       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1678       if (C->getValue() >= VTBits ||      // Bad shift.
1679           C->getValue() >= Tmp) break;    // Shifted all sign bits out.
1680       return Tmp - C->getValue();
1681     }
1682     break;
1683   case ISD::AND:
1684   case ISD::OR:
1685   case ISD::XOR:    // NOT is handled here.
1686     // Logical binary ops preserve the number of sign bits.
1687     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1688     if (Tmp == 1) return 1;  // Early out.
1689     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1690     return std::min(Tmp, Tmp2);
1691
1692   case ISD::SELECT:
1693     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1694     if (Tmp == 1) return 1;  // Early out.
1695     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1696     return std::min(Tmp, Tmp2);
1697     
1698   case ISD::SETCC:
1699     // If setcc returns 0/-1, all bits are sign bits.
1700     if (TLI.getSetCCResultContents() ==
1701         TargetLowering::ZeroOrNegativeOneSetCCResult)
1702       return VTBits;
1703     break;
1704   case ISD::ROTL:
1705   case ISD::ROTR:
1706     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1707       unsigned RotAmt = C->getValue() & (VTBits-1);
1708       
1709       // Handle rotate right by N like a rotate left by 32-N.
1710       if (Op.getOpcode() == ISD::ROTR)
1711         RotAmt = (VTBits-RotAmt) & (VTBits-1);
1712
1713       // If we aren't rotating out all of the known-in sign bits, return the
1714       // number that are left.  This handles rotl(sext(x), 1) for example.
1715       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1716       if (Tmp > RotAmt+1) return Tmp-RotAmt;
1717     }
1718     break;
1719   case ISD::ADD:
1720     // Add can have at most one carry bit.  Thus we know that the output
1721     // is, at worst, one more bit than the inputs.
1722     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1723     if (Tmp == 1) return 1;  // Early out.
1724       
1725     // Special case decrementing a value (ADD X, -1):
1726     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1727       if (CRHS->isAllOnesValue()) {
1728         APInt KnownZero, KnownOne;
1729         APInt Mask = APInt::getAllOnesValue(VTBits);
1730         ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1731         
1732         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1733         // sign bits set.
1734         if ((KnownZero | APInt(VTBits, 1)) == Mask)
1735           return VTBits;
1736         
1737         // If we are subtracting one from a positive number, there is no carry
1738         // out of the result.
1739         if (KnownZero.isNegative())
1740           return Tmp;
1741       }
1742       
1743     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1744     if (Tmp2 == 1) return 1;
1745       return std::min(Tmp, Tmp2)-1;
1746     break;
1747     
1748   case ISD::SUB:
1749     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1750     if (Tmp2 == 1) return 1;
1751       
1752     // Handle NEG.
1753     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1754       if (CLHS->isNullValue()) {
1755         APInt KnownZero, KnownOne;
1756         APInt Mask = APInt::getAllOnesValue(VTBits);
1757         ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1758         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1759         // sign bits set.
1760         if ((KnownZero | APInt(VTBits, 1)) == Mask)
1761           return VTBits;
1762         
1763         // If the input is known to be positive (the sign bit is known clear),
1764         // the output of the NEG has the same number of sign bits as the input.
1765         if (KnownZero.isNegative())
1766           return Tmp2;
1767         
1768         // Otherwise, we treat this like a SUB.
1769       }
1770     
1771     // Sub can have at most one carry bit.  Thus we know that the output
1772     // is, at worst, one more bit than the inputs.
1773     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1774     if (Tmp == 1) return 1;  // Early out.
1775       return std::min(Tmp, Tmp2)-1;
1776     break;
1777   case ISD::TRUNCATE:
1778     // FIXME: it's tricky to do anything useful for this, but it is an important
1779     // case for targets like X86.
1780     break;
1781   }
1782   
1783   // Handle LOADX separately here. EXTLOAD case will fallthrough.
1784   if (Op.getOpcode() == ISD::LOAD) {
1785     LoadSDNode *LD = cast<LoadSDNode>(Op);
1786     unsigned ExtType = LD->getExtensionType();
1787     switch (ExtType) {
1788     default: break;
1789     case ISD::SEXTLOAD:    // '17' bits known
1790       Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1791       return VTBits-Tmp+1;
1792     case ISD::ZEXTLOAD:    // '16' bits known
1793       Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1794       return VTBits-Tmp;
1795     }
1796   }
1797
1798   // Allow the target to implement this method for its nodes.
1799   if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1800       Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 
1801       Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1802       Op.getOpcode() == ISD::INTRINSIC_VOID) {
1803     unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1804     if (NumBits > 1) return NumBits;
1805   }
1806   
1807   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1808   // use this information.
1809   APInt KnownZero, KnownOne;
1810   APInt Mask = APInt::getAllOnesValue(VTBits);
1811   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1812   
1813   if (KnownZero.isNegative()) {        // sign bit is 0
1814     Mask = KnownZero;
1815   } else if (KnownOne.isNegative()) {  // sign bit is 1;
1816     Mask = KnownOne;
1817   } else {
1818     // Nothing known.
1819     return 1;
1820   }
1821   
1822   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1823   // the number of identical bits in the top of the input value.
1824   Mask = ~Mask;
1825   Mask <<= Mask.getBitWidth()-VTBits;
1826   // Return # leading zeros.  We use 'min' here in case Val was zero before
1827   // shifting.  We don't want to return '64' as for an i32 "0".
1828   return std::min(VTBits, Mask.countLeadingZeros());
1829 }
1830
1831
1832 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1833   GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1834   if (!GA) return false;
1835   GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1836   if (!GV) return false;
1837   MachineModuleInfo *MMI = getMachineModuleInfo();
1838   return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1839 }
1840
1841
1842 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1843 /// element of the result of the vector shuffle.
1844 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned Idx) {
1845   MVT::ValueType VT = N->getValueType(0);
1846   SDOperand PermMask = N->getOperand(2);
1847   unsigned NumElems = PermMask.getNumOperands();
1848   SDOperand V = (Idx < NumElems) ? N->getOperand(0) : N->getOperand(1);
1849   Idx %= NumElems;
1850   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1851     return (Idx == 0)
1852      ? V.getOperand(0) : getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
1853   }
1854   if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
1855     SDOperand Elt = PermMask.getOperand(Idx);
1856     if (Elt.getOpcode() == ISD::UNDEF)
1857       return getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
1858     return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Elt)->getValue());
1859   }
1860   return SDOperand();
1861 }
1862
1863
1864 /// getNode - Gets or creates the specified node.
1865 ///
1866 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1867   FoldingSetNodeID ID;
1868   AddNodeIDNode(ID, Opcode, getVTList(VT), (SDOperand*)0, 0);
1869   void *IP = 0;
1870   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1871     return SDOperand(E, 0);
1872   SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1873   CSEMap.InsertNode(N, IP);
1874   
1875   AllNodes.push_back(N);
1876   return SDOperand(N, 0);
1877 }
1878
1879 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1880                                 SDOperand Operand) {
1881   // Constant fold unary operations with an integer constant operand.
1882   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1883     const APInt &Val = C->getAPIntValue();
1884     unsigned BitWidth = MVT::getSizeInBits(VT);
1885     switch (Opcode) {
1886     default: break;
1887     case ISD::SIGN_EXTEND:
1888       return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1889     case ISD::ANY_EXTEND:
1890     case ISD::ZERO_EXTEND:
1891     case ISD::TRUNCATE:
1892       return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1893     case ISD::UINT_TO_FP:
1894     case ISD::SINT_TO_FP: {
1895       const uint64_t zero[] = {0, 0};
1896       // No compile time operations on this type.
1897       if (VT==MVT::ppcf128)
1898         break;
1899       APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1900       (void)apf.convertFromAPInt(Val, 
1901                                  Opcode==ISD::SINT_TO_FP,
1902                                  APFloat::rmNearestTiesToEven);
1903       return getConstantFP(apf, VT);
1904     }
1905     case ISD::BIT_CONVERT:
1906       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1907         return getConstantFP(Val.bitsToFloat(), VT);
1908       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1909         return getConstantFP(Val.bitsToDouble(), VT);
1910       break;
1911     case ISD::BSWAP:
1912       return getConstant(Val.byteSwap(), VT);
1913     case ISD::CTPOP:
1914       return getConstant(Val.countPopulation(), VT);
1915     case ISD::CTLZ:
1916       return getConstant(Val.countLeadingZeros(), VT);
1917     case ISD::CTTZ:
1918       return getConstant(Val.countTrailingZeros(), VT);
1919     }
1920   }
1921
1922   // Constant fold unary operations with a floating point constant operand.
1923   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1924     APFloat V = C->getValueAPF();    // make copy
1925     if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1926       switch (Opcode) {
1927       case ISD::FNEG:
1928         V.changeSign();
1929         return getConstantFP(V, VT);
1930       case ISD::FABS:
1931         V.clearSign();
1932         return getConstantFP(V, VT);
1933       case ISD::FP_ROUND:
1934       case ISD::FP_EXTEND:
1935         // This can return overflow, underflow, or inexact; we don't care.
1936         // FIXME need to be more flexible about rounding mode.
1937         (void)V.convert(*MVTToAPFloatSemantics(VT),
1938                         APFloat::rmNearestTiesToEven);
1939         return getConstantFP(V, VT);
1940       case ISD::FP_TO_SINT:
1941       case ISD::FP_TO_UINT: {
1942         integerPart x;
1943         assert(integerPartWidth >= 64);
1944         // FIXME need to be more flexible about rounding mode.
1945         APFloat::opStatus s = V.convertToInteger(&x, 64U,
1946                               Opcode==ISD::FP_TO_SINT,
1947                               APFloat::rmTowardZero);
1948         if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
1949           break;
1950         return getConstant(x, VT);
1951       }
1952       case ISD::BIT_CONVERT:
1953         if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1954           return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1955         else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1956           return getConstant(V.convertToAPInt().getZExtValue(), VT);
1957         break;
1958       }
1959     }
1960   }
1961
1962   unsigned OpOpcode = Operand.Val->getOpcode();
1963   switch (Opcode) {
1964   case ISD::TokenFactor:
1965   case ISD::MERGE_VALUES:
1966     return Operand;         // Factor or merge of one node?  No need.
1967   case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1968   case ISD::FP_EXTEND:
1969     assert(MVT::isFloatingPoint(VT) &&
1970            MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1971     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
1972     if (Operand.getOpcode() == ISD::UNDEF)
1973       return getNode(ISD::UNDEF, VT);
1974     break;
1975   case ISD::SIGN_EXTEND:
1976     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1977            "Invalid SIGN_EXTEND!");
1978     if (Operand.getValueType() == VT) return Operand;   // noop extension
1979     assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1980            && "Invalid sext node, dst < src!");
1981     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1982       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1983     break;
1984   case ISD::ZERO_EXTEND:
1985     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1986            "Invalid ZERO_EXTEND!");
1987     if (Operand.getValueType() == VT) return Operand;   // noop extension
1988     assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1989            && "Invalid zext node, dst < src!");
1990     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
1991       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1992     break;
1993   case ISD::ANY_EXTEND:
1994     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1995            "Invalid ANY_EXTEND!");
1996     if (Operand.getValueType() == VT) return Operand;   // noop extension
1997     assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1998            && "Invalid anyext node, dst < src!");
1999     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2000       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
2001       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2002     break;
2003   case ISD::TRUNCATE:
2004     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
2005            "Invalid TRUNCATE!");
2006     if (Operand.getValueType() == VT) return Operand;   // noop truncate
2007     assert(MVT::getSizeInBits(Operand.getValueType()) > MVT::getSizeInBits(VT)
2008            && "Invalid truncate node, src < dst!");
2009     if (OpOpcode == ISD::TRUNCATE)
2010       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2011     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2012              OpOpcode == ISD::ANY_EXTEND) {
2013       // If the source is smaller than the dest, we still need an extend.
2014       if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
2015           < MVT::getSizeInBits(VT))
2016         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2017       else if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
2018                > MVT::getSizeInBits(VT))
2019         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2020       else
2021         return Operand.Val->getOperand(0);
2022     }
2023     break;
2024   case ISD::BIT_CONVERT:
2025     // Basic sanity checking.
2026     assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
2027            && "Cannot BIT_CONVERT between types of different sizes!");
2028     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
2029     if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
2030       return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2031     if (OpOpcode == ISD::UNDEF)
2032       return getNode(ISD::UNDEF, VT);
2033     break;
2034   case ISD::SCALAR_TO_VECTOR:
2035     assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
2036            MVT::getVectorElementType(VT) == Operand.getValueType() &&
2037            "Illegal SCALAR_TO_VECTOR node!");
2038     if (OpOpcode == ISD::UNDEF)
2039       return getNode(ISD::UNDEF, VT);
2040     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2041     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2042         isa<ConstantSDNode>(Operand.getOperand(1)) &&
2043         Operand.getConstantOperandVal(1) == 0 &&
2044         Operand.getOperand(0).getValueType() == VT)
2045       return Operand.getOperand(0);
2046     break;
2047   case ISD::FNEG:
2048     if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
2049       return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2050                      Operand.Val->getOperand(0));
2051     if (OpOpcode == ISD::FNEG)  // --X -> X
2052       return Operand.Val->getOperand(0);
2053     break;
2054   case ISD::FABS:
2055     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
2056       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2057     break;
2058   }
2059
2060   SDNode *N;
2061   SDVTList VTs = getVTList(VT);
2062   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2063     FoldingSetNodeID ID;
2064     SDOperand Ops[1] = { Operand };
2065     AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2066     void *IP = 0;
2067     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2068       return SDOperand(E, 0);
2069     N = new UnarySDNode(Opcode, VTs, Operand);
2070     CSEMap.InsertNode(N, IP);
2071   } else {
2072     N = new UnarySDNode(Opcode, VTs, Operand);
2073   }
2074   AllNodes.push_back(N);
2075   return SDOperand(N, 0);
2076 }
2077
2078
2079
2080 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2081                                 SDOperand N1, SDOperand N2) {
2082   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2083   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2084   switch (Opcode) {
2085   default: break;
2086   case ISD::TokenFactor:
2087     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2088            N2.getValueType() == MVT::Other && "Invalid token factor!");
2089     // Fold trivial token factors.
2090     if (N1.getOpcode() == ISD::EntryToken) return N2;
2091     if (N2.getOpcode() == ISD::EntryToken) return N1;
2092     break;
2093   case ISD::AND:
2094     assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
2095            N1.getValueType() == VT && "Binary operator types must match!");
2096     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
2097     // worth handling here.
2098     if (N2C && N2C->isNullValue())
2099       return N2;
2100     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
2101       return N1;
2102     break;
2103   case ISD::OR:
2104   case ISD::XOR:
2105     assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
2106            N1.getValueType() == VT && "Binary operator types must match!");
2107     // (X ^| 0) -> X.  This commonly occurs when legalizing i64 values, so it's
2108     // worth handling here.
2109     if (N2C && N2C->isNullValue())
2110       return N1;
2111     break;
2112   case ISD::UDIV:
2113   case ISD::UREM:
2114   case ISD::MULHU:
2115   case ISD::MULHS:
2116     assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
2117     // fall through
2118   case ISD::ADD:
2119   case ISD::SUB:
2120   case ISD::MUL:
2121   case ISD::SDIV:
2122   case ISD::SREM:
2123   case ISD::FADD:
2124   case ISD::FSUB:
2125   case ISD::FMUL:
2126   case ISD::FDIV:
2127   case ISD::FREM:
2128     assert(N1.getValueType() == N2.getValueType() &&
2129            N1.getValueType() == VT && "Binary operator types must match!");
2130     break;
2131   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
2132     assert(N1.getValueType() == VT &&
2133            MVT::isFloatingPoint(N1.getValueType()) && 
2134            MVT::isFloatingPoint(N2.getValueType()) &&
2135            "Invalid FCOPYSIGN!");
2136     break;
2137   case ISD::SHL:
2138   case ISD::SRA:
2139   case ISD::SRL:
2140   case ISD::ROTL:
2141   case ISD::ROTR:
2142     assert(VT == N1.getValueType() &&
2143            "Shift operators return type must be the same as their first arg");
2144     assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
2145            VT != MVT::i1 && "Shifts only work on integers");
2146     break;
2147   case ISD::FP_ROUND_INREG: {
2148     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2149     assert(VT == N1.getValueType() && "Not an inreg round!");
2150     assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
2151            "Cannot FP_ROUND_INREG integer types");
2152     assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2153            "Not rounding down!");
2154     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
2155     break;
2156   }
2157   case ISD::FP_ROUND:
2158     assert(MVT::isFloatingPoint(VT) &&
2159            MVT::isFloatingPoint(N1.getValueType()) &&
2160            MVT::getSizeInBits(VT) <= MVT::getSizeInBits(N1.getValueType()) &&
2161            isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2162     if (N1.getValueType() == VT) return N1;  // noop conversion.
2163     break;
2164   case ISD::AssertSext:
2165   case ISD::AssertZext: {
2166     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2167     assert(VT == N1.getValueType() && "Not an inreg extend!");
2168     assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2169            "Cannot *_EXTEND_INREG FP types");
2170     assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2171            "Not extending!");
2172     if (VT == EVT) return N1; // noop assertion.
2173     break;
2174   }
2175   case ISD::SIGN_EXTEND_INREG: {
2176     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2177     assert(VT == N1.getValueType() && "Not an inreg extend!");
2178     assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2179            "Cannot *_EXTEND_INREG FP types");
2180     assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2181            "Not extending!");
2182     if (EVT == VT) return N1;  // Not actually extending
2183
2184     if (N1C) {
2185       APInt Val = N1C->getAPIntValue();
2186       unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
2187       Val <<= Val.getBitWidth()-FromBits;
2188       Val = Val.ashr(Val.getBitWidth()-FromBits);
2189       return getConstant(Val, VT);
2190     }
2191     break;
2192   }
2193   case ISD::EXTRACT_VECTOR_ELT:
2194     assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2195
2196     // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2197     if (N1.getOpcode() == ISD::UNDEF)
2198       return getNode(ISD::UNDEF, VT);
2199       
2200     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2201     // expanding copies of large vectors from registers.
2202     if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2203         N1.getNumOperands() > 0) {
2204       unsigned Factor =
2205         MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2206       return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2207                      N1.getOperand(N2C->getValue() / Factor),
2208                      getConstant(N2C->getValue() % Factor, N2.getValueType()));
2209     }
2210
2211     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2212     // expanding large vector constants.
2213     if (N1.getOpcode() == ISD::BUILD_VECTOR)
2214       return N1.getOperand(N2C->getValue());
2215       
2216     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2217     // operations are lowered to scalars.
2218     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2219       if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2220         if (IEC == N2C)
2221           return N1.getOperand(1);
2222         else
2223           return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2224       }
2225     break;
2226   case ISD::EXTRACT_ELEMENT:
2227     assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2228     assert(!MVT::isVector(N1.getValueType()) &&
2229            MVT::isInteger(N1.getValueType()) &&
2230            !MVT::isVector(VT) && MVT::isInteger(VT) &&
2231            "EXTRACT_ELEMENT only applies to integers!");
2232
2233     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2234     // 64-bit integers into 32-bit parts.  Instead of building the extract of
2235     // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 
2236     if (N1.getOpcode() == ISD::BUILD_PAIR)
2237       return N1.getOperand(N2C->getValue());
2238
2239     // EXTRACT_ELEMENT of a constant int is also very common.
2240     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2241       unsigned ElementSize = MVT::getSizeInBits(VT);
2242       unsigned Shift = ElementSize * N2C->getValue();
2243       APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2244       return getConstant(ShiftedVal.trunc(ElementSize), VT);
2245     }
2246     break;
2247   case ISD::EXTRACT_SUBVECTOR:
2248     if (N1.getValueType() == VT) // Trivial extraction.
2249       return N1;
2250     break;
2251   }
2252
2253   if (N1C) {
2254     if (N2C) {
2255       APInt C1 = N1C->getAPIntValue(), C2 = N2C->getAPIntValue();
2256       switch (Opcode) {
2257       case ISD::ADD: return getConstant(C1 + C2, VT);
2258       case ISD::SUB: return getConstant(C1 - C2, VT);
2259       case ISD::MUL: return getConstant(C1 * C2, VT);
2260       case ISD::UDIV:
2261         if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2262         break;
2263       case ISD::UREM :
2264         if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2265         break;
2266       case ISD::SDIV :
2267         if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2268         break;
2269       case ISD::SREM :
2270         if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2271         break;
2272       case ISD::AND  : return getConstant(C1 & C2, VT);
2273       case ISD::OR   : return getConstant(C1 | C2, VT);
2274       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
2275       case ISD::SHL  : return getConstant(C1 << C2, VT);
2276       case ISD::SRL  : return getConstant(C1.lshr(C2), VT);
2277       case ISD::SRA  : return getConstant(C1.ashr(C2), VT);
2278       case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2279       case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2280       default: break;
2281       }
2282     } else {      // Cannonicalize constant to RHS if commutative
2283       if (isCommutativeBinOp(Opcode)) {
2284         std::swap(N1C, N2C);
2285         std::swap(N1, N2);
2286       }
2287     }
2288   }
2289
2290   // Constant fold FP operations.
2291   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2292   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2293   if (N1CFP) {
2294     if (!N2CFP && isCommutativeBinOp(Opcode)) {
2295       // Cannonicalize constant to RHS if commutative
2296       std::swap(N1CFP, N2CFP);
2297       std::swap(N1, N2);
2298     } else if (N2CFP && VT != MVT::ppcf128) {
2299       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2300       APFloat::opStatus s;
2301       switch (Opcode) {
2302       case ISD::FADD: 
2303         s = V1.add(V2, APFloat::rmNearestTiesToEven);
2304         if (s != APFloat::opInvalidOp)
2305           return getConstantFP(V1, VT);
2306         break;
2307       case ISD::FSUB: 
2308         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2309         if (s!=APFloat::opInvalidOp)
2310           return getConstantFP(V1, VT);
2311         break;
2312       case ISD::FMUL:
2313         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2314         if (s!=APFloat::opInvalidOp)
2315           return getConstantFP(V1, VT);
2316         break;
2317       case ISD::FDIV:
2318         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2319         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2320           return getConstantFP(V1, VT);
2321         break;
2322       case ISD::FREM :
2323         s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2324         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2325           return getConstantFP(V1, VT);
2326         break;
2327       case ISD::FCOPYSIGN:
2328         V1.copySign(V2);
2329         return getConstantFP(V1, VT);
2330       default: break;
2331       }
2332     }
2333   }
2334   
2335   // Canonicalize an UNDEF to the RHS, even over a constant.
2336   if (N1.getOpcode() == ISD::UNDEF) {
2337     if (isCommutativeBinOp(Opcode)) {
2338       std::swap(N1, N2);
2339     } else {
2340       switch (Opcode) {
2341       case ISD::FP_ROUND_INREG:
2342       case ISD::SIGN_EXTEND_INREG:
2343       case ISD::SUB:
2344       case ISD::FSUB:
2345       case ISD::FDIV:
2346       case ISD::FREM:
2347       case ISD::SRA:
2348         return N1;     // fold op(undef, arg2) -> undef
2349       case ISD::UDIV:
2350       case ISD::SDIV:
2351       case ISD::UREM:
2352       case ISD::SREM:
2353       case ISD::SRL:
2354       case ISD::SHL:
2355         if (!MVT::isVector(VT)) 
2356           return getConstant(0, VT);    // fold op(undef, arg2) -> 0
2357         // For vectors, we can't easily build an all zero vector, just return
2358         // the LHS.
2359         return N2;
2360       }
2361     }
2362   }
2363   
2364   // Fold a bunch of operators when the RHS is undef. 
2365   if (N2.getOpcode() == ISD::UNDEF) {
2366     switch (Opcode) {
2367     case ISD::XOR:
2368       if (N1.getOpcode() == ISD::UNDEF)
2369         // Handle undef ^ undef -> 0 special case. This is a common
2370         // idiom (misuse).
2371         return getConstant(0, VT);
2372       // fallthrough
2373     case ISD::ADD:
2374     case ISD::ADDC:
2375     case ISD::ADDE:
2376     case ISD::SUB:
2377     case ISD::FADD:
2378     case ISD::FSUB:
2379     case ISD::FMUL:
2380     case ISD::FDIV:
2381     case ISD::FREM:
2382     case ISD::UDIV:
2383     case ISD::SDIV:
2384     case ISD::UREM:
2385     case ISD::SREM:
2386       return N2;       // fold op(arg1, undef) -> undef
2387     case ISD::MUL: 
2388     case ISD::AND:
2389     case ISD::SRL:
2390     case ISD::SHL:
2391       if (!MVT::isVector(VT)) 
2392         return getConstant(0, VT);  // fold op(arg1, undef) -> 0
2393       // For vectors, we can't easily build an all zero vector, just return
2394       // the LHS.
2395       return N1;
2396     case ISD::OR:
2397       if (!MVT::isVector(VT)) 
2398         return getConstant(MVT::getIntVTBitMask(VT), VT);
2399       // For vectors, we can't easily build an all one vector, just return
2400       // the LHS.
2401       return N1;
2402     case ISD::SRA:
2403       return N1;
2404     }
2405   }
2406
2407   // Memoize this node if possible.
2408   SDNode *N;
2409   SDVTList VTs = getVTList(VT);
2410   if (VT != MVT::Flag) {
2411     SDOperand Ops[] = { N1, N2 };
2412     FoldingSetNodeID ID;
2413     AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2414     void *IP = 0;
2415     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2416       return SDOperand(E, 0);
2417     N = new BinarySDNode(Opcode, VTs, N1, N2);
2418     CSEMap.InsertNode(N, IP);
2419   } else {
2420     N = new BinarySDNode(Opcode, VTs, N1, N2);
2421   }
2422
2423   AllNodes.push_back(N);
2424   return SDOperand(N, 0);
2425 }
2426
2427 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2428                                 SDOperand N1, SDOperand N2, SDOperand N3) {
2429   // Perform various simplifications.
2430   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2431   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2432   switch (Opcode) {
2433   case ISD::SETCC: {
2434     // Use FoldSetCC to simplify SETCC's.
2435     SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2436     if (Simp.Val) return Simp;
2437     break;
2438   }
2439   case ISD::SELECT:
2440     if (N1C) {
2441      if (N1C->getValue())
2442         return N2;             // select true, X, Y -> X
2443       else
2444         return N3;             // select false, X, Y -> Y
2445     }
2446
2447     if (N2 == N3) return N2;   // select C, X, X -> X
2448     break;
2449   case ISD::BRCOND:
2450     if (N2C) {
2451       if (N2C->getValue()) // Unconditional branch
2452         return getNode(ISD::BR, MVT::Other, N1, N3);
2453       else
2454         return N1;         // Never-taken branch
2455     }
2456     break;
2457   case ISD::VECTOR_SHUFFLE:
2458     assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2459            MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2460            N3.getOpcode() == ISD::BUILD_VECTOR &&
2461            MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2462            "Illegal VECTOR_SHUFFLE node!");
2463     break;
2464   case ISD::BIT_CONVERT:
2465     // Fold bit_convert nodes from a type to themselves.
2466     if (N1.getValueType() == VT)
2467       return N1;
2468     break;
2469   }
2470
2471   // Memoize node if it doesn't produce a flag.
2472   SDNode *N;
2473   SDVTList VTs = getVTList(VT);
2474   if (VT != MVT::Flag) {
2475     SDOperand Ops[] = { N1, N2, N3 };
2476     FoldingSetNodeID ID;
2477     AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2478     void *IP = 0;
2479     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2480       return SDOperand(E, 0);
2481     N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2482     CSEMap.InsertNode(N, IP);
2483   } else {
2484     N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2485   }
2486   AllNodes.push_back(N);
2487   return SDOperand(N, 0);
2488 }
2489
2490 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2491                                 SDOperand N1, SDOperand N2, SDOperand N3,
2492                                 SDOperand N4) {
2493   SDOperand Ops[] = { N1, N2, N3, N4 };
2494   return getNode(Opcode, VT, Ops, 4);
2495 }
2496
2497 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2498                                 SDOperand N1, SDOperand N2, SDOperand N3,
2499                                 SDOperand N4, SDOperand N5) {
2500   SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2501   return getNode(Opcode, VT, Ops, 5);
2502 }
2503
2504 /// getMemsetValue - Vectorized representation of the memset value
2505 /// operand.
2506 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2507                                 SelectionDAG &DAG) {
2508   MVT::ValueType CurVT = VT;
2509   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2510     uint64_t Val   = C->getValue() & 255;
2511     unsigned Shift = 8;
2512     while (CurVT != MVT::i8) {
2513       Val = (Val << Shift) | Val;
2514       Shift <<= 1;
2515       CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2516     }
2517     return DAG.getConstant(Val, VT);
2518   } else {
2519     Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2520     unsigned Shift = 8;
2521     while (CurVT != MVT::i8) {
2522       Value =
2523         DAG.getNode(ISD::OR, VT,
2524                     DAG.getNode(ISD::SHL, VT, Value,
2525                                 DAG.getConstant(Shift, MVT::i8)), Value);
2526       Shift <<= 1;
2527       CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2528     }
2529
2530     return Value;
2531   }
2532 }
2533
2534 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2535 /// used when a memcpy is turned into a memset when the source is a constant
2536 /// string ptr.
2537 static SDOperand getMemsetStringVal(MVT::ValueType VT,
2538                                     SelectionDAG &DAG,
2539                                     const TargetLowering &TLI,
2540                                     std::string &Str, unsigned Offset) {
2541   uint64_t Val = 0;
2542   unsigned MSB = MVT::getSizeInBits(VT) / 8;
2543   if (TLI.isLittleEndian())
2544     Offset = Offset + MSB - 1;
2545   for (unsigned i = 0; i != MSB; ++i) {
2546     Val = (Val << 8) | (unsigned char)Str[Offset];
2547     Offset += TLI.isLittleEndian() ? -1 : 1;
2548   }
2549   return DAG.getConstant(Val, VT);
2550 }
2551
2552 /// getMemBasePlusOffset - Returns base and offset node for the 
2553 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2554                                       SelectionDAG &DAG) {
2555   MVT::ValueType VT = Base.getValueType();
2556   return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2557 }
2558
2559 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2560 /// to replace the memset / memcpy is below the threshold. It also returns the
2561 /// types of the sequence of memory ops to perform memset / memcpy.
2562 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2563                                      unsigned Limit, uint64_t Size,
2564                                      unsigned Align,
2565                                      const TargetLowering &TLI) {
2566   MVT::ValueType VT;
2567
2568   if (TLI.allowsUnalignedMemoryAccesses()) {
2569     VT = MVT::i64;
2570   } else {
2571     switch (Align & 7) {
2572     case 0:
2573       VT = MVT::i64;
2574       break;
2575     case 4:
2576       VT = MVT::i32;
2577       break;
2578     case 2:
2579       VT = MVT::i16;
2580       break;
2581     default:
2582       VT = MVT::i8;
2583       break;
2584     }
2585   }
2586
2587   MVT::ValueType LVT = MVT::i64;
2588   while (!TLI.isTypeLegal(LVT))
2589     LVT = (MVT::ValueType)((unsigned)LVT - 1);
2590   assert(MVT::isInteger(LVT));
2591
2592   if (VT > LVT)
2593     VT = LVT;
2594
2595   unsigned NumMemOps = 0;
2596   while (Size != 0) {
2597     unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2598     while (VTSize > Size) {
2599       VT = (MVT::ValueType)((unsigned)VT - 1);
2600       VTSize >>= 1;
2601     }
2602     assert(MVT::isInteger(VT));
2603
2604     if (++NumMemOps > Limit)
2605       return false;
2606     MemOps.push_back(VT);
2607     Size -= VTSize;
2608   }
2609
2610   return true;
2611 }
2612
2613 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2614                                          SDOperand Chain, SDOperand Dst,
2615                                          SDOperand Src, uint64_t Size,
2616                                          unsigned Align,
2617                                          bool AlwaysInline,
2618                                          const Value *DstSV, uint64_t DstSVOff,
2619                                          const Value *SrcSV, uint64_t SrcSVOff){
2620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2621
2622   // Expand memcpy to a series of store ops if the size operand falls below
2623   // a certain threshold.
2624   std::vector<MVT::ValueType> MemOps;
2625   uint64_t Limit = -1;
2626   if (!AlwaysInline)
2627     Limit = TLI.getMaxStoresPerMemcpy();
2628   if (!MeetsMaxMemopRequirement(MemOps, Limit, Size, Align, TLI))
2629     return SDOperand();
2630
2631   SmallVector<SDOperand, 8> OutChains;
2632
2633   unsigned NumMemOps = MemOps.size();
2634   unsigned SrcDelta = 0;
2635   GlobalAddressSDNode *G = NULL;
2636   std::string Str;
2637   bool CopyFromStr = false;
2638   uint64_t SrcOff = 0, DstOff = 0;
2639
2640   if (Src.getOpcode() == ISD::GlobalAddress)
2641     G = cast<GlobalAddressSDNode>(Src);
2642   else if (Src.getOpcode() == ISD::ADD &&
2643            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2644            Src.getOperand(1).getOpcode() == ISD::Constant) {
2645     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2646     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2647   }
2648   if (G) {
2649     GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2650     if (GV && GV->isConstant()) {
2651       Str = GV->getStringValue(false);
2652       if (!Str.empty()) {
2653         CopyFromStr = true;
2654         SrcOff += SrcDelta;
2655       }
2656     }
2657   }
2658
2659   for (unsigned i = 0; i < NumMemOps; i++) {
2660     MVT::ValueType VT = MemOps[i];
2661     unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2662     SDOperand Value, Store;
2663
2664     if (CopyFromStr) {
2665       Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2666       Store =
2667         DAG.getStore(Chain, Value,
2668                      getMemBasePlusOffset(Dst, DstOff, DAG),
2669                      DstSV, DstSVOff + DstOff);
2670     } else {
2671       Value = DAG.getLoad(VT, Chain,
2672                           getMemBasePlusOffset(Src, SrcOff, DAG),
2673                           SrcSV, SrcSVOff + SrcOff, false, Align);
2674       Store =
2675         DAG.getStore(Chain, Value,
2676                      getMemBasePlusOffset(Dst, DstOff, DAG),
2677                      DstSV, DstSVOff + DstOff, false, Align);
2678     }
2679     OutChains.push_back(Store);
2680     SrcOff += VTSize;
2681     DstOff += VTSize;
2682   }
2683
2684   return DAG.getNode(ISD::TokenFactor, MVT::Other,
2685                      &OutChains[0], OutChains.size());
2686 }
2687
2688 static SDOperand getMemsetStores(SelectionDAG &DAG,
2689                                  SDOperand Chain, SDOperand Dst,
2690                                  SDOperand Src, uint64_t Size,
2691                                  unsigned Align,
2692                                  const Value *DstSV, uint64_t DstSVOff) {
2693   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2694
2695   // Expand memset to a series of load/store ops if the size operand
2696   // falls below a certain threshold.
2697   std::vector<MVT::ValueType> MemOps;
2698   if (!MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2699                                 Size, Align, TLI))
2700     return SDOperand();
2701
2702   SmallVector<SDOperand, 8> OutChains;
2703   uint64_t DstOff = 0;
2704
2705   unsigned NumMemOps = MemOps.size();
2706   for (unsigned i = 0; i < NumMemOps; i++) {
2707     MVT::ValueType VT = MemOps[i];
2708     unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2709     SDOperand Value = getMemsetValue(Src, VT, DAG);
2710     SDOperand Store = DAG.getStore(Chain, Value,
2711                                    getMemBasePlusOffset(Dst, DstOff, DAG),
2712                                    DstSV, DstSVOff + DstOff);
2713     OutChains.push_back(Store);
2714     DstOff += VTSize;
2715   }
2716
2717   return DAG.getNode(ISD::TokenFactor, MVT::Other,
2718                      &OutChains[0], OutChains.size());
2719 }
2720
2721 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2722                                   SDOperand Src, SDOperand Size,
2723                                   unsigned Align, bool AlwaysInline,
2724                                   const Value *DstSV, uint64_t DstSVOff,
2725                                   const Value *SrcSV, uint64_t SrcSVOff) {
2726
2727   // Check to see if we should lower the memcpy to loads and stores first.
2728   // For cases within the target-specified limits, this is the best choice.
2729   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2730   if (ConstantSize) {
2731     // Memcpy with size zero? Just return the original chain.
2732     if (ConstantSize->isNullValue())
2733       return Chain;
2734
2735     SDOperand Result =
2736       getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2737                               Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2738     if (Result.Val)
2739       return Result;
2740   }
2741
2742   // Then check to see if we should lower the memcpy with target-specific
2743   // code. If the target chooses to do this, this is the next best.
2744   SDOperand Result =
2745     TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2746                                 AlwaysInline,
2747                                 DstSV, DstSVOff, SrcSV, SrcSVOff);
2748   if (Result.Val)
2749     return Result;
2750
2751   // If we really need inline code and the target declined to provide it,
2752   // use a (potentially long) sequence of loads and stores.
2753   if (AlwaysInline) {
2754     assert(ConstantSize && "AlwaysInline requires a constant size!");
2755     return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2756                                    ConstantSize->getValue(), Align, true,
2757                                    DstSV, DstSVOff, SrcSV, SrcSVOff);
2758   }
2759
2760   // Emit a library call.
2761   TargetLowering::ArgListTy Args;
2762   TargetLowering::ArgListEntry Entry;
2763   Entry.Ty = TLI.getTargetData()->getIntPtrType();
2764   Entry.Node = Dst; Args.push_back(Entry);
2765   Entry.Node = Src; Args.push_back(Entry);
2766   Entry.Node = Size; Args.push_back(Entry);
2767   std::pair<SDOperand,SDOperand> CallResult =
2768     TLI.LowerCallTo(Chain, Type::VoidTy,
2769                     false, false, false, CallingConv::C, false,
2770                     getExternalSymbol("memcpy", TLI.getPointerTy()),
2771                     Args, *this);
2772   return CallResult.second;
2773 }
2774
2775 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2776                                    SDOperand Src, SDOperand Size,
2777                                    unsigned Align,
2778                                    const Value *DstSV, uint64_t DstSVOff,
2779                                    const Value *SrcSV, uint64_t SrcSVOff) {
2780
2781   // TODO: Optimize small memmove cases with simple loads and stores,
2782   // ensuring that all loads precede all stores. This can cause severe
2783   // register pressure, so targets should be careful with the size limit.
2784
2785   // Then check to see if we should lower the memmove with target-specific
2786   // code. If the target chooses to do this, this is the next best.
2787   SDOperand Result =
2788     TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2789                                  DstSV, DstSVOff, SrcSV, SrcSVOff);
2790   if (Result.Val)
2791     return Result;
2792
2793   // Emit a library call.
2794   TargetLowering::ArgListTy Args;
2795   TargetLowering::ArgListEntry Entry;
2796   Entry.Ty = TLI.getTargetData()->getIntPtrType();
2797   Entry.Node = Dst; Args.push_back(Entry);
2798   Entry.Node = Src; Args.push_back(Entry);
2799   Entry.Node = Size; Args.push_back(Entry);
2800   std::pair<SDOperand,SDOperand> CallResult =
2801     TLI.LowerCallTo(Chain, Type::VoidTy,
2802                     false, false, false, CallingConv::C, false,
2803                     getExternalSymbol("memmove", TLI.getPointerTy()),
2804                     Args, *this);
2805   return CallResult.second;
2806 }
2807
2808 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2809                                   SDOperand Src, SDOperand Size,
2810                                   unsigned Align,
2811                                   const Value *DstSV, uint64_t DstSVOff) {
2812
2813   // Check to see if we should lower the memset to stores first.
2814   // For cases within the target-specified limits, this is the best choice.
2815   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2816   if (ConstantSize) {
2817     // Memset with size zero? Just return the original chain.
2818     if (ConstantSize->isNullValue())
2819       return Chain;
2820
2821     SDOperand Result =
2822       getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
2823                       DstSV, DstSVOff);
2824     if (Result.Val)
2825       return Result;
2826   }
2827
2828   // Then check to see if we should lower the memset with target-specific
2829   // code. If the target chooses to do this, this is the next best.
2830   SDOperand Result =
2831     TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
2832                                 DstSV, DstSVOff);
2833   if (Result.Val)
2834     return Result;
2835
2836   // Emit a library call.
2837   const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
2838   TargetLowering::ArgListTy Args;
2839   TargetLowering::ArgListEntry Entry;
2840   Entry.Node = Dst; Entry.Ty = IntPtrTy;
2841   Args.push_back(Entry);
2842   // Extend or truncate the argument to be an i32 value for the call.
2843   if (Src.getValueType() > MVT::i32)
2844     Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
2845   else
2846     Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
2847   Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
2848   Args.push_back(Entry);
2849   Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
2850   Args.push_back(Entry);
2851   std::pair<SDOperand,SDOperand> CallResult =
2852     TLI.LowerCallTo(Chain, Type::VoidTy,
2853                     false, false, false, CallingConv::C, false,
2854                     getExternalSymbol("memset", TLI.getPointerTy()),
2855                     Args, *this);
2856   return CallResult.second;
2857 }
2858
2859 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain, 
2860                                   SDOperand Ptr, SDOperand Cmp, 
2861                                   SDOperand Swp, MVT::ValueType VT) {
2862   assert(Opcode == ISD::ATOMIC_LCS && "Invalid Atomic Op");
2863   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
2864   SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
2865   FoldingSetNodeID ID;
2866   SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
2867   AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
2868   ID.AddInteger((unsigned int)VT);
2869   void* IP = 0;
2870   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2871     return SDOperand(E, 0);
2872   SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, VT);
2873   CSEMap.InsertNode(N, IP);
2874   AllNodes.push_back(N);
2875   return SDOperand(N, 0);
2876 }
2877
2878 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain, 
2879                                   SDOperand Ptr, SDOperand Val, 
2880                                   MVT::ValueType VT) {
2881   assert((   Opcode == ISD::ATOMIC_LAS || Opcode == ISD::ATOMIC_LSS
2882           || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
2883           || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
2884           || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
2885           || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX) 
2886          && "Invalid Atomic Op");
2887   SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
2888   FoldingSetNodeID ID;
2889   SDOperand Ops[] = {Chain, Ptr, Val};
2890   AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2891   ID.AddInteger((unsigned int)VT);
2892   void* IP = 0;
2893   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2894     return SDOperand(E, 0);
2895   SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, VT);
2896   CSEMap.InsertNode(N, IP);
2897   AllNodes.push_back(N);
2898   return SDOperand(N, 0);
2899 }
2900
2901 SDOperand
2902 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
2903                       MVT::ValueType VT, SDOperand Chain,
2904                       SDOperand Ptr, SDOperand Offset,
2905                       const Value *SV, int SVOffset, MVT::ValueType EVT,
2906                       bool isVolatile, unsigned Alignment) {
2907   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2908     const Type *Ty = 0;
2909     if (VT != MVT::iPTR) {
2910       Ty = MVT::getTypeForValueType(VT);
2911     } else if (SV) {
2912       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2913       assert(PT && "Value for load must be a pointer");
2914       Ty = PT->getElementType();
2915     }
2916     assert(Ty && "Could not get type information for load");
2917     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2918   }
2919
2920   if (VT == EVT) {
2921     ExtType = ISD::NON_EXTLOAD;
2922   } else if (ExtType == ISD::NON_EXTLOAD) {
2923     assert(VT == EVT && "Non-extending load from different memory type!");
2924   } else {
2925     // Extending load.
2926     if (MVT::isVector(VT))
2927       assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2928     else
2929       assert(MVT::getSizeInBits(EVT) < MVT::getSizeInBits(VT) &&
2930              "Should only be an extending load, not truncating!");
2931     assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2932            "Cannot sign/zero extend a FP/Vector load!");
2933     assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2934            "Cannot convert from FP to Int or Int -> FP!");
2935   }
2936
2937   bool Indexed = AM != ISD::UNINDEXED;
2938   assert(Indexed || Offset.getOpcode() == ISD::UNDEF &&
2939          "Unindexed load with an offset!");
2940
2941   SDVTList VTs = Indexed ?
2942     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
2943   SDOperand Ops[] = { Chain, Ptr, Offset };
2944   FoldingSetNodeID ID;
2945   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2946   ID.AddInteger(AM);
2947   ID.AddInteger(ExtType);
2948   ID.AddInteger((unsigned int)EVT);
2949   ID.AddInteger(Alignment);
2950   ID.AddInteger(isVolatile);
2951   void *IP = 0;
2952   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2953     return SDOperand(E, 0);
2954   SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
2955                              Alignment, isVolatile);
2956   CSEMap.InsertNode(N, IP);
2957   AllNodes.push_back(N);
2958   return SDOperand(N, 0);
2959 }
2960
2961 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2962                                 SDOperand Chain, SDOperand Ptr,
2963                                 const Value *SV, int SVOffset,
2964                                 bool isVolatile, unsigned Alignment) {
2965   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2966   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
2967                  SV, SVOffset, VT, isVolatile, Alignment);
2968 }
2969
2970 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2971                                    SDOperand Chain, SDOperand Ptr,
2972                                    const Value *SV,
2973                                    int SVOffset, MVT::ValueType EVT,
2974                                    bool isVolatile, unsigned Alignment) {
2975   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2976   return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
2977                  SV, SVOffset, EVT, isVolatile, Alignment);
2978 }
2979
2980 SDOperand
2981 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2982                              SDOperand Offset, ISD::MemIndexedMode AM) {
2983   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2984   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2985          "Load is already a indexed load!");
2986   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
2987                  LD->getChain(), Base, Offset, LD->getSrcValue(),
2988                  LD->getSrcValueOffset(), LD->getMemoryVT(),
2989                  LD->isVolatile(), LD->getAlignment());
2990 }
2991
2992 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2993                                  SDOperand Ptr, const Value *SV, int SVOffset,
2994                                  bool isVolatile, unsigned Alignment) {
2995   MVT::ValueType VT = Val.getValueType();
2996
2997   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2998     const Type *Ty = 0;
2999     if (VT != MVT::iPTR) {
3000       Ty = MVT::getTypeForValueType(VT);
3001     } else if (SV) {
3002       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3003       assert(PT && "Value for store must be a pointer");
3004       Ty = PT->getElementType();
3005     }
3006     assert(Ty && "Could not get type information for store");
3007     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3008   }
3009   SDVTList VTs = getVTList(MVT::Other);
3010   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3011   SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3012   FoldingSetNodeID ID;
3013   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3014   ID.AddInteger(ISD::UNINDEXED);
3015   ID.AddInteger(false);
3016   ID.AddInteger((unsigned int)VT);
3017   ID.AddInteger(Alignment);
3018   ID.AddInteger(isVolatile);
3019   void *IP = 0;
3020   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3021     return SDOperand(E, 0);
3022   SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3023                               VT, SV, SVOffset, Alignment, isVolatile);
3024   CSEMap.InsertNode(N, IP);
3025   AllNodes.push_back(N);
3026   return SDOperand(N, 0);
3027 }
3028
3029 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3030                                       SDOperand Ptr, const Value *SV,
3031                                       int SVOffset, MVT::ValueType SVT,
3032                                       bool isVolatile, unsigned Alignment) {
3033   MVT::ValueType VT = Val.getValueType();
3034
3035   if (VT == SVT)
3036     return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3037
3038   assert(MVT::getSizeInBits(VT) > MVT::getSizeInBits(SVT) &&
3039          "Not a truncation?");
3040   assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
3041          "Can't do FP-INT conversion!");
3042
3043   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3044     const Type *Ty = 0;
3045     if (VT != MVT::iPTR) {
3046       Ty = MVT::getTypeForValueType(VT);
3047     } else if (SV) {
3048       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3049       assert(PT && "Value for store must be a pointer");
3050       Ty = PT->getElementType();
3051     }
3052     assert(Ty && "Could not get type information for store");
3053     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3054   }
3055   SDVTList VTs = getVTList(MVT::Other);
3056   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3057   SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3058   FoldingSetNodeID ID;
3059   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3060   ID.AddInteger(ISD::UNINDEXED);
3061   ID.AddInteger(1);
3062   ID.AddInteger((unsigned int)SVT);
3063   ID.AddInteger(Alignment);
3064   ID.AddInteger(isVolatile);
3065   void *IP = 0;
3066   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3067     return SDOperand(E, 0);
3068   SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3069                               SVT, SV, SVOffset, Alignment, isVolatile);
3070   CSEMap.InsertNode(N, IP);
3071   AllNodes.push_back(N);
3072   return SDOperand(N, 0);
3073 }
3074
3075 SDOperand
3076 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3077                               SDOperand Offset, ISD::MemIndexedMode AM) {
3078   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3079   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3080          "Store is already a indexed store!");
3081   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3082   SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3083   FoldingSetNodeID ID;
3084   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3085   ID.AddInteger(AM);
3086   ID.AddInteger(ST->isTruncatingStore());
3087   ID.AddInteger((unsigned int)(ST->getMemoryVT()));
3088   ID.AddInteger(ST->getAlignment());
3089   ID.AddInteger(ST->isVolatile());
3090   void *IP = 0;
3091   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3092     return SDOperand(E, 0);
3093   SDNode *N = new StoreSDNode(Ops, VTs, AM,
3094                               ST->isTruncatingStore(), ST->getMemoryVT(),
3095                               ST->getSrcValue(), ST->getSrcValueOffset(),
3096                               ST->getAlignment(), ST->isVolatile());
3097   CSEMap.InsertNode(N, IP);
3098   AllNodes.push_back(N);
3099   return SDOperand(N, 0);
3100 }
3101
3102 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
3103                                  SDOperand Chain, SDOperand Ptr,
3104                                  SDOperand SV) {
3105   SDOperand Ops[] = { Chain, Ptr, SV };
3106   return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3107 }
3108
3109 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
3110                                 SDOperandPtr Ops, unsigned NumOps) {
3111   switch (NumOps) {
3112   case 0: return getNode(Opcode, VT);
3113   case 1: return getNode(Opcode, VT, Ops[0]);
3114   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3115   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3116   default: break;
3117   }
3118   
3119   switch (Opcode) {
3120   default: break;
3121   case ISD::SELECT_CC: {
3122     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3123     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3124            "LHS and RHS of condition must have same type!");
3125     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3126            "True and False arms of SelectCC must have same type!");
3127     assert(Ops[2].getValueType() == VT &&
3128            "select_cc node must be of same type as true and false value!");
3129     break;
3130   }
3131   case ISD::BR_CC: {
3132     assert(NumOps == 5 && "BR_CC takes 5 operands!");
3133     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3134            "LHS/RHS of comparison should match types!");
3135     break;
3136   }
3137   }
3138
3139   // Memoize nodes.
3140   SDNode *N;
3141   SDVTList VTs = getVTList(VT);
3142   if (VT != MVT::Flag) {
3143     FoldingSetNodeID ID;
3144     AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3145     void *IP = 0;
3146     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3147       return SDOperand(E, 0);
3148     N = new SDNode(Opcode, VTs, Ops, NumOps);
3149     CSEMap.InsertNode(N, IP);
3150   } else {
3151     N = new SDNode(Opcode, VTs, Ops, NumOps);
3152   }
3153   AllNodes.push_back(N);
3154   return SDOperand(N, 0);
3155 }
3156
3157 SDOperand SelectionDAG::getNode(unsigned Opcode,
3158                                 std::vector<MVT::ValueType> &ResultTys,
3159                                 SDOperandPtr Ops, unsigned NumOps) {
3160   return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3161                  Ops, NumOps);
3162 }
3163
3164 SDOperand SelectionDAG::getNode(unsigned Opcode,
3165                                 const MVT::ValueType *VTs, unsigned NumVTs,
3166                                 SDOperandPtr Ops, unsigned NumOps) {
3167   if (NumVTs == 1)
3168     return getNode(Opcode, VTs[0], Ops, NumOps);
3169   return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3170 }  
3171   
3172 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3173                                 SDOperandPtr Ops, unsigned NumOps) {
3174   if (VTList.NumVTs == 1)
3175     return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3176
3177   switch (Opcode) {
3178   // FIXME: figure out how to safely handle things like
3179   // int foo(int x) { return 1 << (x & 255); }
3180   // int bar() { return foo(256); }
3181 #if 0
3182   case ISD::SRA_PARTS:
3183   case ISD::SRL_PARTS:
3184   case ISD::SHL_PARTS:
3185     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3186         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3187       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3188     else if (N3.getOpcode() == ISD::AND)
3189       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3190         // If the and is only masking out bits that cannot effect the shift,
3191         // eliminate the and.
3192         unsigned NumBits = MVT::getSizeInBits(VT)*2;
3193         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3194           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3195       }
3196     break;
3197 #endif
3198   }
3199
3200   // Memoize the node unless it returns a flag.
3201   SDNode *N;
3202   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3203     FoldingSetNodeID ID;
3204     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3205     void *IP = 0;
3206     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3207       return SDOperand(E, 0);
3208     if (NumOps == 1)
3209       N = new UnarySDNode(Opcode, VTList, Ops[0]);
3210     else if (NumOps == 2)
3211       N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3212     else if (NumOps == 3)
3213       N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3214     else
3215       N = new SDNode(Opcode, VTList, Ops, NumOps);
3216     CSEMap.InsertNode(N, IP);
3217   } else {
3218     if (NumOps == 1)
3219       N = new UnarySDNode(Opcode, VTList, Ops[0]);
3220     else if (NumOps == 2)
3221       N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3222     else if (NumOps == 3)
3223       N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3224     else
3225       N = new SDNode(Opcode, VTList, Ops, NumOps);
3226   }
3227   AllNodes.push_back(N);
3228   return SDOperand(N, 0);
3229 }
3230
3231 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3232   return getNode(Opcode, VTList, (SDOperand*)0, 0);
3233 }
3234
3235 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3236                                 SDOperand N1) {
3237   SDOperand Ops[] = { N1 };
3238   return getNode(Opcode, VTList, Ops, 1);
3239 }
3240
3241 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3242                                 SDOperand N1, SDOperand N2) {
3243   SDOperand Ops[] = { N1, N2 };
3244   return getNode(Opcode, VTList, Ops, 2);
3245 }
3246
3247 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3248                                 SDOperand N1, SDOperand N2, SDOperand N3) {
3249   SDOperand Ops[] = { N1, N2, N3 };
3250   return getNode(Opcode, VTList, Ops, 3);
3251 }
3252
3253 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3254                                 SDOperand N1, SDOperand N2, SDOperand N3,
3255                                 SDOperand N4) {
3256   SDOperand Ops[] = { N1, N2, N3, N4 };
3257   return getNode(Opcode, VTList, Ops, 4);
3258 }
3259
3260 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3261                                 SDOperand N1, SDOperand N2, SDOperand N3,
3262                                 SDOperand N4, SDOperand N5) {
3263   SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3264   return getNode(Opcode, VTList, Ops, 5);
3265 }
3266
3267 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
3268   return makeVTList(SDNode::getValueTypeList(VT), 1);
3269 }
3270
3271 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
3272   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
3273        E = VTList.end(); I != E; ++I) {
3274     if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3275       return makeVTList(&(*I)[0], 2);
3276   }
3277   std::vector<MVT::ValueType> V;
3278   V.push_back(VT1);
3279   V.push_back(VT2);
3280   VTList.push_front(V);
3281   return makeVTList(&(*VTList.begin())[0], 2);
3282 }
3283 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
3284                                  MVT::ValueType VT3) {
3285   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
3286        E = VTList.end(); I != E; ++I) {
3287     if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3288         (*I)[2] == VT3)
3289       return makeVTList(&(*I)[0], 3);
3290   }
3291   std::vector<MVT::ValueType> V;
3292   V.push_back(VT1);
3293   V.push_back(VT2);
3294   V.push_back(VT3);
3295   VTList.push_front(V);
3296   return makeVTList(&(*VTList.begin())[0], 3);
3297 }
3298
3299 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
3300   switch (NumVTs) {
3301     case 0: assert(0 && "Cannot have nodes without results!");
3302     case 1: return getVTList(VTs[0]);
3303     case 2: return getVTList(VTs[0], VTs[1]);
3304     case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3305     default: break;
3306   }
3307
3308   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
3309        E = VTList.end(); I != E; ++I) {
3310     if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3311    
3312     bool NoMatch = false;
3313     for (unsigned i = 2; i != NumVTs; ++i)
3314       if (VTs[i] != (*I)[i]) {
3315         NoMatch = true;
3316         break;
3317       }
3318     if (!NoMatch)
3319       return makeVTList(&*I->begin(), NumVTs);
3320   }
3321   
3322   VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
3323   return makeVTList(&*VTList.begin()->begin(), NumVTs);
3324 }
3325
3326
3327 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3328 /// specified operands.  If the resultant node already exists in the DAG,
3329 /// this does not modify the specified node, instead it returns the node that
3330 /// already exists.  If the resultant node does not exist in the DAG, the
3331 /// input node is returned.  As a degenerate case, if you specify the same
3332 /// input operands as the node already has, the input node is returned.
3333 SDOperand SelectionDAG::
3334 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3335   SDNode *N = InN.Val;
3336   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3337   
3338   // Check to see if there is no change.
3339   if (Op == N->getOperand(0)) return InN;
3340   
3341   // See if the modified node already exists.
3342   void *InsertPos = 0;
3343   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3344     return SDOperand(Existing, InN.ResNo);
3345   
3346   // Nope it doesn't.  Remove the node from it's current place in the maps.
3347   if (InsertPos)
3348     RemoveNodeFromCSEMaps(N);
3349   
3350   // Now we update the operands.
3351   N->OperandList[0].getVal()->removeUser(0, N);
3352   N->OperandList[0] = Op;
3353   N->OperandList[0].setUser(N);
3354   Op.Val->addUser(0, N);
3355   
3356   // If this gets put into a CSE map, add it.
3357   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3358   return InN;
3359 }
3360
3361 SDOperand SelectionDAG::
3362 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3363   SDNode *N = InN.Val;
3364   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3365   
3366   // Check to see if there is no change.
3367   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3368     return InN;   // No operands changed, just return the input node.
3369   
3370   // See if the modified node already exists.
3371   void *InsertPos = 0;
3372   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3373     return SDOperand(Existing, InN.ResNo);
3374   
3375   // Nope it doesn't.  Remove the node from it's current place in the maps.
3376   if (InsertPos)
3377     RemoveNodeFromCSEMaps(N);
3378   
3379   // Now we update the operands.
3380   if (N->OperandList[0] != Op1) {
3381     N->OperandList[0].getVal()->removeUser(0, N);
3382     N->OperandList[0] = Op1;
3383     N->OperandList[0].setUser(N);
3384     Op1.Val->addUser(0, N);
3385   }
3386   if (N->OperandList[1] != Op2) {
3387     N->OperandList[1].getVal()->removeUser(1, N);
3388     N->OperandList[1] = Op2;
3389     N->OperandList[1].setUser(N);
3390     Op2.Val->addUser(1, N);
3391   }
3392   
3393   // If this gets put into a CSE map, add it.
3394   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3395   return InN;
3396 }
3397
3398 SDOperand SelectionDAG::
3399 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3400   SDOperand Ops[] = { Op1, Op2, Op3 };
3401   return UpdateNodeOperands(N, Ops, 3);
3402 }
3403
3404 SDOperand SelectionDAG::
3405 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, 
3406                    SDOperand Op3, SDOperand Op4) {
3407   SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3408   return UpdateNodeOperands(N, Ops, 4);
3409 }
3410
3411 SDOperand SelectionDAG::
3412 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3413                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3414   SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3415   return UpdateNodeOperands(N, Ops, 5);
3416 }
3417
3418 SDOperand SelectionDAG::
3419 UpdateNodeOperands(SDOperand InN, SDOperandPtr Ops, unsigned NumOps) {
3420   SDNode *N = InN.Val;
3421   assert(N->getNumOperands() == NumOps &&
3422          "Update with wrong number of operands");
3423   
3424   // Check to see if there is no change.
3425   bool AnyChange = false;
3426   for (unsigned i = 0; i != NumOps; ++i) {
3427     if (Ops[i] != N->getOperand(i)) {
3428       AnyChange = true;
3429       break;
3430     }
3431   }
3432   
3433   // No operands changed, just return the input node.
3434   if (!AnyChange) return InN;
3435   
3436   // See if the modified node already exists.
3437   void *InsertPos = 0;
3438   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3439     return SDOperand(Existing, InN.ResNo);
3440   
3441   // Nope it doesn't.  Remove the node from its current place in the maps.
3442   if (InsertPos)
3443     RemoveNodeFromCSEMaps(N);
3444   
3445   // Now we update the operands.
3446   for (unsigned i = 0; i != NumOps; ++i) {
3447     if (N->OperandList[i] != Ops[i]) {
3448       N->OperandList[i].getVal()->removeUser(i, N);
3449       N->OperandList[i] = Ops[i];
3450       N->OperandList[i].setUser(N);
3451       Ops[i].Val->addUser(i, N);
3452     }
3453   }
3454
3455   // If this gets put into a CSE map, add it.
3456   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3457   return InN;
3458 }
3459
3460 /// MorphNodeTo - This frees the operands of the current node, resets the
3461 /// opcode, types, and operands to the specified value.  This should only be
3462 /// used by the SelectionDAG class.
3463 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3464                          SDOperandPtr Ops, unsigned NumOps) {
3465   NodeType = Opc;
3466   ValueList = L.VTs;
3467   NumValues = L.NumVTs;
3468   
3469   // Clear the operands list, updating used nodes to remove this from their
3470   // use list.
3471   for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3472     I->getVal()->removeUser(std::distance(op_begin(), I), this);
3473   
3474   // If NumOps is larger than the # of operands we currently have, reallocate
3475   // the operand list.
3476   if (NumOps > NumOperands) {
3477     if (OperandsNeedDelete) {
3478       delete [] OperandList;
3479     }
3480     OperandList = new SDUse[NumOps];
3481     OperandsNeedDelete = true;
3482   }
3483   
3484   // Assign the new operands.
3485   NumOperands = NumOps;
3486   
3487   for (unsigned i = 0, e = NumOps; i != e; ++i) {
3488     OperandList[i] = Ops[i];
3489     OperandList[i].setUser(this);
3490     SDNode *N = OperandList[i].getVal();
3491     N->addUser(i, this);
3492     ++N->UsesSize;
3493   }
3494 }
3495
3496 /// SelectNodeTo - These are used for target selectors to *mutate* the
3497 /// specified node to have the specified return type, Target opcode, and
3498 /// operands.  Note that target opcodes are stored as
3499 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3500 ///
3501 /// Note that SelectNodeTo returns the resultant node.  If there is already a
3502 /// node of the specified opcode and operands, it returns that node instead of
3503 /// the current one.
3504 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3505                                    MVT::ValueType VT) {
3506   SDVTList VTs = getVTList(VT);
3507   FoldingSetNodeID ID;
3508   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, (SDOperand*)0, 0);
3509   void *IP = 0;
3510   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3511     return ON;
3512    
3513   RemoveNodeFromCSEMaps(N);
3514   
3515   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, SDOperandPtr(), 0);
3516
3517   CSEMap.InsertNode(N, IP);
3518   return N;
3519 }
3520
3521 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3522                                    MVT::ValueType VT, SDOperand Op1) {
3523   // If an identical node already exists, use it.
3524   SDVTList VTs = getVTList(VT);
3525   SDOperand Ops[] = { Op1 };
3526   
3527   FoldingSetNodeID ID;
3528   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3529   void *IP = 0;
3530   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3531     return ON;
3532                                        
3533   RemoveNodeFromCSEMaps(N);
3534   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3535   CSEMap.InsertNode(N, IP);
3536   return N;
3537 }
3538
3539 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3540                                    MVT::ValueType VT, SDOperand Op1,
3541                                    SDOperand Op2) {
3542   // If an identical node already exists, use it.
3543   SDVTList VTs = getVTList(VT);
3544   SDOperand Ops[] = { Op1, Op2 };
3545   
3546   FoldingSetNodeID ID;
3547   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3548   void *IP = 0;
3549   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3550     return ON;
3551                                        
3552   RemoveNodeFromCSEMaps(N);
3553   
3554   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3555   
3556   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3557   return N;
3558 }
3559
3560 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3561                                    MVT::ValueType VT, SDOperand Op1,
3562                                    SDOperand Op2, SDOperand Op3) {
3563   // If an identical node already exists, use it.
3564   SDVTList VTs = getVTList(VT);
3565   SDOperand Ops[] = { Op1, Op2, Op3 };
3566   FoldingSetNodeID ID;
3567   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3568   void *IP = 0;
3569   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3570     return ON;
3571                                        
3572   RemoveNodeFromCSEMaps(N);
3573   
3574   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3575
3576   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3577   return N;
3578 }
3579
3580 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3581                                    MVT::ValueType VT, SDOperandPtr Ops,
3582                                    unsigned NumOps) {
3583   // If an identical node already exists, use it.
3584   SDVTList VTs = getVTList(VT);
3585   FoldingSetNodeID ID;
3586   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3587   void *IP = 0;
3588   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3589     return ON;
3590                                        
3591   RemoveNodeFromCSEMaps(N);
3592   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3593   
3594   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3595   return N;
3596 }
3597
3598 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
3599                                    MVT::ValueType VT1, MVT::ValueType VT2,
3600                                    SDOperand Op1, SDOperand Op2) {
3601   SDVTList VTs = getVTList(VT1, VT2);
3602   FoldingSetNodeID ID;
3603   SDOperand Ops[] = { Op1, Op2 };
3604   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3605   void *IP = 0;
3606   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3607     return ON;
3608
3609   RemoveNodeFromCSEMaps(N);
3610   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3611   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3612   return N;
3613 }
3614
3615 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3616                                    MVT::ValueType VT1, MVT::ValueType VT2,
3617                                    SDOperand Op1, SDOperand Op2, 
3618                                    SDOperand Op3) {
3619   // If an identical node already exists, use it.
3620   SDVTList VTs = getVTList(VT1, VT2);
3621   SDOperand Ops[] = { Op1, Op2, Op3 };
3622   FoldingSetNodeID ID;
3623   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3624   void *IP = 0;
3625   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3626     return ON;
3627
3628   RemoveNodeFromCSEMaps(N);
3629
3630   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3631   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3632   return N;
3633 }
3634
3635
3636 /// getTargetNode - These are used for target selectors to create a new node
3637 /// with specified return type(s), target opcode, and operands.
3638 ///
3639 /// Note that getTargetNode returns the resultant node.  If there is already a
3640 /// node of the specified opcode and operands, it returns that node instead of
3641 /// the current one.
3642 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
3643   return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3644 }
3645 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3646                                     SDOperand Op1) {
3647   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3648 }
3649 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3650                                     SDOperand Op1, SDOperand Op2) {
3651   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3652 }
3653 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3654                                     SDOperand Op1, SDOperand Op2,
3655                                     SDOperand Op3) {
3656   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3657 }
3658 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3659                                     SDOperandPtr Ops, unsigned NumOps) {
3660   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3661 }
3662 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3663                                     MVT::ValueType VT2) {
3664   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3665   SDOperand Op;
3666   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3667 }
3668 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3669                                     MVT::ValueType VT2, SDOperand Op1) {
3670   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3671   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3672 }
3673 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3674                                     MVT::ValueType VT2, SDOperand Op1,
3675                                     SDOperand Op2) {
3676   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3677   SDOperand Ops[] = { Op1, Op2 };
3678   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3679 }
3680 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3681                                     MVT::ValueType VT2, SDOperand Op1,
3682                                     SDOperand Op2, SDOperand Op3) {
3683   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3684   SDOperand Ops[] = { Op1, Op2, Op3 };
3685   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3686 }
3687 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
3688                                     MVT::ValueType VT2,
3689                                     SDOperandPtr Ops, unsigned NumOps) {
3690   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3691   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3692 }
3693 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3694                                     MVT::ValueType VT2, MVT::ValueType VT3,
3695                                     SDOperand Op1, SDOperand Op2) {
3696   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3697   SDOperand Ops[] = { Op1, Op2 };
3698   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3699 }
3700 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3701                                     MVT::ValueType VT2, MVT::ValueType VT3,
3702                                     SDOperand Op1, SDOperand Op2,
3703                                     SDOperand Op3) {
3704   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3705   SDOperand Ops[] = { Op1, Op2, Op3 };
3706   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3707 }
3708 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
3709                                     MVT::ValueType VT2, MVT::ValueType VT3,
3710                                     SDOperandPtr Ops, unsigned NumOps) {
3711   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3712   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3713 }
3714 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
3715                                     MVT::ValueType VT2, MVT::ValueType VT3,
3716                                     MVT::ValueType VT4,
3717                                     SDOperandPtr Ops, unsigned NumOps) {
3718   std::vector<MVT::ValueType> VTList;
3719   VTList.push_back(VT1);
3720   VTList.push_back(VT2);
3721   VTList.push_back(VT3);
3722   VTList.push_back(VT4);
3723   const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3724   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3725 }
3726 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3727                                     std::vector<MVT::ValueType> &ResultTys,
3728                                     SDOperandPtr Ops, unsigned NumOps) {
3729   const MVT::ValueType *VTs = getNodeValueTypes(ResultTys);
3730   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3731                  Ops, NumOps).Val;
3732 }
3733
3734 /// getNodeIfExists - Get the specified node if it's already available, or
3735 /// else return NULL.
3736 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3737                                       SDOperandPtr Ops, unsigned NumOps) {
3738   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3739     FoldingSetNodeID ID;
3740     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3741     void *IP = 0;
3742     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3743       return E;
3744   }
3745   return NULL;
3746 }
3747
3748
3749 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3750 /// This can cause recursive merging of nodes in the DAG.
3751 ///
3752 /// This version assumes From has a single result value.
3753 ///
3754 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3755                                       DAGUpdateListener *UpdateListener) {
3756   SDNode *From = FromN.Val;
3757   assert(From->getNumValues() == 1 && FromN.ResNo == 0 && 
3758          "Cannot replace with this method!");
3759   assert(From != To.Val && "Cannot replace uses of with self");
3760
3761   while (!From->use_empty()) {
3762     SDNode::use_iterator UI = From->use_begin();
3763     SDNode *U = UI->getUser();
3764
3765     // This node is about to morph, remove its old self from the CSE maps.
3766     RemoveNodeFromCSEMaps(U);
3767     int operandNum = 0;
3768     for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3769          I != E; ++I, ++operandNum)
3770       if (I->getVal() == From) {
3771         From->removeUser(operandNum, U);
3772         *I = To;
3773         I->setUser(U);
3774         To.Val->addUser(operandNum, U);
3775       }    
3776
3777     // Now that we have modified U, add it back to the CSE maps.  If it already
3778     // exists there, recursively merge the results together.
3779     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3780       ReplaceAllUsesWith(U, Existing, UpdateListener);
3781       // U is now dead.  Inform the listener if it exists and delete it.
3782       if (UpdateListener) 
3783         UpdateListener->NodeDeleted(U);
3784       DeleteNodeNotInCSEMaps(U);
3785     } else {
3786       // If the node doesn't already exist, we updated it.  Inform a listener if
3787       // it exists.
3788       if (UpdateListener) 
3789         UpdateListener->NodeUpdated(U);
3790     }
3791   }
3792 }
3793
3794 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3795 /// This can cause recursive merging of nodes in the DAG.
3796 ///
3797 /// This version assumes From/To have matching types and numbers of result
3798 /// values.
3799 ///
3800 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3801                                       DAGUpdateListener *UpdateListener) {
3802   assert(From != To && "Cannot replace uses of with self");
3803   assert(From->getNumValues() == To->getNumValues() &&
3804          "Cannot use this version of ReplaceAllUsesWith!");
3805   if (From->getNumValues() == 1)   // If possible, use the faster version.
3806     return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3807                               UpdateListener);
3808   
3809   while (!From->use_empty()) {
3810     SDNode::use_iterator UI = From->use_begin();
3811     SDNode *U = UI->getUser();
3812
3813     // This node is about to morph, remove its old self from the CSE maps.
3814     RemoveNodeFromCSEMaps(U);
3815     int operandNum = 0;
3816     for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3817          I != E; ++I, ++operandNum)
3818       if (I->getVal() == From) {
3819         From->removeUser(operandNum, U);
3820         I->getVal() = To;
3821         To->addUser(operandNum, U);
3822       }
3823
3824     // Now that we have modified U, add it back to the CSE maps.  If it already
3825     // exists there, recursively merge the results together.
3826     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3827       ReplaceAllUsesWith(U, Existing, UpdateListener);
3828       // U is now dead.  Inform the listener if it exists and delete it.
3829       if (UpdateListener) 
3830         UpdateListener->NodeDeleted(U);
3831       DeleteNodeNotInCSEMaps(U);
3832     } else {
3833       // If the node doesn't already exist, we updated it.  Inform a listener if
3834       // it exists.
3835       if (UpdateListener) 
3836         UpdateListener->NodeUpdated(U);
3837     }
3838   }
3839 }
3840
3841 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3842 /// This can cause recursive merging of nodes in the DAG.
3843 ///
3844 /// This version can replace From with any result values.  To must match the
3845 /// number and types of values returned by From.
3846 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3847                                       SDOperandPtr To,
3848                                       DAGUpdateListener *UpdateListener) {
3849   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
3850     return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
3851
3852   while (!From->use_empty()) {
3853     SDNode::use_iterator UI = From->use_begin();
3854     SDNode *U = UI->getUser();
3855
3856     // This node is about to morph, remove its old self from the CSE maps.
3857     RemoveNodeFromCSEMaps(U);
3858     int operandNum = 0;
3859     for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3860          I != E; ++I, ++operandNum)
3861       if (I->getVal() == From) {
3862         const SDOperand &ToOp = To[I->getSDOperand().ResNo];
3863         From->removeUser(operandNum, U);
3864         *I = ToOp;
3865         I->setUser(U);
3866         ToOp.Val->addUser(operandNum, U);
3867       }
3868
3869     // Now that we have modified U, add it back to the CSE maps.  If it already
3870     // exists there, recursively merge the results together.
3871     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3872       ReplaceAllUsesWith(U, Existing, UpdateListener);
3873       // U is now dead.  Inform the listener if it exists and delete it.
3874       if (UpdateListener) 
3875         UpdateListener->NodeDeleted(U);
3876       DeleteNodeNotInCSEMaps(U);
3877     } else {
3878       // If the node doesn't already exist, we updated it.  Inform a listener if
3879       // it exists.
3880       if (UpdateListener) 
3881         UpdateListener->NodeUpdated(U);
3882     }
3883   }
3884 }
3885
3886 namespace {
3887   /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
3888   /// any deleted nodes from the set passed into its constructor and recursively
3889   /// notifies another update listener if specified.
3890   class ChainedSetUpdaterListener : 
3891   public SelectionDAG::DAGUpdateListener {
3892     SmallSetVector<SDNode*, 16> &Set;
3893     SelectionDAG::DAGUpdateListener *Chain;
3894   public:
3895     ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
3896                               SelectionDAG::DAGUpdateListener *chain)
3897       : Set(set), Chain(chain) {}
3898  
3899     virtual void NodeDeleted(SDNode *N) {
3900       Set.remove(N);
3901       if (Chain) Chain->NodeDeleted(N);
3902     }
3903     virtual void NodeUpdated(SDNode *N) {
3904       if (Chain) Chain->NodeUpdated(N);
3905     }
3906   };
3907 }
3908
3909 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3910 /// uses of other values produced by From.Val alone.  The Deleted vector is
3911 /// handled the same way as for ReplaceAllUsesWith.
3912 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3913                                              DAGUpdateListener *UpdateListener){
3914   assert(From != To && "Cannot replace a value with itself");
3915   
3916   // Handle the simple, trivial, case efficiently.
3917   if (From.Val->getNumValues() == 1) {
3918     ReplaceAllUsesWith(From, To, UpdateListener);
3919     return;
3920   }
3921
3922   if (From.use_empty()) return;
3923
3924   // Get all of the users of From.Val.  We want these in a nice,
3925   // deterministically ordered and uniqued set, so we use a SmallSetVector.
3926   SmallSetVector<SDNode*, 16> Users;
3927   for (SDNode::use_iterator UI = From.Val->use_begin(), 
3928       E = From.Val->use_end(); UI != E; ++UI) {
3929     SDNode *User = UI->getUser();
3930     if (!Users.count(User))
3931       Users.insert(User);
3932   }
3933
3934   // When one of the recursive merges deletes nodes from the graph, we need to
3935   // make sure that UpdateListener is notified *and* that the node is removed
3936   // from Users if present.  CSUL does this.
3937   ChainedSetUpdaterListener CSUL(Users, UpdateListener);
3938   
3939   while (!Users.empty()) {
3940     // We know that this user uses some value of From.  If it is the right
3941     // value, update it.
3942     SDNode *User = Users.back();
3943     Users.pop_back();
3944     
3945     // Scan for an operand that matches From.
3946     SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
3947     for (; Op != E; ++Op)
3948       if (*Op == From) break;
3949     
3950     // If there are no matches, the user must use some other result of From.
3951     if (Op == E) continue;
3952       
3953     // Okay, we know this user needs to be updated.  Remove its old self
3954     // from the CSE maps.
3955     RemoveNodeFromCSEMaps(User);
3956     
3957     // Update all operands that match "From" in case there are multiple uses.
3958     for (; Op != E; ++Op) {
3959       if (*Op == From) {
3960         From.Val->removeUser(Op-User->op_begin(), User);
3961         *Op = To;
3962         Op->setUser(User);
3963         To.Val->addUser(Op-User->op_begin(), User);
3964       }
3965     }
3966                
3967     // Now that we have modified User, add it back to the CSE maps.  If it
3968     // already exists there, recursively merge the results together.
3969     SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
3970     if (!Existing) {
3971       if (UpdateListener) UpdateListener->NodeUpdated(User);
3972       continue;  // Continue on to next user.
3973     }
3974     
3975     // If there was already an existing matching node, use ReplaceAllUsesWith
3976     // to replace the dead one with the existing one.  This can cause
3977     // recursive merging of other unrelated nodes down the line.  The merging
3978     // can cause deletion of nodes that used the old value.  To handle this, we
3979     // use CSUL to remove them from the Users set.
3980     ReplaceAllUsesWith(User, Existing, &CSUL);
3981     
3982     // User is now dead.  Notify a listener if present.
3983     if (UpdateListener) UpdateListener->NodeDeleted(User);
3984     DeleteNodeNotInCSEMaps(User);
3985   }
3986 }
3987
3988 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3989 /// their allnodes order. It returns the maximum id.
3990 unsigned SelectionDAG::AssignNodeIds() {
3991   unsigned Id = 0;
3992   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3993     SDNode *N = I;
3994     N->setNodeId(Id++);
3995   }
3996   return Id;
3997 }
3998
3999 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4000 /// based on their topological order. It returns the maximum id and a vector
4001 /// of the SDNodes* in assigned order by reference.
4002 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4003   unsigned DAGSize = AllNodes.size();
4004   std::vector<unsigned> InDegree(DAGSize);
4005   std::vector<SDNode*> Sources;
4006
4007   // Use a two pass approach to avoid using a std::map which is slow.
4008   unsigned Id = 0;
4009   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4010     SDNode *N = I;
4011     N->setNodeId(Id++);
4012     unsigned Degree = N->use_size();
4013     InDegree[N->getNodeId()] = Degree;
4014     if (Degree == 0)
4015       Sources.push_back(N);
4016   }
4017
4018   TopOrder.clear();
4019   while (!Sources.empty()) {
4020     SDNode *N = Sources.back();
4021     Sources.pop_back();
4022     TopOrder.push_back(N);
4023     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4024       SDNode *P = I->getVal();
4025       unsigned Degree = --InDegree[P->getNodeId()];
4026       if (Degree == 0)
4027         Sources.push_back(P);
4028     }
4029   }
4030
4031   // Second pass, assign the actual topological order as node ids.
4032   Id = 0;
4033   for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4034        TI != TE; ++TI)
4035     (*TI)->setNodeId(Id++);
4036
4037   return Id;
4038 }
4039
4040
4041
4042 //===----------------------------------------------------------------------===//
4043 //                              SDNode Class
4044 //===----------------------------------------------------------------------===//
4045
4046 // Out-of-line virtual method to give class a home.
4047 void SDNode::ANCHOR() {}
4048 void UnarySDNode::ANCHOR() {}
4049 void BinarySDNode::ANCHOR() {}
4050 void TernarySDNode::ANCHOR() {}
4051 void HandleSDNode::ANCHOR() {}
4052 void StringSDNode::ANCHOR() {}
4053 void ConstantSDNode::ANCHOR() {}
4054 void ConstantFPSDNode::ANCHOR() {}
4055 void GlobalAddressSDNode::ANCHOR() {}
4056 void FrameIndexSDNode::ANCHOR() {}
4057 void JumpTableSDNode::ANCHOR() {}
4058 void ConstantPoolSDNode::ANCHOR() {}
4059 void BasicBlockSDNode::ANCHOR() {}
4060 void SrcValueSDNode::ANCHOR() {}
4061 void MemOperandSDNode::ANCHOR() {}
4062 void RegisterSDNode::ANCHOR() {}
4063 void ExternalSymbolSDNode::ANCHOR() {}
4064 void CondCodeSDNode::ANCHOR() {}
4065 void ARG_FLAGSSDNode::ANCHOR() {}
4066 void VTSDNode::ANCHOR() {}
4067 void LoadSDNode::ANCHOR() {}
4068 void StoreSDNode::ANCHOR() {}
4069 void AtomicSDNode::ANCHOR() {}
4070
4071 HandleSDNode::~HandleSDNode() {
4072   SDVTList VTs = { 0, 0 };
4073   MorphNodeTo(ISD::HANDLENODE, VTs, SDOperandPtr(), 0);  // Drops operand uses.
4074 }
4075
4076 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4077                                          MVT::ValueType VT, int o)
4078   : SDNode(isa<GlobalVariable>(GA) &&
4079            cast<GlobalVariable>(GA)->isThreadLocal() ?
4080            // Thread Local
4081            (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4082            // Non Thread Local
4083            (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4084            getSDVTList(VT)), Offset(o) {
4085   TheGlobal = const_cast<GlobalValue*>(GA);
4086 }
4087
4088 /// getMemOperand - Return a MachineMemOperand object describing the memory
4089 /// reference performed by this load or store.
4090 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4091   int Size = (MVT::getSizeInBits(getMemoryVT()) + 7) >> 3;
4092   int Flags =
4093     getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4094                                MachineMemOperand::MOStore;
4095   if (IsVolatile) Flags |= MachineMemOperand::MOVolatile;
4096
4097   // Check if the load references a frame index, and does not have
4098   // an SV attached.
4099   const FrameIndexSDNode *FI =
4100     dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4101   if (!getSrcValue() && FI)
4102     return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4103                              FI->getIndex(), Size, Alignment);
4104   else
4105     return MachineMemOperand(getSrcValue(), Flags,
4106                              getSrcValueOffset(), Size, Alignment);
4107 }
4108
4109 /// Profile - Gather unique data for the node.
4110 ///
4111 void SDNode::Profile(FoldingSetNodeID &ID) {
4112   AddNodeIDNode(ID, this);
4113 }
4114
4115 /// getValueTypeList - Return a pointer to the specified value type.
4116 ///
4117 const MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
4118   if (MVT::isExtendedVT(VT)) {
4119     static std::set<MVT::ValueType> EVTs;
4120     return &(*EVTs.insert(VT).first);
4121   } else {
4122     static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
4123     VTs[VT] = VT;
4124     return &VTs[VT];
4125   }
4126 }
4127
4128 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4129 /// indicated value.  This method ignores uses of other values defined by this
4130 /// operation.
4131 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4132   assert(Value < getNumValues() && "Bad value!");
4133
4134   // If there is only one value, this is easy.
4135   if (getNumValues() == 1)
4136     return use_size() == NUses;
4137   if (use_size() < NUses) return false;
4138
4139   SDOperand TheValue(const_cast<SDNode *>(this), Value);
4140
4141   SmallPtrSet<SDNode*, 32> UsersHandled;
4142
4143   // TODO: Only iterate over uses of a given value of the node
4144   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4145     if (*UI == TheValue) {
4146       if (NUses == 0)
4147         return false;
4148       --NUses;
4149     }
4150   }
4151
4152   // Found exactly the right number of uses?
4153   return NUses == 0;
4154 }
4155
4156
4157 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4158 /// value. This method ignores uses of other values defined by this operation.
4159 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4160   assert(Value < getNumValues() && "Bad value!");
4161
4162   if (use_empty()) return false;
4163
4164   SDOperand TheValue(const_cast<SDNode *>(this), Value);
4165
4166   SmallPtrSet<SDNode*, 32> UsersHandled;
4167
4168   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4169     SDNode *User = UI->getUser();
4170     if (User->getNumOperands() == 1 ||
4171         UsersHandled.insert(User))     // First time we've seen this?
4172       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4173         if (User->getOperand(i) == TheValue) {
4174           return true;
4175         }
4176   }
4177
4178   return false;
4179 }
4180
4181
4182 /// isOnlyUseOf - Return true if this node is the only use of N.
4183 ///
4184 bool SDNode::isOnlyUseOf(SDNode *N) const {
4185   bool Seen = false;
4186   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4187     SDNode *User = I->getUser();
4188     if (User == this)
4189       Seen = true;
4190     else
4191       return false;
4192   }
4193
4194   return Seen;
4195 }
4196
4197 /// isOperand - Return true if this node is an operand of N.
4198 ///
4199 bool SDOperand::isOperandOf(SDNode *N) const {
4200   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4201     if (*this == N->getOperand(i))
4202       return true;
4203   return false;
4204 }
4205
4206 bool SDNode::isOperandOf(SDNode *N) const {
4207   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4208     if (this == N->OperandList[i].getVal())
4209       return true;
4210   return false;
4211 }
4212
4213 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4214 /// be a chain) reaches the specified operand without crossing any 
4215 /// side-effecting instructions.  In practice, this looks through token
4216 /// factors and non-volatile loads.  In order to remain efficient, this only
4217 /// looks a couple of nodes in, it does not do an exhaustive search.
4218 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest, 
4219                                                unsigned Depth) const {
4220   if (*this == Dest) return true;
4221   
4222   // Don't search too deeply, we just want to be able to see through
4223   // TokenFactor's etc.
4224   if (Depth == 0) return false;
4225   
4226   // If this is a token factor, all inputs to the TF happen in parallel.  If any
4227   // of the operands of the TF reach dest, then we can do the xform.
4228   if (getOpcode() == ISD::TokenFactor) {
4229     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4230       if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4231         return true;
4232     return false;
4233   }
4234   
4235   // Loads don't have side effects, look through them.
4236   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4237     if (!Ld->isVolatile())
4238       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4239   }
4240   return false;
4241 }
4242
4243
4244 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4245                             SmallPtrSet<SDNode *, 32> &Visited) {
4246   if (found || !Visited.insert(N))
4247     return;
4248
4249   for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4250     SDNode *Op = N->getOperand(i).Val;
4251     if (Op == P) {
4252       found = true;
4253       return;
4254     }
4255     findPredecessor(Op, P, found, Visited);
4256   }
4257 }
4258
4259 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4260 /// is either an operand of N or it can be reached by recursively traversing
4261 /// up the operands.
4262 /// NOTE: this is an expensive method. Use it carefully.
4263 bool SDNode::isPredecessorOf(SDNode *N) const {
4264   SmallPtrSet<SDNode *, 32> Visited;
4265   bool found = false;
4266   findPredecessor(N, this, found, Visited);
4267   return found;
4268 }
4269
4270 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4271   assert(Num < NumOperands && "Invalid child # of SDNode!");
4272   return cast<ConstantSDNode>(OperandList[Num])->getValue();
4273 }
4274
4275 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4276   switch (getOpcode()) {
4277   default:
4278     if (getOpcode() < ISD::BUILTIN_OP_END)
4279       return "<<Unknown DAG Node>>";
4280     else {
4281       if (G) {
4282         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4283           if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4284             return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4285
4286         TargetLowering &TLI = G->getTargetLoweringInfo();
4287         const char *Name =
4288           TLI.getTargetNodeName(getOpcode());
4289         if (Name) return Name;
4290       }
4291
4292       return "<<Unknown Target Node>>";
4293     }
4294    
4295   case ISD::PREFETCH:      return "Prefetch";
4296   case ISD::MEMBARRIER:    return "MemBarrier";
4297   case ISD::ATOMIC_LCS:    return "AtomicLCS";
4298   case ISD::ATOMIC_LAS:    return "AtomicLAS";
4299   case ISD::ATOMIC_LSS:    return "AtomicLSS";
4300   case ISD::ATOMIC_LOAD_AND:  return "AtomicLoadAnd";
4301   case ISD::ATOMIC_LOAD_OR:   return "AtomicLoadOr";
4302   case ISD::ATOMIC_LOAD_XOR:  return "AtomicLoadXor";
4303   case ISD::ATOMIC_LOAD_MIN:  return "AtomicLoadMin";
4304   case ISD::ATOMIC_LOAD_MAX:  return "AtomicLoadMax";
4305   case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4306   case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4307   case ISD::ATOMIC_SWAP:   return "AtomicSWAP";
4308   case ISD::PCMARKER:      return "PCMarker";
4309   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4310   case ISD::SRCVALUE:      return "SrcValue";
4311   case ISD::MEMOPERAND:    return "MemOperand";
4312   case ISD::EntryToken:    return "EntryToken";
4313   case ISD::TokenFactor:   return "TokenFactor";
4314   case ISD::AssertSext:    return "AssertSext";
4315   case ISD::AssertZext:    return "AssertZext";
4316
4317   case ISD::STRING:        return "String";
4318   case ISD::BasicBlock:    return "BasicBlock";
4319   case ISD::ARG_FLAGS:     return "ArgFlags";
4320   case ISD::VALUETYPE:     return "ValueType";
4321   case ISD::Register:      return "Register";
4322
4323   case ISD::Constant:      return "Constant";
4324   case ISD::ConstantFP:    return "ConstantFP";
4325   case ISD::GlobalAddress: return "GlobalAddress";
4326   case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4327   case ISD::FrameIndex:    return "FrameIndex";
4328   case ISD::JumpTable:     return "JumpTable";
4329   case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4330   case ISD::RETURNADDR: return "RETURNADDR";
4331   case ISD::FRAMEADDR: return "FRAMEADDR";
4332   case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4333   case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4334   case ISD::EHSELECTION: return "EHSELECTION";
4335   case ISD::EH_RETURN: return "EH_RETURN";
4336   case ISD::ConstantPool:  return "ConstantPool";
4337   case ISD::ExternalSymbol: return "ExternalSymbol";
4338   case ISD::INTRINSIC_WO_CHAIN: {
4339     unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4340     return Intrinsic::getName((Intrinsic::ID)IID);
4341   }
4342   case ISD::INTRINSIC_VOID:
4343   case ISD::INTRINSIC_W_CHAIN: {
4344     unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4345     return Intrinsic::getName((Intrinsic::ID)IID);
4346   }
4347
4348   case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
4349   case ISD::TargetConstant: return "TargetConstant";
4350   case ISD::TargetConstantFP:return "TargetConstantFP";
4351   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4352   case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4353   case ISD::TargetFrameIndex: return "TargetFrameIndex";
4354   case ISD::TargetJumpTable:  return "TargetJumpTable";
4355   case ISD::TargetConstantPool:  return "TargetConstantPool";
4356   case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4357
4358   case ISD::CopyToReg:     return "CopyToReg";
4359   case ISD::CopyFromReg:   return "CopyFromReg";
4360   case ISD::UNDEF:         return "undef";
4361   case ISD::MERGE_VALUES:  return "merge_values";
4362   case ISD::INLINEASM:     return "inlineasm";
4363   case ISD::LABEL:         return "label";
4364   case ISD::DECLARE:       return "declare";
4365   case ISD::HANDLENODE:    return "handlenode";
4366   case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4367   case ISD::CALL:          return "call";
4368     
4369   // Unary operators
4370   case ISD::FABS:   return "fabs";
4371   case ISD::FNEG:   return "fneg";
4372   case ISD::FSQRT:  return "fsqrt";
4373   case ISD::FSIN:   return "fsin";
4374   case ISD::FCOS:   return "fcos";
4375   case ISD::FPOWI:  return "fpowi";
4376   case ISD::FPOW:   return "fpow";
4377
4378   // Binary operators
4379   case ISD::ADD:    return "add";
4380   case ISD::SUB:    return "sub";
4381   case ISD::MUL:    return "mul";
4382   case ISD::MULHU:  return "mulhu";
4383   case ISD::MULHS:  return "mulhs";
4384   case ISD::SDIV:   return "sdiv";
4385   case ISD::UDIV:   return "udiv";
4386   case ISD::SREM:   return "srem";
4387   case ISD::UREM:   return "urem";
4388   case ISD::SMUL_LOHI:  return "smul_lohi";
4389   case ISD::UMUL_LOHI:  return "umul_lohi";
4390   case ISD::SDIVREM:    return "sdivrem";
4391   case ISD::UDIVREM:    return "divrem";
4392   case ISD::AND:    return "and";
4393   case ISD::OR:     return "or";
4394   case ISD::XOR:    return "xor";
4395   case ISD::SHL:    return "shl";
4396   case ISD::SRA:    return "sra";
4397   case ISD::SRL:    return "srl";
4398   case ISD::ROTL:   return "rotl";
4399   case ISD::ROTR:   return "rotr";
4400   case ISD::FADD:   return "fadd";
4401   case ISD::FSUB:   return "fsub";
4402   case ISD::FMUL:   return "fmul";
4403   case ISD::FDIV:   return "fdiv";
4404   case ISD::FREM:   return "frem";
4405   case ISD::FCOPYSIGN: return "fcopysign";
4406   case ISD::FGETSIGN:  return "fgetsign";
4407
4408   case ISD::SETCC:       return "setcc";
4409   case ISD::VSETCC:      return "vsetcc";
4410   case ISD::SELECT:      return "select";
4411   case ISD::SELECT_CC:   return "select_cc";
4412   case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
4413   case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
4414   case ISD::CONCAT_VECTORS:      return "concat_vectors";
4415   case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
4416   case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
4417   case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
4418   case ISD::CARRY_FALSE:         return "carry_false";
4419   case ISD::ADDC:        return "addc";
4420   case ISD::ADDE:        return "adde";
4421   case ISD::SUBC:        return "subc";
4422   case ISD::SUBE:        return "sube";
4423   case ISD::SHL_PARTS:   return "shl_parts";
4424   case ISD::SRA_PARTS:   return "sra_parts";
4425   case ISD::SRL_PARTS:   return "srl_parts";
4426   
4427   case ISD::EXTRACT_SUBREG:     return "extract_subreg";
4428   case ISD::INSERT_SUBREG:      return "insert_subreg";
4429   
4430   // Conversion operators.
4431   case ISD::SIGN_EXTEND: return "sign_extend";
4432   case ISD::ZERO_EXTEND: return "zero_extend";
4433   case ISD::ANY_EXTEND:  return "any_extend";
4434   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4435   case ISD::TRUNCATE:    return "truncate";
4436   case ISD::FP_ROUND:    return "fp_round";
4437   case ISD::FLT_ROUNDS_: return "flt_rounds";
4438   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4439   case ISD::FP_EXTEND:   return "fp_extend";
4440
4441   case ISD::SINT_TO_FP:  return "sint_to_fp";
4442   case ISD::UINT_TO_FP:  return "uint_to_fp";
4443   case ISD::FP_TO_SINT:  return "fp_to_sint";
4444   case ISD::FP_TO_UINT:  return "fp_to_uint";
4445   case ISD::BIT_CONVERT: return "bit_convert";
4446
4447     // Control flow instructions
4448   case ISD::BR:      return "br";
4449   case ISD::BRIND:   return "brind";
4450   case ISD::BR_JT:   return "br_jt";
4451   case ISD::BRCOND:  return "brcond";
4452   case ISD::BR_CC:   return "br_cc";
4453   case ISD::RET:     return "ret";
4454   case ISD::CALLSEQ_START:  return "callseq_start";
4455   case ISD::CALLSEQ_END:    return "callseq_end";
4456
4457     // Other operators
4458   case ISD::LOAD:               return "load";
4459   case ISD::STORE:              return "store";
4460   case ISD::VAARG:              return "vaarg";
4461   case ISD::VACOPY:             return "vacopy";
4462   case ISD::VAEND:              return "vaend";
4463   case ISD::VASTART:            return "vastart";
4464   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4465   case ISD::EXTRACT_ELEMENT:    return "extract_element";
4466   case ISD::BUILD_PAIR:         return "build_pair";
4467   case ISD::STACKSAVE:          return "stacksave";
4468   case ISD::STACKRESTORE:       return "stackrestore";
4469   case ISD::TRAP:               return "trap";
4470
4471   // Bit manipulation
4472   case ISD::BSWAP:   return "bswap";
4473   case ISD::CTPOP:   return "ctpop";
4474   case ISD::CTTZ:    return "cttz";
4475   case ISD::CTLZ:    return "ctlz";
4476
4477   // Debug info
4478   case ISD::LOCATION: return "location";
4479   case ISD::DEBUG_LOC: return "debug_loc";
4480
4481   // Trampolines
4482   case ISD::TRAMPOLINE: return "trampoline";
4483
4484   case ISD::CONDCODE:
4485     switch (cast<CondCodeSDNode>(this)->get()) {
4486     default: assert(0 && "Unknown setcc condition!");
4487     case ISD::SETOEQ:  return "setoeq";
4488     case ISD::SETOGT:  return "setogt";
4489     case ISD::SETOGE:  return "setoge";
4490     case ISD::SETOLT:  return "setolt";
4491     case ISD::SETOLE:  return "setole";
4492     case ISD::SETONE:  return "setone";
4493
4494     case ISD::SETO:    return "seto";
4495     case ISD::SETUO:   return "setuo";
4496     case ISD::SETUEQ:  return "setue";
4497     case ISD::SETUGT:  return "setugt";
4498     case ISD::SETUGE:  return "setuge";
4499     case ISD::SETULT:  return "setult";
4500     case ISD::SETULE:  return "setule";
4501     case ISD::SETUNE:  return "setune";
4502
4503     case ISD::SETEQ:   return "seteq";
4504     case ISD::SETGT:   return "setgt";
4505     case ISD::SETGE:   return "setge";
4506     case ISD::SETLT:   return "setlt";
4507     case ISD::SETLE:   return "setle";
4508     case ISD::SETNE:   return "setne";
4509     }
4510   }
4511 }
4512
4513 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4514   switch (AM) {
4515   default:
4516     return "";
4517   case ISD::PRE_INC:
4518     return "<pre-inc>";
4519   case ISD::PRE_DEC:
4520     return "<pre-dec>";
4521   case ISD::POST_INC:
4522     return "<post-inc>";
4523   case ISD::POST_DEC:
4524     return "<post-dec>";
4525   }
4526 }
4527
4528 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4529   std::string S = "< ";
4530
4531   if (isZExt())
4532     S += "zext ";
4533   if (isSExt())
4534     S += "sext ";
4535   if (isInReg())
4536     S += "inreg ";
4537   if (isSRet())
4538     S += "sret ";
4539   if (isByVal())
4540     S += "byval ";
4541   if (isNest())
4542     S += "nest ";
4543   if (getByValAlign())
4544     S += "byval-align:" + utostr(getByValAlign()) + " ";
4545   if (getOrigAlign())
4546     S += "orig-align:" + utostr(getOrigAlign()) + " ";
4547   if (getByValSize())
4548     S += "byval-size:" + utostr(getByValSize()) + " ";
4549   return S + ">";
4550 }
4551
4552 void SDNode::dump() const { dump(0); }
4553 void SDNode::dump(const SelectionDAG *G) const {
4554   cerr << (void*)this << ": ";
4555
4556   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4557     if (i) cerr << ",";
4558     if (getValueType(i) == MVT::Other)
4559       cerr << "ch";
4560     else
4561       cerr << MVT::getValueTypeString(getValueType(i));
4562   }
4563   cerr << " = " << getOperationName(G);
4564
4565   cerr << " ";
4566   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4567     if (i) cerr << ", ";
4568     cerr << (void*)getOperand(i).Val;
4569     if (unsigned RN = getOperand(i).ResNo)
4570       cerr << ":" << RN;
4571   }
4572
4573   if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4574     SDNode *Mask = getOperand(2).Val;
4575     cerr << "<";
4576     for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4577       if (i) cerr << ",";
4578       if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4579         cerr << "u";
4580       else
4581         cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4582     }
4583     cerr << ">";
4584   }
4585
4586   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4587     cerr << "<" << CSDN->getValue() << ">";
4588   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4589     if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4590       cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4591     else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4592       cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4593     else {
4594       cerr << "<APFloat(";
4595       CSDN->getValueAPF().convertToAPInt().dump();
4596       cerr << ")>";
4597     }
4598   } else if (const GlobalAddressSDNode *GADN =
4599              dyn_cast<GlobalAddressSDNode>(this)) {
4600     int offset = GADN->getOffset();
4601     cerr << "<";
4602     WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4603     if (offset > 0)
4604       cerr << " + " << offset;
4605     else
4606       cerr << " " << offset;
4607   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4608     cerr << "<" << FIDN->getIndex() << ">";
4609   } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4610     cerr << "<" << JTDN->getIndex() << ">";
4611   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4612     int offset = CP->getOffset();
4613     if (CP->isMachineConstantPoolEntry())
4614       cerr << "<" << *CP->getMachineCPVal() << ">";
4615     else
4616       cerr << "<" << *CP->getConstVal() << ">";
4617     if (offset > 0)
4618       cerr << " + " << offset;
4619     else
4620       cerr << " " << offset;
4621   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4622     cerr << "<";
4623     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4624     if (LBB)
4625       cerr << LBB->getName() << " ";
4626     cerr << (const void*)BBDN->getBasicBlock() << ">";
4627   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4628     if (G && R->getReg() &&
4629         TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4630       cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4631     } else {
4632       cerr << " #" << R->getReg();
4633     }
4634   } else if (const ExternalSymbolSDNode *ES =
4635              dyn_cast<ExternalSymbolSDNode>(this)) {
4636     cerr << "'" << ES->getSymbol() << "'";
4637   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4638     if (M->getValue())
4639       cerr << "<" << M->getValue() << ">";
4640     else
4641       cerr << "<null>";
4642   } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4643     if (M->MO.getValue())
4644       cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4645     else
4646       cerr << "<null:" << M->MO.getOffset() << ">";
4647   } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4648     cerr << N->getArgFlags().getArgFlagsString();
4649   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4650     cerr << ":" << MVT::getValueTypeString(N->getVT());
4651   } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4652     const Value *SrcValue = LD->getSrcValue();
4653     int SrcOffset = LD->getSrcValueOffset();
4654     cerr << " <";
4655     if (SrcValue)
4656       cerr << SrcValue;
4657     else
4658       cerr << "null";
4659     cerr << ":" << SrcOffset << ">";
4660
4661     bool doExt = true;
4662     switch (LD->getExtensionType()) {
4663     default: doExt = false; break;
4664     case ISD::EXTLOAD:
4665       cerr << " <anyext ";
4666       break;
4667     case ISD::SEXTLOAD:
4668       cerr << " <sext ";
4669       break;
4670     case ISD::ZEXTLOAD:
4671       cerr << " <zext ";
4672       break;
4673     }
4674     if (doExt)
4675       cerr << MVT::getValueTypeString(LD->getMemoryVT()) << ">";
4676
4677     const char *AM = getIndexedModeName(LD->getAddressingMode());
4678     if (*AM)
4679       cerr << " " << AM;
4680     if (LD->isVolatile())
4681       cerr << " <volatile>";
4682     cerr << " alignment=" << LD->getAlignment();
4683   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4684     const Value *SrcValue = ST->getSrcValue();
4685     int SrcOffset = ST->getSrcValueOffset();
4686     cerr << " <";
4687     if (SrcValue)
4688       cerr << SrcValue;
4689     else
4690       cerr << "null";
4691     cerr << ":" << SrcOffset << ">";
4692
4693     if (ST->isTruncatingStore())
4694       cerr << " <trunc "
4695            << MVT::getValueTypeString(ST->getMemoryVT()) << ">";
4696
4697     const char *AM = getIndexedModeName(ST->getAddressingMode());
4698     if (*AM)
4699       cerr << " " << AM;
4700     if (ST->isVolatile())
4701       cerr << " <volatile>";
4702     cerr << " alignment=" << ST->getAlignment();
4703   }
4704 }
4705
4706 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4707   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4708     if (N->getOperand(i).Val->hasOneUse())
4709       DumpNodes(N->getOperand(i).Val, indent+2, G);
4710     else
4711       cerr << "\n" << std::string(indent+2, ' ')
4712            << (void*)N->getOperand(i).Val << ": <multiple use>";
4713
4714
4715   cerr << "\n" << std::string(indent, ' ');
4716   N->dump(G);
4717 }
4718
4719 void SelectionDAG::dump() const {
4720   cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4721   std::vector<const SDNode*> Nodes;
4722   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4723        I != E; ++I)
4724     Nodes.push_back(I);
4725   
4726   std::sort(Nodes.begin(), Nodes.end());
4727
4728   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4729     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4730       DumpNodes(Nodes[i], 2, this);
4731   }
4732
4733   if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4734
4735   cerr << "\n\n";
4736 }
4737
4738 const Type *ConstantPoolSDNode::getType() const {
4739   if (isMachineConstantPoolEntry())
4740     return Val.MachineCPVal->getType();
4741   return Val.ConstVal->getType();
4742 }