SelectionDAG.cpp revision 4c931fc6e2a901f86ef20d5844bcad3cfd99c781
1//===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAG class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/SelectionDAG.h"
15#include "llvm/Constants.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/CodeGen/MachineBasicBlock.h"
22#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineModuleInfo.h"
25#include "llvm/CodeGen/PseudoSourceValue.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Target/TargetRegisterInfo.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetLowering.h"
30#include "llvm/Target/TargetInstrInfo.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/ADT/SetVector.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallSet.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringExtras.h"
37#include <algorithm>
38#include <cmath>
39using namespace llvm;
40
41/// makeVTList - Return an instance of the SDVTList struct initialized with the
42/// specified members.
43static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
44  SDVTList Res = {VTs, NumVTs};
45  return Res;
46}
47
48static const fltSemantics *MVTToAPFloatSemantics(MVT::ValueType VT) {
49  switch (VT) {
50  default: assert(0 && "Unknown FP format");
51  case MVT::f32:     return &APFloat::IEEEsingle;
52  case MVT::f64:     return &APFloat::IEEEdouble;
53  case MVT::f80:     return &APFloat::x87DoubleExtended;
54  case MVT::f128:    return &APFloat::IEEEquad;
55  case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
56  }
57}
58
59SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
60
61//===----------------------------------------------------------------------===//
62//                              ConstantFPSDNode Class
63//===----------------------------------------------------------------------===//
64
65/// isExactlyValue - We don't rely on operator== working on double values, as
66/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
67/// As such, this method can be used to do an exact bit-for-bit comparison of
68/// two floating point values.
69bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
70  return Value.bitwiseIsEqual(V);
71}
72
73bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT,
74                                           const APFloat& Val) {
75  assert(MVT::isFloatingPoint(VT) && "Can only convert between FP types");
76
77  // Anything can be extended to ppc long double.
78  if (VT == MVT::ppcf128)
79    return true;
80
81  // PPC long double cannot be shrunk to anything though.
82  if (&Val.getSemantics() == &APFloat::PPCDoubleDouble)
83    return false;
84
85  // convert modifies in place, so make a copy.
86  APFloat Val2 = APFloat(Val);
87  return Val2.convert(*MVTToAPFloatSemantics(VT),
88                      APFloat::rmNearestTiesToEven) == APFloat::opOK;
89}
90
91//===----------------------------------------------------------------------===//
92//                              ISD Namespace
93//===----------------------------------------------------------------------===//
94
95/// isBuildVectorAllOnes - Return true if the specified node is a
96/// BUILD_VECTOR where all of the elements are ~0 or undef.
97bool ISD::isBuildVectorAllOnes(const SDNode *N) {
98  // Look through a bit convert.
99  if (N->getOpcode() == ISD::BIT_CONVERT)
100    N = N->getOperand(0).Val;
101
102  if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
103
104  unsigned i = 0, e = N->getNumOperands();
105
106  // Skip over all of the undef values.
107  while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
108    ++i;
109
110  // Do not accept an all-undef vector.
111  if (i == e) return false;
112
113  // Do not accept build_vectors that aren't all constants or which have non-~0
114  // elements.
115  SDOperand NotZero = N->getOperand(i);
116  if (isa<ConstantSDNode>(NotZero)) {
117    if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
118      return false;
119  } else if (isa<ConstantFPSDNode>(NotZero)) {
120    if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
121                convertToAPInt().isAllOnesValue())
122      return false;
123  } else
124    return false;
125
126  // Okay, we have at least one ~0 value, check to see if the rest match or are
127  // undefs.
128  for (++i; i != e; ++i)
129    if (N->getOperand(i) != NotZero &&
130        N->getOperand(i).getOpcode() != ISD::UNDEF)
131      return false;
132  return true;
133}
134
135
136/// isBuildVectorAllZeros - Return true if the specified node is a
137/// BUILD_VECTOR where all of the elements are 0 or undef.
138bool ISD::isBuildVectorAllZeros(const SDNode *N) {
139  // Look through a bit convert.
140  if (N->getOpcode() == ISD::BIT_CONVERT)
141    N = N->getOperand(0).Val;
142
143  if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
144
145  unsigned i = 0, e = N->getNumOperands();
146
147  // Skip over all of the undef values.
148  while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
149    ++i;
150
151  // Do not accept an all-undef vector.
152  if (i == e) return false;
153
154  // Do not accept build_vectors that aren't all constants or which have non-~0
155  // elements.
156  SDOperand Zero = N->getOperand(i);
157  if (isa<ConstantSDNode>(Zero)) {
158    if (!cast<ConstantSDNode>(Zero)->isNullValue())
159      return false;
160  } else if (isa<ConstantFPSDNode>(Zero)) {
161    if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
162      return false;
163  } else
164    return false;
165
166  // Okay, we have at least one ~0 value, check to see if the rest match or are
167  // undefs.
168  for (++i; i != e; ++i)
169    if (N->getOperand(i) != Zero &&
170        N->getOperand(i).getOpcode() != ISD::UNDEF)
171      return false;
172  return true;
173}
174
175/// isScalarToVector - Return true if the specified node is a
176/// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
177/// element is not an undef.
178bool ISD::isScalarToVector(const SDNode *N) {
179  if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
180    return true;
181
182  if (N->getOpcode() != ISD::BUILD_VECTOR)
183    return false;
184  if (N->getOperand(0).getOpcode() == ISD::UNDEF)
185    return false;
186  unsigned NumElems = N->getNumOperands();
187  for (unsigned i = 1; i < NumElems; ++i) {
188    SDOperand V = N->getOperand(i);
189    if (V.getOpcode() != ISD::UNDEF)
190      return false;
191  }
192  return true;
193}
194
195
196/// isDebugLabel - Return true if the specified node represents a debug
197/// label (i.e. ISD::LABEL or TargetInstrInfo::LABEL node and third operand
198/// is 0).
199bool ISD::isDebugLabel(const SDNode *N) {
200  SDOperand Zero;
201  if (N->getOpcode() == ISD::LABEL)
202    Zero = N->getOperand(2);
203  else if (N->isTargetOpcode() &&
204           N->getTargetOpcode() == TargetInstrInfo::LABEL)
205    // Chain moved to last operand.
206    Zero = N->getOperand(1);
207  else
208    return false;
209  return isa<ConstantSDNode>(Zero) && cast<ConstantSDNode>(Zero)->isNullValue();
210}
211
212/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
213/// when given the operation for (X op Y).
214ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
215  // To perform this operation, we just need to swap the L and G bits of the
216  // operation.
217  unsigned OldL = (Operation >> 2) & 1;
218  unsigned OldG = (Operation >> 1) & 1;
219  return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
220                       (OldL << 1) |       // New G bit
221                       (OldG << 2));        // New L bit.
222}
223
224/// getSetCCInverse - Return the operation corresponding to !(X op Y), where
225/// 'op' is a valid SetCC operation.
226ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
227  unsigned Operation = Op;
228  if (isInteger)
229    Operation ^= 7;   // Flip L, G, E bits, but not U.
230  else
231    Operation ^= 15;  // Flip all of the condition bits.
232  if (Operation > ISD::SETTRUE2)
233    Operation &= ~8;     // Don't let N and U bits get set.
234  return ISD::CondCode(Operation);
235}
236
237
238/// isSignedOp - For an integer comparison, return 1 if the comparison is a
239/// signed operation and 2 if the result is an unsigned comparison.  Return zero
240/// if the operation does not depend on the sign of the input (setne and seteq).
241static int isSignedOp(ISD::CondCode Opcode) {
242  switch (Opcode) {
243  default: assert(0 && "Illegal integer setcc operation!");
244  case ISD::SETEQ:
245  case ISD::SETNE: return 0;
246  case ISD::SETLT:
247  case ISD::SETLE:
248  case ISD::SETGT:
249  case ISD::SETGE: return 1;
250  case ISD::SETULT:
251  case ISD::SETULE:
252  case ISD::SETUGT:
253  case ISD::SETUGE: return 2;
254  }
255}
256
257/// getSetCCOrOperation - Return the result of a logical OR between different
258/// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
259/// returns SETCC_INVALID if it is not possible to represent the resultant
260/// comparison.
261ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
262                                       bool isInteger) {
263  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
264    // Cannot fold a signed integer setcc with an unsigned integer setcc.
265    return ISD::SETCC_INVALID;
266
267  unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
268
269  // If the N and U bits get set then the resultant comparison DOES suddenly
270  // care about orderedness, and is true when ordered.
271  if (Op > ISD::SETTRUE2)
272    Op &= ~16;     // Clear the U bit if the N bit is set.
273
274  // Canonicalize illegal integer setcc's.
275  if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
276    Op = ISD::SETNE;
277
278  return ISD::CondCode(Op);
279}
280
281/// getSetCCAndOperation - Return the result of a logical AND between different
282/// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
283/// function returns zero if it is not possible to represent the resultant
284/// comparison.
285ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
286                                        bool isInteger) {
287  if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
288    // Cannot fold a signed setcc with an unsigned setcc.
289    return ISD::SETCC_INVALID;
290
291  // Combine all of the condition bits.
292  ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
293
294  // Canonicalize illegal integer setcc's.
295  if (isInteger) {
296    switch (Result) {
297    default: break;
298    case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
299    case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
300    case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
301    case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
302    }
303  }
304
305  return Result;
306}
307
308const TargetMachine &SelectionDAG::getTarget() const {
309  return TLI.getTargetMachine();
310}
311
312//===----------------------------------------------------------------------===//
313//                           SDNode Profile Support
314//===----------------------------------------------------------------------===//
315
316/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
317///
318static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
319  ID.AddInteger(OpC);
320}
321
322/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
323/// solely with their pointer.
324void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
325  ID.AddPointer(VTList.VTs);
326}
327
328/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
329///
330static void AddNodeIDOperands(FoldingSetNodeID &ID,
331                              const SDOperand *Ops, unsigned NumOps) {
332  for (; NumOps; --NumOps, ++Ops) {
333    ID.AddPointer(Ops->Val);
334    ID.AddInteger(Ops->ResNo);
335  }
336}
337
338static void AddNodeIDNode(FoldingSetNodeID &ID,
339                          unsigned short OpC, SDVTList VTList,
340                          const SDOperand *OpList, unsigned N) {
341  AddNodeIDOpcode(ID, OpC);
342  AddNodeIDValueTypes(ID, VTList);
343  AddNodeIDOperands(ID, OpList, N);
344}
345
346/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
347/// data.
348static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
349  AddNodeIDOpcode(ID, N->getOpcode());
350  // Add the return value info.
351  AddNodeIDValueTypes(ID, N->getVTList());
352  // Add the operand info.
353  AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
354
355  // Handle SDNode leafs with special info.
356  switch (N->getOpcode()) {
357  default: break;  // Normal nodes don't need extra info.
358  case ISD::ARG_FLAGS:
359    ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
360    break;
361  case ISD::TargetConstant:
362  case ISD::Constant:
363    ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
364    break;
365  case ISD::TargetConstantFP:
366  case ISD::ConstantFP: {
367    ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
368    break;
369  }
370  case ISD::TargetGlobalAddress:
371  case ISD::GlobalAddress:
372  case ISD::TargetGlobalTLSAddress:
373  case ISD::GlobalTLSAddress: {
374    GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
375    ID.AddPointer(GA->getGlobal());
376    ID.AddInteger(GA->getOffset());
377    break;
378  }
379  case ISD::BasicBlock:
380    ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
381    break;
382  case ISD::Register:
383    ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
384    break;
385  case ISD::SRCVALUE:
386    ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
387    break;
388  case ISD::MEMOPERAND: {
389    const MemOperand &MO = cast<MemOperandSDNode>(N)->MO;
390    ID.AddPointer(MO.getValue());
391    ID.AddInteger(MO.getFlags());
392    ID.AddInteger(MO.getOffset());
393    ID.AddInteger(MO.getSize());
394    ID.AddInteger(MO.getAlignment());
395    break;
396  }
397  case ISD::FrameIndex:
398  case ISD::TargetFrameIndex:
399    ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
400    break;
401  case ISD::JumpTable:
402  case ISD::TargetJumpTable:
403    ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
404    break;
405  case ISD::ConstantPool:
406  case ISD::TargetConstantPool: {
407    ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
408    ID.AddInteger(CP->getAlignment());
409    ID.AddInteger(CP->getOffset());
410    if (CP->isMachineConstantPoolEntry())
411      CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
412    else
413      ID.AddPointer(CP->getConstVal());
414    break;
415  }
416  case ISD::LOAD: {
417    LoadSDNode *LD = cast<LoadSDNode>(N);
418    ID.AddInteger(LD->getAddressingMode());
419    ID.AddInteger(LD->getExtensionType());
420    ID.AddInteger((unsigned int)(LD->getMemoryVT()));
421    ID.AddInteger(LD->getAlignment());
422    ID.AddInteger(LD->isVolatile());
423    break;
424  }
425  case ISD::STORE: {
426    StoreSDNode *ST = cast<StoreSDNode>(N);
427    ID.AddInteger(ST->getAddressingMode());
428    ID.AddInteger(ST->isTruncatingStore());
429    ID.AddInteger((unsigned int)(ST->getMemoryVT()));
430    ID.AddInteger(ST->getAlignment());
431    ID.AddInteger(ST->isVolatile());
432    break;
433  }
434  }
435}
436
437//===----------------------------------------------------------------------===//
438//                              SelectionDAG Class
439//===----------------------------------------------------------------------===//
440
441/// RemoveDeadNodes - This method deletes all unreachable nodes in the
442/// SelectionDAG.
443void SelectionDAG::RemoveDeadNodes() {
444  // Create a dummy node (which is not added to allnodes), that adds a reference
445  // to the root node, preventing it from being deleted.
446  HandleSDNode Dummy(getRoot());
447
448  SmallVector<SDNode*, 128> DeadNodes;
449
450  // Add all obviously-dead nodes to the DeadNodes worklist.
451  for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
452    if (I->use_empty())
453      DeadNodes.push_back(I);
454
455  // Process the worklist, deleting the nodes and adding their uses to the
456  // worklist.
457  while (!DeadNodes.empty()) {
458    SDNode *N = DeadNodes.back();
459    DeadNodes.pop_back();
460
461    // Take the node out of the appropriate CSE map.
462    RemoveNodeFromCSEMaps(N);
463
464    // Next, brutally remove the operand list.  This is safe to do, as there are
465    // no cycles in the graph.
466    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
467      SDNode *Operand = I->Val;
468      Operand->removeUser(N);
469
470      // Now that we removed this operand, see if there are no uses of it left.
471      if (Operand->use_empty())
472        DeadNodes.push_back(Operand);
473    }
474    if (N->OperandsNeedDelete)
475      delete[] N->OperandList;
476    N->OperandList = 0;
477    N->NumOperands = 0;
478
479    // Finally, remove N itself.
480    AllNodes.erase(N);
481  }
482
483  // If the root changed (e.g. it was a dead load, update the root).
484  setRoot(Dummy.getValue());
485}
486
487void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
488  SmallVector<SDNode*, 16> DeadNodes;
489  DeadNodes.push_back(N);
490
491  // Process the worklist, deleting the nodes and adding their uses to the
492  // worklist.
493  while (!DeadNodes.empty()) {
494    SDNode *N = DeadNodes.back();
495    DeadNodes.pop_back();
496
497    if (UpdateListener)
498      UpdateListener->NodeDeleted(N);
499
500    // Take the node out of the appropriate CSE map.
501    RemoveNodeFromCSEMaps(N);
502
503    // Next, brutally remove the operand list.  This is safe to do, as there are
504    // no cycles in the graph.
505    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
506      SDNode *Operand = I->Val;
507      Operand->removeUser(N);
508
509      // Now that we removed this operand, see if there are no uses of it left.
510      if (Operand->use_empty())
511        DeadNodes.push_back(Operand);
512    }
513    if (N->OperandsNeedDelete)
514      delete[] N->OperandList;
515    N->OperandList = 0;
516    N->NumOperands = 0;
517
518    // Finally, remove N itself.
519    AllNodes.erase(N);
520  }
521}
522
523void SelectionDAG::DeleteNode(SDNode *N) {
524  assert(N->use_empty() && "Cannot delete a node that is not dead!");
525
526  // First take this out of the appropriate CSE map.
527  RemoveNodeFromCSEMaps(N);
528
529  // Finally, remove uses due to operands of this node, remove from the
530  // AllNodes list, and delete the node.
531  DeleteNodeNotInCSEMaps(N);
532}
533
534void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
535
536  // Remove it from the AllNodes list.
537  AllNodes.remove(N);
538
539  // Drop all of the operands and decrement used nodes use counts.
540  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
541    I->Val->removeUser(N);
542  if (N->OperandsNeedDelete)
543    delete[] N->OperandList;
544  N->OperandList = 0;
545  N->NumOperands = 0;
546
547  delete N;
548}
549
550/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
551/// correspond to it.  This is useful when we're about to delete or repurpose
552/// the node.  We don't want future request for structurally identical nodes
553/// to return N anymore.
554void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
555  bool Erased = false;
556  switch (N->getOpcode()) {
557  case ISD::HANDLENODE: return;  // noop.
558  case ISD::STRING:
559    Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
560    break;
561  case ISD::CONDCODE:
562    assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
563           "Cond code doesn't exist!");
564    Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
565    CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
566    break;
567  case ISD::ExternalSymbol:
568    Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
569    break;
570  case ISD::TargetExternalSymbol:
571    Erased =
572      TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
573    break;
574  case ISD::VALUETYPE: {
575    MVT::ValueType VT = cast<VTSDNode>(N)->getVT();
576    if (MVT::isExtendedVT(VT)) {
577      Erased = ExtendedValueTypeNodes.erase(VT);
578    } else {
579      Erased = ValueTypeNodes[VT] != 0;
580      ValueTypeNodes[VT] = 0;
581    }
582    break;
583  }
584  default:
585    // Remove it from the CSE Map.
586    Erased = CSEMap.RemoveNode(N);
587    break;
588  }
589#ifndef NDEBUG
590  // Verify that the node was actually in one of the CSE maps, unless it has a
591  // flag result (which cannot be CSE'd) or is one of the special cases that are
592  // not subject to CSE.
593  if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
594      !N->isTargetOpcode()) {
595    N->dump(this);
596    cerr << "\n";
597    assert(0 && "Node is not in map!");
598  }
599#endif
600}
601
602/// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
603/// has been taken out and modified in some way.  If the specified node already
604/// exists in the CSE maps, do not modify the maps, but return the existing node
605/// instead.  If it doesn't exist, add it and return null.
606///
607SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
608  assert(N->getNumOperands() && "This is a leaf node!");
609  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
610    return 0;    // Never add these nodes.
611
612  // Check that remaining values produced are not flags.
613  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
614    if (N->getValueType(i) == MVT::Flag)
615      return 0;   // Never CSE anything that produces a flag.
616
617  SDNode *New = CSEMap.GetOrInsertNode(N);
618  if (New != N) return New;  // Node already existed.
619  return 0;
620}
621
622/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
623/// were replaced with those specified.  If this node is never memoized,
624/// return null, otherwise return a pointer to the slot it would take.  If a
625/// node already exists with these operands, the slot will be non-null.
626SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
627                                           void *&InsertPos) {
628  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
629    return 0;    // Never add these nodes.
630
631  // Check that remaining values produced are not flags.
632  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
633    if (N->getValueType(i) == MVT::Flag)
634      return 0;   // Never CSE anything that produces a flag.
635
636  SDOperand Ops[] = { Op };
637  FoldingSetNodeID ID;
638  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
639  return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
640}
641
642/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
643/// were replaced with those specified.  If this node is never memoized,
644/// return null, otherwise return a pointer to the slot it would take.  If a
645/// node already exists with these operands, the slot will be non-null.
646SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
647                                           SDOperand Op1, SDOperand Op2,
648                                           void *&InsertPos) {
649  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
650    return 0;    // Never add these nodes.
651
652  // Check that remaining values produced are not flags.
653  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
654    if (N->getValueType(i) == MVT::Flag)
655      return 0;   // Never CSE anything that produces a flag.
656
657  SDOperand Ops[] = { Op1, Op2 };
658  FoldingSetNodeID ID;
659  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
660  return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
661}
662
663
664/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
665/// were replaced with those specified.  If this node is never memoized,
666/// return null, otherwise return a pointer to the slot it would take.  If a
667/// node already exists with these operands, the slot will be non-null.
668SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
669                                           const SDOperand *Ops,unsigned NumOps,
670                                           void *&InsertPos) {
671  if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
672    return 0;    // Never add these nodes.
673
674  // Check that remaining values produced are not flags.
675  for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
676    if (N->getValueType(i) == MVT::Flag)
677      return 0;   // Never CSE anything that produces a flag.
678
679  FoldingSetNodeID ID;
680  AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
681
682  if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
683    ID.AddInteger(LD->getAddressingMode());
684    ID.AddInteger(LD->getExtensionType());
685    ID.AddInteger((unsigned int)(LD->getMemoryVT()));
686    ID.AddInteger(LD->getAlignment());
687    ID.AddInteger(LD->isVolatile());
688  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
689    ID.AddInteger(ST->getAddressingMode());
690    ID.AddInteger(ST->isTruncatingStore());
691    ID.AddInteger((unsigned int)(ST->getMemoryVT()));
692    ID.AddInteger(ST->getAlignment());
693    ID.AddInteger(ST->isVolatile());
694  }
695
696  return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
697}
698
699
700SelectionDAG::~SelectionDAG() {
701  while (!AllNodes.empty()) {
702    SDNode *N = AllNodes.begin();
703    N->SetNextInBucket(0);
704    if (N->OperandsNeedDelete)
705      delete [] N->OperandList;
706    N->OperandList = 0;
707    N->NumOperands = 0;
708    AllNodes.pop_front();
709  }
710}
711
712SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
713  if (Op.getValueType() == VT) return Op;
714  APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
715                                   MVT::getSizeInBits(VT));
716  return getNode(ISD::AND, Op.getValueType(), Op,
717                 getConstant(Imm, Op.getValueType()));
718}
719
720SDOperand SelectionDAG::getString(const std::string &Val) {
721  StringSDNode *&N = StringNodes[Val];
722  if (!N) {
723    N = new StringSDNode(Val);
724    AllNodes.push_back(N);
725  }
726  return SDOperand(N, 0);
727}
728
729SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
730  MVT::ValueType EltVT =
731    MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
732
733  return getConstant(APInt(MVT::getSizeInBits(EltVT), Val), VT, isT);
734}
735
736SDOperand SelectionDAG::getConstant(const APInt &Val, MVT::ValueType VT, bool isT) {
737  assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
738
739  MVT::ValueType EltVT =
740    MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
741
742  assert(Val.getBitWidth() == MVT::getSizeInBits(EltVT) &&
743         "APInt size does not match type size!");
744
745  unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
746  FoldingSetNodeID ID;
747  AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
748  ID.Add(Val);
749  void *IP = 0;
750  SDNode *N = NULL;
751  if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
752    if (!MVT::isVector(VT))
753      return SDOperand(N, 0);
754  if (!N) {
755    N = new ConstantSDNode(isT, Val, EltVT);
756    CSEMap.InsertNode(N, IP);
757    AllNodes.push_back(N);
758  }
759
760  SDOperand Result(N, 0);
761  if (MVT::isVector(VT)) {
762    SmallVector<SDOperand, 8> Ops;
763    Ops.assign(MVT::getVectorNumElements(VT), Result);
764    Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
765  }
766  return Result;
767}
768
769SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
770  return getConstant(Val, TLI.getPointerTy(), isTarget);
771}
772
773
774SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
775                                      bool isTarget) {
776  assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
777
778  MVT::ValueType EltVT =
779    MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
780
781  // Do the map lookup using the actual bit pattern for the floating point
782  // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
783  // we don't have issues with SNANs.
784  unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
785  FoldingSetNodeID ID;
786  AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
787  ID.Add(V);
788  void *IP = 0;
789  SDNode *N = NULL;
790  if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
791    if (!MVT::isVector(VT))
792      return SDOperand(N, 0);
793  if (!N) {
794    N = new ConstantFPSDNode(isTarget, V, EltVT);
795    CSEMap.InsertNode(N, IP);
796    AllNodes.push_back(N);
797  }
798
799  SDOperand Result(N, 0);
800  if (MVT::isVector(VT)) {
801    SmallVector<SDOperand, 8> Ops;
802    Ops.assign(MVT::getVectorNumElements(VT), Result);
803    Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
804  }
805  return Result;
806}
807
808SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
809                                      bool isTarget) {
810  MVT::ValueType EltVT =
811    MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
812  if (EltVT==MVT::f32)
813    return getConstantFP(APFloat((float)Val), VT, isTarget);
814  else
815    return getConstantFP(APFloat(Val), VT, isTarget);
816}
817
818SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
819                                         MVT::ValueType VT, int Offset,
820                                         bool isTargetGA) {
821  unsigned Opc;
822
823  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
824  if (!GVar) {
825    // If GV is an alias then use the aliasee for determining thread-localness.
826    if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
827      GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
828  }
829
830  if (GVar && GVar->isThreadLocal())
831    Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
832  else
833    Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
834
835  FoldingSetNodeID ID;
836  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
837  ID.AddPointer(GV);
838  ID.AddInteger(Offset);
839  void *IP = 0;
840  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
841   return SDOperand(E, 0);
842  SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
843  CSEMap.InsertNode(N, IP);
844  AllNodes.push_back(N);
845  return SDOperand(N, 0);
846}
847
848SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
849                                      bool isTarget) {
850  unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
851  FoldingSetNodeID ID;
852  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
853  ID.AddInteger(FI);
854  void *IP = 0;
855  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
856    return SDOperand(E, 0);
857  SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
858  CSEMap.InsertNode(N, IP);
859  AllNodes.push_back(N);
860  return SDOperand(N, 0);
861}
862
863SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
864  unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
865  FoldingSetNodeID ID;
866  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
867  ID.AddInteger(JTI);
868  void *IP = 0;
869  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
870    return SDOperand(E, 0);
871  SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
872  CSEMap.InsertNode(N, IP);
873  AllNodes.push_back(N);
874  return SDOperand(N, 0);
875}
876
877SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
878                                        unsigned Alignment, int Offset,
879                                        bool isTarget) {
880  unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
881  FoldingSetNodeID ID;
882  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
883  ID.AddInteger(Alignment);
884  ID.AddInteger(Offset);
885  ID.AddPointer(C);
886  void *IP = 0;
887  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
888    return SDOperand(E, 0);
889  SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
890  CSEMap.InsertNode(N, IP);
891  AllNodes.push_back(N);
892  return SDOperand(N, 0);
893}
894
895
896SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
897                                        MVT::ValueType VT,
898                                        unsigned Alignment, int Offset,
899                                        bool isTarget) {
900  unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
901  FoldingSetNodeID ID;
902  AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
903  ID.AddInteger(Alignment);
904  ID.AddInteger(Offset);
905  C->AddSelectionDAGCSEId(ID);
906  void *IP = 0;
907  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
908    return SDOperand(E, 0);
909  SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
910  CSEMap.InsertNode(N, IP);
911  AllNodes.push_back(N);
912  return SDOperand(N, 0);
913}
914
915
916SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
917  FoldingSetNodeID ID;
918  AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
919  ID.AddPointer(MBB);
920  void *IP = 0;
921  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
922    return SDOperand(E, 0);
923  SDNode *N = new BasicBlockSDNode(MBB);
924  CSEMap.InsertNode(N, IP);
925  AllNodes.push_back(N);
926  return SDOperand(N, 0);
927}
928
929SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
930  FoldingSetNodeID ID;
931  AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
932  ID.AddInteger(Flags.getRawBits());
933  void *IP = 0;
934  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
935    return SDOperand(E, 0);
936  SDNode *N = new ARG_FLAGSSDNode(Flags);
937  CSEMap.InsertNode(N, IP);
938  AllNodes.push_back(N);
939  return SDOperand(N, 0);
940}
941
942SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
943  if (!MVT::isExtendedVT(VT) && (unsigned)VT >= ValueTypeNodes.size())
944    ValueTypeNodes.resize(VT+1);
945
946  SDNode *&N = MVT::isExtendedVT(VT) ?
947    ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT];
948
949  if (N) return SDOperand(N, 0);
950  N = new VTSDNode(VT);
951  AllNodes.push_back(N);
952  return SDOperand(N, 0);
953}
954
955SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
956  SDNode *&N = ExternalSymbols[Sym];
957  if (N) return SDOperand(N, 0);
958  N = new ExternalSymbolSDNode(false, Sym, VT);
959  AllNodes.push_back(N);
960  return SDOperand(N, 0);
961}
962
963SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
964                                                MVT::ValueType VT) {
965  SDNode *&N = TargetExternalSymbols[Sym];
966  if (N) return SDOperand(N, 0);
967  N = new ExternalSymbolSDNode(true, Sym, VT);
968  AllNodes.push_back(N);
969  return SDOperand(N, 0);
970}
971
972SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
973  if ((unsigned)Cond >= CondCodeNodes.size())
974    CondCodeNodes.resize(Cond+1);
975
976  if (CondCodeNodes[Cond] == 0) {
977    CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
978    AllNodes.push_back(CondCodeNodes[Cond]);
979  }
980  return SDOperand(CondCodeNodes[Cond], 0);
981}
982
983SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
984  FoldingSetNodeID ID;
985  AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
986  ID.AddInteger(RegNo);
987  void *IP = 0;
988  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
989    return SDOperand(E, 0);
990  SDNode *N = new RegisterSDNode(RegNo, VT);
991  CSEMap.InsertNode(N, IP);
992  AllNodes.push_back(N);
993  return SDOperand(N, 0);
994}
995
996SDOperand SelectionDAG::getSrcValue(const Value *V) {
997  assert((!V || isa<PointerType>(V->getType())) &&
998         "SrcValue is not a pointer?");
999
1000  FoldingSetNodeID ID;
1001  AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1002  ID.AddPointer(V);
1003
1004  void *IP = 0;
1005  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1006    return SDOperand(E, 0);
1007
1008  SDNode *N = new SrcValueSDNode(V);
1009  CSEMap.InsertNode(N, IP);
1010  AllNodes.push_back(N);
1011  return SDOperand(N, 0);
1012}
1013
1014SDOperand SelectionDAG::getMemOperand(const MemOperand &MO) {
1015  const Value *v = MO.getValue();
1016  assert((!v || isa<PointerType>(v->getType())) &&
1017         "SrcValue is not a pointer?");
1018
1019  FoldingSetNodeID ID;
1020  AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1021  ID.AddPointer(v);
1022  ID.AddInteger(MO.getFlags());
1023  ID.AddInteger(MO.getOffset());
1024  ID.AddInteger(MO.getSize());
1025  ID.AddInteger(MO.getAlignment());
1026
1027  void *IP = 0;
1028  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1029    return SDOperand(E, 0);
1030
1031  SDNode *N = new MemOperandSDNode(MO);
1032  CSEMap.InsertNode(N, IP);
1033  AllNodes.push_back(N);
1034  return SDOperand(N, 0);
1035}
1036
1037/// CreateStackTemporary - Create a stack temporary, suitable for holding the
1038/// specified value type.
1039SDOperand SelectionDAG::CreateStackTemporary(MVT::ValueType VT) {
1040  MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1041  unsigned ByteSize = MVT::getSizeInBits(VT)/8;
1042  const Type *Ty = MVT::getTypeForValueType(VT);
1043  unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
1044  int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1045  return getFrameIndex(FrameIdx, TLI.getPointerTy());
1046}
1047
1048
1049SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
1050                                  SDOperand N2, ISD::CondCode Cond) {
1051  // These setcc operations always fold.
1052  switch (Cond) {
1053  default: break;
1054  case ISD::SETFALSE:
1055  case ISD::SETFALSE2: return getConstant(0, VT);
1056  case ISD::SETTRUE:
1057  case ISD::SETTRUE2:  return getConstant(1, VT);
1058
1059  case ISD::SETOEQ:
1060  case ISD::SETOGT:
1061  case ISD::SETOGE:
1062  case ISD::SETOLT:
1063  case ISD::SETOLE:
1064  case ISD::SETONE:
1065  case ISD::SETO:
1066  case ISD::SETUO:
1067  case ISD::SETUEQ:
1068  case ISD::SETUNE:
1069    assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
1070    break;
1071  }
1072
1073  if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1074    const APInt &C2 = N2C->getAPIntValue();
1075    if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1076      const APInt &C1 = N1C->getAPIntValue();
1077
1078      switch (Cond) {
1079      default: assert(0 && "Unknown integer setcc!");
1080      case ISD::SETEQ:  return getConstant(C1 == C2, VT);
1081      case ISD::SETNE:  return getConstant(C1 != C2, VT);
1082      case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1083      case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1084      case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1085      case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1086      case ISD::SETLT:  return getConstant(C1.slt(C2), VT);
1087      case ISD::SETGT:  return getConstant(C1.sgt(C2), VT);
1088      case ISD::SETLE:  return getConstant(C1.sle(C2), VT);
1089      case ISD::SETGE:  return getConstant(C1.sge(C2), VT);
1090      }
1091    }
1092  }
1093  if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1094    if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1095      // No compile time operations on this type yet.
1096      if (N1C->getValueType(0) == MVT::ppcf128)
1097        return SDOperand();
1098
1099      APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1100      switch (Cond) {
1101      default: break;
1102      case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
1103                          return getNode(ISD::UNDEF, VT);
1104                        // fall through
1105      case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1106      case ISD::SETNE:  if (R==APFloat::cmpUnordered)
1107                          return getNode(ISD::UNDEF, VT);
1108                        // fall through
1109      case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1110                                           R==APFloat::cmpLessThan, VT);
1111      case ISD::SETLT:  if (R==APFloat::cmpUnordered)
1112                          return getNode(ISD::UNDEF, VT);
1113                        // fall through
1114      case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1115      case ISD::SETGT:  if (R==APFloat::cmpUnordered)
1116                          return getNode(ISD::UNDEF, VT);
1117                        // fall through
1118      case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1119      case ISD::SETLE:  if (R==APFloat::cmpUnordered)
1120                          return getNode(ISD::UNDEF, VT);
1121                        // fall through
1122      case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1123                                           R==APFloat::cmpEqual, VT);
1124      case ISD::SETGE:  if (R==APFloat::cmpUnordered)
1125                          return getNode(ISD::UNDEF, VT);
1126                        // fall through
1127      case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1128                                           R==APFloat::cmpEqual, VT);
1129      case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
1130      case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
1131      case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1132                                           R==APFloat::cmpEqual, VT);
1133      case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1134      case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1135                                           R==APFloat::cmpLessThan, VT);
1136      case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1137                                           R==APFloat::cmpUnordered, VT);
1138      case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1139      case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1140      }
1141    } else {
1142      // Ensure that the constant occurs on the RHS.
1143      return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1144    }
1145  }
1146
1147  // Could not fold it.
1148  return SDOperand();
1149}
1150
1151/// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
1152/// use this predicate to simplify operations downstream.
1153bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1154  unsigned BitWidth = Op.getValueSizeInBits();
1155  return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1156}
1157
1158/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1159/// this predicate to simplify operations downstream.  Mask is known to be zero
1160/// for bits that V cannot have.
1161bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1162                                     unsigned Depth) const {
1163  APInt KnownZero, KnownOne;
1164  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1165  assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1166  return (KnownZero & Mask) == Mask;
1167}
1168
1169/// ComputeMaskedBits - Determine which of the bits specified in Mask are
1170/// known to be either zero or one and return them in the KnownZero/KnownOne
1171/// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
1172/// processing.
1173void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1174                                     APInt &KnownZero, APInt &KnownOne,
1175                                     unsigned Depth) const {
1176  unsigned BitWidth = Mask.getBitWidth();
1177  assert(BitWidth == MVT::getSizeInBits(Op.getValueType()) &&
1178         "Mask size mismatches value type size!");
1179
1180  KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
1181  if (Depth == 6 || Mask == 0)
1182    return;  // Limit search depth.
1183
1184  APInt KnownZero2, KnownOne2;
1185
1186  switch (Op.getOpcode()) {
1187  case ISD::Constant:
1188    // We know all of the bits for a constant!
1189    KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1190    KnownZero = ~KnownOne & Mask;
1191    return;
1192  case ISD::AND:
1193    // If either the LHS or the RHS are Zero, the result is zero.
1194    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1195    ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1196                      KnownZero2, KnownOne2, Depth+1);
1197    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1198    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1199
1200    // Output known-1 bits are only known if set in both the LHS & RHS.
1201    KnownOne &= KnownOne2;
1202    // Output known-0 are known to be clear if zero in either the LHS | RHS.
1203    KnownZero |= KnownZero2;
1204    return;
1205  case ISD::OR:
1206    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1207    ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1208                      KnownZero2, KnownOne2, Depth+1);
1209    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1210    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1211
1212    // Output known-0 bits are only known if clear in both the LHS & RHS.
1213    KnownZero &= KnownZero2;
1214    // Output known-1 are known to be set if set in either the LHS | RHS.
1215    KnownOne |= KnownOne2;
1216    return;
1217  case ISD::XOR: {
1218    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1219    ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1220    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1221    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1222
1223    // Output known-0 bits are known if clear or set in both the LHS & RHS.
1224    APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1225    // Output known-1 are known to be set if set in only one of the LHS, RHS.
1226    KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1227    KnownZero = KnownZeroOut;
1228    return;
1229  }
1230  case ISD::SELECT:
1231    ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1232    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1233    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1234    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1235
1236    // Only known if known in both the LHS and RHS.
1237    KnownOne &= KnownOne2;
1238    KnownZero &= KnownZero2;
1239    return;
1240  case ISD::SELECT_CC:
1241    ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1242    ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1243    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1244    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1245
1246    // Only known if known in both the LHS and RHS.
1247    KnownOne &= KnownOne2;
1248    KnownZero &= KnownZero2;
1249    return;
1250  case ISD::SETCC:
1251    // If we know the result of a setcc has the top bits zero, use this info.
1252    if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1253        BitWidth > 1)
1254      KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1255    return;
1256  case ISD::SHL:
1257    // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1258    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1259      unsigned ShAmt = SA->getValue();
1260
1261      // If the shift count is an invalid immediate, don't do anything.
1262      if (ShAmt >= BitWidth)
1263        return;
1264
1265      ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1266                        KnownZero, KnownOne, Depth+1);
1267      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1268      KnownZero <<= ShAmt;
1269      KnownOne  <<= ShAmt;
1270      // low bits known zero.
1271      KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1272    }
1273    return;
1274  case ISD::SRL:
1275    // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1276    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1277      unsigned ShAmt = SA->getValue();
1278
1279      // If the shift count is an invalid immediate, don't do anything.
1280      if (ShAmt >= BitWidth)
1281        return;
1282
1283      ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1284                        KnownZero, KnownOne, Depth+1);
1285      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1286      KnownZero = KnownZero.lshr(ShAmt);
1287      KnownOne  = KnownOne.lshr(ShAmt);
1288
1289      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1290      KnownZero |= HighBits;  // High bits known zero.
1291    }
1292    return;
1293  case ISD::SRA:
1294    if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1295      unsigned ShAmt = SA->getValue();
1296
1297      // If the shift count is an invalid immediate, don't do anything.
1298      if (ShAmt >= BitWidth)
1299        return;
1300
1301      APInt InDemandedMask = (Mask << ShAmt);
1302      // If any of the demanded bits are produced by the sign extension, we also
1303      // demand the input sign bit.
1304      APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1305      if (HighBits.getBoolValue())
1306        InDemandedMask |= APInt::getSignBit(BitWidth);
1307
1308      ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1309                        Depth+1);
1310      assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1311      KnownZero = KnownZero.lshr(ShAmt);
1312      KnownOne  = KnownOne.lshr(ShAmt);
1313
1314      // Handle the sign bits.
1315      APInt SignBit = APInt::getSignBit(BitWidth);
1316      SignBit = SignBit.lshr(ShAmt);  // Adjust to where it is now in the mask.
1317
1318      if (KnownZero.intersects(SignBit)) {
1319        KnownZero |= HighBits;  // New bits are known zero.
1320      } else if (KnownOne.intersects(SignBit)) {
1321        KnownOne  |= HighBits;  // New bits are known one.
1322      }
1323    }
1324    return;
1325  case ISD::SIGN_EXTEND_INREG: {
1326    MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1327    unsigned EBits = MVT::getSizeInBits(EVT);
1328
1329    // Sign extension.  Compute the demanded bits in the result that are not
1330    // present in the input.
1331    APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1332
1333    APInt InSignBit = APInt::getSignBit(EBits);
1334    APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1335
1336    // If the sign extended bits are demanded, we know that the sign
1337    // bit is demanded.
1338    InSignBit.zext(BitWidth);
1339    if (NewBits.getBoolValue())
1340      InputDemandedBits |= InSignBit;
1341
1342    ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1343                      KnownZero, KnownOne, Depth+1);
1344    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1345
1346    // If the sign bit of the input is known set or clear, then we know the
1347    // top bits of the result.
1348    if (KnownZero.intersects(InSignBit)) {         // Input sign bit known clear
1349      KnownZero |= NewBits;
1350      KnownOne  &= ~NewBits;
1351    } else if (KnownOne.intersects(InSignBit)) {   // Input sign bit known set
1352      KnownOne  |= NewBits;
1353      KnownZero &= ~NewBits;
1354    } else {                              // Input sign bit unknown
1355      KnownZero &= ~NewBits;
1356      KnownOne  &= ~NewBits;
1357    }
1358    return;
1359  }
1360  case ISD::CTTZ:
1361  case ISD::CTLZ:
1362  case ISD::CTPOP: {
1363    unsigned LowBits = Log2_32(BitWidth)+1;
1364    KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1365    KnownOne  = APInt(BitWidth, 0);
1366    return;
1367  }
1368  case ISD::LOAD: {
1369    if (ISD::isZEXTLoad(Op.Val)) {
1370      LoadSDNode *LD = cast<LoadSDNode>(Op);
1371      MVT::ValueType VT = LD->getMemoryVT();
1372      unsigned MemBits = MVT::getSizeInBits(VT);
1373      KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1374    }
1375    return;
1376  }
1377  case ISD::ZERO_EXTEND: {
1378    MVT::ValueType InVT = Op.getOperand(0).getValueType();
1379    unsigned InBits = MVT::getSizeInBits(InVT);
1380    APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1381    APInt InMask    = Mask;
1382    InMask.trunc(InBits);
1383    KnownZero.trunc(InBits);
1384    KnownOne.trunc(InBits);
1385    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1386    KnownZero.zext(BitWidth);
1387    KnownOne.zext(BitWidth);
1388    KnownZero |= NewBits;
1389    return;
1390  }
1391  case ISD::SIGN_EXTEND: {
1392    MVT::ValueType InVT = Op.getOperand(0).getValueType();
1393    unsigned InBits = MVT::getSizeInBits(InVT);
1394    APInt InSignBit = APInt::getSignBit(InBits);
1395    APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1396    APInt InMask = Mask;
1397    InMask.trunc(InBits);
1398
1399    // If any of the sign extended bits are demanded, we know that the sign
1400    // bit is demanded. Temporarily set this bit in the mask for our callee.
1401    if (NewBits.getBoolValue())
1402      InMask |= InSignBit;
1403
1404    KnownZero.trunc(InBits);
1405    KnownOne.trunc(InBits);
1406    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1407
1408    // Note if the sign bit is known to be zero or one.
1409    bool SignBitKnownZero = KnownZero.isNegative();
1410    bool SignBitKnownOne  = KnownOne.isNegative();
1411    assert(!(SignBitKnownZero && SignBitKnownOne) &&
1412           "Sign bit can't be known to be both zero and one!");
1413
1414    // If the sign bit wasn't actually demanded by our caller, we don't
1415    // want it set in the KnownZero and KnownOne result values. Reset the
1416    // mask and reapply it to the result values.
1417    InMask = Mask;
1418    InMask.trunc(InBits);
1419    KnownZero &= InMask;
1420    KnownOne  &= InMask;
1421
1422    KnownZero.zext(BitWidth);
1423    KnownOne.zext(BitWidth);
1424
1425    // If the sign bit is known zero or one, the top bits match.
1426    if (SignBitKnownZero)
1427      KnownZero |= NewBits;
1428    else if (SignBitKnownOne)
1429      KnownOne  |= NewBits;
1430    return;
1431  }
1432  case ISD::ANY_EXTEND: {
1433    MVT::ValueType InVT = Op.getOperand(0).getValueType();
1434    unsigned InBits = MVT::getSizeInBits(InVT);
1435    APInt InMask = Mask;
1436    InMask.trunc(InBits);
1437    KnownZero.trunc(InBits);
1438    KnownOne.trunc(InBits);
1439    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1440    KnownZero.zext(BitWidth);
1441    KnownOne.zext(BitWidth);
1442    return;
1443  }
1444  case ISD::TRUNCATE: {
1445    MVT::ValueType InVT = Op.getOperand(0).getValueType();
1446    unsigned InBits = MVT::getSizeInBits(InVT);
1447    APInt InMask = Mask;
1448    InMask.zext(InBits);
1449    KnownZero.zext(InBits);
1450    KnownOne.zext(InBits);
1451    ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1452    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1453    KnownZero.trunc(BitWidth);
1454    KnownOne.trunc(BitWidth);
1455    break;
1456  }
1457  case ISD::AssertZext: {
1458    MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1459    APInt InMask = APInt::getLowBitsSet(BitWidth, MVT::getSizeInBits(VT));
1460    ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1461                      KnownOne, Depth+1);
1462    KnownZero |= (~InMask) & Mask;
1463    return;
1464  }
1465  case ISD::FGETSIGN:
1466    // All bits are zero except the low bit.
1467    KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1468    return;
1469
1470  case ISD::ADD: {
1471    // If either the LHS or the RHS are Zero, the result is zero.
1472    ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1473    ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1474    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1475    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1476
1477    // Output known-0 bits are known if clear or set in both the low clear bits
1478    // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
1479    // low 3 bits clear.
1480    unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(),
1481                                     KnownZero2.countTrailingOnes());
1482
1483    KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1484    KnownOne = APInt(BitWidth, 0);
1485    return;
1486  }
1487  case ISD::SUB: {
1488    ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1489    if (!CLHS) return;
1490
1491    // We know that the top bits of C-X are clear if X contains less bits
1492    // than C (i.e. no wrap-around can happen).  For example, 20-X is
1493    // positive if we can prove that X is >= 0 and < 16.
1494    if (CLHS->getAPIntValue().isNonNegative()) {
1495      unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1496      // NLZ can't be BitWidth with no sign bit
1497      APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1498      ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
1499
1500      // If all of the MaskV bits are known to be zero, then we know the output
1501      // top bits are zero, because we now know that the output is from [0-C].
1502      if ((KnownZero & MaskV) == MaskV) {
1503        unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1504        // Top bits known zero.
1505        KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1506        KnownOne = APInt(BitWidth, 0);   // No one bits known.
1507      } else {
1508        KnownZero = KnownOne = APInt(BitWidth, 0);  // Otherwise, nothing known.
1509      }
1510    }
1511    return;
1512  }
1513  default:
1514    // Allow the target to implement this method for its nodes.
1515    if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1516  case ISD::INTRINSIC_WO_CHAIN:
1517  case ISD::INTRINSIC_W_CHAIN:
1518  case ISD::INTRINSIC_VOID:
1519      TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1520    }
1521    return;
1522  }
1523}
1524
1525/// ComputeNumSignBits - Return the number of times the sign bit of the
1526/// register is replicated into the other bits.  We know that at least 1 bit
1527/// is always equal to the sign bit (itself), but other cases can give us
1528/// information.  For example, immediately after an "SRA X, 2", we know that
1529/// the top 3 bits are all equal to each other, so we return 3.
1530unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1531  MVT::ValueType VT = Op.getValueType();
1532  assert(MVT::isInteger(VT) && "Invalid VT!");
1533  unsigned VTBits = MVT::getSizeInBits(VT);
1534  unsigned Tmp, Tmp2;
1535
1536  if (Depth == 6)
1537    return 1;  // Limit search depth.
1538
1539  switch (Op.getOpcode()) {
1540  default: break;
1541  case ISD::AssertSext:
1542    Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1543    return VTBits-Tmp+1;
1544  case ISD::AssertZext:
1545    Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1546    return VTBits-Tmp;
1547
1548  case ISD::Constant: {
1549    const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1550    // If negative, return # leading ones.
1551    if (Val.isNegative())
1552      return Val.countLeadingOnes();
1553
1554    // Return # leading zeros.
1555    return Val.countLeadingZeros();
1556  }
1557
1558  case ISD::SIGN_EXTEND:
1559    Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1560    return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1561
1562  case ISD::SIGN_EXTEND_INREG:
1563    // Max of the input and what this extends.
1564    Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1565    Tmp = VTBits-Tmp+1;
1566
1567    Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1568    return std::max(Tmp, Tmp2);
1569
1570  case ISD::SRA:
1571    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1572    // SRA X, C   -> adds C sign bits.
1573    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1574      Tmp += C->getValue();
1575      if (Tmp > VTBits) Tmp = VTBits;
1576    }
1577    return Tmp;
1578  case ISD::SHL:
1579    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1580      // shl destroys sign bits.
1581      Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1582      if (C->getValue() >= VTBits ||      // Bad shift.
1583          C->getValue() >= Tmp) break;    // Shifted all sign bits out.
1584      return Tmp - C->getValue();
1585    }
1586    break;
1587  case ISD::AND:
1588  case ISD::OR:
1589  case ISD::XOR:    // NOT is handled here.
1590    // Logical binary ops preserve the number of sign bits.
1591    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1592    if (Tmp == 1) return 1;  // Early out.
1593    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1594    return std::min(Tmp, Tmp2);
1595
1596  case ISD::SELECT:
1597    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1598    if (Tmp == 1) return 1;  // Early out.
1599    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1600    return std::min(Tmp, Tmp2);
1601
1602  case ISD::SETCC:
1603    // If setcc returns 0/-1, all bits are sign bits.
1604    if (TLI.getSetCCResultContents() ==
1605        TargetLowering::ZeroOrNegativeOneSetCCResult)
1606      return VTBits;
1607    break;
1608  case ISD::ROTL:
1609  case ISD::ROTR:
1610    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1611      unsigned RotAmt = C->getValue() & (VTBits-1);
1612
1613      // Handle rotate right by N like a rotate left by 32-N.
1614      if (Op.getOpcode() == ISD::ROTR)
1615        RotAmt = (VTBits-RotAmt) & (VTBits-1);
1616
1617      // If we aren't rotating out all of the known-in sign bits, return the
1618      // number that are left.  This handles rotl(sext(x), 1) for example.
1619      Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1620      if (Tmp > RotAmt+1) return Tmp-RotAmt;
1621    }
1622    break;
1623  case ISD::ADD:
1624    // Add can have at most one carry bit.  Thus we know that the output
1625    // is, at worst, one more bit than the inputs.
1626    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1627    if (Tmp == 1) return 1;  // Early out.
1628
1629    // Special case decrementing a value (ADD X, -1):
1630    if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1631      if (CRHS->isAllOnesValue()) {
1632        APInt KnownZero, KnownOne;
1633        APInt Mask = APInt::getAllOnesValue(VTBits);
1634        ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1635
1636        // If the input is known to be 0 or 1, the output is 0/-1, which is all
1637        // sign bits set.
1638        if ((KnownZero | APInt(VTBits, 1)) == Mask)
1639          return VTBits;
1640
1641        // If we are subtracting one from a positive number, there is no carry
1642        // out of the result.
1643        if (KnownZero.isNegative())
1644          return Tmp;
1645      }
1646
1647    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1648    if (Tmp2 == 1) return 1;
1649      return std::min(Tmp, Tmp2)-1;
1650    break;
1651
1652  case ISD::SUB:
1653    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1654    if (Tmp2 == 1) return 1;
1655
1656    // Handle NEG.
1657    if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1658      if (CLHS->isNullValue()) {
1659        APInt KnownZero, KnownOne;
1660        APInt Mask = APInt::getAllOnesValue(VTBits);
1661        ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1662        // If the input is known to be 0 or 1, the output is 0/-1, which is all
1663        // sign bits set.
1664        if ((KnownZero | APInt(VTBits, 1)) == Mask)
1665          return VTBits;
1666
1667        // If the input is known to be positive (the sign bit is known clear),
1668        // the output of the NEG has the same number of sign bits as the input.
1669        if (KnownZero.isNegative())
1670          return Tmp2;
1671
1672        // Otherwise, we treat this like a SUB.
1673      }
1674
1675    // Sub can have at most one carry bit.  Thus we know that the output
1676    // is, at worst, one more bit than the inputs.
1677    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1678    if (Tmp == 1) return 1;  // Early out.
1679      return std::min(Tmp, Tmp2)-1;
1680    break;
1681  case ISD::TRUNCATE:
1682    // FIXME: it's tricky to do anything useful for this, but it is an important
1683    // case for targets like X86.
1684    break;
1685  }
1686
1687  // Handle LOADX separately here. EXTLOAD case will fallthrough.
1688  if (Op.getOpcode() == ISD::LOAD) {
1689    LoadSDNode *LD = cast<LoadSDNode>(Op);
1690    unsigned ExtType = LD->getExtensionType();
1691    switch (ExtType) {
1692    default: break;
1693    case ISD::SEXTLOAD:    // '17' bits known
1694      Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1695      return VTBits-Tmp+1;
1696    case ISD::ZEXTLOAD:    // '16' bits known
1697      Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1698      return VTBits-Tmp;
1699    }
1700  }
1701
1702  // Allow the target to implement this method for its nodes.
1703  if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1704      Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1705      Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1706      Op.getOpcode() == ISD::INTRINSIC_VOID) {
1707    unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1708    if (NumBits > 1) return NumBits;
1709  }
1710
1711  // Finally, if we can prove that the top bits of the result are 0's or 1's,
1712  // use this information.
1713  APInt KnownZero, KnownOne;
1714  APInt Mask = APInt::getAllOnesValue(VTBits);
1715  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1716
1717  if (KnownZero.isNegative()) {        // sign bit is 0
1718    Mask = KnownZero;
1719  } else if (KnownOne.isNegative()) {  // sign bit is 1;
1720    Mask = KnownOne;
1721  } else {
1722    // Nothing known.
1723    return 1;
1724  }
1725
1726  // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1727  // the number of identical bits in the top of the input value.
1728  Mask = ~Mask;
1729  Mask <<= Mask.getBitWidth()-VTBits;
1730  // Return # leading zeros.  We use 'min' here in case Val was zero before
1731  // shifting.  We don't want to return '64' as for an i32 "0".
1732  return std::min(VTBits, Mask.countLeadingZeros());
1733}
1734
1735
1736bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1737  GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1738  if (!GA) return false;
1739  GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1740  if (!GV) return false;
1741  MachineModuleInfo *MMI = getMachineModuleInfo();
1742  return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1743}
1744
1745
1746/// getNode - Gets or creates the specified node.
1747///
1748SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1749  FoldingSetNodeID ID;
1750  AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1751  void *IP = 0;
1752  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1753    return SDOperand(E, 0);
1754  SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1755  CSEMap.InsertNode(N, IP);
1756
1757  AllNodes.push_back(N);
1758  return SDOperand(N, 0);
1759}
1760
1761SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1762                                SDOperand Operand) {
1763  // Constant fold unary operations with an integer constant operand.
1764  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1765    const APInt &Val = C->getAPIntValue();
1766    unsigned BitWidth = MVT::getSizeInBits(VT);
1767    switch (Opcode) {
1768    default: break;
1769    case ISD::SIGN_EXTEND:
1770      return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1771    case ISD::ANY_EXTEND:
1772    case ISD::ZERO_EXTEND:
1773    case ISD::TRUNCATE:
1774      return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1775    case ISD::UINT_TO_FP:
1776    case ISD::SINT_TO_FP: {
1777      const uint64_t zero[] = {0, 0};
1778      // No compile time operations on this type.
1779      if (VT==MVT::ppcf128)
1780        break;
1781      APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1782      (void)apf.convertFromAPInt(Val,
1783                                 Opcode==ISD::SINT_TO_FP,
1784                                 APFloat::rmNearestTiesToEven);
1785      return getConstantFP(apf, VT);
1786    }
1787    case ISD::BIT_CONVERT:
1788      if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1789        return getConstantFP(Val.bitsToFloat(), VT);
1790      else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1791        return getConstantFP(Val.bitsToDouble(), VT);
1792      break;
1793    case ISD::BSWAP:
1794      return getConstant(Val.byteSwap(), VT);
1795    case ISD::CTPOP:
1796      return getConstant(Val.countPopulation(), VT);
1797    case ISD::CTLZ:
1798      return getConstant(Val.countLeadingZeros(), VT);
1799    case ISD::CTTZ:
1800      return getConstant(Val.countTrailingZeros(), VT);
1801    }
1802  }
1803
1804  // Constant fold unary operations with a floating point constant operand.
1805  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1806    APFloat V = C->getValueAPF();    // make copy
1807    if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1808      switch (Opcode) {
1809      case ISD::FNEG:
1810        V.changeSign();
1811        return getConstantFP(V, VT);
1812      case ISD::FABS:
1813        V.clearSign();
1814        return getConstantFP(V, VT);
1815      case ISD::FP_ROUND:
1816      case ISD::FP_EXTEND:
1817        // This can return overflow, underflow, or inexact; we don't care.
1818        // FIXME need to be more flexible about rounding mode.
1819        (void)V.convert(*MVTToAPFloatSemantics(VT),
1820                        APFloat::rmNearestTiesToEven);
1821        return getConstantFP(V, VT);
1822      case ISD::FP_TO_SINT:
1823      case ISD::FP_TO_UINT: {
1824        integerPart x;
1825        assert(integerPartWidth >= 64);
1826        // FIXME need to be more flexible about rounding mode.
1827        APFloat::opStatus s = V.convertToInteger(&x, 64U,
1828                              Opcode==ISD::FP_TO_SINT,
1829                              APFloat::rmTowardZero);
1830        if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
1831          break;
1832        return getConstant(x, VT);
1833      }
1834      case ISD::BIT_CONVERT:
1835        if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1836          return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1837        else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1838          return getConstant(V.convertToAPInt().getZExtValue(), VT);
1839        break;
1840      }
1841    }
1842  }
1843
1844  unsigned OpOpcode = Operand.Val->getOpcode();
1845  switch (Opcode) {
1846  case ISD::TokenFactor:
1847    return Operand;         // Factor of one node?  No factor.
1848  case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1849  case ISD::FP_EXTEND:
1850    assert(MVT::isFloatingPoint(VT) &&
1851           MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1852    if (Operand.getValueType() == VT) return Operand;  // noop conversion.
1853    if (Operand.getOpcode() == ISD::UNDEF)
1854      return getNode(ISD::UNDEF, VT);
1855    break;
1856  case ISD::SIGN_EXTEND:
1857    assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1858           "Invalid SIGN_EXTEND!");
1859    if (Operand.getValueType() == VT) return Operand;   // noop extension
1860    assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1861           && "Invalid sext node, dst < src!");
1862    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1863      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1864    break;
1865  case ISD::ZERO_EXTEND:
1866    assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1867           "Invalid ZERO_EXTEND!");
1868    if (Operand.getValueType() == VT) return Operand;   // noop extension
1869    assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1870           && "Invalid zext node, dst < src!");
1871    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
1872      return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1873    break;
1874  case ISD::ANY_EXTEND:
1875    assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1876           "Invalid ANY_EXTEND!");
1877    if (Operand.getValueType() == VT) return Operand;   // noop extension
1878    assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1879           && "Invalid anyext node, dst < src!");
1880    if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1881      // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
1882      return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1883    break;
1884  case ISD::TRUNCATE:
1885    assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1886           "Invalid TRUNCATE!");
1887    if (Operand.getValueType() == VT) return Operand;   // noop truncate
1888    assert(MVT::getSizeInBits(Operand.getValueType()) > MVT::getSizeInBits(VT)
1889           && "Invalid truncate node, src < dst!");
1890    if (OpOpcode == ISD::TRUNCATE)
1891      return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1892    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1893             OpOpcode == ISD::ANY_EXTEND) {
1894      // If the source is smaller than the dest, we still need an extend.
1895      if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1896          < MVT::getSizeInBits(VT))
1897        return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1898      else if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1899               > MVT::getSizeInBits(VT))
1900        return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1901      else
1902        return Operand.Val->getOperand(0);
1903    }
1904    break;
1905  case ISD::BIT_CONVERT:
1906    // Basic sanity checking.
1907    assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1908           && "Cannot BIT_CONVERT between types of different sizes!");
1909    if (VT == Operand.getValueType()) return Operand;  // noop conversion.
1910    if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
1911      return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1912    if (OpOpcode == ISD::UNDEF)
1913      return getNode(ISD::UNDEF, VT);
1914    break;
1915  case ISD::SCALAR_TO_VECTOR:
1916    assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1917           MVT::getVectorElementType(VT) == Operand.getValueType() &&
1918           "Illegal SCALAR_TO_VECTOR node!");
1919    if (OpOpcode == ISD::UNDEF)
1920      return getNode(ISD::UNDEF, VT);
1921    // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
1922    if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
1923        isa<ConstantSDNode>(Operand.getOperand(1)) &&
1924        Operand.getConstantOperandVal(1) == 0 &&
1925        Operand.getOperand(0).getValueType() == VT)
1926      return Operand.getOperand(0);
1927    break;
1928  case ISD::FNEG:
1929    if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
1930      return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1931                     Operand.Val->getOperand(0));
1932    if (OpOpcode == ISD::FNEG)  // --X -> X
1933      return Operand.Val->getOperand(0);
1934    break;
1935  case ISD::FABS:
1936    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
1937      return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1938    break;
1939  }
1940
1941  SDNode *N;
1942  SDVTList VTs = getVTList(VT);
1943  if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1944    FoldingSetNodeID ID;
1945    SDOperand Ops[1] = { Operand };
1946    AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
1947    void *IP = 0;
1948    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1949      return SDOperand(E, 0);
1950    N = new UnarySDNode(Opcode, VTs, Operand);
1951    CSEMap.InsertNode(N, IP);
1952  } else {
1953    N = new UnarySDNode(Opcode, VTs, Operand);
1954  }
1955  AllNodes.push_back(N);
1956  return SDOperand(N, 0);
1957}
1958
1959
1960
1961SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1962                                SDOperand N1, SDOperand N2) {
1963  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1964  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1965  switch (Opcode) {
1966  default: break;
1967  case ISD::TokenFactor:
1968    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1969           N2.getValueType() == MVT::Other && "Invalid token factor!");
1970    // Fold trivial token factors.
1971    if (N1.getOpcode() == ISD::EntryToken) return N2;
1972    if (N2.getOpcode() == ISD::EntryToken) return N1;
1973    break;
1974  case ISD::AND:
1975    assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1976           N1.getValueType() == VT && "Binary operator types must match!");
1977    // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
1978    // worth handling here.
1979    if (N2C && N2C->isNullValue())
1980      return N2;
1981    if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
1982      return N1;
1983    break;
1984  case ISD::OR:
1985  case ISD::XOR:
1986    assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1987           N1.getValueType() == VT && "Binary operator types must match!");
1988    // (X ^| 0) -> X.  This commonly occurs when legalizing i64 values, so it's
1989    // worth handling here.
1990    if (N2C && N2C->isNullValue())
1991      return N1;
1992    break;
1993  case ISD::UDIV:
1994  case ISD::UREM:
1995  case ISD::MULHU:
1996  case ISD::MULHS:
1997    assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1998    // fall through
1999  case ISD::ADD:
2000  case ISD::SUB:
2001  case ISD::MUL:
2002  case ISD::SDIV:
2003  case ISD::SREM:
2004  case ISD::FADD:
2005  case ISD::FSUB:
2006  case ISD::FMUL:
2007  case ISD::FDIV:
2008  case ISD::FREM:
2009    assert(N1.getValueType() == N2.getValueType() &&
2010           N1.getValueType() == VT && "Binary operator types must match!");
2011    break;
2012  case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
2013    assert(N1.getValueType() == VT &&
2014           MVT::isFloatingPoint(N1.getValueType()) &&
2015           MVT::isFloatingPoint(N2.getValueType()) &&
2016           "Invalid FCOPYSIGN!");
2017    break;
2018  case ISD::SHL:
2019  case ISD::SRA:
2020  case ISD::SRL:
2021  case ISD::ROTL:
2022  case ISD::ROTR:
2023    assert(VT == N1.getValueType() &&
2024           "Shift operators return type must be the same as their first arg");
2025    assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
2026           VT != MVT::i1 && "Shifts only work on integers");
2027    break;
2028  case ISD::FP_ROUND_INREG: {
2029    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2030    assert(VT == N1.getValueType() && "Not an inreg round!");
2031    assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
2032           "Cannot FP_ROUND_INREG integer types");
2033    assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2034           "Not rounding down!");
2035    if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
2036    break;
2037  }
2038  case ISD::FP_ROUND:
2039    assert(MVT::isFloatingPoint(VT) &&
2040           MVT::isFloatingPoint(N1.getValueType()) &&
2041           MVT::getSizeInBits(VT) <= MVT::getSizeInBits(N1.getValueType()) &&
2042           isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2043    if (N1.getValueType() == VT) return N1;  // noop conversion.
2044    break;
2045  case ISD::AssertSext:
2046  case ISD::AssertZext: {
2047    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2048    assert(VT == N1.getValueType() && "Not an inreg extend!");
2049    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2050           "Cannot *_EXTEND_INREG FP types");
2051    assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2052           "Not extending!");
2053    if (VT == EVT) return N1; // noop assertion.
2054    break;
2055  }
2056  case ISD::SIGN_EXTEND_INREG: {
2057    MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2058    assert(VT == N1.getValueType() && "Not an inreg extend!");
2059    assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2060           "Cannot *_EXTEND_INREG FP types");
2061    assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2062           "Not extending!");
2063    if (EVT == VT) return N1;  // Not actually extending
2064
2065    if (N1C) {
2066      APInt Val = N1C->getAPIntValue();
2067      unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
2068      Val <<= Val.getBitWidth()-FromBits;
2069      Val = Val.ashr(Val.getBitWidth()-FromBits);
2070      return getConstant(Val, VT);
2071    }
2072    break;
2073  }
2074  case ISD::EXTRACT_VECTOR_ELT:
2075    assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2076
2077    // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2078    if (N1.getOpcode() == ISD::UNDEF)
2079      return getNode(ISD::UNDEF, VT);
2080
2081    // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2082    // expanding copies of large vectors from registers.
2083    if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2084        N1.getNumOperands() > 0) {
2085      unsigned Factor =
2086        MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2087      return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2088                     N1.getOperand(N2C->getValue() / Factor),
2089                     getConstant(N2C->getValue() % Factor, N2.getValueType()));
2090    }
2091
2092    // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2093    // expanding large vector constants.
2094    if (N1.getOpcode() == ISD::BUILD_VECTOR)
2095      return N1.getOperand(N2C->getValue());
2096
2097    // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2098    // operations are lowered to scalars.
2099    if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2100      if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2101        if (IEC == N2C)
2102          return N1.getOperand(1);
2103        else
2104          return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2105      }
2106    break;
2107  case ISD::EXTRACT_ELEMENT:
2108    assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2109    assert(!MVT::isVector(N1.getValueType()) &&
2110           MVT::isInteger(N1.getValueType()) &&
2111           !MVT::isVector(VT) && MVT::isInteger(VT) &&
2112           "EXTRACT_ELEMENT only applies to integers!");
2113
2114    // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2115    // 64-bit integers into 32-bit parts.  Instead of building the extract of
2116    // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2117    if (N1.getOpcode() == ISD::BUILD_PAIR)
2118      return N1.getOperand(N2C->getValue());
2119
2120    // EXTRACT_ELEMENT of a constant int is also very common.
2121    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2122      unsigned ElementSize = MVT::getSizeInBits(VT);
2123      unsigned Shift = ElementSize * N2C->getValue();
2124      APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2125      return getConstant(ShiftedVal.trunc(ElementSize), VT);
2126    }
2127    break;
2128  case ISD::EXTRACT_SUBVECTOR:
2129    if (N1.getValueType() == VT) // Trivial extraction.
2130      return N1;
2131    break;
2132  }
2133
2134  if (N1C) {
2135    if (N2C) {
2136      APInt C1 = N1C->getAPIntValue(), C2 = N2C->getAPIntValue();
2137      switch (Opcode) {
2138      case ISD::ADD: return getConstant(C1 + C2, VT);
2139      case ISD::SUB: return getConstant(C1 - C2, VT);
2140      case ISD::MUL: return getConstant(C1 * C2, VT);
2141      case ISD::UDIV:
2142        if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2143        break;
2144      case ISD::UREM :
2145        if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2146        break;
2147      case ISD::SDIV :
2148        if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2149        break;
2150      case ISD::SREM :
2151        if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2152        break;
2153      case ISD::AND  : return getConstant(C1 & C2, VT);
2154      case ISD::OR   : return getConstant(C1 | C2, VT);
2155      case ISD::XOR  : return getConstant(C1 ^ C2, VT);
2156      case ISD::SHL  : return getConstant(C1 << C2, VT);
2157      case ISD::SRL  : return getConstant(C1.lshr(C2), VT);
2158      case ISD::SRA  : return getConstant(C1.ashr(C2), VT);
2159      case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2160      case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2161      default: break;
2162      }
2163    } else {      // Cannonicalize constant to RHS if commutative
2164      if (isCommutativeBinOp(Opcode)) {
2165        std::swap(N1C, N2C);
2166        std::swap(N1, N2);
2167      }
2168    }
2169  }
2170
2171  // Constant fold FP operations.
2172  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2173  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2174  if (N1CFP) {
2175    if (!N2CFP && isCommutativeBinOp(Opcode)) {
2176      // Cannonicalize constant to RHS if commutative
2177      std::swap(N1CFP, N2CFP);
2178      std::swap(N1, N2);
2179    } else if (N2CFP && VT != MVT::ppcf128) {
2180      APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2181      APFloat::opStatus s;
2182      switch (Opcode) {
2183      case ISD::FADD:
2184        s = V1.add(V2, APFloat::rmNearestTiesToEven);
2185        if (s != APFloat::opInvalidOp)
2186          return getConstantFP(V1, VT);
2187        break;
2188      case ISD::FSUB:
2189        s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2190        if (s!=APFloat::opInvalidOp)
2191          return getConstantFP(V1, VT);
2192        break;
2193      case ISD::FMUL:
2194        s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2195        if (s!=APFloat::opInvalidOp)
2196          return getConstantFP(V1, VT);
2197        break;
2198      case ISD::FDIV:
2199        s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2200        if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2201          return getConstantFP(V1, VT);
2202        break;
2203      case ISD::FREM :
2204        s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2205        if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2206          return getConstantFP(V1, VT);
2207        break;
2208      case ISD::FCOPYSIGN:
2209        V1.copySign(V2);
2210        return getConstantFP(V1, VT);
2211      default: break;
2212      }
2213    }
2214  }
2215
2216  // Canonicalize an UNDEF to the RHS, even over a constant.
2217  if (N1.getOpcode() == ISD::UNDEF) {
2218    if (isCommutativeBinOp(Opcode)) {
2219      std::swap(N1, N2);
2220    } else {
2221      switch (Opcode) {
2222      case ISD::FP_ROUND_INREG:
2223      case ISD::SIGN_EXTEND_INREG:
2224      case ISD::SUB:
2225      case ISD::FSUB:
2226      case ISD::FDIV:
2227      case ISD::FREM:
2228      case ISD::SRA:
2229        return N1;     // fold op(undef, arg2) -> undef
2230      case ISD::UDIV:
2231      case ISD::SDIV:
2232      case ISD::UREM:
2233      case ISD::SREM:
2234      case ISD::SRL:
2235      case ISD::SHL:
2236        if (!MVT::isVector(VT))
2237          return getConstant(0, VT);    // fold op(undef, arg2) -> 0
2238        // For vectors, we can't easily build an all zero vector, just return
2239        // the LHS.
2240        return N2;
2241      }
2242    }
2243  }
2244
2245  // Fold a bunch of operators when the RHS is undef.
2246  if (N2.getOpcode() == ISD::UNDEF) {
2247    switch (Opcode) {
2248    case ISD::ADD:
2249    case ISD::ADDC:
2250    case ISD::ADDE:
2251    case ISD::SUB:
2252    case ISD::FADD:
2253    case ISD::FSUB:
2254    case ISD::FMUL:
2255    case ISD::FDIV:
2256    case ISD::FREM:
2257    case ISD::UDIV:
2258    case ISD::SDIV:
2259    case ISD::UREM:
2260    case ISD::SREM:
2261    case ISD::XOR:
2262      return N2;       // fold op(arg1, undef) -> undef
2263    case ISD::MUL:
2264    case ISD::AND:
2265    case ISD::SRL:
2266    case ISD::SHL:
2267      if (!MVT::isVector(VT))
2268        return getConstant(0, VT);  // fold op(arg1, undef) -> 0
2269      // For vectors, we can't easily build an all zero vector, just return
2270      // the LHS.
2271      return N1;
2272    case ISD::OR:
2273      if (!MVT::isVector(VT))
2274        return getConstant(MVT::getIntVTBitMask(VT), VT);
2275      // For vectors, we can't easily build an all one vector, just return
2276      // the LHS.
2277      return N1;
2278    case ISD::SRA:
2279      return N1;
2280    }
2281  }
2282
2283  // Memoize this node if possible.
2284  SDNode *N;
2285  SDVTList VTs = getVTList(VT);
2286  if (VT != MVT::Flag) {
2287    SDOperand Ops[] = { N1, N2 };
2288    FoldingSetNodeID ID;
2289    AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2290    void *IP = 0;
2291    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2292      return SDOperand(E, 0);
2293    N = new BinarySDNode(Opcode, VTs, N1, N2);
2294    CSEMap.InsertNode(N, IP);
2295  } else {
2296    N = new BinarySDNode(Opcode, VTs, N1, N2);
2297  }
2298
2299  AllNodes.push_back(N);
2300  return SDOperand(N, 0);
2301}
2302
2303SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2304                                SDOperand N1, SDOperand N2, SDOperand N3) {
2305  // Perform various simplifications.
2306  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2307  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2308  switch (Opcode) {
2309  case ISD::SETCC: {
2310    // Use FoldSetCC to simplify SETCC's.
2311    SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2312    if (Simp.Val) return Simp;
2313    break;
2314  }
2315  case ISD::SELECT:
2316    if (N1C) {
2317     if (N1C->getValue())
2318        return N2;             // select true, X, Y -> X
2319      else
2320        return N3;             // select false, X, Y -> Y
2321    }
2322
2323    if (N2 == N3) return N2;   // select C, X, X -> X
2324    break;
2325  case ISD::BRCOND:
2326    if (N2C) {
2327      if (N2C->getValue()) // Unconditional branch
2328        return getNode(ISD::BR, MVT::Other, N1, N3);
2329      else
2330        return N1;         // Never-taken branch
2331    }
2332    break;
2333  case ISD::VECTOR_SHUFFLE:
2334    assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2335           MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2336           N3.getOpcode() == ISD::BUILD_VECTOR &&
2337           MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2338           "Illegal VECTOR_SHUFFLE node!");
2339    break;
2340  case ISD::BIT_CONVERT:
2341    // Fold bit_convert nodes from a type to themselves.
2342    if (N1.getValueType() == VT)
2343      return N1;
2344    break;
2345  }
2346
2347  // Memoize node if it doesn't produce a flag.
2348  SDNode *N;
2349  SDVTList VTs = getVTList(VT);
2350  if (VT != MVT::Flag) {
2351    SDOperand Ops[] = { N1, N2, N3 };
2352    FoldingSetNodeID ID;
2353    AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2354    void *IP = 0;
2355    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2356      return SDOperand(E, 0);
2357    N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2358    CSEMap.InsertNode(N, IP);
2359  } else {
2360    N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2361  }
2362  AllNodes.push_back(N);
2363  return SDOperand(N, 0);
2364}
2365
2366SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2367                                SDOperand N1, SDOperand N2, SDOperand N3,
2368                                SDOperand N4) {
2369  SDOperand Ops[] = { N1, N2, N3, N4 };
2370  return getNode(Opcode, VT, Ops, 4);
2371}
2372
2373SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2374                                SDOperand N1, SDOperand N2, SDOperand N3,
2375                                SDOperand N4, SDOperand N5) {
2376  SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2377  return getNode(Opcode, VT, Ops, 5);
2378}
2379
2380SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dest,
2381                                  SDOperand Src, SDOperand Size,
2382                                  SDOperand Align,
2383                                  SDOperand AlwaysInline) {
2384  SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2385  return getNode(ISD::MEMCPY, MVT::Other, Ops, 6);
2386}
2387
2388SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dest,
2389                                  SDOperand Src, SDOperand Size,
2390                                  SDOperand Align,
2391                                  SDOperand AlwaysInline) {
2392  SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2393  return getNode(ISD::MEMMOVE, MVT::Other, Ops, 6);
2394}
2395
2396SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dest,
2397                                  SDOperand Src, SDOperand Size,
2398                                  SDOperand Align,
2399                                  SDOperand AlwaysInline) {
2400  SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2401  return getNode(ISD::MEMSET, MVT::Other, Ops, 6);
2402}
2403
2404SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
2405                                  SDOperand Ptr, SDOperand Cmp,
2406                                  SDOperand Swp, MVT::ValueType VT) {
2407  assert(Opcode == ISD::ATOMIC_LCS && "Invalid Atomic Op");
2408  assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
2409  SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
2410  FoldingSetNodeID ID;
2411  SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
2412  AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
2413  ID.AddInteger((unsigned int)VT);
2414  void* IP = 0;
2415  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2416    return SDOperand(E, 0);
2417  SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, VT);
2418  CSEMap.InsertNode(N, IP);
2419  AllNodes.push_back(N);
2420  return SDOperand(N, 0);
2421}
2422
2423SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
2424                                  SDOperand Ptr, SDOperand Val,
2425                                  MVT::ValueType VT) {
2426  assert((Opcode == ISD::ATOMIC_LAS || Opcode == ISD::ATOMIC_SWAP)
2427         && "Invalid Atomic Op");
2428  SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
2429  FoldingSetNodeID ID;
2430  SDOperand Ops[] = {Chain, Ptr, Val};
2431  AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2432  ID.AddInteger((unsigned int)VT);
2433  void* IP = 0;
2434  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2435    return SDOperand(E, 0);
2436  SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, VT);
2437  CSEMap.InsertNode(N, IP);
2438  AllNodes.push_back(N);
2439  return SDOperand(N, 0);
2440}
2441
2442SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2443                                SDOperand Chain, SDOperand Ptr,
2444                                const Value *SV, int SVOffset,
2445                                bool isVolatile, unsigned Alignment) {
2446  if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2447    const Type *Ty = 0;
2448    if (VT != MVT::iPTR) {
2449      Ty = MVT::getTypeForValueType(VT);
2450    } else if (SV) {
2451      const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2452      assert(PT && "Value for load must be a pointer");
2453      Ty = PT->getElementType();
2454    }
2455    assert(Ty && "Could not get type information for load");
2456    Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2457  }
2458  SDVTList VTs = getVTList(VT, MVT::Other);
2459  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2460  SDOperand Ops[] = { Chain, Ptr, Undef };
2461  FoldingSetNodeID ID;
2462  AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2463  ID.AddInteger(ISD::UNINDEXED);
2464  ID.AddInteger(ISD::NON_EXTLOAD);
2465  ID.AddInteger((unsigned int)VT);
2466  ID.AddInteger(Alignment);
2467  ID.AddInteger(isVolatile);
2468  void *IP = 0;
2469  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2470    return SDOperand(E, 0);
2471  SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED,
2472                             ISD::NON_EXTLOAD, VT, SV, SVOffset, Alignment,
2473                             isVolatile);
2474  CSEMap.InsertNode(N, IP);
2475  AllNodes.push_back(N);
2476  return SDOperand(N, 0);
2477}
2478
2479SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2480                                   SDOperand Chain, SDOperand Ptr,
2481                                   const Value *SV,
2482                                   int SVOffset, MVT::ValueType EVT,
2483                                   bool isVolatile, unsigned Alignment) {
2484  // If they are asking for an extending load from/to the same thing, return a
2485  // normal load.
2486  if (VT == EVT)
2487    return getLoad(VT, Chain, Ptr, SV, SVOffset, isVolatile, Alignment);
2488
2489  if (MVT::isVector(VT))
2490    assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2491  else
2492    assert(MVT::getSizeInBits(EVT) < MVT::getSizeInBits(VT) &&
2493           "Should only be an extending load, not truncating!");
2494  assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2495         "Cannot sign/zero extend a FP/Vector load!");
2496  assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2497         "Cannot convert from FP to Int or Int -> FP!");
2498
2499  if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2500    const Type *Ty = 0;
2501    if (VT != MVT::iPTR) {
2502      Ty = MVT::getTypeForValueType(VT);
2503    } else if (SV) {
2504      const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2505      assert(PT && "Value for load must be a pointer");
2506      Ty = PT->getElementType();
2507    }
2508    assert(Ty && "Could not get type information for load");
2509    Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2510  }
2511  SDVTList VTs = getVTList(VT, MVT::Other);
2512  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2513  SDOperand Ops[] = { Chain, Ptr, Undef };
2514  FoldingSetNodeID ID;
2515  AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2516  ID.AddInteger(ISD::UNINDEXED);
2517  ID.AddInteger(ExtType);
2518  ID.AddInteger((unsigned int)EVT);
2519  ID.AddInteger(Alignment);
2520  ID.AddInteger(isVolatile);
2521  void *IP = 0;
2522  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2523    return SDOperand(E, 0);
2524  SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED, ExtType, EVT,
2525                             SV, SVOffset, Alignment, isVolatile);
2526  CSEMap.InsertNode(N, IP);
2527  AllNodes.push_back(N);
2528  return SDOperand(N, 0);
2529}
2530
2531SDOperand
2532SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2533                             SDOperand Offset, ISD::MemIndexedMode AM) {
2534  LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2535  assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2536         "Load is already a indexed load!");
2537  MVT::ValueType VT = OrigLoad.getValueType();
2538  SDVTList VTs = getVTList(VT, Base.getValueType(), MVT::Other);
2539  SDOperand Ops[] = { LD->getChain(), Base, Offset };
2540  FoldingSetNodeID ID;
2541  AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2542  ID.AddInteger(AM);
2543  ID.AddInteger(LD->getExtensionType());
2544  ID.AddInteger((unsigned int)(LD->getMemoryVT()));
2545  ID.AddInteger(LD->getAlignment());
2546  ID.AddInteger(LD->isVolatile());
2547  void *IP = 0;
2548  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2549    return SDOperand(E, 0);
2550  SDNode *N = new LoadSDNode(Ops, VTs, AM,
2551                             LD->getExtensionType(), LD->getMemoryVT(),
2552                             LD->getSrcValue(), LD->getSrcValueOffset(),
2553                             LD->getAlignment(), LD->isVolatile());
2554  CSEMap.InsertNode(N, IP);
2555  AllNodes.push_back(N);
2556  return SDOperand(N, 0);
2557}
2558
2559SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2560                                 SDOperand Ptr, const Value *SV, int SVOffset,
2561                                 bool isVolatile, unsigned Alignment) {
2562  MVT::ValueType VT = Val.getValueType();
2563
2564  if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2565    const Type *Ty = 0;
2566    if (VT != MVT::iPTR) {
2567      Ty = MVT::getTypeForValueType(VT);
2568    } else if (SV) {
2569      const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2570      assert(PT && "Value for store must be a pointer");
2571      Ty = PT->getElementType();
2572    }
2573    assert(Ty && "Could not get type information for store");
2574    Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2575  }
2576  SDVTList VTs = getVTList(MVT::Other);
2577  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2578  SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2579  FoldingSetNodeID ID;
2580  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2581  ID.AddInteger(ISD::UNINDEXED);
2582  ID.AddInteger(false);
2583  ID.AddInteger((unsigned int)VT);
2584  ID.AddInteger(Alignment);
2585  ID.AddInteger(isVolatile);
2586  void *IP = 0;
2587  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2588    return SDOperand(E, 0);
2589  SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
2590                              VT, SV, SVOffset, Alignment, isVolatile);
2591  CSEMap.InsertNode(N, IP);
2592  AllNodes.push_back(N);
2593  return SDOperand(N, 0);
2594}
2595
2596SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
2597                                      SDOperand Ptr, const Value *SV,
2598                                      int SVOffset, MVT::ValueType SVT,
2599                                      bool isVolatile, unsigned Alignment) {
2600  MVT::ValueType VT = Val.getValueType();
2601
2602  if (VT == SVT)
2603    return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
2604
2605  assert(MVT::getSizeInBits(VT) > MVT::getSizeInBits(SVT) &&
2606         "Not a truncation?");
2607  assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
2608         "Can't do FP-INT conversion!");
2609
2610  if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2611    const Type *Ty = 0;
2612    if (VT != MVT::iPTR) {
2613      Ty = MVT::getTypeForValueType(VT);
2614    } else if (SV) {
2615      const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2616      assert(PT && "Value for store must be a pointer");
2617      Ty = PT->getElementType();
2618    }
2619    assert(Ty && "Could not get type information for store");
2620    Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2621  }
2622  SDVTList VTs = getVTList(MVT::Other);
2623  SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2624  SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2625  FoldingSetNodeID ID;
2626  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2627  ID.AddInteger(ISD::UNINDEXED);
2628  ID.AddInteger(1);
2629  ID.AddInteger((unsigned int)SVT);
2630  ID.AddInteger(Alignment);
2631  ID.AddInteger(isVolatile);
2632  void *IP = 0;
2633  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2634    return SDOperand(E, 0);
2635  SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
2636                              SVT, SV, SVOffset, Alignment, isVolatile);
2637  CSEMap.InsertNode(N, IP);
2638  AllNodes.push_back(N);
2639  return SDOperand(N, 0);
2640}
2641
2642SDOperand
2643SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
2644                              SDOperand Offset, ISD::MemIndexedMode AM) {
2645  StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
2646  assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
2647         "Store is already a indexed store!");
2648  SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
2649  SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
2650  FoldingSetNodeID ID;
2651  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2652  ID.AddInteger(AM);
2653  ID.AddInteger(ST->isTruncatingStore());
2654  ID.AddInteger((unsigned int)(ST->getMemoryVT()));
2655  ID.AddInteger(ST->getAlignment());
2656  ID.AddInteger(ST->isVolatile());
2657  void *IP = 0;
2658  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2659    return SDOperand(E, 0);
2660  SDNode *N = new StoreSDNode(Ops, VTs, AM,
2661                              ST->isTruncatingStore(), ST->getMemoryVT(),
2662                              ST->getSrcValue(), ST->getSrcValueOffset(),
2663                              ST->getAlignment(), ST->isVolatile());
2664  CSEMap.InsertNode(N, IP);
2665  AllNodes.push_back(N);
2666  return SDOperand(N, 0);
2667}
2668
2669SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
2670                                 SDOperand Chain, SDOperand Ptr,
2671                                 SDOperand SV) {
2672  SDOperand Ops[] = { Chain, Ptr, SV };
2673  return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
2674}
2675
2676SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2677                                const SDOperand *Ops, unsigned NumOps) {
2678  switch (NumOps) {
2679  case 0: return getNode(Opcode, VT);
2680  case 1: return getNode(Opcode, VT, Ops[0]);
2681  case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
2682  case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
2683  default: break;
2684  }
2685
2686  switch (Opcode) {
2687  default: break;
2688  case ISD::SELECT_CC: {
2689    assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
2690    assert(Ops[0].getValueType() == Ops[1].getValueType() &&
2691           "LHS and RHS of condition must have same type!");
2692    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2693           "True and False arms of SelectCC must have same type!");
2694    assert(Ops[2].getValueType() == VT &&
2695           "select_cc node must be of same type as true and false value!");
2696    break;
2697  }
2698  case ISD::BR_CC: {
2699    assert(NumOps == 5 && "BR_CC takes 5 operands!");
2700    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2701           "LHS/RHS of comparison should match types!");
2702    break;
2703  }
2704  }
2705
2706  // Memoize nodes.
2707  SDNode *N;
2708  SDVTList VTs = getVTList(VT);
2709  if (VT != MVT::Flag) {
2710    FoldingSetNodeID ID;
2711    AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
2712    void *IP = 0;
2713    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2714      return SDOperand(E, 0);
2715    N = new SDNode(Opcode, VTs, Ops, NumOps);
2716    CSEMap.InsertNode(N, IP);
2717  } else {
2718    N = new SDNode(Opcode, VTs, Ops, NumOps);
2719  }
2720  AllNodes.push_back(N);
2721  return SDOperand(N, 0);
2722}
2723
2724SDOperand SelectionDAG::getNode(unsigned Opcode,
2725                                std::vector<MVT::ValueType> &ResultTys,
2726                                const SDOperand *Ops, unsigned NumOps) {
2727  return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
2728                 Ops, NumOps);
2729}
2730
2731SDOperand SelectionDAG::getNode(unsigned Opcode,
2732                                const MVT::ValueType *VTs, unsigned NumVTs,
2733                                const SDOperand *Ops, unsigned NumOps) {
2734  if (NumVTs == 1)
2735    return getNode(Opcode, VTs[0], Ops, NumOps);
2736  return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
2737}
2738
2739SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2740                                const SDOperand *Ops, unsigned NumOps) {
2741  if (VTList.NumVTs == 1)
2742    return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
2743
2744  switch (Opcode) {
2745  // FIXME: figure out how to safely handle things like
2746  // int foo(int x) { return 1 << (x & 255); }
2747  // int bar() { return foo(256); }
2748#if 0
2749  case ISD::SRA_PARTS:
2750  case ISD::SRL_PARTS:
2751  case ISD::SHL_PARTS:
2752    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2753        cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
2754      return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2755    else if (N3.getOpcode() == ISD::AND)
2756      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
2757        // If the and is only masking out bits that cannot effect the shift,
2758        // eliminate the and.
2759        unsigned NumBits = MVT::getSizeInBits(VT)*2;
2760        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2761          return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2762      }
2763    break;
2764#endif
2765  }
2766
2767  // Memoize the node unless it returns a flag.
2768  SDNode *N;
2769  if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
2770    FoldingSetNodeID ID;
2771    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
2772    void *IP = 0;
2773    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2774      return SDOperand(E, 0);
2775    if (NumOps == 1)
2776      N = new UnarySDNode(Opcode, VTList, Ops[0]);
2777    else if (NumOps == 2)
2778      N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2779    else if (NumOps == 3)
2780      N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2781    else
2782      N = new SDNode(Opcode, VTList, Ops, NumOps);
2783    CSEMap.InsertNode(N, IP);
2784  } else {
2785    if (NumOps == 1)
2786      N = new UnarySDNode(Opcode, VTList, Ops[0]);
2787    else if (NumOps == 2)
2788      N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2789    else if (NumOps == 3)
2790      N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2791    else
2792      N = new SDNode(Opcode, VTList, Ops, NumOps);
2793  }
2794  AllNodes.push_back(N);
2795  return SDOperand(N, 0);
2796}
2797
2798SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
2799  return getNode(Opcode, VTList, 0, 0);
2800}
2801
2802SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2803                                SDOperand N1) {
2804  SDOperand Ops[] = { N1 };
2805  return getNode(Opcode, VTList, Ops, 1);
2806}
2807
2808SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2809                                SDOperand N1, SDOperand N2) {
2810  SDOperand Ops[] = { N1, N2 };
2811  return getNode(Opcode, VTList, Ops, 2);
2812}
2813
2814SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2815                                SDOperand N1, SDOperand N2, SDOperand N3) {
2816  SDOperand Ops[] = { N1, N2, N3 };
2817  return getNode(Opcode, VTList, Ops, 3);
2818}
2819
2820SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2821                                SDOperand N1, SDOperand N2, SDOperand N3,
2822                                SDOperand N4) {
2823  SDOperand Ops[] = { N1, N2, N3, N4 };
2824  return getNode(Opcode, VTList, Ops, 4);
2825}
2826
2827SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2828                                SDOperand N1, SDOperand N2, SDOperand N3,
2829                                SDOperand N4, SDOperand N5) {
2830  SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2831  return getNode(Opcode, VTList, Ops, 5);
2832}
2833
2834SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
2835  return makeVTList(SDNode::getValueTypeList(VT), 1);
2836}
2837
2838SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
2839  for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2840       E = VTList.end(); I != E; ++I) {
2841    if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
2842      return makeVTList(&(*I)[0], 2);
2843  }
2844  std::vector<MVT::ValueType> V;
2845  V.push_back(VT1);
2846  V.push_back(VT2);
2847  VTList.push_front(V);
2848  return makeVTList(&(*VTList.begin())[0], 2);
2849}
2850SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
2851                                 MVT::ValueType VT3) {
2852  for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2853       E = VTList.end(); I != E; ++I) {
2854    if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
2855        (*I)[2] == VT3)
2856      return makeVTList(&(*I)[0], 3);
2857  }
2858  std::vector<MVT::ValueType> V;
2859  V.push_back(VT1);
2860  V.push_back(VT2);
2861  V.push_back(VT3);
2862  VTList.push_front(V);
2863  return makeVTList(&(*VTList.begin())[0], 3);
2864}
2865
2866SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
2867  switch (NumVTs) {
2868    case 0: assert(0 && "Cannot have nodes without results!");
2869    case 1: return getVTList(VTs[0]);
2870    case 2: return getVTList(VTs[0], VTs[1]);
2871    case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
2872    default: break;
2873  }
2874
2875  for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2876       E = VTList.end(); I != E; ++I) {
2877    if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
2878
2879    bool NoMatch = false;
2880    for (unsigned i = 2; i != NumVTs; ++i)
2881      if (VTs[i] != (*I)[i]) {
2882        NoMatch = true;
2883        break;
2884      }
2885    if (!NoMatch)
2886      return makeVTList(&*I->begin(), NumVTs);
2887  }
2888
2889  VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
2890  return makeVTList(&*VTList.begin()->begin(), NumVTs);
2891}
2892
2893
2894/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
2895/// specified operands.  If the resultant node already exists in the DAG,
2896/// this does not modify the specified node, instead it returns the node that
2897/// already exists.  If the resultant node does not exist in the DAG, the
2898/// input node is returned.  As a degenerate case, if you specify the same
2899/// input operands as the node already has, the input node is returned.
2900SDOperand SelectionDAG::
2901UpdateNodeOperands(SDOperand InN, SDOperand Op) {
2902  SDNode *N = InN.Val;
2903  assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
2904
2905  // Check to see if there is no change.
2906  if (Op == N->getOperand(0)) return InN;
2907
2908  // See if the modified node already exists.
2909  void *InsertPos = 0;
2910  if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
2911    return SDOperand(Existing, InN.ResNo);
2912
2913  // Nope it doesn't.  Remove the node from it's current place in the maps.
2914  if (InsertPos)
2915    RemoveNodeFromCSEMaps(N);
2916
2917  // Now we update the operands.
2918  N->OperandList[0].Val->removeUser(N);
2919  Op.Val->addUser(N);
2920  N->OperandList[0] = Op;
2921
2922  // If this gets put into a CSE map, add it.
2923  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2924  return InN;
2925}
2926
2927SDOperand SelectionDAG::
2928UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
2929  SDNode *N = InN.Val;
2930  assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
2931
2932  // Check to see if there is no change.
2933  if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
2934    return InN;   // No operands changed, just return the input node.
2935
2936  // See if the modified node already exists.
2937  void *InsertPos = 0;
2938  if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
2939    return SDOperand(Existing, InN.ResNo);
2940
2941  // Nope it doesn't.  Remove the node from it's current place in the maps.
2942  if (InsertPos)
2943    RemoveNodeFromCSEMaps(N);
2944
2945  // Now we update the operands.
2946  if (N->OperandList[0] != Op1) {
2947    N->OperandList[0].Val->removeUser(N);
2948    Op1.Val->addUser(N);
2949    N->OperandList[0] = Op1;
2950  }
2951  if (N->OperandList[1] != Op2) {
2952    N->OperandList[1].Val->removeUser(N);
2953    Op2.Val->addUser(N);
2954    N->OperandList[1] = Op2;
2955  }
2956
2957  // If this gets put into a CSE map, add it.
2958  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2959  return InN;
2960}
2961
2962SDOperand SelectionDAG::
2963UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2964  SDOperand Ops[] = { Op1, Op2, Op3 };
2965  return UpdateNodeOperands(N, Ops, 3);
2966}
2967
2968SDOperand SelectionDAG::
2969UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2970                   SDOperand Op3, SDOperand Op4) {
2971  SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
2972  return UpdateNodeOperands(N, Ops, 4);
2973}
2974
2975SDOperand SelectionDAG::
2976UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2977                   SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2978  SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
2979  return UpdateNodeOperands(N, Ops, 5);
2980}
2981
2982
2983SDOperand SelectionDAG::
2984UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
2985  SDNode *N = InN.Val;
2986  assert(N->getNumOperands() == NumOps &&
2987         "Update with wrong number of operands");
2988
2989  // Check to see if there is no change.
2990  bool AnyChange = false;
2991  for (unsigned i = 0; i != NumOps; ++i) {
2992    if (Ops[i] != N->getOperand(i)) {
2993      AnyChange = true;
2994      break;
2995    }
2996  }
2997
2998  // No operands changed, just return the input node.
2999  if (!AnyChange) return InN;
3000
3001  // See if the modified node already exists.
3002  void *InsertPos = 0;
3003  if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3004    return SDOperand(Existing, InN.ResNo);
3005
3006  // Nope it doesn't.  Remove the node from it's current place in the maps.
3007  if (InsertPos)
3008    RemoveNodeFromCSEMaps(N);
3009
3010  // Now we update the operands.
3011  for (unsigned i = 0; i != NumOps; ++i) {
3012    if (N->OperandList[i] != Ops[i]) {
3013      N->OperandList[i].Val->removeUser(N);
3014      Ops[i].Val->addUser(N);
3015      N->OperandList[i] = Ops[i];
3016    }
3017  }
3018
3019  // If this gets put into a CSE map, add it.
3020  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3021  return InN;
3022}
3023
3024
3025/// MorphNodeTo - This frees the operands of the current node, resets the
3026/// opcode, types, and operands to the specified value.  This should only be
3027/// used by the SelectionDAG class.
3028void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3029                         const SDOperand *Ops, unsigned NumOps) {
3030  NodeType = Opc;
3031  ValueList = L.VTs;
3032  NumValues = L.NumVTs;
3033
3034  // Clear the operands list, updating used nodes to remove this from their
3035  // use list.
3036  for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3037    I->Val->removeUser(this);
3038
3039  // If NumOps is larger than the # of operands we currently have, reallocate
3040  // the operand list.
3041  if (NumOps > NumOperands) {
3042    if (OperandsNeedDelete)
3043      delete [] OperandList;
3044    OperandList = new SDOperand[NumOps];
3045    OperandsNeedDelete = true;
3046  }
3047
3048  // Assign the new operands.
3049  NumOperands = NumOps;
3050
3051  for (unsigned i = 0, e = NumOps; i != e; ++i) {
3052    OperandList[i] = Ops[i];
3053    SDNode *N = OperandList[i].Val;
3054    N->Uses.push_back(this);
3055  }
3056}
3057
3058/// SelectNodeTo - These are used for target selectors to *mutate* the
3059/// specified node to have the specified return type, Target opcode, and
3060/// operands.  Note that target opcodes are stored as
3061/// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3062///
3063/// Note that SelectNodeTo returns the resultant node.  If there is already a
3064/// node of the specified opcode and operands, it returns that node instead of
3065/// the current one.
3066SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3067                                   MVT::ValueType VT) {
3068  SDVTList VTs = getVTList(VT);
3069  FoldingSetNodeID ID;
3070  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
3071  void *IP = 0;
3072  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3073    return ON;
3074
3075  RemoveNodeFromCSEMaps(N);
3076
3077  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
3078
3079  CSEMap.InsertNode(N, IP);
3080  return N;
3081}
3082
3083SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3084                                   MVT::ValueType VT, SDOperand Op1) {
3085  // If an identical node already exists, use it.
3086  SDVTList VTs = getVTList(VT);
3087  SDOperand Ops[] = { Op1 };
3088
3089  FoldingSetNodeID ID;
3090  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3091  void *IP = 0;
3092  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3093    return ON;
3094
3095  RemoveNodeFromCSEMaps(N);
3096  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3097  CSEMap.InsertNode(N, IP);
3098  return N;
3099}
3100
3101SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3102                                   MVT::ValueType VT, SDOperand Op1,
3103                                   SDOperand Op2) {
3104  // If an identical node already exists, use it.
3105  SDVTList VTs = getVTList(VT);
3106  SDOperand Ops[] = { Op1, Op2 };
3107
3108  FoldingSetNodeID ID;
3109  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3110  void *IP = 0;
3111  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3112    return ON;
3113
3114  RemoveNodeFromCSEMaps(N);
3115
3116  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3117
3118  CSEMap.InsertNode(N, IP);   // Memoize the new node.
3119  return N;
3120}
3121
3122SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3123                                   MVT::ValueType VT, SDOperand Op1,
3124                                   SDOperand Op2, SDOperand Op3) {
3125  // If an identical node already exists, use it.
3126  SDVTList VTs = getVTList(VT);
3127  SDOperand Ops[] = { Op1, Op2, Op3 };
3128  FoldingSetNodeID ID;
3129  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3130  void *IP = 0;
3131  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3132    return ON;
3133
3134  RemoveNodeFromCSEMaps(N);
3135
3136  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3137
3138  CSEMap.InsertNode(N, IP);   // Memoize the new node.
3139  return N;
3140}
3141
3142SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3143                                   MVT::ValueType VT, const SDOperand *Ops,
3144                                   unsigned NumOps) {
3145  // If an identical node already exists, use it.
3146  SDVTList VTs = getVTList(VT);
3147  FoldingSetNodeID ID;
3148  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3149  void *IP = 0;
3150  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3151    return ON;
3152
3153  RemoveNodeFromCSEMaps(N);
3154  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3155
3156  CSEMap.InsertNode(N, IP);   // Memoize the new node.
3157  return N;
3158}
3159
3160SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3161                                   MVT::ValueType VT1, MVT::ValueType VT2,
3162                                   SDOperand Op1, SDOperand Op2) {
3163  SDVTList VTs = getVTList(VT1, VT2);
3164  FoldingSetNodeID ID;
3165  SDOperand Ops[] = { Op1, Op2 };
3166  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3167  void *IP = 0;
3168  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3169    return ON;
3170
3171  RemoveNodeFromCSEMaps(N);
3172  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3173  CSEMap.InsertNode(N, IP);   // Memoize the new node.
3174  return N;
3175}
3176
3177SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3178                                   MVT::ValueType VT1, MVT::ValueType VT2,
3179                                   SDOperand Op1, SDOperand Op2,
3180                                   SDOperand Op3) {
3181  // If an identical node already exists, use it.
3182  SDVTList VTs = getVTList(VT1, VT2);
3183  SDOperand Ops[] = { Op1, Op2, Op3 };
3184  FoldingSetNodeID ID;
3185  AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3186  void *IP = 0;
3187  if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3188    return ON;
3189
3190  RemoveNodeFromCSEMaps(N);
3191
3192  N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3193  CSEMap.InsertNode(N, IP);   // Memoize the new node.
3194  return N;
3195}
3196
3197
3198/// getTargetNode - These are used for target selectors to create a new node
3199/// with specified return type(s), target opcode, and operands.
3200///
3201/// Note that getTargetNode returns the resultant node.  If there is already a
3202/// node of the specified opcode and operands, it returns that node instead of
3203/// the current one.
3204SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
3205  return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3206}
3207SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3208                                    SDOperand Op1) {
3209  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3210}
3211SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3212                                    SDOperand Op1, SDOperand Op2) {
3213  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3214}
3215SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3216                                    SDOperand Op1, SDOperand Op2,
3217                                    SDOperand Op3) {
3218  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3219}
3220SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3221                                    const SDOperand *Ops, unsigned NumOps) {
3222  return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3223}
3224SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3225                                    MVT::ValueType VT2) {
3226  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3227  SDOperand Op;
3228  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3229}
3230SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3231                                    MVT::ValueType VT2, SDOperand Op1) {
3232  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3233  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3234}
3235SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3236                                    MVT::ValueType VT2, SDOperand Op1,
3237                                    SDOperand Op2) {
3238  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3239  SDOperand Ops[] = { Op1, Op2 };
3240  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3241}
3242SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3243                                    MVT::ValueType VT2, SDOperand Op1,
3244                                    SDOperand Op2, SDOperand Op3) {
3245  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3246  SDOperand Ops[] = { Op1, Op2, Op3 };
3247  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3248}
3249SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3250                                    MVT::ValueType VT2,
3251                                    const SDOperand *Ops, unsigned NumOps) {
3252  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3253  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3254}
3255SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3256                                    MVT::ValueType VT2, MVT::ValueType VT3,
3257                                    SDOperand Op1, SDOperand Op2) {
3258  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3259  SDOperand Ops[] = { Op1, Op2 };
3260  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3261}
3262SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3263                                    MVT::ValueType VT2, MVT::ValueType VT3,
3264                                    SDOperand Op1, SDOperand Op2,
3265                                    SDOperand Op3) {
3266  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3267  SDOperand Ops[] = { Op1, Op2, Op3 };
3268  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3269}
3270SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3271                                    MVT::ValueType VT2, MVT::ValueType VT3,
3272                                    const SDOperand *Ops, unsigned NumOps) {
3273  const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3274  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3275}
3276SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3277                                    MVT::ValueType VT2, MVT::ValueType VT3,
3278                                    MVT::ValueType VT4,
3279                                    const SDOperand *Ops, unsigned NumOps) {
3280  std::vector<MVT::ValueType> VTList;
3281  VTList.push_back(VT1);
3282  VTList.push_back(VT2);
3283  VTList.push_back(VT3);
3284  VTList.push_back(VT4);
3285  const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3286  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3287}
3288SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3289                                    std::vector<MVT::ValueType> &ResultTys,
3290                                    const SDOperand *Ops, unsigned NumOps) {
3291  const MVT::ValueType *VTs = getNodeValueTypes(ResultTys);
3292  return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3293                 Ops, NumOps).Val;
3294}
3295
3296/// getNodeIfExists - Get the specified node if it's already available, or
3297/// else return NULL.
3298SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3299                                      const SDOperand *Ops, unsigned NumOps) {
3300  if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3301    FoldingSetNodeID ID;
3302    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3303    void *IP = 0;
3304    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3305      return E;
3306  }
3307  return NULL;
3308}
3309
3310
3311/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3312/// This can cause recursive merging of nodes in the DAG.
3313///
3314/// This version assumes From has a single result value.
3315///
3316void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3317                                      DAGUpdateListener *UpdateListener) {
3318  SDNode *From = FromN.Val;
3319  assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3320         "Cannot replace with this method!");
3321  assert(From != To.Val && "Cannot replace uses of with self");
3322
3323  while (!From->use_empty()) {
3324    // Process users until they are all gone.
3325    SDNode *U = *From->use_begin();
3326
3327    // This node is about to morph, remove its old self from the CSE maps.
3328    RemoveNodeFromCSEMaps(U);
3329
3330    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3331         I != E; ++I)
3332      if (I->Val == From) {
3333        From->removeUser(U);
3334        *I = To;
3335        To.Val->addUser(U);
3336      }
3337
3338    // Now that we have modified U, add it back to the CSE maps.  If it already
3339    // exists there, recursively merge the results together.
3340    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3341      ReplaceAllUsesWith(U, Existing, UpdateListener);
3342      // U is now dead.  Inform the listener if it exists and delete it.
3343      if (UpdateListener)
3344        UpdateListener->NodeDeleted(U);
3345      DeleteNodeNotInCSEMaps(U);
3346    } else {
3347      // If the node doesn't already exist, we updated it.  Inform a listener if
3348      // it exists.
3349      if (UpdateListener)
3350        UpdateListener->NodeUpdated(U);
3351    }
3352  }
3353}
3354
3355/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3356/// This can cause recursive merging of nodes in the DAG.
3357///
3358/// This version assumes From/To have matching types and numbers of result
3359/// values.
3360///
3361void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3362                                      DAGUpdateListener *UpdateListener) {
3363  assert(From != To && "Cannot replace uses of with self");
3364  assert(From->getNumValues() == To->getNumValues() &&
3365         "Cannot use this version of ReplaceAllUsesWith!");
3366  if (From->getNumValues() == 1)   // If possible, use the faster version.
3367    return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3368                              UpdateListener);
3369
3370  while (!From->use_empty()) {
3371    // Process users until they are all gone.
3372    SDNode *U = *From->use_begin();
3373
3374    // This node is about to morph, remove its old self from the CSE maps.
3375    RemoveNodeFromCSEMaps(U);
3376
3377    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3378         I != E; ++I)
3379      if (I->Val == From) {
3380        From->removeUser(U);
3381        I->Val = To;
3382        To->addUser(U);
3383      }
3384
3385    // Now that we have modified U, add it back to the CSE maps.  If it already
3386    // exists there, recursively merge the results together.
3387    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3388      ReplaceAllUsesWith(U, Existing, UpdateListener);
3389      // U is now dead.  Inform the listener if it exists and delete it.
3390      if (UpdateListener)
3391        UpdateListener->NodeDeleted(U);
3392      DeleteNodeNotInCSEMaps(U);
3393    } else {
3394      // If the node doesn't already exist, we updated it.  Inform a listener if
3395      // it exists.
3396      if (UpdateListener)
3397        UpdateListener->NodeUpdated(U);
3398    }
3399  }
3400}
3401
3402/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3403/// This can cause recursive merging of nodes in the DAG.
3404///
3405/// This version can replace From with any result values.  To must match the
3406/// number and types of values returned by From.
3407void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3408                                      const SDOperand *To,
3409                                      DAGUpdateListener *UpdateListener) {
3410  if (From->getNumValues() == 1)  // Handle the simple case efficiently.
3411    return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
3412
3413  while (!From->use_empty()) {
3414    // Process users until they are all gone.
3415    SDNode *U = *From->use_begin();
3416
3417    // This node is about to morph, remove its old self from the CSE maps.
3418    RemoveNodeFromCSEMaps(U);
3419
3420    for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3421         I != E; ++I)
3422      if (I->Val == From) {
3423        const SDOperand &ToOp = To[I->ResNo];
3424        From->removeUser(U);
3425        *I = ToOp;
3426        ToOp.Val->addUser(U);
3427      }
3428
3429    // Now that we have modified U, add it back to the CSE maps.  If it already
3430    // exists there, recursively merge the results together.
3431    if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3432      ReplaceAllUsesWith(U, Existing, UpdateListener);
3433      // U is now dead.  Inform the listener if it exists and delete it.
3434      if (UpdateListener)
3435        UpdateListener->NodeDeleted(U);
3436      DeleteNodeNotInCSEMaps(U);
3437    } else {
3438      // If the node doesn't already exist, we updated it.  Inform a listener if
3439      // it exists.
3440      if (UpdateListener)
3441        UpdateListener->NodeUpdated(U);
3442    }
3443  }
3444}
3445
3446namespace {
3447  /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
3448  /// any deleted nodes from the set passed into its constructor and recursively
3449  /// notifies another update listener if specified.
3450  class ChainedSetUpdaterListener :
3451  public SelectionDAG::DAGUpdateListener {
3452    SmallSetVector<SDNode*, 16> &Set;
3453    SelectionDAG::DAGUpdateListener *Chain;
3454  public:
3455    ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
3456                              SelectionDAG::DAGUpdateListener *chain)
3457      : Set(set), Chain(chain) {}
3458
3459    virtual void NodeDeleted(SDNode *N) {
3460      Set.remove(N);
3461      if (Chain) Chain->NodeDeleted(N);
3462    }
3463    virtual void NodeUpdated(SDNode *N) {
3464      if (Chain) Chain->NodeUpdated(N);
3465    }
3466  };
3467}
3468
3469/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3470/// uses of other values produced by From.Val alone.  The Deleted vector is
3471/// handled the same way as for ReplaceAllUsesWith.
3472void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3473                                             DAGUpdateListener *UpdateListener){
3474  assert(From != To && "Cannot replace a value with itself");
3475
3476  // Handle the simple, trivial, case efficiently.
3477  if (From.Val->getNumValues() == 1) {
3478    ReplaceAllUsesWith(From, To, UpdateListener);
3479    return;
3480  }
3481
3482  if (From.use_empty()) return;
3483
3484  // Get all of the users of From.Val.  We want these in a nice,
3485  // deterministically ordered and uniqued set, so we use a SmallSetVector.
3486  SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
3487
3488  // When one of the recursive merges deletes nodes from the graph, we need to
3489  // make sure that UpdateListener is notified *and* that the node is removed
3490  // from Users if present.  CSUL does this.
3491  ChainedSetUpdaterListener CSUL(Users, UpdateListener);
3492
3493  while (!Users.empty()) {
3494    // We know that this user uses some value of From.  If it is the right
3495    // value, update it.
3496    SDNode *User = Users.back();
3497    Users.pop_back();
3498
3499    // Scan for an operand that matches From.
3500    SDOperand *Op = User->OperandList, *E = User->OperandList+User->NumOperands;
3501    for (; Op != E; ++Op)
3502      if (*Op == From) break;
3503
3504    // If there are no matches, the user must use some other result of From.
3505    if (Op == E) continue;
3506
3507    // Okay, we know this user needs to be updated.  Remove its old self
3508    // from the CSE maps.
3509    RemoveNodeFromCSEMaps(User);
3510
3511    // Update all operands that match "From" in case there are multiple uses.
3512    for (; Op != E; ++Op) {
3513      if (*Op == From) {
3514        From.Val->removeUser(User);
3515        *Op = To;
3516        To.Val->addUser(User);
3517      }
3518    }
3519
3520    // Now that we have modified User, add it back to the CSE maps.  If it
3521    // already exists there, recursively merge the results together.
3522    SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
3523    if (!Existing) {
3524      if (UpdateListener) UpdateListener->NodeUpdated(User);
3525      continue;  // Continue on to next user.
3526    }
3527
3528    // If there was already an existing matching node, use ReplaceAllUsesWith
3529    // to replace the dead one with the existing one.  This can cause
3530    // recursive merging of other unrelated nodes down the line.  The merging
3531    // can cause deletion of nodes that used the old value.  To handle this, we
3532    // use CSUL to remove them from the Users set.
3533    ReplaceAllUsesWith(User, Existing, &CSUL);
3534
3535    // User is now dead.  Notify a listener if present.
3536    if (UpdateListener) UpdateListener->NodeDeleted(User);
3537    DeleteNodeNotInCSEMaps(User);
3538  }
3539}
3540
3541
3542/// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3543/// their allnodes order. It returns the maximum id.
3544unsigned SelectionDAG::AssignNodeIds() {
3545  unsigned Id = 0;
3546  for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3547    SDNode *N = I;
3548    N->setNodeId(Id++);
3549  }
3550  return Id;
3551}
3552
3553/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
3554/// based on their topological order. It returns the maximum id and a vector
3555/// of the SDNodes* in assigned order by reference.
3556unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
3557  unsigned DAGSize = AllNodes.size();
3558  std::vector<unsigned> InDegree(DAGSize);
3559  std::vector<SDNode*> Sources;
3560
3561  // Use a two pass approach to avoid using a std::map which is slow.
3562  unsigned Id = 0;
3563  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
3564    SDNode *N = I;
3565    N->setNodeId(Id++);
3566    unsigned Degree = N->use_size();
3567    InDegree[N->getNodeId()] = Degree;
3568    if (Degree == 0)
3569      Sources.push_back(N);
3570  }
3571
3572  TopOrder.clear();
3573  while (!Sources.empty()) {
3574    SDNode *N = Sources.back();
3575    Sources.pop_back();
3576    TopOrder.push_back(N);
3577    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
3578      SDNode *P = I->Val;
3579      unsigned Degree = --InDegree[P->getNodeId()];
3580      if (Degree == 0)
3581        Sources.push_back(P);
3582    }
3583  }
3584
3585  // Second pass, assign the actual topological order as node ids.
3586  Id = 0;
3587  for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
3588       TI != TE; ++TI)
3589    (*TI)->setNodeId(Id++);
3590
3591  return Id;
3592}
3593
3594
3595
3596//===----------------------------------------------------------------------===//
3597//                              SDNode Class
3598//===----------------------------------------------------------------------===//
3599
3600// Out-of-line virtual method to give class a home.
3601void SDNode::ANCHOR() {}
3602void UnarySDNode::ANCHOR() {}
3603void BinarySDNode::ANCHOR() {}
3604void TernarySDNode::ANCHOR() {}
3605void HandleSDNode::ANCHOR() {}
3606void StringSDNode::ANCHOR() {}
3607void ConstantSDNode::ANCHOR() {}
3608void ConstantFPSDNode::ANCHOR() {}
3609void GlobalAddressSDNode::ANCHOR() {}
3610void FrameIndexSDNode::ANCHOR() {}
3611void JumpTableSDNode::ANCHOR() {}
3612void ConstantPoolSDNode::ANCHOR() {}
3613void BasicBlockSDNode::ANCHOR() {}
3614void SrcValueSDNode::ANCHOR() {}
3615void MemOperandSDNode::ANCHOR() {}
3616void RegisterSDNode::ANCHOR() {}
3617void ExternalSymbolSDNode::ANCHOR() {}
3618void CondCodeSDNode::ANCHOR() {}
3619void ARG_FLAGSSDNode::ANCHOR() {}
3620void VTSDNode::ANCHOR() {}
3621void LoadSDNode::ANCHOR() {}
3622void StoreSDNode::ANCHOR() {}
3623void AtomicSDNode::ANCHOR() {}
3624
3625HandleSDNode::~HandleSDNode() {
3626  SDVTList VTs = { 0, 0 };
3627  MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0);  // Drops operand uses.
3628}
3629
3630GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
3631                                         MVT::ValueType VT, int o)
3632  : SDNode(isa<GlobalVariable>(GA) &&
3633           cast<GlobalVariable>(GA)->isThreadLocal() ?
3634           // Thread Local
3635           (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
3636           // Non Thread Local
3637           (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
3638           getSDVTList(VT)), Offset(o) {
3639  TheGlobal = const_cast<GlobalValue*>(GA);
3640}
3641
3642/// getMemOperand - Return a MemOperand object describing the memory
3643/// reference performed by this load or store.
3644MemOperand LSBaseSDNode::getMemOperand() const {
3645  int Size = (MVT::getSizeInBits(getMemoryVT()) + 7) >> 3;
3646  int Flags =
3647    getOpcode() == ISD::LOAD ? MemOperand::MOLoad : MemOperand::MOStore;
3648  if (IsVolatile) Flags |= MemOperand::MOVolatile;
3649
3650  // Check if the load references a frame index, and does not have
3651  // an SV attached.
3652  const FrameIndexSDNode *FI =
3653    dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
3654  if (!getSrcValue() && FI)
3655    return MemOperand(PseudoSourceValue::getFixedStack(), Flags,
3656                      FI->getIndex(), Size, Alignment);
3657  else
3658    return MemOperand(getSrcValue(), Flags,
3659                      getSrcValueOffset(), Size, Alignment);
3660}
3661
3662/// Profile - Gather unique data for the node.
3663///
3664void SDNode::Profile(FoldingSetNodeID &ID) {
3665  AddNodeIDNode(ID, this);
3666}
3667
3668/// getValueTypeList - Return a pointer to the specified value type.
3669///
3670const MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
3671  if (MVT::isExtendedVT(VT)) {
3672    static std::set<MVT::ValueType> EVTs;
3673    return &(*EVTs.insert(VT).first);
3674  } else {
3675    static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
3676    VTs[VT] = VT;
3677    return &VTs[VT];
3678  }
3679}
3680
3681/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
3682/// indicated value.  This method ignores uses of other values defined by this
3683/// operation.
3684bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
3685  assert(Value < getNumValues() && "Bad value!");
3686
3687  // If there is only one value, this is easy.
3688  if (getNumValues() == 1)
3689    return use_size() == NUses;
3690  if (use_size() < NUses) return false;
3691
3692  SDOperand TheValue(const_cast<SDNode *>(this), Value);
3693
3694  SmallPtrSet<SDNode*, 32> UsersHandled;
3695
3696  for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3697    SDNode *User = *UI;
3698    if (User->getNumOperands() == 1 ||
3699        UsersHandled.insert(User))     // First time we've seen this?
3700      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3701        if (User->getOperand(i) == TheValue) {
3702          if (NUses == 0)
3703            return false;   // too many uses
3704          --NUses;
3705        }
3706  }
3707
3708  // Found exactly the right number of uses?
3709  return NUses == 0;
3710}
3711
3712
3713/// hasAnyUseOfValue - Return true if there are any use of the indicated
3714/// value. This method ignores uses of other values defined by this operation.
3715bool SDNode::hasAnyUseOfValue(unsigned Value) const {
3716  assert(Value < getNumValues() && "Bad value!");
3717
3718  if (use_empty()) return false;
3719
3720  SDOperand TheValue(const_cast<SDNode *>(this), Value);
3721
3722  SmallPtrSet<SDNode*, 32> UsersHandled;
3723
3724  for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3725    SDNode *User = *UI;
3726    if (User->getNumOperands() == 1 ||
3727        UsersHandled.insert(User))     // First time we've seen this?
3728      for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3729        if (User->getOperand(i) == TheValue) {
3730          return true;
3731        }
3732  }
3733
3734  return false;
3735}
3736
3737
3738/// isOnlyUseOf - Return true if this node is the only use of N.
3739///
3740bool SDNode::isOnlyUseOf(SDNode *N) const {
3741  bool Seen = false;
3742  for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
3743    SDNode *User = *I;
3744    if (User == this)
3745      Seen = true;
3746    else
3747      return false;
3748  }
3749
3750  return Seen;
3751}
3752
3753/// isOperand - Return true if this node is an operand of N.
3754///
3755bool SDOperand::isOperandOf(SDNode *N) const {
3756  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3757    if (*this == N->getOperand(i))
3758      return true;
3759  return false;
3760}
3761
3762bool SDNode::isOperandOf(SDNode *N) const {
3763  for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
3764    if (this == N->OperandList[i].Val)
3765      return true;
3766  return false;
3767}
3768
3769/// reachesChainWithoutSideEffects - Return true if this operand (which must
3770/// be a chain) reaches the specified operand without crossing any
3771/// side-effecting instructions.  In practice, this looks through token
3772/// factors and non-volatile loads.  In order to remain efficient, this only
3773/// looks a couple of nodes in, it does not do an exhaustive search.
3774bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
3775                                               unsigned Depth) const {
3776  if (*this == Dest) return true;
3777
3778  // Don't search too deeply, we just want to be able to see through
3779  // TokenFactor's etc.
3780  if (Depth == 0) return false;
3781
3782  // If this is a token factor, all inputs to the TF happen in parallel.  If any
3783  // of the operands of the TF reach dest, then we can do the xform.
3784  if (getOpcode() == ISD::TokenFactor) {
3785    for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3786      if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
3787        return true;
3788    return false;
3789  }
3790
3791  // Loads don't have side effects, look through them.
3792  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
3793    if (!Ld->isVolatile())
3794      return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
3795  }
3796  return false;
3797}
3798
3799
3800static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
3801                            SmallPtrSet<SDNode *, 32> &Visited) {
3802  if (found || !Visited.insert(N))
3803    return;
3804
3805  for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
3806    SDNode *Op = N->getOperand(i).Val;
3807    if (Op == P) {
3808      found = true;
3809      return;
3810    }
3811    findPredecessor(Op, P, found, Visited);
3812  }
3813}
3814
3815/// isPredecessorOf - Return true if this node is a predecessor of N. This node
3816/// is either an operand of N or it can be reached by recursively traversing
3817/// up the operands.
3818/// NOTE: this is an expensive method. Use it carefully.
3819bool SDNode::isPredecessorOf(SDNode *N) const {
3820  SmallPtrSet<SDNode *, 32> Visited;
3821  bool found = false;
3822  findPredecessor(N, this, found, Visited);
3823  return found;
3824}
3825
3826uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
3827  assert(Num < NumOperands && "Invalid child # of SDNode!");
3828  return cast<ConstantSDNode>(OperandList[Num])->getValue();
3829}
3830
3831std::string SDNode::getOperationName(const SelectionDAG *G) const {
3832  switch (getOpcode()) {
3833  default:
3834    if (getOpcode() < ISD::BUILTIN_OP_END)
3835      return "<<Unknown DAG Node>>";
3836    else {
3837      if (G) {
3838        if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
3839          if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
3840            return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
3841
3842        TargetLowering &TLI = G->getTargetLoweringInfo();
3843        const char *Name =
3844          TLI.getTargetNodeName(getOpcode());
3845        if (Name) return Name;
3846      }
3847
3848      return "<<Unknown Target Node>>";
3849    }
3850
3851  case ISD::PREFETCH:      return "Prefetch";
3852  case ISD::MEMBARRIER:    return "MemBarrier";
3853  case ISD::ATOMIC_LCS:    return "AtomicLCS";
3854  case ISD::ATOMIC_LAS:    return "AtomicLAS";
3855  case ISD::ATOMIC_SWAP:    return "AtomicSWAP";
3856  case ISD::PCMARKER:      return "PCMarker";
3857  case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
3858  case ISD::SRCVALUE:      return "SrcValue";
3859  case ISD::MEMOPERAND:    return "MemOperand";
3860  case ISD::EntryToken:    return "EntryToken";
3861  case ISD::TokenFactor:   return "TokenFactor";
3862  case ISD::AssertSext:    return "AssertSext";
3863  case ISD::AssertZext:    return "AssertZext";
3864
3865  case ISD::STRING:        return "String";
3866  case ISD::BasicBlock:    return "BasicBlock";
3867  case ISD::ARG_FLAGS:     return "ArgFlags";
3868  case ISD::VALUETYPE:     return "ValueType";
3869  case ISD::Register:      return "Register";
3870
3871  case ISD::Constant:      return "Constant";
3872  case ISD::ConstantFP:    return "ConstantFP";
3873  case ISD::GlobalAddress: return "GlobalAddress";
3874  case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
3875  case ISD::FrameIndex:    return "FrameIndex";
3876  case ISD::JumpTable:     return "JumpTable";
3877  case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
3878  case ISD::RETURNADDR: return "RETURNADDR";
3879  case ISD::FRAMEADDR: return "FRAMEADDR";
3880  case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
3881  case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
3882  case ISD::EHSELECTION: return "EHSELECTION";
3883  case ISD::EH_RETURN: return "EH_RETURN";
3884  case ISD::ConstantPool:  return "ConstantPool";
3885  case ISD::ExternalSymbol: return "ExternalSymbol";
3886  case ISD::INTRINSIC_WO_CHAIN: {
3887    unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
3888    return Intrinsic::getName((Intrinsic::ID)IID);
3889  }
3890  case ISD::INTRINSIC_VOID:
3891  case ISD::INTRINSIC_W_CHAIN: {
3892    unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
3893    return Intrinsic::getName((Intrinsic::ID)IID);
3894  }
3895
3896  case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
3897  case ISD::TargetConstant: return "TargetConstant";
3898  case ISD::TargetConstantFP:return "TargetConstantFP";
3899  case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
3900  case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
3901  case ISD::TargetFrameIndex: return "TargetFrameIndex";
3902  case ISD::TargetJumpTable:  return "TargetJumpTable";
3903  case ISD::TargetConstantPool:  return "TargetConstantPool";
3904  case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
3905
3906  case ISD::CopyToReg:     return "CopyToReg";
3907  case ISD::CopyFromReg:   return "CopyFromReg";
3908  case ISD::UNDEF:         return "undef";
3909  case ISD::MERGE_VALUES:  return "merge_values";
3910  case ISD::INLINEASM:     return "inlineasm";
3911  case ISD::LABEL:         return "label";
3912  case ISD::DECLARE:       return "declare";
3913  case ISD::HANDLENODE:    return "handlenode";
3914  case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
3915  case ISD::CALL:          return "call";
3916
3917  // Unary operators
3918  case ISD::FABS:   return "fabs";
3919  case ISD::FNEG:   return "fneg";
3920  case ISD::FSQRT:  return "fsqrt";
3921  case ISD::FSIN:   return "fsin";
3922  case ISD::FCOS:   return "fcos";
3923  case ISD::FPOWI:  return "fpowi";
3924  case ISD::FPOW:   return "fpow";
3925
3926  // Binary operators
3927  case ISD::ADD:    return "add";
3928  case ISD::SUB:    return "sub";
3929  case ISD::MUL:    return "mul";
3930  case ISD::MULHU:  return "mulhu";
3931  case ISD::MULHS:  return "mulhs";
3932  case ISD::SDIV:   return "sdiv";
3933  case ISD::UDIV:   return "udiv";
3934  case ISD::SREM:   return "srem";
3935  case ISD::UREM:   return "urem";
3936  case ISD::SMUL_LOHI:  return "smul_lohi";
3937  case ISD::UMUL_LOHI:  return "umul_lohi";
3938  case ISD::SDIVREM:    return "sdivrem";
3939  case ISD::UDIVREM:    return "divrem";
3940  case ISD::AND:    return "and";
3941  case ISD::OR:     return "or";
3942  case ISD::XOR:    return "xor";
3943  case ISD::SHL:    return "shl";
3944  case ISD::SRA:    return "sra";
3945  case ISD::SRL:    return "srl";
3946  case ISD::ROTL:   return "rotl";
3947  case ISD::ROTR:   return "rotr";
3948  case ISD::FADD:   return "fadd";
3949  case ISD::FSUB:   return "fsub";
3950  case ISD::FMUL:   return "fmul";
3951  case ISD::FDIV:   return "fdiv";
3952  case ISD::FREM:   return "frem";
3953  case ISD::FCOPYSIGN: return "fcopysign";
3954  case ISD::FGETSIGN:  return "fgetsign";
3955
3956  case ISD::SETCC:       return "setcc";
3957  case ISD::SELECT:      return "select";
3958  case ISD::SELECT_CC:   return "select_cc";
3959  case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
3960  case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
3961  case ISD::CONCAT_VECTORS:      return "concat_vectors";
3962  case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
3963  case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
3964  case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
3965  case ISD::CARRY_FALSE:         return "carry_false";
3966  case ISD::ADDC:        return "addc";
3967  case ISD::ADDE:        return "adde";
3968  case ISD::SUBC:        return "subc";
3969  case ISD::SUBE:        return "sube";
3970  case ISD::SHL_PARTS:   return "shl_parts";
3971  case ISD::SRA_PARTS:   return "sra_parts";
3972  case ISD::SRL_PARTS:   return "srl_parts";
3973
3974  case ISD::EXTRACT_SUBREG:     return "extract_subreg";
3975  case ISD::INSERT_SUBREG:      return "insert_subreg";
3976
3977  // Conversion operators.
3978  case ISD::SIGN_EXTEND: return "sign_extend";
3979  case ISD::ZERO_EXTEND: return "zero_extend";
3980  case ISD::ANY_EXTEND:  return "any_extend";
3981  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
3982  case ISD::TRUNCATE:    return "truncate";
3983  case ISD::FP_ROUND:    return "fp_round";
3984  case ISD::FLT_ROUNDS_: return "flt_rounds";
3985  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
3986  case ISD::FP_EXTEND:   return "fp_extend";
3987
3988  case ISD::SINT_TO_FP:  return "sint_to_fp";
3989  case ISD::UINT_TO_FP:  return "uint_to_fp";
3990  case ISD::FP_TO_SINT:  return "fp_to_sint";
3991  case ISD::FP_TO_UINT:  return "fp_to_uint";
3992  case ISD::BIT_CONVERT: return "bit_convert";
3993
3994    // Control flow instructions
3995  case ISD::BR:      return "br";
3996  case ISD::BRIND:   return "brind";
3997  case ISD::BR_JT:   return "br_jt";
3998  case ISD::BRCOND:  return "brcond";
3999  case ISD::BR_CC:   return "br_cc";
4000  case ISD::RET:     return "ret";
4001  case ISD::CALLSEQ_START:  return "callseq_start";
4002  case ISD::CALLSEQ_END:    return "callseq_end";
4003
4004    // Other operators
4005  case ISD::LOAD:               return "load";
4006  case ISD::STORE:              return "store";
4007  case ISD::VAARG:              return "vaarg";
4008  case ISD::VACOPY:             return "vacopy";
4009  case ISD::VAEND:              return "vaend";
4010  case ISD::VASTART:            return "vastart";
4011  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4012  case ISD::EXTRACT_ELEMENT:    return "extract_element";
4013  case ISD::BUILD_PAIR:         return "build_pair";
4014  case ISD::STACKSAVE:          return "stacksave";
4015  case ISD::STACKRESTORE:       return "stackrestore";
4016  case ISD::TRAP:               return "trap";
4017
4018  // Block memory operations.
4019  case ISD::MEMSET:  return "memset";
4020  case ISD::MEMCPY:  return "memcpy";
4021  case ISD::MEMMOVE: return "memmove";
4022
4023  // Bit manipulation
4024  case ISD::BSWAP:   return "bswap";
4025  case ISD::CTPOP:   return "ctpop";
4026  case ISD::CTTZ:    return "cttz";
4027  case ISD::CTLZ:    return "ctlz";
4028
4029  // Debug info
4030  case ISD::LOCATION: return "location";
4031  case ISD::DEBUG_LOC: return "debug_loc";
4032
4033  // Trampolines
4034  case ISD::TRAMPOLINE: return "trampoline";
4035
4036  case ISD::CONDCODE:
4037    switch (cast<CondCodeSDNode>(this)->get()) {
4038    default: assert(0 && "Unknown setcc condition!");
4039    case ISD::SETOEQ:  return "setoeq";
4040    case ISD::SETOGT:  return "setogt";
4041    case ISD::SETOGE:  return "setoge";
4042    case ISD::SETOLT:  return "setolt";
4043    case ISD::SETOLE:  return "setole";
4044    case ISD::SETONE:  return "setone";
4045
4046    case ISD::SETO:    return "seto";
4047    case ISD::SETUO:   return "setuo";
4048    case ISD::SETUEQ:  return "setue";
4049    case ISD::SETUGT:  return "setugt";
4050    case ISD::SETUGE:  return "setuge";
4051    case ISD::SETULT:  return "setult";
4052    case ISD::SETULE:  return "setule";
4053    case ISD::SETUNE:  return "setune";
4054
4055    case ISD::SETEQ:   return "seteq";
4056    case ISD::SETGT:   return "setgt";
4057    case ISD::SETGE:   return "setge";
4058    case ISD::SETLT:   return "setlt";
4059    case ISD::SETLE:   return "setle";
4060    case ISD::SETNE:   return "setne";
4061    }
4062  }
4063}
4064
4065const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4066  switch (AM) {
4067  default:
4068    return "";
4069  case ISD::PRE_INC:
4070    return "<pre-inc>";
4071  case ISD::PRE_DEC:
4072    return "<pre-dec>";
4073  case ISD::POST_INC:
4074    return "<post-inc>";
4075  case ISD::POST_DEC:
4076    return "<post-dec>";
4077  }
4078}
4079
4080std::string ISD::ArgFlagsTy::getArgFlagsString() {
4081  std::string S = "< ";
4082
4083  if (isZExt())
4084    S += "zext ";
4085  if (isSExt())
4086    S += "sext ";
4087  if (isInReg())
4088    S += "inreg ";
4089  if (isSRet())
4090    S += "sret ";
4091  if (isByVal())
4092    S += "byval ";
4093  if (isNest())
4094    S += "nest ";
4095  if (getByValAlign())
4096    S += "byval-align:" + utostr(getByValAlign()) + " ";
4097  if (getOrigAlign())
4098    S += "orig-align:" + utostr(getOrigAlign()) + " ";
4099  if (getByValSize())
4100    S += "byval-size:" + utostr(getByValSize()) + " ";
4101  return S + ">";
4102}
4103
4104void SDNode::dump() const { dump(0); }
4105void SDNode::dump(const SelectionDAG *G) const {
4106  cerr << (void*)this << ": ";
4107
4108  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4109    if (i) cerr << ",";
4110    if (getValueType(i) == MVT::Other)
4111      cerr << "ch";
4112    else
4113      cerr << MVT::getValueTypeString(getValueType(i));
4114  }
4115  cerr << " = " << getOperationName(G);
4116
4117  cerr << " ";
4118  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4119    if (i) cerr << ", ";
4120    cerr << (void*)getOperand(i).Val;
4121    if (unsigned RN = getOperand(i).ResNo)
4122      cerr << ":" << RN;
4123  }
4124
4125  if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4126    SDNode *Mask = getOperand(2).Val;
4127    cerr << "<";
4128    for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4129      if (i) cerr << ",";
4130      if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4131        cerr << "u";
4132      else
4133        cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4134    }
4135    cerr << ">";
4136  }
4137
4138  if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4139    cerr << "<" << CSDN->getValue() << ">";
4140  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4141    if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4142      cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4143    else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4144      cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4145    else {
4146      cerr << "<APFloat(";
4147      CSDN->getValueAPF().convertToAPInt().dump();
4148      cerr << ")>";
4149    }
4150  } else if (const GlobalAddressSDNode *GADN =
4151             dyn_cast<GlobalAddressSDNode>(this)) {
4152    int offset = GADN->getOffset();
4153    cerr << "<";
4154    WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4155    if (offset > 0)
4156      cerr << " + " << offset;
4157    else
4158      cerr << " " << offset;
4159  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4160    cerr << "<" << FIDN->getIndex() << ">";
4161  } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4162    cerr << "<" << JTDN->getIndex() << ">";
4163  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4164    int offset = CP->getOffset();
4165    if (CP->isMachineConstantPoolEntry())
4166      cerr << "<" << *CP->getMachineCPVal() << ">";
4167    else
4168      cerr << "<" << *CP->getConstVal() << ">";
4169    if (offset > 0)
4170      cerr << " + " << offset;
4171    else
4172      cerr << " " << offset;
4173  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4174    cerr << "<";
4175    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4176    if (LBB)
4177      cerr << LBB->getName() << " ";
4178    cerr << (const void*)BBDN->getBasicBlock() << ">";
4179  } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4180    if (G && R->getReg() &&
4181        TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4182      cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4183    } else {
4184      cerr << " #" << R->getReg();
4185    }
4186  } else if (const ExternalSymbolSDNode *ES =
4187             dyn_cast<ExternalSymbolSDNode>(this)) {
4188    cerr << "'" << ES->getSymbol() << "'";
4189  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4190    if (M->getValue())
4191      cerr << "<" << M->getValue() << ">";
4192    else
4193      cerr << "<null>";
4194  } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4195    if (M->MO.getValue())
4196      cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4197    else
4198      cerr << "<null:" << M->MO.getOffset() << ">";
4199  } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4200    cerr << N->getArgFlags().getArgFlagsString();
4201  } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4202    cerr << ":" << MVT::getValueTypeString(N->getVT());
4203  } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4204    const Value *SrcValue = LD->getSrcValue();
4205    int SrcOffset = LD->getSrcValueOffset();
4206    cerr << " <";
4207    if (SrcValue)
4208      cerr << SrcValue;
4209    else
4210      cerr << "null";
4211    cerr << ":" << SrcOffset << ">";
4212
4213    bool doExt = true;
4214    switch (LD->getExtensionType()) {
4215    default: doExt = false; break;
4216    case ISD::EXTLOAD:
4217      cerr << " <anyext ";
4218      break;
4219    case ISD::SEXTLOAD:
4220      cerr << " <sext ";
4221      break;
4222    case ISD::ZEXTLOAD:
4223      cerr << " <zext ";
4224      break;
4225    }
4226    if (doExt)
4227      cerr << MVT::getValueTypeString(LD->getMemoryVT()) << ">";
4228
4229    const char *AM = getIndexedModeName(LD->getAddressingMode());
4230    if (*AM)
4231      cerr << " " << AM;
4232    if (LD->isVolatile())
4233      cerr << " <volatile>";
4234    cerr << " alignment=" << LD->getAlignment();
4235  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4236    const Value *SrcValue = ST->getSrcValue();
4237    int SrcOffset = ST->getSrcValueOffset();
4238    cerr << " <";
4239    if (SrcValue)
4240      cerr << SrcValue;
4241    else
4242      cerr << "null";
4243    cerr << ":" << SrcOffset << ">";
4244
4245    if (ST->isTruncatingStore())
4246      cerr << " <trunc "
4247           << MVT::getValueTypeString(ST->getMemoryVT()) << ">";
4248
4249    const char *AM = getIndexedModeName(ST->getAddressingMode());
4250    if (*AM)
4251      cerr << " " << AM;
4252    if (ST->isVolatile())
4253      cerr << " <volatile>";
4254    cerr << " alignment=" << ST->getAlignment();
4255  }
4256}
4257
4258static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4259  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4260    if (N->getOperand(i).Val->hasOneUse())
4261      DumpNodes(N->getOperand(i).Val, indent+2, G);
4262    else
4263      cerr << "\n" << std::string(indent+2, ' ')
4264           << (void*)N->getOperand(i).Val << ": <multiple use>";
4265
4266
4267  cerr << "\n" << std::string(indent, ' ');
4268  N->dump(G);
4269}
4270
4271void SelectionDAG::dump() const {
4272  cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4273  std::vector<const SDNode*> Nodes;
4274  for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4275       I != E; ++I)
4276    Nodes.push_back(I);
4277
4278  std::sort(Nodes.begin(), Nodes.end());
4279
4280  for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4281    if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4282      DumpNodes(Nodes[i], 2, this);
4283  }
4284
4285  if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4286
4287  cerr << "\n\n";
4288}
4289
4290const Type *ConstantPoolSDNode::getType() const {
4291  if (isMachineConstantPoolEntry())
4292    return Val.MachineCPVal->getType();
4293  return Val.ConstVal->getType();
4294}
4295