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