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