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