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