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