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