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