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