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