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::LABEL or TargetInstrInfo::LABEL node and third operand
197 bool ISD::isDebugLabel(const SDNode *N) {
199 if (N->getOpcode() == ISD::LABEL)
200 Zero = N->getOperand(2);
201 else if (N->isTargetOpcode() &&
202 N->getTargetOpcode() == TargetInstrInfo::LABEL)
203 // Chain moved to last operand.
204 Zero = N->getOperand(1);
207 return isa<ConstantSDNode>(Zero) && cast<ConstantSDNode>(Zero)->isNullValue();
210 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
211 /// when given the operation for (X op Y).
212 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
213 // To perform this operation, we just need to swap the L and G bits of the
215 unsigned OldL = (Operation >> 2) & 1;
216 unsigned OldG = (Operation >> 1) & 1;
217 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
218 (OldL << 1) | // New G bit
219 (OldG << 2)); // New L bit.
222 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
223 /// 'op' is a valid SetCC operation.
224 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
225 unsigned Operation = Op;
227 Operation ^= 7; // Flip L, G, E bits, but not U.
229 Operation ^= 15; // Flip all of the condition bits.
230 if (Operation > ISD::SETTRUE2)
231 Operation &= ~8; // Don't let N and U bits get set.
232 return ISD::CondCode(Operation);
236 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
237 /// signed operation and 2 if the result is an unsigned comparison. Return zero
238 /// if the operation does not depend on the sign of the input (setne and seteq).
239 static int isSignedOp(ISD::CondCode Opcode) {
241 default: assert(0 && "Illegal integer setcc operation!");
243 case ISD::SETNE: return 0;
247 case ISD::SETGE: return 1;
251 case ISD::SETUGE: return 2;
255 /// getSetCCOrOperation - Return the result of a logical OR between different
256 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
257 /// returns SETCC_INVALID if it is not possible to represent the resultant
259 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
261 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
262 // Cannot fold a signed integer setcc with an unsigned integer setcc.
263 return ISD::SETCC_INVALID;
265 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
267 // If the N and U bits get set then the resultant comparison DOES suddenly
268 // care about orderedness, and is true when ordered.
269 if (Op > ISD::SETTRUE2)
270 Op &= ~16; // Clear the U bit if the N bit is set.
272 // Canonicalize illegal integer setcc's.
273 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
276 return ISD::CondCode(Op);
279 /// getSetCCAndOperation - Return the result of a logical AND between different
280 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
281 /// function returns zero if it is not possible to represent the resultant
283 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
285 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
286 // Cannot fold a signed setcc with an unsigned setcc.
287 return ISD::SETCC_INVALID;
289 // Combine all of the condition bits.
290 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
292 // Canonicalize illegal integer setcc's.
296 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
297 case ISD::SETOEQ: // SETEQ & SETU[LG]E
298 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
299 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
300 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
307 const TargetMachine &SelectionDAG::getTarget() const {
308 return TLI.getTargetMachine();
311 //===----------------------------------------------------------------------===//
312 // SDNode Profile Support
313 //===----------------------------------------------------------------------===//
315 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
317 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
321 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
322 /// solely with their pointer.
323 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
324 ID.AddPointer(VTList.VTs);
327 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
329 static void AddNodeIDOperands(FoldingSetNodeID &ID,
330 SDOperandPtr Ops, unsigned NumOps) {
331 for (; NumOps; --NumOps, ++Ops) {
332 ID.AddPointer(Ops->Val);
333 ID.AddInteger(Ops->ResNo);
337 static void AddNodeIDNode(FoldingSetNodeID &ID,
338 unsigned short OpC, SDVTList VTList,
339 SDOperandPtr OpList, unsigned N) {
340 AddNodeIDOpcode(ID, OpC);
341 AddNodeIDValueTypes(ID, VTList);
342 AddNodeIDOperands(ID, OpList, N);
346 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
348 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
349 AddNodeIDOpcode(ID, N->getOpcode());
350 // Add the return value info.
351 AddNodeIDValueTypes(ID, N->getVTList());
352 // Add the operand info.
353 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
355 // Handle SDNode leafs with special info.
356 switch (N->getOpcode()) {
357 default: break; // Normal nodes don't need extra info.
359 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
361 case ISD::TargetConstant:
363 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
365 case ISD::TargetConstantFP:
366 case ISD::ConstantFP: {
367 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
370 case ISD::TargetGlobalAddress:
371 case ISD::GlobalAddress:
372 case ISD::TargetGlobalTLSAddress:
373 case ISD::GlobalTLSAddress: {
374 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
375 ID.AddPointer(GA->getGlobal());
376 ID.AddInteger(GA->getOffset());
379 case ISD::BasicBlock:
380 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
383 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
386 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
388 case ISD::MEMOPERAND: {
389 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
390 ID.AddPointer(MO.getValue());
391 ID.AddInteger(MO.getFlags());
392 ID.AddInteger(MO.getOffset());
393 ID.AddInteger(MO.getSize());
394 ID.AddInteger(MO.getAlignment());
397 case ISD::FrameIndex:
398 case ISD::TargetFrameIndex:
399 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
402 case ISD::TargetJumpTable:
403 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
405 case ISD::ConstantPool:
406 case ISD::TargetConstantPool: {
407 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
408 ID.AddInteger(CP->getAlignment());
409 ID.AddInteger(CP->getOffset());
410 if (CP->isMachineConstantPoolEntry())
411 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
413 ID.AddPointer(CP->getConstVal());
417 LoadSDNode *LD = cast<LoadSDNode>(N);
418 ID.AddInteger(LD->getAddressingMode());
419 ID.AddInteger(LD->getExtensionType());
420 ID.AddInteger(LD->getMemoryVT().getRawBits());
421 ID.AddInteger(LD->getAlignment());
422 ID.AddInteger(LD->isVolatile());
426 StoreSDNode *ST = cast<StoreSDNode>(N);
427 ID.AddInteger(ST->getAddressingMode());
428 ID.AddInteger(ST->isTruncatingStore());
429 ID.AddInteger(ST->getMemoryVT().getRawBits());
430 ID.AddInteger(ST->getAlignment());
431 ID.AddInteger(ST->isVolatile());
434 case ISD::ATOMIC_CMP_SWAP:
435 case ISD::ATOMIC_LOAD_ADD:
436 case ISD::ATOMIC_SWAP:
437 case ISD::ATOMIC_LOAD_SUB:
438 case ISD::ATOMIC_LOAD_AND:
439 case ISD::ATOMIC_LOAD_OR:
440 case ISD::ATOMIC_LOAD_XOR:
441 case ISD::ATOMIC_LOAD_NAND:
442 case ISD::ATOMIC_LOAD_MIN:
443 case ISD::ATOMIC_LOAD_MAX:
444 case ISD::ATOMIC_LOAD_UMIN:
445 case ISD::ATOMIC_LOAD_UMAX: {
446 AtomicSDNode *AT = cast<AtomicSDNode>(N);
447 ID.AddInteger(AT->getAlignment());
448 ID.AddInteger(AT->isVolatile());
451 } // end switch (N->getOpcode())
454 //===----------------------------------------------------------------------===//
455 // SelectionDAG Class
456 //===----------------------------------------------------------------------===//
458 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
460 void SelectionDAG::RemoveDeadNodes() {
461 // Create a dummy node (which is not added to allnodes), that adds a reference
462 // to the root node, preventing it from being deleted.
463 HandleSDNode Dummy(getRoot());
465 SmallVector<SDNode*, 128> DeadNodes;
467 // Add all obviously-dead nodes to the DeadNodes worklist.
468 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
470 DeadNodes.push_back(I);
472 // Process the worklist, deleting the nodes and adding their uses to the
474 while (!DeadNodes.empty()) {
475 SDNode *N = DeadNodes.back();
476 DeadNodes.pop_back();
478 // Take the node out of the appropriate CSE map.
479 RemoveNodeFromCSEMaps(N);
481 // Next, brutally remove the operand list. This is safe to do, as there are
482 // no cycles in the graph.
483 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
484 SDNode *Operand = I->getVal();
485 Operand->removeUser(std::distance(N->op_begin(), I), N);
487 // Now that we removed this operand, see if there are no uses of it left.
488 if (Operand->use_empty())
489 DeadNodes.push_back(Operand);
491 if (N->OperandsNeedDelete) {
492 delete[] N->OperandList;
497 // Finally, remove N itself.
501 // If the root changed (e.g. it was a dead load, update the root).
502 setRoot(Dummy.getValue());
505 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
506 SmallVector<SDNode*, 16> DeadNodes;
507 DeadNodes.push_back(N);
509 // Process the worklist, deleting the nodes and adding their uses to the
511 while (!DeadNodes.empty()) {
512 SDNode *N = DeadNodes.back();
513 DeadNodes.pop_back();
516 UpdateListener->NodeDeleted(N, 0);
518 // Take the node out of the appropriate CSE map.
519 RemoveNodeFromCSEMaps(N);
521 // Next, brutally remove the operand list. This is safe to do, as there are
522 // no cycles in the graph.
523 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
524 SDNode *Operand = I->getVal();
525 Operand->removeUser(std::distance(N->op_begin(), I), N);
527 // Now that we removed this operand, see if there are no uses of it left.
528 if (Operand->use_empty())
529 DeadNodes.push_back(Operand);
531 if (N->OperandsNeedDelete) {
532 delete[] N->OperandList;
537 // Finally, remove N itself.
542 void SelectionDAG::DeleteNode(SDNode *N) {
543 assert(N->use_empty() && "Cannot delete a node that is not dead!");
545 // First take this out of the appropriate CSE map.
546 RemoveNodeFromCSEMaps(N);
548 // Finally, remove uses due to operands of this node, remove from the
549 // AllNodes list, and delete the node.
550 DeleteNodeNotInCSEMaps(N);
553 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
555 // Remove it from the AllNodes list.
558 // Drop all of the operands and decrement used nodes use counts.
559 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
560 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
561 if (N->OperandsNeedDelete) {
562 delete[] N->OperandList;
570 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
571 /// correspond to it. This is useful when we're about to delete or repurpose
572 /// the node. We don't want future request for structurally identical nodes
573 /// to return N anymore.
574 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
576 switch (N->getOpcode()) {
577 case ISD::HANDLENODE: return; // noop.
579 Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
582 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
583 "Cond code doesn't exist!");
584 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
585 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
587 case ISD::ExternalSymbol:
588 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
590 case ISD::TargetExternalSymbol:
592 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
594 case ISD::VALUETYPE: {
595 MVT VT = cast<VTSDNode>(N)->getVT();
596 if (VT.isExtended()) {
597 Erased = ExtendedValueTypeNodes.erase(VT);
599 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
600 ValueTypeNodes[VT.getSimpleVT()] = 0;
605 // Remove it from the CSE Map.
606 Erased = CSEMap.RemoveNode(N);
610 // Verify that the node was actually in one of the CSE maps, unless it has a
611 // flag result (which cannot be CSE'd) or is one of the special cases that are
612 // not subject to CSE.
613 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
614 !N->isTargetOpcode()) {
617 assert(0 && "Node is not in map!");
622 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
623 /// has been taken out and modified in some way. If the specified node already
624 /// exists in the CSE maps, do not modify the maps, but return the existing node
625 /// instead. If it doesn't exist, add it and return null.
627 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
628 assert(N->getNumOperands() && "This is a leaf node!");
629 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
630 return 0; // Never add these nodes.
632 // Check that remaining values produced are not flags.
633 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
634 if (N->getValueType(i) == MVT::Flag)
635 return 0; // Never CSE anything that produces a flag.
637 SDNode *New = CSEMap.GetOrInsertNode(N);
638 if (New != N) return New; // Node already existed.
642 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
643 /// were replaced with those specified. If this node is never memoized,
644 /// return null, otherwise return a pointer to the slot it would take. If a
645 /// node already exists with these operands, the slot will be non-null.
646 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
648 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
649 return 0; // Never add these nodes.
651 // Check that remaining values produced are not flags.
652 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
653 if (N->getValueType(i) == MVT::Flag)
654 return 0; // Never CSE anything that produces a flag.
656 SDOperand Ops[] = { Op };
658 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
659 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
662 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
663 /// were replaced with those specified. If this node is never memoized,
664 /// return null, otherwise return a pointer to the slot it would take. If a
665 /// node already exists with these operands, the slot will be non-null.
666 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
667 SDOperand Op1, SDOperand Op2,
669 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
670 return 0; // Never add these nodes.
672 // Check that remaining values produced are not flags.
673 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
674 if (N->getValueType(i) == MVT::Flag)
675 return 0; // Never CSE anything that produces a flag.
677 SDOperand Ops[] = { Op1, Op2 };
679 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
680 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
684 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
685 /// were replaced with those specified. If this node is never memoized,
686 /// return null, otherwise return a pointer to the slot it would take. If a
687 /// node already exists with these operands, the slot will be non-null.
688 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
689 SDOperandPtr Ops,unsigned NumOps,
691 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
692 return 0; // Never add these nodes.
694 // Check that remaining values produced are not flags.
695 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
696 if (N->getValueType(i) == MVT::Flag)
697 return 0; // Never CSE anything that produces a flag.
700 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
702 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
703 ID.AddInteger(LD->getAddressingMode());
704 ID.AddInteger(LD->getExtensionType());
705 ID.AddInteger(LD->getMemoryVT().getRawBits());
706 ID.AddInteger(LD->getAlignment());
707 ID.AddInteger(LD->isVolatile());
708 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
709 ID.AddInteger(ST->getAddressingMode());
710 ID.AddInteger(ST->isTruncatingStore());
711 ID.AddInteger(ST->getMemoryVT().getRawBits());
712 ID.AddInteger(ST->getAlignment());
713 ID.AddInteger(ST->isVolatile());
716 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
720 SelectionDAG::~SelectionDAG() {
721 while (!AllNodes.empty()) {
722 SDNode *N = AllNodes.begin();
723 N->SetNextInBucket(0);
724 if (N->OperandsNeedDelete) {
725 delete [] N->OperandList;
729 AllNodes.pop_front();
733 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
734 if (Op.getValueType() == VT) return Op;
735 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
737 return getNode(ISD::AND, Op.getValueType(), Op,
738 getConstant(Imm, Op.getValueType()));
741 SDOperand SelectionDAG::getString(const std::string &Val) {
742 StringSDNode *&N = StringNodes[Val];
744 N = new StringSDNode(Val);
745 AllNodes.push_back(N);
747 return SDOperand(N, 0);
750 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
751 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
752 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
755 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
756 assert(VT.isInteger() && "Cannot create FP integer constant!");
758 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
759 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
760 "APInt size does not match type size!");
762 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
764 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
768 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
770 return SDOperand(N, 0);
772 N = new ConstantSDNode(isT, Val, EltVT);
773 CSEMap.InsertNode(N, IP);
774 AllNodes.push_back(N);
777 SDOperand Result(N, 0);
779 SmallVector<SDOperand, 8> Ops;
780 Ops.assign(VT.getVectorNumElements(), Result);
781 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
786 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
787 return getConstant(Val, TLI.getPointerTy(), isTarget);
791 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
792 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
795 VT.isVector() ? VT.getVectorElementType() : VT;
797 // Do the map lookup using the actual bit pattern for the floating point
798 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
799 // we don't have issues with SNANs.
800 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
802 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
806 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
808 return SDOperand(N, 0);
810 N = new ConstantFPSDNode(isTarget, V, EltVT);
811 CSEMap.InsertNode(N, IP);
812 AllNodes.push_back(N);
815 SDOperand Result(N, 0);
817 SmallVector<SDOperand, 8> Ops;
818 Ops.assign(VT.getVectorNumElements(), Result);
819 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
824 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
826 VT.isVector() ? VT.getVectorElementType() : VT;
828 return getConstantFP(APFloat((float)Val), VT, isTarget);
830 return getConstantFP(APFloat(Val), VT, isTarget);
833 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
838 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
840 // If GV is an alias then use the aliasee for determining thread-localness.
841 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
842 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
845 if (GVar && GVar->isThreadLocal())
846 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
848 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
851 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
853 ID.AddInteger(Offset);
855 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
856 return SDOperand(E, 0);
857 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
858 CSEMap.InsertNode(N, IP);
859 AllNodes.push_back(N);
860 return SDOperand(N, 0);
863 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
864 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
866 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
869 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
870 return SDOperand(E, 0);
871 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
872 CSEMap.InsertNode(N, IP);
873 AllNodes.push_back(N);
874 return SDOperand(N, 0);
877 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
878 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
880 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
883 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
884 return SDOperand(E, 0);
885 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
886 CSEMap.InsertNode(N, IP);
887 AllNodes.push_back(N);
888 return SDOperand(N, 0);
891 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
892 unsigned Alignment, int Offset,
894 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
896 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
897 ID.AddInteger(Alignment);
898 ID.AddInteger(Offset);
901 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
902 return SDOperand(E, 0);
903 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
904 CSEMap.InsertNode(N, IP);
905 AllNodes.push_back(N);
906 return SDOperand(N, 0);
910 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
911 unsigned Alignment, int Offset,
913 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
915 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
916 ID.AddInteger(Alignment);
917 ID.AddInteger(Offset);
918 C->AddSelectionDAGCSEId(ID);
920 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
921 return SDOperand(E, 0);
922 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
923 CSEMap.InsertNode(N, IP);
924 AllNodes.push_back(N);
925 return SDOperand(N, 0);
929 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
931 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), (SDOperand*)0, 0);
934 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
935 return SDOperand(E, 0);
936 SDNode *N = new BasicBlockSDNode(MBB);
937 CSEMap.InsertNode(N, IP);
938 AllNodes.push_back(N);
939 return SDOperand(N, 0);
942 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
944 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), (SDOperand*)0, 0);
945 ID.AddInteger(Flags.getRawBits());
947 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
948 return SDOperand(E, 0);
949 SDNode *N = new ARG_FLAGSSDNode(Flags);
950 CSEMap.InsertNode(N, IP);
951 AllNodes.push_back(N);
952 return SDOperand(N, 0);
955 SDOperand SelectionDAG::getValueType(MVT VT) {
956 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
957 ValueTypeNodes.resize(VT.getSimpleVT()+1);
959 SDNode *&N = VT.isExtended() ?
960 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
962 if (N) return SDOperand(N, 0);
963 N = new VTSDNode(VT);
964 AllNodes.push_back(N);
965 return SDOperand(N, 0);
968 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
969 SDNode *&N = ExternalSymbols[Sym];
970 if (N) return SDOperand(N, 0);
971 N = new ExternalSymbolSDNode(false, Sym, VT);
972 AllNodes.push_back(N);
973 return SDOperand(N, 0);
976 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
977 SDNode *&N = TargetExternalSymbols[Sym];
978 if (N) return SDOperand(N, 0);
979 N = new ExternalSymbolSDNode(true, Sym, VT);
980 AllNodes.push_back(N);
981 return SDOperand(N, 0);
984 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
985 if ((unsigned)Cond >= CondCodeNodes.size())
986 CondCodeNodes.resize(Cond+1);
988 if (CondCodeNodes[Cond] == 0) {
989 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
990 AllNodes.push_back(CondCodeNodes[Cond]);
992 return SDOperand(CondCodeNodes[Cond], 0);
995 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
997 AddNodeIDNode(ID, ISD::Register, getVTList(VT), (SDOperand*)0, 0);
998 ID.AddInteger(RegNo);
1000 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1001 return SDOperand(E, 0);
1002 SDNode *N = new RegisterSDNode(RegNo, VT);
1003 CSEMap.InsertNode(N, IP);
1004 AllNodes.push_back(N);
1005 return SDOperand(N, 0);
1008 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1009 assert((!V || isa<PointerType>(V->getType())) &&
1010 "SrcValue is not a pointer?");
1012 FoldingSetNodeID ID;
1013 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), (SDOperand*)0, 0);
1017 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1018 return SDOperand(E, 0);
1020 SDNode *N = new SrcValueSDNode(V);
1021 CSEMap.InsertNode(N, IP);
1022 AllNodes.push_back(N);
1023 return SDOperand(N, 0);
1026 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1027 const Value *v = MO.getValue();
1028 assert((!v || isa<PointerType>(v->getType())) &&
1029 "SrcValue is not a pointer?");
1031 FoldingSetNodeID ID;
1032 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), (SDOperand*)0, 0);
1034 ID.AddInteger(MO.getFlags());
1035 ID.AddInteger(MO.getOffset());
1036 ID.AddInteger(MO.getSize());
1037 ID.AddInteger(MO.getAlignment());
1040 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1041 return SDOperand(E, 0);
1043 SDNode *N = new MemOperandSDNode(MO);
1044 CSEMap.InsertNode(N, IP);
1045 AllNodes.push_back(N);
1046 return SDOperand(N, 0);
1049 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1050 /// specified value type.
1051 SDOperand SelectionDAG::CreateStackTemporary(MVT VT) {
1052 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1053 unsigned ByteSize = VT.getSizeInBits()/8;
1054 const Type *Ty = VT.getTypeForMVT();
1055 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
1056 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1057 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1061 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1062 SDOperand N2, ISD::CondCode Cond) {
1063 // These setcc operations always fold.
1067 case ISD::SETFALSE2: return getConstant(0, VT);
1069 case ISD::SETTRUE2: return getConstant(1, VT);
1081 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1085 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1086 const APInt &C2 = N2C->getAPIntValue();
1087 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1088 const APInt &C1 = N1C->getAPIntValue();
1091 default: assert(0 && "Unknown integer setcc!");
1092 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1093 case ISD::SETNE: return getConstant(C1 != C2, VT);
1094 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1095 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1096 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1097 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1098 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1099 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1100 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1101 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1105 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1106 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1107 // No compile time operations on this type yet.
1108 if (N1C->getValueType(0) == MVT::ppcf128)
1111 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1114 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1115 return getNode(ISD::UNDEF, VT);
1117 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1118 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1119 return getNode(ISD::UNDEF, VT);
1121 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1122 R==APFloat::cmpLessThan, VT);
1123 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1124 return getNode(ISD::UNDEF, VT);
1126 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1127 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1128 return getNode(ISD::UNDEF, VT);
1130 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1131 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1132 return getNode(ISD::UNDEF, VT);
1134 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1135 R==APFloat::cmpEqual, VT);
1136 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1137 return getNode(ISD::UNDEF, VT);
1139 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1140 R==APFloat::cmpEqual, VT);
1141 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1142 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1143 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1144 R==APFloat::cmpEqual, VT);
1145 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1146 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1147 R==APFloat::cmpLessThan, VT);
1148 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1149 R==APFloat::cmpUnordered, VT);
1150 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1151 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1154 // Ensure that the constant occurs on the RHS.
1155 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1159 // Could not fold it.
1163 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1164 /// use this predicate to simplify operations downstream.
1165 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1166 unsigned BitWidth = Op.getValueSizeInBits();
1167 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1170 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1171 /// this predicate to simplify operations downstream. Mask is known to be zero
1172 /// for bits that V cannot have.
1173 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1174 unsigned Depth) const {
1175 APInt KnownZero, KnownOne;
1176 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1177 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1178 return (KnownZero & Mask) == Mask;
1181 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1182 /// known to be either zero or one and return them in the KnownZero/KnownOne
1183 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1185 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1186 APInt &KnownZero, APInt &KnownOne,
1187 unsigned Depth) const {
1188 unsigned BitWidth = Mask.getBitWidth();
1189 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1190 "Mask size mismatches value type size!");
1192 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1193 if (Depth == 6 || Mask == 0)
1194 return; // Limit search depth.
1196 APInt KnownZero2, KnownOne2;
1198 switch (Op.getOpcode()) {
1200 // We know all of the bits for a constant!
1201 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1202 KnownZero = ~KnownOne & Mask;
1205 // If either the LHS or the RHS are Zero, the result is zero.
1206 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1207 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1208 KnownZero2, KnownOne2, Depth+1);
1209 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1210 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1212 // Output known-1 bits are only known if set in both the LHS & RHS.
1213 KnownOne &= KnownOne2;
1214 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1215 KnownZero |= KnownZero2;
1218 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1219 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1220 KnownZero2, KnownOne2, Depth+1);
1221 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1222 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1224 // Output known-0 bits are only known if clear in both the LHS & RHS.
1225 KnownZero &= KnownZero2;
1226 // Output known-1 are known to be set if set in either the LHS | RHS.
1227 KnownOne |= KnownOne2;
1230 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1231 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1232 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1233 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1235 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1236 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1237 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1238 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1239 KnownZero = KnownZeroOut;
1243 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1244 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1245 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1246 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1247 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1249 // If low bits are zero in either operand, output low known-0 bits.
1250 // Also compute a conserative estimate for high known-0 bits.
1251 // More trickiness is possible, but this is sufficient for the
1252 // interesting case of alignment computation.
1254 unsigned TrailZ = KnownZero.countTrailingOnes() +
1255 KnownZero2.countTrailingOnes();
1256 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1257 KnownZero2.countLeadingOnes(),
1258 BitWidth) - BitWidth;
1260 TrailZ = std::min(TrailZ, BitWidth);
1261 LeadZ = std::min(LeadZ, BitWidth);
1262 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1263 APInt::getHighBitsSet(BitWidth, LeadZ);
1268 // For the purposes of computing leading zeros we can conservatively
1269 // treat a udiv as a logical right shift by the power of 2 known to
1270 // be less than the denominator.
1271 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1272 ComputeMaskedBits(Op.getOperand(0),
1273 AllOnes, KnownZero2, KnownOne2, Depth+1);
1274 unsigned LeadZ = KnownZero2.countLeadingOnes();
1278 ComputeMaskedBits(Op.getOperand(1),
1279 AllOnes, KnownZero2, KnownOne2, Depth+1);
1280 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1281 if (RHSUnknownLeadingOnes != BitWidth)
1282 LeadZ = std::min(BitWidth,
1283 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1285 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1289 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1290 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1291 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1292 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1294 // Only known if known in both the LHS and RHS.
1295 KnownOne &= KnownOne2;
1296 KnownZero &= KnownZero2;
1298 case ISD::SELECT_CC:
1299 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1300 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1301 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1302 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1304 // Only known if known in both the LHS and RHS.
1305 KnownOne &= KnownOne2;
1306 KnownZero &= KnownZero2;
1309 // If we know the result of a setcc has the top bits zero, use this info.
1310 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1312 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1315 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1316 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1317 unsigned ShAmt = SA->getValue();
1319 // If the shift count is an invalid immediate, don't do anything.
1320 if (ShAmt >= BitWidth)
1323 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1324 KnownZero, KnownOne, Depth+1);
1325 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1326 KnownZero <<= ShAmt;
1328 // low bits known zero.
1329 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1333 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1334 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1335 unsigned ShAmt = SA->getValue();
1337 // If the shift count is an invalid immediate, don't do anything.
1338 if (ShAmt >= BitWidth)
1341 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1342 KnownZero, KnownOne, Depth+1);
1343 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1344 KnownZero = KnownZero.lshr(ShAmt);
1345 KnownOne = KnownOne.lshr(ShAmt);
1347 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1348 KnownZero |= HighBits; // High bits known zero.
1352 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1353 unsigned ShAmt = SA->getValue();
1355 // If the shift count is an invalid immediate, don't do anything.
1356 if (ShAmt >= BitWidth)
1359 APInt InDemandedMask = (Mask << ShAmt);
1360 // If any of the demanded bits are produced by the sign extension, we also
1361 // demand the input sign bit.
1362 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1363 if (HighBits.getBoolValue())
1364 InDemandedMask |= APInt::getSignBit(BitWidth);
1366 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1368 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1369 KnownZero = KnownZero.lshr(ShAmt);
1370 KnownOne = KnownOne.lshr(ShAmt);
1372 // Handle the sign bits.
1373 APInt SignBit = APInt::getSignBit(BitWidth);
1374 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1376 if (KnownZero.intersects(SignBit)) {
1377 KnownZero |= HighBits; // New bits are known zero.
1378 } else if (KnownOne.intersects(SignBit)) {
1379 KnownOne |= HighBits; // New bits are known one.
1383 case ISD::SIGN_EXTEND_INREG: {
1384 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1385 unsigned EBits = EVT.getSizeInBits();
1387 // Sign extension. Compute the demanded bits in the result that are not
1388 // present in the input.
1389 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1391 APInt InSignBit = APInt::getSignBit(EBits);
1392 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1394 // If the sign extended bits are demanded, we know that the sign
1396 InSignBit.zext(BitWidth);
1397 if (NewBits.getBoolValue())
1398 InputDemandedBits |= InSignBit;
1400 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1401 KnownZero, KnownOne, Depth+1);
1402 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1404 // If the sign bit of the input is known set or clear, then we know the
1405 // top bits of the result.
1406 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1407 KnownZero |= NewBits;
1408 KnownOne &= ~NewBits;
1409 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1410 KnownOne |= NewBits;
1411 KnownZero &= ~NewBits;
1412 } else { // Input sign bit unknown
1413 KnownZero &= ~NewBits;
1414 KnownOne &= ~NewBits;
1421 unsigned LowBits = Log2_32(BitWidth)+1;
1422 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1427 if (ISD::isZEXTLoad(Op.Val)) {
1428 LoadSDNode *LD = cast<LoadSDNode>(Op);
1429 MVT VT = LD->getMemoryVT();
1430 unsigned MemBits = VT.getSizeInBits();
1431 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1435 case ISD::ZERO_EXTEND: {
1436 MVT InVT = Op.getOperand(0).getValueType();
1437 unsigned InBits = InVT.getSizeInBits();
1438 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1439 APInt InMask = Mask;
1440 InMask.trunc(InBits);
1441 KnownZero.trunc(InBits);
1442 KnownOne.trunc(InBits);
1443 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1444 KnownZero.zext(BitWidth);
1445 KnownOne.zext(BitWidth);
1446 KnownZero |= NewBits;
1449 case ISD::SIGN_EXTEND: {
1450 MVT InVT = Op.getOperand(0).getValueType();
1451 unsigned InBits = InVT.getSizeInBits();
1452 APInt InSignBit = APInt::getSignBit(InBits);
1453 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1454 APInt InMask = Mask;
1455 InMask.trunc(InBits);
1457 // If any of the sign extended bits are demanded, we know that the sign
1458 // bit is demanded. Temporarily set this bit in the mask for our callee.
1459 if (NewBits.getBoolValue())
1460 InMask |= InSignBit;
1462 KnownZero.trunc(InBits);
1463 KnownOne.trunc(InBits);
1464 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1466 // Note if the sign bit is known to be zero or one.
1467 bool SignBitKnownZero = KnownZero.isNegative();
1468 bool SignBitKnownOne = KnownOne.isNegative();
1469 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1470 "Sign bit can't be known to be both zero and one!");
1472 // If the sign bit wasn't actually demanded by our caller, we don't
1473 // want it set in the KnownZero and KnownOne result values. Reset the
1474 // mask and reapply it to the result values.
1476 InMask.trunc(InBits);
1477 KnownZero &= InMask;
1480 KnownZero.zext(BitWidth);
1481 KnownOne.zext(BitWidth);
1483 // If the sign bit is known zero or one, the top bits match.
1484 if (SignBitKnownZero)
1485 KnownZero |= NewBits;
1486 else if (SignBitKnownOne)
1487 KnownOne |= NewBits;
1490 case ISD::ANY_EXTEND: {
1491 MVT InVT = Op.getOperand(0).getValueType();
1492 unsigned InBits = InVT.getSizeInBits();
1493 APInt InMask = Mask;
1494 InMask.trunc(InBits);
1495 KnownZero.trunc(InBits);
1496 KnownOne.trunc(InBits);
1497 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1498 KnownZero.zext(BitWidth);
1499 KnownOne.zext(BitWidth);
1502 case ISD::TRUNCATE: {
1503 MVT InVT = Op.getOperand(0).getValueType();
1504 unsigned InBits = InVT.getSizeInBits();
1505 APInt InMask = Mask;
1506 InMask.zext(InBits);
1507 KnownZero.zext(InBits);
1508 KnownOne.zext(InBits);
1509 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1510 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1511 KnownZero.trunc(BitWidth);
1512 KnownOne.trunc(BitWidth);
1515 case ISD::AssertZext: {
1516 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1517 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1518 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1520 KnownZero |= (~InMask) & Mask;
1524 // All bits are zero except the low bit.
1525 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1529 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1530 // We know that the top bits of C-X are clear if X contains less bits
1531 // than C (i.e. no wrap-around can happen). For example, 20-X is
1532 // positive if we can prove that X is >= 0 and < 16.
1533 if (CLHS->getAPIntValue().isNonNegative()) {
1534 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1535 // NLZ can't be BitWidth with no sign bit
1536 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1537 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1540 // If all of the MaskV bits are known to be zero, then we know the
1541 // output top bits are zero, because we now know that the output is
1543 if ((KnownZero2 & MaskV) == MaskV) {
1544 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1545 // Top bits known zero.
1546 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1553 // Output known-0 bits are known if clear or set in both the low clear bits
1554 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1555 // low 3 bits clear.
1556 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1557 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1558 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1559 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1561 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1562 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1563 KnownZeroOut = std::min(KnownZeroOut,
1564 KnownZero2.countTrailingOnes());
1566 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1570 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1571 APInt RA = Rem->getAPIntValue();
1572 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1573 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1574 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1575 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1577 // The sign of a remainder is equal to the sign of the first
1578 // operand (zero being positive).
1579 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1580 KnownZero2 |= ~LowBits;
1581 else if (KnownOne2[BitWidth-1])
1582 KnownOne2 |= ~LowBits;
1584 KnownZero |= KnownZero2 & Mask;
1585 KnownOne |= KnownOne2 & Mask;
1587 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1592 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1593 APInt RA = Rem->getAPIntValue();
1594 if (RA.isPowerOf2()) {
1595 APInt LowBits = (RA - 1);
1596 APInt Mask2 = LowBits & Mask;
1597 KnownZero |= ~LowBits & Mask;
1598 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1599 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1604 // Since the result is less than or equal to either operand, any leading
1605 // zero bits in either operand must also exist in the result.
1606 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1607 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1609 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1612 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1613 KnownZero2.countLeadingOnes());
1615 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1619 // Allow the target to implement this method for its nodes.
1620 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1621 case ISD::INTRINSIC_WO_CHAIN:
1622 case ISD::INTRINSIC_W_CHAIN:
1623 case ISD::INTRINSIC_VOID:
1624 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1630 /// ComputeNumSignBits - Return the number of times the sign bit of the
1631 /// register is replicated into the other bits. We know that at least 1 bit
1632 /// is always equal to the sign bit (itself), but other cases can give us
1633 /// information. For example, immediately after an "SRA X, 2", we know that
1634 /// the top 3 bits are all equal to each other, so we return 3.
1635 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1636 MVT VT = Op.getValueType();
1637 assert(VT.isInteger() && "Invalid VT!");
1638 unsigned VTBits = VT.getSizeInBits();
1640 unsigned FirstAnswer = 1;
1643 return 1; // Limit search depth.
1645 switch (Op.getOpcode()) {
1647 case ISD::AssertSext:
1648 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1649 return VTBits-Tmp+1;
1650 case ISD::AssertZext:
1651 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1654 case ISD::Constant: {
1655 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1656 // If negative, return # leading ones.
1657 if (Val.isNegative())
1658 return Val.countLeadingOnes();
1660 // Return # leading zeros.
1661 return Val.countLeadingZeros();
1664 case ISD::SIGN_EXTEND:
1665 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1666 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1668 case ISD::SIGN_EXTEND_INREG:
1669 // Max of the input and what this extends.
1670 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1673 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1674 return std::max(Tmp, Tmp2);
1677 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1678 // SRA X, C -> adds C sign bits.
1679 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1680 Tmp += C->getValue();
1681 if (Tmp > VTBits) Tmp = VTBits;
1685 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1686 // shl destroys sign bits.
1687 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1688 if (C->getValue() >= VTBits || // Bad shift.
1689 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1690 return Tmp - C->getValue();
1695 case ISD::XOR: // NOT is handled here.
1696 // Logical binary ops preserve the number of sign bits at the worst.
1697 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1699 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1700 FirstAnswer = std::min(Tmp, Tmp2);
1701 // We computed what we know about the sign bits as our first
1702 // answer. Now proceed to the generic code that uses
1703 // ComputeMaskedBits, and pick whichever answer is better.
1708 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1709 if (Tmp == 1) return 1; // Early out.
1710 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1711 return std::min(Tmp, Tmp2);
1714 // If setcc returns 0/-1, all bits are sign bits.
1715 if (TLI.getSetCCResultContents() ==
1716 TargetLowering::ZeroOrNegativeOneSetCCResult)
1721 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1722 unsigned RotAmt = C->getValue() & (VTBits-1);
1724 // Handle rotate right by N like a rotate left by 32-N.
1725 if (Op.getOpcode() == ISD::ROTR)
1726 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1728 // If we aren't rotating out all of the known-in sign bits, return the
1729 // number that are left. This handles rotl(sext(x), 1) for example.
1730 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1731 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1735 // Add can have at most one carry bit. Thus we know that the output
1736 // is, at worst, one more bit than the inputs.
1737 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1738 if (Tmp == 1) return 1; // Early out.
1740 // Special case decrementing a value (ADD X, -1):
1741 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1742 if (CRHS->isAllOnesValue()) {
1743 APInt KnownZero, KnownOne;
1744 APInt Mask = APInt::getAllOnesValue(VTBits);
1745 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1747 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1749 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1752 // If we are subtracting one from a positive number, there is no carry
1753 // out of the result.
1754 if (KnownZero.isNegative())
1758 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1759 if (Tmp2 == 1) return 1;
1760 return std::min(Tmp, Tmp2)-1;
1764 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1765 if (Tmp2 == 1) return 1;
1768 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1769 if (CLHS->isNullValue()) {
1770 APInt KnownZero, KnownOne;
1771 APInt Mask = APInt::getAllOnesValue(VTBits);
1772 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1773 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1775 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1778 // If the input is known to be positive (the sign bit is known clear),
1779 // the output of the NEG has the same number of sign bits as the input.
1780 if (KnownZero.isNegative())
1783 // Otherwise, we treat this like a SUB.
1786 // Sub can have at most one carry bit. Thus we know that the output
1787 // is, at worst, one more bit than the inputs.
1788 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1789 if (Tmp == 1) return 1; // Early out.
1790 return std::min(Tmp, Tmp2)-1;
1793 // FIXME: it's tricky to do anything useful for this, but it is an important
1794 // case for targets like X86.
1798 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1799 if (Op.getOpcode() == ISD::LOAD) {
1800 LoadSDNode *LD = cast<LoadSDNode>(Op);
1801 unsigned ExtType = LD->getExtensionType();
1804 case ISD::SEXTLOAD: // '17' bits known
1805 Tmp = LD->getMemoryVT().getSizeInBits();
1806 return VTBits-Tmp+1;
1807 case ISD::ZEXTLOAD: // '16' bits known
1808 Tmp = LD->getMemoryVT().getSizeInBits();
1813 // Allow the target to implement this method for its nodes.
1814 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1815 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1816 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1817 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1818 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1819 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1822 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1823 // use this information.
1824 APInt KnownZero, KnownOne;
1825 APInt Mask = APInt::getAllOnesValue(VTBits);
1826 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1828 if (KnownZero.isNegative()) { // sign bit is 0
1830 } else if (KnownOne.isNegative()) { // sign bit is 1;
1837 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1838 // the number of identical bits in the top of the input value.
1840 Mask <<= Mask.getBitWidth()-VTBits;
1841 // Return # leading zeros. We use 'min' here in case Val was zero before
1842 // shifting. We don't want to return '64' as for an i32 "0".
1843 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1847 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1848 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1849 if (!GA) return false;
1850 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1851 if (!GV) return false;
1852 MachineModuleInfo *MMI = getMachineModuleInfo();
1853 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1857 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1858 /// element of the result of the vector shuffle.
1859 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1860 MVT VT = N->getValueType(0);
1861 SDOperand PermMask = N->getOperand(2);
1862 SDOperand Idx = PermMask.getOperand(i);
1863 if (Idx.getOpcode() == ISD::UNDEF)
1864 return getNode(ISD::UNDEF, VT.getVectorElementType());
1865 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1866 unsigned NumElems = PermMask.getNumOperands();
1867 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1870 if (V.getOpcode() == ISD::BIT_CONVERT) {
1871 V = V.getOperand(0);
1872 if (V.getValueType().getVectorNumElements() != NumElems)
1875 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1876 return (Index == 0) ? V.getOperand(0)
1877 : getNode(ISD::UNDEF, VT.getVectorElementType());
1878 if (V.getOpcode() == ISD::BUILD_VECTOR)
1879 return V.getOperand(Index);
1880 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1881 return getShuffleScalarElt(V.Val, Index);
1886 /// getNode - Gets or creates the specified node.
1888 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1889 FoldingSetNodeID ID;
1890 AddNodeIDNode(ID, Opcode, getVTList(VT), (SDOperand*)0, 0);
1892 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1893 return SDOperand(E, 0);
1894 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1895 CSEMap.InsertNode(N, IP);
1897 AllNodes.push_back(N);
1898 return SDOperand(N, 0);
1901 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1902 // Constant fold unary operations with an integer constant operand.
1903 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1904 const APInt &Val = C->getAPIntValue();
1905 unsigned BitWidth = VT.getSizeInBits();
1908 case ISD::SIGN_EXTEND:
1909 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1910 case ISD::ANY_EXTEND:
1911 case ISD::ZERO_EXTEND:
1913 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1914 case ISD::UINT_TO_FP:
1915 case ISD::SINT_TO_FP: {
1916 const uint64_t zero[] = {0, 0};
1917 // No compile time operations on this type.
1918 if (VT==MVT::ppcf128)
1920 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1921 (void)apf.convertFromAPInt(Val,
1922 Opcode==ISD::SINT_TO_FP,
1923 APFloat::rmNearestTiesToEven);
1924 return getConstantFP(apf, VT);
1926 case ISD::BIT_CONVERT:
1927 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1928 return getConstantFP(Val.bitsToFloat(), VT);
1929 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1930 return getConstantFP(Val.bitsToDouble(), VT);
1933 return getConstant(Val.byteSwap(), VT);
1935 return getConstant(Val.countPopulation(), VT);
1937 return getConstant(Val.countLeadingZeros(), VT);
1939 return getConstant(Val.countTrailingZeros(), VT);
1943 // Constant fold unary operations with a floating point constant operand.
1944 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1945 APFloat V = C->getValueAPF(); // make copy
1946 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1950 return getConstantFP(V, VT);
1953 return getConstantFP(V, VT);
1955 case ISD::FP_EXTEND:
1956 // This can return overflow, underflow, or inexact; we don't care.
1957 // FIXME need to be more flexible about rounding mode.
1958 (void)V.convert(*MVTToAPFloatSemantics(VT),
1959 APFloat::rmNearestTiesToEven);
1960 return getConstantFP(V, VT);
1961 case ISD::FP_TO_SINT:
1962 case ISD::FP_TO_UINT: {
1964 assert(integerPartWidth >= 64);
1965 // FIXME need to be more flexible about rounding mode.
1966 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1967 Opcode==ISD::FP_TO_SINT,
1968 APFloat::rmTowardZero);
1969 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
1971 return getConstant(x, VT);
1973 case ISD::BIT_CONVERT:
1974 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1975 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1976 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1977 return getConstant(V.convertToAPInt().getZExtValue(), VT);
1983 unsigned OpOpcode = Operand.Val->getOpcode();
1985 case ISD::TokenFactor:
1986 return Operand; // Factor of one node? No need.
1987 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1988 case ISD::FP_EXTEND:
1989 assert(VT.isFloatingPoint() &&
1990 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
1991 if (Operand.getValueType() == VT) return Operand; // noop conversion.
1992 if (Operand.getOpcode() == ISD::UNDEF)
1993 return getNode(ISD::UNDEF, VT);
1995 case ISD::SIGN_EXTEND:
1996 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
1997 "Invalid SIGN_EXTEND!");
1998 if (Operand.getValueType() == VT) return Operand; // noop extension
1999 assert(Operand.getValueType().bitsLT(VT)
2000 && "Invalid sext node, dst < src!");
2001 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2002 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2004 case ISD::ZERO_EXTEND:
2005 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2006 "Invalid ZERO_EXTEND!");
2007 if (Operand.getValueType() == VT) return Operand; // noop extension
2008 assert(Operand.getValueType().bitsLT(VT)
2009 && "Invalid zext node, dst < src!");
2010 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2011 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2013 case ISD::ANY_EXTEND:
2014 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2015 "Invalid ANY_EXTEND!");
2016 if (Operand.getValueType() == VT) return Operand; // noop extension
2017 assert(Operand.getValueType().bitsLT(VT)
2018 && "Invalid anyext node, dst < src!");
2019 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2020 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2021 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2024 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2025 "Invalid TRUNCATE!");
2026 if (Operand.getValueType() == VT) return Operand; // noop truncate
2027 assert(Operand.getValueType().bitsGT(VT)
2028 && "Invalid truncate node, src < dst!");
2029 if (OpOpcode == ISD::TRUNCATE)
2030 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2031 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2032 OpOpcode == ISD::ANY_EXTEND) {
2033 // If the source is smaller than the dest, we still need an extend.
2034 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2035 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2036 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2037 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2039 return Operand.Val->getOperand(0);
2042 case ISD::BIT_CONVERT:
2043 // Basic sanity checking.
2044 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2045 && "Cannot BIT_CONVERT between types of different sizes!");
2046 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2047 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2048 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2049 if (OpOpcode == ISD::UNDEF)
2050 return getNode(ISD::UNDEF, VT);
2052 case ISD::SCALAR_TO_VECTOR:
2053 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2054 VT.getVectorElementType() == Operand.getValueType() &&
2055 "Illegal SCALAR_TO_VECTOR node!");
2056 if (OpOpcode == ISD::UNDEF)
2057 return getNode(ISD::UNDEF, VT);
2058 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2059 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2060 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2061 Operand.getConstantOperandVal(1) == 0 &&
2062 Operand.getOperand(0).getValueType() == VT)
2063 return Operand.getOperand(0);
2066 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2067 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2068 Operand.Val->getOperand(0));
2069 if (OpOpcode == ISD::FNEG) // --X -> X
2070 return Operand.Val->getOperand(0);
2073 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2074 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2079 SDVTList VTs = getVTList(VT);
2080 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2081 FoldingSetNodeID ID;
2082 SDOperand Ops[1] = { Operand };
2083 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2085 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2086 return SDOperand(E, 0);
2087 N = new UnarySDNode(Opcode, VTs, Operand);
2088 CSEMap.InsertNode(N, IP);
2090 N = new UnarySDNode(Opcode, VTs, Operand);
2092 AllNodes.push_back(N);
2093 return SDOperand(N, 0);
2098 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2099 SDOperand N1, SDOperand N2) {
2100 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2101 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2104 case ISD::TokenFactor:
2105 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2106 N2.getValueType() == MVT::Other && "Invalid token factor!");
2107 // Fold trivial token factors.
2108 if (N1.getOpcode() == ISD::EntryToken) return N2;
2109 if (N2.getOpcode() == ISD::EntryToken) return N1;
2112 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2113 N1.getValueType() == VT && "Binary operator types must match!");
2114 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2115 // worth handling here.
2116 if (N2C && N2C->isNullValue())
2118 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2125 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2126 N1.getValueType() == VT && "Binary operator types must match!");
2127 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2128 // it's worth handling here.
2129 if (N2C && N2C->isNullValue())
2136 assert(VT.isInteger() && "This operator does not apply to FP types!");
2146 assert(N1.getValueType() == N2.getValueType() &&
2147 N1.getValueType() == VT && "Binary operator types must match!");
2149 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2150 assert(N1.getValueType() == VT &&
2151 N1.getValueType().isFloatingPoint() &&
2152 N2.getValueType().isFloatingPoint() &&
2153 "Invalid FCOPYSIGN!");
2160 assert(VT == N1.getValueType() &&
2161 "Shift operators return type must be the same as their first arg");
2162 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2163 VT != MVT::i1 && "Shifts only work on integers");
2165 case ISD::FP_ROUND_INREG: {
2166 MVT EVT = cast<VTSDNode>(N2)->getVT();
2167 assert(VT == N1.getValueType() && "Not an inreg round!");
2168 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2169 "Cannot FP_ROUND_INREG integer types");
2170 assert(EVT.bitsLE(VT) && "Not rounding down!");
2171 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2175 assert(VT.isFloatingPoint() &&
2176 N1.getValueType().isFloatingPoint() &&
2177 VT.bitsLE(N1.getValueType()) &&
2178 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2179 if (N1.getValueType() == VT) return N1; // noop conversion.
2181 case ISD::AssertSext:
2182 case ISD::AssertZext: {
2183 MVT EVT = cast<VTSDNode>(N2)->getVT();
2184 assert(VT == N1.getValueType() && "Not an inreg extend!");
2185 assert(VT.isInteger() && EVT.isInteger() &&
2186 "Cannot *_EXTEND_INREG FP types");
2187 assert(EVT.bitsLE(VT) && "Not extending!");
2188 if (VT == EVT) return N1; // noop assertion.
2191 case ISD::SIGN_EXTEND_INREG: {
2192 MVT EVT = cast<VTSDNode>(N2)->getVT();
2193 assert(VT == N1.getValueType() && "Not an inreg extend!");
2194 assert(VT.isInteger() && EVT.isInteger() &&
2195 "Cannot *_EXTEND_INREG FP types");
2196 assert(EVT.bitsLE(VT) && "Not extending!");
2197 if (EVT == VT) return N1; // Not actually extending
2200 APInt Val = N1C->getAPIntValue();
2201 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2202 Val <<= Val.getBitWidth()-FromBits;
2203 Val = Val.ashr(Val.getBitWidth()-FromBits);
2204 return getConstant(Val, VT);
2208 case ISD::EXTRACT_VECTOR_ELT:
2209 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2211 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2212 if (N1.getOpcode() == ISD::UNDEF)
2213 return getNode(ISD::UNDEF, VT);
2215 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2216 // expanding copies of large vectors from registers.
2217 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2218 N1.getNumOperands() > 0) {
2220 N1.getOperand(0).getValueType().getVectorNumElements();
2221 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2222 N1.getOperand(N2C->getValue() / Factor),
2223 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2226 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2227 // expanding large vector constants.
2228 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2229 return N1.getOperand(N2C->getValue());
2231 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2232 // operations are lowered to scalars.
2233 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2234 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2236 return N1.getOperand(1);
2238 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2241 case ISD::EXTRACT_ELEMENT:
2242 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2243 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2244 (N1.getValueType().isInteger() == VT.isInteger()) &&
2245 "Wrong types for EXTRACT_ELEMENT!");
2247 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2248 // 64-bit integers into 32-bit parts. Instead of building the extract of
2249 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2250 if (N1.getOpcode() == ISD::BUILD_PAIR)
2251 return N1.getOperand(N2C->getValue());
2253 // EXTRACT_ELEMENT of a constant int is also very common.
2254 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2255 unsigned ElementSize = VT.getSizeInBits();
2256 unsigned Shift = ElementSize * N2C->getValue();
2257 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2258 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2261 case ISD::EXTRACT_SUBVECTOR:
2262 if (N1.getValueType() == VT) // Trivial extraction.
2269 APInt C1 = N1C->getAPIntValue(), C2 = N2C->getAPIntValue();
2271 case ISD::ADD: return getConstant(C1 + C2, VT);
2272 case ISD::SUB: return getConstant(C1 - C2, VT);
2273 case ISD::MUL: return getConstant(C1 * C2, VT);
2275 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2278 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2281 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2284 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2286 case ISD::AND : return getConstant(C1 & C2, VT);
2287 case ISD::OR : return getConstant(C1 | C2, VT);
2288 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2289 case ISD::SHL : return getConstant(C1 << C2, VT);
2290 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2291 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2292 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2293 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2296 } else { // Cannonicalize constant to RHS if commutative
2297 if (isCommutativeBinOp(Opcode)) {
2298 std::swap(N1C, N2C);
2304 // Constant fold FP operations.
2305 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2306 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2308 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2309 // Cannonicalize constant to RHS if commutative
2310 std::swap(N1CFP, N2CFP);
2312 } else if (N2CFP && VT != MVT::ppcf128) {
2313 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2314 APFloat::opStatus s;
2317 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2318 if (s != APFloat::opInvalidOp)
2319 return getConstantFP(V1, VT);
2322 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2323 if (s!=APFloat::opInvalidOp)
2324 return getConstantFP(V1, VT);
2327 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2328 if (s!=APFloat::opInvalidOp)
2329 return getConstantFP(V1, VT);
2332 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2333 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2334 return getConstantFP(V1, VT);
2337 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2338 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2339 return getConstantFP(V1, VT);
2341 case ISD::FCOPYSIGN:
2343 return getConstantFP(V1, VT);
2349 // Canonicalize an UNDEF to the RHS, even over a constant.
2350 if (N1.getOpcode() == ISD::UNDEF) {
2351 if (isCommutativeBinOp(Opcode)) {
2355 case ISD::FP_ROUND_INREG:
2356 case ISD::SIGN_EXTEND_INREG:
2362 return N1; // fold op(undef, arg2) -> undef
2370 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2371 // For vectors, we can't easily build an all zero vector, just return
2378 // Fold a bunch of operators when the RHS is undef.
2379 if (N2.getOpcode() == ISD::UNDEF) {
2382 if (N1.getOpcode() == ISD::UNDEF)
2383 // Handle undef ^ undef -> 0 special case. This is a common
2385 return getConstant(0, VT);
2400 return N2; // fold op(arg1, undef) -> undef
2406 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2407 // For vectors, we can't easily build an all zero vector, just return
2412 return getConstant(VT.getIntegerVTBitMask(), VT);
2413 // For vectors, we can't easily build an all one vector, just return
2421 // Memoize this node if possible.
2423 SDVTList VTs = getVTList(VT);
2424 if (VT != MVT::Flag) {
2425 SDOperand Ops[] = { N1, N2 };
2426 FoldingSetNodeID ID;
2427 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2429 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2430 return SDOperand(E, 0);
2431 N = new BinarySDNode(Opcode, VTs, N1, N2);
2432 CSEMap.InsertNode(N, IP);
2434 N = new BinarySDNode(Opcode, VTs, N1, N2);
2437 AllNodes.push_back(N);
2438 return SDOperand(N, 0);
2441 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2442 SDOperand N1, SDOperand N2, SDOperand N3) {
2443 // Perform various simplifications.
2444 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2445 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2448 // Use FoldSetCC to simplify SETCC's.
2449 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2450 if (Simp.Val) return Simp;
2455 if (N1C->getValue())
2456 return N2; // select true, X, Y -> X
2458 return N3; // select false, X, Y -> Y
2461 if (N2 == N3) return N2; // select C, X, X -> X
2465 if (N2C->getValue()) // Unconditional branch
2466 return getNode(ISD::BR, MVT::Other, N1, N3);
2468 return N1; // Never-taken branch
2471 case ISD::VECTOR_SHUFFLE:
2472 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2473 VT.isVector() && N3.getValueType().isVector() &&
2474 N3.getOpcode() == ISD::BUILD_VECTOR &&
2475 VT.getVectorNumElements() == N3.getNumOperands() &&
2476 "Illegal VECTOR_SHUFFLE node!");
2478 case ISD::BIT_CONVERT:
2479 // Fold bit_convert nodes from a type to themselves.
2480 if (N1.getValueType() == VT)
2485 // Memoize node if it doesn't produce a flag.
2487 SDVTList VTs = getVTList(VT);
2488 if (VT != MVT::Flag) {
2489 SDOperand Ops[] = { N1, N2, N3 };
2490 FoldingSetNodeID ID;
2491 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2493 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2494 return SDOperand(E, 0);
2495 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2496 CSEMap.InsertNode(N, IP);
2498 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2500 AllNodes.push_back(N);
2501 return SDOperand(N, 0);
2504 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2505 SDOperand N1, SDOperand N2, SDOperand N3,
2507 SDOperand Ops[] = { N1, N2, N3, N4 };
2508 return getNode(Opcode, VT, Ops, 4);
2511 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2512 SDOperand N1, SDOperand N2, SDOperand N3,
2513 SDOperand N4, SDOperand N5) {
2514 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2515 return getNode(Opcode, VT, Ops, 5);
2518 /// getMemsetValue - Vectorized representation of the memset value
2520 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2521 unsigned NumBits = VT.isVector() ?
2522 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2523 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2524 APInt Val = APInt(NumBits, C->getValue() & 255);
2526 for (unsigned i = NumBits; i > 8; i >>= 1) {
2527 Val = (Val << Shift) | Val;
2531 return DAG.getConstant(Val, VT);
2532 return DAG.getConstantFP(APFloat(Val), VT);
2535 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2537 for (unsigned i = NumBits; i > 8; i >>= 1) {
2538 Value = DAG.getNode(ISD::OR, VT,
2539 DAG.getNode(ISD::SHL, VT, Value,
2540 DAG.getConstant(Shift, MVT::i8)), Value);
2547 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2548 /// used when a memcpy is turned into a memset when the source is a constant
2550 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2551 const TargetLowering &TLI,
2552 std::string &Str, unsigned Offset) {
2553 // Handle vector with all elements zero.
2556 return DAG.getConstant(0, VT);
2557 unsigned NumElts = VT.getVectorNumElements();
2558 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2559 return DAG.getNode(ISD::BIT_CONVERT, VT,
2560 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2563 assert(!VT.isVector() && "Can't handle vector type here!");
2564 unsigned NumBits = VT.getSizeInBits();
2565 unsigned MSB = NumBits / 8;
2567 if (TLI.isLittleEndian())
2568 Offset = Offset + MSB - 1;
2569 for (unsigned i = 0; i != MSB; ++i) {
2570 Val = (Val << 8) | (unsigned char)Str[Offset];
2571 Offset += TLI.isLittleEndian() ? -1 : 1;
2573 return DAG.getConstant(Val, VT);
2576 /// getMemBasePlusOffset - Returns base and offset node for the
2578 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2579 SelectionDAG &DAG) {
2580 MVT VT = Base.getValueType();
2581 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2584 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2586 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2587 unsigned SrcDelta = 0;
2588 GlobalAddressSDNode *G = NULL;
2589 if (Src.getOpcode() == ISD::GlobalAddress)
2590 G = cast<GlobalAddressSDNode>(Src);
2591 else if (Src.getOpcode() == ISD::ADD &&
2592 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2593 Src.getOperand(1).getOpcode() == ISD::Constant) {
2594 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2595 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2600 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2601 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2607 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2608 /// to replace the memset / memcpy is below the threshold. It also returns the
2609 /// types of the sequence of memory ops to perform memset / memcpy.
2611 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2612 SDOperand Dst, SDOperand Src,
2613 unsigned Limit, uint64_t Size, unsigned &Align,
2614 std::string &Str, bool &isSrcStr,
2616 const TargetLowering &TLI) {
2617 isSrcStr = isMemSrcFromString(Src, Str);
2618 bool isSrcConst = isa<ConstantSDNode>(Src);
2619 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2620 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2621 if (VT != MVT::iAny) {
2622 unsigned NewAlign = (unsigned)
2623 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2624 // If source is a string constant, this will require an unaligned load.
2625 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2626 if (Dst.getOpcode() != ISD::FrameIndex) {
2627 // Can't change destination alignment. It requires a unaligned store.
2631 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2632 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2633 if (MFI->isFixedObjectIndex(FI)) {
2634 // Can't change destination alignment. It requires a unaligned store.
2638 // Give the stack frame object a larger alignment if needed.
2639 if (MFI->getObjectAlignment(FI) < NewAlign)
2640 MFI->setObjectAlignment(FI, NewAlign);
2647 if (VT == MVT::iAny) {
2651 switch (Align & 7) {
2652 case 0: VT = MVT::i64; break;
2653 case 4: VT = MVT::i32; break;
2654 case 2: VT = MVT::i16; break;
2655 default: VT = MVT::i8; break;
2660 while (!TLI.isTypeLegal(LVT))
2661 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2662 assert(LVT.isInteger());
2668 unsigned NumMemOps = 0;
2670 unsigned VTSize = VT.getSizeInBits() / 8;
2671 while (VTSize > Size) {
2672 // For now, only use non-vector load / store's for the left-over pieces.
2673 if (VT.isVector()) {
2675 while (!TLI.isTypeLegal(VT))
2676 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2677 VTSize = VT.getSizeInBits() / 8;
2679 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2684 if (++NumMemOps > Limit)
2686 MemOps.push_back(VT);
2693 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2694 SDOperand Chain, SDOperand Dst,
2695 SDOperand Src, uint64_t Size,
2696 unsigned Align, bool AlwaysInline,
2697 const Value *DstSV, uint64_t DstSVOff,
2698 const Value *SrcSV, uint64_t SrcSVOff){
2699 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2701 // Expand memcpy to a series of load and store ops if the size operand falls
2702 // below a certain threshold.
2703 std::vector<MVT> MemOps;
2704 uint64_t Limit = -1;
2706 Limit = TLI.getMaxStoresPerMemcpy();
2707 unsigned DstAlign = Align; // Destination alignment can change.
2710 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2711 Str, CopyFromStr, DAG, TLI))
2715 bool isZeroStr = CopyFromStr && Str.empty();
2716 SmallVector<SDOperand, 8> OutChains;
2717 unsigned NumMemOps = MemOps.size();
2718 uint64_t SrcOff = 0, DstOff = 0;
2719 for (unsigned i = 0; i < NumMemOps; i++) {
2721 unsigned VTSize = VT.getSizeInBits() / 8;
2722 SDOperand Value, Store;
2724 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2725 // It's unlikely a store of a vector immediate can be done in a single
2726 // instruction. It would require a load from a constantpool first.
2727 // We also handle store a vector with all zero's.
2728 // FIXME: Handle other cases where store of vector immediate is done in
2729 // a single instruction.
2730 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2731 Store = DAG.getStore(Chain, Value,
2732 getMemBasePlusOffset(Dst, DstOff, DAG),
2733 DstSV, DstSVOff + DstOff);
2735 Value = DAG.getLoad(VT, Chain,
2736 getMemBasePlusOffset(Src, SrcOff, DAG),
2737 SrcSV, SrcSVOff + SrcOff, false, Align);
2738 Store = DAG.getStore(Chain, Value,
2739 getMemBasePlusOffset(Dst, DstOff, DAG),
2740 DstSV, DstSVOff + DstOff, false, DstAlign);
2742 OutChains.push_back(Store);
2747 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2748 &OutChains[0], OutChains.size());
2751 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2752 SDOperand Chain, SDOperand Dst,
2753 SDOperand Src, uint64_t Size,
2754 unsigned Align, bool AlwaysInline,
2755 const Value *DstSV, uint64_t DstSVOff,
2756 const Value *SrcSV, uint64_t SrcSVOff){
2757 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2759 // Expand memmove to a series of load and store ops if the size operand falls
2760 // below a certain threshold.
2761 std::vector<MVT> MemOps;
2762 uint64_t Limit = -1;
2764 Limit = TLI.getMaxStoresPerMemmove();
2765 unsigned DstAlign = Align; // Destination alignment can change.
2768 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2769 Str, CopyFromStr, DAG, TLI))
2772 uint64_t SrcOff = 0, DstOff = 0;
2774 SmallVector<SDOperand, 8> LoadValues;
2775 SmallVector<SDOperand, 8> LoadChains;
2776 SmallVector<SDOperand, 8> OutChains;
2777 unsigned NumMemOps = MemOps.size();
2778 for (unsigned i = 0; i < NumMemOps; i++) {
2780 unsigned VTSize = VT.getSizeInBits() / 8;
2781 SDOperand Value, Store;
2783 Value = DAG.getLoad(VT, Chain,
2784 getMemBasePlusOffset(Src, SrcOff, DAG),
2785 SrcSV, SrcSVOff + SrcOff, false, Align);
2786 LoadValues.push_back(Value);
2787 LoadChains.push_back(Value.getValue(1));
2790 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2791 &LoadChains[0], LoadChains.size());
2793 for (unsigned i = 0; i < NumMemOps; i++) {
2795 unsigned VTSize = VT.getSizeInBits() / 8;
2796 SDOperand Value, Store;
2798 Store = DAG.getStore(Chain, LoadValues[i],
2799 getMemBasePlusOffset(Dst, DstOff, DAG),
2800 DstSV, DstSVOff + DstOff, false, DstAlign);
2801 OutChains.push_back(Store);
2805 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2806 &OutChains[0], OutChains.size());
2809 static SDOperand getMemsetStores(SelectionDAG &DAG,
2810 SDOperand Chain, SDOperand Dst,
2811 SDOperand Src, uint64_t Size,
2813 const Value *DstSV, uint64_t DstSVOff) {
2814 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2816 // Expand memset to a series of load/store ops if the size operand
2817 // falls below a certain threshold.
2818 std::vector<MVT> MemOps;
2821 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2822 Size, Align, Str, CopyFromStr, DAG, TLI))
2825 SmallVector<SDOperand, 8> OutChains;
2826 uint64_t DstOff = 0;
2828 unsigned NumMemOps = MemOps.size();
2829 for (unsigned i = 0; i < NumMemOps; i++) {
2831 unsigned VTSize = VT.getSizeInBits() / 8;
2832 SDOperand Value = getMemsetValue(Src, VT, DAG);
2833 SDOperand Store = DAG.getStore(Chain, Value,
2834 getMemBasePlusOffset(Dst, DstOff, DAG),
2835 DstSV, DstSVOff + DstOff);
2836 OutChains.push_back(Store);
2840 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2841 &OutChains[0], OutChains.size());
2844 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2845 SDOperand Src, SDOperand Size,
2846 unsigned Align, bool AlwaysInline,
2847 const Value *DstSV, uint64_t DstSVOff,
2848 const Value *SrcSV, uint64_t SrcSVOff) {
2850 // Check to see if we should lower the memcpy to loads and stores first.
2851 // For cases within the target-specified limits, this is the best choice.
2852 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2854 // Memcpy with size zero? Just return the original chain.
2855 if (ConstantSize->isNullValue())
2859 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2860 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2865 // Then check to see if we should lower the memcpy with target-specific
2866 // code. If the target chooses to do this, this is the next best.
2868 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2870 DstSV, DstSVOff, SrcSV, SrcSVOff);
2874 // If we really need inline code and the target declined to provide it,
2875 // use a (potentially long) sequence of loads and stores.
2877 assert(ConstantSize && "AlwaysInline requires a constant size!");
2878 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2879 ConstantSize->getValue(), Align, true,
2880 DstSV, DstSVOff, SrcSV, SrcSVOff);
2883 // Emit a library call.
2884 TargetLowering::ArgListTy Args;
2885 TargetLowering::ArgListEntry Entry;
2886 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2887 Entry.Node = Dst; Args.push_back(Entry);
2888 Entry.Node = Src; Args.push_back(Entry);
2889 Entry.Node = Size; Args.push_back(Entry);
2890 std::pair<SDOperand,SDOperand> CallResult =
2891 TLI.LowerCallTo(Chain, Type::VoidTy,
2892 false, false, false, CallingConv::C, false,
2893 getExternalSymbol("memcpy", TLI.getPointerTy()),
2895 return CallResult.second;
2898 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2899 SDOperand Src, SDOperand Size,
2901 const Value *DstSV, uint64_t DstSVOff,
2902 const Value *SrcSV, uint64_t SrcSVOff) {
2904 // Check to see if we should lower the memmove to loads and stores first.
2905 // For cases within the target-specified limits, this is the best choice.
2906 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2908 // Memmove with size zero? Just return the original chain.
2909 if (ConstantSize->isNullValue())
2913 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2914 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2919 // Then check to see if we should lower the memmove with target-specific
2920 // code. If the target chooses to do this, this is the next best.
2922 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2923 DstSV, DstSVOff, SrcSV, SrcSVOff);
2927 // Emit a library call.
2928 TargetLowering::ArgListTy Args;
2929 TargetLowering::ArgListEntry Entry;
2930 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2931 Entry.Node = Dst; Args.push_back(Entry);
2932 Entry.Node = Src; Args.push_back(Entry);
2933 Entry.Node = Size; Args.push_back(Entry);
2934 std::pair<SDOperand,SDOperand> CallResult =
2935 TLI.LowerCallTo(Chain, Type::VoidTy,
2936 false, false, false, CallingConv::C, false,
2937 getExternalSymbol("memmove", TLI.getPointerTy()),
2939 return CallResult.second;
2942 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2943 SDOperand Src, SDOperand Size,
2945 const Value *DstSV, uint64_t DstSVOff) {
2947 // Check to see if we should lower the memset to stores first.
2948 // For cases within the target-specified limits, this is the best choice.
2949 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2951 // Memset with size zero? Just return the original chain.
2952 if (ConstantSize->isNullValue())
2956 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
2962 // Then check to see if we should lower the memset with target-specific
2963 // code. If the target chooses to do this, this is the next best.
2965 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
2970 // Emit a library call.
2971 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
2972 TargetLowering::ArgListTy Args;
2973 TargetLowering::ArgListEntry Entry;
2974 Entry.Node = Dst; Entry.Ty = IntPtrTy;
2975 Args.push_back(Entry);
2976 // Extend or truncate the argument to be an i32 value for the call.
2977 if (Src.getValueType().bitsGT(MVT::i32))
2978 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
2980 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
2981 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
2982 Args.push_back(Entry);
2983 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
2984 Args.push_back(Entry);
2985 std::pair<SDOperand,SDOperand> CallResult =
2986 TLI.LowerCallTo(Chain, Type::VoidTy,
2987 false, false, false, CallingConv::C, false,
2988 getExternalSymbol("memset", TLI.getPointerTy()),
2990 return CallResult.second;
2993 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
2994 SDOperand Ptr, SDOperand Cmp,
2995 SDOperand Swp, const Value* PtrVal,
2996 unsigned Alignment) {
2997 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
2998 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
2999 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
3000 FoldingSetNodeID ID;
3001 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3002 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3004 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3005 return SDOperand(E, 0);
3006 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp,
3008 CSEMap.InsertNode(N, IP);
3009 AllNodes.push_back(N);
3010 return SDOperand(N, 0);
3013 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3014 SDOperand Ptr, SDOperand Val,
3015 const Value* PtrVal,
3016 unsigned Alignment) {
3017 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3018 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3019 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3020 || Opcode == ISD::ATOMIC_LOAD_NAND
3021 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3022 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3023 && "Invalid Atomic Op");
3024 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3025 FoldingSetNodeID ID;
3026 SDOperand Ops[] = {Chain, Ptr, Val};
3027 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3029 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3030 return SDOperand(E, 0);
3031 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val,
3033 CSEMap.InsertNode(N, IP);
3034 AllNodes.push_back(N);
3035 return SDOperand(N, 0);
3039 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3040 MVT VT, SDOperand Chain,
3041 SDOperand Ptr, SDOperand Offset,
3042 const Value *SV, int SVOffset, MVT EVT,
3043 bool isVolatile, unsigned Alignment) {
3044 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3046 if (VT != MVT::iPTR) {
3047 Ty = VT.getTypeForMVT();
3049 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3050 assert(PT && "Value for load must be a pointer");
3051 Ty = PT->getElementType();
3053 assert(Ty && "Could not get type information for load");
3054 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3058 ExtType = ISD::NON_EXTLOAD;
3059 } else if (ExtType == ISD::NON_EXTLOAD) {
3060 assert(VT == EVT && "Non-extending load from different memory type!");
3064 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3066 assert(EVT.bitsLT(VT) &&
3067 "Should only be an extending load, not truncating!");
3068 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3069 "Cannot sign/zero extend a FP/Vector load!");
3070 assert(VT.isInteger() == EVT.isInteger() &&
3071 "Cannot convert from FP to Int or Int -> FP!");
3074 bool Indexed = AM != ISD::UNINDEXED;
3075 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3076 "Unindexed load with an offset!");
3078 SDVTList VTs = Indexed ?
3079 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3080 SDOperand Ops[] = { Chain, Ptr, Offset };
3081 FoldingSetNodeID ID;
3082 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3084 ID.AddInteger(ExtType);
3085 ID.AddInteger(EVT.getRawBits());
3086 ID.AddInteger(Alignment);
3087 ID.AddInteger(isVolatile);
3089 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3090 return SDOperand(E, 0);
3091 SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3092 Alignment, isVolatile);
3093 CSEMap.InsertNode(N, IP);
3094 AllNodes.push_back(N);
3095 return SDOperand(N, 0);
3098 SDOperand SelectionDAG::getLoad(MVT VT,
3099 SDOperand Chain, SDOperand Ptr,
3100 const Value *SV, int SVOffset,
3101 bool isVolatile, unsigned Alignment) {
3102 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3103 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3104 SV, SVOffset, VT, isVolatile, Alignment);
3107 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3108 SDOperand Chain, SDOperand Ptr,
3110 int SVOffset, MVT EVT,
3111 bool isVolatile, unsigned Alignment) {
3112 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3113 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3114 SV, SVOffset, EVT, isVolatile, Alignment);
3118 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3119 SDOperand Offset, ISD::MemIndexedMode AM) {
3120 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3121 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3122 "Load is already a indexed load!");
3123 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3124 LD->getChain(), Base, Offset, LD->getSrcValue(),
3125 LD->getSrcValueOffset(), LD->getMemoryVT(),
3126 LD->isVolatile(), LD->getAlignment());
3129 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3130 SDOperand Ptr, const Value *SV, int SVOffset,
3131 bool isVolatile, unsigned Alignment) {
3132 MVT VT = Val.getValueType();
3134 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3136 if (VT != MVT::iPTR) {
3137 Ty = VT.getTypeForMVT();
3139 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3140 assert(PT && "Value for store must be a pointer");
3141 Ty = PT->getElementType();
3143 assert(Ty && "Could not get type information for store");
3144 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3146 SDVTList VTs = getVTList(MVT::Other);
3147 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3148 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3149 FoldingSetNodeID ID;
3150 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3151 ID.AddInteger(ISD::UNINDEXED);
3152 ID.AddInteger(false);
3153 ID.AddInteger(VT.getRawBits());
3154 ID.AddInteger(Alignment);
3155 ID.AddInteger(isVolatile);
3157 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3158 return SDOperand(E, 0);
3159 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3160 VT, SV, SVOffset, Alignment, isVolatile);
3161 CSEMap.InsertNode(N, IP);
3162 AllNodes.push_back(N);
3163 return SDOperand(N, 0);
3166 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3167 SDOperand Ptr, const Value *SV,
3168 int SVOffset, MVT SVT,
3169 bool isVolatile, unsigned Alignment) {
3170 MVT VT = Val.getValueType();
3173 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3175 assert(VT.bitsGT(SVT) && "Not a truncation?");
3176 assert(VT.isInteger() == SVT.isInteger() &&
3177 "Can't do FP-INT conversion!");
3179 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3181 if (VT != MVT::iPTR) {
3182 Ty = VT.getTypeForMVT();
3184 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3185 assert(PT && "Value for store must be a pointer");
3186 Ty = PT->getElementType();
3188 assert(Ty && "Could not get type information for store");
3189 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3191 SDVTList VTs = getVTList(MVT::Other);
3192 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3193 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3194 FoldingSetNodeID ID;
3195 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3196 ID.AddInteger(ISD::UNINDEXED);
3198 ID.AddInteger(SVT.getRawBits());
3199 ID.AddInteger(Alignment);
3200 ID.AddInteger(isVolatile);
3202 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3203 return SDOperand(E, 0);
3204 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3205 SVT, SV, SVOffset, Alignment, isVolatile);
3206 CSEMap.InsertNode(N, IP);
3207 AllNodes.push_back(N);
3208 return SDOperand(N, 0);
3212 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3213 SDOperand Offset, ISD::MemIndexedMode AM) {
3214 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3215 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3216 "Store is already a indexed store!");
3217 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3218 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3219 FoldingSetNodeID ID;
3220 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3222 ID.AddInteger(ST->isTruncatingStore());
3223 ID.AddInteger(ST->getMemoryVT().getRawBits());
3224 ID.AddInteger(ST->getAlignment());
3225 ID.AddInteger(ST->isVolatile());
3227 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3228 return SDOperand(E, 0);
3229 SDNode *N = new StoreSDNode(Ops, VTs, AM,
3230 ST->isTruncatingStore(), ST->getMemoryVT(),
3231 ST->getSrcValue(), ST->getSrcValueOffset(),
3232 ST->getAlignment(), ST->isVolatile());
3233 CSEMap.InsertNode(N, IP);
3234 AllNodes.push_back(N);
3235 return SDOperand(N, 0);
3238 SDOperand SelectionDAG::getVAArg(MVT VT,
3239 SDOperand Chain, SDOperand Ptr,
3241 SDOperand Ops[] = { Chain, Ptr, SV };
3242 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3245 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3246 SDOperandPtr Ops, unsigned NumOps) {
3248 case 0: return getNode(Opcode, VT);
3249 case 1: return getNode(Opcode, VT, Ops[0]);
3250 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3251 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3257 case ISD::SELECT_CC: {
3258 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3259 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3260 "LHS and RHS of condition must have same type!");
3261 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3262 "True and False arms of SelectCC must have same type!");
3263 assert(Ops[2].getValueType() == VT &&
3264 "select_cc node must be of same type as true and false value!");
3268 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3269 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3270 "LHS/RHS of comparison should match types!");
3277 SDVTList VTs = getVTList(VT);
3278 if (VT != MVT::Flag) {
3279 FoldingSetNodeID ID;
3280 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3282 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3283 return SDOperand(E, 0);
3284 N = new SDNode(Opcode, VTs, Ops, NumOps);
3285 CSEMap.InsertNode(N, IP);
3287 N = new SDNode(Opcode, VTs, Ops, NumOps);
3289 AllNodes.push_back(N);
3290 return SDOperand(N, 0);
3293 SDOperand SelectionDAG::getNode(unsigned Opcode,
3294 std::vector<MVT> &ResultTys,
3295 SDOperandPtr Ops, unsigned NumOps) {
3296 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3300 SDOperand SelectionDAG::getNode(unsigned Opcode,
3301 const MVT *VTs, unsigned NumVTs,
3302 SDOperandPtr Ops, unsigned NumOps) {
3304 return getNode(Opcode, VTs[0], Ops, NumOps);
3305 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3308 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3309 SDOperandPtr Ops, unsigned NumOps) {
3310 if (VTList.NumVTs == 1)
3311 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3314 // FIXME: figure out how to safely handle things like
3315 // int foo(int x) { return 1 << (x & 255); }
3316 // int bar() { return foo(256); }
3318 case ISD::SRA_PARTS:
3319 case ISD::SRL_PARTS:
3320 case ISD::SHL_PARTS:
3321 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3322 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3323 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3324 else if (N3.getOpcode() == ISD::AND)
3325 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3326 // If the and is only masking out bits that cannot effect the shift,
3327 // eliminate the and.
3328 unsigned NumBits = VT.getSizeInBits()*2;
3329 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3330 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3336 // Memoize the node unless it returns a flag.
3338 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3339 FoldingSetNodeID ID;
3340 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3342 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3343 return SDOperand(E, 0);
3345 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3346 else if (NumOps == 2)
3347 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3348 else if (NumOps == 3)
3349 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3351 N = new SDNode(Opcode, VTList, Ops, NumOps);
3352 CSEMap.InsertNode(N, IP);
3355 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3356 else if (NumOps == 2)
3357 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3358 else if (NumOps == 3)
3359 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3361 N = new SDNode(Opcode, VTList, Ops, NumOps);
3363 AllNodes.push_back(N);
3364 return SDOperand(N, 0);
3367 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3368 return getNode(Opcode, VTList, (SDOperand*)0, 0);
3371 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3373 SDOperand Ops[] = { N1 };
3374 return getNode(Opcode, VTList, Ops, 1);
3377 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3378 SDOperand N1, SDOperand N2) {
3379 SDOperand Ops[] = { N1, N2 };
3380 return getNode(Opcode, VTList, Ops, 2);
3383 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3384 SDOperand N1, SDOperand N2, SDOperand N3) {
3385 SDOperand Ops[] = { N1, N2, N3 };
3386 return getNode(Opcode, VTList, Ops, 3);
3389 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3390 SDOperand N1, SDOperand N2, SDOperand N3,
3392 SDOperand Ops[] = { N1, N2, N3, N4 };
3393 return getNode(Opcode, VTList, Ops, 4);
3396 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3397 SDOperand N1, SDOperand N2, SDOperand N3,
3398 SDOperand N4, SDOperand N5) {
3399 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3400 return getNode(Opcode, VTList, Ops, 5);
3403 SDVTList SelectionDAG::getVTList(MVT VT) {
3404 return makeVTList(SDNode::getValueTypeList(VT), 1);
3407 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3408 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3409 E = VTList.end(); I != E; ++I) {
3410 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3411 return makeVTList(&(*I)[0], 2);
3416 VTList.push_front(V);
3417 return makeVTList(&(*VTList.begin())[0], 2);
3419 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3421 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3422 E = VTList.end(); I != E; ++I) {
3423 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3425 return makeVTList(&(*I)[0], 3);
3431 VTList.push_front(V);
3432 return makeVTList(&(*VTList.begin())[0], 3);
3435 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3437 case 0: assert(0 && "Cannot have nodes without results!");
3438 case 1: return getVTList(VTs[0]);
3439 case 2: return getVTList(VTs[0], VTs[1]);
3440 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3444 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3445 E = VTList.end(); I != E; ++I) {
3446 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3448 bool NoMatch = false;
3449 for (unsigned i = 2; i != NumVTs; ++i)
3450 if (VTs[i] != (*I)[i]) {
3455 return makeVTList(&*I->begin(), NumVTs);
3458 VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3459 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3463 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3464 /// specified operands. If the resultant node already exists in the DAG,
3465 /// this does not modify the specified node, instead it returns the node that
3466 /// already exists. If the resultant node does not exist in the DAG, the
3467 /// input node is returned. As a degenerate case, if you specify the same
3468 /// input operands as the node already has, the input node is returned.
3469 SDOperand SelectionDAG::
3470 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3471 SDNode *N = InN.Val;
3472 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3474 // Check to see if there is no change.
3475 if (Op == N->getOperand(0)) return InN;
3477 // See if the modified node already exists.
3478 void *InsertPos = 0;
3479 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3480 return SDOperand(Existing, InN.ResNo);
3482 // Nope it doesn't. Remove the node from it's current place in the maps.
3484 RemoveNodeFromCSEMaps(N);
3486 // Now we update the operands.
3487 N->OperandList[0].getVal()->removeUser(0, N);
3488 N->OperandList[0] = Op;
3489 N->OperandList[0].setUser(N);
3490 Op.Val->addUser(0, N);
3492 // If this gets put into a CSE map, add it.
3493 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3497 SDOperand SelectionDAG::
3498 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3499 SDNode *N = InN.Val;
3500 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3502 // Check to see if there is no change.
3503 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3504 return InN; // No operands changed, just return the input node.
3506 // See if the modified node already exists.
3507 void *InsertPos = 0;
3508 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, 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 if (N->OperandList[0] != Op1) {
3517 N->OperandList[0].getVal()->removeUser(0, N);
3518 N->OperandList[0] = Op1;
3519 N->OperandList[0].setUser(N);
3520 Op1.Val->addUser(0, N);
3522 if (N->OperandList[1] != Op2) {
3523 N->OperandList[1].getVal()->removeUser(1, N);
3524 N->OperandList[1] = Op2;
3525 N->OperandList[1].setUser(N);
3526 Op2.Val->addUser(1, N);
3529 // If this gets put into a CSE map, add it.
3530 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3534 SDOperand SelectionDAG::
3535 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3536 SDOperand Ops[] = { Op1, Op2, Op3 };
3537 return UpdateNodeOperands(N, Ops, 3);
3540 SDOperand SelectionDAG::
3541 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3542 SDOperand Op3, SDOperand Op4) {
3543 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3544 return UpdateNodeOperands(N, Ops, 4);
3547 SDOperand SelectionDAG::
3548 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3549 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3550 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3551 return UpdateNodeOperands(N, Ops, 5);
3554 SDOperand SelectionDAG::
3555 UpdateNodeOperands(SDOperand InN, SDOperandPtr Ops, unsigned NumOps) {
3556 SDNode *N = InN.Val;
3557 assert(N->getNumOperands() == NumOps &&
3558 "Update with wrong number of operands");
3560 // Check to see if there is no change.
3561 bool AnyChange = false;
3562 for (unsigned i = 0; i != NumOps; ++i) {
3563 if (Ops[i] != N->getOperand(i)) {
3569 // No operands changed, just return the input node.
3570 if (!AnyChange) return InN;
3572 // See if the modified node already exists.
3573 void *InsertPos = 0;
3574 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3575 return SDOperand(Existing, InN.ResNo);
3577 // Nope it doesn't. Remove the node from its current place in the maps.
3579 RemoveNodeFromCSEMaps(N);
3581 // Now we update the operands.
3582 for (unsigned i = 0; i != NumOps; ++i) {
3583 if (N->OperandList[i] != Ops[i]) {
3584 N->OperandList[i].getVal()->removeUser(i, N);
3585 N->OperandList[i] = Ops[i];
3586 N->OperandList[i].setUser(N);
3587 Ops[i].Val->addUser(i, N);
3591 // If this gets put into a CSE map, add it.
3592 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3596 /// MorphNodeTo - This frees the operands of the current node, resets the
3597 /// opcode, types, and operands to the specified value. This should only be
3598 /// used by the SelectionDAG class.
3599 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3600 SDOperandPtr Ops, unsigned NumOps) {
3603 NumValues = L.NumVTs;
3605 // Clear the operands list, updating used nodes to remove this from their
3607 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3608 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3610 // If NumOps is larger than the # of operands we currently have, reallocate
3611 // the operand list.
3612 if (NumOps > NumOperands) {
3613 if (OperandsNeedDelete) {
3614 delete [] OperandList;
3616 OperandList = new SDUse[NumOps];
3617 OperandsNeedDelete = true;
3620 // Assign the new operands.
3621 NumOperands = NumOps;
3623 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3624 OperandList[i] = Ops[i];
3625 OperandList[i].setUser(this);
3626 SDNode *N = OperandList[i].getVal();
3627 N->addUser(i, this);
3632 /// SelectNodeTo - These are used for target selectors to *mutate* the
3633 /// specified node to have the specified return type, Target opcode, and
3634 /// operands. Note that target opcodes are stored as
3635 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3637 /// Note that SelectNodeTo returns the resultant node. If there is already a
3638 /// node of the specified opcode and operands, it returns that node instead of
3639 /// the current one.
3640 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3642 SDVTList VTs = getVTList(VT);
3643 FoldingSetNodeID ID;
3644 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, (SDOperand*)0, 0);
3646 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3649 RemoveNodeFromCSEMaps(N);
3651 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, SDOperandPtr(), 0);
3653 CSEMap.InsertNode(N, IP);
3657 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3658 MVT VT, SDOperand Op1) {
3659 // If an identical node already exists, use it.
3660 SDVTList VTs = getVTList(VT);
3661 SDOperand Ops[] = { Op1 };
3663 FoldingSetNodeID ID;
3664 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3666 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3669 RemoveNodeFromCSEMaps(N);
3670 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3671 CSEMap.InsertNode(N, IP);
3675 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3676 MVT VT, SDOperand Op1,
3678 // If an identical node already exists, use it.
3679 SDVTList VTs = getVTList(VT);
3680 SDOperand Ops[] = { Op1, Op2 };
3682 FoldingSetNodeID ID;
3683 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3685 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3688 RemoveNodeFromCSEMaps(N);
3690 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3692 CSEMap.InsertNode(N, IP); // Memoize the new node.
3696 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3697 MVT VT, SDOperand Op1,
3698 SDOperand Op2, SDOperand Op3) {
3699 // If an identical node already exists, use it.
3700 SDVTList VTs = getVTList(VT);
3701 SDOperand Ops[] = { Op1, Op2, Op3 };
3702 FoldingSetNodeID ID;
3703 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3705 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3708 RemoveNodeFromCSEMaps(N);
3710 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3712 CSEMap.InsertNode(N, IP); // Memoize the new node.
3716 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3717 MVT VT, SDOperandPtr Ops,
3719 // If an identical node already exists, use it.
3720 SDVTList VTs = getVTList(VT);
3721 FoldingSetNodeID ID;
3722 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3724 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3727 RemoveNodeFromCSEMaps(N);
3728 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3730 CSEMap.InsertNode(N, IP); // Memoize the new node.
3734 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3736 SDOperand Op1, SDOperand Op2) {
3737 SDVTList VTs = getVTList(VT1, VT2);
3738 FoldingSetNodeID ID;
3739 SDOperand Ops[] = { Op1, Op2 };
3740 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3742 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3745 RemoveNodeFromCSEMaps(N);
3746 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3747 CSEMap.InsertNode(N, IP); // Memoize the new node.
3751 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3753 SDOperand Op1, SDOperand Op2,
3755 // If an identical node already exists, use it.
3756 SDVTList VTs = getVTList(VT1, VT2);
3757 SDOperand Ops[] = { Op1, Op2, Op3 };
3758 FoldingSetNodeID ID;
3759 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3761 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3764 RemoveNodeFromCSEMaps(N);
3766 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3767 CSEMap.InsertNode(N, IP); // Memoize the new node.
3772 /// getTargetNode - These are used for target selectors to create a new node
3773 /// with specified return type(s), target opcode, and operands.
3775 /// Note that getTargetNode returns the resultant node. If there is already a
3776 /// node of the specified opcode and operands, it returns that node instead of
3777 /// the current one.
3778 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3779 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3781 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3782 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3784 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3785 SDOperand Op1, SDOperand Op2) {
3786 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3788 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3789 SDOperand Op1, SDOperand Op2,
3791 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3793 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3794 SDOperandPtr Ops, unsigned NumOps) {
3795 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3797 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3798 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3800 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3802 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3803 MVT VT2, SDOperand Op1) {
3804 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3805 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3807 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3808 MVT VT2, SDOperand Op1,
3810 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3811 SDOperand Ops[] = { Op1, Op2 };
3812 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3814 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3815 MVT VT2, SDOperand Op1,
3816 SDOperand Op2, SDOperand Op3) {
3817 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3818 SDOperand Ops[] = { Op1, Op2, Op3 };
3819 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3821 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3822 SDOperandPtr Ops, unsigned NumOps) {
3823 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3824 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3826 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3827 SDOperand Op1, SDOperand Op2) {
3828 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3829 SDOperand Ops[] = { Op1, Op2 };
3830 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3832 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3833 SDOperand Op1, SDOperand Op2,
3835 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3836 SDOperand Ops[] = { Op1, Op2, Op3 };
3837 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3839 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3840 SDOperandPtr Ops, unsigned NumOps) {
3841 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3842 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3844 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3845 MVT VT2, MVT VT3, MVT VT4,
3846 SDOperandPtr Ops, unsigned NumOps) {
3847 std::vector<MVT> VTList;
3848 VTList.push_back(VT1);
3849 VTList.push_back(VT2);
3850 VTList.push_back(VT3);
3851 VTList.push_back(VT4);
3852 const MVT *VTs = getNodeValueTypes(VTList);
3853 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3855 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3856 std::vector<MVT> &ResultTys,
3857 SDOperandPtr Ops, unsigned NumOps) {
3858 const MVT *VTs = getNodeValueTypes(ResultTys);
3859 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3863 /// getNodeIfExists - Get the specified node if it's already available, or
3864 /// else return NULL.
3865 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3866 SDOperandPtr Ops, unsigned NumOps) {
3867 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3868 FoldingSetNodeID ID;
3869 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3871 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3878 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3879 /// This can cause recursive merging of nodes in the DAG.
3881 /// This version assumes From has a single result value.
3883 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3884 DAGUpdateListener *UpdateListener) {
3885 SDNode *From = FromN.Val;
3886 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3887 "Cannot replace with this method!");
3888 assert(From != To.Val && "Cannot replace uses of with self");
3890 while (!From->use_empty()) {
3891 SDNode::use_iterator UI = From->use_begin();
3892 SDNode *U = UI->getUser();
3894 // This node is about to morph, remove its old self from the CSE maps.
3895 RemoveNodeFromCSEMaps(U);
3897 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3898 I != E; ++I, ++operandNum)
3899 if (I->getVal() == From) {
3900 From->removeUser(operandNum, U);
3903 To.Val->addUser(operandNum, U);
3906 // Now that we have modified U, add it back to the CSE maps. If it already
3907 // exists there, recursively merge the results together.
3908 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3909 ReplaceAllUsesWith(U, Existing, UpdateListener);
3910 // U is now dead. Inform the listener if it exists and delete it.
3912 UpdateListener->NodeDeleted(U, Existing);
3913 DeleteNodeNotInCSEMaps(U);
3915 // If the node doesn't already exist, we updated it. Inform a listener if
3918 UpdateListener->NodeUpdated(U);
3923 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3924 /// This can cause recursive merging of nodes in the DAG.
3926 /// This version assumes From/To have matching types and numbers of result
3929 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3930 DAGUpdateListener *UpdateListener) {
3931 assert(From != To && "Cannot replace uses of with self");
3932 assert(From->getNumValues() == To->getNumValues() &&
3933 "Cannot use this version of ReplaceAllUsesWith!");
3934 if (From->getNumValues() == 1) // If possible, use the faster version.
3935 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3938 while (!From->use_empty()) {
3939 SDNode::use_iterator UI = From->use_begin();
3940 SDNode *U = UI->getUser();
3942 // This node is about to morph, remove its old self from the CSE maps.
3943 RemoveNodeFromCSEMaps(U);
3945 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3946 I != E; ++I, ++operandNum)
3947 if (I->getVal() == From) {
3948 From->removeUser(operandNum, U);
3950 To->addUser(operandNum, U);
3953 // Now that we have modified U, add it back to the CSE maps. If it already
3954 // exists there, recursively merge the results together.
3955 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3956 ReplaceAllUsesWith(U, Existing, UpdateListener);
3957 // U is now dead. Inform the listener if it exists and delete it.
3959 UpdateListener->NodeDeleted(U, Existing);
3960 DeleteNodeNotInCSEMaps(U);
3962 // If the node doesn't already exist, we updated it. Inform a listener if
3965 UpdateListener->NodeUpdated(U);
3970 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3971 /// This can cause recursive merging of nodes in the DAG.
3973 /// This version can replace From with any result values. To must match the
3974 /// number and types of values returned by From.
3975 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3977 DAGUpdateListener *UpdateListener) {
3978 if (From->getNumValues() == 1) // Handle the simple case efficiently.
3979 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
3981 while (!From->use_empty()) {
3982 SDNode::use_iterator UI = From->use_begin();
3983 SDNode *U = UI->getUser();
3985 // This node is about to morph, remove its old self from the CSE maps.
3986 RemoveNodeFromCSEMaps(U);
3988 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3989 I != E; ++I, ++operandNum)
3990 if (I->getVal() == From) {
3991 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
3992 From->removeUser(operandNum, U);
3995 ToOp.Val->addUser(operandNum, U);
3998 // Now that we have modified U, add it back to the CSE maps. If it already
3999 // exists there, recursively merge the results together.
4000 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4001 ReplaceAllUsesWith(U, Existing, UpdateListener);
4002 // U is now dead. Inform the listener if it exists and delete it.
4004 UpdateListener->NodeDeleted(U, Existing);
4005 DeleteNodeNotInCSEMaps(U);
4007 // If the node doesn't already exist, we updated it. Inform a listener if
4010 UpdateListener->NodeUpdated(U);
4016 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4017 /// any deleted nodes from the set passed into its constructor and recursively
4018 /// notifies another update listener if specified.
4019 class ChainedSetUpdaterListener :
4020 public SelectionDAG::DAGUpdateListener {
4021 SmallSetVector<SDNode*, 16> &Set;
4022 SelectionDAG::DAGUpdateListener *Chain;
4024 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4025 SelectionDAG::DAGUpdateListener *chain)
4026 : Set(set), Chain(chain) {}
4028 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4030 if (Chain) Chain->NodeDeleted(N, E);
4032 virtual void NodeUpdated(SDNode *N) {
4033 if (Chain) Chain->NodeUpdated(N);
4038 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4039 /// uses of other values produced by From.Val alone. The Deleted vector is
4040 /// handled the same way as for ReplaceAllUsesWith.
4041 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4042 DAGUpdateListener *UpdateListener){
4043 assert(From != To && "Cannot replace a value with itself");
4045 // Handle the simple, trivial, case efficiently.
4046 if (From.Val->getNumValues() == 1) {
4047 ReplaceAllUsesWith(From, To, UpdateListener);
4051 if (From.use_empty()) return;
4053 // Get all of the users of From.Val. We want these in a nice,
4054 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4055 SmallSetVector<SDNode*, 16> Users;
4056 for (SDNode::use_iterator UI = From.Val->use_begin(),
4057 E = From.Val->use_end(); UI != E; ++UI) {
4058 SDNode *User = UI->getUser();
4059 if (!Users.count(User))
4063 // When one of the recursive merges deletes nodes from the graph, we need to
4064 // make sure that UpdateListener is notified *and* that the node is removed
4065 // from Users if present. CSUL does this.
4066 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4068 while (!Users.empty()) {
4069 // We know that this user uses some value of From. If it is the right
4070 // value, update it.
4071 SDNode *User = Users.back();
4074 // Scan for an operand that matches From.
4075 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4076 for (; Op != E; ++Op)
4077 if (*Op == From) break;
4079 // If there are no matches, the user must use some other result of From.
4080 if (Op == E) continue;
4082 // Okay, we know this user needs to be updated. Remove its old self
4083 // from the CSE maps.
4084 RemoveNodeFromCSEMaps(User);
4086 // Update all operands that match "From" in case there are multiple uses.
4087 for (; Op != E; ++Op) {
4089 From.Val->removeUser(Op-User->op_begin(), User);
4092 To.Val->addUser(Op-User->op_begin(), User);
4096 // Now that we have modified User, add it back to the CSE maps. If it
4097 // already exists there, recursively merge the results together.
4098 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4100 if (UpdateListener) UpdateListener->NodeUpdated(User);
4101 continue; // Continue on to next user.
4104 // If there was already an existing matching node, use ReplaceAllUsesWith
4105 // to replace the dead one with the existing one. This can cause
4106 // recursive merging of other unrelated nodes down the line. The merging
4107 // can cause deletion of nodes that used the old value. To handle this, we
4108 // use CSUL to remove them from the Users set.
4109 ReplaceAllUsesWith(User, Existing, &CSUL);
4111 // User is now dead. Notify a listener if present.
4112 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4113 DeleteNodeNotInCSEMaps(User);
4117 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4118 /// their allnodes order. It returns the maximum id.
4119 unsigned SelectionDAG::AssignNodeIds() {
4121 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4128 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4129 /// based on their topological order. It returns the maximum id and a vector
4130 /// of the SDNodes* in assigned order by reference.
4131 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4132 unsigned DAGSize = AllNodes.size();
4133 std::vector<unsigned> InDegree(DAGSize);
4134 std::vector<SDNode*> Sources;
4136 // Use a two pass approach to avoid using a std::map which is slow.
4138 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4141 unsigned Degree = N->use_size();
4142 InDegree[N->getNodeId()] = Degree;
4144 Sources.push_back(N);
4148 while (!Sources.empty()) {
4149 SDNode *N = Sources.back();
4151 TopOrder.push_back(N);
4152 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4153 SDNode *P = I->getVal();
4154 unsigned Degree = --InDegree[P->getNodeId()];
4156 Sources.push_back(P);
4160 // Second pass, assign the actual topological order as node ids.
4162 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4164 (*TI)->setNodeId(Id++);
4171 //===----------------------------------------------------------------------===//
4173 //===----------------------------------------------------------------------===//
4175 // Out-of-line virtual method to give class a home.
4176 void SDNode::ANCHOR() {}
4177 void UnarySDNode::ANCHOR() {}
4178 void BinarySDNode::ANCHOR() {}
4179 void TernarySDNode::ANCHOR() {}
4180 void HandleSDNode::ANCHOR() {}
4181 void StringSDNode::ANCHOR() {}
4182 void ConstantSDNode::ANCHOR() {}
4183 void ConstantFPSDNode::ANCHOR() {}
4184 void GlobalAddressSDNode::ANCHOR() {}
4185 void FrameIndexSDNode::ANCHOR() {}
4186 void JumpTableSDNode::ANCHOR() {}
4187 void ConstantPoolSDNode::ANCHOR() {}
4188 void BasicBlockSDNode::ANCHOR() {}
4189 void SrcValueSDNode::ANCHOR() {}
4190 void MemOperandSDNode::ANCHOR() {}
4191 void RegisterSDNode::ANCHOR() {}
4192 void ExternalSymbolSDNode::ANCHOR() {}
4193 void CondCodeSDNode::ANCHOR() {}
4194 void ARG_FLAGSSDNode::ANCHOR() {}
4195 void VTSDNode::ANCHOR() {}
4196 void MemSDNode::ANCHOR() {}
4197 void LoadSDNode::ANCHOR() {}
4198 void StoreSDNode::ANCHOR() {}
4199 void AtomicSDNode::ANCHOR() {}
4201 HandleSDNode::~HandleSDNode() {
4202 SDVTList VTs = { 0, 0 };
4203 MorphNodeTo(ISD::HANDLENODE, VTs, SDOperandPtr(), 0); // Drops operand uses.
4206 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4208 : SDNode(isa<GlobalVariable>(GA) &&
4209 cast<GlobalVariable>(GA)->isThreadLocal() ?
4211 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4213 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4214 getSDVTList(VT)), Offset(o) {
4215 TheGlobal = const_cast<GlobalValue*>(GA);
4218 /// getMemOperand - Return a MachineMemOperand object describing the memory
4219 /// reference performed by this atomic.
4220 MachineMemOperand AtomicSDNode::getMemOperand() const {
4221 int Size = (getValueType(0).getSizeInBits() + 7) >> 3;
4222 int Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4223 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4225 // Check if the atomic references a frame index
4226 const FrameIndexSDNode *FI =
4227 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4228 if (!getSrcValue() && FI)
4229 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4230 FI->getIndex(), Size, getAlignment());
4232 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4233 Size, getAlignment());
4236 /// getMemOperand - Return a MachineMemOperand object describing the memory
4237 /// reference performed by this load or store.
4238 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4239 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4241 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4242 MachineMemOperand::MOStore;
4243 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4245 // Check if the load references a frame index, and does not have
4247 const FrameIndexSDNode *FI =
4248 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4249 if (!getSrcValue() && FI)
4250 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4251 FI->getIndex(), Size, getAlignment());
4253 return MachineMemOperand(getSrcValue(), Flags,
4254 getSrcValueOffset(), Size, getAlignment());
4257 /// Profile - Gather unique data for the node.
4259 void SDNode::Profile(FoldingSetNodeID &ID) {
4260 AddNodeIDNode(ID, this);
4263 /// getValueTypeList - Return a pointer to the specified value type.
4265 const MVT *SDNode::getValueTypeList(MVT VT) {
4266 if (VT.isExtended()) {
4267 static std::set<MVT, MVT::compareRawBits> EVTs;
4268 return &(*EVTs.insert(VT).first);
4270 static MVT VTs[MVT::LAST_VALUETYPE];
4271 VTs[VT.getSimpleVT()] = VT;
4272 return &VTs[VT.getSimpleVT()];
4276 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4277 /// indicated value. This method ignores uses of other values defined by this
4279 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4280 assert(Value < getNumValues() && "Bad value!");
4282 // If there is only one value, this is easy.
4283 if (getNumValues() == 1)
4284 return use_size() == NUses;
4285 if (use_size() < NUses) return false;
4287 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4289 SmallPtrSet<SDNode*, 32> UsersHandled;
4291 // TODO: Only iterate over uses of a given value of the node
4292 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4293 if (*UI == TheValue) {
4300 // Found exactly the right number of uses?
4305 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4306 /// value. This method ignores uses of other values defined by this operation.
4307 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4308 assert(Value < getNumValues() && "Bad value!");
4310 if (use_empty()) return false;
4312 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4314 SmallPtrSet<SDNode*, 32> UsersHandled;
4316 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4317 SDNode *User = UI->getUser();
4318 if (User->getNumOperands() == 1 ||
4319 UsersHandled.insert(User)) // First time we've seen this?
4320 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4321 if (User->getOperand(i) == TheValue) {
4330 /// isOnlyUseOf - Return true if this node is the only use of N.
4332 bool SDNode::isOnlyUseOf(SDNode *N) const {
4334 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4335 SDNode *User = I->getUser();
4345 /// isOperand - Return true if this node is an operand of N.
4347 bool SDOperand::isOperandOf(SDNode *N) const {
4348 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4349 if (*this == N->getOperand(i))
4354 bool SDNode::isOperandOf(SDNode *N) const {
4355 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4356 if (this == N->OperandList[i].getVal())
4361 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4362 /// be a chain) reaches the specified operand without crossing any
4363 /// side-effecting instructions. In practice, this looks through token
4364 /// factors and non-volatile loads. In order to remain efficient, this only
4365 /// looks a couple of nodes in, it does not do an exhaustive search.
4366 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4367 unsigned Depth) const {
4368 if (*this == Dest) return true;
4370 // Don't search too deeply, we just want to be able to see through
4371 // TokenFactor's etc.
4372 if (Depth == 0) return false;
4374 // If this is a token factor, all inputs to the TF happen in parallel. If any
4375 // of the operands of the TF reach dest, then we can do the xform.
4376 if (getOpcode() == ISD::TokenFactor) {
4377 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4378 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4383 // Loads don't have side effects, look through them.
4384 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4385 if (!Ld->isVolatile())
4386 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4392 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4393 SmallPtrSet<SDNode *, 32> &Visited) {
4394 if (found || !Visited.insert(N))
4397 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4398 SDNode *Op = N->getOperand(i).Val;
4403 findPredecessor(Op, P, found, Visited);
4407 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4408 /// is either an operand of N or it can be reached by recursively traversing
4409 /// up the operands.
4410 /// NOTE: this is an expensive method. Use it carefully.
4411 bool SDNode::isPredecessorOf(SDNode *N) const {
4412 SmallPtrSet<SDNode *, 32> Visited;
4414 findPredecessor(N, this, found, Visited);
4418 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4419 assert(Num < NumOperands && "Invalid child # of SDNode!");
4420 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4423 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4424 switch (getOpcode()) {
4426 if (getOpcode() < ISD::BUILTIN_OP_END)
4427 return "<<Unknown DAG Node>>";
4430 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4431 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4432 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4434 TargetLowering &TLI = G->getTargetLoweringInfo();
4436 TLI.getTargetNodeName(getOpcode());
4437 if (Name) return Name;
4440 return "<<Unknown Target Node>>";
4443 case ISD::PREFETCH: return "Prefetch";
4444 case ISD::MEMBARRIER: return "MemBarrier";
4445 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4446 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4447 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4448 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4449 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4450 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4451 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4452 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4453 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4454 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4455 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4456 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4457 case ISD::PCMARKER: return "PCMarker";
4458 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4459 case ISD::SRCVALUE: return "SrcValue";
4460 case ISD::MEMOPERAND: return "MemOperand";
4461 case ISD::EntryToken: return "EntryToken";
4462 case ISD::TokenFactor: return "TokenFactor";
4463 case ISD::AssertSext: return "AssertSext";
4464 case ISD::AssertZext: return "AssertZext";
4466 case ISD::STRING: return "String";
4467 case ISD::BasicBlock: return "BasicBlock";
4468 case ISD::ARG_FLAGS: return "ArgFlags";
4469 case ISD::VALUETYPE: return "ValueType";
4470 case ISD::Register: return "Register";
4472 case ISD::Constant: return "Constant";
4473 case ISD::ConstantFP: return "ConstantFP";
4474 case ISD::GlobalAddress: return "GlobalAddress";
4475 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4476 case ISD::FrameIndex: return "FrameIndex";
4477 case ISD::JumpTable: return "JumpTable";
4478 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4479 case ISD::RETURNADDR: return "RETURNADDR";
4480 case ISD::FRAMEADDR: return "FRAMEADDR";
4481 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4482 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4483 case ISD::EHSELECTION: return "EHSELECTION";
4484 case ISD::EH_RETURN: return "EH_RETURN";
4485 case ISD::ConstantPool: return "ConstantPool";
4486 case ISD::ExternalSymbol: return "ExternalSymbol";
4487 case ISD::INTRINSIC_WO_CHAIN: {
4488 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4489 return Intrinsic::getName((Intrinsic::ID)IID);
4491 case ISD::INTRINSIC_VOID:
4492 case ISD::INTRINSIC_W_CHAIN: {
4493 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4494 return Intrinsic::getName((Intrinsic::ID)IID);
4497 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4498 case ISD::TargetConstant: return "TargetConstant";
4499 case ISD::TargetConstantFP:return "TargetConstantFP";
4500 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4501 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4502 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4503 case ISD::TargetJumpTable: return "TargetJumpTable";
4504 case ISD::TargetConstantPool: return "TargetConstantPool";
4505 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4507 case ISD::CopyToReg: return "CopyToReg";
4508 case ISD::CopyFromReg: return "CopyFromReg";
4509 case ISD::UNDEF: return "undef";
4510 case ISD::MERGE_VALUES: return "merge_values";
4511 case ISD::INLINEASM: return "inlineasm";
4512 case ISD::LABEL: return "label";
4513 case ISD::DECLARE: return "declare";
4514 case ISD::HANDLENODE: return "handlenode";
4515 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4516 case ISD::CALL: return "call";
4519 case ISD::FABS: return "fabs";
4520 case ISD::FNEG: return "fneg";
4521 case ISD::FSQRT: return "fsqrt";
4522 case ISD::FSIN: return "fsin";
4523 case ISD::FCOS: return "fcos";
4524 case ISD::FPOWI: return "fpowi";
4525 case ISD::FPOW: return "fpow";
4528 case ISD::ADD: return "add";
4529 case ISD::SUB: return "sub";
4530 case ISD::MUL: return "mul";
4531 case ISD::MULHU: return "mulhu";
4532 case ISD::MULHS: return "mulhs";
4533 case ISD::SDIV: return "sdiv";
4534 case ISD::UDIV: return "udiv";
4535 case ISD::SREM: return "srem";
4536 case ISD::UREM: return "urem";
4537 case ISD::SMUL_LOHI: return "smul_lohi";
4538 case ISD::UMUL_LOHI: return "umul_lohi";
4539 case ISD::SDIVREM: return "sdivrem";
4540 case ISD::UDIVREM: return "divrem";
4541 case ISD::AND: return "and";
4542 case ISD::OR: return "or";
4543 case ISD::XOR: return "xor";
4544 case ISD::SHL: return "shl";
4545 case ISD::SRA: return "sra";
4546 case ISD::SRL: return "srl";
4547 case ISD::ROTL: return "rotl";
4548 case ISD::ROTR: return "rotr";
4549 case ISD::FADD: return "fadd";
4550 case ISD::FSUB: return "fsub";
4551 case ISD::FMUL: return "fmul";
4552 case ISD::FDIV: return "fdiv";
4553 case ISD::FREM: return "frem";
4554 case ISD::FCOPYSIGN: return "fcopysign";
4555 case ISD::FGETSIGN: return "fgetsign";
4557 case ISD::SETCC: return "setcc";
4558 case ISD::VSETCC: return "vsetcc";
4559 case ISD::SELECT: return "select";
4560 case ISD::SELECT_CC: return "select_cc";
4561 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4562 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4563 case ISD::CONCAT_VECTORS: return "concat_vectors";
4564 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4565 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4566 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4567 case ISD::CARRY_FALSE: return "carry_false";
4568 case ISD::ADDC: return "addc";
4569 case ISD::ADDE: return "adde";
4570 case ISD::SUBC: return "subc";
4571 case ISD::SUBE: return "sube";
4572 case ISD::SHL_PARTS: return "shl_parts";
4573 case ISD::SRA_PARTS: return "sra_parts";
4574 case ISD::SRL_PARTS: return "srl_parts";
4576 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4577 case ISD::INSERT_SUBREG: return "insert_subreg";
4579 // Conversion operators.
4580 case ISD::SIGN_EXTEND: return "sign_extend";
4581 case ISD::ZERO_EXTEND: return "zero_extend";
4582 case ISD::ANY_EXTEND: return "any_extend";
4583 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4584 case ISD::TRUNCATE: return "truncate";
4585 case ISD::FP_ROUND: return "fp_round";
4586 case ISD::FLT_ROUNDS_: return "flt_rounds";
4587 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4588 case ISD::FP_EXTEND: return "fp_extend";
4590 case ISD::SINT_TO_FP: return "sint_to_fp";
4591 case ISD::UINT_TO_FP: return "uint_to_fp";
4592 case ISD::FP_TO_SINT: return "fp_to_sint";
4593 case ISD::FP_TO_UINT: return "fp_to_uint";
4594 case ISD::BIT_CONVERT: return "bit_convert";
4596 // Control flow instructions
4597 case ISD::BR: return "br";
4598 case ISD::BRIND: return "brind";
4599 case ISD::BR_JT: return "br_jt";
4600 case ISD::BRCOND: return "brcond";
4601 case ISD::BR_CC: return "br_cc";
4602 case ISD::RET: return "ret";
4603 case ISD::CALLSEQ_START: return "callseq_start";
4604 case ISD::CALLSEQ_END: return "callseq_end";
4607 case ISD::LOAD: return "load";
4608 case ISD::STORE: return "store";
4609 case ISD::VAARG: return "vaarg";
4610 case ISD::VACOPY: return "vacopy";
4611 case ISD::VAEND: return "vaend";
4612 case ISD::VASTART: return "vastart";
4613 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4614 case ISD::EXTRACT_ELEMENT: return "extract_element";
4615 case ISD::BUILD_PAIR: return "build_pair";
4616 case ISD::STACKSAVE: return "stacksave";
4617 case ISD::STACKRESTORE: return "stackrestore";
4618 case ISD::TRAP: return "trap";
4621 case ISD::BSWAP: return "bswap";
4622 case ISD::CTPOP: return "ctpop";
4623 case ISD::CTTZ: return "cttz";
4624 case ISD::CTLZ: return "ctlz";
4627 case ISD::LOCATION: return "location";
4628 case ISD::DEBUG_LOC: return "debug_loc";
4631 case ISD::TRAMPOLINE: return "trampoline";
4634 switch (cast<CondCodeSDNode>(this)->get()) {
4635 default: assert(0 && "Unknown setcc condition!");
4636 case ISD::SETOEQ: return "setoeq";
4637 case ISD::SETOGT: return "setogt";
4638 case ISD::SETOGE: return "setoge";
4639 case ISD::SETOLT: return "setolt";
4640 case ISD::SETOLE: return "setole";
4641 case ISD::SETONE: return "setone";
4643 case ISD::SETO: return "seto";
4644 case ISD::SETUO: return "setuo";
4645 case ISD::SETUEQ: return "setue";
4646 case ISD::SETUGT: return "setugt";
4647 case ISD::SETUGE: return "setuge";
4648 case ISD::SETULT: return "setult";
4649 case ISD::SETULE: return "setule";
4650 case ISD::SETUNE: return "setune";
4652 case ISD::SETEQ: return "seteq";
4653 case ISD::SETGT: return "setgt";
4654 case ISD::SETGE: return "setge";
4655 case ISD::SETLT: return "setlt";
4656 case ISD::SETLE: return "setle";
4657 case ISD::SETNE: return "setne";
4662 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4671 return "<post-inc>";
4673 return "<post-dec>";
4677 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4678 std::string S = "< ";
4692 if (getByValAlign())
4693 S += "byval-align:" + utostr(getByValAlign()) + " ";
4695 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4697 S += "byval-size:" + utostr(getByValSize()) + " ";
4701 void SDNode::dump() const { dump(0); }
4702 void SDNode::dump(const SelectionDAG *G) const {
4703 cerr << (void*)this << ": ";
4705 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4707 if (getValueType(i) == MVT::Other)
4710 cerr << getValueType(i).getMVTString();
4712 cerr << " = " << getOperationName(G);
4715 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4716 if (i) cerr << ", ";
4717 cerr << (void*)getOperand(i).Val;
4718 if (unsigned RN = getOperand(i).ResNo)
4722 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4723 SDNode *Mask = getOperand(2).Val;
4725 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4727 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4730 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4735 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4736 cerr << "<" << CSDN->getValue() << ">";
4737 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4738 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4739 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4740 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4741 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4743 cerr << "<APFloat(";
4744 CSDN->getValueAPF().convertToAPInt().dump();
4747 } else if (const GlobalAddressSDNode *GADN =
4748 dyn_cast<GlobalAddressSDNode>(this)) {
4749 int offset = GADN->getOffset();
4751 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4753 cerr << " + " << offset;
4755 cerr << " " << offset;
4756 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4757 cerr << "<" << FIDN->getIndex() << ">";
4758 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4759 cerr << "<" << JTDN->getIndex() << ">";
4760 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4761 int offset = CP->getOffset();
4762 if (CP->isMachineConstantPoolEntry())
4763 cerr << "<" << *CP->getMachineCPVal() << ">";
4765 cerr << "<" << *CP->getConstVal() << ">";
4767 cerr << " + " << offset;
4769 cerr << " " << offset;
4770 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4772 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4774 cerr << LBB->getName() << " ";
4775 cerr << (const void*)BBDN->getBasicBlock() << ">";
4776 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4777 if (G && R->getReg() &&
4778 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4779 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4781 cerr << " #" << R->getReg();
4783 } else if (const ExternalSymbolSDNode *ES =
4784 dyn_cast<ExternalSymbolSDNode>(this)) {
4785 cerr << "'" << ES->getSymbol() << "'";
4786 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4788 cerr << "<" << M->getValue() << ">";
4791 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4792 if (M->MO.getValue())
4793 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4795 cerr << "<null:" << M->MO.getOffset() << ">";
4796 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4797 cerr << N->getArgFlags().getArgFlagsString();
4798 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4799 cerr << ":" << N->getVT().getMVTString();
4801 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4802 const Value *SrcValue = LD->getSrcValue();
4803 int SrcOffset = LD->getSrcValueOffset();
4809 cerr << ":" << SrcOffset << ">";
4812 switch (LD->getExtensionType()) {
4813 default: doExt = false; break;
4815 cerr << " <anyext ";
4825 cerr << LD->getMemoryVT().getMVTString() << ">";
4827 const char *AM = getIndexedModeName(LD->getAddressingMode());
4830 if (LD->isVolatile())
4831 cerr << " <volatile>";
4832 cerr << " alignment=" << LD->getAlignment();
4833 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4834 const Value *SrcValue = ST->getSrcValue();
4835 int SrcOffset = ST->getSrcValueOffset();
4841 cerr << ":" << SrcOffset << ">";
4843 if (ST->isTruncatingStore())
4845 << ST->getMemoryVT().getMVTString() << ">";
4847 const char *AM = getIndexedModeName(ST->getAddressingMode());
4850 if (ST->isVolatile())
4851 cerr << " <volatile>";
4852 cerr << " alignment=" << ST->getAlignment();
4853 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4854 const Value *SrcValue = AT->getSrcValue();
4855 int SrcOffset = AT->getSrcValueOffset();
4861 cerr << ":" << SrcOffset << ">";
4862 if (AT->isVolatile())
4863 cerr << " <volatile>";
4864 cerr << " alignment=" << AT->getAlignment();
4868 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4869 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4870 if (N->getOperand(i).Val->hasOneUse())
4871 DumpNodes(N->getOperand(i).Val, indent+2, G);
4873 cerr << "\n" << std::string(indent+2, ' ')
4874 << (void*)N->getOperand(i).Val << ": <multiple use>";
4877 cerr << "\n" << std::string(indent, ' ');
4881 void SelectionDAG::dump() const {
4882 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4883 std::vector<const SDNode*> Nodes;
4884 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4888 std::sort(Nodes.begin(), Nodes.end());
4890 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4891 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4892 DumpNodes(Nodes[i], 2, this);
4895 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4900 const Type *ConstantPoolSDNode::getType() const {
4901 if (isMachineConstantPoolEntry())
4902 return Val.MachineCPVal->getType();
4903 return Val.ConstVal->getType();