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