1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/GlobalAlias.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/StringExtras.h"
42 /// makeVTList - Return an instance of the SDVTList struct initialized with the
43 /// specified members.
44 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
45 SDVTList Res = {VTs, NumVTs};
49 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
50 switch (VT.getSimpleVT()) {
51 default: assert(0 && "Unknown FP format");
52 case MVT::f32: return &APFloat::IEEEsingle;
53 case MVT::f64: return &APFloat::IEEEdouble;
54 case MVT::f80: return &APFloat::x87DoubleExtended;
55 case MVT::f128: return &APFloat::IEEEquad;
56 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
60 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
62 //===----------------------------------------------------------------------===//
63 // ConstantFPSDNode Class
64 //===----------------------------------------------------------------------===//
66 /// isExactlyValue - We don't rely on operator== working on double values, as
67 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
68 /// As such, this method can be used to do an exact bit-for-bit comparison of
69 /// two floating point values.
70 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
71 return Value.bitwiseIsEqual(V);
74 bool ConstantFPSDNode::isValueValidForType(MVT VT,
76 assert(VT.isFloatingPoint() && "Can only convert between FP types");
78 // PPC long double cannot be converted to any other type.
79 if (VT == MVT::ppcf128 ||
80 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
83 // convert modifies in place, so make a copy.
84 APFloat Val2 = APFloat(Val);
85 return Val2.convert(*MVTToAPFloatSemantics(VT),
86 APFloat::rmNearestTiesToEven) == APFloat::opOK;
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 /// isBuildVectorAllOnes - Return true if the specified node is a
94 /// BUILD_VECTOR where all of the elements are ~0 or undef.
95 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
96 // Look through a bit convert.
97 if (N->getOpcode() == ISD::BIT_CONVERT)
98 N = N->getOperand(0).Val;
100 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
102 unsigned i = 0, e = N->getNumOperands();
104 // Skip over all of the undef values.
105 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
108 // Do not accept an all-undef vector.
109 if (i == e) return false;
111 // Do not accept build_vectors that aren't all constants or which have non-~0
113 SDOperand NotZero = N->getOperand(i);
114 if (isa<ConstantSDNode>(NotZero)) {
115 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
117 } else if (isa<ConstantFPSDNode>(NotZero)) {
118 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
119 convertToAPInt().isAllOnesValue())
124 // Okay, we have at least one ~0 value, check to see if the rest match or are
126 for (++i; i != e; ++i)
127 if (N->getOperand(i) != NotZero &&
128 N->getOperand(i).getOpcode() != ISD::UNDEF)
134 /// isBuildVectorAllZeros - Return true if the specified node is a
135 /// BUILD_VECTOR where all of the elements are 0 or undef.
136 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
137 // Look through a bit convert.
138 if (N->getOpcode() == ISD::BIT_CONVERT)
139 N = N->getOperand(0).Val;
141 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
143 unsigned i = 0, e = N->getNumOperands();
145 // Skip over all of the undef values.
146 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
149 // Do not accept an all-undef vector.
150 if (i == e) return false;
152 // Do not accept build_vectors that aren't all constants or which have non-~0
154 SDOperand Zero = N->getOperand(i);
155 if (isa<ConstantSDNode>(Zero)) {
156 if (!cast<ConstantSDNode>(Zero)->isNullValue())
158 } else if (isa<ConstantFPSDNode>(Zero)) {
159 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
164 // Okay, we have at least one ~0 value, check to see if the rest match or are
166 for (++i; i != e; ++i)
167 if (N->getOperand(i) != Zero &&
168 N->getOperand(i).getOpcode() != ISD::UNDEF)
173 /// isScalarToVector - Return true if the specified node is a
174 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
175 /// element is not an undef.
176 bool ISD::isScalarToVector(const SDNode *N) {
177 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
180 if (N->getOpcode() != ISD::BUILD_VECTOR)
182 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
184 unsigned NumElems = N->getNumOperands();
185 for (unsigned i = 1; i < NumElems; ++i) {
186 SDOperand V = N->getOperand(i);
187 if (V.getOpcode() != ISD::UNDEF)
194 /// isDebugLabel - Return true if the specified node represents a debug
195 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
196 bool ISD::isDebugLabel(const SDNode *N) {
198 if (N->getOpcode() == ISD::DBG_LABEL)
200 if (N->isTargetOpcode() &&
201 N->getTargetOpcode() == TargetInstrInfo::DBG_LABEL)
206 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
207 /// when given the operation for (X op Y).
208 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
209 // To perform this operation, we just need to swap the L and G bits of the
211 unsigned OldL = (Operation >> 2) & 1;
212 unsigned OldG = (Operation >> 1) & 1;
213 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
214 (OldL << 1) | // New G bit
215 (OldG << 2)); // New L bit.
218 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
219 /// 'op' is a valid SetCC operation.
220 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
221 unsigned Operation = Op;
223 Operation ^= 7; // Flip L, G, E bits, but not U.
225 Operation ^= 15; // Flip all of the condition bits.
226 if (Operation > ISD::SETTRUE2)
227 Operation &= ~8; // Don't let N and U bits get set.
228 return ISD::CondCode(Operation);
232 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
233 /// signed operation and 2 if the result is an unsigned comparison. Return zero
234 /// if the operation does not depend on the sign of the input (setne and seteq).
235 static int isSignedOp(ISD::CondCode Opcode) {
237 default: assert(0 && "Illegal integer setcc operation!");
239 case ISD::SETNE: return 0;
243 case ISD::SETGE: return 1;
247 case ISD::SETUGE: return 2;
251 /// getSetCCOrOperation - Return the result of a logical OR between different
252 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
253 /// returns SETCC_INVALID if it is not possible to represent the resultant
255 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
257 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
258 // Cannot fold a signed integer setcc with an unsigned integer setcc.
259 return ISD::SETCC_INVALID;
261 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
263 // If the N and U bits get set then the resultant comparison DOES suddenly
264 // care about orderedness, and is true when ordered.
265 if (Op > ISD::SETTRUE2)
266 Op &= ~16; // Clear the U bit if the N bit is set.
268 // Canonicalize illegal integer setcc's.
269 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
272 return ISD::CondCode(Op);
275 /// getSetCCAndOperation - Return the result of a logical AND between different
276 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
277 /// function returns zero if it is not possible to represent the resultant
279 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
281 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
282 // Cannot fold a signed setcc with an unsigned setcc.
283 return ISD::SETCC_INVALID;
285 // Combine all of the condition bits.
286 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
288 // Canonicalize illegal integer setcc's.
292 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
293 case ISD::SETOEQ: // SETEQ & SETU[LG]E
294 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
295 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
296 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
303 const TargetMachine &SelectionDAG::getTarget() const {
304 return TLI.getTargetMachine();
307 //===----------------------------------------------------------------------===//
308 // SDNode Profile Support
309 //===----------------------------------------------------------------------===//
311 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
313 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
317 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
318 /// solely with their pointer.
319 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
320 ID.AddPointer(VTList.VTs);
323 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
325 static void AddNodeIDOperands(FoldingSetNodeID &ID,
326 SDOperandPtr Ops, unsigned NumOps) {
327 for (; NumOps; --NumOps, ++Ops) {
328 ID.AddPointer(Ops->Val);
329 ID.AddInteger(Ops->ResNo);
333 static void AddNodeIDNode(FoldingSetNodeID &ID,
334 unsigned short OpC, SDVTList VTList,
335 SDOperandPtr OpList, unsigned N) {
336 AddNodeIDOpcode(ID, OpC);
337 AddNodeIDValueTypes(ID, VTList);
338 AddNodeIDOperands(ID, OpList, N);
342 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
344 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
345 AddNodeIDOpcode(ID, N->getOpcode());
346 // Add the return value info.
347 AddNodeIDValueTypes(ID, N->getVTList());
348 // Add the operand info.
349 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
351 // Handle SDNode leafs with special info.
352 switch (N->getOpcode()) {
353 default: break; // Normal nodes don't need extra info.
355 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
357 case ISD::TargetConstant:
359 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
361 case ISD::TargetConstantFP:
362 case ISD::ConstantFP: {
363 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
366 case ISD::TargetGlobalAddress:
367 case ISD::GlobalAddress:
368 case ISD::TargetGlobalTLSAddress:
369 case ISD::GlobalTLSAddress: {
370 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
371 ID.AddPointer(GA->getGlobal());
372 ID.AddInteger(GA->getOffset());
375 case ISD::BasicBlock:
376 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
379 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
381 case ISD::DBG_STOPPOINT: {
382 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
383 ID.AddInteger(DSP->getLine());
384 ID.AddInteger(DSP->getColumn());
385 ID.AddPointer(DSP->getCompileUnit());
390 ID.AddInteger(cast<LabelSDNode>(N)->getLabelID());
393 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
395 case ISD::MEMOPERAND: {
396 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
397 ID.AddPointer(MO.getValue());
398 ID.AddInteger(MO.getFlags());
399 ID.AddInteger(MO.getOffset());
400 ID.AddInteger(MO.getSize());
401 ID.AddInteger(MO.getAlignment());
404 case ISD::FrameIndex:
405 case ISD::TargetFrameIndex:
406 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
409 case ISD::TargetJumpTable:
410 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
412 case ISD::ConstantPool:
413 case ISD::TargetConstantPool: {
414 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
415 ID.AddInteger(CP->getAlignment());
416 ID.AddInteger(CP->getOffset());
417 if (CP->isMachineConstantPoolEntry())
418 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
420 ID.AddPointer(CP->getConstVal());
424 LoadSDNode *LD = cast<LoadSDNode>(N);
425 ID.AddInteger(LD->getAddressingMode());
426 ID.AddInteger(LD->getExtensionType());
427 ID.AddInteger(LD->getMemoryVT().getRawBits());
428 ID.AddInteger(LD->getAlignment());
429 ID.AddInteger(LD->isVolatile());
433 StoreSDNode *ST = cast<StoreSDNode>(N);
434 ID.AddInteger(ST->getAddressingMode());
435 ID.AddInteger(ST->isTruncatingStore());
436 ID.AddInteger(ST->getMemoryVT().getRawBits());
437 ID.AddInteger(ST->getAlignment());
438 ID.AddInteger(ST->isVolatile());
441 case ISD::ATOMIC_CMP_SWAP:
442 case ISD::ATOMIC_LOAD_ADD:
443 case ISD::ATOMIC_SWAP:
444 case ISD::ATOMIC_LOAD_SUB:
445 case ISD::ATOMIC_LOAD_AND:
446 case ISD::ATOMIC_LOAD_OR:
447 case ISD::ATOMIC_LOAD_XOR:
448 case ISD::ATOMIC_LOAD_NAND:
449 case ISD::ATOMIC_LOAD_MIN:
450 case ISD::ATOMIC_LOAD_MAX:
451 case ISD::ATOMIC_LOAD_UMIN:
452 case ISD::ATOMIC_LOAD_UMAX: {
453 AtomicSDNode *AT = cast<AtomicSDNode>(N);
454 ID.AddInteger(AT->getAlignment());
455 ID.AddInteger(AT->isVolatile());
458 } // end switch (N->getOpcode())
461 //===----------------------------------------------------------------------===//
462 // SelectionDAG Class
463 //===----------------------------------------------------------------------===//
465 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
467 void SelectionDAG::RemoveDeadNodes() {
468 // Create a dummy node (which is not added to allnodes), that adds a reference
469 // to the root node, preventing it from being deleted.
470 HandleSDNode Dummy(getRoot());
472 SmallVector<SDNode*, 128> DeadNodes;
474 // Add all obviously-dead nodes to the DeadNodes worklist.
475 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
477 DeadNodes.push_back(I);
479 // Process the worklist, deleting the nodes and adding their uses to the
481 while (!DeadNodes.empty()) {
482 SDNode *N = DeadNodes.back();
483 DeadNodes.pop_back();
485 // Take the node out of the appropriate CSE map.
486 RemoveNodeFromCSEMaps(N);
488 // Next, brutally remove the operand list. This is safe to do, as there are
489 // no cycles in the graph.
490 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
491 SDNode *Operand = I->getVal();
492 Operand->removeUser(std::distance(N->op_begin(), I), N);
494 // Now that we removed this operand, see if there are no uses of it left.
495 if (Operand->use_empty())
496 DeadNodes.push_back(Operand);
498 if (N->OperandsNeedDelete) {
499 delete[] N->OperandList;
504 // Finally, remove N itself.
508 // If the root changed (e.g. it was a dead load, update the root).
509 setRoot(Dummy.getValue());
512 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
513 SmallVector<SDNode*, 16> DeadNodes;
514 DeadNodes.push_back(N);
516 // Process the worklist, deleting the nodes and adding their uses to the
518 while (!DeadNodes.empty()) {
519 SDNode *N = DeadNodes.back();
520 DeadNodes.pop_back();
523 UpdateListener->NodeDeleted(N, 0);
525 // Take the node out of the appropriate CSE map.
526 RemoveNodeFromCSEMaps(N);
528 // Next, brutally remove the operand list. This is safe to do, as there are
529 // no cycles in the graph.
530 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
531 SDNode *Operand = I->getVal();
532 Operand->removeUser(std::distance(N->op_begin(), I), N);
534 // Now that we removed this operand, see if there are no uses of it left.
535 if (Operand->use_empty())
536 DeadNodes.push_back(Operand);
538 if (N->OperandsNeedDelete) {
539 delete[] N->OperandList;
544 // Finally, remove N itself.
549 void SelectionDAG::DeleteNode(SDNode *N) {
550 assert(N->use_empty() && "Cannot delete a node that is not dead!");
552 // First take this out of the appropriate CSE map.
553 RemoveNodeFromCSEMaps(N);
555 // Finally, remove uses due to operands of this node, remove from the
556 // AllNodes list, and delete the node.
557 DeleteNodeNotInCSEMaps(N);
560 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
562 // Remove it from the AllNodes list.
565 // Drop all of the operands and decrement used nodes use counts.
566 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
567 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
568 if (N->OperandsNeedDelete) {
569 delete[] N->OperandList;
577 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
578 /// correspond to it. This is useful when we're about to delete or repurpose
579 /// the node. We don't want future request for structurally identical nodes
580 /// to return N anymore.
581 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
583 switch (N->getOpcode()) {
584 case ISD::HANDLENODE: return; // noop.
586 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
587 "Cond code doesn't exist!");
588 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
589 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
591 case ISD::ExternalSymbol:
592 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
594 case ISD::TargetExternalSymbol:
596 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
598 case ISD::VALUETYPE: {
599 MVT VT = cast<VTSDNode>(N)->getVT();
600 if (VT.isExtended()) {
601 Erased = ExtendedValueTypeNodes.erase(VT);
603 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
604 ValueTypeNodes[VT.getSimpleVT()] = 0;
609 // Remove it from the CSE Map.
610 Erased = CSEMap.RemoveNode(N);
614 // Verify that the node was actually in one of the CSE maps, unless it has a
615 // flag result (which cannot be CSE'd) or is one of the special cases that are
616 // not subject to CSE.
617 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
618 !N->isTargetOpcode()) {
621 assert(0 && "Node is not in map!");
626 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
627 /// has been taken out and modified in some way. If the specified node already
628 /// exists in the CSE maps, do not modify the maps, but return the existing node
629 /// instead. If it doesn't exist, add it and return null.
631 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
632 assert(N->getNumOperands() && "This is a leaf node!");
633 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
634 return 0; // Never add these nodes.
636 // Check that remaining values produced are not flags.
637 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
638 if (N->getValueType(i) == MVT::Flag)
639 return 0; // Never CSE anything that produces a flag.
641 SDNode *New = CSEMap.GetOrInsertNode(N);
642 if (New != N) return New; // Node already existed.
646 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
647 /// were replaced with those specified. If this node is never memoized,
648 /// return null, otherwise return a pointer to the slot it would take. If a
649 /// node already exists with these operands, the slot will be non-null.
650 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
652 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
653 return 0; // Never add these nodes.
655 // Check that remaining values produced are not flags.
656 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
657 if (N->getValueType(i) == MVT::Flag)
658 return 0; // Never CSE anything that produces a flag.
660 SDOperand Ops[] = { Op };
662 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
663 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
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.
670 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
671 SDOperand Op1, SDOperand Op2,
673 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
674 return 0; // Never add these nodes.
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.
681 SDOperand Ops[] = { Op1, Op2 };
683 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
684 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
688 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
689 /// were replaced with those specified. If this node is never memoized,
690 /// return null, otherwise return a pointer to the slot it would take. If a
691 /// node already exists with these operands, the slot will be non-null.
692 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
693 SDOperandPtr Ops,unsigned NumOps,
695 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
696 return 0; // Never add these nodes.
698 // Check that remaining values produced are not flags.
699 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
700 if (N->getValueType(i) == MVT::Flag)
701 return 0; // Never CSE anything that produces a flag.
704 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
706 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
707 ID.AddInteger(LD->getAddressingMode());
708 ID.AddInteger(LD->getExtensionType());
709 ID.AddInteger(LD->getMemoryVT().getRawBits());
710 ID.AddInteger(LD->getAlignment());
711 ID.AddInteger(LD->isVolatile());
712 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
713 ID.AddInteger(ST->getAddressingMode());
714 ID.AddInteger(ST->isTruncatingStore());
715 ID.AddInteger(ST->getMemoryVT().getRawBits());
716 ID.AddInteger(ST->getAlignment());
717 ID.AddInteger(ST->isVolatile());
720 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
724 SelectionDAG::~SelectionDAG() {
725 while (!AllNodes.empty()) {
726 SDNode *N = AllNodes.begin();
727 N->SetNextInBucket(0);
728 if (N->OperandsNeedDelete) {
729 delete [] N->OperandList;
733 AllNodes.pop_front();
737 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
738 if (Op.getValueType() == VT) return Op;
739 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
741 return getNode(ISD::AND, Op.getValueType(), Op,
742 getConstant(Imm, Op.getValueType()));
745 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
746 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
747 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
750 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
751 assert(VT.isInteger() && "Cannot create FP integer constant!");
753 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
754 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
755 "APInt size does not match type size!");
757 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
759 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
763 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
765 return SDOperand(N, 0);
767 N = new ConstantSDNode(isT, Val, EltVT);
768 CSEMap.InsertNode(N, IP);
769 AllNodes.push_back(N);
772 SDOperand Result(N, 0);
774 SmallVector<SDOperand, 8> Ops;
775 Ops.assign(VT.getVectorNumElements(), Result);
776 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
781 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
782 return getConstant(Val, TLI.getPointerTy(), isTarget);
786 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
787 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
790 VT.isVector() ? VT.getVectorElementType() : VT;
792 // Do the map lookup using the actual bit pattern for the floating point
793 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
794 // we don't have issues with SNANs.
795 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
797 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
801 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
803 return SDOperand(N, 0);
805 N = new ConstantFPSDNode(isTarget, V, EltVT);
806 CSEMap.InsertNode(N, IP);
807 AllNodes.push_back(N);
810 SDOperand Result(N, 0);
812 SmallVector<SDOperand, 8> Ops;
813 Ops.assign(VT.getVectorNumElements(), Result);
814 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
819 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
821 VT.isVector() ? VT.getVectorElementType() : VT;
823 return getConstantFP(APFloat((float)Val), VT, isTarget);
825 return getConstantFP(APFloat(Val), VT, isTarget);
828 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
833 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
835 // If GV is an alias then use the aliasee for determining thread-localness.
836 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
837 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
840 if (GVar && GVar->isThreadLocal())
841 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
843 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
846 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
848 ID.AddInteger(Offset);
850 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
851 return SDOperand(E, 0);
852 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
853 CSEMap.InsertNode(N, IP);
854 AllNodes.push_back(N);
855 return SDOperand(N, 0);
858 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
859 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
861 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
864 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
865 return SDOperand(E, 0);
866 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
867 CSEMap.InsertNode(N, IP);
868 AllNodes.push_back(N);
869 return SDOperand(N, 0);
872 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
873 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
875 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
878 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
879 return SDOperand(E, 0);
880 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
881 CSEMap.InsertNode(N, IP);
882 AllNodes.push_back(N);
883 return SDOperand(N, 0);
886 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
887 unsigned Alignment, int Offset,
889 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
891 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
892 ID.AddInteger(Alignment);
893 ID.AddInteger(Offset);
896 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
897 return SDOperand(E, 0);
898 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
899 CSEMap.InsertNode(N, IP);
900 AllNodes.push_back(N);
901 return SDOperand(N, 0);
905 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
906 unsigned Alignment, int Offset,
908 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
910 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
911 ID.AddInteger(Alignment);
912 ID.AddInteger(Offset);
913 C->AddSelectionDAGCSEId(ID);
915 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
916 return SDOperand(E, 0);
917 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
918 CSEMap.InsertNode(N, IP);
919 AllNodes.push_back(N);
920 return SDOperand(N, 0);
924 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
926 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), (SDOperand*)0, 0);
929 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
930 return SDOperand(E, 0);
931 SDNode *N = new BasicBlockSDNode(MBB);
932 CSEMap.InsertNode(N, IP);
933 AllNodes.push_back(N);
934 return SDOperand(N, 0);
937 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
939 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), (SDOperand*)0, 0);
940 ID.AddInteger(Flags.getRawBits());
942 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
943 return SDOperand(E, 0);
944 SDNode *N = new ARG_FLAGSSDNode(Flags);
945 CSEMap.InsertNode(N, IP);
946 AllNodes.push_back(N);
947 return SDOperand(N, 0);
950 SDOperand SelectionDAG::getValueType(MVT VT) {
951 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
952 ValueTypeNodes.resize(VT.getSimpleVT()+1);
954 SDNode *&N = VT.isExtended() ?
955 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
957 if (N) return SDOperand(N, 0);
958 N = new VTSDNode(VT);
959 AllNodes.push_back(N);
960 return SDOperand(N, 0);
963 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
964 SDNode *&N = ExternalSymbols[Sym];
965 if (N) return SDOperand(N, 0);
966 N = new ExternalSymbolSDNode(false, Sym, VT);
967 AllNodes.push_back(N);
968 return SDOperand(N, 0);
971 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
972 SDNode *&N = TargetExternalSymbols[Sym];
973 if (N) return SDOperand(N, 0);
974 N = new ExternalSymbolSDNode(true, Sym, VT);
975 AllNodes.push_back(N);
976 return SDOperand(N, 0);
979 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
980 if ((unsigned)Cond >= CondCodeNodes.size())
981 CondCodeNodes.resize(Cond+1);
983 if (CondCodeNodes[Cond] == 0) {
984 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
985 AllNodes.push_back(CondCodeNodes[Cond]);
987 return SDOperand(CondCodeNodes[Cond], 0);
990 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
992 AddNodeIDNode(ID, ISD::Register, getVTList(VT), (SDOperand*)0, 0);
993 ID.AddInteger(RegNo);
995 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
996 return SDOperand(E, 0);
997 SDNode *N = new RegisterSDNode(RegNo, VT);
998 CSEMap.InsertNode(N, IP);
999 AllNodes.push_back(N);
1000 return SDOperand(N, 0);
1003 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
1004 unsigned Line, unsigned Col,
1005 const CompileUnitDesc *CU) {
1006 FoldingSetNodeID ID;
1007 SDOperand Ops[] = { Root };
1008 AddNodeIDNode(ID, ISD::DBG_STOPPOINT, getVTList(MVT::Other), &Ops[0], 1);
1009 ID.AddInteger(Line);
1013 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1014 return SDOperand(E, 0);
1015 SDNode *N = new DbgStopPointSDNode(Root, Line, Col, CU);
1016 CSEMap.InsertNode(N, IP);
1017 AllNodes.push_back(N);
1018 return SDOperand(N, 0);
1021 SDOperand SelectionDAG::getLabel(unsigned Opcode,
1024 FoldingSetNodeID ID;
1025 SDOperand Ops[] = { Root };
1026 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1027 ID.AddInteger(LabelID);
1029 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1030 return SDOperand(E, 0);
1031 SDNode *N = new LabelSDNode(Opcode, Root, LabelID);
1032 CSEMap.InsertNode(N, IP);
1033 AllNodes.push_back(N);
1034 return SDOperand(N, 0);
1037 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1038 assert((!V || isa<PointerType>(V->getType())) &&
1039 "SrcValue is not a pointer?");
1041 FoldingSetNodeID ID;
1042 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), (SDOperand*)0, 0);
1046 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1047 return SDOperand(E, 0);
1049 SDNode *N = new SrcValueSDNode(V);
1050 CSEMap.InsertNode(N, IP);
1051 AllNodes.push_back(N);
1052 return SDOperand(N, 0);
1055 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1056 const Value *v = MO.getValue();
1057 assert((!v || isa<PointerType>(v->getType())) &&
1058 "SrcValue is not a pointer?");
1060 FoldingSetNodeID ID;
1061 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), (SDOperand*)0, 0);
1063 ID.AddInteger(MO.getFlags());
1064 ID.AddInteger(MO.getOffset());
1065 ID.AddInteger(MO.getSize());
1066 ID.AddInteger(MO.getAlignment());
1069 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1070 return SDOperand(E, 0);
1072 SDNode *N = new MemOperandSDNode(MO);
1073 CSEMap.InsertNode(N, IP);
1074 AllNodes.push_back(N);
1075 return SDOperand(N, 0);
1078 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1079 /// specified value type.
1080 SDOperand SelectionDAG::CreateStackTemporary(MVT VT) {
1081 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1082 unsigned ByteSize = VT.getSizeInBits()/8;
1083 const Type *Ty = VT.getTypeForMVT();
1084 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
1085 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1086 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1090 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1091 SDOperand N2, ISD::CondCode Cond) {
1092 // These setcc operations always fold.
1096 case ISD::SETFALSE2: return getConstant(0, VT);
1098 case ISD::SETTRUE2: return getConstant(1, VT);
1110 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1114 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1115 const APInt &C2 = N2C->getAPIntValue();
1116 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1117 const APInt &C1 = N1C->getAPIntValue();
1120 default: assert(0 && "Unknown integer setcc!");
1121 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1122 case ISD::SETNE: return getConstant(C1 != C2, VT);
1123 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1124 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1125 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1126 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1127 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1128 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1129 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1130 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1134 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1135 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1136 // No compile time operations on this type yet.
1137 if (N1C->getValueType(0) == MVT::ppcf128)
1140 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1143 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1144 return getNode(ISD::UNDEF, VT);
1146 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1147 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1148 return getNode(ISD::UNDEF, VT);
1150 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1151 R==APFloat::cmpLessThan, VT);
1152 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1153 return getNode(ISD::UNDEF, VT);
1155 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1156 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1157 return getNode(ISD::UNDEF, VT);
1159 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1160 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1161 return getNode(ISD::UNDEF, VT);
1163 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1164 R==APFloat::cmpEqual, VT);
1165 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1166 return getNode(ISD::UNDEF, VT);
1168 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1169 R==APFloat::cmpEqual, VT);
1170 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1171 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1172 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1173 R==APFloat::cmpEqual, VT);
1174 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1175 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1176 R==APFloat::cmpLessThan, VT);
1177 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1178 R==APFloat::cmpUnordered, VT);
1179 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1180 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1183 // Ensure that the constant occurs on the RHS.
1184 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1188 // Could not fold it.
1192 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1193 /// use this predicate to simplify operations downstream.
1194 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1195 unsigned BitWidth = Op.getValueSizeInBits();
1196 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1199 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1200 /// this predicate to simplify operations downstream. Mask is known to be zero
1201 /// for bits that V cannot have.
1202 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1203 unsigned Depth) const {
1204 APInt KnownZero, KnownOne;
1205 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1206 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1207 return (KnownZero & Mask) == Mask;
1210 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1211 /// known to be either zero or one and return them in the KnownZero/KnownOne
1212 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1214 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1215 APInt &KnownZero, APInt &KnownOne,
1216 unsigned Depth) const {
1217 unsigned BitWidth = Mask.getBitWidth();
1218 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1219 "Mask size mismatches value type size!");
1221 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1222 if (Depth == 6 || Mask == 0)
1223 return; // Limit search depth.
1225 APInt KnownZero2, KnownOne2;
1227 switch (Op.getOpcode()) {
1229 // We know all of the bits for a constant!
1230 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1231 KnownZero = ~KnownOne & Mask;
1234 // If either the LHS or the RHS are Zero, the result is zero.
1235 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1236 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1237 KnownZero2, KnownOne2, Depth+1);
1238 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1239 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1241 // Output known-1 bits are only known if set in both the LHS & RHS.
1242 KnownOne &= KnownOne2;
1243 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1244 KnownZero |= KnownZero2;
1247 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1248 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1249 KnownZero2, KnownOne2, Depth+1);
1250 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1251 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1253 // Output known-0 bits are only known if clear in both the LHS & RHS.
1254 KnownZero &= KnownZero2;
1255 // Output known-1 are known to be set if set in either the LHS | RHS.
1256 KnownOne |= KnownOne2;
1259 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1260 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1261 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1262 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1264 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1265 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1266 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1267 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1268 KnownZero = KnownZeroOut;
1272 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1273 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1274 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1275 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1276 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1278 // If low bits are zero in either operand, output low known-0 bits.
1279 // Also compute a conserative estimate for high known-0 bits.
1280 // More trickiness is possible, but this is sufficient for the
1281 // interesting case of alignment computation.
1283 unsigned TrailZ = KnownZero.countTrailingOnes() +
1284 KnownZero2.countTrailingOnes();
1285 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1286 KnownZero2.countLeadingOnes(),
1287 BitWidth) - BitWidth;
1289 TrailZ = std::min(TrailZ, BitWidth);
1290 LeadZ = std::min(LeadZ, BitWidth);
1291 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1292 APInt::getHighBitsSet(BitWidth, LeadZ);
1297 // For the purposes of computing leading zeros we can conservatively
1298 // treat a udiv as a logical right shift by the power of 2 known to
1299 // be less than the denominator.
1300 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1301 ComputeMaskedBits(Op.getOperand(0),
1302 AllOnes, KnownZero2, KnownOne2, Depth+1);
1303 unsigned LeadZ = KnownZero2.countLeadingOnes();
1307 ComputeMaskedBits(Op.getOperand(1),
1308 AllOnes, KnownZero2, KnownOne2, Depth+1);
1309 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1310 if (RHSUnknownLeadingOnes != BitWidth)
1311 LeadZ = std::min(BitWidth,
1312 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1314 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1318 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1319 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1320 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1321 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1323 // Only known if known in both the LHS and RHS.
1324 KnownOne &= KnownOne2;
1325 KnownZero &= KnownZero2;
1327 case ISD::SELECT_CC:
1328 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1329 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1330 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1331 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1333 // Only known if known in both the LHS and RHS.
1334 KnownOne &= KnownOne2;
1335 KnownZero &= KnownZero2;
1338 // If we know the result of a setcc has the top bits zero, use this info.
1339 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1341 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1344 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1345 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1346 unsigned ShAmt = SA->getValue();
1348 // If the shift count is an invalid immediate, don't do anything.
1349 if (ShAmt >= BitWidth)
1352 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1353 KnownZero, KnownOne, Depth+1);
1354 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1355 KnownZero <<= ShAmt;
1357 // low bits known zero.
1358 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1362 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1363 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1364 unsigned ShAmt = SA->getValue();
1366 // If the shift count is an invalid immediate, don't do anything.
1367 if (ShAmt >= BitWidth)
1370 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1371 KnownZero, KnownOne, Depth+1);
1372 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1373 KnownZero = KnownZero.lshr(ShAmt);
1374 KnownOne = KnownOne.lshr(ShAmt);
1376 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1377 KnownZero |= HighBits; // High bits known zero.
1381 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1382 unsigned ShAmt = SA->getValue();
1384 // If the shift count is an invalid immediate, don't do anything.
1385 if (ShAmt >= BitWidth)
1388 APInt InDemandedMask = (Mask << ShAmt);
1389 // If any of the demanded bits are produced by the sign extension, we also
1390 // demand the input sign bit.
1391 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1392 if (HighBits.getBoolValue())
1393 InDemandedMask |= APInt::getSignBit(BitWidth);
1395 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1397 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1398 KnownZero = KnownZero.lshr(ShAmt);
1399 KnownOne = KnownOne.lshr(ShAmt);
1401 // Handle the sign bits.
1402 APInt SignBit = APInt::getSignBit(BitWidth);
1403 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1405 if (KnownZero.intersects(SignBit)) {
1406 KnownZero |= HighBits; // New bits are known zero.
1407 } else if (KnownOne.intersects(SignBit)) {
1408 KnownOne |= HighBits; // New bits are known one.
1412 case ISD::SIGN_EXTEND_INREG: {
1413 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1414 unsigned EBits = EVT.getSizeInBits();
1416 // Sign extension. Compute the demanded bits in the result that are not
1417 // present in the input.
1418 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1420 APInt InSignBit = APInt::getSignBit(EBits);
1421 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1423 // If the sign extended bits are demanded, we know that the sign
1425 InSignBit.zext(BitWidth);
1426 if (NewBits.getBoolValue())
1427 InputDemandedBits |= InSignBit;
1429 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1430 KnownZero, KnownOne, Depth+1);
1431 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1433 // If the sign bit of the input is known set or clear, then we know the
1434 // top bits of the result.
1435 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1436 KnownZero |= NewBits;
1437 KnownOne &= ~NewBits;
1438 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1439 KnownOne |= NewBits;
1440 KnownZero &= ~NewBits;
1441 } else { // Input sign bit unknown
1442 KnownZero &= ~NewBits;
1443 KnownOne &= ~NewBits;
1450 unsigned LowBits = Log2_32(BitWidth)+1;
1451 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1456 if (ISD::isZEXTLoad(Op.Val)) {
1457 LoadSDNode *LD = cast<LoadSDNode>(Op);
1458 MVT VT = LD->getMemoryVT();
1459 unsigned MemBits = VT.getSizeInBits();
1460 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1464 case ISD::ZERO_EXTEND: {
1465 MVT InVT = Op.getOperand(0).getValueType();
1466 unsigned InBits = InVT.getSizeInBits();
1467 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1468 APInt InMask = Mask;
1469 InMask.trunc(InBits);
1470 KnownZero.trunc(InBits);
1471 KnownOne.trunc(InBits);
1472 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1473 KnownZero.zext(BitWidth);
1474 KnownOne.zext(BitWidth);
1475 KnownZero |= NewBits;
1478 case ISD::SIGN_EXTEND: {
1479 MVT InVT = Op.getOperand(0).getValueType();
1480 unsigned InBits = InVT.getSizeInBits();
1481 APInt InSignBit = APInt::getSignBit(InBits);
1482 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1483 APInt InMask = Mask;
1484 InMask.trunc(InBits);
1486 // If any of the sign extended bits are demanded, we know that the sign
1487 // bit is demanded. Temporarily set this bit in the mask for our callee.
1488 if (NewBits.getBoolValue())
1489 InMask |= InSignBit;
1491 KnownZero.trunc(InBits);
1492 KnownOne.trunc(InBits);
1493 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1495 // Note if the sign bit is known to be zero or one.
1496 bool SignBitKnownZero = KnownZero.isNegative();
1497 bool SignBitKnownOne = KnownOne.isNegative();
1498 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1499 "Sign bit can't be known to be both zero and one!");
1501 // If the sign bit wasn't actually demanded by our caller, we don't
1502 // want it set in the KnownZero and KnownOne result values. Reset the
1503 // mask and reapply it to the result values.
1505 InMask.trunc(InBits);
1506 KnownZero &= InMask;
1509 KnownZero.zext(BitWidth);
1510 KnownOne.zext(BitWidth);
1512 // If the sign bit is known zero or one, the top bits match.
1513 if (SignBitKnownZero)
1514 KnownZero |= NewBits;
1515 else if (SignBitKnownOne)
1516 KnownOne |= NewBits;
1519 case ISD::ANY_EXTEND: {
1520 MVT InVT = Op.getOperand(0).getValueType();
1521 unsigned InBits = InVT.getSizeInBits();
1522 APInt InMask = Mask;
1523 InMask.trunc(InBits);
1524 KnownZero.trunc(InBits);
1525 KnownOne.trunc(InBits);
1526 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1527 KnownZero.zext(BitWidth);
1528 KnownOne.zext(BitWidth);
1531 case ISD::TRUNCATE: {
1532 MVT InVT = Op.getOperand(0).getValueType();
1533 unsigned InBits = InVT.getSizeInBits();
1534 APInt InMask = Mask;
1535 InMask.zext(InBits);
1536 KnownZero.zext(InBits);
1537 KnownOne.zext(InBits);
1538 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1539 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1540 KnownZero.trunc(BitWidth);
1541 KnownOne.trunc(BitWidth);
1544 case ISD::AssertZext: {
1545 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1546 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1547 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1549 KnownZero |= (~InMask) & Mask;
1553 // All bits are zero except the low bit.
1554 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1558 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1559 // We know that the top bits of C-X are clear if X contains less bits
1560 // than C (i.e. no wrap-around can happen). For example, 20-X is
1561 // positive if we can prove that X is >= 0 and < 16.
1562 if (CLHS->getAPIntValue().isNonNegative()) {
1563 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1564 // NLZ can't be BitWidth with no sign bit
1565 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1566 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1569 // If all of the MaskV bits are known to be zero, then we know the
1570 // output top bits are zero, because we now know that the output is
1572 if ((KnownZero2 & MaskV) == MaskV) {
1573 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1574 // Top bits known zero.
1575 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1582 // Output known-0 bits are known if clear or set in both the low clear bits
1583 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1584 // low 3 bits clear.
1585 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1586 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1587 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1588 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1590 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1591 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1592 KnownZeroOut = std::min(KnownZeroOut,
1593 KnownZero2.countTrailingOnes());
1595 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1599 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1600 APInt RA = Rem->getAPIntValue();
1601 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1602 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1603 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1604 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1606 // The sign of a remainder is equal to the sign of the first
1607 // operand (zero being positive).
1608 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1609 KnownZero2 |= ~LowBits;
1610 else if (KnownOne2[BitWidth-1])
1611 KnownOne2 |= ~LowBits;
1613 KnownZero |= KnownZero2 & Mask;
1614 KnownOne |= KnownOne2 & Mask;
1616 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1621 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1622 APInt RA = Rem->getAPIntValue();
1623 if (RA.isPowerOf2()) {
1624 APInt LowBits = (RA - 1);
1625 APInt Mask2 = LowBits & Mask;
1626 KnownZero |= ~LowBits & Mask;
1627 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1628 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1633 // Since the result is less than or equal to either operand, any leading
1634 // zero bits in either operand must also exist in the result.
1635 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1636 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1638 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1641 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1642 KnownZero2.countLeadingOnes());
1644 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1648 // Allow the target to implement this method for its nodes.
1649 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1650 case ISD::INTRINSIC_WO_CHAIN:
1651 case ISD::INTRINSIC_W_CHAIN:
1652 case ISD::INTRINSIC_VOID:
1653 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1659 /// ComputeNumSignBits - Return the number of times the sign bit of the
1660 /// register is replicated into the other bits. We know that at least 1 bit
1661 /// is always equal to the sign bit (itself), but other cases can give us
1662 /// information. For example, immediately after an "SRA X, 2", we know that
1663 /// the top 3 bits are all equal to each other, so we return 3.
1664 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1665 MVT VT = Op.getValueType();
1666 assert(VT.isInteger() && "Invalid VT!");
1667 unsigned VTBits = VT.getSizeInBits();
1669 unsigned FirstAnswer = 1;
1672 return 1; // Limit search depth.
1674 switch (Op.getOpcode()) {
1676 case ISD::AssertSext:
1677 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1678 return VTBits-Tmp+1;
1679 case ISD::AssertZext:
1680 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1683 case ISD::Constant: {
1684 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1685 // If negative, return # leading ones.
1686 if (Val.isNegative())
1687 return Val.countLeadingOnes();
1689 // Return # leading zeros.
1690 return Val.countLeadingZeros();
1693 case ISD::SIGN_EXTEND:
1694 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1695 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1697 case ISD::SIGN_EXTEND_INREG:
1698 // Max of the input and what this extends.
1699 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1702 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1703 return std::max(Tmp, Tmp2);
1706 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1707 // SRA X, C -> adds C sign bits.
1708 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1709 Tmp += C->getValue();
1710 if (Tmp > VTBits) Tmp = VTBits;
1714 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1715 // shl destroys sign bits.
1716 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1717 if (C->getValue() >= VTBits || // Bad shift.
1718 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1719 return Tmp - C->getValue();
1724 case ISD::XOR: // NOT is handled here.
1725 // Logical binary ops preserve the number of sign bits at the worst.
1726 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1728 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1729 FirstAnswer = std::min(Tmp, Tmp2);
1730 // We computed what we know about the sign bits as our first
1731 // answer. Now proceed to the generic code that uses
1732 // ComputeMaskedBits, and pick whichever answer is better.
1737 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1738 if (Tmp == 1) return 1; // Early out.
1739 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1740 return std::min(Tmp, Tmp2);
1743 // If setcc returns 0/-1, all bits are sign bits.
1744 if (TLI.getSetCCResultContents() ==
1745 TargetLowering::ZeroOrNegativeOneSetCCResult)
1750 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1751 unsigned RotAmt = C->getValue() & (VTBits-1);
1753 // Handle rotate right by N like a rotate left by 32-N.
1754 if (Op.getOpcode() == ISD::ROTR)
1755 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1757 // If we aren't rotating out all of the known-in sign bits, return the
1758 // number that are left. This handles rotl(sext(x), 1) for example.
1759 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1760 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1764 // Add can have at most one carry bit. Thus we know that the output
1765 // is, at worst, one more bit than the inputs.
1766 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1767 if (Tmp == 1) return 1; // Early out.
1769 // Special case decrementing a value (ADD X, -1):
1770 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1771 if (CRHS->isAllOnesValue()) {
1772 APInt KnownZero, KnownOne;
1773 APInt Mask = APInt::getAllOnesValue(VTBits);
1774 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1776 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1778 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1781 // If we are subtracting one from a positive number, there is no carry
1782 // out of the result.
1783 if (KnownZero.isNegative())
1787 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1788 if (Tmp2 == 1) return 1;
1789 return std::min(Tmp, Tmp2)-1;
1793 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1794 if (Tmp2 == 1) return 1;
1797 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1798 if (CLHS->isNullValue()) {
1799 APInt KnownZero, KnownOne;
1800 APInt Mask = APInt::getAllOnesValue(VTBits);
1801 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1802 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1804 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1807 // If the input is known to be positive (the sign bit is known clear),
1808 // the output of the NEG has the same number of sign bits as the input.
1809 if (KnownZero.isNegative())
1812 // Otherwise, we treat this like a SUB.
1815 // Sub can have at most one carry bit. Thus we know that the output
1816 // is, at worst, one more bit than the inputs.
1817 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1818 if (Tmp == 1) return 1; // Early out.
1819 return std::min(Tmp, Tmp2)-1;
1822 // FIXME: it's tricky to do anything useful for this, but it is an important
1823 // case for targets like X86.
1827 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1828 if (Op.getOpcode() == ISD::LOAD) {
1829 LoadSDNode *LD = cast<LoadSDNode>(Op);
1830 unsigned ExtType = LD->getExtensionType();
1833 case ISD::SEXTLOAD: // '17' bits known
1834 Tmp = LD->getMemoryVT().getSizeInBits();
1835 return VTBits-Tmp+1;
1836 case ISD::ZEXTLOAD: // '16' bits known
1837 Tmp = LD->getMemoryVT().getSizeInBits();
1842 // Allow the target to implement this method for its nodes.
1843 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1844 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1845 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1846 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1847 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1848 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1851 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1852 // use this information.
1853 APInt KnownZero, KnownOne;
1854 APInt Mask = APInt::getAllOnesValue(VTBits);
1855 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1857 if (KnownZero.isNegative()) { // sign bit is 0
1859 } else if (KnownOne.isNegative()) { // sign bit is 1;
1866 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1867 // the number of identical bits in the top of the input value.
1869 Mask <<= Mask.getBitWidth()-VTBits;
1870 // Return # leading zeros. We use 'min' here in case Val was zero before
1871 // shifting. We don't want to return '64' as for an i32 "0".
1872 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1876 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1877 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1878 if (!GA) return false;
1879 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1880 if (!GV) return false;
1881 MachineModuleInfo *MMI = getMachineModuleInfo();
1882 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1886 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1887 /// element of the result of the vector shuffle.
1888 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1889 MVT VT = N->getValueType(0);
1890 SDOperand PermMask = N->getOperand(2);
1891 SDOperand Idx = PermMask.getOperand(i);
1892 if (Idx.getOpcode() == ISD::UNDEF)
1893 return getNode(ISD::UNDEF, VT.getVectorElementType());
1894 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1895 unsigned NumElems = PermMask.getNumOperands();
1896 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1899 if (V.getOpcode() == ISD::BIT_CONVERT) {
1900 V = V.getOperand(0);
1901 if (V.getValueType().getVectorNumElements() != NumElems)
1904 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1905 return (Index == 0) ? V.getOperand(0)
1906 : getNode(ISD::UNDEF, VT.getVectorElementType());
1907 if (V.getOpcode() == ISD::BUILD_VECTOR)
1908 return V.getOperand(Index);
1909 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1910 return getShuffleScalarElt(V.Val, Index);
1915 /// getNode - Gets or creates the specified node.
1917 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1918 FoldingSetNodeID ID;
1919 AddNodeIDNode(ID, Opcode, getVTList(VT), (SDOperand*)0, 0);
1921 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1922 return SDOperand(E, 0);
1923 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1924 CSEMap.InsertNode(N, IP);
1926 AllNodes.push_back(N);
1927 return SDOperand(N, 0);
1930 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1931 // Constant fold unary operations with an integer constant operand.
1932 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1933 const APInt &Val = C->getAPIntValue();
1934 unsigned BitWidth = VT.getSizeInBits();
1937 case ISD::SIGN_EXTEND:
1938 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1939 case ISD::ANY_EXTEND:
1940 case ISD::ZERO_EXTEND:
1942 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1943 case ISD::UINT_TO_FP:
1944 case ISD::SINT_TO_FP: {
1945 const uint64_t zero[] = {0, 0};
1946 // No compile time operations on this type.
1947 if (VT==MVT::ppcf128)
1949 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1950 (void)apf.convertFromAPInt(Val,
1951 Opcode==ISD::SINT_TO_FP,
1952 APFloat::rmNearestTiesToEven);
1953 return getConstantFP(apf, VT);
1955 case ISD::BIT_CONVERT:
1956 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1957 return getConstantFP(Val.bitsToFloat(), VT);
1958 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1959 return getConstantFP(Val.bitsToDouble(), VT);
1962 return getConstant(Val.byteSwap(), VT);
1964 return getConstant(Val.countPopulation(), VT);
1966 return getConstant(Val.countLeadingZeros(), VT);
1968 return getConstant(Val.countTrailingZeros(), VT);
1972 // Constant fold unary operations with a floating point constant operand.
1973 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1974 APFloat V = C->getValueAPF(); // make copy
1975 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1979 return getConstantFP(V, VT);
1982 return getConstantFP(V, VT);
1984 case ISD::FP_EXTEND:
1985 // This can return overflow, underflow, or inexact; we don't care.
1986 // FIXME need to be more flexible about rounding mode.
1987 (void)V.convert(*MVTToAPFloatSemantics(VT),
1988 APFloat::rmNearestTiesToEven);
1989 return getConstantFP(V, VT);
1990 case ISD::FP_TO_SINT:
1991 case ISD::FP_TO_UINT: {
1993 assert(integerPartWidth >= 64);
1994 // FIXME need to be more flexible about rounding mode.
1995 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1996 Opcode==ISD::FP_TO_SINT,
1997 APFloat::rmTowardZero);
1998 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2000 return getConstant(x, VT);
2002 case ISD::BIT_CONVERT:
2003 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2004 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2005 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2006 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2012 unsigned OpOpcode = Operand.Val->getOpcode();
2014 case ISD::TokenFactor:
2015 return Operand; // Factor of one node? No need.
2016 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2017 case ISD::FP_EXTEND:
2018 assert(VT.isFloatingPoint() &&
2019 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2020 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2021 if (Operand.getOpcode() == ISD::UNDEF)
2022 return getNode(ISD::UNDEF, VT);
2024 case ISD::SIGN_EXTEND:
2025 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2026 "Invalid SIGN_EXTEND!");
2027 if (Operand.getValueType() == VT) return Operand; // noop extension
2028 assert(Operand.getValueType().bitsLT(VT)
2029 && "Invalid sext node, dst < src!");
2030 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2031 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2033 case ISD::ZERO_EXTEND:
2034 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2035 "Invalid ZERO_EXTEND!");
2036 if (Operand.getValueType() == VT) return Operand; // noop extension
2037 assert(Operand.getValueType().bitsLT(VT)
2038 && "Invalid zext node, dst < src!");
2039 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2040 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2042 case ISD::ANY_EXTEND:
2043 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2044 "Invalid ANY_EXTEND!");
2045 if (Operand.getValueType() == VT) return Operand; // noop extension
2046 assert(Operand.getValueType().bitsLT(VT)
2047 && "Invalid anyext node, dst < src!");
2048 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2049 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2050 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2053 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2054 "Invalid TRUNCATE!");
2055 if (Operand.getValueType() == VT) return Operand; // noop truncate
2056 assert(Operand.getValueType().bitsGT(VT)
2057 && "Invalid truncate node, src < dst!");
2058 if (OpOpcode == ISD::TRUNCATE)
2059 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2060 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2061 OpOpcode == ISD::ANY_EXTEND) {
2062 // If the source is smaller than the dest, we still need an extend.
2063 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2064 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2065 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2066 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2068 return Operand.Val->getOperand(0);
2071 case ISD::BIT_CONVERT:
2072 // Basic sanity checking.
2073 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2074 && "Cannot BIT_CONVERT between types of different sizes!");
2075 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2076 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2077 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2078 if (OpOpcode == ISD::UNDEF)
2079 return getNode(ISD::UNDEF, VT);
2081 case ISD::SCALAR_TO_VECTOR:
2082 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2083 VT.getVectorElementType() == Operand.getValueType() &&
2084 "Illegal SCALAR_TO_VECTOR node!");
2085 if (OpOpcode == ISD::UNDEF)
2086 return getNode(ISD::UNDEF, VT);
2087 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2088 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2089 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2090 Operand.getConstantOperandVal(1) == 0 &&
2091 Operand.getOperand(0).getValueType() == VT)
2092 return Operand.getOperand(0);
2095 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2096 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2097 Operand.Val->getOperand(0));
2098 if (OpOpcode == ISD::FNEG) // --X -> X
2099 return Operand.Val->getOperand(0);
2102 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2103 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2108 SDVTList VTs = getVTList(VT);
2109 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2110 FoldingSetNodeID ID;
2111 SDOperand Ops[1] = { Operand };
2112 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2114 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2115 return SDOperand(E, 0);
2116 N = new UnarySDNode(Opcode, VTs, Operand);
2117 CSEMap.InsertNode(N, IP);
2119 N = new UnarySDNode(Opcode, VTs, Operand);
2121 AllNodes.push_back(N);
2122 return SDOperand(N, 0);
2127 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2128 SDOperand N1, SDOperand N2) {
2129 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2130 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2133 case ISD::TokenFactor:
2134 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2135 N2.getValueType() == MVT::Other && "Invalid token factor!");
2136 // Fold trivial token factors.
2137 if (N1.getOpcode() == ISD::EntryToken) return N2;
2138 if (N2.getOpcode() == ISD::EntryToken) return N1;
2141 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2142 N1.getValueType() == VT && "Binary operator types must match!");
2143 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2144 // worth handling here.
2145 if (N2C && N2C->isNullValue())
2147 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2154 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2155 N1.getValueType() == VT && "Binary operator types must match!");
2156 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2157 // it's worth handling here.
2158 if (N2C && N2C->isNullValue())
2165 assert(VT.isInteger() && "This operator does not apply to FP types!");
2175 assert(N1.getValueType() == N2.getValueType() &&
2176 N1.getValueType() == VT && "Binary operator types must match!");
2178 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2179 assert(N1.getValueType() == VT &&
2180 N1.getValueType().isFloatingPoint() &&
2181 N2.getValueType().isFloatingPoint() &&
2182 "Invalid FCOPYSIGN!");
2189 assert(VT == N1.getValueType() &&
2190 "Shift operators return type must be the same as their first arg");
2191 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2192 VT != MVT::i1 && "Shifts only work on integers");
2194 case ISD::FP_ROUND_INREG: {
2195 MVT EVT = cast<VTSDNode>(N2)->getVT();
2196 assert(VT == N1.getValueType() && "Not an inreg round!");
2197 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2198 "Cannot FP_ROUND_INREG integer types");
2199 assert(EVT.bitsLE(VT) && "Not rounding down!");
2200 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2204 assert(VT.isFloatingPoint() &&
2205 N1.getValueType().isFloatingPoint() &&
2206 VT.bitsLE(N1.getValueType()) &&
2207 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2208 if (N1.getValueType() == VT) return N1; // noop conversion.
2210 case ISD::AssertSext:
2211 case ISD::AssertZext: {
2212 MVT EVT = cast<VTSDNode>(N2)->getVT();
2213 assert(VT == N1.getValueType() && "Not an inreg extend!");
2214 assert(VT.isInteger() && EVT.isInteger() &&
2215 "Cannot *_EXTEND_INREG FP types");
2216 assert(EVT.bitsLE(VT) && "Not extending!");
2217 if (VT == EVT) return N1; // noop assertion.
2220 case ISD::SIGN_EXTEND_INREG: {
2221 MVT EVT = cast<VTSDNode>(N2)->getVT();
2222 assert(VT == N1.getValueType() && "Not an inreg extend!");
2223 assert(VT.isInteger() && EVT.isInteger() &&
2224 "Cannot *_EXTEND_INREG FP types");
2225 assert(EVT.bitsLE(VT) && "Not extending!");
2226 if (EVT == VT) return N1; // Not actually extending
2229 APInt Val = N1C->getAPIntValue();
2230 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2231 Val <<= Val.getBitWidth()-FromBits;
2232 Val = Val.ashr(Val.getBitWidth()-FromBits);
2233 return getConstant(Val, VT);
2237 case ISD::EXTRACT_VECTOR_ELT:
2238 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2240 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2241 if (N1.getOpcode() == ISD::UNDEF)
2242 return getNode(ISD::UNDEF, VT);
2244 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2245 // expanding copies of large vectors from registers.
2246 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2247 N1.getNumOperands() > 0) {
2249 N1.getOperand(0).getValueType().getVectorNumElements();
2250 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2251 N1.getOperand(N2C->getValue() / Factor),
2252 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2255 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2256 // expanding large vector constants.
2257 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2258 return N1.getOperand(N2C->getValue());
2260 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2261 // operations are lowered to scalars.
2262 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2263 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2265 return N1.getOperand(1);
2267 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2270 case ISD::EXTRACT_ELEMENT:
2271 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2272 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2273 (N1.getValueType().isInteger() == VT.isInteger()) &&
2274 "Wrong types for EXTRACT_ELEMENT!");
2276 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2277 // 64-bit integers into 32-bit parts. Instead of building the extract of
2278 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2279 if (N1.getOpcode() == ISD::BUILD_PAIR)
2280 return N1.getOperand(N2C->getValue());
2282 // EXTRACT_ELEMENT of a constant int is also very common.
2283 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2284 unsigned ElementSize = VT.getSizeInBits();
2285 unsigned Shift = ElementSize * N2C->getValue();
2286 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2287 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2290 case ISD::EXTRACT_SUBVECTOR:
2291 if (N1.getValueType() == VT) // Trivial extraction.
2298 APInt C1 = N1C->getAPIntValue(), C2 = N2C->getAPIntValue();
2300 case ISD::ADD: return getConstant(C1 + C2, VT);
2301 case ISD::SUB: return getConstant(C1 - C2, VT);
2302 case ISD::MUL: return getConstant(C1 * C2, VT);
2304 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2307 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2310 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2313 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2315 case ISD::AND : return getConstant(C1 & C2, VT);
2316 case ISD::OR : return getConstant(C1 | C2, VT);
2317 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2318 case ISD::SHL : return getConstant(C1 << C2, VT);
2319 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2320 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2321 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2322 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2325 } else { // Cannonicalize constant to RHS if commutative
2326 if (isCommutativeBinOp(Opcode)) {
2327 std::swap(N1C, N2C);
2333 // Constant fold FP operations.
2334 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2335 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2337 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2338 // Cannonicalize constant to RHS if commutative
2339 std::swap(N1CFP, N2CFP);
2341 } else if (N2CFP && VT != MVT::ppcf128) {
2342 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2343 APFloat::opStatus s;
2346 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2347 if (s != APFloat::opInvalidOp)
2348 return getConstantFP(V1, VT);
2351 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2352 if (s!=APFloat::opInvalidOp)
2353 return getConstantFP(V1, VT);
2356 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2357 if (s!=APFloat::opInvalidOp)
2358 return getConstantFP(V1, VT);
2361 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2362 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2363 return getConstantFP(V1, VT);
2366 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2367 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2368 return getConstantFP(V1, VT);
2370 case ISD::FCOPYSIGN:
2372 return getConstantFP(V1, VT);
2378 // Canonicalize an UNDEF to the RHS, even over a constant.
2379 if (N1.getOpcode() == ISD::UNDEF) {
2380 if (isCommutativeBinOp(Opcode)) {
2384 case ISD::FP_ROUND_INREG:
2385 case ISD::SIGN_EXTEND_INREG:
2391 return N1; // fold op(undef, arg2) -> undef
2399 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2400 // For vectors, we can't easily build an all zero vector, just return
2407 // Fold a bunch of operators when the RHS is undef.
2408 if (N2.getOpcode() == ISD::UNDEF) {
2411 if (N1.getOpcode() == ISD::UNDEF)
2412 // Handle undef ^ undef -> 0 special case. This is a common
2414 return getConstant(0, VT);
2429 return N2; // fold op(arg1, undef) -> undef
2435 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2436 // For vectors, we can't easily build an all zero vector, just return
2441 return getConstant(VT.getIntegerVTBitMask(), VT);
2442 // For vectors, we can't easily build an all one vector, just return
2450 // Memoize this node if possible.
2452 SDVTList VTs = getVTList(VT);
2453 if (VT != MVT::Flag) {
2454 SDOperand Ops[] = { N1, N2 };
2455 FoldingSetNodeID ID;
2456 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2458 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2459 return SDOperand(E, 0);
2460 N = new BinarySDNode(Opcode, VTs, N1, N2);
2461 CSEMap.InsertNode(N, IP);
2463 N = new BinarySDNode(Opcode, VTs, N1, N2);
2466 AllNodes.push_back(N);
2467 return SDOperand(N, 0);
2470 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2471 SDOperand N1, SDOperand N2, SDOperand N3) {
2472 // Perform various simplifications.
2473 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2474 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2477 // Use FoldSetCC to simplify SETCC's.
2478 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2479 if (Simp.Val) return Simp;
2484 if (N1C->getValue())
2485 return N2; // select true, X, Y -> X
2487 return N3; // select false, X, Y -> Y
2490 if (N2 == N3) return N2; // select C, X, X -> X
2494 if (N2C->getValue()) // Unconditional branch
2495 return getNode(ISD::BR, MVT::Other, N1, N3);
2497 return N1; // Never-taken branch
2500 case ISD::VECTOR_SHUFFLE:
2501 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2502 VT.isVector() && N3.getValueType().isVector() &&
2503 N3.getOpcode() == ISD::BUILD_VECTOR &&
2504 VT.getVectorNumElements() == N3.getNumOperands() &&
2505 "Illegal VECTOR_SHUFFLE node!");
2507 case ISD::BIT_CONVERT:
2508 // Fold bit_convert nodes from a type to themselves.
2509 if (N1.getValueType() == VT)
2514 // Memoize node if it doesn't produce a flag.
2516 SDVTList VTs = getVTList(VT);
2517 if (VT != MVT::Flag) {
2518 SDOperand Ops[] = { N1, N2, N3 };
2519 FoldingSetNodeID ID;
2520 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2522 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2523 return SDOperand(E, 0);
2524 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2525 CSEMap.InsertNode(N, IP);
2527 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2529 AllNodes.push_back(N);
2530 return SDOperand(N, 0);
2533 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2534 SDOperand N1, SDOperand N2, SDOperand N3,
2536 SDOperand Ops[] = { N1, N2, N3, N4 };
2537 return getNode(Opcode, VT, Ops, 4);
2540 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2541 SDOperand N1, SDOperand N2, SDOperand N3,
2542 SDOperand N4, SDOperand N5) {
2543 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2544 return getNode(Opcode, VT, Ops, 5);
2547 /// getMemsetValue - Vectorized representation of the memset value
2549 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2550 unsigned NumBits = VT.isVector() ?
2551 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2552 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2553 APInt Val = APInt(NumBits, C->getValue() & 255);
2555 for (unsigned i = NumBits; i > 8; i >>= 1) {
2556 Val = (Val << Shift) | Val;
2560 return DAG.getConstant(Val, VT);
2561 return DAG.getConstantFP(APFloat(Val), VT);
2564 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2566 for (unsigned i = NumBits; i > 8; i >>= 1) {
2567 Value = DAG.getNode(ISD::OR, VT,
2568 DAG.getNode(ISD::SHL, VT, Value,
2569 DAG.getConstant(Shift, MVT::i8)), Value);
2576 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2577 /// used when a memcpy is turned into a memset when the source is a constant
2579 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2580 const TargetLowering &TLI,
2581 std::string &Str, unsigned Offset) {
2582 // Handle vector with all elements zero.
2585 return DAG.getConstant(0, VT);
2586 unsigned NumElts = VT.getVectorNumElements();
2587 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2588 return DAG.getNode(ISD::BIT_CONVERT, VT,
2589 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2592 assert(!VT.isVector() && "Can't handle vector type here!");
2593 unsigned NumBits = VT.getSizeInBits();
2594 unsigned MSB = NumBits / 8;
2596 if (TLI.isLittleEndian())
2597 Offset = Offset + MSB - 1;
2598 for (unsigned i = 0; i != MSB; ++i) {
2599 Val = (Val << 8) | (unsigned char)Str[Offset];
2600 Offset += TLI.isLittleEndian() ? -1 : 1;
2602 return DAG.getConstant(Val, VT);
2605 /// getMemBasePlusOffset - Returns base and offset node for the
2607 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2608 SelectionDAG &DAG) {
2609 MVT VT = Base.getValueType();
2610 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2613 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2615 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2616 unsigned SrcDelta = 0;
2617 GlobalAddressSDNode *G = NULL;
2618 if (Src.getOpcode() == ISD::GlobalAddress)
2619 G = cast<GlobalAddressSDNode>(Src);
2620 else if (Src.getOpcode() == ISD::ADD &&
2621 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2622 Src.getOperand(1).getOpcode() == ISD::Constant) {
2623 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2624 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2629 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2630 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2636 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2637 /// to replace the memset / memcpy is below the threshold. It also returns the
2638 /// types of the sequence of memory ops to perform memset / memcpy.
2640 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2641 SDOperand Dst, SDOperand Src,
2642 unsigned Limit, uint64_t Size, unsigned &Align,
2643 std::string &Str, bool &isSrcStr,
2645 const TargetLowering &TLI) {
2646 isSrcStr = isMemSrcFromString(Src, Str);
2647 bool isSrcConst = isa<ConstantSDNode>(Src);
2648 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2649 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2650 if (VT != MVT::iAny) {
2651 unsigned NewAlign = (unsigned)
2652 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2653 // If source is a string constant, this will require an unaligned load.
2654 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2655 if (Dst.getOpcode() != ISD::FrameIndex) {
2656 // Can't change destination alignment. It requires a unaligned store.
2660 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2661 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2662 if (MFI->isFixedObjectIndex(FI)) {
2663 // Can't change destination alignment. It requires a unaligned store.
2667 // Give the stack frame object a larger alignment if needed.
2668 if (MFI->getObjectAlignment(FI) < NewAlign)
2669 MFI->setObjectAlignment(FI, NewAlign);
2676 if (VT == MVT::iAny) {
2680 switch (Align & 7) {
2681 case 0: VT = MVT::i64; break;
2682 case 4: VT = MVT::i32; break;
2683 case 2: VT = MVT::i16; break;
2684 default: VT = MVT::i8; break;
2689 while (!TLI.isTypeLegal(LVT))
2690 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2691 assert(LVT.isInteger());
2697 unsigned NumMemOps = 0;
2699 unsigned VTSize = VT.getSizeInBits() / 8;
2700 while (VTSize > Size) {
2701 // For now, only use non-vector load / store's for the left-over pieces.
2702 if (VT.isVector()) {
2704 while (!TLI.isTypeLegal(VT))
2705 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2706 VTSize = VT.getSizeInBits() / 8;
2708 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2713 if (++NumMemOps > Limit)
2715 MemOps.push_back(VT);
2722 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2723 SDOperand Chain, SDOperand Dst,
2724 SDOperand Src, uint64_t Size,
2725 unsigned Align, bool AlwaysInline,
2726 const Value *DstSV, uint64_t DstSVOff,
2727 const Value *SrcSV, uint64_t SrcSVOff){
2728 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2730 // Expand memcpy to a series of load and store ops if the size operand falls
2731 // below a certain threshold.
2732 std::vector<MVT> MemOps;
2733 uint64_t Limit = -1;
2735 Limit = TLI.getMaxStoresPerMemcpy();
2736 unsigned DstAlign = Align; // Destination alignment can change.
2739 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2740 Str, CopyFromStr, DAG, TLI))
2744 bool isZeroStr = CopyFromStr && Str.empty();
2745 SmallVector<SDOperand, 8> OutChains;
2746 unsigned NumMemOps = MemOps.size();
2747 uint64_t SrcOff = 0, DstOff = 0;
2748 for (unsigned i = 0; i < NumMemOps; i++) {
2750 unsigned VTSize = VT.getSizeInBits() / 8;
2751 SDOperand Value, Store;
2753 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2754 // It's unlikely a store of a vector immediate can be done in a single
2755 // instruction. It would require a load from a constantpool first.
2756 // We also handle store a vector with all zero's.
2757 // FIXME: Handle other cases where store of vector immediate is done in
2758 // a single instruction.
2759 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2760 Store = DAG.getStore(Chain, Value,
2761 getMemBasePlusOffset(Dst, DstOff, DAG),
2762 DstSV, DstSVOff + DstOff);
2764 Value = DAG.getLoad(VT, Chain,
2765 getMemBasePlusOffset(Src, SrcOff, DAG),
2766 SrcSV, SrcSVOff + SrcOff, false, Align);
2767 Store = DAG.getStore(Chain, Value,
2768 getMemBasePlusOffset(Dst, DstOff, DAG),
2769 DstSV, DstSVOff + DstOff, false, DstAlign);
2771 OutChains.push_back(Store);
2776 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2777 &OutChains[0], OutChains.size());
2780 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2781 SDOperand Chain, SDOperand Dst,
2782 SDOperand Src, uint64_t Size,
2783 unsigned Align, bool AlwaysInline,
2784 const Value *DstSV, uint64_t DstSVOff,
2785 const Value *SrcSV, uint64_t SrcSVOff){
2786 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2788 // Expand memmove to a series of load and store ops if the size operand falls
2789 // below a certain threshold.
2790 std::vector<MVT> MemOps;
2791 uint64_t Limit = -1;
2793 Limit = TLI.getMaxStoresPerMemmove();
2794 unsigned DstAlign = Align; // Destination alignment can change.
2797 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2798 Str, CopyFromStr, DAG, TLI))
2801 uint64_t SrcOff = 0, DstOff = 0;
2803 SmallVector<SDOperand, 8> LoadValues;
2804 SmallVector<SDOperand, 8> LoadChains;
2805 SmallVector<SDOperand, 8> OutChains;
2806 unsigned NumMemOps = MemOps.size();
2807 for (unsigned i = 0; i < NumMemOps; i++) {
2809 unsigned VTSize = VT.getSizeInBits() / 8;
2810 SDOperand Value, Store;
2812 Value = DAG.getLoad(VT, Chain,
2813 getMemBasePlusOffset(Src, SrcOff, DAG),
2814 SrcSV, SrcSVOff + SrcOff, false, Align);
2815 LoadValues.push_back(Value);
2816 LoadChains.push_back(Value.getValue(1));
2819 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2820 &LoadChains[0], LoadChains.size());
2822 for (unsigned i = 0; i < NumMemOps; i++) {
2824 unsigned VTSize = VT.getSizeInBits() / 8;
2825 SDOperand Value, Store;
2827 Store = DAG.getStore(Chain, LoadValues[i],
2828 getMemBasePlusOffset(Dst, DstOff, DAG),
2829 DstSV, DstSVOff + DstOff, false, DstAlign);
2830 OutChains.push_back(Store);
2834 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2835 &OutChains[0], OutChains.size());
2838 static SDOperand getMemsetStores(SelectionDAG &DAG,
2839 SDOperand Chain, SDOperand Dst,
2840 SDOperand Src, uint64_t Size,
2842 const Value *DstSV, uint64_t DstSVOff) {
2843 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2845 // Expand memset to a series of load/store ops if the size operand
2846 // falls below a certain threshold.
2847 std::vector<MVT> MemOps;
2850 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2851 Size, Align, Str, CopyFromStr, DAG, TLI))
2854 SmallVector<SDOperand, 8> OutChains;
2855 uint64_t DstOff = 0;
2857 unsigned NumMemOps = MemOps.size();
2858 for (unsigned i = 0; i < NumMemOps; i++) {
2860 unsigned VTSize = VT.getSizeInBits() / 8;
2861 SDOperand Value = getMemsetValue(Src, VT, DAG);
2862 SDOperand Store = DAG.getStore(Chain, Value,
2863 getMemBasePlusOffset(Dst, DstOff, DAG),
2864 DstSV, DstSVOff + DstOff);
2865 OutChains.push_back(Store);
2869 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2870 &OutChains[0], OutChains.size());
2873 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2874 SDOperand Src, SDOperand Size,
2875 unsigned Align, bool AlwaysInline,
2876 const Value *DstSV, uint64_t DstSVOff,
2877 const Value *SrcSV, uint64_t SrcSVOff) {
2879 // Check to see if we should lower the memcpy to loads and stores first.
2880 // For cases within the target-specified limits, this is the best choice.
2881 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2883 // Memcpy with size zero? Just return the original chain.
2884 if (ConstantSize->isNullValue())
2888 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2889 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2894 // Then check to see if we should lower the memcpy with target-specific
2895 // code. If the target chooses to do this, this is the next best.
2897 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2899 DstSV, DstSVOff, SrcSV, SrcSVOff);
2903 // If we really need inline code and the target declined to provide it,
2904 // use a (potentially long) sequence of loads and stores.
2906 assert(ConstantSize && "AlwaysInline requires a constant size!");
2907 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2908 ConstantSize->getValue(), Align, true,
2909 DstSV, DstSVOff, SrcSV, SrcSVOff);
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("memcpy", TLI.getPointerTy()),
2924 return CallResult.second;
2927 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2928 SDOperand Src, SDOperand Size,
2930 const Value *DstSV, uint64_t DstSVOff,
2931 const Value *SrcSV, uint64_t SrcSVOff) {
2933 // Check to see if we should lower the memmove to loads and stores first.
2934 // For cases within the target-specified limits, this is the best choice.
2935 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2937 // Memmove with size zero? Just return the original chain.
2938 if (ConstantSize->isNullValue())
2942 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2943 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2948 // Then check to see if we should lower the memmove with target-specific
2949 // code. If the target chooses to do this, this is the next best.
2951 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2952 DstSV, DstSVOff, SrcSV, SrcSVOff);
2956 // Emit a library call.
2957 TargetLowering::ArgListTy Args;
2958 TargetLowering::ArgListEntry Entry;
2959 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2960 Entry.Node = Dst; Args.push_back(Entry);
2961 Entry.Node = Src; Args.push_back(Entry);
2962 Entry.Node = Size; Args.push_back(Entry);
2963 std::pair<SDOperand,SDOperand> CallResult =
2964 TLI.LowerCallTo(Chain, Type::VoidTy,
2965 false, false, false, CallingConv::C, false,
2966 getExternalSymbol("memmove", TLI.getPointerTy()),
2968 return CallResult.second;
2971 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2972 SDOperand Src, SDOperand Size,
2974 const Value *DstSV, uint64_t DstSVOff) {
2976 // Check to see if we should lower the memset to stores first.
2977 // For cases within the target-specified limits, this is the best choice.
2978 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2980 // Memset with size zero? Just return the original chain.
2981 if (ConstantSize->isNullValue())
2985 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
2991 // Then check to see if we should lower the memset with target-specific
2992 // code. If the target chooses to do this, this is the next best.
2994 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
2999 // Emit a library call.
3000 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3001 TargetLowering::ArgListTy Args;
3002 TargetLowering::ArgListEntry Entry;
3003 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3004 Args.push_back(Entry);
3005 // Extend or truncate the argument to be an i32 value for the call.
3006 if (Src.getValueType().bitsGT(MVT::i32))
3007 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3009 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3010 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3011 Args.push_back(Entry);
3012 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3013 Args.push_back(Entry);
3014 std::pair<SDOperand,SDOperand> CallResult =
3015 TLI.LowerCallTo(Chain, Type::VoidTy,
3016 false, false, false, CallingConv::C, false,
3017 getExternalSymbol("memset", TLI.getPointerTy()),
3019 return CallResult.second;
3022 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3023 SDOperand Ptr, SDOperand Cmp,
3024 SDOperand Swp, const Value* PtrVal,
3025 unsigned Alignment) {
3026 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3027 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3028 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
3029 FoldingSetNodeID ID;
3030 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3031 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3033 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3034 return SDOperand(E, 0);
3035 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp,
3037 CSEMap.InsertNode(N, IP);
3038 AllNodes.push_back(N);
3039 return SDOperand(N, 0);
3042 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3043 SDOperand Ptr, SDOperand Val,
3044 const Value* PtrVal,
3045 unsigned Alignment) {
3046 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3047 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3048 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3049 || Opcode == ISD::ATOMIC_LOAD_NAND
3050 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3051 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3052 && "Invalid Atomic Op");
3053 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3054 FoldingSetNodeID ID;
3055 SDOperand Ops[] = {Chain, Ptr, Val};
3056 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3058 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3059 return SDOperand(E, 0);
3060 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val,
3062 CSEMap.InsertNode(N, IP);
3063 AllNodes.push_back(N);
3064 return SDOperand(N, 0);
3068 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3069 MVT VT, SDOperand Chain,
3070 SDOperand Ptr, SDOperand Offset,
3071 const Value *SV, int SVOffset, MVT EVT,
3072 bool isVolatile, unsigned Alignment) {
3073 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3075 if (VT != MVT::iPTR) {
3076 Ty = VT.getTypeForMVT();
3078 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3079 assert(PT && "Value for load must be a pointer");
3080 Ty = PT->getElementType();
3082 assert(Ty && "Could not get type information for load");
3083 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3087 ExtType = ISD::NON_EXTLOAD;
3088 } else if (ExtType == ISD::NON_EXTLOAD) {
3089 assert(VT == EVT && "Non-extending load from different memory type!");
3093 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3095 assert(EVT.bitsLT(VT) &&
3096 "Should only be an extending load, not truncating!");
3097 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3098 "Cannot sign/zero extend a FP/Vector load!");
3099 assert(VT.isInteger() == EVT.isInteger() &&
3100 "Cannot convert from FP to Int or Int -> FP!");
3103 bool Indexed = AM != ISD::UNINDEXED;
3104 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3105 "Unindexed load with an offset!");
3107 SDVTList VTs = Indexed ?
3108 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3109 SDOperand Ops[] = { Chain, Ptr, Offset };
3110 FoldingSetNodeID ID;
3111 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3113 ID.AddInteger(ExtType);
3114 ID.AddInteger(EVT.getRawBits());
3115 ID.AddInteger(Alignment);
3116 ID.AddInteger(isVolatile);
3118 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3119 return SDOperand(E, 0);
3120 SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3121 Alignment, isVolatile);
3122 CSEMap.InsertNode(N, IP);
3123 AllNodes.push_back(N);
3124 return SDOperand(N, 0);
3127 SDOperand SelectionDAG::getLoad(MVT VT,
3128 SDOperand Chain, SDOperand Ptr,
3129 const Value *SV, int SVOffset,
3130 bool isVolatile, unsigned Alignment) {
3131 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3132 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3133 SV, SVOffset, VT, isVolatile, Alignment);
3136 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3137 SDOperand Chain, SDOperand Ptr,
3139 int SVOffset, MVT EVT,
3140 bool isVolatile, unsigned Alignment) {
3141 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3142 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3143 SV, SVOffset, EVT, isVolatile, Alignment);
3147 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3148 SDOperand Offset, ISD::MemIndexedMode AM) {
3149 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3150 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3151 "Load is already a indexed load!");
3152 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3153 LD->getChain(), Base, Offset, LD->getSrcValue(),
3154 LD->getSrcValueOffset(), LD->getMemoryVT(),
3155 LD->isVolatile(), LD->getAlignment());
3158 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3159 SDOperand Ptr, const Value *SV, int SVOffset,
3160 bool isVolatile, unsigned Alignment) {
3161 MVT VT = Val.getValueType();
3163 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3165 if (VT != MVT::iPTR) {
3166 Ty = VT.getTypeForMVT();
3168 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3169 assert(PT && "Value for store must be a pointer");
3170 Ty = PT->getElementType();
3172 assert(Ty && "Could not get type information for store");
3173 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3175 SDVTList VTs = getVTList(MVT::Other);
3176 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3177 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3178 FoldingSetNodeID ID;
3179 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3180 ID.AddInteger(ISD::UNINDEXED);
3181 ID.AddInteger(false);
3182 ID.AddInteger(VT.getRawBits());
3183 ID.AddInteger(Alignment);
3184 ID.AddInteger(isVolatile);
3186 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3187 return SDOperand(E, 0);
3188 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3189 VT, SV, SVOffset, Alignment, isVolatile);
3190 CSEMap.InsertNode(N, IP);
3191 AllNodes.push_back(N);
3192 return SDOperand(N, 0);
3195 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3196 SDOperand Ptr, const Value *SV,
3197 int SVOffset, MVT SVT,
3198 bool isVolatile, unsigned Alignment) {
3199 MVT VT = Val.getValueType();
3202 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3204 assert(VT.bitsGT(SVT) && "Not a truncation?");
3205 assert(VT.isInteger() == SVT.isInteger() &&
3206 "Can't do FP-INT conversion!");
3208 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3210 if (VT != MVT::iPTR) {
3211 Ty = VT.getTypeForMVT();
3213 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3214 assert(PT && "Value for store must be a pointer");
3215 Ty = PT->getElementType();
3217 assert(Ty && "Could not get type information for store");
3218 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3220 SDVTList VTs = getVTList(MVT::Other);
3221 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3222 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3223 FoldingSetNodeID ID;
3224 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3225 ID.AddInteger(ISD::UNINDEXED);
3227 ID.AddInteger(SVT.getRawBits());
3228 ID.AddInteger(Alignment);
3229 ID.AddInteger(isVolatile);
3231 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3232 return SDOperand(E, 0);
3233 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3234 SVT, SV, SVOffset, Alignment, isVolatile);
3235 CSEMap.InsertNode(N, IP);
3236 AllNodes.push_back(N);
3237 return SDOperand(N, 0);
3241 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3242 SDOperand Offset, ISD::MemIndexedMode AM) {
3243 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3244 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3245 "Store is already a indexed store!");
3246 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3247 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3248 FoldingSetNodeID ID;
3249 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3251 ID.AddInteger(ST->isTruncatingStore());
3252 ID.AddInteger(ST->getMemoryVT().getRawBits());
3253 ID.AddInteger(ST->getAlignment());
3254 ID.AddInteger(ST->isVolatile());
3256 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3257 return SDOperand(E, 0);
3258 SDNode *N = new StoreSDNode(Ops, VTs, AM,
3259 ST->isTruncatingStore(), ST->getMemoryVT(),
3260 ST->getSrcValue(), ST->getSrcValueOffset(),
3261 ST->getAlignment(), ST->isVolatile());
3262 CSEMap.InsertNode(N, IP);
3263 AllNodes.push_back(N);
3264 return SDOperand(N, 0);
3267 SDOperand SelectionDAG::getVAArg(MVT VT,
3268 SDOperand Chain, SDOperand Ptr,
3270 SDOperand Ops[] = { Chain, Ptr, SV };
3271 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3274 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3275 SDOperandPtr Ops, unsigned NumOps) {
3277 case 0: return getNode(Opcode, VT);
3278 case 1: return getNode(Opcode, VT, Ops[0]);
3279 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3280 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3286 case ISD::SELECT_CC: {
3287 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3288 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3289 "LHS and RHS of condition must have same type!");
3290 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3291 "True and False arms of SelectCC must have same type!");
3292 assert(Ops[2].getValueType() == VT &&
3293 "select_cc node must be of same type as true and false value!");
3297 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3298 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3299 "LHS/RHS of comparison should match types!");
3306 SDVTList VTs = getVTList(VT);
3307 if (VT != MVT::Flag) {
3308 FoldingSetNodeID ID;
3309 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3311 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3312 return SDOperand(E, 0);
3313 N = new SDNode(Opcode, VTs, Ops, NumOps);
3314 CSEMap.InsertNode(N, IP);
3316 N = new SDNode(Opcode, VTs, Ops, NumOps);
3318 AllNodes.push_back(N);
3319 return SDOperand(N, 0);
3322 SDOperand SelectionDAG::getNode(unsigned Opcode,
3323 std::vector<MVT> &ResultTys,
3324 SDOperandPtr Ops, unsigned NumOps) {
3325 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3329 SDOperand SelectionDAG::getNode(unsigned Opcode,
3330 const MVT *VTs, unsigned NumVTs,
3331 SDOperandPtr Ops, unsigned NumOps) {
3333 return getNode(Opcode, VTs[0], Ops, NumOps);
3334 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3337 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3338 SDOperandPtr Ops, unsigned NumOps) {
3339 if (VTList.NumVTs == 1)
3340 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3343 // FIXME: figure out how to safely handle things like
3344 // int foo(int x) { return 1 << (x & 255); }
3345 // int bar() { return foo(256); }
3347 case ISD::SRA_PARTS:
3348 case ISD::SRL_PARTS:
3349 case ISD::SHL_PARTS:
3350 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3351 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3352 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3353 else if (N3.getOpcode() == ISD::AND)
3354 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3355 // If the and is only masking out bits that cannot effect the shift,
3356 // eliminate the and.
3357 unsigned NumBits = VT.getSizeInBits()*2;
3358 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3359 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3365 // Memoize the node unless it returns a flag.
3367 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3368 FoldingSetNodeID ID;
3369 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3371 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3372 return SDOperand(E, 0);
3374 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3375 else if (NumOps == 2)
3376 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3377 else if (NumOps == 3)
3378 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3380 N = new SDNode(Opcode, VTList, Ops, NumOps);
3381 CSEMap.InsertNode(N, IP);
3384 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3385 else if (NumOps == 2)
3386 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3387 else if (NumOps == 3)
3388 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3390 N = new SDNode(Opcode, VTList, Ops, NumOps);
3392 AllNodes.push_back(N);
3393 return SDOperand(N, 0);
3396 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3397 return getNode(Opcode, VTList, (SDOperand*)0, 0);
3400 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3402 SDOperand Ops[] = { N1 };
3403 return getNode(Opcode, VTList, Ops, 1);
3406 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3407 SDOperand N1, SDOperand N2) {
3408 SDOperand Ops[] = { N1, N2 };
3409 return getNode(Opcode, VTList, Ops, 2);
3412 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3413 SDOperand N1, SDOperand N2, SDOperand N3) {
3414 SDOperand Ops[] = { N1, N2, N3 };
3415 return getNode(Opcode, VTList, Ops, 3);
3418 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3419 SDOperand N1, SDOperand N2, SDOperand N3,
3421 SDOperand Ops[] = { N1, N2, N3, N4 };
3422 return getNode(Opcode, VTList, Ops, 4);
3425 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3426 SDOperand N1, SDOperand N2, SDOperand N3,
3427 SDOperand N4, SDOperand N5) {
3428 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3429 return getNode(Opcode, VTList, Ops, 5);
3432 SDVTList SelectionDAG::getVTList(MVT VT) {
3433 return makeVTList(SDNode::getValueTypeList(VT), 1);
3436 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3437 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3438 E = VTList.end(); I != E; ++I) {
3439 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3440 return makeVTList(&(*I)[0], 2);
3445 VTList.push_front(V);
3446 return makeVTList(&(*VTList.begin())[0], 2);
3448 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3450 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3451 E = VTList.end(); I != E; ++I) {
3452 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3454 return makeVTList(&(*I)[0], 3);
3460 VTList.push_front(V);
3461 return makeVTList(&(*VTList.begin())[0], 3);
3464 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3466 case 0: assert(0 && "Cannot have nodes without results!");
3467 case 1: return getVTList(VTs[0]);
3468 case 2: return getVTList(VTs[0], VTs[1]);
3469 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3473 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3474 E = VTList.end(); I != E; ++I) {
3475 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3477 bool NoMatch = false;
3478 for (unsigned i = 2; i != NumVTs; ++i)
3479 if (VTs[i] != (*I)[i]) {
3484 return makeVTList(&*I->begin(), NumVTs);
3487 VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3488 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3492 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3493 /// specified operands. If the resultant node already exists in the DAG,
3494 /// this does not modify the specified node, instead it returns the node that
3495 /// already exists. If the resultant node does not exist in the DAG, the
3496 /// input node is returned. As a degenerate case, if you specify the same
3497 /// input operands as the node already has, the input node is returned.
3498 SDOperand SelectionDAG::
3499 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3500 SDNode *N = InN.Val;
3501 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3503 // Check to see if there is no change.
3504 if (Op == N->getOperand(0)) return InN;
3506 // See if the modified node already exists.
3507 void *InsertPos = 0;
3508 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3509 return SDOperand(Existing, InN.ResNo);
3511 // Nope it doesn't. Remove the node from it's current place in the maps.
3513 RemoveNodeFromCSEMaps(N);
3515 // Now we update the operands.
3516 N->OperandList[0].getVal()->removeUser(0, N);
3517 N->OperandList[0] = Op;
3518 N->OperandList[0].setUser(N);
3519 Op.Val->addUser(0, N);
3521 // If this gets put into a CSE map, add it.
3522 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3526 SDOperand SelectionDAG::
3527 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3528 SDNode *N = InN.Val;
3529 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3531 // Check to see if there is no change.
3532 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3533 return InN; // No operands changed, just return the input node.
3535 // See if the modified node already exists.
3536 void *InsertPos = 0;
3537 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3538 return SDOperand(Existing, InN.ResNo);
3540 // Nope it doesn't. Remove the node from it's current place in the maps.
3542 RemoveNodeFromCSEMaps(N);
3544 // Now we update the operands.
3545 if (N->OperandList[0] != Op1) {
3546 N->OperandList[0].getVal()->removeUser(0, N);
3547 N->OperandList[0] = Op1;
3548 N->OperandList[0].setUser(N);
3549 Op1.Val->addUser(0, N);
3551 if (N->OperandList[1] != Op2) {
3552 N->OperandList[1].getVal()->removeUser(1, N);
3553 N->OperandList[1] = Op2;
3554 N->OperandList[1].setUser(N);
3555 Op2.Val->addUser(1, N);
3558 // If this gets put into a CSE map, add it.
3559 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3563 SDOperand SelectionDAG::
3564 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3565 SDOperand Ops[] = { Op1, Op2, Op3 };
3566 return UpdateNodeOperands(N, Ops, 3);
3569 SDOperand SelectionDAG::
3570 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3571 SDOperand Op3, SDOperand Op4) {
3572 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3573 return UpdateNodeOperands(N, Ops, 4);
3576 SDOperand SelectionDAG::
3577 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3578 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3579 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3580 return UpdateNodeOperands(N, Ops, 5);
3583 SDOperand SelectionDAG::
3584 UpdateNodeOperands(SDOperand InN, SDOperandPtr Ops, unsigned NumOps) {
3585 SDNode *N = InN.Val;
3586 assert(N->getNumOperands() == NumOps &&
3587 "Update with wrong number of operands");
3589 // Check to see if there is no change.
3590 bool AnyChange = false;
3591 for (unsigned i = 0; i != NumOps; ++i) {
3592 if (Ops[i] != N->getOperand(i)) {
3598 // No operands changed, just return the input node.
3599 if (!AnyChange) return InN;
3601 // See if the modified node already exists.
3602 void *InsertPos = 0;
3603 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3604 return SDOperand(Existing, InN.ResNo);
3606 // Nope it doesn't. Remove the node from its current place in the maps.
3608 RemoveNodeFromCSEMaps(N);
3610 // Now we update the operands.
3611 for (unsigned i = 0; i != NumOps; ++i) {
3612 if (N->OperandList[i] != Ops[i]) {
3613 N->OperandList[i].getVal()->removeUser(i, N);
3614 N->OperandList[i] = Ops[i];
3615 N->OperandList[i].setUser(N);
3616 Ops[i].Val->addUser(i, N);
3620 // If this gets put into a CSE map, add it.
3621 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3625 /// MorphNodeTo - This frees the operands of the current node, resets the
3626 /// opcode, types, and operands to the specified value. This should only be
3627 /// used by the SelectionDAG class.
3628 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3629 SDOperandPtr Ops, unsigned NumOps) {
3632 NumValues = L.NumVTs;
3634 // Clear the operands list, updating used nodes to remove this from their
3636 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3637 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3639 // If NumOps is larger than the # of operands we currently have, reallocate
3640 // the operand list.
3641 if (NumOps > NumOperands) {
3642 if (OperandsNeedDelete) {
3643 delete [] OperandList;
3645 OperandList = new SDUse[NumOps];
3646 OperandsNeedDelete = true;
3649 // Assign the new operands.
3650 NumOperands = NumOps;
3652 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3653 OperandList[i] = Ops[i];
3654 OperandList[i].setUser(this);
3655 SDNode *N = OperandList[i].getVal();
3656 N->addUser(i, this);
3661 /// SelectNodeTo - These are used for target selectors to *mutate* the
3662 /// specified node to have the specified return type, Target opcode, and
3663 /// operands. Note that target opcodes are stored as
3664 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3666 /// Note that SelectNodeTo returns the resultant node. If there is already a
3667 /// node of the specified opcode and operands, it returns that node instead of
3668 /// the current one.
3669 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3671 SDVTList VTs = getVTList(VT);
3672 FoldingSetNodeID ID;
3673 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, (SDOperand*)0, 0);
3675 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3678 RemoveNodeFromCSEMaps(N);
3680 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, SDOperandPtr(), 0);
3682 CSEMap.InsertNode(N, IP);
3686 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3687 MVT VT, SDOperand Op1) {
3688 // If an identical node already exists, use it.
3689 SDVTList VTs = getVTList(VT);
3690 SDOperand Ops[] = { Op1 };
3692 FoldingSetNodeID ID;
3693 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3695 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3698 RemoveNodeFromCSEMaps(N);
3699 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3700 CSEMap.InsertNode(N, IP);
3704 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3705 MVT VT, SDOperand Op1,
3707 // If an identical node already exists, use it.
3708 SDVTList VTs = getVTList(VT);
3709 SDOperand Ops[] = { Op1, Op2 };
3711 FoldingSetNodeID ID;
3712 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3714 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3717 RemoveNodeFromCSEMaps(N);
3719 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3721 CSEMap.InsertNode(N, IP); // Memoize the new node.
3725 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3726 MVT VT, SDOperand Op1,
3727 SDOperand Op2, SDOperand Op3) {
3728 // If an identical node already exists, use it.
3729 SDVTList VTs = getVTList(VT);
3730 SDOperand Ops[] = { Op1, Op2, Op3 };
3731 FoldingSetNodeID ID;
3732 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3734 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3737 RemoveNodeFromCSEMaps(N);
3739 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3741 CSEMap.InsertNode(N, IP); // Memoize the new node.
3745 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3746 MVT VT, SDOperandPtr Ops,
3748 // If an identical node already exists, use it.
3749 SDVTList VTs = getVTList(VT);
3750 FoldingSetNodeID ID;
3751 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3753 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3756 RemoveNodeFromCSEMaps(N);
3757 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3759 CSEMap.InsertNode(N, IP); // Memoize the new node.
3763 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3765 SDOperand Op1, SDOperand Op2) {
3766 SDVTList VTs = getVTList(VT1, VT2);
3767 FoldingSetNodeID ID;
3768 SDOperand Ops[] = { Op1, Op2 };
3769 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3771 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3774 RemoveNodeFromCSEMaps(N);
3775 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3776 CSEMap.InsertNode(N, IP); // Memoize the new node.
3780 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3782 SDOperand Op1, SDOperand Op2,
3784 // If an identical node already exists, use it.
3785 SDVTList VTs = getVTList(VT1, VT2);
3786 SDOperand Ops[] = { Op1, Op2, Op3 };
3787 FoldingSetNodeID ID;
3788 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3790 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3793 RemoveNodeFromCSEMaps(N);
3795 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3796 CSEMap.InsertNode(N, IP); // Memoize the new node.
3801 /// getTargetNode - These are used for target selectors to create a new node
3802 /// with specified return type(s), target opcode, and operands.
3804 /// Note that getTargetNode returns the resultant node. If there is already a
3805 /// node of the specified opcode and operands, it returns that node instead of
3806 /// the current one.
3807 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3808 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3810 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3811 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3813 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3814 SDOperand Op1, SDOperand Op2) {
3815 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3817 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3818 SDOperand Op1, SDOperand Op2,
3820 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3822 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3823 SDOperandPtr Ops, unsigned NumOps) {
3824 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3826 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3827 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3829 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3831 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3832 MVT VT2, SDOperand Op1) {
3833 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3834 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3836 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3837 MVT VT2, SDOperand Op1,
3839 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3840 SDOperand Ops[] = { Op1, Op2 };
3841 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3843 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3844 MVT VT2, SDOperand Op1,
3845 SDOperand Op2, SDOperand Op3) {
3846 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3847 SDOperand Ops[] = { Op1, Op2, Op3 };
3848 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3850 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3851 SDOperandPtr Ops, unsigned NumOps) {
3852 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3853 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3855 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3856 SDOperand Op1, SDOperand Op2) {
3857 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3858 SDOperand Ops[] = { Op1, Op2 };
3859 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3861 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3862 SDOperand Op1, SDOperand Op2,
3864 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3865 SDOperand Ops[] = { Op1, Op2, Op3 };
3866 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3868 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3869 SDOperandPtr Ops, unsigned NumOps) {
3870 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3871 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3873 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3874 MVT VT2, MVT VT3, MVT VT4,
3875 SDOperandPtr Ops, unsigned NumOps) {
3876 std::vector<MVT> VTList;
3877 VTList.push_back(VT1);
3878 VTList.push_back(VT2);
3879 VTList.push_back(VT3);
3880 VTList.push_back(VT4);
3881 const MVT *VTs = getNodeValueTypes(VTList);
3882 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3884 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3885 std::vector<MVT> &ResultTys,
3886 SDOperandPtr Ops, unsigned NumOps) {
3887 const MVT *VTs = getNodeValueTypes(ResultTys);
3888 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3892 /// getNodeIfExists - Get the specified node if it's already available, or
3893 /// else return NULL.
3894 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3895 SDOperandPtr Ops, unsigned NumOps) {
3896 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3897 FoldingSetNodeID ID;
3898 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3900 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3907 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3908 /// This can cause recursive merging of nodes in the DAG.
3910 /// This version assumes From has a single result value.
3912 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3913 DAGUpdateListener *UpdateListener) {
3914 SDNode *From = FromN.Val;
3915 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3916 "Cannot replace with this method!");
3917 assert(From != To.Val && "Cannot replace uses of with self");
3919 while (!From->use_empty()) {
3920 SDNode::use_iterator UI = From->use_begin();
3921 SDNode *U = UI->getUser();
3923 // This node is about to morph, remove its old self from the CSE maps.
3924 RemoveNodeFromCSEMaps(U);
3926 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3927 I != E; ++I, ++operandNum)
3928 if (I->getVal() == From) {
3929 From->removeUser(operandNum, U);
3932 To.Val->addUser(operandNum, U);
3935 // Now that we have modified U, add it back to the CSE maps. If it already
3936 // exists there, recursively merge the results together.
3937 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3938 ReplaceAllUsesWith(U, Existing, UpdateListener);
3939 // U is now dead. Inform the listener if it exists and delete it.
3941 UpdateListener->NodeDeleted(U, Existing);
3942 DeleteNodeNotInCSEMaps(U);
3944 // If the node doesn't already exist, we updated it. Inform a listener if
3947 UpdateListener->NodeUpdated(U);
3952 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3953 /// This can cause recursive merging of nodes in the DAG.
3955 /// This version assumes From/To have matching types and numbers of result
3958 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3959 DAGUpdateListener *UpdateListener) {
3960 assert(From != To && "Cannot replace uses of with self");
3961 assert(From->getNumValues() == To->getNumValues() &&
3962 "Cannot use this version of ReplaceAllUsesWith!");
3963 if (From->getNumValues() == 1) // If possible, use the faster version.
3964 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3967 while (!From->use_empty()) {
3968 SDNode::use_iterator UI = From->use_begin();
3969 SDNode *U = UI->getUser();
3971 // This node is about to morph, remove its old self from the CSE maps.
3972 RemoveNodeFromCSEMaps(U);
3974 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3975 I != E; ++I, ++operandNum)
3976 if (I->getVal() == From) {
3977 From->removeUser(operandNum, U);
3979 To->addUser(operandNum, U);
3982 // Now that we have modified U, add it back to the CSE maps. If it already
3983 // exists there, recursively merge the results together.
3984 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3985 ReplaceAllUsesWith(U, Existing, UpdateListener);
3986 // U is now dead. Inform the listener if it exists and delete it.
3988 UpdateListener->NodeDeleted(U, Existing);
3989 DeleteNodeNotInCSEMaps(U);
3991 // If the node doesn't already exist, we updated it. Inform a listener if
3994 UpdateListener->NodeUpdated(U);
3999 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4000 /// This can cause recursive merging of nodes in the DAG.
4002 /// This version can replace From with any result values. To must match the
4003 /// number and types of values returned by From.
4004 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4006 DAGUpdateListener *UpdateListener) {
4007 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4008 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
4010 while (!From->use_empty()) {
4011 SDNode::use_iterator UI = From->use_begin();
4012 SDNode *U = UI->getUser();
4014 // This node is about to morph, remove its old self from the CSE maps.
4015 RemoveNodeFromCSEMaps(U);
4017 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4018 I != E; ++I, ++operandNum)
4019 if (I->getVal() == From) {
4020 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4021 From->removeUser(operandNum, U);
4024 ToOp.Val->addUser(operandNum, U);
4027 // Now that we have modified U, add it back to the CSE maps. If it already
4028 // exists there, recursively merge the results together.
4029 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4030 ReplaceAllUsesWith(U, Existing, UpdateListener);
4031 // U is now dead. Inform the listener if it exists and delete it.
4033 UpdateListener->NodeDeleted(U, Existing);
4034 DeleteNodeNotInCSEMaps(U);
4036 // If the node doesn't already exist, we updated it. Inform a listener if
4039 UpdateListener->NodeUpdated(U);
4045 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4046 /// any deleted nodes from the set passed into its constructor and recursively
4047 /// notifies another update listener if specified.
4048 class ChainedSetUpdaterListener :
4049 public SelectionDAG::DAGUpdateListener {
4050 SmallSetVector<SDNode*, 16> &Set;
4051 SelectionDAG::DAGUpdateListener *Chain;
4053 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4054 SelectionDAG::DAGUpdateListener *chain)
4055 : Set(set), Chain(chain) {}
4057 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4059 if (Chain) Chain->NodeDeleted(N, E);
4061 virtual void NodeUpdated(SDNode *N) {
4062 if (Chain) Chain->NodeUpdated(N);
4067 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4068 /// uses of other values produced by From.Val alone. The Deleted vector is
4069 /// handled the same way as for ReplaceAllUsesWith.
4070 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4071 DAGUpdateListener *UpdateListener){
4072 assert(From != To && "Cannot replace a value with itself");
4074 // Handle the simple, trivial, case efficiently.
4075 if (From.Val->getNumValues() == 1) {
4076 ReplaceAllUsesWith(From, To, UpdateListener);
4080 if (From.use_empty()) return;
4082 // Get all of the users of From.Val. We want these in a nice,
4083 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4084 SmallSetVector<SDNode*, 16> Users;
4085 for (SDNode::use_iterator UI = From.Val->use_begin(),
4086 E = From.Val->use_end(); UI != E; ++UI) {
4087 SDNode *User = UI->getUser();
4088 if (!Users.count(User))
4092 // When one of the recursive merges deletes nodes from the graph, we need to
4093 // make sure that UpdateListener is notified *and* that the node is removed
4094 // from Users if present. CSUL does this.
4095 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4097 while (!Users.empty()) {
4098 // We know that this user uses some value of From. If it is the right
4099 // value, update it.
4100 SDNode *User = Users.back();
4103 // Scan for an operand that matches From.
4104 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4105 for (; Op != E; ++Op)
4106 if (*Op == From) break;
4108 // If there are no matches, the user must use some other result of From.
4109 if (Op == E) continue;
4111 // Okay, we know this user needs to be updated. Remove its old self
4112 // from the CSE maps.
4113 RemoveNodeFromCSEMaps(User);
4115 // Update all operands that match "From" in case there are multiple uses.
4116 for (; Op != E; ++Op) {
4118 From.Val->removeUser(Op-User->op_begin(), User);
4121 To.Val->addUser(Op-User->op_begin(), User);
4125 // Now that we have modified User, add it back to the CSE maps. If it
4126 // already exists there, recursively merge the results together.
4127 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4129 if (UpdateListener) UpdateListener->NodeUpdated(User);
4130 continue; // Continue on to next user.
4133 // If there was already an existing matching node, use ReplaceAllUsesWith
4134 // to replace the dead one with the existing one. This can cause
4135 // recursive merging of other unrelated nodes down the line. The merging
4136 // can cause deletion of nodes that used the old value. To handle this, we
4137 // use CSUL to remove them from the Users set.
4138 ReplaceAllUsesWith(User, Existing, &CSUL);
4140 // User is now dead. Notify a listener if present.
4141 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4142 DeleteNodeNotInCSEMaps(User);
4146 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4147 /// their allnodes order. It returns the maximum id.
4148 unsigned SelectionDAG::AssignNodeIds() {
4150 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4157 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4158 /// based on their topological order. It returns the maximum id and a vector
4159 /// of the SDNodes* in assigned order by reference.
4160 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4161 unsigned DAGSize = AllNodes.size();
4162 std::vector<unsigned> InDegree(DAGSize);
4163 std::vector<SDNode*> Sources;
4165 // Use a two pass approach to avoid using a std::map which is slow.
4167 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4170 unsigned Degree = N->use_size();
4171 InDegree[N->getNodeId()] = Degree;
4173 Sources.push_back(N);
4177 while (!Sources.empty()) {
4178 SDNode *N = Sources.back();
4180 TopOrder.push_back(N);
4181 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4182 SDNode *P = I->getVal();
4183 unsigned Degree = --InDegree[P->getNodeId()];
4185 Sources.push_back(P);
4189 // Second pass, assign the actual topological order as node ids.
4191 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4193 (*TI)->setNodeId(Id++);
4200 //===----------------------------------------------------------------------===//
4202 //===----------------------------------------------------------------------===//
4204 // Out-of-line virtual method to give class a home.
4205 void SDNode::ANCHOR() {}
4206 void UnarySDNode::ANCHOR() {}
4207 void BinarySDNode::ANCHOR() {}
4208 void TernarySDNode::ANCHOR() {}
4209 void HandleSDNode::ANCHOR() {}
4210 void ConstantSDNode::ANCHOR() {}
4211 void ConstantFPSDNode::ANCHOR() {}
4212 void GlobalAddressSDNode::ANCHOR() {}
4213 void FrameIndexSDNode::ANCHOR() {}
4214 void JumpTableSDNode::ANCHOR() {}
4215 void ConstantPoolSDNode::ANCHOR() {}
4216 void BasicBlockSDNode::ANCHOR() {}
4217 void SrcValueSDNode::ANCHOR() {}
4218 void MemOperandSDNode::ANCHOR() {}
4219 void RegisterSDNode::ANCHOR() {}
4220 void DbgStopPointSDNode::ANCHOR() {}
4221 void LabelSDNode::ANCHOR() {}
4222 void ExternalSymbolSDNode::ANCHOR() {}
4223 void CondCodeSDNode::ANCHOR() {}
4224 void ARG_FLAGSSDNode::ANCHOR() {}
4225 void VTSDNode::ANCHOR() {}
4226 void MemSDNode::ANCHOR() {}
4227 void LoadSDNode::ANCHOR() {}
4228 void StoreSDNode::ANCHOR() {}
4229 void AtomicSDNode::ANCHOR() {}
4231 HandleSDNode::~HandleSDNode() {
4232 SDVTList VTs = { 0, 0 };
4233 MorphNodeTo(ISD::HANDLENODE, VTs, SDOperandPtr(), 0); // Drops operand uses.
4236 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4238 : SDNode(isa<GlobalVariable>(GA) &&
4239 cast<GlobalVariable>(GA)->isThreadLocal() ?
4241 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4243 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4244 getSDVTList(VT)), Offset(o) {
4245 TheGlobal = const_cast<GlobalValue*>(GA);
4248 /// getMemOperand - Return a MachineMemOperand object describing the memory
4249 /// reference performed by this atomic.
4250 MachineMemOperand AtomicSDNode::getMemOperand() const {
4251 int Size = (getValueType(0).getSizeInBits() + 7) >> 3;
4252 int Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4253 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4255 // Check if the atomic references a frame index
4256 const FrameIndexSDNode *FI =
4257 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4258 if (!getSrcValue() && FI)
4259 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4260 FI->getIndex(), Size, getAlignment());
4262 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4263 Size, getAlignment());
4266 /// getMemOperand - Return a MachineMemOperand object describing the memory
4267 /// reference performed by this load or store.
4268 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4269 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4271 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4272 MachineMemOperand::MOStore;
4273 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4275 // Check if the load references a frame index, and does not have
4277 const FrameIndexSDNode *FI =
4278 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4279 if (!getSrcValue() && FI)
4280 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4281 FI->getIndex(), Size, getAlignment());
4283 return MachineMemOperand(getSrcValue(), Flags,
4284 getSrcValueOffset(), Size, getAlignment());
4287 /// Profile - Gather unique data for the node.
4289 void SDNode::Profile(FoldingSetNodeID &ID) {
4290 AddNodeIDNode(ID, this);
4293 /// getValueTypeList - Return a pointer to the specified value type.
4295 const MVT *SDNode::getValueTypeList(MVT VT) {
4296 if (VT.isExtended()) {
4297 static std::set<MVT, MVT::compareRawBits> EVTs;
4298 return &(*EVTs.insert(VT).first);
4300 static MVT VTs[MVT::LAST_VALUETYPE];
4301 VTs[VT.getSimpleVT()] = VT;
4302 return &VTs[VT.getSimpleVT()];
4306 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4307 /// indicated value. This method ignores uses of other values defined by this
4309 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4310 assert(Value < getNumValues() && "Bad value!");
4312 // If there is only one value, this is easy.
4313 if (getNumValues() == 1)
4314 return use_size() == NUses;
4315 if (use_size() < NUses) return false;
4317 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4319 SmallPtrSet<SDNode*, 32> UsersHandled;
4321 // TODO: Only iterate over uses of a given value of the node
4322 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4323 if (*UI == TheValue) {
4330 // Found exactly the right number of uses?
4335 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4336 /// value. This method ignores uses of other values defined by this operation.
4337 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4338 assert(Value < getNumValues() && "Bad value!");
4340 if (use_empty()) return false;
4342 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4344 SmallPtrSet<SDNode*, 32> UsersHandled;
4346 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4347 SDNode *User = UI->getUser();
4348 if (User->getNumOperands() == 1 ||
4349 UsersHandled.insert(User)) // First time we've seen this?
4350 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4351 if (User->getOperand(i) == TheValue) {
4360 /// isOnlyUseOf - Return true if this node is the only use of N.
4362 bool SDNode::isOnlyUseOf(SDNode *N) const {
4364 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4365 SDNode *User = I->getUser();
4375 /// isOperand - Return true if this node is an operand of N.
4377 bool SDOperand::isOperandOf(SDNode *N) const {
4378 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4379 if (*this == N->getOperand(i))
4384 bool SDNode::isOperandOf(SDNode *N) const {
4385 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4386 if (this == N->OperandList[i].getVal())
4391 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4392 /// be a chain) reaches the specified operand without crossing any
4393 /// side-effecting instructions. In practice, this looks through token
4394 /// factors and non-volatile loads. In order to remain efficient, this only
4395 /// looks a couple of nodes in, it does not do an exhaustive search.
4396 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4397 unsigned Depth) const {
4398 if (*this == Dest) return true;
4400 // Don't search too deeply, we just want to be able to see through
4401 // TokenFactor's etc.
4402 if (Depth == 0) return false;
4404 // If this is a token factor, all inputs to the TF happen in parallel. If any
4405 // of the operands of the TF reach dest, then we can do the xform.
4406 if (getOpcode() == ISD::TokenFactor) {
4407 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4408 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4413 // Loads don't have side effects, look through them.
4414 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4415 if (!Ld->isVolatile())
4416 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4422 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4423 SmallPtrSet<SDNode *, 32> &Visited) {
4424 if (found || !Visited.insert(N))
4427 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4428 SDNode *Op = N->getOperand(i).Val;
4433 findPredecessor(Op, P, found, Visited);
4437 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4438 /// is either an operand of N or it can be reached by recursively traversing
4439 /// up the operands.
4440 /// NOTE: this is an expensive method. Use it carefully.
4441 bool SDNode::isPredecessorOf(SDNode *N) const {
4442 SmallPtrSet<SDNode *, 32> Visited;
4444 findPredecessor(N, this, found, Visited);
4448 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4449 assert(Num < NumOperands && "Invalid child # of SDNode!");
4450 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4453 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4454 switch (getOpcode()) {
4456 if (getOpcode() < ISD::BUILTIN_OP_END)
4457 return "<<Unknown DAG Node>>";
4460 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4461 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4462 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4464 TargetLowering &TLI = G->getTargetLoweringInfo();
4466 TLI.getTargetNodeName(getOpcode());
4467 if (Name) return Name;
4470 return "<<Unknown Target Node>>";
4473 case ISD::PREFETCH: return "Prefetch";
4474 case ISD::MEMBARRIER: return "MemBarrier";
4475 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4476 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4477 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4478 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4479 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4480 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4481 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4482 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4483 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4484 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4485 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4486 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4487 case ISD::PCMARKER: return "PCMarker";
4488 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4489 case ISD::SRCVALUE: return "SrcValue";
4490 case ISD::MEMOPERAND: return "MemOperand";
4491 case ISD::EntryToken: return "EntryToken";
4492 case ISD::TokenFactor: return "TokenFactor";
4493 case ISD::AssertSext: return "AssertSext";
4494 case ISD::AssertZext: return "AssertZext";
4496 case ISD::BasicBlock: return "BasicBlock";
4497 case ISD::ARG_FLAGS: return "ArgFlags";
4498 case ISD::VALUETYPE: return "ValueType";
4499 case ISD::Register: return "Register";
4501 case ISD::Constant: return "Constant";
4502 case ISD::ConstantFP: return "ConstantFP";
4503 case ISD::GlobalAddress: return "GlobalAddress";
4504 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4505 case ISD::FrameIndex: return "FrameIndex";
4506 case ISD::JumpTable: return "JumpTable";
4507 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4508 case ISD::RETURNADDR: return "RETURNADDR";
4509 case ISD::FRAMEADDR: return "FRAMEADDR";
4510 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4511 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4512 case ISD::EHSELECTION: return "EHSELECTION";
4513 case ISD::EH_RETURN: return "EH_RETURN";
4514 case ISD::ConstantPool: return "ConstantPool";
4515 case ISD::ExternalSymbol: return "ExternalSymbol";
4516 case ISD::INTRINSIC_WO_CHAIN: {
4517 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4518 return Intrinsic::getName((Intrinsic::ID)IID);
4520 case ISD::INTRINSIC_VOID:
4521 case ISD::INTRINSIC_W_CHAIN: {
4522 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4523 return Intrinsic::getName((Intrinsic::ID)IID);
4526 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4527 case ISD::TargetConstant: return "TargetConstant";
4528 case ISD::TargetConstantFP:return "TargetConstantFP";
4529 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4530 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4531 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4532 case ISD::TargetJumpTable: return "TargetJumpTable";
4533 case ISD::TargetConstantPool: return "TargetConstantPool";
4534 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4536 case ISD::CopyToReg: return "CopyToReg";
4537 case ISD::CopyFromReg: return "CopyFromReg";
4538 case ISD::UNDEF: return "undef";
4539 case ISD::MERGE_VALUES: return "merge_values";
4540 case ISD::INLINEASM: return "inlineasm";
4541 case ISD::DBG_LABEL: return "dbg_label";
4542 case ISD::EH_LABEL: return "eh_label";
4543 case ISD::DECLARE: return "declare";
4544 case ISD::HANDLENODE: return "handlenode";
4545 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4546 case ISD::CALL: return "call";
4549 case ISD::FABS: return "fabs";
4550 case ISD::FNEG: return "fneg";
4551 case ISD::FSQRT: return "fsqrt";
4552 case ISD::FSIN: return "fsin";
4553 case ISD::FCOS: return "fcos";
4554 case ISD::FPOWI: return "fpowi";
4555 case ISD::FPOW: return "fpow";
4558 case ISD::ADD: return "add";
4559 case ISD::SUB: return "sub";
4560 case ISD::MUL: return "mul";
4561 case ISD::MULHU: return "mulhu";
4562 case ISD::MULHS: return "mulhs";
4563 case ISD::SDIV: return "sdiv";
4564 case ISD::UDIV: return "udiv";
4565 case ISD::SREM: return "srem";
4566 case ISD::UREM: return "urem";
4567 case ISD::SMUL_LOHI: return "smul_lohi";
4568 case ISD::UMUL_LOHI: return "umul_lohi";
4569 case ISD::SDIVREM: return "sdivrem";
4570 case ISD::UDIVREM: return "divrem";
4571 case ISD::AND: return "and";
4572 case ISD::OR: return "or";
4573 case ISD::XOR: return "xor";
4574 case ISD::SHL: return "shl";
4575 case ISD::SRA: return "sra";
4576 case ISD::SRL: return "srl";
4577 case ISD::ROTL: return "rotl";
4578 case ISD::ROTR: return "rotr";
4579 case ISD::FADD: return "fadd";
4580 case ISD::FSUB: return "fsub";
4581 case ISD::FMUL: return "fmul";
4582 case ISD::FDIV: return "fdiv";
4583 case ISD::FREM: return "frem";
4584 case ISD::FCOPYSIGN: return "fcopysign";
4585 case ISD::FGETSIGN: return "fgetsign";
4587 case ISD::SETCC: return "setcc";
4588 case ISD::VSETCC: return "vsetcc";
4589 case ISD::SELECT: return "select";
4590 case ISD::SELECT_CC: return "select_cc";
4591 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4592 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4593 case ISD::CONCAT_VECTORS: return "concat_vectors";
4594 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4595 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4596 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4597 case ISD::CARRY_FALSE: return "carry_false";
4598 case ISD::ADDC: return "addc";
4599 case ISD::ADDE: return "adde";
4600 case ISD::SUBC: return "subc";
4601 case ISD::SUBE: return "sube";
4602 case ISD::SHL_PARTS: return "shl_parts";
4603 case ISD::SRA_PARTS: return "sra_parts";
4604 case ISD::SRL_PARTS: return "srl_parts";
4606 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4607 case ISD::INSERT_SUBREG: return "insert_subreg";
4609 // Conversion operators.
4610 case ISD::SIGN_EXTEND: return "sign_extend";
4611 case ISD::ZERO_EXTEND: return "zero_extend";
4612 case ISD::ANY_EXTEND: return "any_extend";
4613 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4614 case ISD::TRUNCATE: return "truncate";
4615 case ISD::FP_ROUND: return "fp_round";
4616 case ISD::FLT_ROUNDS_: return "flt_rounds";
4617 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4618 case ISD::FP_EXTEND: return "fp_extend";
4620 case ISD::SINT_TO_FP: return "sint_to_fp";
4621 case ISD::UINT_TO_FP: return "uint_to_fp";
4622 case ISD::FP_TO_SINT: return "fp_to_sint";
4623 case ISD::FP_TO_UINT: return "fp_to_uint";
4624 case ISD::BIT_CONVERT: return "bit_convert";
4626 // Control flow instructions
4627 case ISD::BR: return "br";
4628 case ISD::BRIND: return "brind";
4629 case ISD::BR_JT: return "br_jt";
4630 case ISD::BRCOND: return "brcond";
4631 case ISD::BR_CC: return "br_cc";
4632 case ISD::RET: return "ret";
4633 case ISD::CALLSEQ_START: return "callseq_start";
4634 case ISD::CALLSEQ_END: return "callseq_end";
4637 case ISD::LOAD: return "load";
4638 case ISD::STORE: return "store";
4639 case ISD::VAARG: return "vaarg";
4640 case ISD::VACOPY: return "vacopy";
4641 case ISD::VAEND: return "vaend";
4642 case ISD::VASTART: return "vastart";
4643 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4644 case ISD::EXTRACT_ELEMENT: return "extract_element";
4645 case ISD::BUILD_PAIR: return "build_pair";
4646 case ISD::STACKSAVE: return "stacksave";
4647 case ISD::STACKRESTORE: return "stackrestore";
4648 case ISD::TRAP: return "trap";
4651 case ISD::BSWAP: return "bswap";
4652 case ISD::CTPOP: return "ctpop";
4653 case ISD::CTTZ: return "cttz";
4654 case ISD::CTLZ: return "ctlz";
4657 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4658 case ISD::DEBUG_LOC: return "debug_loc";
4661 case ISD::TRAMPOLINE: return "trampoline";
4664 switch (cast<CondCodeSDNode>(this)->get()) {
4665 default: assert(0 && "Unknown setcc condition!");
4666 case ISD::SETOEQ: return "setoeq";
4667 case ISD::SETOGT: return "setogt";
4668 case ISD::SETOGE: return "setoge";
4669 case ISD::SETOLT: return "setolt";
4670 case ISD::SETOLE: return "setole";
4671 case ISD::SETONE: return "setone";
4673 case ISD::SETO: return "seto";
4674 case ISD::SETUO: return "setuo";
4675 case ISD::SETUEQ: return "setue";
4676 case ISD::SETUGT: return "setugt";
4677 case ISD::SETUGE: return "setuge";
4678 case ISD::SETULT: return "setult";
4679 case ISD::SETULE: return "setule";
4680 case ISD::SETUNE: return "setune";
4682 case ISD::SETEQ: return "seteq";
4683 case ISD::SETGT: return "setgt";
4684 case ISD::SETGE: return "setge";
4685 case ISD::SETLT: return "setlt";
4686 case ISD::SETLE: return "setle";
4687 case ISD::SETNE: return "setne";
4692 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4701 return "<post-inc>";
4703 return "<post-dec>";
4707 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4708 std::string S = "< ";
4722 if (getByValAlign())
4723 S += "byval-align:" + utostr(getByValAlign()) + " ";
4725 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4727 S += "byval-size:" + utostr(getByValSize()) + " ";
4731 void SDNode::dump() const { dump(0); }
4732 void SDNode::dump(const SelectionDAG *G) const {
4733 cerr << (void*)this << ": ";
4735 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4737 if (getValueType(i) == MVT::Other)
4740 cerr << getValueType(i).getMVTString();
4742 cerr << " = " << getOperationName(G);
4745 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4746 if (i) cerr << ", ";
4747 cerr << (void*)getOperand(i).Val;
4748 if (unsigned RN = getOperand(i).ResNo)
4752 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4753 SDNode *Mask = getOperand(2).Val;
4755 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4757 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4760 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4765 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4766 cerr << "<" << CSDN->getValue() << ">";
4767 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4768 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4769 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4770 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4771 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4773 cerr << "<APFloat(";
4774 CSDN->getValueAPF().convertToAPInt().dump();
4777 } else if (const GlobalAddressSDNode *GADN =
4778 dyn_cast<GlobalAddressSDNode>(this)) {
4779 int offset = GADN->getOffset();
4781 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4783 cerr << " + " << offset;
4785 cerr << " " << offset;
4786 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4787 cerr << "<" << FIDN->getIndex() << ">";
4788 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4789 cerr << "<" << JTDN->getIndex() << ">";
4790 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4791 int offset = CP->getOffset();
4792 if (CP->isMachineConstantPoolEntry())
4793 cerr << "<" << *CP->getMachineCPVal() << ">";
4795 cerr << "<" << *CP->getConstVal() << ">";
4797 cerr << " + " << offset;
4799 cerr << " " << offset;
4800 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4802 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4804 cerr << LBB->getName() << " ";
4805 cerr << (const void*)BBDN->getBasicBlock() << ">";
4806 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4807 if (G && R->getReg() &&
4808 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4809 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4811 cerr << " #" << R->getReg();
4813 } else if (const ExternalSymbolSDNode *ES =
4814 dyn_cast<ExternalSymbolSDNode>(this)) {
4815 cerr << "'" << ES->getSymbol() << "'";
4816 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4818 cerr << "<" << M->getValue() << ">";
4821 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4822 if (M->MO.getValue())
4823 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4825 cerr << "<null:" << M->MO.getOffset() << ">";
4826 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4827 cerr << N->getArgFlags().getArgFlagsString();
4828 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4829 cerr << ":" << N->getVT().getMVTString();
4831 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4832 const Value *SrcValue = LD->getSrcValue();
4833 int SrcOffset = LD->getSrcValueOffset();
4839 cerr << ":" << SrcOffset << ">";
4842 switch (LD->getExtensionType()) {
4843 default: doExt = false; break;
4845 cerr << " <anyext ";
4855 cerr << LD->getMemoryVT().getMVTString() << ">";
4857 const char *AM = getIndexedModeName(LD->getAddressingMode());
4860 if (LD->isVolatile())
4861 cerr << " <volatile>";
4862 cerr << " alignment=" << LD->getAlignment();
4863 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4864 const Value *SrcValue = ST->getSrcValue();
4865 int SrcOffset = ST->getSrcValueOffset();
4871 cerr << ":" << SrcOffset << ">";
4873 if (ST->isTruncatingStore())
4875 << ST->getMemoryVT().getMVTString() << ">";
4877 const char *AM = getIndexedModeName(ST->getAddressingMode());
4880 if (ST->isVolatile())
4881 cerr << " <volatile>";
4882 cerr << " alignment=" << ST->getAlignment();
4883 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4884 const Value *SrcValue = AT->getSrcValue();
4885 int SrcOffset = AT->getSrcValueOffset();
4891 cerr << ":" << SrcOffset << ">";
4892 if (AT->isVolatile())
4893 cerr << " <volatile>";
4894 cerr << " alignment=" << AT->getAlignment();
4898 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4899 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4900 if (N->getOperand(i).Val->hasOneUse())
4901 DumpNodes(N->getOperand(i).Val, indent+2, G);
4903 cerr << "\n" << std::string(indent+2, ' ')
4904 << (void*)N->getOperand(i).Val << ": <multiple use>";
4907 cerr << "\n" << std::string(indent, ' ');
4911 void SelectionDAG::dump() const {
4912 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4913 std::vector<const SDNode*> Nodes;
4914 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4918 std::sort(Nodes.begin(), Nodes.end());
4920 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4921 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4922 DumpNodes(Nodes[i], 2, this);
4925 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4930 const Type *ConstantPoolSDNode::getType() const {
4931 if (isMachineConstantPoolEntry())
4932 return Val.MachineCPVal->getType();
4933 return Val.ConstVal->getType();