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