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/GlobalAlias.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/ADT/SetVector.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/StringExtras.h"
41 /// makeVTList - Return an instance of the SDVTList struct initialized with the
42 /// specified members.
43 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
44 SDVTList Res = {VTs, NumVTs};
48 static const fltSemantics *MVTToAPFloatSemantics(MVT::ValueType VT) {
50 default: assert(0 && "Unknown FP format");
51 case MVT::f32: return &APFloat::IEEEsingle;
52 case MVT::f64: return &APFloat::IEEEdouble;
53 case MVT::f80: return &APFloat::x87DoubleExtended;
54 case MVT::f128: return &APFloat::IEEEquad;
55 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
59 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
61 //===----------------------------------------------------------------------===//
62 // ConstantFPSDNode Class
63 //===----------------------------------------------------------------------===//
65 /// isExactlyValue - We don't rely on operator== working on double values, as
66 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
67 /// As such, this method can be used to do an exact bit-for-bit comparison of
68 /// two floating point values.
69 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
70 return Value.bitwiseIsEqual(V);
73 bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT,
75 assert(MVT::isFloatingPoint(VT) && "Can only convert between FP types");
77 // PPC long double cannot be converted to any other type.
78 if (VT == MVT::ppcf128 ||
79 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
82 // convert modifies in place, so make a copy.
83 APFloat Val2 = APFloat(Val);
84 return Val2.convert(*MVTToAPFloatSemantics(VT),
85 APFloat::rmNearestTiesToEven) == APFloat::opOK;
88 //===----------------------------------------------------------------------===//
90 //===----------------------------------------------------------------------===//
92 /// isBuildVectorAllOnes - Return true if the specified node is a
93 /// BUILD_VECTOR where all of the elements are ~0 or undef.
94 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
95 // Look through a bit convert.
96 if (N->getOpcode() == ISD::BIT_CONVERT)
97 N = N->getOperand(0).Val;
99 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
101 unsigned i = 0, e = N->getNumOperands();
103 // Skip over all of the undef values.
104 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
107 // Do not accept an all-undef vector.
108 if (i == e) return false;
110 // Do not accept build_vectors that aren't all constants or which have non-~0
112 SDOperand NotZero = N->getOperand(i);
113 if (isa<ConstantSDNode>(NotZero)) {
114 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
116 } else if (isa<ConstantFPSDNode>(NotZero)) {
117 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
118 convertToAPInt().isAllOnesValue())
123 // Okay, we have at least one ~0 value, check to see if the rest match or are
125 for (++i; i != e; ++i)
126 if (N->getOperand(i) != NotZero &&
127 N->getOperand(i).getOpcode() != ISD::UNDEF)
133 /// isBuildVectorAllZeros - Return true if the specified node is a
134 /// BUILD_VECTOR where all of the elements are 0 or undef.
135 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
136 // Look through a bit convert.
137 if (N->getOpcode() == ISD::BIT_CONVERT)
138 N = N->getOperand(0).Val;
140 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
142 unsigned i = 0, e = N->getNumOperands();
144 // Skip over all of the undef values.
145 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
148 // Do not accept an all-undef vector.
149 if (i == e) return false;
151 // Do not accept build_vectors that aren't all constants or which have non-~0
153 SDOperand Zero = N->getOperand(i);
154 if (isa<ConstantSDNode>(Zero)) {
155 if (!cast<ConstantSDNode>(Zero)->isNullValue())
157 } else if (isa<ConstantFPSDNode>(Zero)) {
158 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
163 // Okay, we have at least one ~0 value, check to see if the rest match or are
165 for (++i; i != e; ++i)
166 if (N->getOperand(i) != Zero &&
167 N->getOperand(i).getOpcode() != ISD::UNDEF)
172 /// isScalarToVector - Return true if the specified node is a
173 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
174 /// element is not an undef.
175 bool ISD::isScalarToVector(const SDNode *N) {
176 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
179 if (N->getOpcode() != ISD::BUILD_VECTOR)
181 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
183 unsigned NumElems = N->getNumOperands();
184 for (unsigned i = 1; i < NumElems; ++i) {
185 SDOperand V = N->getOperand(i);
186 if (V.getOpcode() != ISD::UNDEF)
193 /// isDebugLabel - Return true if the specified node represents a debug
194 /// label (i.e. ISD::LABEL or TargetInstrInfo::LABEL node and third operand
196 bool ISD::isDebugLabel(const SDNode *N) {
198 if (N->getOpcode() == ISD::LABEL)
199 Zero = N->getOperand(2);
200 else if (N->isTargetOpcode() &&
201 N->getTargetOpcode() == TargetInstrInfo::LABEL)
202 // Chain moved to last operand.
203 Zero = N->getOperand(1);
206 return isa<ConstantSDNode>(Zero) && cast<ConstantSDNode>(Zero)->isNullValue();
209 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
210 /// when given the operation for (X op Y).
211 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
212 // To perform this operation, we just need to swap the L and G bits of the
214 unsigned OldL = (Operation >> 2) & 1;
215 unsigned OldG = (Operation >> 1) & 1;
216 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
217 (OldL << 1) | // New G bit
218 (OldG << 2)); // New L bit.
221 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
222 /// 'op' is a valid SetCC operation.
223 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
224 unsigned Operation = Op;
226 Operation ^= 7; // Flip L, G, E bits, but not U.
228 Operation ^= 15; // Flip all of the condition bits.
229 if (Operation > ISD::SETTRUE2)
230 Operation &= ~8; // Don't let N and U bits get set.
231 return ISD::CondCode(Operation);
235 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
236 /// signed operation and 2 if the result is an unsigned comparison. Return zero
237 /// if the operation does not depend on the sign of the input (setne and seteq).
238 static int isSignedOp(ISD::CondCode Opcode) {
240 default: assert(0 && "Illegal integer setcc operation!");
242 case ISD::SETNE: return 0;
246 case ISD::SETGE: return 1;
250 case ISD::SETUGE: return 2;
254 /// getSetCCOrOperation - Return the result of a logical OR between different
255 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
256 /// returns SETCC_INVALID if it is not possible to represent the resultant
258 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
260 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
261 // Cannot fold a signed integer setcc with an unsigned integer setcc.
262 return ISD::SETCC_INVALID;
264 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
266 // If the N and U bits get set then the resultant comparison DOES suddenly
267 // care about orderedness, and is true when ordered.
268 if (Op > ISD::SETTRUE2)
269 Op &= ~16; // Clear the U bit if the N bit is set.
271 // Canonicalize illegal integer setcc's.
272 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
275 return ISD::CondCode(Op);
278 /// getSetCCAndOperation - Return the result of a logical AND between different
279 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
280 /// function returns zero if it is not possible to represent the resultant
282 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
284 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
285 // Cannot fold a signed setcc with an unsigned setcc.
286 return ISD::SETCC_INVALID;
288 // Combine all of the condition bits.
289 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
291 // Canonicalize illegal integer setcc's.
295 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
296 case ISD::SETOEQ: // SETEQ & SETU[LG]E
297 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
298 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
299 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
306 const TargetMachine &SelectionDAG::getTarget() const {
307 return TLI.getTargetMachine();
310 //===----------------------------------------------------------------------===//
311 // SDNode Profile Support
312 //===----------------------------------------------------------------------===//
314 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
316 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
320 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
321 /// solely with their pointer.
322 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
323 ID.AddPointer(VTList.VTs);
326 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
328 static void AddNodeIDOperands(FoldingSetNodeID &ID,
329 SDOperandPtr Ops, unsigned NumOps) {
330 for (; NumOps; --NumOps, ++Ops) {
331 ID.AddPointer(Ops->Val);
332 ID.AddInteger(Ops->ResNo);
336 static void AddNodeIDNode(FoldingSetNodeID &ID,
337 unsigned short OpC, SDVTList VTList,
338 SDOperandPtr OpList, unsigned N) {
339 AddNodeIDOpcode(ID, OpC);
340 AddNodeIDValueTypes(ID, VTList);
341 AddNodeIDOperands(ID, OpList, N);
345 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
347 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
348 AddNodeIDOpcode(ID, N->getOpcode());
349 // Add the return value info.
350 AddNodeIDValueTypes(ID, N->getVTList());
351 // Add the operand info.
352 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
354 // Handle SDNode leafs with special info.
355 switch (N->getOpcode()) {
356 default: break; // Normal nodes don't need extra info.
358 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
360 case ISD::TargetConstant:
362 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
364 case ISD::TargetConstantFP:
365 case ISD::ConstantFP: {
366 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
369 case ISD::TargetGlobalAddress:
370 case ISD::GlobalAddress:
371 case ISD::TargetGlobalTLSAddress:
372 case ISD::GlobalTLSAddress: {
373 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
374 ID.AddPointer(GA->getGlobal());
375 ID.AddInteger(GA->getOffset());
378 case ISD::BasicBlock:
379 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
382 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
385 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
387 case ISD::MEMOPERAND: {
388 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
389 ID.AddPointer(MO.getValue());
390 ID.AddInteger(MO.getFlags());
391 ID.AddInteger(MO.getOffset());
392 ID.AddInteger(MO.getSize());
393 ID.AddInteger(MO.getAlignment());
396 case ISD::FrameIndex:
397 case ISD::TargetFrameIndex:
398 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
401 case ISD::TargetJumpTable:
402 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
404 case ISD::ConstantPool:
405 case ISD::TargetConstantPool: {
406 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
407 ID.AddInteger(CP->getAlignment());
408 ID.AddInteger(CP->getOffset());
409 if (CP->isMachineConstantPoolEntry())
410 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
412 ID.AddPointer(CP->getConstVal());
416 LoadSDNode *LD = cast<LoadSDNode>(N);
417 ID.AddInteger(LD->getAddressingMode());
418 ID.AddInteger(LD->getExtensionType());
419 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
420 ID.AddInteger(LD->getAlignment());
421 ID.AddInteger(LD->isVolatile());
425 StoreSDNode *ST = cast<StoreSDNode>(N);
426 ID.AddInteger(ST->getAddressingMode());
427 ID.AddInteger(ST->isTruncatingStore());
428 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
429 ID.AddInteger(ST->getAlignment());
430 ID.AddInteger(ST->isVolatile());
436 //===----------------------------------------------------------------------===//
437 // SelectionDAG Class
438 //===----------------------------------------------------------------------===//
440 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
442 void SelectionDAG::RemoveDeadNodes() {
443 // Create a dummy node (which is not added to allnodes), that adds a reference
444 // to the root node, preventing it from being deleted.
445 HandleSDNode Dummy(getRoot());
447 SmallVector<SDNode*, 128> DeadNodes;
449 // Add all obviously-dead nodes to the DeadNodes worklist.
450 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
452 DeadNodes.push_back(I);
454 // Process the worklist, deleting the nodes and adding their uses to the
456 while (!DeadNodes.empty()) {
457 SDNode *N = DeadNodes.back();
458 DeadNodes.pop_back();
460 // Take the node out of the appropriate CSE map.
461 RemoveNodeFromCSEMaps(N);
463 // Next, brutally remove the operand list. This is safe to do, as there are
464 // no cycles in the graph.
465 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
466 SDNode *Operand = I->getVal();
467 Operand->removeUser(std::distance(N->op_begin(), I), N);
469 // Now that we removed this operand, see if there are no uses of it left.
470 if (Operand->use_empty())
471 DeadNodes.push_back(Operand);
473 if (N->OperandsNeedDelete) {
474 delete[] N->OperandList;
479 // Finally, remove N itself.
483 // If the root changed (e.g. it was a dead load, update the root).
484 setRoot(Dummy.getValue());
487 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
488 SmallVector<SDNode*, 16> DeadNodes;
489 DeadNodes.push_back(N);
491 // Process the worklist, deleting the nodes and adding their uses to the
493 while (!DeadNodes.empty()) {
494 SDNode *N = DeadNodes.back();
495 DeadNodes.pop_back();
498 UpdateListener->NodeDeleted(N);
500 // Take the node out of the appropriate CSE map.
501 RemoveNodeFromCSEMaps(N);
503 // Next, brutally remove the operand list. This is safe to do, as there are
504 // no cycles in the graph.
505 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
506 SDNode *Operand = I->getVal();
507 Operand->removeUser(std::distance(N->op_begin(), I), N);
509 // Now that we removed this operand, see if there are no uses of it left.
510 if (Operand->use_empty())
511 DeadNodes.push_back(Operand);
513 if (N->OperandsNeedDelete) {
514 delete[] N->OperandList;
519 // Finally, remove N itself.
524 void SelectionDAG::DeleteNode(SDNode *N) {
525 assert(N->use_empty() && "Cannot delete a node that is not dead!");
527 // First take this out of the appropriate CSE map.
528 RemoveNodeFromCSEMaps(N);
530 // Finally, remove uses due to operands of this node, remove from the
531 // AllNodes list, and delete the node.
532 DeleteNodeNotInCSEMaps(N);
535 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
537 // Remove it from the AllNodes list.
540 // Drop all of the operands and decrement used nodes use counts.
541 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
542 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
543 if (N->OperandsNeedDelete) {
544 delete[] N->OperandList;
552 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
553 /// correspond to it. This is useful when we're about to delete or repurpose
554 /// the node. We don't want future request for structurally identical nodes
555 /// to return N anymore.
556 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
558 switch (N->getOpcode()) {
559 case ISD::HANDLENODE: return; // noop.
561 Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
564 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
565 "Cond code doesn't exist!");
566 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
567 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
569 case ISD::ExternalSymbol:
570 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
572 case ISD::TargetExternalSymbol:
574 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
576 case ISD::VALUETYPE: {
577 MVT::ValueType VT = cast<VTSDNode>(N)->getVT();
578 if (MVT::isExtendedVT(VT)) {
579 Erased = ExtendedValueTypeNodes.erase(VT);
581 Erased = ValueTypeNodes[VT] != 0;
582 ValueTypeNodes[VT] = 0;
587 // Remove it from the CSE Map.
588 Erased = CSEMap.RemoveNode(N);
592 // Verify that the node was actually in one of the CSE maps, unless it has a
593 // flag result (which cannot be CSE'd) or is one of the special cases that are
594 // not subject to CSE.
595 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
596 !N->isTargetOpcode()) {
599 assert(0 && "Node is not in map!");
604 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
605 /// has been taken out and modified in some way. If the specified node already
606 /// exists in the CSE maps, do not modify the maps, but return the existing node
607 /// instead. If it doesn't exist, add it and return null.
609 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
610 assert(N->getNumOperands() && "This is a leaf node!");
611 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
612 return 0; // Never add these nodes.
614 // Check that remaining values produced are not flags.
615 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
616 if (N->getValueType(i) == MVT::Flag)
617 return 0; // Never CSE anything that produces a flag.
619 SDNode *New = CSEMap.GetOrInsertNode(N);
620 if (New != N) return New; // Node already existed.
624 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
625 /// were replaced with those specified. If this node is never memoized,
626 /// return null, otherwise return a pointer to the slot it would take. If a
627 /// node already exists with these operands, the slot will be non-null.
628 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
630 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
631 return 0; // Never add these nodes.
633 // Check that remaining values produced are not flags.
634 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
635 if (N->getValueType(i) == MVT::Flag)
636 return 0; // Never CSE anything that produces a flag.
638 SDOperand Ops[] = { Op };
640 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
641 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
644 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
645 /// were replaced with those specified. If this node is never memoized,
646 /// return null, otherwise return a pointer to the slot it would take. If a
647 /// node already exists with these operands, the slot will be non-null.
648 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
649 SDOperand Op1, SDOperand Op2,
651 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
652 return 0; // Never add these nodes.
654 // Check that remaining values produced are not flags.
655 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
656 if (N->getValueType(i) == MVT::Flag)
657 return 0; // Never CSE anything that produces a flag.
659 SDOperand Ops[] = { Op1, Op2 };
661 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
662 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
666 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
667 /// were replaced with those specified. If this node is never memoized,
668 /// return null, otherwise return a pointer to the slot it would take. If a
669 /// node already exists with these operands, the slot will be non-null.
670 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
671 SDOperandPtr Ops,unsigned NumOps,
673 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
674 return 0; // Never add these nodes.
676 // Check that remaining values produced are not flags.
677 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
678 if (N->getValueType(i) == MVT::Flag)
679 return 0; // Never CSE anything that produces a flag.
682 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
684 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
685 ID.AddInteger(LD->getAddressingMode());
686 ID.AddInteger(LD->getExtensionType());
687 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
688 ID.AddInteger(LD->getAlignment());
689 ID.AddInteger(LD->isVolatile());
690 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
691 ID.AddInteger(ST->getAddressingMode());
692 ID.AddInteger(ST->isTruncatingStore());
693 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
694 ID.AddInteger(ST->getAlignment());
695 ID.AddInteger(ST->isVolatile());
698 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
702 SelectionDAG::~SelectionDAG() {
703 while (!AllNodes.empty()) {
704 SDNode *N = AllNodes.begin();
705 N->SetNextInBucket(0);
706 if (N->OperandsNeedDelete) {
707 delete [] N->OperandList;
711 AllNodes.pop_front();
715 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
716 if (Op.getValueType() == VT) return Op;
717 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
718 MVT::getSizeInBits(VT));
719 return getNode(ISD::AND, Op.getValueType(), Op,
720 getConstant(Imm, Op.getValueType()));
723 SDOperand SelectionDAG::getString(const std::string &Val) {
724 StringSDNode *&N = StringNodes[Val];
726 N = new StringSDNode(Val);
727 AllNodes.push_back(N);
729 return SDOperand(N, 0);
732 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
733 MVT::ValueType EltVT =
734 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
736 return getConstant(APInt(MVT::getSizeInBits(EltVT), Val), VT, isT);
739 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT::ValueType VT, bool isT) {
740 assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
742 MVT::ValueType EltVT =
743 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
745 assert(Val.getBitWidth() == MVT::getSizeInBits(EltVT) &&
746 "APInt size does not match type size!");
748 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
750 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
754 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
755 if (!MVT::isVector(VT))
756 return SDOperand(N, 0);
758 N = new ConstantSDNode(isT, Val, EltVT);
759 CSEMap.InsertNode(N, IP);
760 AllNodes.push_back(N);
763 SDOperand Result(N, 0);
764 if (MVT::isVector(VT)) {
765 SmallVector<SDOperand, 8> Ops;
766 Ops.assign(MVT::getVectorNumElements(VT), Result);
767 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
772 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
773 return getConstant(Val, TLI.getPointerTy(), isTarget);
777 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
779 assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
781 MVT::ValueType EltVT =
782 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
784 // Do the map lookup using the actual bit pattern for the floating point
785 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
786 // we don't have issues with SNANs.
787 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
789 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
793 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
794 if (!MVT::isVector(VT))
795 return SDOperand(N, 0);
797 N = new ConstantFPSDNode(isTarget, V, EltVT);
798 CSEMap.InsertNode(N, IP);
799 AllNodes.push_back(N);
802 SDOperand Result(N, 0);
803 if (MVT::isVector(VT)) {
804 SmallVector<SDOperand, 8> Ops;
805 Ops.assign(MVT::getVectorNumElements(VT), Result);
806 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
811 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
813 MVT::ValueType EltVT =
814 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
816 return getConstantFP(APFloat((float)Val), VT, isTarget);
818 return getConstantFP(APFloat(Val), VT, isTarget);
821 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
822 MVT::ValueType VT, int Offset,
826 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
828 // If GV is an alias then use the aliasee for determining thread-localness.
829 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
830 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
833 if (GVar && GVar->isThreadLocal())
834 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
836 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
839 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
841 ID.AddInteger(Offset);
843 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
844 return SDOperand(E, 0);
845 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
846 CSEMap.InsertNode(N, IP);
847 AllNodes.push_back(N);
848 return SDOperand(N, 0);
851 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
853 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
855 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
858 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
859 return SDOperand(E, 0);
860 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
861 CSEMap.InsertNode(N, IP);
862 AllNodes.push_back(N);
863 return SDOperand(N, 0);
866 SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
867 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
869 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
872 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
873 return SDOperand(E, 0);
874 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
875 CSEMap.InsertNode(N, IP);
876 AllNodes.push_back(N);
877 return SDOperand(N, 0);
880 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
881 unsigned Alignment, int Offset,
883 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
885 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
886 ID.AddInteger(Alignment);
887 ID.AddInteger(Offset);
890 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
891 return SDOperand(E, 0);
892 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
893 CSEMap.InsertNode(N, IP);
894 AllNodes.push_back(N);
895 return SDOperand(N, 0);
899 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
901 unsigned Alignment, int Offset,
903 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
905 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
906 ID.AddInteger(Alignment);
907 ID.AddInteger(Offset);
908 C->AddSelectionDAGCSEId(ID);
910 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
911 return SDOperand(E, 0);
912 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
913 CSEMap.InsertNode(N, IP);
914 AllNodes.push_back(N);
915 return SDOperand(N, 0);
919 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
921 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), (SDOperand*)0, 0);
924 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
925 return SDOperand(E, 0);
926 SDNode *N = new BasicBlockSDNode(MBB);
927 CSEMap.InsertNode(N, IP);
928 AllNodes.push_back(N);
929 return SDOperand(N, 0);
932 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
934 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), (SDOperand*)0, 0);
935 ID.AddInteger(Flags.getRawBits());
937 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
938 return SDOperand(E, 0);
939 SDNode *N = new ARG_FLAGSSDNode(Flags);
940 CSEMap.InsertNode(N, IP);
941 AllNodes.push_back(N);
942 return SDOperand(N, 0);
945 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
946 if (!MVT::isExtendedVT(VT) && (unsigned)VT >= ValueTypeNodes.size())
947 ValueTypeNodes.resize(VT+1);
949 SDNode *&N = MVT::isExtendedVT(VT) ?
950 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT];
952 if (N) return SDOperand(N, 0);
953 N = new VTSDNode(VT);
954 AllNodes.push_back(N);
955 return SDOperand(N, 0);
958 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
959 SDNode *&N = ExternalSymbols[Sym];
960 if (N) return SDOperand(N, 0);
961 N = new ExternalSymbolSDNode(false, Sym, VT);
962 AllNodes.push_back(N);
963 return SDOperand(N, 0);
966 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
968 SDNode *&N = TargetExternalSymbols[Sym];
969 if (N) return SDOperand(N, 0);
970 N = new ExternalSymbolSDNode(true, Sym, VT);
971 AllNodes.push_back(N);
972 return SDOperand(N, 0);
975 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
976 if ((unsigned)Cond >= CondCodeNodes.size())
977 CondCodeNodes.resize(Cond+1);
979 if (CondCodeNodes[Cond] == 0) {
980 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
981 AllNodes.push_back(CondCodeNodes[Cond]);
983 return SDOperand(CondCodeNodes[Cond], 0);
986 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
988 AddNodeIDNode(ID, ISD::Register, getVTList(VT), (SDOperand*)0, 0);
989 ID.AddInteger(RegNo);
991 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
992 return SDOperand(E, 0);
993 SDNode *N = new RegisterSDNode(RegNo, VT);
994 CSEMap.InsertNode(N, IP);
995 AllNodes.push_back(N);
996 return SDOperand(N, 0);
999 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1000 assert((!V || isa<PointerType>(V->getType())) &&
1001 "SrcValue is not a pointer?");
1003 FoldingSetNodeID ID;
1004 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), (SDOperand*)0, 0);
1008 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1009 return SDOperand(E, 0);
1011 SDNode *N = new SrcValueSDNode(V);
1012 CSEMap.InsertNode(N, IP);
1013 AllNodes.push_back(N);
1014 return SDOperand(N, 0);
1017 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1018 const Value *v = MO.getValue();
1019 assert((!v || isa<PointerType>(v->getType())) &&
1020 "SrcValue is not a pointer?");
1022 FoldingSetNodeID ID;
1023 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), (SDOperand*)0, 0);
1025 ID.AddInteger(MO.getFlags());
1026 ID.AddInteger(MO.getOffset());
1027 ID.AddInteger(MO.getSize());
1028 ID.AddInteger(MO.getAlignment());
1031 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1032 return SDOperand(E, 0);
1034 SDNode *N = new MemOperandSDNode(MO);
1035 CSEMap.InsertNode(N, IP);
1036 AllNodes.push_back(N);
1037 return SDOperand(N, 0);
1040 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1041 /// specified value type.
1042 SDOperand SelectionDAG::CreateStackTemporary(MVT::ValueType VT) {
1043 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1044 unsigned ByteSize = MVT::getSizeInBits(VT)/8;
1045 const Type *Ty = MVT::getTypeForValueType(VT);
1046 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
1047 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1048 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1052 SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
1053 SDOperand N2, ISD::CondCode Cond) {
1054 // These setcc operations always fold.
1058 case ISD::SETFALSE2: return getConstant(0, VT);
1060 case ISD::SETTRUE2: return getConstant(1, VT);
1072 assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
1076 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1077 const APInt &C2 = N2C->getAPIntValue();
1078 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1079 const APInt &C1 = N1C->getAPIntValue();
1082 default: assert(0 && "Unknown integer setcc!");
1083 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1084 case ISD::SETNE: return getConstant(C1 != C2, VT);
1085 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1086 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1087 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1088 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1089 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1090 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1091 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1092 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1096 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1097 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1098 // No compile time operations on this type yet.
1099 if (N1C->getValueType(0) == MVT::ppcf128)
1102 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1105 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1106 return getNode(ISD::UNDEF, VT);
1108 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1109 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1110 return getNode(ISD::UNDEF, VT);
1112 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1113 R==APFloat::cmpLessThan, VT);
1114 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1115 return getNode(ISD::UNDEF, VT);
1117 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1118 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1119 return getNode(ISD::UNDEF, VT);
1121 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1122 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1123 return getNode(ISD::UNDEF, VT);
1125 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1126 R==APFloat::cmpEqual, VT);
1127 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1128 return getNode(ISD::UNDEF, VT);
1130 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1131 R==APFloat::cmpEqual, VT);
1132 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1133 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1134 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1135 R==APFloat::cmpEqual, VT);
1136 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1137 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1138 R==APFloat::cmpLessThan, VT);
1139 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1140 R==APFloat::cmpUnordered, VT);
1141 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1142 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1145 // Ensure that the constant occurs on the RHS.
1146 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1150 // Could not fold it.
1154 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1155 /// use this predicate to simplify operations downstream.
1156 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1157 unsigned BitWidth = Op.getValueSizeInBits();
1158 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1161 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1162 /// this predicate to simplify operations downstream. Mask is known to be zero
1163 /// for bits that V cannot have.
1164 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1165 unsigned Depth) const {
1166 APInt KnownZero, KnownOne;
1167 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1168 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1169 return (KnownZero & Mask) == Mask;
1172 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1173 /// known to be either zero or one and return them in the KnownZero/KnownOne
1174 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1176 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1177 APInt &KnownZero, APInt &KnownOne,
1178 unsigned Depth) const {
1179 unsigned BitWidth = Mask.getBitWidth();
1180 assert(BitWidth == MVT::getSizeInBits(Op.getValueType()) &&
1181 "Mask size mismatches value type size!");
1183 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1184 if (Depth == 6 || Mask == 0)
1185 return; // Limit search depth.
1187 APInt KnownZero2, KnownOne2;
1189 switch (Op.getOpcode()) {
1191 // We know all of the bits for a constant!
1192 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1193 KnownZero = ~KnownOne & Mask;
1196 // If either the LHS or the RHS are Zero, the result is zero.
1197 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1198 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1199 KnownZero2, KnownOne2, Depth+1);
1200 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1201 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1203 // Output known-1 bits are only known if set in both the LHS & RHS.
1204 KnownOne &= KnownOne2;
1205 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1206 KnownZero |= KnownZero2;
1209 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1210 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1211 KnownZero2, KnownOne2, Depth+1);
1212 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1213 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1215 // Output known-0 bits are only known if clear in both the LHS & RHS.
1216 KnownZero &= KnownZero2;
1217 // Output known-1 are known to be set if set in either the LHS | RHS.
1218 KnownOne |= KnownOne2;
1221 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1222 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1223 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1224 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1226 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1227 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1228 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1229 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1230 KnownZero = KnownZeroOut;
1234 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1235 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1236 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1237 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1238 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1240 // If low bits are zero in either operand, output low known-0 bits.
1241 // Also compute a conserative estimate for high known-0 bits.
1242 // More trickiness is possible, but this is sufficient for the
1243 // interesting case of alignment computation.
1245 unsigned TrailZ = KnownZero.countTrailingOnes() +
1246 KnownZero2.countTrailingOnes();
1247 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1248 KnownZero2.countLeadingOnes(),
1249 BitWidth) - BitWidth;
1251 TrailZ = std::min(TrailZ, BitWidth);
1252 LeadZ = std::min(LeadZ, BitWidth);
1253 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1254 APInt::getHighBitsSet(BitWidth, LeadZ);
1259 // For the purposes of computing leading zeros we can conservatively
1260 // treat a udiv as a logical right shift by the power of 2 known to
1261 // be less than the denominator.
1262 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1263 ComputeMaskedBits(Op.getOperand(0),
1264 AllOnes, KnownZero2, KnownOne2, Depth+1);
1265 unsigned LeadZ = KnownZero2.countLeadingOnes();
1269 ComputeMaskedBits(Op.getOperand(1),
1270 AllOnes, KnownZero2, KnownOne2, Depth+1);
1271 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1272 if (RHSUnknownLeadingOnes != BitWidth)
1273 LeadZ = std::min(BitWidth,
1274 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1276 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1280 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1281 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1282 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1283 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1285 // Only known if known in both the LHS and RHS.
1286 KnownOne &= KnownOne2;
1287 KnownZero &= KnownZero2;
1289 case ISD::SELECT_CC:
1290 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1291 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1292 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1293 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1295 // Only known if known in both the LHS and RHS.
1296 KnownOne &= KnownOne2;
1297 KnownZero &= KnownZero2;
1300 // If we know the result of a setcc has the top bits zero, use this info.
1301 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1303 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1306 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1307 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1308 unsigned ShAmt = SA->getValue();
1310 // If the shift count is an invalid immediate, don't do anything.
1311 if (ShAmt >= BitWidth)
1314 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1315 KnownZero, KnownOne, Depth+1);
1316 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1317 KnownZero <<= ShAmt;
1319 // low bits known zero.
1320 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1324 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1325 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1326 unsigned ShAmt = SA->getValue();
1328 // If the shift count is an invalid immediate, don't do anything.
1329 if (ShAmt >= BitWidth)
1332 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1333 KnownZero, KnownOne, Depth+1);
1334 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1335 KnownZero = KnownZero.lshr(ShAmt);
1336 KnownOne = KnownOne.lshr(ShAmt);
1338 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1339 KnownZero |= HighBits; // High bits known zero.
1343 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1344 unsigned ShAmt = SA->getValue();
1346 // If the shift count is an invalid immediate, don't do anything.
1347 if (ShAmt >= BitWidth)
1350 APInt InDemandedMask = (Mask << ShAmt);
1351 // If any of the demanded bits are produced by the sign extension, we also
1352 // demand the input sign bit.
1353 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1354 if (HighBits.getBoolValue())
1355 InDemandedMask |= APInt::getSignBit(BitWidth);
1357 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1359 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1360 KnownZero = KnownZero.lshr(ShAmt);
1361 KnownOne = KnownOne.lshr(ShAmt);
1363 // Handle the sign bits.
1364 APInt SignBit = APInt::getSignBit(BitWidth);
1365 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1367 if (KnownZero.intersects(SignBit)) {
1368 KnownZero |= HighBits; // New bits are known zero.
1369 } else if (KnownOne.intersects(SignBit)) {
1370 KnownOne |= HighBits; // New bits are known one.
1374 case ISD::SIGN_EXTEND_INREG: {
1375 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1376 unsigned EBits = MVT::getSizeInBits(EVT);
1378 // Sign extension. Compute the demanded bits in the result that are not
1379 // present in the input.
1380 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1382 APInt InSignBit = APInt::getSignBit(EBits);
1383 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1385 // If the sign extended bits are demanded, we know that the sign
1387 InSignBit.zext(BitWidth);
1388 if (NewBits.getBoolValue())
1389 InputDemandedBits |= InSignBit;
1391 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1392 KnownZero, KnownOne, Depth+1);
1393 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1395 // If the sign bit of the input is known set or clear, then we know the
1396 // top bits of the result.
1397 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1398 KnownZero |= NewBits;
1399 KnownOne &= ~NewBits;
1400 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1401 KnownOne |= NewBits;
1402 KnownZero &= ~NewBits;
1403 } else { // Input sign bit unknown
1404 KnownZero &= ~NewBits;
1405 KnownOne &= ~NewBits;
1412 unsigned LowBits = Log2_32(BitWidth)+1;
1413 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1414 KnownOne = APInt(BitWidth, 0);
1418 if (ISD::isZEXTLoad(Op.Val)) {
1419 LoadSDNode *LD = cast<LoadSDNode>(Op);
1420 MVT::ValueType VT = LD->getMemoryVT();
1421 unsigned MemBits = MVT::getSizeInBits(VT);
1422 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1426 case ISD::ZERO_EXTEND: {
1427 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1428 unsigned InBits = MVT::getSizeInBits(InVT);
1429 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1430 APInt InMask = Mask;
1431 InMask.trunc(InBits);
1432 KnownZero.trunc(InBits);
1433 KnownOne.trunc(InBits);
1434 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1435 KnownZero.zext(BitWidth);
1436 KnownOne.zext(BitWidth);
1437 KnownZero |= NewBits;
1440 case ISD::SIGN_EXTEND: {
1441 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1442 unsigned InBits = MVT::getSizeInBits(InVT);
1443 APInt InSignBit = APInt::getSignBit(InBits);
1444 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1445 APInt InMask = Mask;
1446 InMask.trunc(InBits);
1448 // If any of the sign extended bits are demanded, we know that the sign
1449 // bit is demanded. Temporarily set this bit in the mask for our callee.
1450 if (NewBits.getBoolValue())
1451 InMask |= InSignBit;
1453 KnownZero.trunc(InBits);
1454 KnownOne.trunc(InBits);
1455 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1457 // Note if the sign bit is known to be zero or one.
1458 bool SignBitKnownZero = KnownZero.isNegative();
1459 bool SignBitKnownOne = KnownOne.isNegative();
1460 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1461 "Sign bit can't be known to be both zero and one!");
1463 // If the sign bit wasn't actually demanded by our caller, we don't
1464 // want it set in the KnownZero and KnownOne result values. Reset the
1465 // mask and reapply it to the result values.
1467 InMask.trunc(InBits);
1468 KnownZero &= InMask;
1471 KnownZero.zext(BitWidth);
1472 KnownOne.zext(BitWidth);
1474 // If the sign bit is known zero or one, the top bits match.
1475 if (SignBitKnownZero)
1476 KnownZero |= NewBits;
1477 else if (SignBitKnownOne)
1478 KnownOne |= NewBits;
1481 case ISD::ANY_EXTEND: {
1482 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1483 unsigned InBits = MVT::getSizeInBits(InVT);
1484 APInt InMask = Mask;
1485 InMask.trunc(InBits);
1486 KnownZero.trunc(InBits);
1487 KnownOne.trunc(InBits);
1488 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1489 KnownZero.zext(BitWidth);
1490 KnownOne.zext(BitWidth);
1493 case ISD::TRUNCATE: {
1494 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1495 unsigned InBits = MVT::getSizeInBits(InVT);
1496 APInt InMask = Mask;
1497 InMask.zext(InBits);
1498 KnownZero.zext(InBits);
1499 KnownOne.zext(InBits);
1500 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1501 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1502 KnownZero.trunc(BitWidth);
1503 KnownOne.trunc(BitWidth);
1506 case ISD::AssertZext: {
1507 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1508 APInt InMask = APInt::getLowBitsSet(BitWidth, MVT::getSizeInBits(VT));
1509 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1511 KnownZero |= (~InMask) & Mask;
1515 // All bits are zero except the low bit.
1516 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1520 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1521 // We know that the top bits of C-X are clear if X contains less bits
1522 // than C (i.e. no wrap-around can happen). For example, 20-X is
1523 // positive if we can prove that X is >= 0 and < 16.
1524 if (CLHS->getAPIntValue().isNonNegative()) {
1525 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1526 // NLZ can't be BitWidth with no sign bit
1527 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1528 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1531 // If all of the MaskV bits are known to be zero, then we know the
1532 // output top bits are zero, because we now know that the output is
1534 if ((KnownZero2 & MaskV) == MaskV) {
1535 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1536 // Top bits known zero.
1537 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1544 // Output known-0 bits are known if clear or set in both the low clear bits
1545 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1546 // low 3 bits clear.
1547 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1548 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1549 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1550 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1552 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1553 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1554 KnownZeroOut = std::min(KnownZeroOut,
1555 KnownZero2.countTrailingOnes());
1557 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1561 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1562 APInt RA = Rem->getAPIntValue();
1563 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1564 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1565 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1566 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1568 // The sign of a remainder is equal to the sign of the first
1569 // operand (zero being positive).
1570 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1571 KnownZero2 |= ~LowBits;
1572 else if (KnownOne2[BitWidth-1])
1573 KnownOne2 |= ~LowBits;
1575 KnownZero |= KnownZero2 & Mask;
1576 KnownOne |= KnownOne2 & Mask;
1578 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1583 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1584 APInt RA = Rem->getAPIntValue();
1585 if (RA.isPowerOf2()) {
1586 APInt LowBits = (RA - 1);
1587 APInt Mask2 = LowBits & Mask;
1588 KnownZero |= ~LowBits & Mask;
1589 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1590 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1595 // Since the result is less than or equal to either operand, any leading
1596 // zero bits in either operand must also exist in the result.
1597 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1598 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1600 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1603 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1604 KnownZero2.countLeadingOnes());
1606 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1610 // Allow the target to implement this method for its nodes.
1611 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1612 case ISD::INTRINSIC_WO_CHAIN:
1613 case ISD::INTRINSIC_W_CHAIN:
1614 case ISD::INTRINSIC_VOID:
1615 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1621 /// ComputeNumSignBits - Return the number of times the sign bit of the
1622 /// register is replicated into the other bits. We know that at least 1 bit
1623 /// is always equal to the sign bit (itself), but other cases can give us
1624 /// information. For example, immediately after an "SRA X, 2", we know that
1625 /// the top 3 bits are all equal to each other, so we return 3.
1626 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1627 MVT::ValueType VT = Op.getValueType();
1628 assert(MVT::isInteger(VT) && "Invalid VT!");
1629 unsigned VTBits = MVT::getSizeInBits(VT);
1631 unsigned FirstAnswer = 1;
1634 return 1; // Limit search depth.
1636 switch (Op.getOpcode()) {
1638 case ISD::AssertSext:
1639 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1640 return VTBits-Tmp+1;
1641 case ISD::AssertZext:
1642 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1645 case ISD::Constant: {
1646 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1647 // If negative, return # leading ones.
1648 if (Val.isNegative())
1649 return Val.countLeadingOnes();
1651 // Return # leading zeros.
1652 return Val.countLeadingZeros();
1655 case ISD::SIGN_EXTEND:
1656 Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1657 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1659 case ISD::SIGN_EXTEND_INREG:
1660 // Max of the input and what this extends.
1661 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1664 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1665 return std::max(Tmp, Tmp2);
1668 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1669 // SRA X, C -> adds C sign bits.
1670 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1671 Tmp += C->getValue();
1672 if (Tmp > VTBits) Tmp = VTBits;
1676 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1677 // shl destroys sign bits.
1678 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1679 if (C->getValue() >= VTBits || // Bad shift.
1680 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1681 return Tmp - C->getValue();
1686 case ISD::XOR: // NOT is handled here.
1687 // Logical binary ops preserve the number of sign bits at the worst.
1688 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1690 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1691 FirstAnswer = std::min(Tmp, Tmp2);
1692 // We computed what we know about the sign bits as our first
1693 // answer. Now proceed to the generic code that uses
1694 // ComputeMaskedBits, and pick whichever answer is better.
1699 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1700 if (Tmp == 1) return 1; // Early out.
1701 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1702 return std::min(Tmp, Tmp2);
1705 // If setcc returns 0/-1, all bits are sign bits.
1706 if (TLI.getSetCCResultContents() ==
1707 TargetLowering::ZeroOrNegativeOneSetCCResult)
1712 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1713 unsigned RotAmt = C->getValue() & (VTBits-1);
1715 // Handle rotate right by N like a rotate left by 32-N.
1716 if (Op.getOpcode() == ISD::ROTR)
1717 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1719 // If we aren't rotating out all of the known-in sign bits, return the
1720 // number that are left. This handles rotl(sext(x), 1) for example.
1721 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1722 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1726 // Add can have at most one carry bit. Thus we know that the output
1727 // is, at worst, one more bit than the inputs.
1728 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1729 if (Tmp == 1) return 1; // Early out.
1731 // Special case decrementing a value (ADD X, -1):
1732 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1733 if (CRHS->isAllOnesValue()) {
1734 APInt KnownZero, KnownOne;
1735 APInt Mask = APInt::getAllOnesValue(VTBits);
1736 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1738 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1740 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1743 // If we are subtracting one from a positive number, there is no carry
1744 // out of the result.
1745 if (KnownZero.isNegative())
1749 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1750 if (Tmp2 == 1) return 1;
1751 return std::min(Tmp, Tmp2)-1;
1755 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1756 if (Tmp2 == 1) return 1;
1759 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1760 if (CLHS->isNullValue()) {
1761 APInt KnownZero, KnownOne;
1762 APInt Mask = APInt::getAllOnesValue(VTBits);
1763 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1764 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1766 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1769 // If the input is known to be positive (the sign bit is known clear),
1770 // the output of the NEG has the same number of sign bits as the input.
1771 if (KnownZero.isNegative())
1774 // Otherwise, we treat this like a SUB.
1777 // Sub can have at most one carry bit. Thus we know that the output
1778 // is, at worst, one more bit than the inputs.
1779 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1780 if (Tmp == 1) return 1; // Early out.
1781 return std::min(Tmp, Tmp2)-1;
1784 // FIXME: it's tricky to do anything useful for this, but it is an important
1785 // case for targets like X86.
1789 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1790 if (Op.getOpcode() == ISD::LOAD) {
1791 LoadSDNode *LD = cast<LoadSDNode>(Op);
1792 unsigned ExtType = LD->getExtensionType();
1795 case ISD::SEXTLOAD: // '17' bits known
1796 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1797 return VTBits-Tmp+1;
1798 case ISD::ZEXTLOAD: // '16' bits known
1799 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1804 // Allow the target to implement this method for its nodes.
1805 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1806 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1807 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1808 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1809 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1810 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1813 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1814 // use this information.
1815 APInt KnownZero, KnownOne;
1816 APInt Mask = APInt::getAllOnesValue(VTBits);
1817 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1819 if (KnownZero.isNegative()) { // sign bit is 0
1821 } else if (KnownOne.isNegative()) { // sign bit is 1;
1828 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1829 // the number of identical bits in the top of the input value.
1831 Mask <<= Mask.getBitWidth()-VTBits;
1832 // Return # leading zeros. We use 'min' here in case Val was zero before
1833 // shifting. We don't want to return '64' as for an i32 "0".
1834 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1838 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1839 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1840 if (!GA) return false;
1841 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1842 if (!GV) return false;
1843 MachineModuleInfo *MMI = getMachineModuleInfo();
1844 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1848 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1849 /// element of the result of the vector shuffle.
1850 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned Idx) {
1851 MVT::ValueType VT = N->getValueType(0);
1852 SDOperand PermMask = N->getOperand(2);
1853 unsigned NumElems = PermMask.getNumOperands();
1854 SDOperand V = (Idx < NumElems) ? N->getOperand(0) : N->getOperand(1);
1857 if (V.getOpcode() == ISD::BIT_CONVERT) {
1858 V = V.getOperand(0);
1859 if (MVT::getVectorNumElements(V.getValueType()) != NumElems)
1862 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1863 return (Idx == 0) ? V.getOperand(0)
1864 : getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
1865 if (V.getOpcode() == ISD::BUILD_VECTOR)
1866 return V.getOperand(Idx);
1867 if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
1868 SDOperand Elt = PermMask.getOperand(Idx);
1869 if (Elt.getOpcode() == ISD::UNDEF)
1870 return getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
1871 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Elt)->getValue());
1877 /// getNode - Gets or creates the specified node.
1879 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1880 FoldingSetNodeID ID;
1881 AddNodeIDNode(ID, Opcode, getVTList(VT), (SDOperand*)0, 0);
1883 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1884 return SDOperand(E, 0);
1885 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1886 CSEMap.InsertNode(N, IP);
1888 AllNodes.push_back(N);
1889 return SDOperand(N, 0);
1892 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1893 SDOperand Operand) {
1894 // Constant fold unary operations with an integer constant operand.
1895 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1896 const APInt &Val = C->getAPIntValue();
1897 unsigned BitWidth = MVT::getSizeInBits(VT);
1900 case ISD::SIGN_EXTEND:
1901 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1902 case ISD::ANY_EXTEND:
1903 case ISD::ZERO_EXTEND:
1905 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1906 case ISD::UINT_TO_FP:
1907 case ISD::SINT_TO_FP: {
1908 const uint64_t zero[] = {0, 0};
1909 // No compile time operations on this type.
1910 if (VT==MVT::ppcf128)
1912 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1913 (void)apf.convertFromAPInt(Val,
1914 Opcode==ISD::SINT_TO_FP,
1915 APFloat::rmNearestTiesToEven);
1916 return getConstantFP(apf, VT);
1918 case ISD::BIT_CONVERT:
1919 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1920 return getConstantFP(Val.bitsToFloat(), VT);
1921 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1922 return getConstantFP(Val.bitsToDouble(), VT);
1925 return getConstant(Val.byteSwap(), VT);
1927 return getConstant(Val.countPopulation(), VT);
1929 return getConstant(Val.countLeadingZeros(), VT);
1931 return getConstant(Val.countTrailingZeros(), VT);
1935 // Constant fold unary operations with a floating point constant operand.
1936 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1937 APFloat V = C->getValueAPF(); // make copy
1938 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1942 return getConstantFP(V, VT);
1945 return getConstantFP(V, VT);
1947 case ISD::FP_EXTEND:
1948 // This can return overflow, underflow, or inexact; we don't care.
1949 // FIXME need to be more flexible about rounding mode.
1950 (void)V.convert(*MVTToAPFloatSemantics(VT),
1951 APFloat::rmNearestTiesToEven);
1952 return getConstantFP(V, VT);
1953 case ISD::FP_TO_SINT:
1954 case ISD::FP_TO_UINT: {
1956 assert(integerPartWidth >= 64);
1957 // FIXME need to be more flexible about rounding mode.
1958 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1959 Opcode==ISD::FP_TO_SINT,
1960 APFloat::rmTowardZero);
1961 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
1963 return getConstant(x, VT);
1965 case ISD::BIT_CONVERT:
1966 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1967 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1968 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1969 return getConstant(V.convertToAPInt().getZExtValue(), VT);
1975 unsigned OpOpcode = Operand.Val->getOpcode();
1977 case ISD::TokenFactor:
1978 case ISD::MERGE_VALUES:
1979 return Operand; // Factor or merge of one node? No need.
1980 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1981 case ISD::FP_EXTEND:
1982 assert(MVT::isFloatingPoint(VT) &&
1983 MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1984 if (Operand.getValueType() == VT) return Operand; // noop conversion.
1985 if (Operand.getOpcode() == ISD::UNDEF)
1986 return getNode(ISD::UNDEF, VT);
1988 case ISD::SIGN_EXTEND:
1989 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1990 "Invalid SIGN_EXTEND!");
1991 if (Operand.getValueType() == VT) return Operand; // noop extension
1992 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1993 && "Invalid sext node, dst < src!");
1994 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1995 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1997 case ISD::ZERO_EXTEND:
1998 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1999 "Invalid ZERO_EXTEND!");
2000 if (Operand.getValueType() == VT) return Operand; // noop extension
2001 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
2002 && "Invalid zext node, dst < src!");
2003 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2004 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2006 case ISD::ANY_EXTEND:
2007 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
2008 "Invalid ANY_EXTEND!");
2009 if (Operand.getValueType() == VT) return Operand; // noop extension
2010 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
2011 && "Invalid anyext node, dst < src!");
2012 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2013 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2014 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2017 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
2018 "Invalid TRUNCATE!");
2019 if (Operand.getValueType() == VT) return Operand; // noop truncate
2020 assert(MVT::getSizeInBits(Operand.getValueType()) > MVT::getSizeInBits(VT)
2021 && "Invalid truncate node, src < dst!");
2022 if (OpOpcode == ISD::TRUNCATE)
2023 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2024 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2025 OpOpcode == ISD::ANY_EXTEND) {
2026 // If the source is smaller than the dest, we still need an extend.
2027 if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
2028 < MVT::getSizeInBits(VT))
2029 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2030 else if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
2031 > MVT::getSizeInBits(VT))
2032 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2034 return Operand.Val->getOperand(0);
2037 case ISD::BIT_CONVERT:
2038 // Basic sanity checking.
2039 assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
2040 && "Cannot BIT_CONVERT between types of different sizes!");
2041 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2042 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2043 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2044 if (OpOpcode == ISD::UNDEF)
2045 return getNode(ISD::UNDEF, VT);
2047 case ISD::SCALAR_TO_VECTOR:
2048 assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
2049 MVT::getVectorElementType(VT) == Operand.getValueType() &&
2050 "Illegal SCALAR_TO_VECTOR node!");
2051 if (OpOpcode == ISD::UNDEF)
2052 return getNode(ISD::UNDEF, VT);
2053 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2054 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2055 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2056 Operand.getConstantOperandVal(1) == 0 &&
2057 Operand.getOperand(0).getValueType() == VT)
2058 return Operand.getOperand(0);
2061 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2062 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2063 Operand.Val->getOperand(0));
2064 if (OpOpcode == ISD::FNEG) // --X -> X
2065 return Operand.Val->getOperand(0);
2068 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2069 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2074 SDVTList VTs = getVTList(VT);
2075 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2076 FoldingSetNodeID ID;
2077 SDOperand Ops[1] = { Operand };
2078 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2080 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2081 return SDOperand(E, 0);
2082 N = new UnarySDNode(Opcode, VTs, Operand);
2083 CSEMap.InsertNode(N, IP);
2085 N = new UnarySDNode(Opcode, VTs, Operand);
2087 AllNodes.push_back(N);
2088 return SDOperand(N, 0);
2093 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2094 SDOperand N1, SDOperand N2) {
2095 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2096 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2099 case ISD::TokenFactor:
2100 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2101 N2.getValueType() == MVT::Other && "Invalid token factor!");
2102 // Fold trivial token factors.
2103 if (N1.getOpcode() == ISD::EntryToken) return N2;
2104 if (N2.getOpcode() == ISD::EntryToken) return N1;
2107 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
2108 N1.getValueType() == VT && "Binary operator types must match!");
2109 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2110 // worth handling here.
2111 if (N2C && N2C->isNullValue())
2113 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2118 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
2119 N1.getValueType() == VT && "Binary operator types must match!");
2120 // (X ^| 0) -> X. This commonly occurs when legalizing i64 values, so it's
2121 // worth handling here.
2122 if (N2C && N2C->isNullValue())
2129 assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
2141 assert(N1.getValueType() == N2.getValueType() &&
2142 N1.getValueType() == VT && "Binary operator types must match!");
2144 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2145 assert(N1.getValueType() == VT &&
2146 MVT::isFloatingPoint(N1.getValueType()) &&
2147 MVT::isFloatingPoint(N2.getValueType()) &&
2148 "Invalid FCOPYSIGN!");
2155 assert(VT == N1.getValueType() &&
2156 "Shift operators return type must be the same as their first arg");
2157 assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
2158 VT != MVT::i1 && "Shifts only work on integers");
2160 case ISD::FP_ROUND_INREG: {
2161 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2162 assert(VT == N1.getValueType() && "Not an inreg round!");
2163 assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
2164 "Cannot FP_ROUND_INREG integer types");
2165 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2166 "Not rounding down!");
2167 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2171 assert(MVT::isFloatingPoint(VT) &&
2172 MVT::isFloatingPoint(N1.getValueType()) &&
2173 MVT::getSizeInBits(VT) <= MVT::getSizeInBits(N1.getValueType()) &&
2174 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2175 if (N1.getValueType() == VT) return N1; // noop conversion.
2177 case ISD::AssertSext:
2178 case ISD::AssertZext: {
2179 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2180 assert(VT == N1.getValueType() && "Not an inreg extend!");
2181 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2182 "Cannot *_EXTEND_INREG FP types");
2183 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2185 if (VT == EVT) return N1; // noop assertion.
2188 case ISD::SIGN_EXTEND_INREG: {
2189 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2190 assert(VT == N1.getValueType() && "Not an inreg extend!");
2191 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2192 "Cannot *_EXTEND_INREG FP types");
2193 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2195 if (EVT == VT) return N1; // Not actually extending
2198 APInt Val = N1C->getAPIntValue();
2199 unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
2200 Val <<= Val.getBitWidth()-FromBits;
2201 Val = Val.ashr(Val.getBitWidth()-FromBits);
2202 return getConstant(Val, VT);
2206 case ISD::EXTRACT_VECTOR_ELT:
2207 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2209 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2210 if (N1.getOpcode() == ISD::UNDEF)
2211 return getNode(ISD::UNDEF, VT);
2213 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2214 // expanding copies of large vectors from registers.
2215 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2216 N1.getNumOperands() > 0) {
2218 MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2219 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2220 N1.getOperand(N2C->getValue() / Factor),
2221 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2224 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2225 // expanding large vector constants.
2226 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2227 return N1.getOperand(N2C->getValue());
2229 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2230 // operations are lowered to scalars.
2231 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2232 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2234 return N1.getOperand(1);
2236 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2239 case ISD::EXTRACT_ELEMENT:
2240 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2241 assert(!MVT::isVector(N1.getValueType()) &&
2242 MVT::isInteger(N1.getValueType()) &&
2243 !MVT::isVector(VT) && MVT::isInteger(VT) &&
2244 "EXTRACT_ELEMENT only applies to integers!");
2246 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2247 // 64-bit integers into 32-bit parts. Instead of building the extract of
2248 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2249 if (N1.getOpcode() == ISD::BUILD_PAIR)
2250 return N1.getOperand(N2C->getValue());
2252 // EXTRACT_ELEMENT of a constant int is also very common.
2253 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2254 unsigned ElementSize = MVT::getSizeInBits(VT);
2255 unsigned Shift = ElementSize * N2C->getValue();
2256 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2257 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2260 case ISD::EXTRACT_SUBVECTOR:
2261 if (N1.getValueType() == VT) // Trivial extraction.
2268 APInt C1 = N1C->getAPIntValue(), C2 = N2C->getAPIntValue();
2270 case ISD::ADD: return getConstant(C1 + C2, VT);
2271 case ISD::SUB: return getConstant(C1 - C2, VT);
2272 case ISD::MUL: return getConstant(C1 * C2, VT);
2274 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2277 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2280 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2283 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2285 case ISD::AND : return getConstant(C1 & C2, VT);
2286 case ISD::OR : return getConstant(C1 | C2, VT);
2287 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2288 case ISD::SHL : return getConstant(C1 << C2, VT);
2289 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2290 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2291 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2292 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2295 } else { // Cannonicalize constant to RHS if commutative
2296 if (isCommutativeBinOp(Opcode)) {
2297 std::swap(N1C, N2C);
2303 // Constant fold FP operations.
2304 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2305 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2307 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2308 // Cannonicalize constant to RHS if commutative
2309 std::swap(N1CFP, N2CFP);
2311 } else if (N2CFP && VT != MVT::ppcf128) {
2312 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2313 APFloat::opStatus s;
2316 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2317 if (s != APFloat::opInvalidOp)
2318 return getConstantFP(V1, VT);
2321 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2322 if (s!=APFloat::opInvalidOp)
2323 return getConstantFP(V1, VT);
2326 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2327 if (s!=APFloat::opInvalidOp)
2328 return getConstantFP(V1, VT);
2331 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2332 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2333 return getConstantFP(V1, VT);
2336 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2337 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2338 return getConstantFP(V1, VT);
2340 case ISD::FCOPYSIGN:
2342 return getConstantFP(V1, VT);
2348 // Canonicalize an UNDEF to the RHS, even over a constant.
2349 if (N1.getOpcode() == ISD::UNDEF) {
2350 if (isCommutativeBinOp(Opcode)) {
2354 case ISD::FP_ROUND_INREG:
2355 case ISD::SIGN_EXTEND_INREG:
2361 return N1; // fold op(undef, arg2) -> undef
2368 if (!MVT::isVector(VT))
2369 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2370 // For vectors, we can't easily build an all zero vector, just return
2377 // Fold a bunch of operators when the RHS is undef.
2378 if (N2.getOpcode() == ISD::UNDEF) {
2381 if (N1.getOpcode() == ISD::UNDEF)
2382 // Handle undef ^ undef -> 0 special case. This is a common
2384 return getConstant(0, VT);
2399 return N2; // fold op(arg1, undef) -> undef
2404 if (!MVT::isVector(VT))
2405 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2406 // For vectors, we can't easily build an all zero vector, just return
2410 if (!MVT::isVector(VT))
2411 return getConstant(MVT::getIntVTBitMask(VT), VT);
2412 // For vectors, we can't easily build an all one vector, just return
2420 // Memoize this node if possible.
2422 SDVTList VTs = getVTList(VT);
2423 if (VT != MVT::Flag) {
2424 SDOperand Ops[] = { N1, N2 };
2425 FoldingSetNodeID ID;
2426 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2428 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2429 return SDOperand(E, 0);
2430 N = new BinarySDNode(Opcode, VTs, N1, N2);
2431 CSEMap.InsertNode(N, IP);
2433 N = new BinarySDNode(Opcode, VTs, N1, N2);
2436 AllNodes.push_back(N);
2437 return SDOperand(N, 0);
2440 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2441 SDOperand N1, SDOperand N2, SDOperand N3) {
2442 // Perform various simplifications.
2443 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2444 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2447 // Use FoldSetCC to simplify SETCC's.
2448 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2449 if (Simp.Val) return Simp;
2454 if (N1C->getValue())
2455 return N2; // select true, X, Y -> X
2457 return N3; // select false, X, Y -> Y
2460 if (N2 == N3) return N2; // select C, X, X -> X
2464 if (N2C->getValue()) // Unconditional branch
2465 return getNode(ISD::BR, MVT::Other, N1, N3);
2467 return N1; // Never-taken branch
2470 case ISD::VECTOR_SHUFFLE:
2471 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2472 MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2473 N3.getOpcode() == ISD::BUILD_VECTOR &&
2474 MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2475 "Illegal VECTOR_SHUFFLE node!");
2477 case ISD::BIT_CONVERT:
2478 // Fold bit_convert nodes from a type to themselves.
2479 if (N1.getValueType() == VT)
2484 // Memoize node if it doesn't produce a flag.
2486 SDVTList VTs = getVTList(VT);
2487 if (VT != MVT::Flag) {
2488 SDOperand Ops[] = { N1, N2, N3 };
2489 FoldingSetNodeID ID;
2490 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2492 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2493 return SDOperand(E, 0);
2494 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2495 CSEMap.InsertNode(N, IP);
2497 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2499 AllNodes.push_back(N);
2500 return SDOperand(N, 0);
2503 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2504 SDOperand N1, SDOperand N2, SDOperand N3,
2506 SDOperand Ops[] = { N1, N2, N3, N4 };
2507 return getNode(Opcode, VT, Ops, 4);
2510 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2511 SDOperand N1, SDOperand N2, SDOperand N3,
2512 SDOperand N4, SDOperand N5) {
2513 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2514 return getNode(Opcode, VT, Ops, 5);
2517 /// getMemsetValue - Vectorized representation of the memset value
2519 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2520 SelectionDAG &DAG) {
2521 unsigned NumBits = MVT::isVector(VT) ?
2522 MVT::getSizeInBits(MVT::getVectorElementType(VT)) : MVT::getSizeInBits(VT);
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;
2530 if (MVT::isInteger(VT))
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::ValueType VT, SelectionDAG &DAG,
2551 const TargetLowering &TLI,
2552 std::string &Str, unsigned Offset) {
2553 assert(!MVT::isVector(VT) && "Can't handle vector type here!");
2554 unsigned NumBits = MVT::getSizeInBits(VT);
2555 unsigned MSB = NumBits / 8;
2557 if (TLI.isLittleEndian())
2558 Offset = Offset + MSB - 1;
2559 for (unsigned i = 0; i != MSB; ++i) {
2560 Val = (Val << 8) | (unsigned char)Str[Offset];
2561 Offset += TLI.isLittleEndian() ? -1 : 1;
2563 return DAG.getConstant(Val, VT);
2566 /// getMemBasePlusOffset - Returns base and offset node for the
2568 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2569 SelectionDAG &DAG) {
2570 MVT::ValueType VT = Base.getValueType();
2571 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2574 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2576 static bool isMemSrcFromString(SDOperand Src, std::string &Str,
2578 unsigned SrcDelta = 0;
2579 GlobalAddressSDNode *G = NULL;
2580 if (Src.getOpcode() == ISD::GlobalAddress)
2581 G = cast<GlobalAddressSDNode>(Src);
2582 else if (Src.getOpcode() == ISD::ADD &&
2583 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2584 Src.getOperand(1).getOpcode() == ISD::Constant) {
2585 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2586 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2591 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2592 if (GV && GV->isConstant()) {
2593 Str = GV->getStringValue(false);
2603 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2604 /// to replace the memset / memcpy is below the threshold. It also returns the
2605 /// types of the sequence of memory ops to perform memset / memcpy.
2607 bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2608 SDOperand Dst, SDOperand Src,
2609 unsigned Limit, uint64_t Size, unsigned &Align,
2611 const TargetLowering &TLI) {
2612 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2615 uint64_t SrcOff = 0;
2616 bool isSrcStr = isMemSrcFromString(Src, Str, SrcOff);
2617 bool isSrcConst = isa<ConstantSDNode>(Src);
2618 MVT::ValueType VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2619 if (VT != MVT::iAny) {
2620 unsigned NewAlign = (unsigned)
2621 TLI.getTargetData()->getABITypeAlignment(MVT::getTypeForValueType(VT));
2622 // If source is a string constant, this will require an unaligned load.
2623 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2624 if (Dst.getOpcode() != ISD::FrameIndex) {
2625 // Can't change destination alignment. It requires a unaligned store.
2629 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2630 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2631 if (MFI->isFixedObjectIndex(FI)) {
2632 // Can't change destination alignment. It requires a unaligned store.
2636 // Give the stack frame object a larger alignment.
2637 MFI->setObjectAlignment(FI, NewAlign);
2644 if (VT == MVT::iAny) {
2648 switch (Align & 7) {
2649 case 0: VT = MVT::i64; break;
2650 case 4: VT = MVT::i32; break;
2651 case 2: VT = MVT::i16; break;
2652 default: VT = MVT::i8; break;
2656 MVT::ValueType LVT = MVT::i64;
2657 while (!TLI.isTypeLegal(LVT))
2658 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2659 assert(MVT::isInteger(LVT));
2665 unsigned NumMemOps = 0;
2667 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2668 while (VTSize > Size) {
2669 // For now, only use non-vector load / store's for the left-over pieces.
2670 if (MVT::isVector(VT)) {
2672 while (!TLI.isTypeLegal(VT))
2673 VT = (MVT::ValueType)((unsigned)VT - 1);
2674 VTSize = MVT::getSizeInBits(VT) / 8;
2676 VT = (MVT::ValueType)((unsigned)VT - 1);
2681 if (++NumMemOps > Limit)
2683 MemOps.push_back(VT);
2690 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2691 SDOperand Chain, SDOperand Dst,
2692 SDOperand Src, uint64_t Size,
2693 unsigned Align, bool AlwaysInline,
2694 const Value *DstSV, uint64_t DstSVOff,
2695 const Value *SrcSV, uint64_t SrcSVOff){
2696 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2698 // Expand memcpy to a series of load and store ops if the size operand falls
2699 // below a certain threshold.
2700 std::vector<MVT::ValueType> MemOps;
2701 uint64_t Limit = -1;
2703 Limit = TLI.getMaxStoresPerMemcpy();
2704 unsigned DstAlign = Align; // Destination alignment can change.
2705 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2710 uint64_t SrcOff = 0, DstOff = 0;
2711 bool CopyFromStr = isMemSrcFromString(Src, Str, SrcOff);
2713 SmallVector<SDOperand, 8> OutChains;
2714 unsigned NumMemOps = MemOps.size();
2715 for (unsigned i = 0; i < NumMemOps; i++) {
2716 MVT::ValueType VT = MemOps[i];
2717 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2718 SDOperand Value, Store;
2720 if (CopyFromStr && !MVT::isVector(VT)) {
2721 // It's unlikely a store of a vector immediate can be done in a single
2722 // instruction. It would require a load from a constantpool first.
2723 // FIXME: Handle cases where store of vector immediate is done in a
2724 // single instruction.
2725 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2726 Store = DAG.getStore(Chain, Value,
2727 getMemBasePlusOffset(Dst, DstOff, DAG),
2728 DstSV, DstSVOff + DstOff);
2730 Value = DAG.getLoad(VT, Chain,
2731 getMemBasePlusOffset(Src, SrcOff, DAG),
2732 SrcSV, SrcSVOff + SrcOff, false, Align);
2733 Store = DAG.getStore(Chain, Value,
2734 getMemBasePlusOffset(Dst, DstOff, DAG),
2735 DstSV, DstSVOff + DstOff, false, DstAlign);
2737 OutChains.push_back(Store);
2742 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2743 &OutChains[0], OutChains.size());
2746 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2747 SDOperand Chain, SDOperand Dst,
2748 SDOperand Src, uint64_t Size,
2749 unsigned Align, bool AlwaysInline,
2750 const Value *DstSV, uint64_t DstSVOff,
2751 const Value *SrcSV, uint64_t SrcSVOff){
2752 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2754 // Expand memmove to a series of load and store ops if the size operand falls
2755 // below a certain threshold.
2756 std::vector<MVT::ValueType> MemOps;
2757 uint64_t Limit = -1;
2759 Limit = TLI.getMaxStoresPerMemmove();
2760 unsigned DstAlign = Align; // Destination alignment can change.
2761 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2765 uint64_t SrcOff = 0, DstOff = 0;
2767 SmallVector<SDOperand, 8> LoadValues;
2768 SmallVector<SDOperand, 8> LoadChains;
2769 SmallVector<SDOperand, 8> OutChains;
2770 unsigned NumMemOps = MemOps.size();
2771 for (unsigned i = 0; i < NumMemOps; i++) {
2772 MVT::ValueType VT = MemOps[i];
2773 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2774 SDOperand Value, Store;
2776 Value = DAG.getLoad(VT, Chain,
2777 getMemBasePlusOffset(Src, SrcOff, DAG),
2778 SrcSV, SrcSVOff + SrcOff, false, Align);
2779 LoadValues.push_back(Value);
2780 LoadChains.push_back(Value.getValue(1));
2783 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2784 &LoadChains[0], LoadChains.size());
2786 for (unsigned i = 0; i < NumMemOps; i++) {
2787 MVT::ValueType VT = MemOps[i];
2788 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2789 SDOperand Value, Store;
2791 Store = DAG.getStore(Chain, LoadValues[i],
2792 getMemBasePlusOffset(Dst, DstOff, DAG),
2793 DstSV, DstSVOff + DstOff, false, DstAlign);
2794 OutChains.push_back(Store);
2798 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2799 &OutChains[0], OutChains.size());
2802 static SDOperand getMemsetStores(SelectionDAG &DAG,
2803 SDOperand Chain, SDOperand Dst,
2804 SDOperand Src, uint64_t Size,
2806 const Value *DstSV, uint64_t DstSVOff) {
2807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2809 // Expand memset to a series of load/store ops if the size operand
2810 // falls below a certain threshold.
2811 std::vector<MVT::ValueType> MemOps;
2812 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2813 Size, Align, DAG, TLI))
2816 SmallVector<SDOperand, 8> OutChains;
2817 uint64_t DstOff = 0;
2819 unsigned NumMemOps = MemOps.size();
2820 for (unsigned i = 0; i < NumMemOps; i++) {
2821 MVT::ValueType VT = MemOps[i];
2822 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2823 SDOperand Value = getMemsetValue(Src, VT, DAG);
2824 SDOperand Store = DAG.getStore(Chain, Value,
2825 getMemBasePlusOffset(Dst, DstOff, DAG),
2826 DstSV, DstSVOff + DstOff);
2827 OutChains.push_back(Store);
2831 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2832 &OutChains[0], OutChains.size());
2835 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2836 SDOperand Src, SDOperand Size,
2837 unsigned Align, bool AlwaysInline,
2838 const Value *DstSV, uint64_t DstSVOff,
2839 const Value *SrcSV, uint64_t SrcSVOff) {
2841 // Check to see if we should lower the memcpy to loads and stores first.
2842 // For cases within the target-specified limits, this is the best choice.
2843 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2845 // Memcpy with size zero? Just return the original chain.
2846 if (ConstantSize->isNullValue())
2850 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2851 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2856 // Then check to see if we should lower the memcpy with target-specific
2857 // code. If the target chooses to do this, this is the next best.
2859 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2861 DstSV, DstSVOff, SrcSV, SrcSVOff);
2865 // If we really need inline code and the target declined to provide it,
2866 // use a (potentially long) sequence of loads and stores.
2868 assert(ConstantSize && "AlwaysInline requires a constant size!");
2869 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2870 ConstantSize->getValue(), Align, true,
2871 DstSV, DstSVOff, SrcSV, SrcSVOff);
2874 // Emit a library call.
2875 TargetLowering::ArgListTy Args;
2876 TargetLowering::ArgListEntry Entry;
2877 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2878 Entry.Node = Dst; Args.push_back(Entry);
2879 Entry.Node = Src; Args.push_back(Entry);
2880 Entry.Node = Size; Args.push_back(Entry);
2881 std::pair<SDOperand,SDOperand> CallResult =
2882 TLI.LowerCallTo(Chain, Type::VoidTy,
2883 false, false, false, CallingConv::C, false,
2884 getExternalSymbol("memcpy", TLI.getPointerTy()),
2886 return CallResult.second;
2889 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2890 SDOperand Src, SDOperand Size,
2892 const Value *DstSV, uint64_t DstSVOff,
2893 const Value *SrcSV, uint64_t SrcSVOff) {
2895 // Check to see if we should lower the memmove to loads and stores first.
2896 // For cases within the target-specified limits, this is the best choice.
2897 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2899 // Memmove with size zero? Just return the original chain.
2900 if (ConstantSize->isNullValue())
2904 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2905 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2910 // Then check to see if we should lower the memmove with target-specific
2911 // code. If the target chooses to do this, this is the next best.
2913 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2914 DstSV, DstSVOff, SrcSV, SrcSVOff);
2918 // Emit a library call.
2919 TargetLowering::ArgListTy Args;
2920 TargetLowering::ArgListEntry Entry;
2921 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2922 Entry.Node = Dst; Args.push_back(Entry);
2923 Entry.Node = Src; Args.push_back(Entry);
2924 Entry.Node = Size; Args.push_back(Entry);
2925 std::pair<SDOperand,SDOperand> CallResult =
2926 TLI.LowerCallTo(Chain, Type::VoidTy,
2927 false, false, false, CallingConv::C, false,
2928 getExternalSymbol("memmove", TLI.getPointerTy()),
2930 return CallResult.second;
2933 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2934 SDOperand Src, SDOperand Size,
2936 const Value *DstSV, uint64_t DstSVOff) {
2938 // Check to see if we should lower the memset to stores first.
2939 // For cases within the target-specified limits, this is the best choice.
2940 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2942 // Memset with size zero? Just return the original chain.
2943 if (ConstantSize->isNullValue())
2947 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
2953 // Then check to see if we should lower the memset with target-specific
2954 // code. If the target chooses to do this, this is the next best.
2956 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
2961 // Emit a library call.
2962 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
2963 TargetLowering::ArgListTy Args;
2964 TargetLowering::ArgListEntry Entry;
2965 Entry.Node = Dst; Entry.Ty = IntPtrTy;
2966 Args.push_back(Entry);
2967 // Extend or truncate the argument to be an i32 value for the call.
2968 if (Src.getValueType() > MVT::i32)
2969 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
2971 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
2972 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
2973 Args.push_back(Entry);
2974 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
2975 Args.push_back(Entry);
2976 std::pair<SDOperand,SDOperand> CallResult =
2977 TLI.LowerCallTo(Chain, Type::VoidTy,
2978 false, false, false, CallingConv::C, false,
2979 getExternalSymbol("memset", TLI.getPointerTy()),
2981 return CallResult.second;
2984 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
2985 SDOperand Ptr, SDOperand Cmp,
2986 SDOperand Swp, MVT::ValueType VT) {
2987 assert(Opcode == ISD::ATOMIC_LCS && "Invalid Atomic Op");
2988 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
2989 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
2990 FoldingSetNodeID ID;
2991 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
2992 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
2993 ID.AddInteger((unsigned int)VT);
2995 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2996 return SDOperand(E, 0);
2997 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, VT);
2998 CSEMap.InsertNode(N, IP);
2999 AllNodes.push_back(N);
3000 return SDOperand(N, 0);
3003 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3004 SDOperand Ptr, SDOperand Val,
3005 MVT::ValueType VT) {
3006 assert(( Opcode == ISD::ATOMIC_LAS || Opcode == ISD::ATOMIC_LSS
3007 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3008 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3009 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3010 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3011 && "Invalid Atomic Op");
3012 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3013 FoldingSetNodeID ID;
3014 SDOperand Ops[] = {Chain, Ptr, Val};
3015 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3016 ID.AddInteger((unsigned int)VT);
3018 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3019 return SDOperand(E, 0);
3020 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, VT);
3021 CSEMap.InsertNode(N, IP);
3022 AllNodes.push_back(N);
3023 return SDOperand(N, 0);
3027 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3028 MVT::ValueType VT, SDOperand Chain,
3029 SDOperand Ptr, SDOperand Offset,
3030 const Value *SV, int SVOffset, MVT::ValueType EVT,
3031 bool isVolatile, unsigned Alignment) {
3032 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3034 if (VT != MVT::iPTR) {
3035 Ty = MVT::getTypeForValueType(VT);
3037 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3038 assert(PT && "Value for load must be a pointer");
3039 Ty = PT->getElementType();
3041 assert(Ty && "Could not get type information for load");
3042 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3046 ExtType = ISD::NON_EXTLOAD;
3047 } else if (ExtType == ISD::NON_EXTLOAD) {
3048 assert(VT == EVT && "Non-extending load from different memory type!");
3051 if (MVT::isVector(VT))
3052 assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
3054 assert(MVT::getSizeInBits(EVT) < MVT::getSizeInBits(VT) &&
3055 "Should only be an extending load, not truncating!");
3056 assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
3057 "Cannot sign/zero extend a FP/Vector load!");
3058 assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
3059 "Cannot convert from FP to Int or Int -> FP!");
3062 bool Indexed = AM != ISD::UNINDEXED;
3063 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3064 "Unindexed load with an offset!");
3066 SDVTList VTs = Indexed ?
3067 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3068 SDOperand Ops[] = { Chain, Ptr, Offset };
3069 FoldingSetNodeID ID;
3070 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3072 ID.AddInteger(ExtType);
3073 ID.AddInteger((unsigned int)EVT);
3074 ID.AddInteger(Alignment);
3075 ID.AddInteger(isVolatile);
3077 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3078 return SDOperand(E, 0);
3079 SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3080 Alignment, isVolatile);
3081 CSEMap.InsertNode(N, IP);
3082 AllNodes.push_back(N);
3083 return SDOperand(N, 0);
3086 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
3087 SDOperand Chain, SDOperand Ptr,
3088 const Value *SV, int SVOffset,
3089 bool isVolatile, unsigned Alignment) {
3090 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3091 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3092 SV, SVOffset, VT, isVolatile, Alignment);
3095 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
3096 SDOperand Chain, SDOperand Ptr,
3098 int SVOffset, MVT::ValueType EVT,
3099 bool isVolatile, unsigned Alignment) {
3100 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3101 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3102 SV, SVOffset, EVT, isVolatile, Alignment);
3106 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3107 SDOperand Offset, ISD::MemIndexedMode AM) {
3108 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3109 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3110 "Load is already a indexed load!");
3111 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3112 LD->getChain(), Base, Offset, LD->getSrcValue(),
3113 LD->getSrcValueOffset(), LD->getMemoryVT(),
3114 LD->isVolatile(), LD->getAlignment());
3117 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3118 SDOperand Ptr, const Value *SV, int SVOffset,
3119 bool isVolatile, unsigned Alignment) {
3120 MVT::ValueType VT = Val.getValueType();
3122 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3124 if (VT != MVT::iPTR) {
3125 Ty = MVT::getTypeForValueType(VT);
3127 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3128 assert(PT && "Value for store must be a pointer");
3129 Ty = PT->getElementType();
3131 assert(Ty && "Could not get type information for store");
3132 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3134 SDVTList VTs = getVTList(MVT::Other);
3135 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3136 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3137 FoldingSetNodeID ID;
3138 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3139 ID.AddInteger(ISD::UNINDEXED);
3140 ID.AddInteger(false);
3141 ID.AddInteger((unsigned int)VT);
3142 ID.AddInteger(Alignment);
3143 ID.AddInteger(isVolatile);
3145 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3146 return SDOperand(E, 0);
3147 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3148 VT, SV, SVOffset, Alignment, isVolatile);
3149 CSEMap.InsertNode(N, IP);
3150 AllNodes.push_back(N);
3151 return SDOperand(N, 0);
3154 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3155 SDOperand Ptr, const Value *SV,
3156 int SVOffset, MVT::ValueType SVT,
3157 bool isVolatile, unsigned Alignment) {
3158 MVT::ValueType VT = Val.getValueType();
3161 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3163 assert(MVT::getSizeInBits(VT) > MVT::getSizeInBits(SVT) &&
3164 "Not a truncation?");
3165 assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
3166 "Can't do FP-INT conversion!");
3168 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3170 if (VT != MVT::iPTR) {
3171 Ty = MVT::getTypeForValueType(VT);
3173 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3174 assert(PT && "Value for store must be a pointer");
3175 Ty = PT->getElementType();
3177 assert(Ty && "Could not get type information for store");
3178 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3180 SDVTList VTs = getVTList(MVT::Other);
3181 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3182 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3183 FoldingSetNodeID ID;
3184 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3185 ID.AddInteger(ISD::UNINDEXED);
3187 ID.AddInteger((unsigned int)SVT);
3188 ID.AddInteger(Alignment);
3189 ID.AddInteger(isVolatile);
3191 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3192 return SDOperand(E, 0);
3193 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3194 SVT, SV, SVOffset, Alignment, isVolatile);
3195 CSEMap.InsertNode(N, IP);
3196 AllNodes.push_back(N);
3197 return SDOperand(N, 0);
3201 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3202 SDOperand Offset, ISD::MemIndexedMode AM) {
3203 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3204 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3205 "Store is already a indexed store!");
3206 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3207 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3208 FoldingSetNodeID ID;
3209 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3211 ID.AddInteger(ST->isTruncatingStore());
3212 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
3213 ID.AddInteger(ST->getAlignment());
3214 ID.AddInteger(ST->isVolatile());
3216 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3217 return SDOperand(E, 0);
3218 SDNode *N = new StoreSDNode(Ops, VTs, AM,
3219 ST->isTruncatingStore(), ST->getMemoryVT(),
3220 ST->getSrcValue(), ST->getSrcValueOffset(),
3221 ST->getAlignment(), ST->isVolatile());
3222 CSEMap.InsertNode(N, IP);
3223 AllNodes.push_back(N);
3224 return SDOperand(N, 0);
3227 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
3228 SDOperand Chain, SDOperand Ptr,
3230 SDOperand Ops[] = { Chain, Ptr, SV };
3231 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3234 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
3235 SDOperandPtr Ops, unsigned NumOps) {
3237 case 0: return getNode(Opcode, VT);
3238 case 1: return getNode(Opcode, VT, Ops[0]);
3239 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3240 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3246 case ISD::SELECT_CC: {
3247 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3248 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3249 "LHS and RHS of condition must have same type!");
3250 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3251 "True and False arms of SelectCC must have same type!");
3252 assert(Ops[2].getValueType() == VT &&
3253 "select_cc node must be of same type as true and false value!");
3257 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3258 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3259 "LHS/RHS of comparison should match types!");
3266 SDVTList VTs = getVTList(VT);
3267 if (VT != MVT::Flag) {
3268 FoldingSetNodeID ID;
3269 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3271 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3272 return SDOperand(E, 0);
3273 N = new SDNode(Opcode, VTs, Ops, NumOps);
3274 CSEMap.InsertNode(N, IP);
3276 N = new SDNode(Opcode, VTs, Ops, NumOps);
3278 AllNodes.push_back(N);
3279 return SDOperand(N, 0);
3282 SDOperand SelectionDAG::getNode(unsigned Opcode,
3283 std::vector<MVT::ValueType> &ResultTys,
3284 SDOperandPtr Ops, unsigned NumOps) {
3285 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3289 SDOperand SelectionDAG::getNode(unsigned Opcode,
3290 const MVT::ValueType *VTs, unsigned NumVTs,
3291 SDOperandPtr Ops, unsigned NumOps) {
3293 return getNode(Opcode, VTs[0], Ops, NumOps);
3294 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3297 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3298 SDOperandPtr Ops, unsigned NumOps) {
3299 if (VTList.NumVTs == 1)
3300 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3303 // FIXME: figure out how to safely handle things like
3304 // int foo(int x) { return 1 << (x & 255); }
3305 // int bar() { return foo(256); }
3307 case ISD::SRA_PARTS:
3308 case ISD::SRL_PARTS:
3309 case ISD::SHL_PARTS:
3310 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3311 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3312 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3313 else if (N3.getOpcode() == ISD::AND)
3314 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3315 // If the and is only masking out bits that cannot effect the shift,
3316 // eliminate the and.
3317 unsigned NumBits = MVT::getSizeInBits(VT)*2;
3318 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3319 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3325 // Memoize the node unless it returns a flag.
3327 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3328 FoldingSetNodeID ID;
3329 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3331 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3332 return SDOperand(E, 0);
3334 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3335 else if (NumOps == 2)
3336 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3337 else if (NumOps == 3)
3338 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3340 N = new SDNode(Opcode, VTList, Ops, NumOps);
3341 CSEMap.InsertNode(N, IP);
3344 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3345 else if (NumOps == 2)
3346 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3347 else if (NumOps == 3)
3348 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3350 N = new SDNode(Opcode, VTList, Ops, NumOps);
3352 AllNodes.push_back(N);
3353 return SDOperand(N, 0);
3356 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3357 return getNode(Opcode, VTList, (SDOperand*)0, 0);
3360 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3362 SDOperand Ops[] = { N1 };
3363 return getNode(Opcode, VTList, Ops, 1);
3366 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3367 SDOperand N1, SDOperand N2) {
3368 SDOperand Ops[] = { N1, N2 };
3369 return getNode(Opcode, VTList, Ops, 2);
3372 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3373 SDOperand N1, SDOperand N2, SDOperand N3) {
3374 SDOperand Ops[] = { N1, N2, N3 };
3375 return getNode(Opcode, VTList, Ops, 3);
3378 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3379 SDOperand N1, SDOperand N2, SDOperand N3,
3381 SDOperand Ops[] = { N1, N2, N3, N4 };
3382 return getNode(Opcode, VTList, Ops, 4);
3385 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3386 SDOperand N1, SDOperand N2, SDOperand N3,
3387 SDOperand N4, SDOperand N5) {
3388 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3389 return getNode(Opcode, VTList, Ops, 5);
3392 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
3393 return makeVTList(SDNode::getValueTypeList(VT), 1);
3396 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
3397 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
3398 E = VTList.end(); I != E; ++I) {
3399 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3400 return makeVTList(&(*I)[0], 2);
3402 std::vector<MVT::ValueType> V;
3405 VTList.push_front(V);
3406 return makeVTList(&(*VTList.begin())[0], 2);
3408 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
3409 MVT::ValueType VT3) {
3410 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
3411 E = VTList.end(); I != E; ++I) {
3412 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3414 return makeVTList(&(*I)[0], 3);
3416 std::vector<MVT::ValueType> V;
3420 VTList.push_front(V);
3421 return makeVTList(&(*VTList.begin())[0], 3);
3424 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
3426 case 0: assert(0 && "Cannot have nodes without results!");
3427 case 1: return getVTList(VTs[0]);
3428 case 2: return getVTList(VTs[0], VTs[1]);
3429 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3433 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
3434 E = VTList.end(); I != E; ++I) {
3435 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3437 bool NoMatch = false;
3438 for (unsigned i = 2; i != NumVTs; ++i)
3439 if (VTs[i] != (*I)[i]) {
3444 return makeVTList(&*I->begin(), NumVTs);
3447 VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
3448 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3452 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3453 /// specified operands. If the resultant node already exists in the DAG,
3454 /// this does not modify the specified node, instead it returns the node that
3455 /// already exists. If the resultant node does not exist in the DAG, the
3456 /// input node is returned. As a degenerate case, if you specify the same
3457 /// input operands as the node already has, the input node is returned.
3458 SDOperand SelectionDAG::
3459 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3460 SDNode *N = InN.Val;
3461 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3463 // Check to see if there is no change.
3464 if (Op == N->getOperand(0)) return InN;
3466 // See if the modified node already exists.
3467 void *InsertPos = 0;
3468 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3469 return SDOperand(Existing, InN.ResNo);
3471 // Nope it doesn't. Remove the node from it's current place in the maps.
3473 RemoveNodeFromCSEMaps(N);
3475 // Now we update the operands.
3476 N->OperandList[0].getVal()->removeUser(0, N);
3477 N->OperandList[0] = Op;
3478 N->OperandList[0].setUser(N);
3479 Op.Val->addUser(0, N);
3481 // If this gets put into a CSE map, add it.
3482 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3486 SDOperand SelectionDAG::
3487 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3488 SDNode *N = InN.Val;
3489 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3491 // Check to see if there is no change.
3492 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3493 return InN; // No operands changed, just return the input node.
3495 // See if the modified node already exists.
3496 void *InsertPos = 0;
3497 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3498 return SDOperand(Existing, InN.ResNo);
3500 // Nope it doesn't. Remove the node from it's current place in the maps.
3502 RemoveNodeFromCSEMaps(N);
3504 // Now we update the operands.
3505 if (N->OperandList[0] != Op1) {
3506 N->OperandList[0].getVal()->removeUser(0, N);
3507 N->OperandList[0] = Op1;
3508 N->OperandList[0].setUser(N);
3509 Op1.Val->addUser(0, N);
3511 if (N->OperandList[1] != Op2) {
3512 N->OperandList[1].getVal()->removeUser(1, N);
3513 N->OperandList[1] = Op2;
3514 N->OperandList[1].setUser(N);
3515 Op2.Val->addUser(1, N);
3518 // If this gets put into a CSE map, add it.
3519 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3523 SDOperand SelectionDAG::
3524 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3525 SDOperand Ops[] = { Op1, Op2, Op3 };
3526 return UpdateNodeOperands(N, Ops, 3);
3529 SDOperand SelectionDAG::
3530 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3531 SDOperand Op3, SDOperand Op4) {
3532 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3533 return UpdateNodeOperands(N, Ops, 4);
3536 SDOperand SelectionDAG::
3537 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3538 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3539 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3540 return UpdateNodeOperands(N, Ops, 5);
3543 SDOperand SelectionDAG::
3544 UpdateNodeOperands(SDOperand InN, SDOperandPtr Ops, unsigned NumOps) {
3545 SDNode *N = InN.Val;
3546 assert(N->getNumOperands() == NumOps &&
3547 "Update with wrong number of operands");
3549 // Check to see if there is no change.
3550 bool AnyChange = false;
3551 for (unsigned i = 0; i != NumOps; ++i) {
3552 if (Ops[i] != N->getOperand(i)) {
3558 // No operands changed, just return the input node.
3559 if (!AnyChange) return InN;
3561 // See if the modified node already exists.
3562 void *InsertPos = 0;
3563 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3564 return SDOperand(Existing, InN.ResNo);
3566 // Nope it doesn't. Remove the node from its current place in the maps.
3568 RemoveNodeFromCSEMaps(N);
3570 // Now we update the operands.
3571 for (unsigned i = 0; i != NumOps; ++i) {
3572 if (N->OperandList[i] != Ops[i]) {
3573 N->OperandList[i].getVal()->removeUser(i, N);
3574 N->OperandList[i] = Ops[i];
3575 N->OperandList[i].setUser(N);
3576 Ops[i].Val->addUser(i, N);
3580 // If this gets put into a CSE map, add it.
3581 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3585 /// MorphNodeTo - This frees the operands of the current node, resets the
3586 /// opcode, types, and operands to the specified value. This should only be
3587 /// used by the SelectionDAG class.
3588 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3589 SDOperandPtr Ops, unsigned NumOps) {
3592 NumValues = L.NumVTs;
3594 // Clear the operands list, updating used nodes to remove this from their
3596 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3597 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3599 // If NumOps is larger than the # of operands we currently have, reallocate
3600 // the operand list.
3601 if (NumOps > NumOperands) {
3602 if (OperandsNeedDelete) {
3603 delete [] OperandList;
3605 OperandList = new SDUse[NumOps];
3606 OperandsNeedDelete = true;
3609 // Assign the new operands.
3610 NumOperands = NumOps;
3612 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3613 OperandList[i] = Ops[i];
3614 OperandList[i].setUser(this);
3615 SDNode *N = OperandList[i].getVal();
3616 N->addUser(i, this);
3621 /// SelectNodeTo - These are used for target selectors to *mutate* the
3622 /// specified node to have the specified return type, Target opcode, and
3623 /// operands. Note that target opcodes are stored as
3624 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3626 /// Note that SelectNodeTo returns the resultant node. If there is already a
3627 /// node of the specified opcode and operands, it returns that node instead of
3628 /// the current one.
3629 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3630 MVT::ValueType VT) {
3631 SDVTList VTs = getVTList(VT);
3632 FoldingSetNodeID ID;
3633 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, (SDOperand*)0, 0);
3635 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3638 RemoveNodeFromCSEMaps(N);
3640 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, SDOperandPtr(), 0);
3642 CSEMap.InsertNode(N, IP);
3646 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3647 MVT::ValueType VT, SDOperand Op1) {
3648 // If an identical node already exists, use it.
3649 SDVTList VTs = getVTList(VT);
3650 SDOperand Ops[] = { Op1 };
3652 FoldingSetNodeID ID;
3653 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3655 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3658 RemoveNodeFromCSEMaps(N);
3659 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3660 CSEMap.InsertNode(N, IP);
3664 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3665 MVT::ValueType VT, SDOperand Op1,
3667 // If an identical node already exists, use it.
3668 SDVTList VTs = getVTList(VT);
3669 SDOperand Ops[] = { Op1, Op2 };
3671 FoldingSetNodeID ID;
3672 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3674 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3677 RemoveNodeFromCSEMaps(N);
3679 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3681 CSEMap.InsertNode(N, IP); // Memoize the new node.
3685 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3686 MVT::ValueType VT, SDOperand Op1,
3687 SDOperand Op2, SDOperand Op3) {
3688 // If an identical node already exists, use it.
3689 SDVTList VTs = getVTList(VT);
3690 SDOperand Ops[] = { Op1, Op2, Op3 };
3691 FoldingSetNodeID ID;
3692 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3694 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3697 RemoveNodeFromCSEMaps(N);
3699 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3701 CSEMap.InsertNode(N, IP); // Memoize the new node.
3705 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3706 MVT::ValueType VT, SDOperandPtr Ops,
3708 // If an identical node already exists, use it.
3709 SDVTList VTs = getVTList(VT);
3710 FoldingSetNodeID ID;
3711 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3713 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3716 RemoveNodeFromCSEMaps(N);
3717 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3719 CSEMap.InsertNode(N, IP); // Memoize the new node.
3723 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3724 MVT::ValueType VT1, MVT::ValueType VT2,
3725 SDOperand Op1, SDOperand Op2) {
3726 SDVTList VTs = getVTList(VT1, VT2);
3727 FoldingSetNodeID ID;
3728 SDOperand Ops[] = { Op1, Op2 };
3729 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3731 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3734 RemoveNodeFromCSEMaps(N);
3735 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3736 CSEMap.InsertNode(N, IP); // Memoize the new node.
3740 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3741 MVT::ValueType VT1, MVT::ValueType VT2,
3742 SDOperand Op1, SDOperand Op2,
3744 // If an identical node already exists, use it.
3745 SDVTList VTs = getVTList(VT1, VT2);
3746 SDOperand Ops[] = { Op1, Op2, Op3 };
3747 FoldingSetNodeID ID;
3748 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3750 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3753 RemoveNodeFromCSEMaps(N);
3755 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3756 CSEMap.InsertNode(N, IP); // Memoize the new node.
3761 /// getTargetNode - These are used for target selectors to create a new node
3762 /// with specified return type(s), target opcode, and operands.
3764 /// Note that getTargetNode returns the resultant node. If there is already a
3765 /// node of the specified opcode and operands, it returns that node instead of
3766 /// the current one.
3767 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
3768 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3770 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3772 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3774 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3775 SDOperand Op1, SDOperand Op2) {
3776 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3778 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3779 SDOperand Op1, SDOperand Op2,
3781 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3783 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3784 SDOperandPtr Ops, unsigned NumOps) {
3785 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3787 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3788 MVT::ValueType VT2) {
3789 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3791 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3793 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3794 MVT::ValueType VT2, SDOperand Op1) {
3795 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3796 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3798 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3799 MVT::ValueType VT2, SDOperand Op1,
3801 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3802 SDOperand Ops[] = { Op1, Op2 };
3803 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3805 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3806 MVT::ValueType VT2, SDOperand Op1,
3807 SDOperand Op2, SDOperand Op3) {
3808 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3809 SDOperand Ops[] = { Op1, Op2, Op3 };
3810 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3812 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3814 SDOperandPtr Ops, unsigned NumOps) {
3815 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3816 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3818 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3819 MVT::ValueType VT2, MVT::ValueType VT3,
3820 SDOperand Op1, SDOperand Op2) {
3821 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3822 SDOperand Ops[] = { Op1, Op2 };
3823 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3825 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3826 MVT::ValueType VT2, MVT::ValueType VT3,
3827 SDOperand Op1, SDOperand Op2,
3829 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3830 SDOperand Ops[] = { Op1, Op2, Op3 };
3831 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3833 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3834 MVT::ValueType VT2, MVT::ValueType VT3,
3835 SDOperandPtr Ops, unsigned NumOps) {
3836 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3837 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3839 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3840 MVT::ValueType VT2, MVT::ValueType VT3,
3842 SDOperandPtr Ops, unsigned NumOps) {
3843 std::vector<MVT::ValueType> VTList;
3844 VTList.push_back(VT1);
3845 VTList.push_back(VT2);
3846 VTList.push_back(VT3);
3847 VTList.push_back(VT4);
3848 const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3849 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3851 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3852 std::vector<MVT::ValueType> &ResultTys,
3853 SDOperandPtr Ops, unsigned NumOps) {
3854 const MVT::ValueType *VTs = getNodeValueTypes(ResultTys);
3855 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3859 /// getNodeIfExists - Get the specified node if it's already available, or
3860 /// else return NULL.
3861 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3862 SDOperandPtr Ops, unsigned NumOps) {
3863 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3864 FoldingSetNodeID ID;
3865 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3867 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3874 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3875 /// This can cause recursive merging of nodes in the DAG.
3877 /// This version assumes From has a single result value.
3879 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3880 DAGUpdateListener *UpdateListener) {
3881 SDNode *From = FromN.Val;
3882 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3883 "Cannot replace with this method!");
3884 assert(From != To.Val && "Cannot replace uses of with self");
3886 while (!From->use_empty()) {
3887 SDNode::use_iterator UI = From->use_begin();
3888 SDNode *U = UI->getUser();
3890 // This node is about to morph, remove its old self from the CSE maps.
3891 RemoveNodeFromCSEMaps(U);
3893 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3894 I != E; ++I, ++operandNum)
3895 if (I->getVal() == From) {
3896 From->removeUser(operandNum, U);
3899 To.Val->addUser(operandNum, U);
3902 // Now that we have modified U, add it back to the CSE maps. If it already
3903 // exists there, recursively merge the results together.
3904 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3905 ReplaceAllUsesWith(U, Existing, UpdateListener);
3906 // U is now dead. Inform the listener if it exists and delete it.
3908 UpdateListener->NodeDeleted(U);
3909 DeleteNodeNotInCSEMaps(U);
3911 // If the node doesn't already exist, we updated it. Inform a listener if
3914 UpdateListener->NodeUpdated(U);
3919 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3920 /// This can cause recursive merging of nodes in the DAG.
3922 /// This version assumes From/To have matching types and numbers of result
3925 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3926 DAGUpdateListener *UpdateListener) {
3927 assert(From != To && "Cannot replace uses of with self");
3928 assert(From->getNumValues() == To->getNumValues() &&
3929 "Cannot use this version of ReplaceAllUsesWith!");
3930 if (From->getNumValues() == 1) // If possible, use the faster version.
3931 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3934 while (!From->use_empty()) {
3935 SDNode::use_iterator UI = From->use_begin();
3936 SDNode *U = UI->getUser();
3938 // This node is about to morph, remove its old self from the CSE maps.
3939 RemoveNodeFromCSEMaps(U);
3941 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3942 I != E; ++I, ++operandNum)
3943 if (I->getVal() == From) {
3944 From->removeUser(operandNum, U);
3946 To->addUser(operandNum, U);
3949 // Now that we have modified U, add it back to the CSE maps. If it already
3950 // exists there, recursively merge the results together.
3951 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3952 ReplaceAllUsesWith(U, Existing, UpdateListener);
3953 // U is now dead. Inform the listener if it exists and delete it.
3955 UpdateListener->NodeDeleted(U);
3956 DeleteNodeNotInCSEMaps(U);
3958 // If the node doesn't already exist, we updated it. Inform a listener if
3961 UpdateListener->NodeUpdated(U);
3966 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3967 /// This can cause recursive merging of nodes in the DAG.
3969 /// This version can replace From with any result values. To must match the
3970 /// number and types of values returned by From.
3971 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3973 DAGUpdateListener *UpdateListener) {
3974 if (From->getNumValues() == 1) // Handle the simple case efficiently.
3975 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
3977 while (!From->use_empty()) {
3978 SDNode::use_iterator UI = From->use_begin();
3979 SDNode *U = UI->getUser();
3981 // This node is about to morph, remove its old self from the CSE maps.
3982 RemoveNodeFromCSEMaps(U);
3984 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3985 I != E; ++I, ++operandNum)
3986 if (I->getVal() == From) {
3987 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
3988 From->removeUser(operandNum, U);
3991 ToOp.Val->addUser(operandNum, U);
3994 // Now that we have modified U, add it back to the CSE maps. If it already
3995 // exists there, recursively merge the results together.
3996 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3997 ReplaceAllUsesWith(U, Existing, UpdateListener);
3998 // U is now dead. Inform the listener if it exists and delete it.
4000 UpdateListener->NodeDeleted(U);
4001 DeleteNodeNotInCSEMaps(U);
4003 // If the node doesn't already exist, we updated it. Inform a listener if
4006 UpdateListener->NodeUpdated(U);
4012 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4013 /// any deleted nodes from the set passed into its constructor and recursively
4014 /// notifies another update listener if specified.
4015 class ChainedSetUpdaterListener :
4016 public SelectionDAG::DAGUpdateListener {
4017 SmallSetVector<SDNode*, 16> &Set;
4018 SelectionDAG::DAGUpdateListener *Chain;
4020 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4021 SelectionDAG::DAGUpdateListener *chain)
4022 : Set(set), Chain(chain) {}
4024 virtual void NodeDeleted(SDNode *N) {
4026 if (Chain) Chain->NodeDeleted(N);
4028 virtual void NodeUpdated(SDNode *N) {
4029 if (Chain) Chain->NodeUpdated(N);
4034 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4035 /// uses of other values produced by From.Val alone. The Deleted vector is
4036 /// handled the same way as for ReplaceAllUsesWith.
4037 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4038 DAGUpdateListener *UpdateListener){
4039 assert(From != To && "Cannot replace a value with itself");
4041 // Handle the simple, trivial, case efficiently.
4042 if (From.Val->getNumValues() == 1) {
4043 ReplaceAllUsesWith(From, To, UpdateListener);
4047 if (From.use_empty()) return;
4049 // Get all of the users of From.Val. We want these in a nice,
4050 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4051 SmallSetVector<SDNode*, 16> Users;
4052 for (SDNode::use_iterator UI = From.Val->use_begin(),
4053 E = From.Val->use_end(); UI != E; ++UI) {
4054 SDNode *User = UI->getUser();
4055 if (!Users.count(User))
4059 // When one of the recursive merges deletes nodes from the graph, we need to
4060 // make sure that UpdateListener is notified *and* that the node is removed
4061 // from Users if present. CSUL does this.
4062 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4064 while (!Users.empty()) {
4065 // We know that this user uses some value of From. If it is the right
4066 // value, update it.
4067 SDNode *User = Users.back();
4070 // Scan for an operand that matches From.
4071 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4072 for (; Op != E; ++Op)
4073 if (*Op == From) break;
4075 // If there are no matches, the user must use some other result of From.
4076 if (Op == E) continue;
4078 // Okay, we know this user needs to be updated. Remove its old self
4079 // from the CSE maps.
4080 RemoveNodeFromCSEMaps(User);
4082 // Update all operands that match "From" in case there are multiple uses.
4083 for (; Op != E; ++Op) {
4085 From.Val->removeUser(Op-User->op_begin(), User);
4088 To.Val->addUser(Op-User->op_begin(), User);
4092 // Now that we have modified User, add it back to the CSE maps. If it
4093 // already exists there, recursively merge the results together.
4094 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4096 if (UpdateListener) UpdateListener->NodeUpdated(User);
4097 continue; // Continue on to next user.
4100 // If there was already an existing matching node, use ReplaceAllUsesWith
4101 // to replace the dead one with the existing one. This can cause
4102 // recursive merging of other unrelated nodes down the line. The merging
4103 // can cause deletion of nodes that used the old value. To handle this, we
4104 // use CSUL to remove them from the Users set.
4105 ReplaceAllUsesWith(User, Existing, &CSUL);
4107 // User is now dead. Notify a listener if present.
4108 if (UpdateListener) UpdateListener->NodeDeleted(User);
4109 DeleteNodeNotInCSEMaps(User);
4113 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4114 /// their allnodes order. It returns the maximum id.
4115 unsigned SelectionDAG::AssignNodeIds() {
4117 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4124 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4125 /// based on their topological order. It returns the maximum id and a vector
4126 /// of the SDNodes* in assigned order by reference.
4127 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4128 unsigned DAGSize = AllNodes.size();
4129 std::vector<unsigned> InDegree(DAGSize);
4130 std::vector<SDNode*> Sources;
4132 // Use a two pass approach to avoid using a std::map which is slow.
4134 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4137 unsigned Degree = N->use_size();
4138 InDegree[N->getNodeId()] = Degree;
4140 Sources.push_back(N);
4144 while (!Sources.empty()) {
4145 SDNode *N = Sources.back();
4147 TopOrder.push_back(N);
4148 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4149 SDNode *P = I->getVal();
4150 unsigned Degree = --InDegree[P->getNodeId()];
4152 Sources.push_back(P);
4156 // Second pass, assign the actual topological order as node ids.
4158 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4160 (*TI)->setNodeId(Id++);
4167 //===----------------------------------------------------------------------===//
4169 //===----------------------------------------------------------------------===//
4171 // Out-of-line virtual method to give class a home.
4172 void SDNode::ANCHOR() {}
4173 void UnarySDNode::ANCHOR() {}
4174 void BinarySDNode::ANCHOR() {}
4175 void TernarySDNode::ANCHOR() {}
4176 void HandleSDNode::ANCHOR() {}
4177 void StringSDNode::ANCHOR() {}
4178 void ConstantSDNode::ANCHOR() {}
4179 void ConstantFPSDNode::ANCHOR() {}
4180 void GlobalAddressSDNode::ANCHOR() {}
4181 void FrameIndexSDNode::ANCHOR() {}
4182 void JumpTableSDNode::ANCHOR() {}
4183 void ConstantPoolSDNode::ANCHOR() {}
4184 void BasicBlockSDNode::ANCHOR() {}
4185 void SrcValueSDNode::ANCHOR() {}
4186 void MemOperandSDNode::ANCHOR() {}
4187 void RegisterSDNode::ANCHOR() {}
4188 void ExternalSymbolSDNode::ANCHOR() {}
4189 void CondCodeSDNode::ANCHOR() {}
4190 void ARG_FLAGSSDNode::ANCHOR() {}
4191 void VTSDNode::ANCHOR() {}
4192 void LoadSDNode::ANCHOR() {}
4193 void StoreSDNode::ANCHOR() {}
4194 void AtomicSDNode::ANCHOR() {}
4196 HandleSDNode::~HandleSDNode() {
4197 SDVTList VTs = { 0, 0 };
4198 MorphNodeTo(ISD::HANDLENODE, VTs, SDOperandPtr(), 0); // Drops operand uses.
4201 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4202 MVT::ValueType VT, int o)
4203 : SDNode(isa<GlobalVariable>(GA) &&
4204 cast<GlobalVariable>(GA)->isThreadLocal() ?
4206 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4208 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4209 getSDVTList(VT)), Offset(o) {
4210 TheGlobal = const_cast<GlobalValue*>(GA);
4213 /// getMemOperand - Return a MachineMemOperand object describing the memory
4214 /// reference performed by this load or store.
4215 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4216 int Size = (MVT::getSizeInBits(getMemoryVT()) + 7) >> 3;
4218 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4219 MachineMemOperand::MOStore;
4220 if (IsVolatile) Flags |= MachineMemOperand::MOVolatile;
4222 // Check if the load references a frame index, and does not have
4224 const FrameIndexSDNode *FI =
4225 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4226 if (!getSrcValue() && FI)
4227 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4228 FI->getIndex(), Size, Alignment);
4230 return MachineMemOperand(getSrcValue(), Flags,
4231 getSrcValueOffset(), Size, Alignment);
4234 /// Profile - Gather unique data for the node.
4236 void SDNode::Profile(FoldingSetNodeID &ID) {
4237 AddNodeIDNode(ID, this);
4240 /// getValueTypeList - Return a pointer to the specified value type.
4242 const MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
4243 if (MVT::isExtendedVT(VT)) {
4244 static std::set<MVT::ValueType> EVTs;
4245 return &(*EVTs.insert(VT).first);
4247 static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
4253 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4254 /// indicated value. This method ignores uses of other values defined by this
4256 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4257 assert(Value < getNumValues() && "Bad value!");
4259 // If there is only one value, this is easy.
4260 if (getNumValues() == 1)
4261 return use_size() == NUses;
4262 if (use_size() < NUses) return false;
4264 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4266 SmallPtrSet<SDNode*, 32> UsersHandled;
4268 // TODO: Only iterate over uses of a given value of the node
4269 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4270 if (*UI == TheValue) {
4277 // Found exactly the right number of uses?
4282 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4283 /// value. This method ignores uses of other values defined by this operation.
4284 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4285 assert(Value < getNumValues() && "Bad value!");
4287 if (use_empty()) return false;
4289 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4291 SmallPtrSet<SDNode*, 32> UsersHandled;
4293 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4294 SDNode *User = UI->getUser();
4295 if (User->getNumOperands() == 1 ||
4296 UsersHandled.insert(User)) // First time we've seen this?
4297 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4298 if (User->getOperand(i) == TheValue) {
4307 /// isOnlyUseOf - Return true if this node is the only use of N.
4309 bool SDNode::isOnlyUseOf(SDNode *N) const {
4311 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4312 SDNode *User = I->getUser();
4322 /// isOperand - Return true if this node is an operand of N.
4324 bool SDOperand::isOperandOf(SDNode *N) const {
4325 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4326 if (*this == N->getOperand(i))
4331 bool SDNode::isOperandOf(SDNode *N) const {
4332 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4333 if (this == N->OperandList[i].getVal())
4338 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4339 /// be a chain) reaches the specified operand without crossing any
4340 /// side-effecting instructions. In practice, this looks through token
4341 /// factors and non-volatile loads. In order to remain efficient, this only
4342 /// looks a couple of nodes in, it does not do an exhaustive search.
4343 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4344 unsigned Depth) const {
4345 if (*this == Dest) return true;
4347 // Don't search too deeply, we just want to be able to see through
4348 // TokenFactor's etc.
4349 if (Depth == 0) return false;
4351 // If this is a token factor, all inputs to the TF happen in parallel. If any
4352 // of the operands of the TF reach dest, then we can do the xform.
4353 if (getOpcode() == ISD::TokenFactor) {
4354 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4355 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4360 // Loads don't have side effects, look through them.
4361 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4362 if (!Ld->isVolatile())
4363 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4369 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4370 SmallPtrSet<SDNode *, 32> &Visited) {
4371 if (found || !Visited.insert(N))
4374 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4375 SDNode *Op = N->getOperand(i).Val;
4380 findPredecessor(Op, P, found, Visited);
4384 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4385 /// is either an operand of N or it can be reached by recursively traversing
4386 /// up the operands.
4387 /// NOTE: this is an expensive method. Use it carefully.
4388 bool SDNode::isPredecessorOf(SDNode *N) const {
4389 SmallPtrSet<SDNode *, 32> Visited;
4391 findPredecessor(N, this, found, Visited);
4395 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4396 assert(Num < NumOperands && "Invalid child # of SDNode!");
4397 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4400 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4401 switch (getOpcode()) {
4403 if (getOpcode() < ISD::BUILTIN_OP_END)
4404 return "<<Unknown DAG Node>>";
4407 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4408 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4409 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4411 TargetLowering &TLI = G->getTargetLoweringInfo();
4413 TLI.getTargetNodeName(getOpcode());
4414 if (Name) return Name;
4417 return "<<Unknown Target Node>>";
4420 case ISD::PREFETCH: return "Prefetch";
4421 case ISD::MEMBARRIER: return "MemBarrier";
4422 case ISD::ATOMIC_LCS: return "AtomicLCS";
4423 case ISD::ATOMIC_LAS: return "AtomicLAS";
4424 case ISD::ATOMIC_LSS: return "AtomicLSS";
4425 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4426 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4427 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4428 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4429 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4430 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4431 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4432 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4433 case ISD::PCMARKER: return "PCMarker";
4434 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4435 case ISD::SRCVALUE: return "SrcValue";
4436 case ISD::MEMOPERAND: return "MemOperand";
4437 case ISD::EntryToken: return "EntryToken";
4438 case ISD::TokenFactor: return "TokenFactor";
4439 case ISD::AssertSext: return "AssertSext";
4440 case ISD::AssertZext: return "AssertZext";
4442 case ISD::STRING: return "String";
4443 case ISD::BasicBlock: return "BasicBlock";
4444 case ISD::ARG_FLAGS: return "ArgFlags";
4445 case ISD::VALUETYPE: return "ValueType";
4446 case ISD::Register: return "Register";
4448 case ISD::Constant: return "Constant";
4449 case ISD::ConstantFP: return "ConstantFP";
4450 case ISD::GlobalAddress: return "GlobalAddress";
4451 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4452 case ISD::FrameIndex: return "FrameIndex";
4453 case ISD::JumpTable: return "JumpTable";
4454 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4455 case ISD::RETURNADDR: return "RETURNADDR";
4456 case ISD::FRAMEADDR: return "FRAMEADDR";
4457 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4458 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4459 case ISD::EHSELECTION: return "EHSELECTION";
4460 case ISD::EH_RETURN: return "EH_RETURN";
4461 case ISD::ConstantPool: return "ConstantPool";
4462 case ISD::ExternalSymbol: return "ExternalSymbol";
4463 case ISD::INTRINSIC_WO_CHAIN: {
4464 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4465 return Intrinsic::getName((Intrinsic::ID)IID);
4467 case ISD::INTRINSIC_VOID:
4468 case ISD::INTRINSIC_W_CHAIN: {
4469 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4470 return Intrinsic::getName((Intrinsic::ID)IID);
4473 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4474 case ISD::TargetConstant: return "TargetConstant";
4475 case ISD::TargetConstantFP:return "TargetConstantFP";
4476 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4477 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4478 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4479 case ISD::TargetJumpTable: return "TargetJumpTable";
4480 case ISD::TargetConstantPool: return "TargetConstantPool";
4481 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4483 case ISD::CopyToReg: return "CopyToReg";
4484 case ISD::CopyFromReg: return "CopyFromReg";
4485 case ISD::UNDEF: return "undef";
4486 case ISD::MERGE_VALUES: return "merge_values";
4487 case ISD::INLINEASM: return "inlineasm";
4488 case ISD::LABEL: return "label";
4489 case ISD::DECLARE: return "declare";
4490 case ISD::HANDLENODE: return "handlenode";
4491 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4492 case ISD::CALL: return "call";
4495 case ISD::FABS: return "fabs";
4496 case ISD::FNEG: return "fneg";
4497 case ISD::FSQRT: return "fsqrt";
4498 case ISD::FSIN: return "fsin";
4499 case ISD::FCOS: return "fcos";
4500 case ISD::FPOWI: return "fpowi";
4501 case ISD::FPOW: return "fpow";
4504 case ISD::ADD: return "add";
4505 case ISD::SUB: return "sub";
4506 case ISD::MUL: return "mul";
4507 case ISD::MULHU: return "mulhu";
4508 case ISD::MULHS: return "mulhs";
4509 case ISD::SDIV: return "sdiv";
4510 case ISD::UDIV: return "udiv";
4511 case ISD::SREM: return "srem";
4512 case ISD::UREM: return "urem";
4513 case ISD::SMUL_LOHI: return "smul_lohi";
4514 case ISD::UMUL_LOHI: return "umul_lohi";
4515 case ISD::SDIVREM: return "sdivrem";
4516 case ISD::UDIVREM: return "divrem";
4517 case ISD::AND: return "and";
4518 case ISD::OR: return "or";
4519 case ISD::XOR: return "xor";
4520 case ISD::SHL: return "shl";
4521 case ISD::SRA: return "sra";
4522 case ISD::SRL: return "srl";
4523 case ISD::ROTL: return "rotl";
4524 case ISD::ROTR: return "rotr";
4525 case ISD::FADD: return "fadd";
4526 case ISD::FSUB: return "fsub";
4527 case ISD::FMUL: return "fmul";
4528 case ISD::FDIV: return "fdiv";
4529 case ISD::FREM: return "frem";
4530 case ISD::FCOPYSIGN: return "fcopysign";
4531 case ISD::FGETSIGN: return "fgetsign";
4533 case ISD::SETCC: return "setcc";
4534 case ISD::VSETCC: return "vsetcc";
4535 case ISD::SELECT: return "select";
4536 case ISD::SELECT_CC: return "select_cc";
4537 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4538 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4539 case ISD::CONCAT_VECTORS: return "concat_vectors";
4540 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4541 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4542 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4543 case ISD::CARRY_FALSE: return "carry_false";
4544 case ISD::ADDC: return "addc";
4545 case ISD::ADDE: return "adde";
4546 case ISD::SUBC: return "subc";
4547 case ISD::SUBE: return "sube";
4548 case ISD::SHL_PARTS: return "shl_parts";
4549 case ISD::SRA_PARTS: return "sra_parts";
4550 case ISD::SRL_PARTS: return "srl_parts";
4552 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4553 case ISD::INSERT_SUBREG: return "insert_subreg";
4555 // Conversion operators.
4556 case ISD::SIGN_EXTEND: return "sign_extend";
4557 case ISD::ZERO_EXTEND: return "zero_extend";
4558 case ISD::ANY_EXTEND: return "any_extend";
4559 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4560 case ISD::TRUNCATE: return "truncate";
4561 case ISD::FP_ROUND: return "fp_round";
4562 case ISD::FLT_ROUNDS_: return "flt_rounds";
4563 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4564 case ISD::FP_EXTEND: return "fp_extend";
4566 case ISD::SINT_TO_FP: return "sint_to_fp";
4567 case ISD::UINT_TO_FP: return "uint_to_fp";
4568 case ISD::FP_TO_SINT: return "fp_to_sint";
4569 case ISD::FP_TO_UINT: return "fp_to_uint";
4570 case ISD::BIT_CONVERT: return "bit_convert";
4572 // Control flow instructions
4573 case ISD::BR: return "br";
4574 case ISD::BRIND: return "brind";
4575 case ISD::BR_JT: return "br_jt";
4576 case ISD::BRCOND: return "brcond";
4577 case ISD::BR_CC: return "br_cc";
4578 case ISD::RET: return "ret";
4579 case ISD::CALLSEQ_START: return "callseq_start";
4580 case ISD::CALLSEQ_END: return "callseq_end";
4583 case ISD::LOAD: return "load";
4584 case ISD::STORE: return "store";
4585 case ISD::VAARG: return "vaarg";
4586 case ISD::VACOPY: return "vacopy";
4587 case ISD::VAEND: return "vaend";
4588 case ISD::VASTART: return "vastart";
4589 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4590 case ISD::EXTRACT_ELEMENT: return "extract_element";
4591 case ISD::BUILD_PAIR: return "build_pair";
4592 case ISD::STACKSAVE: return "stacksave";
4593 case ISD::STACKRESTORE: return "stackrestore";
4594 case ISD::TRAP: return "trap";
4597 case ISD::BSWAP: return "bswap";
4598 case ISD::CTPOP: return "ctpop";
4599 case ISD::CTTZ: return "cttz";
4600 case ISD::CTLZ: return "ctlz";
4603 case ISD::LOCATION: return "location";
4604 case ISD::DEBUG_LOC: return "debug_loc";
4607 case ISD::TRAMPOLINE: return "trampoline";
4610 switch (cast<CondCodeSDNode>(this)->get()) {
4611 default: assert(0 && "Unknown setcc condition!");
4612 case ISD::SETOEQ: return "setoeq";
4613 case ISD::SETOGT: return "setogt";
4614 case ISD::SETOGE: return "setoge";
4615 case ISD::SETOLT: return "setolt";
4616 case ISD::SETOLE: return "setole";
4617 case ISD::SETONE: return "setone";
4619 case ISD::SETO: return "seto";
4620 case ISD::SETUO: return "setuo";
4621 case ISD::SETUEQ: return "setue";
4622 case ISD::SETUGT: return "setugt";
4623 case ISD::SETUGE: return "setuge";
4624 case ISD::SETULT: return "setult";
4625 case ISD::SETULE: return "setule";
4626 case ISD::SETUNE: return "setune";
4628 case ISD::SETEQ: return "seteq";
4629 case ISD::SETGT: return "setgt";
4630 case ISD::SETGE: return "setge";
4631 case ISD::SETLT: return "setlt";
4632 case ISD::SETLE: return "setle";
4633 case ISD::SETNE: return "setne";
4638 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4647 return "<post-inc>";
4649 return "<post-dec>";
4653 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4654 std::string S = "< ";
4668 if (getByValAlign())
4669 S += "byval-align:" + utostr(getByValAlign()) + " ";
4671 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4673 S += "byval-size:" + utostr(getByValSize()) + " ";
4677 void SDNode::dump() const { dump(0); }
4678 void SDNode::dump(const SelectionDAG *G) const {
4679 cerr << (void*)this << ": ";
4681 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4683 if (getValueType(i) == MVT::Other)
4686 cerr << MVT::getValueTypeString(getValueType(i));
4688 cerr << " = " << getOperationName(G);
4691 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4692 if (i) cerr << ", ";
4693 cerr << (void*)getOperand(i).Val;
4694 if (unsigned RN = getOperand(i).ResNo)
4698 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4699 SDNode *Mask = getOperand(2).Val;
4701 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4703 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4706 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4711 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4712 cerr << "<" << CSDN->getValue() << ">";
4713 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4714 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4715 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4716 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4717 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4719 cerr << "<APFloat(";
4720 CSDN->getValueAPF().convertToAPInt().dump();
4723 } else if (const GlobalAddressSDNode *GADN =
4724 dyn_cast<GlobalAddressSDNode>(this)) {
4725 int offset = GADN->getOffset();
4727 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4729 cerr << " + " << offset;
4731 cerr << " " << offset;
4732 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4733 cerr << "<" << FIDN->getIndex() << ">";
4734 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4735 cerr << "<" << JTDN->getIndex() << ">";
4736 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4737 int offset = CP->getOffset();
4738 if (CP->isMachineConstantPoolEntry())
4739 cerr << "<" << *CP->getMachineCPVal() << ">";
4741 cerr << "<" << *CP->getConstVal() << ">";
4743 cerr << " + " << offset;
4745 cerr << " " << offset;
4746 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4748 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4750 cerr << LBB->getName() << " ";
4751 cerr << (const void*)BBDN->getBasicBlock() << ">";
4752 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4753 if (G && R->getReg() &&
4754 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4755 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4757 cerr << " #" << R->getReg();
4759 } else if (const ExternalSymbolSDNode *ES =
4760 dyn_cast<ExternalSymbolSDNode>(this)) {
4761 cerr << "'" << ES->getSymbol() << "'";
4762 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4764 cerr << "<" << M->getValue() << ">";
4767 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4768 if (M->MO.getValue())
4769 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4771 cerr << "<null:" << M->MO.getOffset() << ">";
4772 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4773 cerr << N->getArgFlags().getArgFlagsString();
4774 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4775 cerr << ":" << MVT::getValueTypeString(N->getVT());
4776 } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4777 const Value *SrcValue = LD->getSrcValue();
4778 int SrcOffset = LD->getSrcValueOffset();
4784 cerr << ":" << SrcOffset << ">";
4787 switch (LD->getExtensionType()) {
4788 default: doExt = false; break;
4790 cerr << " <anyext ";
4800 cerr << MVT::getValueTypeString(LD->getMemoryVT()) << ">";
4802 const char *AM = getIndexedModeName(LD->getAddressingMode());
4805 if (LD->isVolatile())
4806 cerr << " <volatile>";
4807 cerr << " alignment=" << LD->getAlignment();
4808 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4809 const Value *SrcValue = ST->getSrcValue();
4810 int SrcOffset = ST->getSrcValueOffset();
4816 cerr << ":" << SrcOffset << ">";
4818 if (ST->isTruncatingStore())
4820 << MVT::getValueTypeString(ST->getMemoryVT()) << ">";
4822 const char *AM = getIndexedModeName(ST->getAddressingMode());
4825 if (ST->isVolatile())
4826 cerr << " <volatile>";
4827 cerr << " alignment=" << ST->getAlignment();
4831 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4832 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4833 if (N->getOperand(i).Val->hasOneUse())
4834 DumpNodes(N->getOperand(i).Val, indent+2, G);
4836 cerr << "\n" << std::string(indent+2, ' ')
4837 << (void*)N->getOperand(i).Val << ": <multiple use>";
4840 cerr << "\n" << std::string(indent, ' ');
4844 void SelectionDAG::dump() const {
4845 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4846 std::vector<const SDNode*> Nodes;
4847 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4851 std::sort(Nodes.begin(), Nodes.end());
4853 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4854 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4855 DumpNodes(Nodes[i], 2, this);
4858 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4863 const Type *ConstantPoolSDNode::getType() const {
4864 if (isMachineConstantPoolEntry())
4865 return Val.MachineCPVal->getType();
4866 return Val.ConstVal->getType();