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 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/Constants.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/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringExtras.h"
40 /// makeVTList - Return an instance of the SDVTList struct initialized with the
41 /// specified members.
42 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
43 SDVTList Res = {VTs, NumVTs};
47 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
49 //===----------------------------------------------------------------------===//
50 // ConstantFPSDNode Class
51 //===----------------------------------------------------------------------===//
53 /// isExactlyValue - We don't rely on operator== working on double values, as
54 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
55 /// As such, this method can be used to do an exact bit-for-bit comparison of
56 /// two floating point values.
57 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
58 return Value.bitwiseIsEqual(V);
61 bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT,
63 // convert modifies in place, so make a copy.
64 APFloat Val2 = APFloat(Val);
67 return false; // These can't be represented as floating point!
69 // FIXME rounding mode needs to be more flexible
71 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
72 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
75 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
76 &Val2.getSemantics() == &APFloat::IEEEdouble ||
77 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
79 // TODO: Figure out how to test if we can use a shorter type instead!
87 //===----------------------------------------------------------------------===//
89 //===----------------------------------------------------------------------===//
91 /// isBuildVectorAllOnes - Return true if the specified node is a
92 /// BUILD_VECTOR where all of the elements are ~0 or undef.
93 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
94 // Look through a bit convert.
95 if (N->getOpcode() == ISD::BIT_CONVERT)
96 N = N->getOperand(0).Val;
98 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
100 unsigned i = 0, e = N->getNumOperands();
102 // Skip over all of the undef values.
103 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
106 // Do not accept an all-undef vector.
107 if (i == e) return false;
109 // Do not accept build_vectors that aren't all constants or which have non-~0
111 SDOperand NotZero = N->getOperand(i);
112 if (isa<ConstantSDNode>(NotZero)) {
113 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
115 } else if (isa<ConstantFPSDNode>(NotZero)) {
116 MVT::ValueType VT = NotZero.getValueType();
118 if (((cast<ConstantFPSDNode>(NotZero)->getValueAPF().
119 convertToAPInt().getZExtValue())) != (uint64_t)-1)
122 if ((uint32_t)cast<ConstantFPSDNode>(NotZero)->
123 getValueAPF().convertToAPInt().getZExtValue() !=
130 // Okay, we have at least one ~0 value, check to see if the rest match or are
132 for (++i; i != e; ++i)
133 if (N->getOperand(i) != NotZero &&
134 N->getOperand(i).getOpcode() != ISD::UNDEF)
140 /// isBuildVectorAllZeros - Return true if the specified node is a
141 /// BUILD_VECTOR where all of the elements are 0 or undef.
142 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
143 // Look through a bit convert.
144 if (N->getOpcode() == ISD::BIT_CONVERT)
145 N = N->getOperand(0).Val;
147 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
149 unsigned i = 0, e = N->getNumOperands();
151 // Skip over all of the undef values.
152 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
155 // Do not accept an all-undef vector.
156 if (i == e) return false;
158 // Do not accept build_vectors that aren't all constants or which have non-~0
160 SDOperand Zero = N->getOperand(i);
161 if (isa<ConstantSDNode>(Zero)) {
162 if (!cast<ConstantSDNode>(Zero)->isNullValue())
164 } else if (isa<ConstantFPSDNode>(Zero)) {
165 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
170 // Okay, we have at least one ~0 value, check to see if the rest match or are
172 for (++i; i != e; ++i)
173 if (N->getOperand(i) != Zero &&
174 N->getOperand(i).getOpcode() != ISD::UNDEF)
179 /// isDebugLabel - Return true if the specified node represents a debug
180 /// label (i.e. ISD::LABEL or TargetInstrInfo::LABEL node and third operand
182 bool ISD::isDebugLabel(const SDNode *N) {
184 if (N->getOpcode() == ISD::LABEL)
185 Zero = N->getOperand(2);
186 else if (N->isTargetOpcode() &&
187 N->getTargetOpcode() == TargetInstrInfo::LABEL)
188 // Chain moved to last operand.
189 Zero = N->getOperand(1);
192 return isa<ConstantSDNode>(Zero) && cast<ConstantSDNode>(Zero)->isNullValue();
195 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
196 /// when given the operation for (X op Y).
197 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
198 // To perform this operation, we just need to swap the L and G bits of the
200 unsigned OldL = (Operation >> 2) & 1;
201 unsigned OldG = (Operation >> 1) & 1;
202 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
203 (OldL << 1) | // New G bit
204 (OldG << 2)); // New L bit.
207 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
208 /// 'op' is a valid SetCC operation.
209 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
210 unsigned Operation = Op;
212 Operation ^= 7; // Flip L, G, E bits, but not U.
214 Operation ^= 15; // Flip all of the condition bits.
215 if (Operation > ISD::SETTRUE2)
216 Operation &= ~8; // Don't let N and U bits get set.
217 return ISD::CondCode(Operation);
221 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
222 /// signed operation and 2 if the result is an unsigned comparison. Return zero
223 /// if the operation does not depend on the sign of the input (setne and seteq).
224 static int isSignedOp(ISD::CondCode Opcode) {
226 default: assert(0 && "Illegal integer setcc operation!");
228 case ISD::SETNE: return 0;
232 case ISD::SETGE: return 1;
236 case ISD::SETUGE: return 2;
240 /// getSetCCOrOperation - Return the result of a logical OR between different
241 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
242 /// returns SETCC_INVALID if it is not possible to represent the resultant
244 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
246 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
247 // Cannot fold a signed integer setcc with an unsigned integer setcc.
248 return ISD::SETCC_INVALID;
250 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
252 // If the N and U bits get set then the resultant comparison DOES suddenly
253 // care about orderedness, and is true when ordered.
254 if (Op > ISD::SETTRUE2)
255 Op &= ~16; // Clear the U bit if the N bit is set.
257 // Canonicalize illegal integer setcc's.
258 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
261 return ISD::CondCode(Op);
264 /// getSetCCAndOperation - Return the result of a logical AND between different
265 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
266 /// function returns zero if it is not possible to represent the resultant
268 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
270 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
271 // Cannot fold a signed setcc with an unsigned setcc.
272 return ISD::SETCC_INVALID;
274 // Combine all of the condition bits.
275 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
277 // Canonicalize illegal integer setcc's.
281 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
282 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
283 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
284 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
291 const TargetMachine &SelectionDAG::getTarget() const {
292 return TLI.getTargetMachine();
295 //===----------------------------------------------------------------------===//
296 // SDNode Profile Support
297 //===----------------------------------------------------------------------===//
299 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
301 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
305 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
306 /// solely with their pointer.
307 void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
308 ID.AddPointer(VTList.VTs);
311 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
313 static void AddNodeIDOperands(FoldingSetNodeID &ID,
314 const SDOperand *Ops, unsigned NumOps) {
315 for (; NumOps; --NumOps, ++Ops) {
316 ID.AddPointer(Ops->Val);
317 ID.AddInteger(Ops->ResNo);
321 static void AddNodeIDNode(FoldingSetNodeID &ID,
322 unsigned short OpC, SDVTList VTList,
323 const SDOperand *OpList, unsigned N) {
324 AddNodeIDOpcode(ID, OpC);
325 AddNodeIDValueTypes(ID, VTList);
326 AddNodeIDOperands(ID, OpList, N);
329 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
331 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
332 AddNodeIDOpcode(ID, N->getOpcode());
333 // Add the return value info.
334 AddNodeIDValueTypes(ID, N->getVTList());
335 // Add the operand info.
336 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
338 // Handle SDNode leafs with special info.
339 switch (N->getOpcode()) {
340 default: break; // Normal nodes don't need extra info.
341 case ISD::TargetConstant:
343 ID.AddInteger(cast<ConstantSDNode>(N)->getValue());
345 case ISD::TargetConstantFP:
346 case ISD::ConstantFP: {
347 ID.AddAPFloat(cast<ConstantFPSDNode>(N)->getValueAPF());
350 case ISD::TargetGlobalAddress:
351 case ISD::GlobalAddress:
352 case ISD::TargetGlobalTLSAddress:
353 case ISD::GlobalTLSAddress: {
354 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
355 ID.AddPointer(GA->getGlobal());
356 ID.AddInteger(GA->getOffset());
359 case ISD::BasicBlock:
360 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
363 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
366 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
368 case ISD::MEMOPERAND: {
369 const MemOperand &MO = cast<MemOperandSDNode>(N)->MO;
370 ID.AddPointer(MO.getValue());
371 ID.AddInteger(MO.getFlags());
372 ID.AddInteger(MO.getOffset());
373 ID.AddInteger(MO.getSize());
374 ID.AddInteger(MO.getAlignment());
377 case ISD::FrameIndex:
378 case ISD::TargetFrameIndex:
379 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
382 case ISD::TargetJumpTable:
383 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
385 case ISD::ConstantPool:
386 case ISD::TargetConstantPool: {
387 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
388 ID.AddInteger(CP->getAlignment());
389 ID.AddInteger(CP->getOffset());
390 if (CP->isMachineConstantPoolEntry())
391 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
393 ID.AddPointer(CP->getConstVal());
397 LoadSDNode *LD = cast<LoadSDNode>(N);
398 ID.AddInteger(LD->getAddressingMode());
399 ID.AddInteger(LD->getExtensionType());
400 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
401 ID.AddInteger(LD->getAlignment());
402 ID.AddInteger(LD->isVolatile());
406 StoreSDNode *ST = cast<StoreSDNode>(N);
407 ID.AddInteger(ST->getAddressingMode());
408 ID.AddInteger(ST->isTruncatingStore());
409 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
410 ID.AddInteger(ST->getAlignment());
411 ID.AddInteger(ST->isVolatile());
417 //===----------------------------------------------------------------------===//
418 // SelectionDAG Class
419 //===----------------------------------------------------------------------===//
421 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
423 void SelectionDAG::RemoveDeadNodes() {
424 // Create a dummy node (which is not added to allnodes), that adds a reference
425 // to the root node, preventing it from being deleted.
426 HandleSDNode Dummy(getRoot());
428 SmallVector<SDNode*, 128> DeadNodes;
430 // Add all obviously-dead nodes to the DeadNodes worklist.
431 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
433 DeadNodes.push_back(I);
435 // Process the worklist, deleting the nodes and adding their uses to the
437 while (!DeadNodes.empty()) {
438 SDNode *N = DeadNodes.back();
439 DeadNodes.pop_back();
441 // Take the node out of the appropriate CSE map.
442 RemoveNodeFromCSEMaps(N);
444 // Next, brutally remove the operand list. This is safe to do, as there are
445 // no cycles in the graph.
446 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
447 SDNode *Operand = I->Val;
448 Operand->removeUser(N);
450 // Now that we removed this operand, see if there are no uses of it left.
451 if (Operand->use_empty())
452 DeadNodes.push_back(Operand);
454 if (N->OperandsNeedDelete)
455 delete[] N->OperandList;
459 // Finally, remove N itself.
463 // If the root changed (e.g. it was a dead load, update the root).
464 setRoot(Dummy.getValue());
467 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
468 SmallVector<SDNode*, 16> DeadNodes;
469 DeadNodes.push_back(N);
471 // Process the worklist, deleting the nodes and adding their uses to the
473 while (!DeadNodes.empty()) {
474 SDNode *N = DeadNodes.back();
475 DeadNodes.pop_back();
478 UpdateListener->NodeDeleted(N);
480 // Take the node out of the appropriate CSE map.
481 RemoveNodeFromCSEMaps(N);
483 // Next, brutally remove the operand list. This is safe to do, as there are
484 // no cycles in the graph.
485 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
486 SDNode *Operand = I->Val;
487 Operand->removeUser(N);
489 // Now that we removed this operand, see if there are no uses of it left.
490 if (Operand->use_empty())
491 DeadNodes.push_back(Operand);
493 if (N->OperandsNeedDelete)
494 delete[] N->OperandList;
498 // Finally, remove N itself.
503 void SelectionDAG::DeleteNode(SDNode *N) {
504 assert(N->use_empty() && "Cannot delete a node that is not dead!");
506 // First take this out of the appropriate CSE map.
507 RemoveNodeFromCSEMaps(N);
509 // Finally, remove uses due to operands of this node, remove from the
510 // AllNodes list, and delete the node.
511 DeleteNodeNotInCSEMaps(N);
514 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
516 // Remove it from the AllNodes list.
519 // Drop all of the operands and decrement used nodes use counts.
520 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
521 I->Val->removeUser(N);
522 if (N->OperandsNeedDelete)
523 delete[] N->OperandList;
530 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
531 /// correspond to it. This is useful when we're about to delete or repurpose
532 /// the node. We don't want future request for structurally identical nodes
533 /// to return N anymore.
534 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
536 switch (N->getOpcode()) {
537 case ISD::HANDLENODE: return; // noop.
539 Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
542 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
543 "Cond code doesn't exist!");
544 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
545 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
547 case ISD::ExternalSymbol:
548 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
550 case ISD::TargetExternalSymbol:
552 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
554 case ISD::VALUETYPE: {
555 MVT::ValueType VT = cast<VTSDNode>(N)->getVT();
556 if (MVT::isExtendedVT(VT)) {
557 Erased = ExtendedValueTypeNodes.erase(VT);
559 Erased = ValueTypeNodes[VT] != 0;
560 ValueTypeNodes[VT] = 0;
565 // Remove it from the CSE Map.
566 Erased = CSEMap.RemoveNode(N);
570 // Verify that the node was actually in one of the CSE maps, unless it has a
571 // flag result (which cannot be CSE'd) or is one of the special cases that are
572 // not subject to CSE.
573 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
574 !N->isTargetOpcode()) {
577 assert(0 && "Node is not in map!");
582 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
583 /// has been taken out and modified in some way. If the specified node already
584 /// exists in the CSE maps, do not modify the maps, but return the existing node
585 /// instead. If it doesn't exist, add it and return null.
587 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
588 assert(N->getNumOperands() && "This is a leaf node!");
589 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
590 return 0; // Never add these nodes.
592 // Check that remaining values produced are not flags.
593 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
594 if (N->getValueType(i) == MVT::Flag)
595 return 0; // Never CSE anything that produces a flag.
597 SDNode *New = CSEMap.GetOrInsertNode(N);
598 if (New != N) return New; // Node already existed.
602 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
603 /// were replaced with those specified. If this node is never memoized,
604 /// return null, otherwise return a pointer to the slot it would take. If a
605 /// node already exists with these operands, the slot will be non-null.
606 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
608 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
609 return 0; // Never add these nodes.
611 // Check that remaining values produced are not flags.
612 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
613 if (N->getValueType(i) == MVT::Flag)
614 return 0; // Never CSE anything that produces a flag.
616 SDOperand Ops[] = { Op };
618 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
619 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
622 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
623 /// were replaced with those specified. If this node is never memoized,
624 /// return null, otherwise return a pointer to the slot it would take. If a
625 /// node already exists with these operands, the slot will be non-null.
626 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
627 SDOperand Op1, SDOperand Op2,
629 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
630 return 0; // Never add these nodes.
632 // Check that remaining values produced are not flags.
633 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
634 if (N->getValueType(i) == MVT::Flag)
635 return 0; // Never CSE anything that produces a flag.
637 SDOperand Ops[] = { Op1, Op2 };
639 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
640 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 const SDOperand *Ops,unsigned NumOps,
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.
660 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
662 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
663 ID.AddInteger(LD->getAddressingMode());
664 ID.AddInteger(LD->getExtensionType());
665 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
666 ID.AddInteger(LD->getAlignment());
667 ID.AddInteger(LD->isVolatile());
668 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
669 ID.AddInteger(ST->getAddressingMode());
670 ID.AddInteger(ST->isTruncatingStore());
671 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
672 ID.AddInteger(ST->getAlignment());
673 ID.AddInteger(ST->isVolatile());
676 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
680 SelectionDAG::~SelectionDAG() {
681 while (!AllNodes.empty()) {
682 SDNode *N = AllNodes.begin();
683 N->SetNextInBucket(0);
684 if (N->OperandsNeedDelete)
685 delete [] N->OperandList;
688 AllNodes.pop_front();
692 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
693 if (Op.getValueType() == VT) return Op;
694 int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
695 return getNode(ISD::AND, Op.getValueType(), Op,
696 getConstant(Imm, Op.getValueType()));
699 SDOperand SelectionDAG::getString(const std::string &Val) {
700 StringSDNode *&N = StringNodes[Val];
702 N = new StringSDNode(Val);
703 AllNodes.push_back(N);
705 return SDOperand(N, 0);
708 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
709 assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
711 MVT::ValueType EltVT =
712 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
714 // Mask out any bits that are not valid for this constant.
715 Val &= MVT::getIntVTBitMask(EltVT);
717 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
719 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
723 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
724 if (!MVT::isVector(VT))
725 return SDOperand(N, 0);
727 N = new ConstantSDNode(isT, Val, EltVT);
728 CSEMap.InsertNode(N, IP);
729 AllNodes.push_back(N);
732 SDOperand Result(N, 0);
733 if (MVT::isVector(VT)) {
734 SmallVector<SDOperand, 8> Ops;
735 Ops.assign(MVT::getVectorNumElements(VT), Result);
736 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
741 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
742 return getConstant(Val, TLI.getPointerTy(), isTarget);
746 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
748 assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
750 MVT::ValueType EltVT =
751 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
753 // Do the map lookup using the actual bit pattern for the floating point
754 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
755 // we don't have issues with SNANs.
756 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
758 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
762 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
763 if (!MVT::isVector(VT))
764 return SDOperand(N, 0);
766 N = new ConstantFPSDNode(isTarget, V, EltVT);
767 CSEMap.InsertNode(N, IP);
768 AllNodes.push_back(N);
771 SDOperand Result(N, 0);
772 if (MVT::isVector(VT)) {
773 SmallVector<SDOperand, 8> Ops;
774 Ops.assign(MVT::getVectorNumElements(VT), Result);
775 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
780 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
782 MVT::ValueType EltVT =
783 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
785 return getConstantFP(APFloat((float)Val), VT, isTarget);
787 return getConstantFP(APFloat(Val), VT, isTarget);
790 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
791 MVT::ValueType VT, int Offset,
793 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
795 if (GVar && GVar->isThreadLocal())
796 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
798 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
800 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
802 ID.AddInteger(Offset);
804 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
805 return SDOperand(E, 0);
806 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
807 CSEMap.InsertNode(N, IP);
808 AllNodes.push_back(N);
809 return SDOperand(N, 0);
812 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
814 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
816 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
819 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
820 return SDOperand(E, 0);
821 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
822 CSEMap.InsertNode(N, IP);
823 AllNodes.push_back(N);
824 return SDOperand(N, 0);
827 SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
828 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
830 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
833 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
834 return SDOperand(E, 0);
835 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
836 CSEMap.InsertNode(N, IP);
837 AllNodes.push_back(N);
838 return SDOperand(N, 0);
841 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
842 unsigned Alignment, int Offset,
844 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
846 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
847 ID.AddInteger(Alignment);
848 ID.AddInteger(Offset);
851 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
852 return SDOperand(E, 0);
853 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
854 CSEMap.InsertNode(N, IP);
855 AllNodes.push_back(N);
856 return SDOperand(N, 0);
860 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
862 unsigned Alignment, int Offset,
864 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
866 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
867 ID.AddInteger(Alignment);
868 ID.AddInteger(Offset);
869 C->AddSelectionDAGCSEId(ID);
871 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
872 return SDOperand(E, 0);
873 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
874 CSEMap.InsertNode(N, IP);
875 AllNodes.push_back(N);
876 return SDOperand(N, 0);
880 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
882 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
885 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
886 return SDOperand(E, 0);
887 SDNode *N = new BasicBlockSDNode(MBB);
888 CSEMap.InsertNode(N, IP);
889 AllNodes.push_back(N);
890 return SDOperand(N, 0);
893 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
894 if (!MVT::isExtendedVT(VT) && (unsigned)VT >= ValueTypeNodes.size())
895 ValueTypeNodes.resize(VT+1);
897 SDNode *&N = MVT::isExtendedVT(VT) ?
898 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT];
900 if (N) return SDOperand(N, 0);
901 N = new VTSDNode(VT);
902 AllNodes.push_back(N);
903 return SDOperand(N, 0);
906 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
907 SDNode *&N = ExternalSymbols[Sym];
908 if (N) return SDOperand(N, 0);
909 N = new ExternalSymbolSDNode(false, Sym, VT);
910 AllNodes.push_back(N);
911 return SDOperand(N, 0);
914 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
916 SDNode *&N = TargetExternalSymbols[Sym];
917 if (N) return SDOperand(N, 0);
918 N = new ExternalSymbolSDNode(true, Sym, VT);
919 AllNodes.push_back(N);
920 return SDOperand(N, 0);
923 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
924 if ((unsigned)Cond >= CondCodeNodes.size())
925 CondCodeNodes.resize(Cond+1);
927 if (CondCodeNodes[Cond] == 0) {
928 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
929 AllNodes.push_back(CondCodeNodes[Cond]);
931 return SDOperand(CondCodeNodes[Cond], 0);
934 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
936 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
937 ID.AddInteger(RegNo);
939 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
940 return SDOperand(E, 0);
941 SDNode *N = new RegisterSDNode(RegNo, VT);
942 CSEMap.InsertNode(N, IP);
943 AllNodes.push_back(N);
944 return SDOperand(N, 0);
947 SDOperand SelectionDAG::getSrcValue(const Value *V) {
948 assert((!V || isa<PointerType>(V->getType())) &&
949 "SrcValue is not a pointer?");
952 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
956 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
957 return SDOperand(E, 0);
959 SDNode *N = new SrcValueSDNode(V);
960 CSEMap.InsertNode(N, IP);
961 AllNodes.push_back(N);
962 return SDOperand(N, 0);
965 SDOperand SelectionDAG::getMemOperand(const MemOperand &MO) {
966 const Value *v = MO.getValue();
967 assert((!v || isa<PointerType>(v->getType())) &&
968 "SrcValue is not a pointer?");
971 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
973 ID.AddInteger(MO.getFlags());
974 ID.AddInteger(MO.getOffset());
975 ID.AddInteger(MO.getSize());
976 ID.AddInteger(MO.getAlignment());
979 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
980 return SDOperand(E, 0);
982 SDNode *N = new MemOperandSDNode(MO);
983 CSEMap.InsertNode(N, IP);
984 AllNodes.push_back(N);
985 return SDOperand(N, 0);
988 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
989 /// specified value type.
990 SDOperand SelectionDAG::CreateStackTemporary(MVT::ValueType VT) {
991 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
992 unsigned ByteSize = MVT::getSizeInBits(VT)/8;
993 const Type *Ty = MVT::getTypeForValueType(VT);
994 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
995 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
996 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1000 SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
1001 SDOperand N2, ISD::CondCode Cond) {
1002 // These setcc operations always fold.
1006 case ISD::SETFALSE2: return getConstant(0, VT);
1008 case ISD::SETTRUE2: return getConstant(1, VT);
1020 assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
1024 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1025 uint64_t C2 = N2C->getValue();
1026 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1027 uint64_t C1 = N1C->getValue();
1029 // Sign extend the operands if required
1030 if (ISD::isSignedIntSetCC(Cond)) {
1031 C1 = N1C->getSignExtended();
1032 C2 = N2C->getSignExtended();
1036 default: assert(0 && "Unknown integer setcc!");
1037 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1038 case ISD::SETNE: return getConstant(C1 != C2, VT);
1039 case ISD::SETULT: return getConstant(C1 < C2, VT);
1040 case ISD::SETUGT: return getConstant(C1 > C2, VT);
1041 case ISD::SETULE: return getConstant(C1 <= C2, VT);
1042 case ISD::SETUGE: return getConstant(C1 >= C2, VT);
1043 case ISD::SETLT: return getConstant((int64_t)C1 < (int64_t)C2, VT);
1044 case ISD::SETGT: return getConstant((int64_t)C1 > (int64_t)C2, VT);
1045 case ISD::SETLE: return getConstant((int64_t)C1 <= (int64_t)C2, VT);
1046 case ISD::SETGE: return getConstant((int64_t)C1 >= (int64_t)C2, VT);
1050 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
1051 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1052 // No compile time operations on this type yet.
1053 if (N1C->getValueType(0) == MVT::ppcf128)
1056 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1059 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1060 return getNode(ISD::UNDEF, VT);
1062 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1063 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1064 return getNode(ISD::UNDEF, VT);
1066 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1067 R==APFloat::cmpLessThan, VT);
1068 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1069 return getNode(ISD::UNDEF, VT);
1071 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1072 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1073 return getNode(ISD::UNDEF, VT);
1075 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1076 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1077 return getNode(ISD::UNDEF, VT);
1079 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1080 R==APFloat::cmpEqual, VT);
1081 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1082 return getNode(ISD::UNDEF, VT);
1084 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1085 R==APFloat::cmpEqual, VT);
1086 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1087 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1088 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1089 R==APFloat::cmpEqual, VT);
1090 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1091 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1092 R==APFloat::cmpLessThan, VT);
1093 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1094 R==APFloat::cmpUnordered, VT);
1095 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1096 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1099 // Ensure that the constant occurs on the RHS.
1100 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1103 // Could not fold it.
1107 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1108 /// this predicate to simplify operations downstream. Mask is known to be zero
1109 /// for bits that V cannot have.
1110 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, uint64_t Mask,
1111 unsigned Depth) const {
1112 // The masks are not wide enough to represent this type! Should use APInt.
1113 if (Op.getValueType() == MVT::i128)
1116 uint64_t KnownZero, KnownOne;
1117 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1118 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1119 return (KnownZero & Mask) == Mask;
1122 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1123 /// known to be either zero or one and return them in the KnownZero/KnownOne
1124 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1126 void SelectionDAG::ComputeMaskedBits(SDOperand Op, uint64_t Mask,
1127 uint64_t &KnownZero, uint64_t &KnownOne,
1128 unsigned Depth) const {
1129 KnownZero = KnownOne = 0; // Don't know anything.
1130 if (Depth == 6 || Mask == 0)
1131 return; // Limit search depth.
1133 // The masks are not wide enough to represent this type! Should use APInt.
1134 if (Op.getValueType() == MVT::i128)
1137 uint64_t KnownZero2, KnownOne2;
1139 switch (Op.getOpcode()) {
1141 // We know all of the bits for a constant!
1142 KnownOne = cast<ConstantSDNode>(Op)->getValue() & Mask;
1143 KnownZero = ~KnownOne & Mask;
1146 // If either the LHS or the RHS are Zero, the result is zero.
1147 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1149 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1150 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1151 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1153 // Output known-1 bits are only known if set in both the LHS & RHS.
1154 KnownOne &= KnownOne2;
1155 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1156 KnownZero |= KnownZero2;
1159 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1161 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1162 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1163 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1165 // Output known-0 bits are only known if clear in both the LHS & RHS.
1166 KnownZero &= KnownZero2;
1167 // Output known-1 are known to be set if set in either the LHS | RHS.
1168 KnownOne |= KnownOne2;
1171 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1172 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1173 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1174 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1176 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1177 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1178 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1179 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1180 KnownZero = KnownZeroOut;
1184 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1185 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1186 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1187 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1189 // Only known if known in both the LHS and RHS.
1190 KnownOne &= KnownOne2;
1191 KnownZero &= KnownZero2;
1193 case ISD::SELECT_CC:
1194 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1195 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1196 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1197 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1199 // Only known if known in both the LHS and RHS.
1200 KnownOne &= KnownOne2;
1201 KnownZero &= KnownZero2;
1204 // If we know the result of a setcc has the top bits zero, use this info.
1205 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
1206 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
1209 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1210 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1211 ComputeMaskedBits(Op.getOperand(0), Mask >> SA->getValue(),
1212 KnownZero, KnownOne, Depth+1);
1213 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1214 KnownZero <<= SA->getValue();
1215 KnownOne <<= SA->getValue();
1216 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1220 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1221 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1222 MVT::ValueType VT = Op.getValueType();
1223 unsigned ShAmt = SA->getValue();
1225 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1226 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt) & TypeMask,
1227 KnownZero, KnownOne, Depth+1);
1228 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1229 KnownZero &= TypeMask;
1230 KnownOne &= TypeMask;
1231 KnownZero >>= ShAmt;
1234 uint64_t HighBits = (1ULL << ShAmt)-1;
1235 HighBits <<= MVT::getSizeInBits(VT)-ShAmt;
1236 KnownZero |= HighBits; // High bits known zero.
1240 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1241 MVT::ValueType VT = Op.getValueType();
1242 unsigned ShAmt = SA->getValue();
1244 // Compute the new bits that are at the top now.
1245 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1247 uint64_t InDemandedMask = (Mask << ShAmt) & TypeMask;
1248 // If any of the demanded bits are produced by the sign extension, we also
1249 // demand the input sign bit.
1250 uint64_t HighBits = (1ULL << ShAmt)-1;
1251 HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
1252 if (HighBits & Mask)
1253 InDemandedMask |= MVT::getIntVTSignBit(VT);
1255 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1257 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1258 KnownZero &= TypeMask;
1259 KnownOne &= TypeMask;
1260 KnownZero >>= ShAmt;
1263 // Handle the sign bits.
1264 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1265 SignBit >>= ShAmt; // Adjust to where it is now in the mask.
1267 if (KnownZero & SignBit) {
1268 KnownZero |= HighBits; // New bits are known zero.
1269 } else if (KnownOne & SignBit) {
1270 KnownOne |= HighBits; // New bits are known one.
1274 case ISD::SIGN_EXTEND_INREG: {
1275 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1277 // Sign extension. Compute the demanded bits in the result that are not
1278 // present in the input.
1279 uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & Mask;
1281 uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
1282 int64_t InputDemandedBits = Mask & MVT::getIntVTBitMask(EVT);
1284 // If the sign extended bits are demanded, we know that the sign
1287 InputDemandedBits |= InSignBit;
1289 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1290 KnownZero, KnownOne, Depth+1);
1291 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1293 // If the sign bit of the input is known set or clear, then we know the
1294 // top bits of the result.
1295 if (KnownZero & InSignBit) { // Input sign bit known clear
1296 KnownZero |= NewBits;
1297 KnownOne &= ~NewBits;
1298 } else if (KnownOne & InSignBit) { // Input sign bit known set
1299 KnownOne |= NewBits;
1300 KnownZero &= ~NewBits;
1301 } else { // Input sign bit unknown
1302 KnownZero &= ~NewBits;
1303 KnownOne &= ~NewBits;
1310 MVT::ValueType VT = Op.getValueType();
1311 unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
1312 KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
1317 if (ISD::isZEXTLoad(Op.Val)) {
1318 LoadSDNode *LD = cast<LoadSDNode>(Op);
1319 MVT::ValueType VT = LD->getMemoryVT();
1320 KnownZero |= ~MVT::getIntVTBitMask(VT) & Mask;
1324 case ISD::ZERO_EXTEND: {
1325 uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
1326 uint64_t NewBits = (~InMask) & Mask;
1327 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1329 KnownZero |= NewBits & Mask;
1330 KnownOne &= ~NewBits;
1333 case ISD::SIGN_EXTEND: {
1334 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1335 unsigned InBits = MVT::getSizeInBits(InVT);
1336 uint64_t InMask = MVT::getIntVTBitMask(InVT);
1337 uint64_t InSignBit = 1ULL << (InBits-1);
1338 uint64_t NewBits = (~InMask) & Mask;
1339 uint64_t InDemandedBits = Mask & InMask;
1341 // If any of the sign extended bits are demanded, we know that the sign
1344 InDemandedBits |= InSignBit;
1346 ComputeMaskedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1348 // If the sign bit is known zero or one, the top bits match.
1349 if (KnownZero & InSignBit) {
1350 KnownZero |= NewBits;
1351 KnownOne &= ~NewBits;
1352 } else if (KnownOne & InSignBit) {
1353 KnownOne |= NewBits;
1354 KnownZero &= ~NewBits;
1355 } else { // Otherwise, top bits aren't known.
1356 KnownOne &= ~NewBits;
1357 KnownZero &= ~NewBits;
1361 case ISD::ANY_EXTEND: {
1362 MVT::ValueType VT = Op.getOperand(0).getValueType();
1363 ComputeMaskedBits(Op.getOperand(0), Mask & MVT::getIntVTBitMask(VT),
1364 KnownZero, KnownOne, Depth+1);
1367 case ISD::TRUNCATE: {
1368 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1369 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1370 uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
1371 KnownZero &= OutMask;
1372 KnownOne &= OutMask;
1375 case ISD::AssertZext: {
1376 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1377 uint64_t InMask = MVT::getIntVTBitMask(VT);
1378 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1380 KnownZero |= (~InMask) & Mask;
1384 // All bits are zero except the low bit.
1385 KnownZero = MVT::getIntVTBitMask(Op.getValueType()) ^ 1;
1389 // If either the LHS or the RHS are Zero, the result is zero.
1390 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1391 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1392 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1393 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1395 // Output known-0 bits are known if clear or set in both the low clear bits
1396 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1397 // low 3 bits clear.
1398 uint64_t KnownZeroOut = std::min(CountTrailingZeros_64(~KnownZero),
1399 CountTrailingZeros_64(~KnownZero2));
1401 KnownZero = (1ULL << KnownZeroOut) - 1;
1406 ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1409 // We know that the top bits of C-X are clear if X contains less bits
1410 // than C (i.e. no wrap-around can happen). For example, 20-X is
1411 // positive if we can prove that X is >= 0 and < 16.
1412 MVT::ValueType VT = CLHS->getValueType(0);
1413 if ((CLHS->getValue() & MVT::getIntVTSignBit(VT)) == 0) { // sign bit clear
1414 unsigned NLZ = CountLeadingZeros_64(CLHS->getValue()+1);
1415 uint64_t MaskV = (1ULL << (63-NLZ))-1; // NLZ can't be 64 with no sign bit
1416 MaskV = ~MaskV & MVT::getIntVTBitMask(VT);
1417 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
1419 // If all of the MaskV bits are known to be zero, then we know the output
1420 // top bits are zero, because we now know that the output is from [0-C].
1421 if ((KnownZero & MaskV) == MaskV) {
1422 unsigned NLZ2 = CountLeadingZeros_64(CLHS->getValue());
1423 KnownZero = ~((1ULL << (64-NLZ2))-1) & Mask; // Top bits known zero.
1424 KnownOne = 0; // No one bits known.
1426 KnownZero = KnownOne = 0; // Otherwise, nothing known.
1432 // Allow the target to implement this method for its nodes.
1433 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1434 case ISD::INTRINSIC_WO_CHAIN:
1435 case ISD::INTRINSIC_W_CHAIN:
1436 case ISD::INTRINSIC_VOID:
1437 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1443 /// ComputeNumSignBits - Return the number of times the sign bit of the
1444 /// register is replicated into the other bits. We know that at least 1 bit
1445 /// is always equal to the sign bit (itself), but other cases can give us
1446 /// information. For example, immediately after an "SRA X, 2", we know that
1447 /// the top 3 bits are all equal to each other, so we return 3.
1448 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1449 MVT::ValueType VT = Op.getValueType();
1450 assert(MVT::isInteger(VT) && "Invalid VT!");
1451 unsigned VTBits = MVT::getSizeInBits(VT);
1455 return 1; // Limit search depth.
1457 switch (Op.getOpcode()) {
1459 case ISD::AssertSext:
1460 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1461 return VTBits-Tmp+1;
1462 case ISD::AssertZext:
1463 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1466 case ISD::Constant: {
1467 uint64_t Val = cast<ConstantSDNode>(Op)->getValue();
1468 // If negative, invert the bits, then look at it.
1469 if (Val & MVT::getIntVTSignBit(VT))
1472 // Shift the bits so they are the leading bits in the int64_t.
1475 // Return # leading zeros. We use 'min' here in case Val was zero before
1476 // shifting. We don't want to return '64' as for an i32 "0".
1477 return std::min(VTBits, CountLeadingZeros_64(Val));
1480 case ISD::SIGN_EXTEND:
1481 Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1482 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1484 case ISD::SIGN_EXTEND_INREG:
1485 // Max of the input and what this extends.
1486 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1489 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1490 return std::max(Tmp, Tmp2);
1493 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1494 // SRA X, C -> adds C sign bits.
1495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1496 Tmp += C->getValue();
1497 if (Tmp > VTBits) Tmp = VTBits;
1501 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1502 // shl destroys sign bits.
1503 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1504 if (C->getValue() >= VTBits || // Bad shift.
1505 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1506 return Tmp - C->getValue();
1511 case ISD::XOR: // NOT is handled here.
1512 // Logical binary ops preserve the number of sign bits.
1513 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1514 if (Tmp == 1) return 1; // Early out.
1515 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1516 return std::min(Tmp, Tmp2);
1519 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1520 if (Tmp == 1) return 1; // Early out.
1521 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1522 return std::min(Tmp, Tmp2);
1525 // If setcc returns 0/-1, all bits are sign bits.
1526 if (TLI.getSetCCResultContents() ==
1527 TargetLowering::ZeroOrNegativeOneSetCCResult)
1532 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1533 unsigned RotAmt = C->getValue() & (VTBits-1);
1535 // Handle rotate right by N like a rotate left by 32-N.
1536 if (Op.getOpcode() == ISD::ROTR)
1537 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1539 // If we aren't rotating out all of the known-in sign bits, return the
1540 // number that are left. This handles rotl(sext(x), 1) for example.
1541 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1542 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1546 // Add can have at most one carry bit. Thus we know that the output
1547 // is, at worst, one more bit than the inputs.
1548 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1549 if (Tmp == 1) return 1; // Early out.
1551 // Special case decrementing a value (ADD X, -1):
1552 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1553 if (CRHS->isAllOnesValue()) {
1554 uint64_t KnownZero, KnownOne;
1555 uint64_t Mask = MVT::getIntVTBitMask(VT);
1556 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1558 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1560 if ((KnownZero|1) == Mask)
1563 // If we are subtracting one from a positive number, there is no carry
1564 // out of the result.
1565 if (KnownZero & MVT::getIntVTSignBit(VT))
1569 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1570 if (Tmp2 == 1) return 1;
1571 return std::min(Tmp, Tmp2)-1;
1575 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1576 if (Tmp2 == 1) return 1;
1579 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1580 if (CLHS->getValue() == 0) {
1581 uint64_t KnownZero, KnownOne;
1582 uint64_t Mask = MVT::getIntVTBitMask(VT);
1583 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1584 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1586 if ((KnownZero|1) == Mask)
1589 // If the input is known to be positive (the sign bit is known clear),
1590 // the output of the NEG has the same number of sign bits as the input.
1591 if (KnownZero & MVT::getIntVTSignBit(VT))
1594 // Otherwise, we treat this like a SUB.
1597 // Sub can have at most one carry bit. Thus we know that the output
1598 // is, at worst, one more bit than the inputs.
1599 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1600 if (Tmp == 1) return 1; // Early out.
1601 return std::min(Tmp, Tmp2)-1;
1604 // FIXME: it's tricky to do anything useful for this, but it is an important
1605 // case for targets like X86.
1609 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1610 if (Op.getOpcode() == ISD::LOAD) {
1611 LoadSDNode *LD = cast<LoadSDNode>(Op);
1612 unsigned ExtType = LD->getExtensionType();
1615 case ISD::SEXTLOAD: // '17' bits known
1616 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1617 return VTBits-Tmp+1;
1618 case ISD::ZEXTLOAD: // '16' bits known
1619 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1624 // Allow the target to implement this method for its nodes.
1625 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1626 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1627 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1628 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1629 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1630 if (NumBits > 1) return NumBits;
1633 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1634 // use this information.
1635 uint64_t KnownZero, KnownOne;
1636 uint64_t Mask = MVT::getIntVTBitMask(VT);
1637 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1639 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1640 if (KnownZero & SignBit) { // SignBit is 0
1642 } else if (KnownOne & SignBit) { // SignBit is 1;
1649 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1650 // the number of identical bits in the top of the input value.
1653 // Return # leading zeros. We use 'min' here in case Val was zero before
1654 // shifting. We don't want to return '64' as for an i32 "0".
1655 return std::min(VTBits, CountLeadingZeros_64(Mask));
1659 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1660 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1661 if (!GA) return false;
1662 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1663 if (!GV) return false;
1664 MachineModuleInfo *MMI = getMachineModuleInfo();
1665 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1669 /// getNode - Gets or creates the specified node.
1671 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1672 FoldingSetNodeID ID;
1673 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1675 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1676 return SDOperand(E, 0);
1677 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1678 CSEMap.InsertNode(N, IP);
1680 AllNodes.push_back(N);
1681 return SDOperand(N, 0);
1684 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1685 SDOperand Operand) {
1687 // Constant fold unary operations with an integer constant operand.
1688 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1689 uint64_t Val = C->getValue();
1692 case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
1693 case ISD::ANY_EXTEND:
1694 case ISD::ZERO_EXTEND: return getConstant(Val, VT);
1695 case ISD::TRUNCATE: return getConstant(Val, VT);
1696 case ISD::UINT_TO_FP:
1697 case ISD::SINT_TO_FP: {
1698 const uint64_t zero[] = {0, 0};
1699 // No compile time operations on this type.
1700 if (VT==MVT::ppcf128)
1702 APFloat apf = APFloat(APInt(MVT::getSizeInBits(VT), 2, zero));
1703 (void)apf.convertFromZeroExtendedInteger(&Val,
1704 MVT::getSizeInBits(Operand.getValueType()),
1705 Opcode==ISD::SINT_TO_FP,
1706 APFloat::rmNearestTiesToEven);
1707 return getConstantFP(apf, VT);
1709 case ISD::BIT_CONVERT:
1710 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1711 return getConstantFP(BitsToFloat(Val), VT);
1712 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1713 return getConstantFP(BitsToDouble(Val), VT);
1717 default: assert(0 && "Invalid bswap!"); break;
1718 case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
1719 case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
1720 case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
1725 default: assert(0 && "Invalid ctpop!"); break;
1726 case MVT::i1: return getConstant(Val != 0, VT);
1728 Tmp1 = (unsigned)Val & 0xFF;
1729 return getConstant(CountPopulation_32(Tmp1), VT);
1731 Tmp1 = (unsigned)Val & 0xFFFF;
1732 return getConstant(CountPopulation_32(Tmp1), VT);
1734 return getConstant(CountPopulation_32((unsigned)Val), VT);
1736 return getConstant(CountPopulation_64(Val), VT);
1740 default: assert(0 && "Invalid ctlz!"); break;
1741 case MVT::i1: return getConstant(Val == 0, VT);
1743 Tmp1 = (unsigned)Val & 0xFF;
1744 return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
1746 Tmp1 = (unsigned)Val & 0xFFFF;
1747 return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
1749 return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
1751 return getConstant(CountLeadingZeros_64(Val), VT);
1755 default: assert(0 && "Invalid cttz!"); break;
1756 case MVT::i1: return getConstant(Val == 0, VT);
1758 Tmp1 = (unsigned)Val | 0x100;
1759 return getConstant(CountTrailingZeros_32(Tmp1), VT);
1761 Tmp1 = (unsigned)Val | 0x10000;
1762 return getConstant(CountTrailingZeros_32(Tmp1), VT);
1764 return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
1766 return getConstant(CountTrailingZeros_64(Val), VT);
1771 // Constant fold unary operations with a floating point constant operand.
1772 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1773 APFloat V = C->getValueAPF(); // make copy
1774 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1778 return getConstantFP(V, VT);
1781 return getConstantFP(V, VT);
1783 case ISD::FP_EXTEND:
1784 // This can return overflow, underflow, or inexact; we don't care.
1785 // FIXME need to be more flexible about rounding mode.
1786 (void) V.convert(VT==MVT::f32 ? APFloat::IEEEsingle :
1787 VT==MVT::f64 ? APFloat::IEEEdouble :
1788 VT==MVT::f80 ? APFloat::x87DoubleExtended :
1789 VT==MVT::f128 ? APFloat::IEEEquad :
1791 APFloat::rmNearestTiesToEven);
1792 return getConstantFP(V, VT);
1793 case ISD::FP_TO_SINT:
1794 case ISD::FP_TO_UINT: {
1796 assert(integerPartWidth >= 64);
1797 // FIXME need to be more flexible about rounding mode.
1798 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1799 Opcode==ISD::FP_TO_SINT,
1800 APFloat::rmTowardZero);
1801 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
1803 return getConstant(x, VT);
1805 case ISD::BIT_CONVERT:
1806 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1807 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1808 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1809 return getConstant(V.convertToAPInt().getZExtValue(), VT);
1815 unsigned OpOpcode = Operand.Val->getOpcode();
1817 case ISD::TokenFactor:
1818 return Operand; // Factor of one node? No factor.
1819 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1820 case ISD::FP_EXTEND:
1821 assert(MVT::isFloatingPoint(VT) &&
1822 MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1823 if (Operand.getValueType() == VT) return Operand; // noop conversion.
1825 case ISD::SIGN_EXTEND:
1826 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1827 "Invalid SIGN_EXTEND!");
1828 if (Operand.getValueType() == VT) return Operand; // noop extension
1829 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1830 && "Invalid sext node, dst < src!");
1831 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1832 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1834 case ISD::ZERO_EXTEND:
1835 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1836 "Invalid ZERO_EXTEND!");
1837 if (Operand.getValueType() == VT) return Operand; // noop extension
1838 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1839 && "Invalid zext node, dst < src!");
1840 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
1841 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1843 case ISD::ANY_EXTEND:
1844 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1845 "Invalid ANY_EXTEND!");
1846 if (Operand.getValueType() == VT) return Operand; // noop extension
1847 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1848 && "Invalid anyext node, dst < src!");
1849 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1850 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
1851 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1854 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1855 "Invalid TRUNCATE!");
1856 if (Operand.getValueType() == VT) return Operand; // noop truncate
1857 assert(MVT::getSizeInBits(Operand.getValueType()) > MVT::getSizeInBits(VT)
1858 && "Invalid truncate node, src < dst!");
1859 if (OpOpcode == ISD::TRUNCATE)
1860 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1861 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1862 OpOpcode == ISD::ANY_EXTEND) {
1863 // If the source is smaller than the dest, we still need an extend.
1864 if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1865 < MVT::getSizeInBits(VT))
1866 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1867 else if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1868 > MVT::getSizeInBits(VT))
1869 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1871 return Operand.Val->getOperand(0);
1874 case ISD::BIT_CONVERT:
1875 // Basic sanity checking.
1876 assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1877 && "Cannot BIT_CONVERT between types of different sizes!");
1878 if (VT == Operand.getValueType()) return Operand; // noop conversion.
1879 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
1880 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1881 if (OpOpcode == ISD::UNDEF)
1882 return getNode(ISD::UNDEF, VT);
1884 case ISD::SCALAR_TO_VECTOR:
1885 assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1886 MVT::getVectorElementType(VT) == Operand.getValueType() &&
1887 "Illegal SCALAR_TO_VECTOR node!");
1890 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
1891 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1892 Operand.Val->getOperand(0));
1893 if (OpOpcode == ISD::FNEG) // --X -> X
1894 return Operand.Val->getOperand(0);
1897 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
1898 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1903 SDVTList VTs = getVTList(VT);
1904 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1905 FoldingSetNodeID ID;
1906 SDOperand Ops[1] = { Operand };
1907 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
1909 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1910 return SDOperand(E, 0);
1911 N = new UnarySDNode(Opcode, VTs, Operand);
1912 CSEMap.InsertNode(N, IP);
1914 N = new UnarySDNode(Opcode, VTs, Operand);
1916 AllNodes.push_back(N);
1917 return SDOperand(N, 0);
1922 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1923 SDOperand N1, SDOperand N2) {
1924 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1925 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1928 case ISD::TokenFactor:
1929 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1930 N2.getValueType() == MVT::Other && "Invalid token factor!");
1931 // Fold trivial token factors.
1932 if (N1.getOpcode() == ISD::EntryToken) return N2;
1933 if (N2.getOpcode() == ISD::EntryToken) return N1;
1936 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1937 N1.getValueType() == VT && "Binary operator types must match!");
1938 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
1939 // worth handling here.
1940 if (N2C && N2C->getValue() == 0)
1942 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
1947 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1948 N1.getValueType() == VT && "Binary operator types must match!");
1949 // (X ^| 0) -> X. This commonly occurs when legalizing i64 values, so it's
1950 // worth handling here.
1951 if (N2C && N2C->getValue() == 0)
1958 assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1970 assert(N1.getValueType() == N2.getValueType() &&
1971 N1.getValueType() == VT && "Binary operator types must match!");
1973 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
1974 assert(N1.getValueType() == VT &&
1975 MVT::isFloatingPoint(N1.getValueType()) &&
1976 MVT::isFloatingPoint(N2.getValueType()) &&
1977 "Invalid FCOPYSIGN!");
1984 assert(VT == N1.getValueType() &&
1985 "Shift operators return type must be the same as their first arg");
1986 assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1987 VT != MVT::i1 && "Shifts only work on integers");
1989 case ISD::FP_ROUND_INREG: {
1990 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1991 assert(VT == N1.getValueType() && "Not an inreg round!");
1992 assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1993 "Cannot FP_ROUND_INREG integer types");
1994 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1995 "Not rounding down!");
1996 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2000 assert(MVT::isFloatingPoint(VT) &&
2001 MVT::isFloatingPoint(N1.getValueType()) &&
2002 MVT::getSizeInBits(VT) <= MVT::getSizeInBits(N1.getValueType()) &&
2003 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2004 if (N1.getValueType() == VT) return N1; // noop conversion.
2006 case ISD::AssertSext:
2007 case ISD::AssertZext: {
2008 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2009 assert(VT == N1.getValueType() && "Not an inreg extend!");
2010 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2011 "Cannot *_EXTEND_INREG FP types");
2012 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2016 case ISD::SIGN_EXTEND_INREG: {
2017 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2018 assert(VT == N1.getValueType() && "Not an inreg extend!");
2019 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2020 "Cannot *_EXTEND_INREG FP types");
2021 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2023 if (EVT == VT) return N1; // Not actually extending
2026 int64_t Val = N1C->getValue();
2027 unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
2028 Val <<= 64-FromBits;
2029 Val >>= 64-FromBits;
2030 return getConstant(Val, VT);
2034 case ISD::EXTRACT_VECTOR_ELT:
2035 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2037 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2038 // expanding copies of large vectors from registers.
2039 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2040 N1.getNumOperands() > 0) {
2042 MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2043 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2044 N1.getOperand(N2C->getValue() / Factor),
2045 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2048 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2049 // expanding large vector constants.
2050 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2051 return N1.getOperand(N2C->getValue());
2053 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2054 // operations are lowered to scalars.
2055 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2056 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2058 return N1.getOperand(1);
2060 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2063 case ISD::EXTRACT_ELEMENT:
2064 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2066 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2067 // 64-bit integers into 32-bit parts. Instead of building the extract of
2068 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2069 if (N1.getOpcode() == ISD::BUILD_PAIR)
2070 return N1.getOperand(N2C->getValue());
2072 // EXTRACT_ELEMENT of a constant int is also very common.
2073 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2074 unsigned Shift = MVT::getSizeInBits(VT) * N2C->getValue();
2075 return getConstant(C->getValue() >> Shift, VT);
2082 uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
2084 case ISD::ADD: return getConstant(C1 + C2, VT);
2085 case ISD::SUB: return getConstant(C1 - C2, VT);
2086 case ISD::MUL: return getConstant(C1 * C2, VT);
2088 if (C2) return getConstant(C1 / C2, VT);
2091 if (C2) return getConstant(C1 % C2, VT);
2094 if (C2) return getConstant(N1C->getSignExtended() /
2095 N2C->getSignExtended(), VT);
2098 if (C2) return getConstant(N1C->getSignExtended() %
2099 N2C->getSignExtended(), VT);
2101 case ISD::AND : return getConstant(C1 & C2, VT);
2102 case ISD::OR : return getConstant(C1 | C2, VT);
2103 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2104 case ISD::SHL : return getConstant(C1 << C2, VT);
2105 case ISD::SRL : return getConstant(C1 >> C2, VT);
2106 case ISD::SRA : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
2108 return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
2111 return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)),
2115 } else { // Cannonicalize constant to RHS if commutative
2116 if (isCommutativeBinOp(Opcode)) {
2117 std::swap(N1C, N2C);
2123 // Constant fold FP operations.
2124 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2125 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2127 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2128 // Cannonicalize constant to RHS if commutative
2129 std::swap(N1CFP, N2CFP);
2131 } else if (N2CFP && VT != MVT::ppcf128) {
2132 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2133 APFloat::opStatus s;
2136 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2137 if (s != APFloat::opInvalidOp)
2138 return getConstantFP(V1, VT);
2141 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2142 if (s!=APFloat::opInvalidOp)
2143 return getConstantFP(V1, VT);
2146 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2147 if (s!=APFloat::opInvalidOp)
2148 return getConstantFP(V1, VT);
2151 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2152 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2153 return getConstantFP(V1, VT);
2156 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2157 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2158 return getConstantFP(V1, VT);
2160 case ISD::FCOPYSIGN:
2162 return getConstantFP(V1, VT);
2168 // Canonicalize an UNDEF to the RHS, even over a constant.
2169 if (N1.getOpcode() == ISD::UNDEF) {
2170 if (isCommutativeBinOp(Opcode)) {
2174 case ISD::FP_ROUND_INREG:
2175 case ISD::SIGN_EXTEND_INREG:
2181 return N1; // fold op(undef, arg2) -> undef
2188 if (!MVT::isVector(VT))
2189 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2190 // For vectors, we can't easily build an all zero vector, just return
2197 // Fold a bunch of operators when the RHS is undef.
2198 if (N2.getOpcode() == ISD::UNDEF) {
2214 return N2; // fold op(arg1, undef) -> undef
2219 if (!MVT::isVector(VT))
2220 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2221 // For vectors, we can't easily build an all zero vector, just return
2225 if (!MVT::isVector(VT))
2226 return getConstant(MVT::getIntVTBitMask(VT), VT);
2227 // For vectors, we can't easily build an all one vector, just return
2235 // Memoize this node if possible.
2237 SDVTList VTs = getVTList(VT);
2238 if (VT != MVT::Flag) {
2239 SDOperand Ops[] = { N1, N2 };
2240 FoldingSetNodeID ID;
2241 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2243 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2244 return SDOperand(E, 0);
2245 N = new BinarySDNode(Opcode, VTs, N1, N2);
2246 CSEMap.InsertNode(N, IP);
2248 N = new BinarySDNode(Opcode, VTs, N1, N2);
2251 AllNodes.push_back(N);
2252 return SDOperand(N, 0);
2255 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2256 SDOperand N1, SDOperand N2, SDOperand N3) {
2257 // Perform various simplifications.
2258 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2259 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2262 // Use FoldSetCC to simplify SETCC's.
2263 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2264 if (Simp.Val) return Simp;
2269 if (N1C->getValue())
2270 return N2; // select true, X, Y -> X
2272 return N3; // select false, X, Y -> Y
2274 if (N2 == N3) return N2; // select C, X, X -> X
2278 if (N2C->getValue()) // Unconditional branch
2279 return getNode(ISD::BR, MVT::Other, N1, N3);
2281 return N1; // Never-taken branch
2283 case ISD::VECTOR_SHUFFLE:
2284 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2285 MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2286 N3.getOpcode() == ISD::BUILD_VECTOR &&
2287 MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2288 "Illegal VECTOR_SHUFFLE node!");
2290 case ISD::BIT_CONVERT:
2291 // Fold bit_convert nodes from a type to themselves.
2292 if (N1.getValueType() == VT)
2297 // Memoize node if it doesn't produce a flag.
2299 SDVTList VTs = getVTList(VT);
2300 if (VT != MVT::Flag) {
2301 SDOperand Ops[] = { N1, N2, N3 };
2302 FoldingSetNodeID ID;
2303 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2305 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2306 return SDOperand(E, 0);
2307 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2308 CSEMap.InsertNode(N, IP);
2310 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2312 AllNodes.push_back(N);
2313 return SDOperand(N, 0);
2316 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2317 SDOperand N1, SDOperand N2, SDOperand N3,
2319 SDOperand Ops[] = { N1, N2, N3, N4 };
2320 return getNode(Opcode, VT, Ops, 4);
2323 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2324 SDOperand N1, SDOperand N2, SDOperand N3,
2325 SDOperand N4, SDOperand N5) {
2326 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2327 return getNode(Opcode, VT, Ops, 5);
2330 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dest,
2331 SDOperand Src, SDOperand Size,
2333 SDOperand AlwaysInline) {
2334 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2335 return getNode(ISD::MEMCPY, MVT::Other, Ops, 6);
2338 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dest,
2339 SDOperand Src, SDOperand Size,
2341 SDOperand AlwaysInline) {
2342 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2343 return getNode(ISD::MEMMOVE, MVT::Other, Ops, 6);
2346 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dest,
2347 SDOperand Src, SDOperand Size,
2349 SDOperand AlwaysInline) {
2350 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2351 return getNode(ISD::MEMSET, MVT::Other, Ops, 6);
2354 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2355 SDOperand Chain, SDOperand Ptr,
2356 const Value *SV, int SVOffset,
2357 bool isVolatile, unsigned Alignment) {
2358 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2360 if (VT != MVT::iPTR) {
2361 Ty = MVT::getTypeForValueType(VT);
2363 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2364 assert(PT && "Value for load must be a pointer");
2365 Ty = PT->getElementType();
2367 assert(Ty && "Could not get type information for load");
2368 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2370 SDVTList VTs = getVTList(VT, MVT::Other);
2371 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2372 SDOperand Ops[] = { Chain, Ptr, Undef };
2373 FoldingSetNodeID ID;
2374 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2375 ID.AddInteger(ISD::UNINDEXED);
2376 ID.AddInteger(ISD::NON_EXTLOAD);
2377 ID.AddInteger((unsigned int)VT);
2378 ID.AddInteger(Alignment);
2379 ID.AddInteger(isVolatile);
2381 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2382 return SDOperand(E, 0);
2383 SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED,
2384 ISD::NON_EXTLOAD, VT, SV, SVOffset, Alignment,
2386 CSEMap.InsertNode(N, IP);
2387 AllNodes.push_back(N);
2388 return SDOperand(N, 0);
2391 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2392 SDOperand Chain, SDOperand Ptr,
2394 int SVOffset, MVT::ValueType EVT,
2395 bool isVolatile, unsigned Alignment) {
2396 // If they are asking for an extending load from/to the same thing, return a
2399 return getLoad(VT, Chain, Ptr, SV, SVOffset, isVolatile, Alignment);
2401 if (MVT::isVector(VT))
2402 assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2404 assert(MVT::getSizeInBits(EVT) < MVT::getSizeInBits(VT) &&
2405 "Should only be an extending load, not truncating!");
2406 assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2407 "Cannot sign/zero extend a FP/Vector load!");
2408 assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2409 "Cannot convert from FP to Int or Int -> FP!");
2411 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2413 if (VT != MVT::iPTR) {
2414 Ty = MVT::getTypeForValueType(VT);
2416 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2417 assert(PT && "Value for load must be a pointer");
2418 Ty = PT->getElementType();
2420 assert(Ty && "Could not get type information for load");
2421 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2423 SDVTList VTs = getVTList(VT, MVT::Other);
2424 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2425 SDOperand Ops[] = { Chain, Ptr, Undef };
2426 FoldingSetNodeID ID;
2427 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2428 ID.AddInteger(ISD::UNINDEXED);
2429 ID.AddInteger(ExtType);
2430 ID.AddInteger((unsigned int)EVT);
2431 ID.AddInteger(Alignment);
2432 ID.AddInteger(isVolatile);
2434 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2435 return SDOperand(E, 0);
2436 SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED, ExtType, EVT,
2437 SV, SVOffset, Alignment, isVolatile);
2438 CSEMap.InsertNode(N, IP);
2439 AllNodes.push_back(N);
2440 return SDOperand(N, 0);
2444 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2445 SDOperand Offset, ISD::MemIndexedMode AM) {
2446 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2447 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2448 "Load is already a indexed load!");
2449 MVT::ValueType VT = OrigLoad.getValueType();
2450 SDVTList VTs = getVTList(VT, Base.getValueType(), MVT::Other);
2451 SDOperand Ops[] = { LD->getChain(), Base, Offset };
2452 FoldingSetNodeID ID;
2453 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2455 ID.AddInteger(LD->getExtensionType());
2456 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
2457 ID.AddInteger(LD->getAlignment());
2458 ID.AddInteger(LD->isVolatile());
2460 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2461 return SDOperand(E, 0);
2462 SDNode *N = new LoadSDNode(Ops, VTs, AM,
2463 LD->getExtensionType(), LD->getMemoryVT(),
2464 LD->getSrcValue(), LD->getSrcValueOffset(),
2465 LD->getAlignment(), LD->isVolatile());
2466 CSEMap.InsertNode(N, IP);
2467 AllNodes.push_back(N);
2468 return SDOperand(N, 0);
2471 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2472 SDOperand Ptr, const Value *SV, int SVOffset,
2473 bool isVolatile, unsigned Alignment) {
2474 MVT::ValueType VT = Val.getValueType();
2476 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2478 if (VT != MVT::iPTR) {
2479 Ty = MVT::getTypeForValueType(VT);
2481 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2482 assert(PT && "Value for store must be a pointer");
2483 Ty = PT->getElementType();
2485 assert(Ty && "Could not get type information for store");
2486 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2488 SDVTList VTs = getVTList(MVT::Other);
2489 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2490 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2491 FoldingSetNodeID ID;
2492 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2493 ID.AddInteger(ISD::UNINDEXED);
2494 ID.AddInteger(false);
2495 ID.AddInteger((unsigned int)VT);
2496 ID.AddInteger(Alignment);
2497 ID.AddInteger(isVolatile);
2499 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2500 return SDOperand(E, 0);
2501 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
2502 VT, SV, SVOffset, Alignment, isVolatile);
2503 CSEMap.InsertNode(N, IP);
2504 AllNodes.push_back(N);
2505 return SDOperand(N, 0);
2508 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
2509 SDOperand Ptr, const Value *SV,
2510 int SVOffset, MVT::ValueType SVT,
2511 bool isVolatile, unsigned Alignment) {
2512 MVT::ValueType VT = Val.getValueType();
2515 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
2517 assert(MVT::getSizeInBits(VT) > MVT::getSizeInBits(SVT) &&
2518 "Not a truncation?");
2519 assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
2520 "Can't do FP-INT conversion!");
2522 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2524 if (VT != MVT::iPTR) {
2525 Ty = MVT::getTypeForValueType(VT);
2527 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2528 assert(PT && "Value for store must be a pointer");
2529 Ty = PT->getElementType();
2531 assert(Ty && "Could not get type information for store");
2532 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2534 SDVTList VTs = getVTList(MVT::Other);
2535 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2536 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2537 FoldingSetNodeID ID;
2538 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2539 ID.AddInteger(ISD::UNINDEXED);
2541 ID.AddInteger((unsigned int)SVT);
2542 ID.AddInteger(Alignment);
2543 ID.AddInteger(isVolatile);
2545 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2546 return SDOperand(E, 0);
2547 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
2548 SVT, SV, SVOffset, Alignment, isVolatile);
2549 CSEMap.InsertNode(N, IP);
2550 AllNodes.push_back(N);
2551 return SDOperand(N, 0);
2555 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
2556 SDOperand Offset, ISD::MemIndexedMode AM) {
2557 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
2558 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
2559 "Store is already a indexed store!");
2560 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
2561 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
2562 FoldingSetNodeID ID;
2563 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2565 ID.AddInteger(ST->isTruncatingStore());
2566 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
2567 ID.AddInteger(ST->getAlignment());
2568 ID.AddInteger(ST->isVolatile());
2570 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2571 return SDOperand(E, 0);
2572 SDNode *N = new StoreSDNode(Ops, VTs, AM,
2573 ST->isTruncatingStore(), ST->getMemoryVT(),
2574 ST->getSrcValue(), ST->getSrcValueOffset(),
2575 ST->getAlignment(), ST->isVolatile());
2576 CSEMap.InsertNode(N, IP);
2577 AllNodes.push_back(N);
2578 return SDOperand(N, 0);
2581 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
2582 SDOperand Chain, SDOperand Ptr,
2584 SDOperand Ops[] = { Chain, Ptr, SV };
2585 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
2588 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2589 const SDOperand *Ops, unsigned NumOps) {
2591 case 0: return getNode(Opcode, VT);
2592 case 1: return getNode(Opcode, VT, Ops[0]);
2593 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
2594 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
2600 case ISD::SELECT_CC: {
2601 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
2602 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
2603 "LHS and RHS of condition must have same type!");
2604 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2605 "True and False arms of SelectCC must have same type!");
2606 assert(Ops[2].getValueType() == VT &&
2607 "select_cc node must be of same type as true and false value!");
2611 assert(NumOps == 5 && "BR_CC takes 5 operands!");
2612 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2613 "LHS/RHS of comparison should match types!");
2620 SDVTList VTs = getVTList(VT);
2621 if (VT != MVT::Flag) {
2622 FoldingSetNodeID ID;
2623 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
2625 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2626 return SDOperand(E, 0);
2627 N = new SDNode(Opcode, VTs, Ops, NumOps);
2628 CSEMap.InsertNode(N, IP);
2630 N = new SDNode(Opcode, VTs, Ops, NumOps);
2632 AllNodes.push_back(N);
2633 return SDOperand(N, 0);
2636 SDOperand SelectionDAG::getNode(unsigned Opcode,
2637 std::vector<MVT::ValueType> &ResultTys,
2638 const SDOperand *Ops, unsigned NumOps) {
2639 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
2643 SDOperand SelectionDAG::getNode(unsigned Opcode,
2644 const MVT::ValueType *VTs, unsigned NumVTs,
2645 const SDOperand *Ops, unsigned NumOps) {
2647 return getNode(Opcode, VTs[0], Ops, NumOps);
2648 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
2651 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2652 const SDOperand *Ops, unsigned NumOps) {
2653 if (VTList.NumVTs == 1)
2654 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
2657 // FIXME: figure out how to safely handle things like
2658 // int foo(int x) { return 1 << (x & 255); }
2659 // int bar() { return foo(256); }
2661 case ISD::SRA_PARTS:
2662 case ISD::SRL_PARTS:
2663 case ISD::SHL_PARTS:
2664 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2665 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
2666 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2667 else if (N3.getOpcode() == ISD::AND)
2668 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
2669 // If the and is only masking out bits that cannot effect the shift,
2670 // eliminate the and.
2671 unsigned NumBits = MVT::getSizeInBits(VT)*2;
2672 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2673 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2679 // Memoize the node unless it returns a flag.
2681 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
2682 FoldingSetNodeID ID;
2683 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
2685 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2686 return SDOperand(E, 0);
2688 N = new UnarySDNode(Opcode, VTList, Ops[0]);
2689 else if (NumOps == 2)
2690 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2691 else if (NumOps == 3)
2692 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2694 N = new SDNode(Opcode, VTList, Ops, NumOps);
2695 CSEMap.InsertNode(N, IP);
2698 N = new UnarySDNode(Opcode, VTList, Ops[0]);
2699 else if (NumOps == 2)
2700 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2701 else if (NumOps == 3)
2702 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2704 N = new SDNode(Opcode, VTList, Ops, NumOps);
2706 AllNodes.push_back(N);
2707 return SDOperand(N, 0);
2710 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
2711 return getNode(Opcode, VTList, 0, 0);
2714 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2716 SDOperand Ops[] = { N1 };
2717 return getNode(Opcode, VTList, Ops, 1);
2720 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2721 SDOperand N1, SDOperand N2) {
2722 SDOperand Ops[] = { N1, N2 };
2723 return getNode(Opcode, VTList, Ops, 2);
2726 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2727 SDOperand N1, SDOperand N2, SDOperand N3) {
2728 SDOperand Ops[] = { N1, N2, N3 };
2729 return getNode(Opcode, VTList, Ops, 3);
2732 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2733 SDOperand N1, SDOperand N2, SDOperand N3,
2735 SDOperand Ops[] = { N1, N2, N3, N4 };
2736 return getNode(Opcode, VTList, Ops, 4);
2739 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2740 SDOperand N1, SDOperand N2, SDOperand N3,
2741 SDOperand N4, SDOperand N5) {
2742 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2743 return getNode(Opcode, VTList, Ops, 5);
2746 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
2747 return makeVTList(SDNode::getValueTypeList(VT), 1);
2750 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
2751 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2752 E = VTList.end(); I != E; ++I) {
2753 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
2754 return makeVTList(&(*I)[0], 2);
2756 std::vector<MVT::ValueType> V;
2759 VTList.push_front(V);
2760 return makeVTList(&(*VTList.begin())[0], 2);
2762 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
2763 MVT::ValueType VT3) {
2764 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2765 E = VTList.end(); I != E; ++I) {
2766 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
2768 return makeVTList(&(*I)[0], 3);
2770 std::vector<MVT::ValueType> V;
2774 VTList.push_front(V);
2775 return makeVTList(&(*VTList.begin())[0], 3);
2778 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
2780 case 0: assert(0 && "Cannot have nodes without results!");
2781 case 1: return getVTList(VTs[0]);
2782 case 2: return getVTList(VTs[0], VTs[1]);
2783 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
2787 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2788 E = VTList.end(); I != E; ++I) {
2789 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
2791 bool NoMatch = false;
2792 for (unsigned i = 2; i != NumVTs; ++i)
2793 if (VTs[i] != (*I)[i]) {
2798 return makeVTList(&*I->begin(), NumVTs);
2801 VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
2802 return makeVTList(&*VTList.begin()->begin(), NumVTs);
2806 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
2807 /// specified operands. If the resultant node already exists in the DAG,
2808 /// this does not modify the specified node, instead it returns the node that
2809 /// already exists. If the resultant node does not exist in the DAG, the
2810 /// input node is returned. As a degenerate case, if you specify the same
2811 /// input operands as the node already has, the input node is returned.
2812 SDOperand SelectionDAG::
2813 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
2814 SDNode *N = InN.Val;
2815 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
2817 // Check to see if there is no change.
2818 if (Op == N->getOperand(0)) return InN;
2820 // See if the modified node already exists.
2821 void *InsertPos = 0;
2822 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
2823 return SDOperand(Existing, InN.ResNo);
2825 // Nope it doesn't. Remove the node from it's current place in the maps.
2827 RemoveNodeFromCSEMaps(N);
2829 // Now we update the operands.
2830 N->OperandList[0].Val->removeUser(N);
2832 N->OperandList[0] = Op;
2834 // If this gets put into a CSE map, add it.
2835 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2839 SDOperand SelectionDAG::
2840 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
2841 SDNode *N = InN.Val;
2842 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
2844 // Check to see if there is no change.
2845 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
2846 return InN; // No operands changed, just return the input node.
2848 // See if the modified node already exists.
2849 void *InsertPos = 0;
2850 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
2851 return SDOperand(Existing, InN.ResNo);
2853 // Nope it doesn't. Remove the node from it's current place in the maps.
2855 RemoveNodeFromCSEMaps(N);
2857 // Now we update the operands.
2858 if (N->OperandList[0] != Op1) {
2859 N->OperandList[0].Val->removeUser(N);
2860 Op1.Val->addUser(N);
2861 N->OperandList[0] = Op1;
2863 if (N->OperandList[1] != Op2) {
2864 N->OperandList[1].Val->removeUser(N);
2865 Op2.Val->addUser(N);
2866 N->OperandList[1] = Op2;
2869 // If this gets put into a CSE map, add it.
2870 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2874 SDOperand SelectionDAG::
2875 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2876 SDOperand Ops[] = { Op1, Op2, Op3 };
2877 return UpdateNodeOperands(N, Ops, 3);
2880 SDOperand SelectionDAG::
2881 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2882 SDOperand Op3, SDOperand Op4) {
2883 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
2884 return UpdateNodeOperands(N, Ops, 4);
2887 SDOperand SelectionDAG::
2888 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2889 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2890 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
2891 return UpdateNodeOperands(N, Ops, 5);
2895 SDOperand SelectionDAG::
2896 UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
2897 SDNode *N = InN.Val;
2898 assert(N->getNumOperands() == NumOps &&
2899 "Update with wrong number of operands");
2901 // Check to see if there is no change.
2902 bool AnyChange = false;
2903 for (unsigned i = 0; i != NumOps; ++i) {
2904 if (Ops[i] != N->getOperand(i)) {
2910 // No operands changed, just return the input node.
2911 if (!AnyChange) return InN;
2913 // See if the modified node already exists.
2914 void *InsertPos = 0;
2915 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
2916 return SDOperand(Existing, InN.ResNo);
2918 // Nope it doesn't. Remove the node from it's current place in the maps.
2920 RemoveNodeFromCSEMaps(N);
2922 // Now we update the operands.
2923 for (unsigned i = 0; i != NumOps; ++i) {
2924 if (N->OperandList[i] != Ops[i]) {
2925 N->OperandList[i].Val->removeUser(N);
2926 Ops[i].Val->addUser(N);
2927 N->OperandList[i] = Ops[i];
2931 // If this gets put into a CSE map, add it.
2932 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2937 /// MorphNodeTo - This frees the operands of the current node, resets the
2938 /// opcode, types, and operands to the specified value. This should only be
2939 /// used by the SelectionDAG class.
2940 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
2941 const SDOperand *Ops, unsigned NumOps) {
2944 NumValues = L.NumVTs;
2946 // Clear the operands list, updating used nodes to remove this from their
2948 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2949 I->Val->removeUser(this);
2951 // If NumOps is larger than the # of operands we currently have, reallocate
2952 // the operand list.
2953 if (NumOps > NumOperands) {
2954 if (OperandsNeedDelete)
2955 delete [] OperandList;
2956 OperandList = new SDOperand[NumOps];
2957 OperandsNeedDelete = true;
2960 // Assign the new operands.
2961 NumOperands = NumOps;
2963 for (unsigned i = 0, e = NumOps; i != e; ++i) {
2964 OperandList[i] = Ops[i];
2965 SDNode *N = OperandList[i].Val;
2966 N->Uses.push_back(this);
2970 /// SelectNodeTo - These are used for target selectors to *mutate* the
2971 /// specified node to have the specified return type, Target opcode, and
2972 /// operands. Note that target opcodes are stored as
2973 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
2975 /// Note that SelectNodeTo returns the resultant node. If there is already a
2976 /// node of the specified opcode and operands, it returns that node instead of
2977 /// the current one.
2978 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2979 MVT::ValueType VT) {
2980 SDVTList VTs = getVTList(VT);
2981 FoldingSetNodeID ID;
2982 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2984 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2987 RemoveNodeFromCSEMaps(N);
2989 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2991 CSEMap.InsertNode(N, IP);
2995 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2996 MVT::ValueType VT, SDOperand Op1) {
2997 // If an identical node already exists, use it.
2998 SDVTList VTs = getVTList(VT);
2999 SDOperand Ops[] = { Op1 };
3001 FoldingSetNodeID ID;
3002 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3004 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3007 RemoveNodeFromCSEMaps(N);
3008 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3009 CSEMap.InsertNode(N, IP);
3013 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3014 MVT::ValueType VT, SDOperand Op1,
3016 // If an identical node already exists, use it.
3017 SDVTList VTs = getVTList(VT);
3018 SDOperand Ops[] = { Op1, Op2 };
3020 FoldingSetNodeID ID;
3021 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3023 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3026 RemoveNodeFromCSEMaps(N);
3028 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3030 CSEMap.InsertNode(N, IP); // Memoize the new node.
3034 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3035 MVT::ValueType VT, SDOperand Op1,
3036 SDOperand Op2, SDOperand Op3) {
3037 // If an identical node already exists, use it.
3038 SDVTList VTs = getVTList(VT);
3039 SDOperand Ops[] = { Op1, Op2, Op3 };
3040 FoldingSetNodeID ID;
3041 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3043 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3046 RemoveNodeFromCSEMaps(N);
3048 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3050 CSEMap.InsertNode(N, IP); // Memoize the new node.
3054 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3055 MVT::ValueType VT, const SDOperand *Ops,
3057 // If an identical node already exists, use it.
3058 SDVTList VTs = getVTList(VT);
3059 FoldingSetNodeID ID;
3060 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3062 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3065 RemoveNodeFromCSEMaps(N);
3066 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3068 CSEMap.InsertNode(N, IP); // Memoize the new node.
3072 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3073 MVT::ValueType VT1, MVT::ValueType VT2,
3074 SDOperand Op1, SDOperand Op2) {
3075 SDVTList VTs = getVTList(VT1, VT2);
3076 FoldingSetNodeID ID;
3077 SDOperand Ops[] = { Op1, Op2 };
3078 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3080 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3083 RemoveNodeFromCSEMaps(N);
3084 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3085 CSEMap.InsertNode(N, IP); // Memoize the new node.
3089 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3090 MVT::ValueType VT1, MVT::ValueType VT2,
3091 SDOperand Op1, SDOperand Op2,
3093 // If an identical node already exists, use it.
3094 SDVTList VTs = getVTList(VT1, VT2);
3095 SDOperand Ops[] = { Op1, Op2, Op3 };
3096 FoldingSetNodeID ID;
3097 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3099 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3102 RemoveNodeFromCSEMaps(N);
3104 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3105 CSEMap.InsertNode(N, IP); // Memoize the new node.
3110 /// getTargetNode - These are used for target selectors to create a new node
3111 /// with specified return type(s), target opcode, and operands.
3113 /// Note that getTargetNode returns the resultant node. If there is already a
3114 /// node of the specified opcode and operands, it returns that node instead of
3115 /// the current one.
3116 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
3117 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3119 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3121 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3123 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3124 SDOperand Op1, SDOperand Op2) {
3125 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3127 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3128 SDOperand Op1, SDOperand Op2,
3130 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3132 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3133 const SDOperand *Ops, unsigned NumOps) {
3134 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3136 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3137 MVT::ValueType VT2) {
3138 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3140 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3142 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3143 MVT::ValueType VT2, SDOperand Op1) {
3144 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3145 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3147 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3148 MVT::ValueType VT2, SDOperand Op1,
3150 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3151 SDOperand Ops[] = { Op1, Op2 };
3152 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3154 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3155 MVT::ValueType VT2, SDOperand Op1,
3156 SDOperand Op2, SDOperand Op3) {
3157 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3158 SDOperand Ops[] = { Op1, Op2, Op3 };
3159 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3161 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3163 const SDOperand *Ops, unsigned NumOps) {
3164 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3165 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3167 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3168 MVT::ValueType VT2, MVT::ValueType VT3,
3169 SDOperand Op1, SDOperand Op2) {
3170 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3171 SDOperand Ops[] = { Op1, Op2 };
3172 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3174 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3175 MVT::ValueType VT2, MVT::ValueType VT3,
3176 SDOperand Op1, SDOperand Op2,
3178 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3179 SDOperand Ops[] = { Op1, Op2, Op3 };
3180 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3182 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3183 MVT::ValueType VT2, MVT::ValueType VT3,
3184 const SDOperand *Ops, unsigned NumOps) {
3185 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3186 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3188 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3189 MVT::ValueType VT2, MVT::ValueType VT3,
3191 const SDOperand *Ops, unsigned NumOps) {
3192 std::vector<MVT::ValueType> VTList;
3193 VTList.push_back(VT1);
3194 VTList.push_back(VT2);
3195 VTList.push_back(VT3);
3196 VTList.push_back(VT4);
3197 const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3198 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3200 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3201 std::vector<MVT::ValueType> &ResultTys,
3202 const SDOperand *Ops, unsigned NumOps) {
3203 const MVT::ValueType *VTs = getNodeValueTypes(ResultTys);
3204 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3209 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3210 /// This can cause recursive merging of nodes in the DAG.
3212 /// This version assumes From has a single result value.
3214 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3215 DAGUpdateListener *UpdateListener) {
3216 SDNode *From = FromN.Val;
3217 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3218 "Cannot replace with this method!");
3219 assert(From != To.Val && "Cannot replace uses of with self");
3221 while (!From->use_empty()) {
3222 // Process users until they are all gone.
3223 SDNode *U = *From->use_begin();
3225 // This node is about to morph, remove its old self from the CSE maps.
3226 RemoveNodeFromCSEMaps(U);
3228 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3230 if (I->Val == From) {
3231 From->removeUser(U);
3236 // Now that we have modified U, add it back to the CSE maps. If it already
3237 // exists there, recursively merge the results together.
3238 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3239 ReplaceAllUsesWith(U, Existing, UpdateListener);
3240 // U is now dead. Inform the listener if it exists and delete it.
3242 UpdateListener->NodeDeleted(U);
3243 DeleteNodeNotInCSEMaps(U);
3245 // If the node doesn't already exist, we updated it. Inform a listener if
3248 UpdateListener->NodeUpdated(U);
3253 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3254 /// This can cause recursive merging of nodes in the DAG.
3256 /// This version assumes From/To have matching types and numbers of result
3259 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3260 DAGUpdateListener *UpdateListener) {
3261 assert(From != To && "Cannot replace uses of with self");
3262 assert(From->getNumValues() == To->getNumValues() &&
3263 "Cannot use this version of ReplaceAllUsesWith!");
3264 if (From->getNumValues() == 1) // If possible, use the faster version.
3265 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3268 while (!From->use_empty()) {
3269 // Process users until they are all gone.
3270 SDNode *U = *From->use_begin();
3272 // This node is about to morph, remove its old self from the CSE maps.
3273 RemoveNodeFromCSEMaps(U);
3275 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3277 if (I->Val == From) {
3278 From->removeUser(U);
3283 // Now that we have modified U, add it back to the CSE maps. If it already
3284 // exists there, recursively merge the results together.
3285 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3286 ReplaceAllUsesWith(U, Existing, UpdateListener);
3287 // U is now dead. Inform the listener if it exists and delete it.
3289 UpdateListener->NodeDeleted(U);
3290 DeleteNodeNotInCSEMaps(U);
3292 // If the node doesn't already exist, we updated it. Inform a listener if
3295 UpdateListener->NodeUpdated(U);
3300 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3301 /// This can cause recursive merging of nodes in the DAG.
3303 /// This version can replace From with any result values. To must match the
3304 /// number and types of values returned by From.
3305 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3306 const SDOperand *To,
3307 DAGUpdateListener *UpdateListener) {
3308 if (From->getNumValues() == 1) // Handle the simple case efficiently.
3309 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
3311 while (!From->use_empty()) {
3312 // Process users until they are all gone.
3313 SDNode *U = *From->use_begin();
3315 // This node is about to morph, remove its old self from the CSE maps.
3316 RemoveNodeFromCSEMaps(U);
3318 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3320 if (I->Val == From) {
3321 const SDOperand &ToOp = To[I->ResNo];
3322 From->removeUser(U);
3324 ToOp.Val->addUser(U);
3327 // Now that we have modified U, add it back to the CSE maps. If it already
3328 // exists there, recursively merge the results together.
3329 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3330 ReplaceAllUsesWith(U, Existing, UpdateListener);
3331 // U is now dead. Inform the listener if it exists and delete it.
3333 UpdateListener->NodeDeleted(U);
3334 DeleteNodeNotInCSEMaps(U);
3336 // If the node doesn't already exist, we updated it. Inform a listener if
3339 UpdateListener->NodeUpdated(U);
3345 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
3346 /// any deleted nodes from the set passed into its constructor and recursively
3347 /// notifies another update listener if specified.
3348 class ChainedSetUpdaterListener :
3349 public SelectionDAG::DAGUpdateListener {
3350 SmallSetVector<SDNode*, 16> &Set;
3351 SelectionDAG::DAGUpdateListener *Chain;
3353 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
3354 SelectionDAG::DAGUpdateListener *chain)
3355 : Set(set), Chain(chain) {}
3357 virtual void NodeDeleted(SDNode *N) {
3359 if (Chain) Chain->NodeDeleted(N);
3361 virtual void NodeUpdated(SDNode *N) {
3362 if (Chain) Chain->NodeUpdated(N);
3367 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3368 /// uses of other values produced by From.Val alone. The Deleted vector is
3369 /// handled the same way as for ReplaceAllUsesWith.
3370 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3371 DAGUpdateListener *UpdateListener){
3372 assert(From != To && "Cannot replace a value with itself");
3374 // Handle the simple, trivial, case efficiently.
3375 if (From.Val->getNumValues() == 1) {
3376 ReplaceAllUsesWith(From, To, UpdateListener);
3380 if (From.use_empty()) return;
3382 // Get all of the users of From.Val. We want these in a nice,
3383 // deterministically ordered and uniqued set, so we use a SmallSetVector.
3384 SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
3386 // When one of the recursive merges deletes nodes from the graph, we need to
3387 // make sure that UpdateListener is notified *and* that the node is removed
3388 // from Users if present. CSUL does this.
3389 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
3391 while (!Users.empty()) {
3392 // We know that this user uses some value of From. If it is the right
3393 // value, update it.
3394 SDNode *User = Users.back();
3397 // Scan for an operand that matches From.
3398 SDOperand *Op = User->OperandList, *E = User->OperandList+User->NumOperands;
3399 for (; Op != E; ++Op)
3400 if (*Op == From) break;
3402 // If there are no matches, the user must use some other result of From.
3403 if (Op == E) continue;
3405 // Okay, we know this user needs to be updated. Remove its old self
3406 // from the CSE maps.
3407 RemoveNodeFromCSEMaps(User);
3409 // Update all operands that match "From" in case there are multiple uses.
3410 for (; Op != E; ++Op) {
3412 From.Val->removeUser(User);
3414 To.Val->addUser(User);
3418 // Now that we have modified User, add it back to the CSE maps. If it
3419 // already exists there, recursively merge the results together.
3420 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
3422 if (UpdateListener) UpdateListener->NodeUpdated(User);
3423 continue; // Continue on to next user.
3426 // If there was already an existing matching node, use ReplaceAllUsesWith
3427 // to replace the dead one with the existing one. This can cause
3428 // recursive merging of other unrelated nodes down the line. The merging
3429 // can cause deletion of nodes that used the old value. To handle this, we
3430 // use CSUL to remove them from the Users set.
3431 ReplaceAllUsesWith(User, Existing, &CSUL);
3433 // User is now dead. Notify a listener if present.
3434 if (UpdateListener) UpdateListener->NodeDeleted(User);
3435 DeleteNodeNotInCSEMaps(User);
3440 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3441 /// their allnodes order. It returns the maximum id.
3442 unsigned SelectionDAG::AssignNodeIds() {
3444 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3451 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
3452 /// based on their topological order. It returns the maximum id and a vector
3453 /// of the SDNodes* in assigned order by reference.
3454 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
3455 unsigned DAGSize = AllNodes.size();
3456 std::vector<unsigned> InDegree(DAGSize);
3457 std::vector<SDNode*> Sources;
3459 // Use a two pass approach to avoid using a std::map which is slow.
3461 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
3464 unsigned Degree = N->use_size();
3465 InDegree[N->getNodeId()] = Degree;
3467 Sources.push_back(N);
3471 while (!Sources.empty()) {
3472 SDNode *N = Sources.back();
3474 TopOrder.push_back(N);
3475 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
3477 unsigned Degree = --InDegree[P->getNodeId()];
3479 Sources.push_back(P);
3483 // Second pass, assign the actual topological order as node ids.
3485 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
3487 (*TI)->setNodeId(Id++);
3494 //===----------------------------------------------------------------------===//
3496 //===----------------------------------------------------------------------===//
3498 // Out-of-line virtual method to give class a home.
3499 void SDNode::ANCHOR() {}
3500 void UnarySDNode::ANCHOR() {}
3501 void BinarySDNode::ANCHOR() {}
3502 void TernarySDNode::ANCHOR() {}
3503 void HandleSDNode::ANCHOR() {}
3504 void StringSDNode::ANCHOR() {}
3505 void ConstantSDNode::ANCHOR() {}
3506 void ConstantFPSDNode::ANCHOR() {}
3507 void GlobalAddressSDNode::ANCHOR() {}
3508 void FrameIndexSDNode::ANCHOR() {}
3509 void JumpTableSDNode::ANCHOR() {}
3510 void ConstantPoolSDNode::ANCHOR() {}
3511 void BasicBlockSDNode::ANCHOR() {}
3512 void SrcValueSDNode::ANCHOR() {}
3513 void MemOperandSDNode::ANCHOR() {}
3514 void RegisterSDNode::ANCHOR() {}
3515 void ExternalSymbolSDNode::ANCHOR() {}
3516 void CondCodeSDNode::ANCHOR() {}
3517 void VTSDNode::ANCHOR() {}
3518 void LoadSDNode::ANCHOR() {}
3519 void StoreSDNode::ANCHOR() {}
3521 HandleSDNode::~HandleSDNode() {
3522 SDVTList VTs = { 0, 0 };
3523 MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0); // Drops operand uses.
3526 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
3527 MVT::ValueType VT, int o)
3528 : SDNode(isa<GlobalVariable>(GA) &&
3529 cast<GlobalVariable>(GA)->isThreadLocal() ?
3531 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
3533 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
3534 getSDVTList(VT)), Offset(o) {
3535 TheGlobal = const_cast<GlobalValue*>(GA);
3538 /// getMemOperand - Return a MemOperand object describing the memory
3539 /// reference performed by this load or store.
3540 MemOperand LSBaseSDNode::getMemOperand() const {
3541 int Size = (MVT::getSizeInBits(getMemoryVT()) + 7) >> 3;
3543 getOpcode() == ISD::LOAD ? MemOperand::MOLoad : MemOperand::MOStore;
3544 if (IsVolatile) Flags |= MemOperand::MOVolatile;
3546 // Check if the load references a frame index, and does not have
3548 const FrameIndexSDNode *FI =
3549 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
3550 if (!getSrcValue() && FI)
3551 return MemOperand(PseudoSourceValue::getFixedStack(), Flags,
3552 FI->getIndex(), Size, Alignment);
3554 return MemOperand(getSrcValue(), Flags,
3555 getSrcValueOffset(), Size, Alignment);
3558 /// Profile - Gather unique data for the node.
3560 void SDNode::Profile(FoldingSetNodeID &ID) {
3561 AddNodeIDNode(ID, this);
3564 /// getValueTypeList - Return a pointer to the specified value type.
3566 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
3567 if (MVT::isExtendedVT(VT)) {
3568 static std::set<MVT::ValueType> EVTs;
3569 return (MVT::ValueType *)&(*EVTs.insert(VT).first);
3571 static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
3577 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
3578 /// indicated value. This method ignores uses of other values defined by this
3580 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
3581 assert(Value < getNumValues() && "Bad value!");
3583 // If there is only one value, this is easy.
3584 if (getNumValues() == 1)
3585 return use_size() == NUses;
3586 if (use_size() < NUses) return false;
3588 SDOperand TheValue(const_cast<SDNode *>(this), Value);
3590 SmallPtrSet<SDNode*, 32> UsersHandled;
3592 for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3594 if (User->getNumOperands() == 1 ||
3595 UsersHandled.insert(User)) // First time we've seen this?
3596 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3597 if (User->getOperand(i) == TheValue) {
3599 return false; // too many uses
3604 // Found exactly the right number of uses?
3609 /// hasAnyUseOfValue - Return true if there are any use of the indicated
3610 /// value. This method ignores uses of other values defined by this operation.
3611 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
3612 assert(Value < getNumValues() && "Bad value!");
3614 if (use_empty()) return false;
3616 SDOperand TheValue(const_cast<SDNode *>(this), Value);
3618 SmallPtrSet<SDNode*, 32> UsersHandled;
3620 for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3622 if (User->getNumOperands() == 1 ||
3623 UsersHandled.insert(User)) // First time we've seen this?
3624 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3625 if (User->getOperand(i) == TheValue) {
3634 /// isOnlyUse - Return true if this node is the only use of N.
3636 bool SDNode::isOnlyUse(SDNode *N) const {
3638 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
3649 /// isOperand - Return true if this node is an operand of N.
3651 bool SDOperand::isOperand(SDNode *N) const {
3652 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3653 if (*this == N->getOperand(i))
3658 bool SDNode::isOperand(SDNode *N) const {
3659 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
3660 if (this == N->OperandList[i].Val)
3665 /// reachesChainWithoutSideEffects - Return true if this operand (which must
3666 /// be a chain) reaches the specified operand without crossing any
3667 /// side-effecting instructions. In practice, this looks through token
3668 /// factors and non-volatile loads. In order to remain efficient, this only
3669 /// looks a couple of nodes in, it does not do an exhaustive search.
3670 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
3671 unsigned Depth) const {
3672 if (*this == Dest) return true;
3674 // Don't search too deeply, we just want to be able to see through
3675 // TokenFactor's etc.
3676 if (Depth == 0) return false;
3678 // If this is a token factor, all inputs to the TF happen in parallel. If any
3679 // of the operands of the TF reach dest, then we can do the xform.
3680 if (getOpcode() == ISD::TokenFactor) {
3681 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3682 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
3687 // Loads don't have side effects, look through them.
3688 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
3689 if (!Ld->isVolatile())
3690 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
3696 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
3697 SmallPtrSet<SDNode *, 32> &Visited) {
3698 if (found || !Visited.insert(N))
3701 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
3702 SDNode *Op = N->getOperand(i).Val;
3707 findPredecessor(Op, P, found, Visited);
3711 /// isPredecessor - Return true if this node is a predecessor of N. This node
3712 /// is either an operand of N or it can be reached by recursively traversing
3713 /// up the operands.
3714 /// NOTE: this is an expensive method. Use it carefully.
3715 bool SDNode::isPredecessor(SDNode *N) const {
3716 SmallPtrSet<SDNode *, 32> Visited;
3718 findPredecessor(N, this, found, Visited);
3722 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
3723 assert(Num < NumOperands && "Invalid child # of SDNode!");
3724 return cast<ConstantSDNode>(OperandList[Num])->getValue();
3727 std::string SDNode::getOperationName(const SelectionDAG *G) const {
3728 switch (getOpcode()) {
3730 if (getOpcode() < ISD::BUILTIN_OP_END)
3731 return "<<Unknown DAG Node>>";
3734 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
3735 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
3736 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
3738 TargetLowering &TLI = G->getTargetLoweringInfo();
3740 TLI.getTargetNodeName(getOpcode());
3741 if (Name) return Name;
3744 return "<<Unknown Target Node>>";
3747 case ISD::PCMARKER: return "PCMarker";
3748 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
3749 case ISD::SRCVALUE: return "SrcValue";
3750 case ISD::MEMOPERAND: return "MemOperand";
3751 case ISD::EntryToken: return "EntryToken";
3752 case ISD::TokenFactor: return "TokenFactor";
3753 case ISD::AssertSext: return "AssertSext";
3754 case ISD::AssertZext: return "AssertZext";
3756 case ISD::STRING: return "String";
3757 case ISD::BasicBlock: return "BasicBlock";
3758 case ISD::VALUETYPE: return "ValueType";
3759 case ISD::Register: return "Register";
3761 case ISD::Constant: return "Constant";
3762 case ISD::ConstantFP: return "ConstantFP";
3763 case ISD::GlobalAddress: return "GlobalAddress";
3764 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
3765 case ISD::FrameIndex: return "FrameIndex";
3766 case ISD::JumpTable: return "JumpTable";
3767 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
3768 case ISD::RETURNADDR: return "RETURNADDR";
3769 case ISD::FRAMEADDR: return "FRAMEADDR";
3770 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
3771 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
3772 case ISD::EHSELECTION: return "EHSELECTION";
3773 case ISD::EH_RETURN: return "EH_RETURN";
3774 case ISD::ConstantPool: return "ConstantPool";
3775 case ISD::ExternalSymbol: return "ExternalSymbol";
3776 case ISD::INTRINSIC_WO_CHAIN: {
3777 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
3778 return Intrinsic::getName((Intrinsic::ID)IID);
3780 case ISD::INTRINSIC_VOID:
3781 case ISD::INTRINSIC_W_CHAIN: {
3782 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
3783 return Intrinsic::getName((Intrinsic::ID)IID);
3786 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
3787 case ISD::TargetConstant: return "TargetConstant";
3788 case ISD::TargetConstantFP:return "TargetConstantFP";
3789 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
3790 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
3791 case ISD::TargetFrameIndex: return "TargetFrameIndex";
3792 case ISD::TargetJumpTable: return "TargetJumpTable";
3793 case ISD::TargetConstantPool: return "TargetConstantPool";
3794 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
3796 case ISD::CopyToReg: return "CopyToReg";
3797 case ISD::CopyFromReg: return "CopyFromReg";
3798 case ISD::UNDEF: return "undef";
3799 case ISD::MERGE_VALUES: return "merge_values";
3800 case ISD::INLINEASM: return "inlineasm";
3801 case ISD::LABEL: return "label";
3802 case ISD::DECLARE: return "declare";
3803 case ISD::HANDLENODE: return "handlenode";
3804 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
3805 case ISD::CALL: return "call";
3808 case ISD::FABS: return "fabs";
3809 case ISD::FNEG: return "fneg";
3810 case ISD::FSQRT: return "fsqrt";
3811 case ISD::FSIN: return "fsin";
3812 case ISD::FCOS: return "fcos";
3813 case ISD::FPOWI: return "fpowi";
3814 case ISD::FPOW: return "fpow";
3817 case ISD::ADD: return "add";
3818 case ISD::SUB: return "sub";
3819 case ISD::MUL: return "mul";
3820 case ISD::MULHU: return "mulhu";
3821 case ISD::MULHS: return "mulhs";
3822 case ISD::SDIV: return "sdiv";
3823 case ISD::UDIV: return "udiv";
3824 case ISD::SREM: return "srem";
3825 case ISD::UREM: return "urem";
3826 case ISD::SMUL_LOHI: return "smul_lohi";
3827 case ISD::UMUL_LOHI: return "umul_lohi";
3828 case ISD::SDIVREM: return "sdivrem";
3829 case ISD::UDIVREM: return "divrem";
3830 case ISD::AND: return "and";
3831 case ISD::OR: return "or";
3832 case ISD::XOR: return "xor";
3833 case ISD::SHL: return "shl";
3834 case ISD::SRA: return "sra";
3835 case ISD::SRL: return "srl";
3836 case ISD::ROTL: return "rotl";
3837 case ISD::ROTR: return "rotr";
3838 case ISD::FADD: return "fadd";
3839 case ISD::FSUB: return "fsub";
3840 case ISD::FMUL: return "fmul";
3841 case ISD::FDIV: return "fdiv";
3842 case ISD::FREM: return "frem";
3843 case ISD::FCOPYSIGN: return "fcopysign";
3844 case ISD::FGETSIGN: return "fgetsign";
3846 case ISD::SETCC: return "setcc";
3847 case ISD::SELECT: return "select";
3848 case ISD::SELECT_CC: return "select_cc";
3849 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
3850 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
3851 case ISD::CONCAT_VECTORS: return "concat_vectors";
3852 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
3853 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
3854 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
3855 case ISD::CARRY_FALSE: return "carry_false";
3856 case ISD::ADDC: return "addc";
3857 case ISD::ADDE: return "adde";
3858 case ISD::SUBC: return "subc";
3859 case ISD::SUBE: return "sube";
3860 case ISD::SHL_PARTS: return "shl_parts";
3861 case ISD::SRA_PARTS: return "sra_parts";
3862 case ISD::SRL_PARTS: return "srl_parts";
3864 case ISD::EXTRACT_SUBREG: return "extract_subreg";
3865 case ISD::INSERT_SUBREG: return "insert_subreg";
3867 // Conversion operators.
3868 case ISD::SIGN_EXTEND: return "sign_extend";
3869 case ISD::ZERO_EXTEND: return "zero_extend";
3870 case ISD::ANY_EXTEND: return "any_extend";
3871 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
3872 case ISD::TRUNCATE: return "truncate";
3873 case ISD::FP_ROUND: return "fp_round";
3874 case ISD::FLT_ROUNDS_: return "flt_rounds";
3875 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
3876 case ISD::FP_EXTEND: return "fp_extend";
3878 case ISD::SINT_TO_FP: return "sint_to_fp";
3879 case ISD::UINT_TO_FP: return "uint_to_fp";
3880 case ISD::FP_TO_SINT: return "fp_to_sint";
3881 case ISD::FP_TO_UINT: return "fp_to_uint";
3882 case ISD::BIT_CONVERT: return "bit_convert";
3884 // Control flow instructions
3885 case ISD::BR: return "br";
3886 case ISD::BRIND: return "brind";
3887 case ISD::BR_JT: return "br_jt";
3888 case ISD::BRCOND: return "brcond";
3889 case ISD::BR_CC: return "br_cc";
3890 case ISD::RET: return "ret";
3891 case ISD::CALLSEQ_START: return "callseq_start";
3892 case ISD::CALLSEQ_END: return "callseq_end";
3895 case ISD::LOAD: return "load";
3896 case ISD::STORE: return "store";
3897 case ISD::VAARG: return "vaarg";
3898 case ISD::VACOPY: return "vacopy";
3899 case ISD::VAEND: return "vaend";
3900 case ISD::VASTART: return "vastart";
3901 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
3902 case ISD::EXTRACT_ELEMENT: return "extract_element";
3903 case ISD::BUILD_PAIR: return "build_pair";
3904 case ISD::STACKSAVE: return "stacksave";
3905 case ISD::STACKRESTORE: return "stackrestore";
3906 case ISD::TRAP: return "trap";
3908 // Block memory operations.
3909 case ISD::MEMSET: return "memset";
3910 case ISD::MEMCPY: return "memcpy";
3911 case ISD::MEMMOVE: return "memmove";
3914 case ISD::BSWAP: return "bswap";
3915 case ISD::CTPOP: return "ctpop";
3916 case ISD::CTTZ: return "cttz";
3917 case ISD::CTLZ: return "ctlz";
3920 case ISD::LOCATION: return "location";
3921 case ISD::DEBUG_LOC: return "debug_loc";
3924 case ISD::TRAMPOLINE: return "trampoline";
3927 switch (cast<CondCodeSDNode>(this)->get()) {
3928 default: assert(0 && "Unknown setcc condition!");
3929 case ISD::SETOEQ: return "setoeq";
3930 case ISD::SETOGT: return "setogt";
3931 case ISD::SETOGE: return "setoge";
3932 case ISD::SETOLT: return "setolt";
3933 case ISD::SETOLE: return "setole";
3934 case ISD::SETONE: return "setone";
3936 case ISD::SETO: return "seto";
3937 case ISD::SETUO: return "setuo";
3938 case ISD::SETUEQ: return "setue";
3939 case ISD::SETUGT: return "setugt";
3940 case ISD::SETUGE: return "setuge";
3941 case ISD::SETULT: return "setult";
3942 case ISD::SETULE: return "setule";
3943 case ISD::SETUNE: return "setune";
3945 case ISD::SETEQ: return "seteq";
3946 case ISD::SETGT: return "setgt";
3947 case ISD::SETGE: return "setge";
3948 case ISD::SETLT: return "setlt";
3949 case ISD::SETLE: return "setle";
3950 case ISD::SETNE: return "setne";
3955 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
3964 return "<post-inc>";
3966 return "<post-dec>";
3970 void SDNode::dump() const { dump(0); }
3971 void SDNode::dump(const SelectionDAG *G) const {
3972 cerr << (void*)this << ": ";
3974 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
3976 if (getValueType(i) == MVT::Other)
3979 cerr << MVT::getValueTypeString(getValueType(i));
3981 cerr << " = " << getOperationName(G);
3984 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3985 if (i) cerr << ", ";
3986 cerr << (void*)getOperand(i).Val;
3987 if (unsigned RN = getOperand(i).ResNo)
3991 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
3992 SDNode *Mask = getOperand(2).Val;
3994 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
3996 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
3999 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4004 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4005 cerr << "<" << CSDN->getValue() << ">";
4006 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4007 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4008 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4009 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4010 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4012 cerr << "<APFloat(";
4013 CSDN->getValueAPF().convertToAPInt().dump();
4016 } else if (const GlobalAddressSDNode *GADN =
4017 dyn_cast<GlobalAddressSDNode>(this)) {
4018 int offset = GADN->getOffset();
4020 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4022 cerr << " + " << offset;
4024 cerr << " " << offset;
4025 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4026 cerr << "<" << FIDN->getIndex() << ">";
4027 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4028 cerr << "<" << JTDN->getIndex() << ">";
4029 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4030 int offset = CP->getOffset();
4031 if (CP->isMachineConstantPoolEntry())
4032 cerr << "<" << *CP->getMachineCPVal() << ">";
4034 cerr << "<" << *CP->getConstVal() << ">";
4036 cerr << " + " << offset;
4038 cerr << " " << offset;
4039 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4041 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4043 cerr << LBB->getName() << " ";
4044 cerr << (const void*)BBDN->getBasicBlock() << ">";
4045 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4046 if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
4047 cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
4049 cerr << " #" << R->getReg();
4051 } else if (const ExternalSymbolSDNode *ES =
4052 dyn_cast<ExternalSymbolSDNode>(this)) {
4053 cerr << "'" << ES->getSymbol() << "'";
4054 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4056 cerr << "<" << M->getValue() << ">";
4059 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4060 if (M->MO.getValue())
4061 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4063 cerr << "<null:" << M->MO.getOffset() << ">";
4064 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4065 cerr << ":" << MVT::getValueTypeString(N->getVT());
4066 } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4067 const Value *SrcValue = LD->getSrcValue();
4068 int SrcOffset = LD->getSrcValueOffset();
4074 cerr << ":" << SrcOffset << ">";
4077 switch (LD->getExtensionType()) {
4078 default: doExt = false; break;
4080 cerr << " <anyext ";
4090 cerr << MVT::getValueTypeString(LD->getMemoryVT()) << ">";
4092 const char *AM = getIndexedModeName(LD->getAddressingMode());
4095 if (LD->isVolatile())
4096 cerr << " <volatile>";
4097 cerr << " alignment=" << LD->getAlignment();
4098 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4099 const Value *SrcValue = ST->getSrcValue();
4100 int SrcOffset = ST->getSrcValueOffset();
4106 cerr << ":" << SrcOffset << ">";
4108 if (ST->isTruncatingStore())
4110 << MVT::getValueTypeString(ST->getMemoryVT()) << ">";
4112 const char *AM = getIndexedModeName(ST->getAddressingMode());
4115 if (ST->isVolatile())
4116 cerr << " <volatile>";
4117 cerr << " alignment=" << ST->getAlignment();
4121 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4122 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4123 if (N->getOperand(i).Val->hasOneUse())
4124 DumpNodes(N->getOperand(i).Val, indent+2, G);
4126 cerr << "\n" << std::string(indent+2, ' ')
4127 << (void*)N->getOperand(i).Val << ": <multiple use>";
4130 cerr << "\n" << std::string(indent, ' ');
4134 void SelectionDAG::dump() const {
4135 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4136 std::vector<const SDNode*> Nodes;
4137 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4141 std::sort(Nodes.begin(), Nodes.end());
4143 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4144 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4145 DumpNodes(Nodes[i], 2, this);
4148 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4153 const Type *ConstantPoolSDNode::getType() const {
4154 if (isMachineConstantPoolEntry())
4155 return Val.MachineCPVal->getType();
4156 return Val.ConstVal->getType();