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