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