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