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