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