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