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