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