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