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