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