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