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