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