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