1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/GlobalAlias.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/SetVector.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/StringExtras.h"
45 /// makeVTList - Return an instance of the SDVTList struct initialized with the
46 /// specified members.
47 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
48 SDVTList Res = {VTs, NumVTs};
52 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
53 switch (VT.getSimpleVT()) {
54 default: assert(0 && "Unknown FP format");
55 case MVT::f32: return &APFloat::IEEEsingle;
56 case MVT::f64: return &APFloat::IEEEdouble;
57 case MVT::f80: return &APFloat::x87DoubleExtended;
58 case MVT::f128: return &APFloat::IEEEquad;
59 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
63 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
65 //===----------------------------------------------------------------------===//
66 // ConstantFPSDNode Class
67 //===----------------------------------------------------------------------===//
69 /// isExactlyValue - We don't rely on operator== working on double values, as
70 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
71 /// As such, this method can be used to do an exact bit-for-bit comparison of
72 /// two floating point values.
73 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
74 return getValueAPF().bitwiseIsEqual(V);
77 bool ConstantFPSDNode::isValueValidForType(MVT VT,
79 assert(VT.isFloatingPoint() && "Can only convert between FP types");
81 // PPC long double cannot be converted to any other type.
82 if (VT == MVT::ppcf128 ||
83 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
86 // convert modifies in place, so make a copy.
87 APFloat Val2 = APFloat(Val);
89 (void) Val2.convert(*MVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
94 //===----------------------------------------------------------------------===//
96 //===----------------------------------------------------------------------===//
98 /// isBuildVectorAllOnes - Return true if the specified node is a
99 /// BUILD_VECTOR where all of the elements are ~0 or undef.
100 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
101 // Look through a bit convert.
102 if (N->getOpcode() == ISD::BIT_CONVERT)
103 N = N->getOperand(0).getNode();
105 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
107 unsigned i = 0, e = N->getNumOperands();
109 // Skip over all of the undef values.
110 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
113 // Do not accept an all-undef vector.
114 if (i == e) return false;
116 // Do not accept build_vectors that aren't all constants or which have non-~0
118 SDValue NotZero = N->getOperand(i);
119 if (isa<ConstantSDNode>(NotZero)) {
120 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
122 } else if (isa<ConstantFPSDNode>(NotZero)) {
123 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
124 bitcastToAPInt().isAllOnesValue())
129 // Okay, we have at least one ~0 value, check to see if the rest match or are
131 for (++i; i != e; ++i)
132 if (N->getOperand(i) != NotZero &&
133 N->getOperand(i).getOpcode() != ISD::UNDEF)
139 /// isBuildVectorAllZeros - Return true if the specified node is a
140 /// BUILD_VECTOR where all of the elements are 0 or undef.
141 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
142 // Look through a bit convert.
143 if (N->getOpcode() == ISD::BIT_CONVERT)
144 N = N->getOperand(0).getNode();
146 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
148 unsigned i = 0, e = N->getNumOperands();
150 // Skip over all of the undef values.
151 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
154 // Do not accept an all-undef vector.
155 if (i == e) return false;
157 // Do not accept build_vectors that aren't all constants or which have non-~0
159 SDValue Zero = N->getOperand(i);
160 if (isa<ConstantSDNode>(Zero)) {
161 if (!cast<ConstantSDNode>(Zero)->isNullValue())
163 } else if (isa<ConstantFPSDNode>(Zero)) {
164 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
169 // Okay, we have at least one ~0 value, check to see if the rest match or are
171 for (++i; i != e; ++i)
172 if (N->getOperand(i) != Zero &&
173 N->getOperand(i).getOpcode() != ISD::UNDEF)
178 /// isScalarToVector - Return true if the specified node is a
179 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
180 /// element is not an undef.
181 bool ISD::isScalarToVector(const SDNode *N) {
182 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
185 if (N->getOpcode() != ISD::BUILD_VECTOR)
187 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
189 unsigned NumElems = N->getNumOperands();
190 for (unsigned i = 1; i < NumElems; ++i) {
191 SDValue V = N->getOperand(i);
192 if (V.getOpcode() != ISD::UNDEF)
199 /// isDebugLabel - Return true if the specified node represents a debug
200 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
201 bool ISD::isDebugLabel(const SDNode *N) {
203 if (N->getOpcode() == ISD::DBG_LABEL)
205 if (N->isMachineOpcode() &&
206 N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
211 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
212 /// when given the operation for (X op Y).
213 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
214 // To perform this operation, we just need to swap the L and G bits of the
216 unsigned OldL = (Operation >> 2) & 1;
217 unsigned OldG = (Operation >> 1) & 1;
218 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
219 (OldL << 1) | // New G bit
220 (OldG << 2)); // New L bit.
223 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
224 /// 'op' is a valid SetCC operation.
225 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
226 unsigned Operation = Op;
228 Operation ^= 7; // Flip L, G, E bits, but not U.
230 Operation ^= 15; // Flip all of the condition bits.
232 if (Operation > ISD::SETTRUE2)
233 Operation &= ~8; // Don't let N and U bits get set.
235 return ISD::CondCode(Operation);
239 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
240 /// signed operation and 2 if the result is an unsigned comparison. Return zero
241 /// if the operation does not depend on the sign of the input (setne and seteq).
242 static int isSignedOp(ISD::CondCode Opcode) {
244 default: assert(0 && "Illegal integer setcc operation!");
246 case ISD::SETNE: return 0;
250 case ISD::SETGE: return 1;
254 case ISD::SETUGE: return 2;
258 /// getSetCCOrOperation - Return the result of a logical OR between different
259 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
260 /// returns SETCC_INVALID if it is not possible to represent the resultant
262 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
264 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
265 // Cannot fold a signed integer setcc with an unsigned integer setcc.
266 return ISD::SETCC_INVALID;
268 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
270 // If the N and U bits get set then the resultant comparison DOES suddenly
271 // care about orderedness, and is true when ordered.
272 if (Op > ISD::SETTRUE2)
273 Op &= ~16; // Clear the U bit if the N bit is set.
275 // Canonicalize illegal integer setcc's.
276 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
279 return ISD::CondCode(Op);
282 /// getSetCCAndOperation - Return the result of a logical AND between different
283 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
284 /// function returns zero if it is not possible to represent the resultant
286 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
288 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
289 // Cannot fold a signed setcc with an unsigned setcc.
290 return ISD::SETCC_INVALID;
292 // Combine all of the condition bits.
293 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
295 // Canonicalize illegal integer setcc's.
299 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
300 case ISD::SETOEQ: // SETEQ & SETU[LG]E
301 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
302 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
303 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
310 const TargetMachine &SelectionDAG::getTarget() const {
311 return MF->getTarget();
314 //===----------------------------------------------------------------------===//
315 // SDNode Profile Support
316 //===----------------------------------------------------------------------===//
318 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
320 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
324 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
325 /// solely with their pointer.
326 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
327 ID.AddPointer(VTList.VTs);
330 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
332 static void AddNodeIDOperands(FoldingSetNodeID &ID,
333 const SDValue *Ops, unsigned NumOps) {
334 for (; NumOps; --NumOps, ++Ops) {
335 ID.AddPointer(Ops->getNode());
336 ID.AddInteger(Ops->getResNo());
340 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
342 static void AddNodeIDOperands(FoldingSetNodeID &ID,
343 const SDUse *Ops, unsigned NumOps) {
344 for (; NumOps; --NumOps, ++Ops) {
345 ID.AddPointer(Ops->getVal());
346 ID.AddInteger(Ops->getSDValue().getResNo());
350 static void AddNodeIDNode(FoldingSetNodeID &ID,
351 unsigned short OpC, SDVTList VTList,
352 const SDValue *OpList, unsigned N) {
353 AddNodeIDOpcode(ID, OpC);
354 AddNodeIDValueTypes(ID, VTList);
355 AddNodeIDOperands(ID, OpList, N);
358 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
360 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
361 switch (N->getOpcode()) {
362 default: break; // Normal nodes don't need extra info.
364 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
366 case ISD::TargetConstant:
368 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
370 case ISD::TargetConstantFP:
371 case ISD::ConstantFP: {
372 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
375 case ISD::TargetGlobalAddress:
376 case ISD::GlobalAddress:
377 case ISD::TargetGlobalTLSAddress:
378 case ISD::GlobalTLSAddress: {
379 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
380 ID.AddPointer(GA->getGlobal());
381 ID.AddInteger(GA->getOffset());
384 case ISD::BasicBlock:
385 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
388 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
390 case ISD::DBG_STOPPOINT: {
391 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
392 ID.AddInteger(DSP->getLine());
393 ID.AddInteger(DSP->getColumn());
394 ID.AddPointer(DSP->getCompileUnit());
398 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
400 case ISD::MEMOPERAND: {
401 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
405 case ISD::FrameIndex:
406 case ISD::TargetFrameIndex:
407 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
410 case ISD::TargetJumpTable:
411 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
413 case ISD::ConstantPool:
414 case ISD::TargetConstantPool: {
415 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
416 ID.AddInteger(CP->getAlignment());
417 ID.AddInteger(CP->getOffset());
418 if (CP->isMachineConstantPoolEntry())
419 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
421 ID.AddPointer(CP->getConstVal());
425 const CallSDNode *Call = cast<CallSDNode>(N);
426 ID.AddInteger(Call->getCallingConv());
427 ID.AddInteger(Call->isVarArg());
431 const LoadSDNode *LD = cast<LoadSDNode>(N);
432 ID.AddInteger(LD->getAddressingMode());
433 ID.AddInteger(LD->getExtensionType());
434 ID.AddInteger(LD->getMemoryVT().getRawBits());
435 ID.AddInteger(LD->getRawFlags());
439 const StoreSDNode *ST = cast<StoreSDNode>(N);
440 ID.AddInteger(ST->getAddressingMode());
441 ID.AddInteger(ST->isTruncatingStore());
442 ID.AddInteger(ST->getMemoryVT().getRawBits());
443 ID.AddInteger(ST->getRawFlags());
446 case ISD::ATOMIC_CMP_SWAP:
447 case ISD::ATOMIC_SWAP:
448 case ISD::ATOMIC_LOAD_ADD:
449 case ISD::ATOMIC_LOAD_SUB:
450 case ISD::ATOMIC_LOAD_AND:
451 case ISD::ATOMIC_LOAD_OR:
452 case ISD::ATOMIC_LOAD_XOR:
453 case ISD::ATOMIC_LOAD_NAND:
454 case ISD::ATOMIC_LOAD_MIN:
455 case ISD::ATOMIC_LOAD_MAX:
456 case ISD::ATOMIC_LOAD_UMIN:
457 case ISD::ATOMIC_LOAD_UMAX: {
458 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
459 ID.AddInteger(AT->getRawFlags());
462 } // end switch (N->getOpcode())
465 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
467 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
468 AddNodeIDOpcode(ID, N->getOpcode());
469 // Add the return value info.
470 AddNodeIDValueTypes(ID, N->getVTList());
471 // Add the operand info.
472 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
474 // Handle SDNode leafs with special info.
475 AddNodeIDCustom(ID, N);
478 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
479 /// the CSE map that carries both alignment and volatility information.
481 static inline unsigned
482 encodeMemSDNodeFlags(bool isVolatile, unsigned Alignment) {
483 return isVolatile | ((Log2_32(Alignment) + 1) << 1);
486 //===----------------------------------------------------------------------===//
487 // SelectionDAG Class
488 //===----------------------------------------------------------------------===//
490 /// doNotCSE - Return true if CSE should not be performed for this node.
491 static bool doNotCSE(SDNode *N) {
492 if (N->getValueType(0) == MVT::Flag)
493 return true; // Never CSE anything that produces a flag.
495 switch (N->getOpcode()) {
497 case ISD::HANDLENODE:
499 case ISD::DBG_STOPPOINT:
502 return true; // Never CSE these nodes.
505 // Check that remaining values produced are not flags.
506 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
507 if (N->getValueType(i) == MVT::Flag)
508 return true; // Never CSE anything that produces a flag.
513 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
515 void SelectionDAG::RemoveDeadNodes() {
516 // Create a dummy node (which is not added to allnodes), that adds a reference
517 // to the root node, preventing it from being deleted.
518 HandleSDNode Dummy(getRoot());
520 SmallVector<SDNode*, 128> DeadNodes;
522 // Add all obviously-dead nodes to the DeadNodes worklist.
523 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
525 DeadNodes.push_back(I);
527 RemoveDeadNodes(DeadNodes);
529 // If the root changed (e.g. it was a dead load, update the root).
530 setRoot(Dummy.getValue());
533 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
534 /// given list, and any nodes that become unreachable as a result.
535 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
536 DAGUpdateListener *UpdateListener) {
538 // Process the worklist, deleting the nodes and adding their uses to the
540 while (!DeadNodes.empty()) {
541 SDNode *N = DeadNodes.back();
542 DeadNodes.pop_back();
545 UpdateListener->NodeDeleted(N, 0);
547 // Take the node out of the appropriate CSE map.
548 RemoveNodeFromCSEMaps(N);
550 // Next, brutally remove the operand list. This is safe to do, as there are
551 // no cycles in the graph.
552 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
553 SDNode *Operand = I->getVal();
554 Operand->removeUser(std::distance(N->op_begin(), I), N);
556 // Now that we removed this operand, see if there are no uses of it left.
557 if (Operand->use_empty())
558 DeadNodes.push_back(Operand);
565 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
566 SmallVector<SDNode*, 16> DeadNodes(1, N);
567 RemoveDeadNodes(DeadNodes, UpdateListener);
570 void SelectionDAG::DeleteNode(SDNode *N) {
571 assert(N->use_empty() && "Cannot delete a node that is not dead!");
573 // First take this out of the appropriate CSE map.
574 RemoveNodeFromCSEMaps(N);
576 // Finally, remove uses due to operands of this node, remove from the
577 // AllNodes list, and delete the node.
578 DeleteNodeNotInCSEMaps(N);
581 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
582 assert(N != AllNodes.begin());
584 // Drop all of the operands and decrement used node's use counts.
585 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
586 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
591 void SelectionDAG::DeallocateNode(SDNode *N) {
592 if (N->OperandsNeedDelete)
593 delete[] N->OperandList;
595 // Set the opcode to DELETED_NODE to help catch bugs when node
596 // memory is reallocated.
597 N->NodeType = ISD::DELETED_NODE;
599 NodeAllocator.Deallocate(AllNodes.remove(N));
602 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
603 /// correspond to it. This is useful when we're about to delete or repurpose
604 /// the node. We don't want future request for structurally identical nodes
605 /// to return N anymore.
606 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
608 switch (N->getOpcode()) {
609 case ISD::EntryToken:
610 assert(0 && "EntryToken should not be in CSEMaps!");
612 case ISD::HANDLENODE: return false; // noop.
614 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
615 "Cond code doesn't exist!");
616 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
617 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
619 case ISD::ExternalSymbol:
620 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
622 case ISD::TargetExternalSymbol:
624 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
626 case ISD::VALUETYPE: {
627 MVT VT = cast<VTSDNode>(N)->getVT();
628 if (VT.isExtended()) {
629 Erased = ExtendedValueTypeNodes.erase(VT);
631 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
632 ValueTypeNodes[VT.getSimpleVT()] = 0;
637 // Remove it from the CSE Map.
638 Erased = CSEMap.RemoveNode(N);
642 // Verify that the node was actually in one of the CSE maps, unless it has a
643 // flag result (which cannot be CSE'd) or is one of the special cases that are
644 // not subject to CSE.
645 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
646 !N->isMachineOpcode() && !doNotCSE(N)) {
649 assert(0 && "Node is not in map!");
655 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
656 /// has been taken out and modified in some way. If the specified node already
657 /// exists in the CSE maps, do not modify the maps, but return the existing node
658 /// instead. If it doesn't exist, add it and return null.
660 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
661 assert(N->getNumOperands() && "This is a leaf node!");
666 SDNode *New = CSEMap.GetOrInsertNode(N);
667 if (New != N) return New; // Node already existed.
671 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
672 /// were replaced with those specified. If this node is never memoized,
673 /// return null, otherwise return a pointer to the slot it would take. If a
674 /// node already exists with these operands, the slot will be non-null.
675 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
680 SDValue Ops[] = { Op };
682 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
683 AddNodeIDCustom(ID, N);
684 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
687 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
688 /// were replaced with those specified. If this node is never memoized,
689 /// return null, otherwise return a pointer to the slot it would take. If a
690 /// node already exists with these operands, the slot will be non-null.
691 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
692 SDValue Op1, SDValue Op2,
697 SDValue Ops[] = { Op1, Op2 };
699 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
700 AddNodeIDCustom(ID, N);
701 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
705 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
706 /// were replaced with those specified. If this node is never memoized,
707 /// return null, otherwise return a pointer to the slot it would take. If a
708 /// node already exists with these operands, the slot will be non-null.
709 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
710 const SDValue *Ops,unsigned NumOps,
716 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
717 AddNodeIDCustom(ID, N);
718 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
721 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
722 void SelectionDAG::VerifyNode(SDNode *N) {
723 switch (N->getOpcode()) {
726 case ISD::BUILD_PAIR: {
727 MVT VT = N->getValueType(0);
728 assert(N->getNumValues() == 1 && "Too many results!");
729 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
730 "Wrong return type!");
731 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
732 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
733 "Mismatched operand types!");
734 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
735 "Wrong operand type!");
736 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
737 "Wrong return type size");
740 case ISD::BUILD_VECTOR: {
741 assert(N->getNumValues() == 1 && "Too many results!");
742 assert(N->getValueType(0).isVector() && "Wrong return type!");
743 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
744 "Wrong number of operands!");
745 // FIXME: Change vector_shuffle to a variadic node with mask elements being
746 // operands of the node. Currently the mask is a BUILD_VECTOR passed as an
747 // operand, and it is not always possible to legalize it. Turning off the
748 // following checks at least makes it possible to legalize most of the time.
749 // MVT EltVT = N->getValueType(0).getVectorElementType();
750 // for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
751 // assert(I->getSDValue().getValueType() == EltVT &&
752 // "Wrong operand type!");
758 /// getMVTAlignment - Compute the default alignment value for the
761 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
762 const Type *Ty = VT == MVT::iPTR ?
763 PointerType::get(Type::Int8Ty, 0) :
766 return TLI.getTargetData()->getABITypeAlignment(Ty);
769 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
770 : TLI(tli), FLI(fli),
771 EntryNode(ISD::EntryToken, getVTList(MVT::Other)),
772 Root(getEntryNode()) {
773 AllNodes.push_back(&EntryNode);
776 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
783 SelectionDAG::~SelectionDAG() {
787 void SelectionDAG::allnodes_clear() {
788 assert(&*AllNodes.begin() == &EntryNode);
789 AllNodes.remove(AllNodes.begin());
790 while (!AllNodes.empty())
791 DeallocateNode(AllNodes.begin());
794 void SelectionDAG::clear() {
796 OperandAllocator.Reset();
799 ExtendedValueTypeNodes.clear();
800 ExternalSymbols.clear();
801 TargetExternalSymbols.clear();
802 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
803 static_cast<CondCodeSDNode*>(0));
804 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
805 static_cast<SDNode*>(0));
808 AllNodes.push_back(&EntryNode);
809 Root = getEntryNode();
812 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
813 if (Op.getValueType() == VT) return Op;
814 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
816 return getNode(ISD::AND, Op.getValueType(), Op,
817 getConstant(Imm, Op.getValueType()));
820 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
822 SDValue SelectionDAG::getNOT(SDValue Val, MVT VT) {
825 MVT EltVT = VT.getVectorElementType();
826 SDValue NegOneElt = getConstant(EltVT.getIntegerVTBitMask(), EltVT);
827 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOneElt);
828 NegOne = getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0], NegOnes.size());
830 NegOne = getConstant(VT.getIntegerVTBitMask(), VT);
832 return getNode(ISD::XOR, VT, Val, NegOne);
835 SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
836 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
837 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
840 SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
841 return getConstant(*ConstantInt::get(Val), VT, isT);
844 SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) {
845 assert(VT.isInteger() && "Cannot create FP integer constant!");
847 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
848 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
849 "APInt size does not match type size!");
851 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
853 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
857 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
859 return SDValue(N, 0);
861 N = NodeAllocator.Allocate<ConstantSDNode>();
862 new (N) ConstantSDNode(isT, &Val, EltVT);
863 CSEMap.InsertNode(N, IP);
864 AllNodes.push_back(N);
867 SDValue Result(N, 0);
869 SmallVector<SDValue, 8> Ops;
870 Ops.assign(VT.getVectorNumElements(), Result);
871 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
876 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
877 return getConstant(Val, TLI.getPointerTy(), isTarget);
881 SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
882 return getConstantFP(*ConstantFP::get(V), VT, isTarget);
885 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, MVT VT, bool isTarget){
886 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
889 VT.isVector() ? VT.getVectorElementType() : VT;
891 // Do the map lookup using the actual bit pattern for the floating point
892 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
893 // we don't have issues with SNANs.
894 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
896 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
900 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
902 return SDValue(N, 0);
904 N = NodeAllocator.Allocate<ConstantFPSDNode>();
905 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
906 CSEMap.InsertNode(N, IP);
907 AllNodes.push_back(N);
910 SDValue Result(N, 0);
912 SmallVector<SDValue, 8> Ops;
913 Ops.assign(VT.getVectorNumElements(), Result);
914 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
919 SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
921 VT.isVector() ? VT.getVectorElementType() : VT;
923 return getConstantFP(APFloat((float)Val), VT, isTarget);
925 return getConstantFP(APFloat(Val), VT, isTarget);
928 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
929 MVT VT, int64_t Offset,
933 // Truncate (with sign-extension) the offset value to the pointer size.
934 unsigned BitWidth = TLI.getPointerTy().getSizeInBits();
936 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
938 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
940 // If GV is an alias then use the aliasee for determining thread-localness.
941 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
942 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
945 if (GVar && GVar->isThreadLocal())
946 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
948 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
951 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
953 ID.AddInteger(Offset);
955 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
956 return SDValue(E, 0);
957 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
958 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
959 CSEMap.InsertNode(N, IP);
960 AllNodes.push_back(N);
961 return SDValue(N, 0);
964 SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
965 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
967 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
970 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
971 return SDValue(E, 0);
972 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
973 new (N) FrameIndexSDNode(FI, VT, isTarget);
974 CSEMap.InsertNode(N, IP);
975 AllNodes.push_back(N);
976 return SDValue(N, 0);
979 SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
980 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
982 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
985 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
986 return SDValue(E, 0);
987 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
988 new (N) JumpTableSDNode(JTI, VT, isTarget);
989 CSEMap.InsertNode(N, IP);
990 AllNodes.push_back(N);
991 return SDValue(N, 0);
994 SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
995 unsigned Alignment, int Offset,
999 TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
1000 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1001 FoldingSetNodeID ID;
1002 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1003 ID.AddInteger(Alignment);
1004 ID.AddInteger(Offset);
1007 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1008 return SDValue(E, 0);
1009 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1010 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1011 CSEMap.InsertNode(N, IP);
1012 AllNodes.push_back(N);
1013 return SDValue(N, 0);
1017 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
1018 unsigned Alignment, int Offset,
1022 TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
1023 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1024 FoldingSetNodeID ID;
1025 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1026 ID.AddInteger(Alignment);
1027 ID.AddInteger(Offset);
1028 C->AddSelectionDAGCSEId(ID);
1030 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1031 return SDValue(E, 0);
1032 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1033 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1034 CSEMap.InsertNode(N, IP);
1035 AllNodes.push_back(N);
1036 return SDValue(N, 0);
1040 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1041 FoldingSetNodeID ID;
1042 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1045 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1046 return SDValue(E, 0);
1047 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1048 new (N) BasicBlockSDNode(MBB);
1049 CSEMap.InsertNode(N, IP);
1050 AllNodes.push_back(N);
1051 return SDValue(N, 0);
1054 SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
1055 FoldingSetNodeID ID;
1056 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
1057 ID.AddInteger(Flags.getRawBits());
1059 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1060 return SDValue(E, 0);
1061 SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
1062 new (N) ARG_FLAGSSDNode(Flags);
1063 CSEMap.InsertNode(N, IP);
1064 AllNodes.push_back(N);
1065 return SDValue(N, 0);
1068 SDValue SelectionDAG::getValueType(MVT VT) {
1069 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1070 ValueTypeNodes.resize(VT.getSimpleVT()+1);
1072 SDNode *&N = VT.isExtended() ?
1073 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1075 if (N) return SDValue(N, 0);
1076 N = NodeAllocator.Allocate<VTSDNode>();
1077 new (N) VTSDNode(VT);
1078 AllNodes.push_back(N);
1079 return SDValue(N, 0);
1082 SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1083 SDNode *&N = ExternalSymbols[Sym];
1084 if (N) return SDValue(N, 0);
1085 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1086 new (N) ExternalSymbolSDNode(false, Sym, VT);
1087 AllNodes.push_back(N);
1088 return SDValue(N, 0);
1091 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1092 SDNode *&N = TargetExternalSymbols[Sym];
1093 if (N) return SDValue(N, 0);
1094 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1095 new (N) ExternalSymbolSDNode(true, Sym, VT);
1096 AllNodes.push_back(N);
1097 return SDValue(N, 0);
1100 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1101 if ((unsigned)Cond >= CondCodeNodes.size())
1102 CondCodeNodes.resize(Cond+1);
1104 if (CondCodeNodes[Cond] == 0) {
1105 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1106 new (N) CondCodeSDNode(Cond);
1107 CondCodeNodes[Cond] = N;
1108 AllNodes.push_back(N);
1110 return SDValue(CondCodeNodes[Cond], 0);
1113 SDValue SelectionDAG::getConvertRndSat(MVT VT, SDValue Val, SDValue DTy,
1114 SDValue STy, SDValue Rnd, SDValue Sat,
1115 ISD::CvtCode Code) {
1116 // If the src and dest types are the same, no conversion is necessary.
1120 FoldingSetNodeID ID;
1122 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1123 return SDValue(E, 0);
1124 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
1125 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1126 new (N) CvtRndSatSDNode(VT, Ops, 5, Code);
1127 CSEMap.InsertNode(N, IP);
1128 AllNodes.push_back(N);
1129 return SDValue(N, 0);
1132 SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1133 FoldingSetNodeID ID;
1134 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1135 ID.AddInteger(RegNo);
1137 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1138 return SDValue(E, 0);
1139 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1140 new (N) RegisterSDNode(RegNo, VT);
1141 CSEMap.InsertNode(N, IP);
1142 AllNodes.push_back(N);
1143 return SDValue(N, 0);
1146 SDValue SelectionDAG::getDbgStopPoint(SDValue Root,
1147 unsigned Line, unsigned Col,
1149 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1150 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1151 AllNodes.push_back(N);
1152 return SDValue(N, 0);
1155 SDValue SelectionDAG::getLabel(unsigned Opcode,
1158 FoldingSetNodeID ID;
1159 SDValue Ops[] = { Root };
1160 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1161 ID.AddInteger(LabelID);
1163 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1164 return SDValue(E, 0);
1165 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1166 new (N) LabelSDNode(Opcode, Root, LabelID);
1167 CSEMap.InsertNode(N, IP);
1168 AllNodes.push_back(N);
1169 return SDValue(N, 0);
1172 SDValue SelectionDAG::getSrcValue(const Value *V) {
1173 assert((!V || isa<PointerType>(V->getType())) &&
1174 "SrcValue is not a pointer?");
1176 FoldingSetNodeID ID;
1177 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1181 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1182 return SDValue(E, 0);
1184 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1185 new (N) SrcValueSDNode(V);
1186 CSEMap.InsertNode(N, IP);
1187 AllNodes.push_back(N);
1188 return SDValue(N, 0);
1191 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1193 const Value *v = MO.getValue();
1194 assert((!v || isa<PointerType>(v->getType())) &&
1195 "SrcValue is not a pointer?");
1198 FoldingSetNodeID ID;
1199 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1203 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1204 return SDValue(E, 0);
1206 SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
1207 new (N) MemOperandSDNode(MO);
1208 CSEMap.InsertNode(N, IP);
1209 AllNodes.push_back(N);
1210 return SDValue(N, 0);
1213 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1214 /// specified value type.
1215 SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1216 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1217 unsigned ByteSize = VT.getStoreSizeInBits()/8;
1218 const Type *Ty = VT.getTypeForMVT();
1219 unsigned StackAlign =
1220 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1222 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1223 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1226 /// CreateStackTemporary - Create a stack temporary suitable for holding
1227 /// either of the specified value types.
1228 SDValue SelectionDAG::CreateStackTemporary(MVT VT1, MVT VT2) {
1229 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1230 VT2.getStoreSizeInBits())/8;
1231 const Type *Ty1 = VT1.getTypeForMVT();
1232 const Type *Ty2 = VT2.getTypeForMVT();
1233 const TargetData *TD = TLI.getTargetData();
1234 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1235 TD->getPrefTypeAlignment(Ty2));
1237 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1238 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align);
1239 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1242 SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
1243 SDValue N2, ISD::CondCode Cond) {
1244 // These setcc operations always fold.
1248 case ISD::SETFALSE2: return getConstant(0, VT);
1250 case ISD::SETTRUE2: return getConstant(1, VT);
1262 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1266 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1267 const APInt &C2 = N2C->getAPIntValue();
1268 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1269 const APInt &C1 = N1C->getAPIntValue();
1272 default: assert(0 && "Unknown integer setcc!");
1273 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1274 case ISD::SETNE: return getConstant(C1 != C2, VT);
1275 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1276 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1277 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1278 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1279 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1280 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1281 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1282 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1286 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1287 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1288 // No compile time operations on this type yet.
1289 if (N1C->getValueType(0) == MVT::ppcf128)
1292 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1295 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1296 return getNode(ISD::UNDEF, VT);
1298 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1299 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1300 return getNode(ISD::UNDEF, VT);
1302 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1303 R==APFloat::cmpLessThan, VT);
1304 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1305 return getNode(ISD::UNDEF, VT);
1307 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1308 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1309 return getNode(ISD::UNDEF, VT);
1311 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1312 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1313 return getNode(ISD::UNDEF, VT);
1315 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1316 R==APFloat::cmpEqual, VT);
1317 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1318 return getNode(ISD::UNDEF, VT);
1320 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1321 R==APFloat::cmpEqual, VT);
1322 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1323 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1324 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1325 R==APFloat::cmpEqual, VT);
1326 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1327 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1328 R==APFloat::cmpLessThan, VT);
1329 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1330 R==APFloat::cmpUnordered, VT);
1331 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1332 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1335 // Ensure that the constant occurs on the RHS.
1336 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1340 // Could not fold it.
1344 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1345 /// use this predicate to simplify operations downstream.
1346 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1347 unsigned BitWidth = Op.getValueSizeInBits();
1348 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1351 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1352 /// this predicate to simplify operations downstream. Mask is known to be zero
1353 /// for bits that V cannot have.
1354 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1355 unsigned Depth) const {
1356 APInt KnownZero, KnownOne;
1357 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1358 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1359 return (KnownZero & Mask) == Mask;
1362 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1363 /// known to be either zero or one and return them in the KnownZero/KnownOne
1364 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1366 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1367 APInt &KnownZero, APInt &KnownOne,
1368 unsigned Depth) const {
1369 unsigned BitWidth = Mask.getBitWidth();
1370 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1371 "Mask size mismatches value type size!");
1373 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1374 if (Depth == 6 || Mask == 0)
1375 return; // Limit search depth.
1377 APInt KnownZero2, KnownOne2;
1379 switch (Op.getOpcode()) {
1381 // We know all of the bits for a constant!
1382 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1383 KnownZero = ~KnownOne & Mask;
1386 // If either the LHS or the RHS are Zero, the result is zero.
1387 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1388 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1389 KnownZero2, KnownOne2, Depth+1);
1390 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1391 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1393 // Output known-1 bits are only known if set in both the LHS & RHS.
1394 KnownOne &= KnownOne2;
1395 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1396 KnownZero |= KnownZero2;
1399 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1400 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1401 KnownZero2, KnownOne2, Depth+1);
1402 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1403 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1405 // Output known-0 bits are only known if clear in both the LHS & RHS.
1406 KnownZero &= KnownZero2;
1407 // Output known-1 are known to be set if set in either the LHS | RHS.
1408 KnownOne |= KnownOne2;
1411 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1412 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1413 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1414 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1416 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1417 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1418 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1419 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1420 KnownZero = KnownZeroOut;
1424 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1425 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1426 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1427 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1428 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1430 // If low bits are zero in either operand, output low known-0 bits.
1431 // Also compute a conserative estimate for high known-0 bits.
1432 // More trickiness is possible, but this is sufficient for the
1433 // interesting case of alignment computation.
1435 unsigned TrailZ = KnownZero.countTrailingOnes() +
1436 KnownZero2.countTrailingOnes();
1437 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1438 KnownZero2.countLeadingOnes(),
1439 BitWidth) - BitWidth;
1441 TrailZ = std::min(TrailZ, BitWidth);
1442 LeadZ = std::min(LeadZ, BitWidth);
1443 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1444 APInt::getHighBitsSet(BitWidth, LeadZ);
1449 // For the purposes of computing leading zeros we can conservatively
1450 // treat a udiv as a logical right shift by the power of 2 known to
1451 // be less than the denominator.
1452 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1453 ComputeMaskedBits(Op.getOperand(0),
1454 AllOnes, KnownZero2, KnownOne2, Depth+1);
1455 unsigned LeadZ = KnownZero2.countLeadingOnes();
1459 ComputeMaskedBits(Op.getOperand(1),
1460 AllOnes, KnownZero2, KnownOne2, Depth+1);
1461 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1462 if (RHSUnknownLeadingOnes != BitWidth)
1463 LeadZ = std::min(BitWidth,
1464 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1466 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1470 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1471 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1472 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1473 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1475 // Only known if known in both the LHS and RHS.
1476 KnownOne &= KnownOne2;
1477 KnownZero &= KnownZero2;
1479 case ISD::SELECT_CC:
1480 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1481 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1482 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1483 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1485 // Only known if known in both the LHS and RHS.
1486 KnownOne &= KnownOne2;
1487 KnownZero &= KnownZero2;
1495 if (Op.getResNo() != 1)
1497 // The boolean result conforms to getBooleanContents. Fall through.
1499 // If we know the result of a setcc has the top bits zero, use this info.
1500 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1502 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1505 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1506 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1507 unsigned ShAmt = SA->getZExtValue();
1509 // If the shift count is an invalid immediate, don't do anything.
1510 if (ShAmt >= BitWidth)
1513 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1514 KnownZero, KnownOne, Depth+1);
1515 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1516 KnownZero <<= ShAmt;
1518 // low bits known zero.
1519 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1523 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1524 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1525 unsigned ShAmt = SA->getZExtValue();
1527 // If the shift count is an invalid immediate, don't do anything.
1528 if (ShAmt >= BitWidth)
1531 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1532 KnownZero, KnownOne, Depth+1);
1533 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1534 KnownZero = KnownZero.lshr(ShAmt);
1535 KnownOne = KnownOne.lshr(ShAmt);
1537 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1538 KnownZero |= HighBits; // High bits known zero.
1542 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1543 unsigned ShAmt = SA->getZExtValue();
1545 // If the shift count is an invalid immediate, don't do anything.
1546 if (ShAmt >= BitWidth)
1549 APInt InDemandedMask = (Mask << ShAmt);
1550 // If any of the demanded bits are produced by the sign extension, we also
1551 // demand the input sign bit.
1552 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1553 if (HighBits.getBoolValue())
1554 InDemandedMask |= APInt::getSignBit(BitWidth);
1556 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1558 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1559 KnownZero = KnownZero.lshr(ShAmt);
1560 KnownOne = KnownOne.lshr(ShAmt);
1562 // Handle the sign bits.
1563 APInt SignBit = APInt::getSignBit(BitWidth);
1564 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1566 if (KnownZero.intersects(SignBit)) {
1567 KnownZero |= HighBits; // New bits are known zero.
1568 } else if (KnownOne.intersects(SignBit)) {
1569 KnownOne |= HighBits; // New bits are known one.
1573 case ISD::SIGN_EXTEND_INREG: {
1574 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1575 unsigned EBits = EVT.getSizeInBits();
1577 // Sign extension. Compute the demanded bits in the result that are not
1578 // present in the input.
1579 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1581 APInt InSignBit = APInt::getSignBit(EBits);
1582 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1584 // If the sign extended bits are demanded, we know that the sign
1586 InSignBit.zext(BitWidth);
1587 if (NewBits.getBoolValue())
1588 InputDemandedBits |= InSignBit;
1590 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1591 KnownZero, KnownOne, Depth+1);
1592 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1594 // If the sign bit of the input is known set or clear, then we know the
1595 // top bits of the result.
1596 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1597 KnownZero |= NewBits;
1598 KnownOne &= ~NewBits;
1599 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1600 KnownOne |= NewBits;
1601 KnownZero &= ~NewBits;
1602 } else { // Input sign bit unknown
1603 KnownZero &= ~NewBits;
1604 KnownOne &= ~NewBits;
1611 unsigned LowBits = Log2_32(BitWidth)+1;
1612 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1617 if (ISD::isZEXTLoad(Op.getNode())) {
1618 LoadSDNode *LD = cast<LoadSDNode>(Op);
1619 MVT VT = LD->getMemoryVT();
1620 unsigned MemBits = VT.getSizeInBits();
1621 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1625 case ISD::ZERO_EXTEND: {
1626 MVT InVT = Op.getOperand(0).getValueType();
1627 unsigned InBits = InVT.getSizeInBits();
1628 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1629 APInt InMask = Mask;
1630 InMask.trunc(InBits);
1631 KnownZero.trunc(InBits);
1632 KnownOne.trunc(InBits);
1633 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1634 KnownZero.zext(BitWidth);
1635 KnownOne.zext(BitWidth);
1636 KnownZero |= NewBits;
1639 case ISD::SIGN_EXTEND: {
1640 MVT InVT = Op.getOperand(0).getValueType();
1641 unsigned InBits = InVT.getSizeInBits();
1642 APInt InSignBit = APInt::getSignBit(InBits);
1643 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1644 APInt InMask = Mask;
1645 InMask.trunc(InBits);
1647 // If any of the sign extended bits are demanded, we know that the sign
1648 // bit is demanded. Temporarily set this bit in the mask for our callee.
1649 if (NewBits.getBoolValue())
1650 InMask |= InSignBit;
1652 KnownZero.trunc(InBits);
1653 KnownOne.trunc(InBits);
1654 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1656 // Note if the sign bit is known to be zero or one.
1657 bool SignBitKnownZero = KnownZero.isNegative();
1658 bool SignBitKnownOne = KnownOne.isNegative();
1659 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1660 "Sign bit can't be known to be both zero and one!");
1662 // If the sign bit wasn't actually demanded by our caller, we don't
1663 // want it set in the KnownZero and KnownOne result values. Reset the
1664 // mask and reapply it to the result values.
1666 InMask.trunc(InBits);
1667 KnownZero &= InMask;
1670 KnownZero.zext(BitWidth);
1671 KnownOne.zext(BitWidth);
1673 // If the sign bit is known zero or one, the top bits match.
1674 if (SignBitKnownZero)
1675 KnownZero |= NewBits;
1676 else if (SignBitKnownOne)
1677 KnownOne |= NewBits;
1680 case ISD::ANY_EXTEND: {
1681 MVT InVT = Op.getOperand(0).getValueType();
1682 unsigned InBits = InVT.getSizeInBits();
1683 APInt InMask = Mask;
1684 InMask.trunc(InBits);
1685 KnownZero.trunc(InBits);
1686 KnownOne.trunc(InBits);
1687 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1688 KnownZero.zext(BitWidth);
1689 KnownOne.zext(BitWidth);
1692 case ISD::TRUNCATE: {
1693 MVT InVT = Op.getOperand(0).getValueType();
1694 unsigned InBits = InVT.getSizeInBits();
1695 APInt InMask = Mask;
1696 InMask.zext(InBits);
1697 KnownZero.zext(InBits);
1698 KnownOne.zext(InBits);
1699 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1700 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1701 KnownZero.trunc(BitWidth);
1702 KnownOne.trunc(BitWidth);
1705 case ISD::AssertZext: {
1706 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1707 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1708 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1710 KnownZero |= (~InMask) & Mask;
1714 // All bits are zero except the low bit.
1715 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1719 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1720 // We know that the top bits of C-X are clear if X contains less bits
1721 // than C (i.e. no wrap-around can happen). For example, 20-X is
1722 // positive if we can prove that X is >= 0 and < 16.
1723 if (CLHS->getAPIntValue().isNonNegative()) {
1724 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1725 // NLZ can't be BitWidth with no sign bit
1726 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1727 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1730 // If all of the MaskV bits are known to be zero, then we know the
1731 // output top bits are zero, because we now know that the output is
1733 if ((KnownZero2 & MaskV) == MaskV) {
1734 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1735 // Top bits known zero.
1736 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1743 // Output known-0 bits are known if clear or set in both the low clear bits
1744 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1745 // low 3 bits clear.
1746 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1747 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1748 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1749 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1751 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1752 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1753 KnownZeroOut = std::min(KnownZeroOut,
1754 KnownZero2.countTrailingOnes());
1756 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1760 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1761 const APInt &RA = Rem->getAPIntValue();
1762 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1763 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1764 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1765 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1767 // If the sign bit of the first operand is zero, the sign bit of
1768 // the result is zero. If the first operand has no one bits below
1769 // the second operand's single 1 bit, its sign will be zero.
1770 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1771 KnownZero2 |= ~LowBits;
1773 KnownZero |= KnownZero2 & Mask;
1775 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1780 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1781 const APInt &RA = Rem->getAPIntValue();
1782 if (RA.isPowerOf2()) {
1783 APInt LowBits = (RA - 1);
1784 APInt Mask2 = LowBits & Mask;
1785 KnownZero |= ~LowBits & Mask;
1786 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1787 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1792 // Since the result is less than or equal to either operand, any leading
1793 // zero bits in either operand must also exist in the result.
1794 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1795 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1797 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1800 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1801 KnownZero2.countLeadingOnes());
1803 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1807 // Allow the target to implement this method for its nodes.
1808 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1809 case ISD::INTRINSIC_WO_CHAIN:
1810 case ISD::INTRINSIC_W_CHAIN:
1811 case ISD::INTRINSIC_VOID:
1812 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1818 /// ComputeNumSignBits - Return the number of times the sign bit of the
1819 /// register is replicated into the other bits. We know that at least 1 bit
1820 /// is always equal to the sign bit (itself), but other cases can give us
1821 /// information. For example, immediately after an "SRA X, 2", we know that
1822 /// the top 3 bits are all equal to each other, so we return 3.
1823 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1824 MVT VT = Op.getValueType();
1825 assert(VT.isInteger() && "Invalid VT!");
1826 unsigned VTBits = VT.getSizeInBits();
1828 unsigned FirstAnswer = 1;
1831 return 1; // Limit search depth.
1833 switch (Op.getOpcode()) {
1835 case ISD::AssertSext:
1836 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1837 return VTBits-Tmp+1;
1838 case ISD::AssertZext:
1839 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1842 case ISD::Constant: {
1843 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1844 // If negative, return # leading ones.
1845 if (Val.isNegative())
1846 return Val.countLeadingOnes();
1848 // Return # leading zeros.
1849 return Val.countLeadingZeros();
1852 case ISD::SIGN_EXTEND:
1853 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1854 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1856 case ISD::SIGN_EXTEND_INREG:
1857 // Max of the input and what this extends.
1858 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1861 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1862 return std::max(Tmp, Tmp2);
1865 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1866 // SRA X, C -> adds C sign bits.
1867 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1868 Tmp += C->getZExtValue();
1869 if (Tmp > VTBits) Tmp = VTBits;
1873 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1874 // shl destroys sign bits.
1875 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1876 if (C->getZExtValue() >= VTBits || // Bad shift.
1877 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
1878 return Tmp - C->getZExtValue();
1883 case ISD::XOR: // NOT is handled here.
1884 // Logical binary ops preserve the number of sign bits at the worst.
1885 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1887 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1888 FirstAnswer = std::min(Tmp, Tmp2);
1889 // We computed what we know about the sign bits as our first
1890 // answer. Now proceed to the generic code that uses
1891 // ComputeMaskedBits, and pick whichever answer is better.
1896 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1897 if (Tmp == 1) return 1; // Early out.
1898 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1899 return std::min(Tmp, Tmp2);
1907 if (Op.getResNo() != 1)
1909 // The boolean result conforms to getBooleanContents. Fall through.
1911 // If setcc returns 0/-1, all bits are sign bits.
1912 if (TLI.getBooleanContents() ==
1913 TargetLowering::ZeroOrNegativeOneBooleanContent)
1918 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1919 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
1921 // Handle rotate right by N like a rotate left by 32-N.
1922 if (Op.getOpcode() == ISD::ROTR)
1923 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1925 // If we aren't rotating out all of the known-in sign bits, return the
1926 // number that are left. This handles rotl(sext(x), 1) for example.
1927 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1928 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1932 // Add can have at most one carry bit. Thus we know that the output
1933 // is, at worst, one more bit than the inputs.
1934 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1935 if (Tmp == 1) return 1; // Early out.
1937 // Special case decrementing a value (ADD X, -1):
1938 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1939 if (CRHS->isAllOnesValue()) {
1940 APInt KnownZero, KnownOne;
1941 APInt Mask = APInt::getAllOnesValue(VTBits);
1942 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1944 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1946 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1949 // If we are subtracting one from a positive number, there is no carry
1950 // out of the result.
1951 if (KnownZero.isNegative())
1955 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1956 if (Tmp2 == 1) return 1;
1957 return std::min(Tmp, Tmp2)-1;
1961 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1962 if (Tmp2 == 1) return 1;
1965 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1966 if (CLHS->isNullValue()) {
1967 APInt KnownZero, KnownOne;
1968 APInt Mask = APInt::getAllOnesValue(VTBits);
1969 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1970 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1972 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1975 // If the input is known to be positive (the sign bit is known clear),
1976 // the output of the NEG has the same number of sign bits as the input.
1977 if (KnownZero.isNegative())
1980 // Otherwise, we treat this like a SUB.
1983 // Sub can have at most one carry bit. Thus we know that the output
1984 // is, at worst, one more bit than the inputs.
1985 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1986 if (Tmp == 1) return 1; // Early out.
1987 return std::min(Tmp, Tmp2)-1;
1990 // FIXME: it's tricky to do anything useful for this, but it is an important
1991 // case for targets like X86.
1995 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1996 if (Op.getOpcode() == ISD::LOAD) {
1997 LoadSDNode *LD = cast<LoadSDNode>(Op);
1998 unsigned ExtType = LD->getExtensionType();
2001 case ISD::SEXTLOAD: // '17' bits known
2002 Tmp = LD->getMemoryVT().getSizeInBits();
2003 return VTBits-Tmp+1;
2004 case ISD::ZEXTLOAD: // '16' bits known
2005 Tmp = LD->getMemoryVT().getSizeInBits();
2010 // Allow the target to implement this method for its nodes.
2011 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2012 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2013 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2014 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2015 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2016 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2019 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2020 // use this information.
2021 APInt KnownZero, KnownOne;
2022 APInt Mask = APInt::getAllOnesValue(VTBits);
2023 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2025 if (KnownZero.isNegative()) { // sign bit is 0
2027 } else if (KnownOne.isNegative()) { // sign bit is 1;
2034 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2035 // the number of identical bits in the top of the input value.
2037 Mask <<= Mask.getBitWidth()-VTBits;
2038 // Return # leading zeros. We use 'min' here in case Val was zero before
2039 // shifting. We don't want to return '64' as for an i32 "0".
2040 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2044 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2045 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2046 if (!GA) return false;
2047 if (GA->getOffset() != 0) return false;
2048 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2049 if (!GV) return false;
2050 MachineModuleInfo *MMI = getMachineModuleInfo();
2051 return MMI && MMI->hasDebugInfo();
2055 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2056 /// element of the result of the vector shuffle.
2057 SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
2058 MVT VT = N->getValueType(0);
2059 SDValue PermMask = N->getOperand(2);
2060 SDValue Idx = PermMask.getOperand(i);
2061 if (Idx.getOpcode() == ISD::UNDEF)
2062 return getNode(ISD::UNDEF, VT.getVectorElementType());
2063 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
2064 unsigned NumElems = PermMask.getNumOperands();
2065 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2068 if (V.getOpcode() == ISD::BIT_CONVERT) {
2069 V = V.getOperand(0);
2070 MVT VVT = V.getValueType();
2071 if (!VVT.isVector() || VVT.getVectorNumElements() != NumElems)
2074 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2075 return (Index == 0) ? V.getOperand(0)
2076 : getNode(ISD::UNDEF, VT.getVectorElementType());
2077 if (V.getOpcode() == ISD::BUILD_VECTOR)
2078 return V.getOperand(Index);
2079 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
2080 return getShuffleScalarElt(V.getNode(), Index);
2085 /// getNode - Gets or creates the specified node.
2087 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
2088 FoldingSetNodeID ID;
2089 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2091 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2092 return SDValue(E, 0);
2093 SDNode *N = NodeAllocator.Allocate<SDNode>();
2094 new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
2095 CSEMap.InsertNode(N, IP);
2097 AllNodes.push_back(N);
2101 return SDValue(N, 0);
2104 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
2105 // Constant fold unary operations with an integer constant operand.
2106 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2107 const APInt &Val = C->getAPIntValue();
2108 unsigned BitWidth = VT.getSizeInBits();
2111 case ISD::SIGN_EXTEND:
2112 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2113 case ISD::ANY_EXTEND:
2114 case ISD::ZERO_EXTEND:
2116 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2117 case ISD::UINT_TO_FP:
2118 case ISD::SINT_TO_FP: {
2119 const uint64_t zero[] = {0, 0};
2120 // No compile time operations on this type.
2121 if (VT==MVT::ppcf128)
2123 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2124 (void)apf.convertFromAPInt(Val,
2125 Opcode==ISD::SINT_TO_FP,
2126 APFloat::rmNearestTiesToEven);
2127 return getConstantFP(apf, VT);
2129 case ISD::BIT_CONVERT:
2130 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2131 return getConstantFP(Val.bitsToFloat(), VT);
2132 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2133 return getConstantFP(Val.bitsToDouble(), VT);
2136 return getConstant(Val.byteSwap(), VT);
2138 return getConstant(Val.countPopulation(), VT);
2140 return getConstant(Val.countLeadingZeros(), VT);
2142 return getConstant(Val.countTrailingZeros(), VT);
2146 // Constant fold unary operations with a floating point constant operand.
2147 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2148 APFloat V = C->getValueAPF(); // make copy
2149 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2153 return getConstantFP(V, VT);
2156 return getConstantFP(V, VT);
2158 case ISD::FP_EXTEND: {
2160 // This can return overflow, underflow, or inexact; we don't care.
2161 // FIXME need to be more flexible about rounding mode.
2162 (void)V.convert(*MVTToAPFloatSemantics(VT),
2163 APFloat::rmNearestTiesToEven, &ignored);
2164 return getConstantFP(V, VT);
2166 case ISD::FP_TO_SINT:
2167 case ISD::FP_TO_UINT: {
2170 assert(integerPartWidth >= 64);
2171 // FIXME need to be more flexible about rounding mode.
2172 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2173 Opcode==ISD::FP_TO_SINT,
2174 APFloat::rmTowardZero, &ignored);
2175 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2177 return getConstant(x, VT);
2179 case ISD::BIT_CONVERT:
2180 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2181 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2182 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2183 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2189 unsigned OpOpcode = Operand.getNode()->getOpcode();
2191 case ISD::TokenFactor:
2192 case ISD::MERGE_VALUES:
2193 case ISD::CONCAT_VECTORS:
2194 return Operand; // Factor, merge or concat of one node? No need.
2195 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2196 case ISD::FP_EXTEND:
2197 assert(VT.isFloatingPoint() &&
2198 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2199 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2200 if (Operand.getOpcode() == ISD::UNDEF)
2201 return getNode(ISD::UNDEF, VT);
2203 case ISD::SIGN_EXTEND:
2204 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2205 "Invalid SIGN_EXTEND!");
2206 if (Operand.getValueType() == VT) return Operand; // noop extension
2207 assert(Operand.getValueType().bitsLT(VT)
2208 && "Invalid sext node, dst < src!");
2209 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2210 return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2212 case ISD::ZERO_EXTEND:
2213 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2214 "Invalid ZERO_EXTEND!");
2215 if (Operand.getValueType() == VT) return Operand; // noop extension
2216 assert(Operand.getValueType().bitsLT(VT)
2217 && "Invalid zext node, dst < src!");
2218 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2219 return getNode(ISD::ZERO_EXTEND, VT, Operand.getNode()->getOperand(0));
2221 case ISD::ANY_EXTEND:
2222 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2223 "Invalid ANY_EXTEND!");
2224 if (Operand.getValueType() == VT) return Operand; // noop extension
2225 assert(Operand.getValueType().bitsLT(VT)
2226 && "Invalid anyext node, dst < src!");
2227 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2228 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2229 return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2232 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2233 "Invalid TRUNCATE!");
2234 if (Operand.getValueType() == VT) return Operand; // noop truncate
2235 assert(Operand.getValueType().bitsGT(VT)
2236 && "Invalid truncate node, src < dst!");
2237 if (OpOpcode == ISD::TRUNCATE)
2238 return getNode(ISD::TRUNCATE, VT, Operand.getNode()->getOperand(0));
2239 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2240 OpOpcode == ISD::ANY_EXTEND) {
2241 // If the source is smaller than the dest, we still need an extend.
2242 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2243 return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2244 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2245 return getNode(ISD::TRUNCATE, VT, Operand.getNode()->getOperand(0));
2247 return Operand.getNode()->getOperand(0);
2250 case ISD::BIT_CONVERT:
2251 // Basic sanity checking.
2252 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2253 && "Cannot BIT_CONVERT between types of different sizes!");
2254 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2255 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2256 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2257 if (OpOpcode == ISD::UNDEF)
2258 return getNode(ISD::UNDEF, VT);
2260 case ISD::SCALAR_TO_VECTOR:
2261 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2262 VT.getVectorElementType() == Operand.getValueType() &&
2263 "Illegal SCALAR_TO_VECTOR node!");
2264 if (OpOpcode == ISD::UNDEF)
2265 return getNode(ISD::UNDEF, VT);
2266 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2267 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2268 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2269 Operand.getConstantOperandVal(1) == 0 &&
2270 Operand.getOperand(0).getValueType() == VT)
2271 return Operand.getOperand(0);
2274 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2275 return getNode(ISD::FSUB, VT, Operand.getNode()->getOperand(1),
2276 Operand.getNode()->getOperand(0));
2277 if (OpOpcode == ISD::FNEG) // --X -> X
2278 return Operand.getNode()->getOperand(0);
2281 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2282 return getNode(ISD::FABS, VT, Operand.getNode()->getOperand(0));
2287 SDVTList VTs = getVTList(VT);
2288 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2289 FoldingSetNodeID ID;
2290 SDValue Ops[1] = { Operand };
2291 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2293 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2294 return SDValue(E, 0);
2295 N = NodeAllocator.Allocate<UnarySDNode>();
2296 new (N) UnarySDNode(Opcode, VTs, Operand);
2297 CSEMap.InsertNode(N, IP);
2299 N = NodeAllocator.Allocate<UnarySDNode>();
2300 new (N) UnarySDNode(Opcode, VTs, Operand);
2303 AllNodes.push_back(N);
2307 return SDValue(N, 0);
2310 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2312 ConstantSDNode *Cst1,
2313 ConstantSDNode *Cst2) {
2314 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2317 case ISD::ADD: return getConstant(C1 + C2, VT);
2318 case ISD::SUB: return getConstant(C1 - C2, VT);
2319 case ISD::MUL: return getConstant(C1 * C2, VT);
2321 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2324 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2327 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2330 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2332 case ISD::AND: return getConstant(C1 & C2, VT);
2333 case ISD::OR: return getConstant(C1 | C2, VT);
2334 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2335 case ISD::SHL: return getConstant(C1 << C2, VT);
2336 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2337 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2338 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2339 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2346 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2347 SDValue N1, SDValue N2) {
2348 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2349 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2352 case ISD::TokenFactor:
2353 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2354 N2.getValueType() == MVT::Other && "Invalid token factor!");
2355 // Fold trivial token factors.
2356 if (N1.getOpcode() == ISD::EntryToken) return N2;
2357 if (N2.getOpcode() == ISD::EntryToken) return N1;
2358 if (N1 == N2) return N1;
2360 case ISD::CONCAT_VECTORS:
2361 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2362 // one big BUILD_VECTOR.
2363 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2364 N2.getOpcode() == ISD::BUILD_VECTOR) {
2365 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2366 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2367 return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2371 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2372 N1.getValueType() == VT && "Binary operator types must match!");
2373 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2374 // worth handling here.
2375 if (N2C && N2C->isNullValue())
2377 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2384 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2385 N1.getValueType() == VT && "Binary operator types must match!");
2386 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2387 // it's worth handling here.
2388 if (N2C && N2C->isNullValue())
2398 assert(VT.isInteger() && "This operator does not apply to FP types!");
2405 if (UnsafeFPMath && Opcode == ISD::FADD) {
2407 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2408 if (CFP->getValueAPF().isZero())
2411 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2412 if (CFP->getValueAPF().isZero())
2415 assert(N1.getValueType() == N2.getValueType() &&
2416 N1.getValueType() == VT && "Binary operator types must match!");
2418 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2419 assert(N1.getValueType() == VT &&
2420 N1.getValueType().isFloatingPoint() &&
2421 N2.getValueType().isFloatingPoint() &&
2422 "Invalid FCOPYSIGN!");
2429 assert(VT == N1.getValueType() &&
2430 "Shift operators return type must be the same as their first arg");
2431 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2432 "Shifts only work on integers");
2433 assert((N2.getValueType() == TLI.getShiftAmountTy() ||
2434 (N2.getValueType().isVector() && N2.getValueType().isInteger())) &&
2435 "Wrong type for shift amount");
2437 // Always fold shifts of i1 values so the code generator doesn't need to
2438 // handle them. Since we know the size of the shift has to be less than the
2439 // size of the value, the shift/rotate count is guaranteed to be zero.
2443 case ISD::FP_ROUND_INREG: {
2444 MVT EVT = cast<VTSDNode>(N2)->getVT();
2445 assert(VT == N1.getValueType() && "Not an inreg round!");
2446 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2447 "Cannot FP_ROUND_INREG integer types");
2448 assert(EVT.bitsLE(VT) && "Not rounding down!");
2449 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2453 assert(VT.isFloatingPoint() &&
2454 N1.getValueType().isFloatingPoint() &&
2455 VT.bitsLE(N1.getValueType()) &&
2456 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2457 if (N1.getValueType() == VT) return N1; // noop conversion.
2459 case ISD::AssertSext:
2460 case ISD::AssertZext: {
2461 MVT EVT = cast<VTSDNode>(N2)->getVT();
2462 assert(VT == N1.getValueType() && "Not an inreg extend!");
2463 assert(VT.isInteger() && EVT.isInteger() &&
2464 "Cannot *_EXTEND_INREG FP types");
2465 assert(EVT.bitsLE(VT) && "Not extending!");
2466 if (VT == EVT) return N1; // noop assertion.
2469 case ISD::SIGN_EXTEND_INREG: {
2470 MVT EVT = cast<VTSDNode>(N2)->getVT();
2471 assert(VT == N1.getValueType() && "Not an inreg extend!");
2472 assert(VT.isInteger() && EVT.isInteger() &&
2473 "Cannot *_EXTEND_INREG FP types");
2474 assert(EVT.bitsLE(VT) && "Not extending!");
2475 if (EVT == VT) return N1; // Not actually extending
2478 APInt Val = N1C->getAPIntValue();
2479 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2480 Val <<= Val.getBitWidth()-FromBits;
2481 Val = Val.ashr(Val.getBitWidth()-FromBits);
2482 return getConstant(Val, VT);
2486 case ISD::EXTRACT_VECTOR_ELT:
2487 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2488 if (N1.getOpcode() == ISD::UNDEF)
2489 return getNode(ISD::UNDEF, VT);
2491 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2492 // expanding copies of large vectors from registers.
2494 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2495 N1.getNumOperands() > 0) {
2497 N1.getOperand(0).getValueType().getVectorNumElements();
2498 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2499 N1.getOperand(N2C->getZExtValue() / Factor),
2500 getConstant(N2C->getZExtValue() % Factor,
2501 N2.getValueType()));
2504 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2505 // expanding large vector constants.
2506 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR)
2507 return N1.getOperand(N2C->getZExtValue());
2509 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2510 // operations are lowered to scalars.
2511 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2512 if (N1.getOperand(2) == N2)
2513 return N1.getOperand(1);
2515 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2518 case ISD::EXTRACT_ELEMENT:
2519 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2520 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2521 (N1.getValueType().isInteger() == VT.isInteger()) &&
2522 "Wrong types for EXTRACT_ELEMENT!");
2524 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2525 // 64-bit integers into 32-bit parts. Instead of building the extract of
2526 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2527 if (N1.getOpcode() == ISD::BUILD_PAIR)
2528 return N1.getOperand(N2C->getZExtValue());
2530 // EXTRACT_ELEMENT of a constant int is also very common.
2531 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2532 unsigned ElementSize = VT.getSizeInBits();
2533 unsigned Shift = ElementSize * N2C->getZExtValue();
2534 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2535 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2538 case ISD::EXTRACT_SUBVECTOR:
2539 if (N1.getValueType() == VT) // Trivial extraction.
2546 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2547 if (SV.getNode()) return SV;
2548 } else { // Cannonicalize constant to RHS if commutative
2549 if (isCommutativeBinOp(Opcode)) {
2550 std::swap(N1C, N2C);
2556 // Constant fold FP operations.
2557 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2558 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2560 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2561 // Cannonicalize constant to RHS if commutative
2562 std::swap(N1CFP, N2CFP);
2564 } else if (N2CFP && VT != MVT::ppcf128) {
2565 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2566 APFloat::opStatus s;
2569 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2570 if (s != APFloat::opInvalidOp)
2571 return getConstantFP(V1, VT);
2574 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2575 if (s!=APFloat::opInvalidOp)
2576 return getConstantFP(V1, VT);
2579 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2580 if (s!=APFloat::opInvalidOp)
2581 return getConstantFP(V1, VT);
2584 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2585 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2586 return getConstantFP(V1, VT);
2589 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2590 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2591 return getConstantFP(V1, VT);
2593 case ISD::FCOPYSIGN:
2595 return getConstantFP(V1, VT);
2601 // Canonicalize an UNDEF to the RHS, even over a constant.
2602 if (N1.getOpcode() == ISD::UNDEF) {
2603 if (isCommutativeBinOp(Opcode)) {
2607 case ISD::FP_ROUND_INREG:
2608 case ISD::SIGN_EXTEND_INREG:
2614 return N1; // fold op(undef, arg2) -> undef
2622 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2623 // For vectors, we can't easily build an all zero vector, just return
2630 // Fold a bunch of operators when the RHS is undef.
2631 if (N2.getOpcode() == ISD::UNDEF) {
2634 if (N1.getOpcode() == ISD::UNDEF)
2635 // Handle undef ^ undef -> 0 special case. This is a common
2637 return getConstant(0, VT);
2652 return N2; // fold op(arg1, undef) -> undef
2658 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2659 // For vectors, we can't easily build an all zero vector, just return
2664 return getConstant(VT.getIntegerVTBitMask(), VT);
2665 // For vectors, we can't easily build an all one vector, just return
2673 // Memoize this node if possible.
2675 SDVTList VTs = getVTList(VT);
2676 if (VT != MVT::Flag) {
2677 SDValue Ops[] = { N1, N2 };
2678 FoldingSetNodeID ID;
2679 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2681 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2682 return SDValue(E, 0);
2683 N = NodeAllocator.Allocate<BinarySDNode>();
2684 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2685 CSEMap.InsertNode(N, IP);
2687 N = NodeAllocator.Allocate<BinarySDNode>();
2688 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2691 AllNodes.push_back(N);
2695 return SDValue(N, 0);
2698 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2699 SDValue N1, SDValue N2, SDValue N3) {
2700 // Perform various simplifications.
2701 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2702 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2704 case ISD::CONCAT_VECTORS:
2705 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2706 // one big BUILD_VECTOR.
2707 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2708 N2.getOpcode() == ISD::BUILD_VECTOR &&
2709 N3.getOpcode() == ISD::BUILD_VECTOR) {
2710 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2711 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2712 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2713 return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2717 // Use FoldSetCC to simplify SETCC's.
2718 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2719 if (Simp.getNode()) return Simp;
2724 if (N1C->getZExtValue())
2725 return N2; // select true, X, Y -> X
2727 return N3; // select false, X, Y -> Y
2730 if (N2 == N3) return N2; // select C, X, X -> X
2734 if (N2C->getZExtValue()) // Unconditional branch
2735 return getNode(ISD::BR, MVT::Other, N1, N3);
2737 return N1; // Never-taken branch
2740 case ISD::VECTOR_SHUFFLE:
2741 assert(N1.getValueType() == N2.getValueType() &&
2742 N1.getValueType().isVector() &&
2743 VT.isVector() && N3.getValueType().isVector() &&
2744 N3.getOpcode() == ISD::BUILD_VECTOR &&
2745 VT.getVectorNumElements() == N3.getNumOperands() &&
2746 "Illegal VECTOR_SHUFFLE node!");
2748 case ISD::BIT_CONVERT:
2749 // Fold bit_convert nodes from a type to themselves.
2750 if (N1.getValueType() == VT)
2755 // Memoize node if it doesn't produce a flag.
2757 SDVTList VTs = getVTList(VT);
2758 if (VT != MVT::Flag) {
2759 SDValue Ops[] = { N1, N2, N3 };
2760 FoldingSetNodeID ID;
2761 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2763 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2764 return SDValue(E, 0);
2765 N = NodeAllocator.Allocate<TernarySDNode>();
2766 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2767 CSEMap.InsertNode(N, IP);
2769 N = NodeAllocator.Allocate<TernarySDNode>();
2770 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2772 AllNodes.push_back(N);
2776 return SDValue(N, 0);
2779 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2780 SDValue N1, SDValue N2, SDValue N3,
2782 SDValue Ops[] = { N1, N2, N3, N4 };
2783 return getNode(Opcode, VT, Ops, 4);
2786 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2787 SDValue N1, SDValue N2, SDValue N3,
2788 SDValue N4, SDValue N5) {
2789 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2790 return getNode(Opcode, VT, Ops, 5);
2793 /// getMemsetValue - Vectorized representation of the memset value
2795 static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG) {
2796 unsigned NumBits = VT.isVector() ?
2797 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2798 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2799 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
2801 for (unsigned i = NumBits; i > 8; i >>= 1) {
2802 Val = (Val << Shift) | Val;
2806 return DAG.getConstant(Val, VT);
2807 return DAG.getConstantFP(APFloat(Val), VT);
2810 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2811 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2813 for (unsigned i = NumBits; i > 8; i >>= 1) {
2814 Value = DAG.getNode(ISD::OR, VT,
2815 DAG.getNode(ISD::SHL, VT, Value,
2816 DAG.getConstant(Shift,
2817 TLI.getShiftAmountTy())),
2825 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2826 /// used when a memcpy is turned into a memset when the source is a constant
2828 static SDValue getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2829 const TargetLowering &TLI,
2830 std::string &Str, unsigned Offset) {
2831 // Handle vector with all elements zero.
2834 return DAG.getConstant(0, VT);
2835 unsigned NumElts = VT.getVectorNumElements();
2836 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2837 return DAG.getNode(ISD::BIT_CONVERT, VT,
2838 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2841 assert(!VT.isVector() && "Can't handle vector type here!");
2842 unsigned NumBits = VT.getSizeInBits();
2843 unsigned MSB = NumBits / 8;
2845 if (TLI.isLittleEndian())
2846 Offset = Offset + MSB - 1;
2847 for (unsigned i = 0; i != MSB; ++i) {
2848 Val = (Val << 8) | (unsigned char)Str[Offset];
2849 Offset += TLI.isLittleEndian() ? -1 : 1;
2851 return DAG.getConstant(Val, VT);
2854 /// getMemBasePlusOffset - Returns base and offset node for the
2856 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
2857 SelectionDAG &DAG) {
2858 MVT VT = Base.getValueType();
2859 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2862 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2864 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
2865 unsigned SrcDelta = 0;
2866 GlobalAddressSDNode *G = NULL;
2867 if (Src.getOpcode() == ISD::GlobalAddress)
2868 G = cast<GlobalAddressSDNode>(Src);
2869 else if (Src.getOpcode() == ISD::ADD &&
2870 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2871 Src.getOperand(1).getOpcode() == ISD::Constant) {
2872 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2873 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
2878 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2879 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2885 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2886 /// to replace the memset / memcpy is below the threshold. It also returns the
2887 /// types of the sequence of memory ops to perform memset / memcpy.
2889 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2890 SDValue Dst, SDValue Src,
2891 unsigned Limit, uint64_t Size, unsigned &Align,
2892 std::string &Str, bool &isSrcStr,
2894 const TargetLowering &TLI) {
2895 isSrcStr = isMemSrcFromString(Src, Str);
2896 bool isSrcConst = isa<ConstantSDNode>(Src);
2897 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2898 MVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2899 if (VT != MVT::iAny) {
2900 unsigned NewAlign = (unsigned)
2901 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2902 // If source is a string constant, this will require an unaligned load.
2903 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2904 if (Dst.getOpcode() != ISD::FrameIndex) {
2905 // Can't change destination alignment. It requires a unaligned store.
2909 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2910 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2911 if (MFI->isFixedObjectIndex(FI)) {
2912 // Can't change destination alignment. It requires a unaligned store.
2916 // Give the stack frame object a larger alignment if needed.
2917 if (MFI->getObjectAlignment(FI) < NewAlign)
2918 MFI->setObjectAlignment(FI, NewAlign);
2925 if (VT == MVT::iAny) {
2929 switch (Align & 7) {
2930 case 0: VT = MVT::i64; break;
2931 case 4: VT = MVT::i32; break;
2932 case 2: VT = MVT::i16; break;
2933 default: VT = MVT::i8; break;
2938 while (!TLI.isTypeLegal(LVT))
2939 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2940 assert(LVT.isInteger());
2946 unsigned NumMemOps = 0;
2948 unsigned VTSize = VT.getSizeInBits() / 8;
2949 while (VTSize > Size) {
2950 // For now, only use non-vector load / store's for the left-over pieces.
2951 if (VT.isVector()) {
2953 while (!TLI.isTypeLegal(VT))
2954 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2955 VTSize = VT.getSizeInBits() / 8;
2957 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2962 if (++NumMemOps > Limit)
2964 MemOps.push_back(VT);
2971 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG,
2972 SDValue Chain, SDValue Dst,
2973 SDValue Src, uint64_t Size,
2974 unsigned Align, bool AlwaysInline,
2975 const Value *DstSV, uint64_t DstSVOff,
2976 const Value *SrcSV, uint64_t SrcSVOff){
2977 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2979 // Expand memcpy to a series of load and store ops if the size operand falls
2980 // below a certain threshold.
2981 std::vector<MVT> MemOps;
2982 uint64_t Limit = -1ULL;
2984 Limit = TLI.getMaxStoresPerMemcpy();
2985 unsigned DstAlign = Align; // Destination alignment can change.
2988 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2989 Str, CopyFromStr, DAG, TLI))
2993 bool isZeroStr = CopyFromStr && Str.empty();
2994 SmallVector<SDValue, 8> OutChains;
2995 unsigned NumMemOps = MemOps.size();
2996 uint64_t SrcOff = 0, DstOff = 0;
2997 for (unsigned i = 0; i < NumMemOps; i++) {
2999 unsigned VTSize = VT.getSizeInBits() / 8;
3000 SDValue Value, Store;
3002 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3003 // It's unlikely a store of a vector immediate can be done in a single
3004 // instruction. It would require a load from a constantpool first.
3005 // We also handle store a vector with all zero's.
3006 // FIXME: Handle other cases where store of vector immediate is done in
3007 // a single instruction.
3008 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3009 Store = DAG.getStore(Chain, Value,
3010 getMemBasePlusOffset(Dst, DstOff, DAG),
3011 DstSV, DstSVOff + DstOff, false, DstAlign);
3013 Value = DAG.getLoad(VT, Chain,
3014 getMemBasePlusOffset(Src, SrcOff, DAG),
3015 SrcSV, SrcSVOff + SrcOff, false, Align);
3016 Store = DAG.getStore(Chain, Value,
3017 getMemBasePlusOffset(Dst, DstOff, DAG),
3018 DstSV, DstSVOff + DstOff, false, DstAlign);
3020 OutChains.push_back(Store);
3025 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3026 &OutChains[0], OutChains.size());
3029 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG,
3030 SDValue Chain, SDValue Dst,
3031 SDValue Src, uint64_t Size,
3032 unsigned Align, bool AlwaysInline,
3033 const Value *DstSV, uint64_t DstSVOff,
3034 const Value *SrcSV, uint64_t SrcSVOff){
3035 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3037 // Expand memmove to a series of load and store ops if the size operand falls
3038 // below a certain threshold.
3039 std::vector<MVT> MemOps;
3040 uint64_t Limit = -1ULL;
3042 Limit = TLI.getMaxStoresPerMemmove();
3043 unsigned DstAlign = Align; // Destination alignment can change.
3046 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3047 Str, CopyFromStr, DAG, TLI))
3050 uint64_t SrcOff = 0, DstOff = 0;
3052 SmallVector<SDValue, 8> LoadValues;
3053 SmallVector<SDValue, 8> LoadChains;
3054 SmallVector<SDValue, 8> OutChains;
3055 unsigned NumMemOps = MemOps.size();
3056 for (unsigned i = 0; i < NumMemOps; i++) {
3058 unsigned VTSize = VT.getSizeInBits() / 8;
3059 SDValue Value, Store;
3061 Value = DAG.getLoad(VT, Chain,
3062 getMemBasePlusOffset(Src, SrcOff, DAG),
3063 SrcSV, SrcSVOff + SrcOff, false, Align);
3064 LoadValues.push_back(Value);
3065 LoadChains.push_back(Value.getValue(1));
3068 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3069 &LoadChains[0], LoadChains.size());
3071 for (unsigned i = 0; i < NumMemOps; i++) {
3073 unsigned VTSize = VT.getSizeInBits() / 8;
3074 SDValue Value, Store;
3076 Store = DAG.getStore(Chain, LoadValues[i],
3077 getMemBasePlusOffset(Dst, DstOff, DAG),
3078 DstSV, DstSVOff + DstOff, false, DstAlign);
3079 OutChains.push_back(Store);
3083 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3084 &OutChains[0], OutChains.size());
3087 static SDValue getMemsetStores(SelectionDAG &DAG,
3088 SDValue Chain, SDValue Dst,
3089 SDValue Src, uint64_t Size,
3091 const Value *DstSV, uint64_t DstSVOff) {
3092 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3094 // Expand memset to a series of load/store ops if the size operand
3095 // falls below a certain threshold.
3096 std::vector<MVT> MemOps;
3099 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3100 Size, Align, Str, CopyFromStr, DAG, TLI))
3103 SmallVector<SDValue, 8> OutChains;
3104 uint64_t DstOff = 0;
3106 unsigned NumMemOps = MemOps.size();
3107 for (unsigned i = 0; i < NumMemOps; i++) {
3109 unsigned VTSize = VT.getSizeInBits() / 8;
3110 SDValue Value = getMemsetValue(Src, VT, DAG);
3111 SDValue Store = DAG.getStore(Chain, Value,
3112 getMemBasePlusOffset(Dst, DstOff, DAG),
3113 DstSV, DstSVOff + DstOff);
3114 OutChains.push_back(Store);
3118 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3119 &OutChains[0], OutChains.size());
3122 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDValue Dst,
3123 SDValue Src, SDValue Size,
3124 unsigned Align, bool AlwaysInline,
3125 const Value *DstSV, uint64_t DstSVOff,
3126 const Value *SrcSV, uint64_t SrcSVOff) {
3128 // Check to see if we should lower the memcpy to loads and stores first.
3129 // For cases within the target-specified limits, this is the best choice.
3130 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3132 // Memcpy with size zero? Just return the original chain.
3133 if (ConstantSize->isNullValue())
3137 getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3138 ConstantSize->getZExtValue(),
3139 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3140 if (Result.getNode())
3144 // Then check to see if we should lower the memcpy with target-specific
3145 // code. If the target chooses to do this, this is the next best.
3147 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
3149 DstSV, DstSVOff, SrcSV, SrcSVOff);
3150 if (Result.getNode())
3153 // If we really need inline code and the target declined to provide it,
3154 // use a (potentially long) sequence of loads and stores.
3156 assert(ConstantSize && "AlwaysInline requires a constant size!");
3157 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3158 ConstantSize->getZExtValue(), Align, true,
3159 DstSV, DstSVOff, SrcSV, SrcSVOff);
3162 // Emit a library call.
3163 TargetLowering::ArgListTy Args;
3164 TargetLowering::ArgListEntry Entry;
3165 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3166 Entry.Node = Dst; Args.push_back(Entry);
3167 Entry.Node = Src; Args.push_back(Entry);
3168 Entry.Node = Size; Args.push_back(Entry);
3169 std::pair<SDValue,SDValue> CallResult =
3170 TLI.LowerCallTo(Chain, Type::VoidTy,
3171 false, false, false, false, CallingConv::C, false,
3172 getExternalSymbol("memcpy", TLI.getPointerTy()),
3174 return CallResult.second;
3177 SDValue SelectionDAG::getMemmove(SDValue Chain, SDValue Dst,
3178 SDValue Src, SDValue Size,
3180 const Value *DstSV, uint64_t DstSVOff,
3181 const Value *SrcSV, uint64_t SrcSVOff) {
3183 // Check to see if we should lower the memmove to loads and stores first.
3184 // For cases within the target-specified limits, this is the best choice.
3185 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3187 // Memmove with size zero? Just return the original chain.
3188 if (ConstantSize->isNullValue())
3192 getMemmoveLoadsAndStores(*this, Chain, Dst, Src,
3193 ConstantSize->getZExtValue(),
3194 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3195 if (Result.getNode())
3199 // Then check to see if we should lower the memmove with target-specific
3200 // code. If the target chooses to do this, this is the next best.
3202 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
3203 DstSV, DstSVOff, SrcSV, SrcSVOff);
3204 if (Result.getNode())
3207 // Emit a library call.
3208 TargetLowering::ArgListTy Args;
3209 TargetLowering::ArgListEntry Entry;
3210 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3211 Entry.Node = Dst; Args.push_back(Entry);
3212 Entry.Node = Src; Args.push_back(Entry);
3213 Entry.Node = Size; Args.push_back(Entry);
3214 std::pair<SDValue,SDValue> CallResult =
3215 TLI.LowerCallTo(Chain, Type::VoidTy,
3216 false, false, false, false, CallingConv::C, false,
3217 getExternalSymbol("memmove", TLI.getPointerTy()),
3219 return CallResult.second;
3222 SDValue SelectionDAG::getMemset(SDValue Chain, SDValue Dst,
3223 SDValue Src, SDValue Size,
3225 const Value *DstSV, uint64_t DstSVOff) {
3227 // Check to see if we should lower the memset to stores first.
3228 // For cases within the target-specified limits, this is the best choice.
3229 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3231 // Memset with size zero? Just return the original chain.
3232 if (ConstantSize->isNullValue())
3236 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getZExtValue(),
3237 Align, DstSV, DstSVOff);
3238 if (Result.getNode())
3242 // Then check to see if we should lower the memset with target-specific
3243 // code. If the target chooses to do this, this is the next best.
3245 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3247 if (Result.getNode())
3250 // Emit a library call.
3251 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3252 TargetLowering::ArgListTy Args;
3253 TargetLowering::ArgListEntry Entry;
3254 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3255 Args.push_back(Entry);
3256 // Extend or truncate the argument to be an i32 value for the call.
3257 if (Src.getValueType().bitsGT(MVT::i32))
3258 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3260 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3261 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3262 Args.push_back(Entry);
3263 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3264 Args.push_back(Entry);
3265 std::pair<SDValue,SDValue> CallResult =
3266 TLI.LowerCallTo(Chain, Type::VoidTy,
3267 false, false, false, false, CallingConv::C, false,
3268 getExternalSymbol("memset", TLI.getPointerTy()),
3270 return CallResult.second;
3273 SDValue SelectionDAG::getAtomic(unsigned Opcode, MVT MemVT,
3275 SDValue Ptr, SDValue Cmp,
3276 SDValue Swp, const Value* PtrVal,
3277 unsigned Alignment) {
3278 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3279 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3281 MVT VT = Cmp.getValueType();
3283 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3284 Alignment = getMVTAlignment(MemVT);
3286 SDVTList VTs = getVTList(VT, MVT::Other);
3287 FoldingSetNodeID ID;
3288 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3289 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3291 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3292 return SDValue(E, 0);
3293 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3294 new (N) AtomicSDNode(Opcode, VTs, MemVT,
3295 Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3296 CSEMap.InsertNode(N, IP);
3297 AllNodes.push_back(N);
3298 return SDValue(N, 0);
3301 SDValue SelectionDAG::getAtomic(unsigned Opcode, MVT MemVT,
3303 SDValue Ptr, SDValue Val,
3304 const Value* PtrVal,
3305 unsigned Alignment) {
3306 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3307 Opcode == ISD::ATOMIC_LOAD_SUB ||
3308 Opcode == ISD::ATOMIC_LOAD_AND ||
3309 Opcode == ISD::ATOMIC_LOAD_OR ||
3310 Opcode == ISD::ATOMIC_LOAD_XOR ||
3311 Opcode == ISD::ATOMIC_LOAD_NAND ||
3312 Opcode == ISD::ATOMIC_LOAD_MIN ||
3313 Opcode == ISD::ATOMIC_LOAD_MAX ||
3314 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3315 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3316 Opcode == ISD::ATOMIC_SWAP) &&
3317 "Invalid Atomic Op");
3319 MVT VT = Val.getValueType();
3321 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3322 Alignment = getMVTAlignment(MemVT);
3324 SDVTList VTs = getVTList(VT, MVT::Other);
3325 FoldingSetNodeID ID;
3326 SDValue Ops[] = {Chain, Ptr, Val};
3327 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3329 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3330 return SDValue(E, 0);
3331 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3332 new (N) AtomicSDNode(Opcode, VTs, MemVT,
3333 Chain, Ptr, Val, PtrVal, Alignment);
3334 CSEMap.InsertNode(N, IP);
3335 AllNodes.push_back(N);
3336 return SDValue(N, 0);
3339 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3340 /// Allowed to return something different (and simpler) if Simplify is true.
3341 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps) {
3345 SmallVector<MVT, 4> VTs;
3346 VTs.reserve(NumOps);
3347 for (unsigned i = 0; i < NumOps; ++i)
3348 VTs.push_back(Ops[i].getValueType());
3349 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3353 SelectionDAG::getMemIntrinsicNode(unsigned Opcode,
3354 const MVT *VTs, unsigned NumVTs,
3355 const SDValue *Ops, unsigned NumOps,
3356 MVT MemVT, const Value *srcValue, int SVOff,
3357 unsigned Align, bool Vol,
3358 bool ReadMem, bool WriteMem) {
3359 return getMemIntrinsicNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps,
3360 MemVT, srcValue, SVOff, Align, Vol,
3365 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDVTList VTList,
3366 const SDValue *Ops, unsigned NumOps,
3367 MVT MemVT, const Value *srcValue, int SVOff,
3368 unsigned Align, bool Vol,
3369 bool ReadMem, bool WriteMem) {
3370 // Memoize the node unless it returns a flag.
3371 MemIntrinsicSDNode *N;
3372 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3373 FoldingSetNodeID ID;
3374 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3376 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3377 return SDValue(E, 0);
3379 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3380 new (N) MemIntrinsicSDNode(Opcode, VTList, Ops, NumOps, MemVT,
3381 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3382 CSEMap.InsertNode(N, IP);
3384 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3385 new (N) MemIntrinsicSDNode(Opcode, VTList, Ops, NumOps, MemVT,
3386 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3388 AllNodes.push_back(N);
3389 return SDValue(N, 0);
3393 SelectionDAG::getCall(unsigned CallingConv, bool IsVarArgs, bool IsTailCall,
3394 bool IsInreg, SDVTList VTs,
3395 const SDValue *Operands, unsigned NumOperands) {
3396 // Do not include isTailCall in the folding set profile.
3397 FoldingSetNodeID ID;
3398 AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
3399 ID.AddInteger(CallingConv);
3400 ID.AddInteger(IsVarArgs);
3402 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3403 // Instead of including isTailCall in the folding set, we just
3404 // set the flag of the existing node.
3406 cast<CallSDNode>(E)->setNotTailCall();
3407 return SDValue(E, 0);
3409 SDNode *N = NodeAllocator.Allocate<CallSDNode>();
3410 new (N) CallSDNode(CallingConv, IsVarArgs, IsTailCall, IsInreg,
3411 VTs, Operands, NumOperands);
3412 CSEMap.InsertNode(N, IP);
3413 AllNodes.push_back(N);
3414 return SDValue(N, 0);
3418 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3419 MVT VT, SDValue Chain,
3420 SDValue Ptr, SDValue Offset,
3421 const Value *SV, int SVOffset, MVT EVT,
3422 bool isVolatile, unsigned Alignment) {
3423 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3424 Alignment = getMVTAlignment(VT);
3427 ExtType = ISD::NON_EXTLOAD;
3428 } else if (ExtType == ISD::NON_EXTLOAD) {
3429 assert(VT == EVT && "Non-extending load from different memory type!");
3433 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3434 "Invalid vector extload!");
3436 assert(EVT.bitsLT(VT) &&
3437 "Should only be an extending load, not truncating!");
3438 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3439 "Cannot sign/zero extend a FP/Vector load!");
3440 assert(VT.isInteger() == EVT.isInteger() &&
3441 "Cannot convert from FP to Int or Int -> FP!");
3444 bool Indexed = AM != ISD::UNINDEXED;
3445 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3446 "Unindexed load with an offset!");
3448 SDVTList VTs = Indexed ?
3449 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3450 SDValue Ops[] = { Chain, Ptr, Offset };
3451 FoldingSetNodeID ID;
3452 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3454 ID.AddInteger(ExtType);
3455 ID.AddInteger(EVT.getRawBits());
3456 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3458 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3459 return SDValue(E, 0);
3460 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3461 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3462 Alignment, isVolatile);
3463 CSEMap.InsertNode(N, IP);
3464 AllNodes.push_back(N);
3465 return SDValue(N, 0);
3468 SDValue SelectionDAG::getLoad(MVT VT,
3469 SDValue Chain, SDValue Ptr,
3470 const Value *SV, int SVOffset,
3471 bool isVolatile, unsigned Alignment) {
3472 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3473 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3474 SV, SVOffset, VT, isVolatile, Alignment);
3477 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3478 SDValue Chain, SDValue Ptr,
3480 int SVOffset, MVT EVT,
3481 bool isVolatile, unsigned Alignment) {
3482 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3483 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3484 SV, SVOffset, EVT, isVolatile, Alignment);
3488 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDValue Base,
3489 SDValue Offset, ISD::MemIndexedMode AM) {
3490 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3491 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3492 "Load is already a indexed load!");
3493 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3494 LD->getChain(), Base, Offset, LD->getSrcValue(),
3495 LD->getSrcValueOffset(), LD->getMemoryVT(),
3496 LD->isVolatile(), LD->getAlignment());
3499 SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
3500 SDValue Ptr, const Value *SV, int SVOffset,
3501 bool isVolatile, unsigned Alignment) {
3502 MVT VT = Val.getValueType();
3504 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3505 Alignment = getMVTAlignment(VT);
3507 SDVTList VTs = getVTList(MVT::Other);
3508 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3509 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3510 FoldingSetNodeID ID;
3511 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3512 ID.AddInteger(ISD::UNINDEXED);
3513 ID.AddInteger(false);
3514 ID.AddInteger(VT.getRawBits());
3515 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3517 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3518 return SDValue(E, 0);
3519 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3520 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3521 VT, SV, SVOffset, Alignment, isVolatile);
3522 CSEMap.InsertNode(N, IP);
3523 AllNodes.push_back(N);
3524 return SDValue(N, 0);
3527 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDValue Val,
3528 SDValue Ptr, const Value *SV,
3529 int SVOffset, MVT SVT,
3530 bool isVolatile, unsigned Alignment) {
3531 MVT VT = Val.getValueType();
3534 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3536 assert(VT.bitsGT(SVT) && "Not a truncation?");
3537 assert(VT.isInteger() == SVT.isInteger() &&
3538 "Can't do FP-INT conversion!");
3540 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3541 Alignment = getMVTAlignment(VT);
3543 SDVTList VTs = getVTList(MVT::Other);
3544 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3545 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3546 FoldingSetNodeID ID;
3547 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3548 ID.AddInteger(ISD::UNINDEXED);
3550 ID.AddInteger(SVT.getRawBits());
3551 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3553 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3554 return SDValue(E, 0);
3555 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3556 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3557 SVT, SV, SVOffset, Alignment, isVolatile);
3558 CSEMap.InsertNode(N, IP);
3559 AllNodes.push_back(N);
3560 return SDValue(N, 0);
3564 SelectionDAG::getIndexedStore(SDValue OrigStore, SDValue Base,
3565 SDValue Offset, ISD::MemIndexedMode AM) {
3566 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3567 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3568 "Store is already a indexed store!");
3569 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3570 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3571 FoldingSetNodeID ID;
3572 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3574 ID.AddInteger(ST->isTruncatingStore());
3575 ID.AddInteger(ST->getMemoryVT().getRawBits());
3576 ID.AddInteger(ST->getRawFlags());
3578 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3579 return SDValue(E, 0);
3580 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3581 new (N) StoreSDNode(Ops, VTs, AM,
3582 ST->isTruncatingStore(), ST->getMemoryVT(),
3583 ST->getSrcValue(), ST->getSrcValueOffset(),
3584 ST->getAlignment(), ST->isVolatile());
3585 CSEMap.InsertNode(N, IP);
3586 AllNodes.push_back(N);
3587 return SDValue(N, 0);
3590 SDValue SelectionDAG::getVAArg(MVT VT,
3591 SDValue Chain, SDValue Ptr,
3593 SDValue Ops[] = { Chain, Ptr, SV };
3594 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3597 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3598 const SDUse *Ops, unsigned NumOps) {
3600 case 0: return getNode(Opcode, VT);
3601 case 1: return getNode(Opcode, VT, Ops[0]);
3602 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3603 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3607 // Copy from an SDUse array into an SDValue array for use with
3608 // the regular getNode logic.
3609 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3610 return getNode(Opcode, VT, &NewOps[0], NumOps);
3613 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3614 const SDValue *Ops, unsigned NumOps) {
3616 case 0: return getNode(Opcode, VT);
3617 case 1: return getNode(Opcode, VT, Ops[0]);
3618 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3619 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3625 case ISD::SELECT_CC: {
3626 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3627 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3628 "LHS and RHS of condition must have same type!");
3629 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3630 "True and False arms of SelectCC must have same type!");
3631 assert(Ops[2].getValueType() == VT &&
3632 "select_cc node must be of same type as true and false value!");
3636 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3637 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3638 "LHS/RHS of comparison should match types!");
3645 SDVTList VTs = getVTList(VT);
3646 if (VT != MVT::Flag) {
3647 FoldingSetNodeID ID;
3648 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3650 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3651 return SDValue(E, 0);
3652 N = NodeAllocator.Allocate<SDNode>();
3653 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3654 CSEMap.InsertNode(N, IP);
3656 N = NodeAllocator.Allocate<SDNode>();
3657 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3659 AllNodes.push_back(N);
3663 return SDValue(N, 0);
3666 SDValue SelectionDAG::getNode(unsigned Opcode,
3667 const std::vector<MVT> &ResultTys,
3668 const SDValue *Ops, unsigned NumOps) {
3669 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3673 SDValue SelectionDAG::getNode(unsigned Opcode,
3674 const MVT *VTs, unsigned NumVTs,
3675 const SDValue *Ops, unsigned NumOps) {
3677 return getNode(Opcode, VTs[0], Ops, NumOps);
3678 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3681 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3682 const SDValue *Ops, unsigned NumOps) {
3683 if (VTList.NumVTs == 1)
3684 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3687 // FIXME: figure out how to safely handle things like
3688 // int foo(int x) { return 1 << (x & 255); }
3689 // int bar() { return foo(256); }
3691 case ISD::SRA_PARTS:
3692 case ISD::SRL_PARTS:
3693 case ISD::SHL_PARTS:
3694 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3695 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3696 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3697 else if (N3.getOpcode() == ISD::AND)
3698 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3699 // If the and is only masking out bits that cannot effect the shift,
3700 // eliminate the and.
3701 unsigned NumBits = VT.getSizeInBits()*2;
3702 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3703 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3709 // Memoize the node unless it returns a flag.
3711 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3712 FoldingSetNodeID ID;
3713 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3715 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3716 return SDValue(E, 0);
3718 N = NodeAllocator.Allocate<UnarySDNode>();
3719 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3720 } else if (NumOps == 2) {
3721 N = NodeAllocator.Allocate<BinarySDNode>();
3722 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3723 } else if (NumOps == 3) {
3724 N = NodeAllocator.Allocate<TernarySDNode>();
3725 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3727 N = NodeAllocator.Allocate<SDNode>();
3728 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3730 CSEMap.InsertNode(N, IP);
3733 N = NodeAllocator.Allocate<UnarySDNode>();
3734 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3735 } else if (NumOps == 2) {
3736 N = NodeAllocator.Allocate<BinarySDNode>();
3737 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3738 } else if (NumOps == 3) {
3739 N = NodeAllocator.Allocate<TernarySDNode>();
3740 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3742 N = NodeAllocator.Allocate<SDNode>();
3743 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3746 AllNodes.push_back(N);
3750 return SDValue(N, 0);
3753 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3754 return getNode(Opcode, VTList, 0, 0);
3757 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3759 SDValue Ops[] = { N1 };
3760 return getNode(Opcode, VTList, Ops, 1);
3763 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3764 SDValue N1, SDValue N2) {
3765 SDValue Ops[] = { N1, N2 };
3766 return getNode(Opcode, VTList, Ops, 2);
3769 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3770 SDValue N1, SDValue N2, SDValue N3) {
3771 SDValue Ops[] = { N1, N2, N3 };
3772 return getNode(Opcode, VTList, Ops, 3);
3775 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3776 SDValue N1, SDValue N2, SDValue N3,
3778 SDValue Ops[] = { N1, N2, N3, N4 };
3779 return getNode(Opcode, VTList, Ops, 4);
3782 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3783 SDValue N1, SDValue N2, SDValue N3,
3784 SDValue N4, SDValue N5) {
3785 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3786 return getNode(Opcode, VTList, Ops, 5);
3789 SDVTList SelectionDAG::getVTList(MVT VT) {
3790 return makeVTList(SDNode::getValueTypeList(VT), 1);
3793 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3794 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3795 E = VTList.rend(); I != E; ++I)
3796 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
3799 MVT *Array = Allocator.Allocate<MVT>(2);
3802 SDVTList Result = makeVTList(Array, 2);
3803 VTList.push_back(Result);
3807 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
3808 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3809 E = VTList.rend(); I != E; ++I)
3810 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
3814 MVT *Array = Allocator.Allocate<MVT>(3);
3818 SDVTList Result = makeVTList(Array, 3);
3819 VTList.push_back(Result);
3823 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3, MVT VT4) {
3824 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3825 E = VTList.rend(); I != E; ++I)
3826 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
3827 I->VTs[2] == VT3 && I->VTs[3] == VT4)
3830 MVT *Array = Allocator.Allocate<MVT>(3);
3835 SDVTList Result = makeVTList(Array, 4);
3836 VTList.push_back(Result);
3840 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3842 case 0: assert(0 && "Cannot have nodes without results!");
3843 case 1: return getVTList(VTs[0]);
3844 case 2: return getVTList(VTs[0], VTs[1]);
3845 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3849 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3850 E = VTList.rend(); I != E; ++I) {
3851 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
3854 bool NoMatch = false;
3855 for (unsigned i = 2; i != NumVTs; ++i)
3856 if (VTs[i] != I->VTs[i]) {
3864 MVT *Array = Allocator.Allocate<MVT>(NumVTs);
3865 std::copy(VTs, VTs+NumVTs, Array);
3866 SDVTList Result = makeVTList(Array, NumVTs);
3867 VTList.push_back(Result);
3872 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3873 /// specified operands. If the resultant node already exists in the DAG,
3874 /// this does not modify the specified node, instead it returns the node that
3875 /// already exists. If the resultant node does not exist in the DAG, the
3876 /// input node is returned. As a degenerate case, if you specify the same
3877 /// input operands as the node already has, the input node is returned.
3878 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
3879 SDNode *N = InN.getNode();
3880 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3882 // Check to see if there is no change.
3883 if (Op == N->getOperand(0)) return InN;
3885 // See if the modified node already exists.
3886 void *InsertPos = 0;
3887 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3888 return SDValue(Existing, InN.getResNo());
3890 // Nope it doesn't. Remove the node from its current place in the maps.
3892 if (!RemoveNodeFromCSEMaps(N))
3895 // Now we update the operands.
3896 N->OperandList[0].getVal()->removeUser(0, N);
3897 N->OperandList[0] = Op;
3898 N->OperandList[0].setUser(N);
3899 Op.getNode()->addUser(0, N);
3901 // If this gets put into a CSE map, add it.
3902 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3906 SDValue SelectionDAG::
3907 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
3908 SDNode *N = InN.getNode();
3909 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3911 // Check to see if there is no change.
3912 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3913 return InN; // No operands changed, just return the input node.
3915 // See if the modified node already exists.
3916 void *InsertPos = 0;
3917 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3918 return SDValue(Existing, InN.getResNo());
3920 // Nope it doesn't. Remove the node from its current place in the maps.
3922 if (!RemoveNodeFromCSEMaps(N))
3925 // Now we update the operands.
3926 if (N->OperandList[0] != Op1) {
3927 N->OperandList[0].getVal()->removeUser(0, N);
3928 N->OperandList[0] = Op1;
3929 N->OperandList[0].setUser(N);
3930 Op1.getNode()->addUser(0, N);
3932 if (N->OperandList[1] != Op2) {
3933 N->OperandList[1].getVal()->removeUser(1, N);
3934 N->OperandList[1] = Op2;
3935 N->OperandList[1].setUser(N);
3936 Op2.getNode()->addUser(1, N);
3939 // If this gets put into a CSE map, add it.
3940 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3944 SDValue SelectionDAG::
3945 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
3946 SDValue Ops[] = { Op1, Op2, Op3 };
3947 return UpdateNodeOperands(N, Ops, 3);
3950 SDValue SelectionDAG::
3951 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3952 SDValue Op3, SDValue Op4) {
3953 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
3954 return UpdateNodeOperands(N, Ops, 4);
3957 SDValue SelectionDAG::
3958 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3959 SDValue Op3, SDValue Op4, SDValue Op5) {
3960 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3961 return UpdateNodeOperands(N, Ops, 5);
3964 SDValue SelectionDAG::
3965 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
3966 SDNode *N = InN.getNode();
3967 assert(N->getNumOperands() == NumOps &&
3968 "Update with wrong number of operands");
3970 // Check to see if there is no change.
3971 bool AnyChange = false;
3972 for (unsigned i = 0; i != NumOps; ++i) {
3973 if (Ops[i] != N->getOperand(i)) {
3979 // No operands changed, just return the input node.
3980 if (!AnyChange) return InN;
3982 // See if the modified node already exists.
3983 void *InsertPos = 0;
3984 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3985 return SDValue(Existing, InN.getResNo());
3987 // Nope it doesn't. Remove the node from its current place in the maps.
3989 if (!RemoveNodeFromCSEMaps(N))
3992 // Now we update the operands.
3993 for (unsigned i = 0; i != NumOps; ++i) {
3994 if (N->OperandList[i] != Ops[i]) {
3995 N->OperandList[i].getVal()->removeUser(i, N);
3996 N->OperandList[i] = Ops[i];
3997 N->OperandList[i].setUser(N);
3998 Ops[i].getNode()->addUser(i, N);
4002 // If this gets put into a CSE map, add it.
4003 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4007 /// DropOperands - Release the operands and set this node to have
4009 void SDNode::DropOperands() {
4010 // Unlike the code in MorphNodeTo that does this, we don't need to
4011 // watch for dead nodes here.
4012 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
4013 I->getVal()->removeUser(std::distance(op_begin(), I), this);
4018 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4021 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4023 SDVTList VTs = getVTList(VT);
4024 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4027 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4028 MVT VT, SDValue Op1) {
4029 SDVTList VTs = getVTList(VT);
4030 SDValue Ops[] = { Op1 };
4031 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4034 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4035 MVT VT, SDValue Op1,
4037 SDVTList VTs = getVTList(VT);
4038 SDValue Ops[] = { Op1, Op2 };
4039 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4042 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4043 MVT VT, SDValue Op1,
4044 SDValue Op2, SDValue Op3) {
4045 SDVTList VTs = getVTList(VT);
4046 SDValue Ops[] = { Op1, Op2, Op3 };
4047 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4050 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4051 MVT VT, const SDValue *Ops,
4053 SDVTList VTs = getVTList(VT);
4054 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4057 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4058 MVT VT1, MVT VT2, const SDValue *Ops,
4060 SDVTList VTs = getVTList(VT1, VT2);
4061 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4064 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4066 SDVTList VTs = getVTList(VT1, VT2);
4067 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4070 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4071 MVT VT1, MVT VT2, MVT VT3,
4072 const SDValue *Ops, unsigned NumOps) {
4073 SDVTList VTs = getVTList(VT1, VT2, VT3);
4074 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4077 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4078 MVT VT1, MVT VT2, MVT VT3, MVT VT4,
4079 const SDValue *Ops, unsigned NumOps) {
4080 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4081 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4084 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4087 SDVTList VTs = getVTList(VT1, VT2);
4088 SDValue Ops[] = { Op1 };
4089 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4092 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4094 SDValue Op1, SDValue Op2) {
4095 SDVTList VTs = getVTList(VT1, VT2);
4096 SDValue Ops[] = { Op1, Op2 };
4097 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4100 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4102 SDValue Op1, SDValue Op2,
4104 SDVTList VTs = getVTList(VT1, VT2);
4105 SDValue Ops[] = { Op1, Op2, Op3 };
4106 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4109 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4110 MVT VT1, MVT VT2, MVT VT3,
4111 SDValue Op1, SDValue Op2,
4113 SDVTList VTs = getVTList(VT1, VT2, VT3);
4114 SDValue Ops[] = { Op1, Op2, Op3 };
4115 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4118 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4119 SDVTList VTs, const SDValue *Ops,
4121 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4124 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4126 SDVTList VTs = getVTList(VT);
4127 return MorphNodeTo(N, Opc, VTs, 0, 0);
4130 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4131 MVT VT, SDValue Op1) {
4132 SDVTList VTs = getVTList(VT);
4133 SDValue Ops[] = { Op1 };
4134 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4137 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4138 MVT VT, SDValue Op1,
4140 SDVTList VTs = getVTList(VT);
4141 SDValue Ops[] = { Op1, Op2 };
4142 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4145 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4146 MVT VT, SDValue Op1,
4147 SDValue Op2, SDValue Op3) {
4148 SDVTList VTs = getVTList(VT);
4149 SDValue Ops[] = { Op1, Op2, Op3 };
4150 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4153 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4154 MVT VT, const SDValue *Ops,
4156 SDVTList VTs = getVTList(VT);
4157 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4160 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4161 MVT VT1, MVT VT2, const SDValue *Ops,
4163 SDVTList VTs = getVTList(VT1, VT2);
4164 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4167 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4169 SDVTList VTs = getVTList(VT1, VT2);
4170 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4173 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4174 MVT VT1, MVT VT2, MVT VT3,
4175 const SDValue *Ops, unsigned NumOps) {
4176 SDVTList VTs = getVTList(VT1, VT2, VT3);
4177 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4180 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4183 SDVTList VTs = getVTList(VT1, VT2);
4184 SDValue Ops[] = { Op1 };
4185 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4188 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4190 SDValue Op1, SDValue Op2) {
4191 SDVTList VTs = getVTList(VT1, VT2);
4192 SDValue Ops[] = { Op1, Op2 };
4193 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4196 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4198 SDValue Op1, SDValue Op2,
4200 SDVTList VTs = getVTList(VT1, VT2);
4201 SDValue Ops[] = { Op1, Op2, Op3 };
4202 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4205 /// MorphNodeTo - These *mutate* the specified node to have the specified
4206 /// return type, opcode, and operands.
4208 /// Note that MorphNodeTo returns the resultant node. If there is already a
4209 /// node of the specified opcode and operands, it returns that node instead of
4210 /// the current one.
4212 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4213 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4214 /// node, and because it doesn't require CSE recalculation for any of
4215 /// the node's users.
4217 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4218 SDVTList VTs, const SDValue *Ops,
4220 // If an identical node already exists, use it.
4222 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4223 FoldingSetNodeID ID;
4224 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4225 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4229 if (!RemoveNodeFromCSEMaps(N))
4232 // Start the morphing.
4234 N->ValueList = VTs.VTs;
4235 N->NumValues = VTs.NumVTs;
4237 // Clear the operands list, updating used nodes to remove this from their
4238 // use list. Keep track of any operands that become dead as a result.
4239 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4240 for (SDNode::op_iterator B = N->op_begin(), I = B, E = N->op_end();
4242 SDNode *Used = I->getVal();
4243 Used->removeUser(std::distance(B, I), N);
4244 if (Used->use_empty())
4245 DeadNodeSet.insert(Used);
4248 // If NumOps is larger than the # of operands we currently have, reallocate
4249 // the operand list.
4250 if (NumOps > N->NumOperands) {
4251 if (N->OperandsNeedDelete)
4252 delete[] N->OperandList;
4254 if (N->isMachineOpcode()) {
4255 // We're creating a final node that will live unmorphed for the
4256 // remainder of the current SelectionDAG iteration, so we can allocate
4257 // the operands directly out of a pool with no recycling metadata.
4258 N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
4259 N->OperandsNeedDelete = false;
4261 N->OperandList = new SDUse[NumOps];
4262 N->OperandsNeedDelete = true;
4266 // Assign the new operands.
4267 N->NumOperands = NumOps;
4268 for (unsigned i = 0, e = NumOps; i != e; ++i) {
4269 N->OperandList[i] = Ops[i];
4270 N->OperandList[i].setUser(N);
4271 SDNode *ToUse = N->OperandList[i].getVal();
4272 ToUse->addUser(i, N);
4275 // Delete any nodes that are still dead after adding the uses for the
4277 SmallVector<SDNode *, 16> DeadNodes;
4278 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4279 E = DeadNodeSet.end(); I != E; ++I)
4280 if ((*I)->use_empty())
4281 DeadNodes.push_back(*I);
4282 RemoveDeadNodes(DeadNodes);
4285 CSEMap.InsertNode(N, IP); // Memoize the new node.
4290 /// getTargetNode - These are used for target selectors to create a new node
4291 /// with specified return type(s), target opcode, and operands.
4293 /// Note that getTargetNode returns the resultant node. If there is already a
4294 /// node of the specified opcode and operands, it returns that node instead of
4295 /// the current one.
4296 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
4297 return getNode(~Opcode, VT).getNode();
4299 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
4300 return getNode(~Opcode, VT, Op1).getNode();
4302 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4303 SDValue Op1, SDValue Op2) {
4304 return getNode(~Opcode, VT, Op1, Op2).getNode();
4306 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4307 SDValue Op1, SDValue Op2,
4309 return getNode(~Opcode, VT, Op1, Op2, Op3).getNode();
4311 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4312 const SDValue *Ops, unsigned NumOps) {
4313 return getNode(~Opcode, VT, Ops, NumOps).getNode();
4315 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
4316 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4318 return getNode(~Opcode, VTs, 2, &Op, 0).getNode();
4320 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4321 MVT VT2, SDValue Op1) {
4322 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4323 return getNode(~Opcode, VTs, 2, &Op1, 1).getNode();
4325 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4326 MVT VT2, SDValue Op1,
4328 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4329 SDValue Ops[] = { Op1, Op2 };
4330 return getNode(~Opcode, VTs, 2, Ops, 2).getNode();
4332 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4333 MVT VT2, SDValue Op1,
4334 SDValue Op2, SDValue Op3) {
4335 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4336 SDValue Ops[] = { Op1, Op2, Op3 };
4337 return getNode(~Opcode, VTs, 2, Ops, 3).getNode();
4339 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
4340 const SDValue *Ops, unsigned NumOps) {
4341 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4342 return getNode(~Opcode, VTs, 2, Ops, NumOps).getNode();
4344 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4345 SDValue Op1, SDValue Op2) {
4346 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4347 SDValue Ops[] = { Op1, Op2 };
4348 return getNode(~Opcode, VTs, 3, Ops, 2).getNode();
4350 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4351 SDValue Op1, SDValue Op2,
4353 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4354 SDValue Ops[] = { Op1, Op2, Op3 };
4355 return getNode(~Opcode, VTs, 3, Ops, 3).getNode();
4357 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4358 const SDValue *Ops, unsigned NumOps) {
4359 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4360 return getNode(~Opcode, VTs, 3, Ops, NumOps).getNode();
4362 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4363 MVT VT2, MVT VT3, MVT VT4,
4364 const SDValue *Ops, unsigned NumOps) {
4365 std::vector<MVT> VTList;
4366 VTList.push_back(VT1);
4367 VTList.push_back(VT2);
4368 VTList.push_back(VT3);
4369 VTList.push_back(VT4);
4370 const MVT *VTs = getNodeValueTypes(VTList);
4371 return getNode(~Opcode, VTs, 4, Ops, NumOps).getNode();
4373 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
4374 const std::vector<MVT> &ResultTys,
4375 const SDValue *Ops, unsigned NumOps) {
4376 const MVT *VTs = getNodeValueTypes(ResultTys);
4377 return getNode(~Opcode, VTs, ResultTys.size(),
4378 Ops, NumOps).getNode();
4381 /// getNodeIfExists - Get the specified node if it's already available, or
4382 /// else return NULL.
4383 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4384 const SDValue *Ops, unsigned NumOps) {
4385 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4386 FoldingSetNodeID ID;
4387 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4389 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4396 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4397 /// This can cause recursive merging of nodes in the DAG.
4399 /// This version assumes From has a single result value.
4401 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4402 DAGUpdateListener *UpdateListener) {
4403 SDNode *From = FromN.getNode();
4404 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4405 "Cannot replace with this method!");
4406 assert(From != To.getNode() && "Cannot replace uses of with self");
4408 // Iterate over all the existing uses of From. This specifically avoids
4409 // visiting any new uses of From that arise while the replacement is
4410 // happening, because any such uses would be the result of CSE: If an
4411 // existing node looks like From after one of its operands is replaced
4412 // by To, we don't want to replace of all its users with To too.
4413 // See PR3018 for more info.
4414 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4417 do ++UI; while (UI != UE && *UI == U);
4419 // This node is about to morph, remove its old self from the CSE maps.
4420 RemoveNodeFromCSEMaps(U);
4422 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4423 I != E; ++I, ++operandNum)
4424 if (I->getVal() == From) {
4425 From->removeUser(operandNum, U);
4428 To.getNode()->addUser(operandNum, U);
4431 // Now that we have modified U, add it back to the CSE maps. If it already
4432 // exists there, recursively merge the results together.
4433 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4434 ReplaceAllUsesWith(U, Existing, UpdateListener);
4435 // U is now dead. Inform the listener if it exists and delete it.
4437 UpdateListener->NodeDeleted(U, Existing);
4438 DeleteNodeNotInCSEMaps(U);
4440 // If the node doesn't already exist, we updated it. Inform a listener if
4443 UpdateListener->NodeUpdated(U);
4448 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4449 /// This can cause recursive merging of nodes in the DAG.
4451 /// This version assumes From/To have matching types and numbers of result
4454 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4455 DAGUpdateListener *UpdateListener) {
4456 assert(From->getVTList().VTs == To->getVTList().VTs &&
4457 From->getNumValues() == To->getNumValues() &&
4458 "Cannot use this version of ReplaceAllUsesWith!");
4460 // Handle the trivial case.
4464 // Iterate over just the existing users of From. See the comments in
4465 // the ReplaceAllUsesWith above.
4466 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4469 do ++UI; while (UI != UE && *UI == U);
4471 // This node is about to morph, remove its old self from the CSE maps.
4472 RemoveNodeFromCSEMaps(U);
4474 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4475 I != E; ++I, ++operandNum)
4476 if (I->getVal() == From) {
4477 From->removeUser(operandNum, U);
4478 I->getSDValue().setNode(To);
4479 To->addUser(operandNum, U);
4482 // Now that we have modified U, add it back to the CSE maps. If it already
4483 // exists there, recursively merge the results together.
4484 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4485 ReplaceAllUsesWith(U, Existing, UpdateListener);
4486 // U is now dead. Inform the listener if it exists and delete it.
4488 UpdateListener->NodeDeleted(U, Existing);
4489 DeleteNodeNotInCSEMaps(U);
4491 // If the node doesn't already exist, we updated it. Inform a listener if
4494 UpdateListener->NodeUpdated(U);
4499 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4500 /// This can cause recursive merging of nodes in the DAG.
4502 /// This version can replace From with any result values. To must match the
4503 /// number and types of values returned by From.
4504 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4506 DAGUpdateListener *UpdateListener) {
4507 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4508 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4510 // Iterate over just the existing users of From. See the comments in
4511 // the ReplaceAllUsesWith above.
4512 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4515 do ++UI; while (UI != UE && *UI == U);
4517 // This node is about to morph, remove its old self from the CSE maps.
4518 RemoveNodeFromCSEMaps(U);
4520 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4521 I != E; ++I, ++operandNum)
4522 if (I->getVal() == From) {
4523 const SDValue &ToOp = To[I->getSDValue().getResNo()];
4524 From->removeUser(operandNum, U);
4527 ToOp.getNode()->addUser(operandNum, U);
4530 // Now that we have modified U, add it back to the CSE maps. If it already
4531 // exists there, recursively merge the results together.
4532 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4533 ReplaceAllUsesWith(U, Existing, UpdateListener);
4534 // U is now dead. Inform the listener if it exists and delete it.
4536 UpdateListener->NodeDeleted(U, Existing);
4537 DeleteNodeNotInCSEMaps(U);
4539 // If the node doesn't already exist, we updated it. Inform a listener if
4542 UpdateListener->NodeUpdated(U);
4547 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4548 /// uses of other values produced by From.getVal() alone. The Deleted vector is
4549 /// handled the same way as for ReplaceAllUsesWith.
4550 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4551 DAGUpdateListener *UpdateListener){
4552 // Handle the really simple, really trivial case efficiently.
4553 if (From == To) return;
4555 // Handle the simple, trivial, case efficiently.
4556 if (From.getNode()->getNumValues() == 1) {
4557 ReplaceAllUsesWith(From, To, UpdateListener);
4561 // Get all of the users of From.getNode(). We want these in a nice,
4562 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4563 SmallSetVector<SDNode*, 16> Users(From.getNode()->use_begin(), From.getNode()->use_end());
4565 while (!Users.empty()) {
4566 // We know that this user uses some value of From. If it is the right
4567 // value, update it.
4568 SDNode *User = Users.back();
4571 // Scan for an operand that matches From.
4572 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4573 for (; Op != E; ++Op)
4574 if (*Op == From) break;
4576 // If there are no matches, the user must use some other result of From.
4577 if (Op == E) continue;
4579 // Okay, we know this user needs to be updated. Remove its old self
4580 // from the CSE maps.
4581 RemoveNodeFromCSEMaps(User);
4583 // Update all operands that match "From" in case there are multiple uses.
4584 for (; Op != E; ++Op) {
4586 From.getNode()->removeUser(Op-User->op_begin(), User);
4589 To.getNode()->addUser(Op-User->op_begin(), User);
4593 // Now that we have modified User, add it back to the CSE maps. If it
4594 // already exists there, recursively merge the results together.
4595 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4597 if (UpdateListener) UpdateListener->NodeUpdated(User);
4598 continue; // Continue on to next user.
4601 // If there was already an existing matching node, use ReplaceAllUsesWith
4602 // to replace the dead one with the existing one. This can cause
4603 // recursive merging of other unrelated nodes down the line.
4604 ReplaceAllUsesWith(User, Existing, UpdateListener);
4606 // User is now dead. Notify a listener if present.
4607 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4608 DeleteNodeNotInCSEMaps(User);
4612 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
4613 /// uses of other values produced by From.getVal() alone. The same value may
4614 /// appear in both the From and To list. The Deleted vector is
4615 /// handled the same way as for ReplaceAllUsesWith.
4616 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
4619 DAGUpdateListener *UpdateListener){
4620 // Handle the simple, trivial case efficiently.
4622 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
4624 SmallVector<std::pair<SDNode *, unsigned>, 16> Users;
4625 for (unsigned i = 0; i != Num; ++i)
4626 for (SDNode::use_iterator UI = From[i].getNode()->use_begin(),
4627 E = From[i].getNode()->use_end(); UI != E; ++UI)
4628 Users.push_back(std::make_pair(*UI, i));
4630 while (!Users.empty()) {
4631 // We know that this user uses some value of From. If it is the right
4632 // value, update it.
4633 SDNode *User = Users.back().first;
4634 unsigned i = Users.back().second;
4637 // Scan for an operand that matches From.
4638 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4639 for (; Op != E; ++Op)
4640 if (*Op == From[i]) break;
4642 // If there are no matches, the user must use some other result of From.
4643 if (Op == E) continue;
4645 // Okay, we know this user needs to be updated. Remove its old self
4646 // from the CSE maps.
4647 RemoveNodeFromCSEMaps(User);
4649 // Update all operands that match "From" in case there are multiple uses.
4650 for (; Op != E; ++Op) {
4651 if (*Op == From[i]) {
4652 From[i].getNode()->removeUser(Op-User->op_begin(), User);
4655 To[i].getNode()->addUser(Op-User->op_begin(), User);
4659 // Now that we have modified User, add it back to the CSE maps. If it
4660 // already exists there, recursively merge the results together.
4661 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4663 if (UpdateListener) UpdateListener->NodeUpdated(User);
4664 continue; // Continue on to next user.
4667 // If there was already an existing matching node, use ReplaceAllUsesWith
4668 // to replace the dead one with the existing one. This can cause
4669 // recursive merging of other unrelated nodes down the line.
4670 ReplaceAllUsesWith(User, Existing, UpdateListener);
4672 // User is now dead. Notify a listener if present.
4673 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4674 DeleteNodeNotInCSEMaps(User);
4678 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4679 /// based on their topological order. It returns the maximum id and a vector
4680 /// of the SDNodes* in assigned order by reference.
4681 unsigned SelectionDAG::AssignTopologicalOrder() {
4683 unsigned DAGSize = 0;
4685 // SortedPos tracks the progress of the algorithm. Nodes before it are
4686 // sorted, nodes after it are unsorted. When the algorithm completes
4687 // it is at the end of the list.
4688 allnodes_iterator SortedPos = allnodes_begin();
4690 // Visit all the nodes. Move nodes with no operands to the front of
4691 // the list immediately. Annotate nodes that do have operands with their
4692 // operand count. Before we do this, the Node Id fields of the nodes
4693 // may contain arbitrary values. After, the Node Id fields for nodes
4694 // before SortedPos will contain the topological sort index, and the
4695 // Node Id fields for nodes At SortedPos and after will contain the
4696 // count of outstanding operands.
4697 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
4699 unsigned Degree = N->getNumOperands();
4701 // A node with no uses, add it to the result array immediately.
4702 N->setNodeId(DAGSize++);
4703 allnodes_iterator Q = N;
4705 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
4708 // Temporarily use the Node Id as scratch space for the degree count.
4709 N->setNodeId(Degree);
4713 // Visit all the nodes. As we iterate, moves nodes into sorted order,
4714 // such that by the time the end is reached all nodes will be sorted.
4715 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
4717 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4720 unsigned Degree = P->getNodeId();
4723 // All of P's operands are sorted, so P may sorted now.
4724 P->setNodeId(DAGSize++);
4726 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
4729 // Update P's outstanding operand count.
4730 P->setNodeId(Degree);
4735 assert(SortedPos == AllNodes.end() &&
4736 "Topological sort incomplete!");
4737 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
4738 "First node in topological sort is not the entry token!");
4739 assert(AllNodes.front().getNodeId() == 0 &&
4740 "First node in topological sort has non-zero id!");
4741 assert(AllNodes.front().getNumOperands() == 0 &&
4742 "First node in topological sort has operands!");
4743 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
4744 "Last node in topologic sort has unexpected id!");
4745 assert(AllNodes.back().use_empty() &&
4746 "Last node in topologic sort has users!");
4747 assert(DAGSize == allnodes_size() && "Node count mismatch!");
4753 //===----------------------------------------------------------------------===//
4755 //===----------------------------------------------------------------------===//
4757 HandleSDNode::~HandleSDNode() {
4761 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4763 : SDNode(isa<GlobalVariable>(GA) &&
4764 cast<GlobalVariable>(GA)->isThreadLocal() ?
4766 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4768 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4769 getSDVTList(VT)), Offset(o) {
4770 TheGlobal = const_cast<GlobalValue*>(GA);
4773 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
4774 const Value *srcValue, int SVO,
4775 unsigned alignment, bool vol)
4776 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
4777 Flags(encodeMemSDNodeFlags(vol, alignment)) {
4779 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4780 assert(getAlignment() == alignment && "Alignment representation error!");
4781 assert(isVolatile() == vol && "Volatile representation error!");
4784 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, const SDValue *Ops,
4785 unsigned NumOps, MVT memvt, const Value *srcValue,
4786 int SVO, unsigned alignment, bool vol)
4787 : SDNode(Opc, VTs, Ops, NumOps),
4788 MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
4789 Flags(vol | ((Log2_32(alignment) + 1) << 1)) {
4790 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4791 assert(getAlignment() == alignment && "Alignment representation error!");
4792 assert(isVolatile() == vol && "Volatile representation error!");
4795 /// getMemOperand - Return a MachineMemOperand object describing the memory
4796 /// reference performed by this memory reference.
4797 MachineMemOperand MemSDNode::getMemOperand() const {
4799 if (isa<LoadSDNode>(this))
4800 Flags = MachineMemOperand::MOLoad;
4801 else if (isa<StoreSDNode>(this))
4802 Flags = MachineMemOperand::MOStore;
4803 else if (isa<AtomicSDNode>(this)) {
4804 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4807 const MemIntrinsicSDNode* MemIntrinNode = dyn_cast<MemIntrinsicSDNode>(this);
4808 assert(MemIntrinNode && "Unknown MemSDNode opcode!");
4809 if (MemIntrinNode->readMem()) Flags |= MachineMemOperand::MOLoad;
4810 if (MemIntrinNode->writeMem()) Flags |= MachineMemOperand::MOStore;
4813 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4814 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4816 // Check if the memory reference references a frame index
4817 const FrameIndexSDNode *FI =
4818 dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
4819 if (!getSrcValue() && FI)
4820 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
4821 Flags, 0, Size, getAlignment());
4823 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4824 Size, getAlignment());
4827 /// Profile - Gather unique data for the node.
4829 void SDNode::Profile(FoldingSetNodeID &ID) const {
4830 AddNodeIDNode(ID, this);
4833 /// getValueTypeList - Return a pointer to the specified value type.
4835 const MVT *SDNode::getValueTypeList(MVT VT) {
4836 if (VT.isExtended()) {
4837 static std::set<MVT, MVT::compareRawBits> EVTs;
4838 return &(*EVTs.insert(VT).first);
4840 static MVT VTs[MVT::LAST_VALUETYPE];
4841 VTs[VT.getSimpleVT()] = VT;
4842 return &VTs[VT.getSimpleVT()];
4846 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4847 /// indicated value. This method ignores uses of other values defined by this
4849 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4850 assert(Value < getNumValues() && "Bad value!");
4852 // TODO: Only iterate over uses of a given value of the node
4853 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4854 if (UI.getUse().getSDValue().getResNo() == Value) {
4861 // Found exactly the right number of uses?
4866 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4867 /// value. This method ignores uses of other values defined by this operation.
4868 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4869 assert(Value < getNumValues() && "Bad value!");
4871 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
4872 if (UI.getUse().getSDValue().getResNo() == Value)
4879 /// isOnlyUserOf - Return true if this node is the only use of N.
4881 bool SDNode::isOnlyUserOf(SDNode *N) const {
4883 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4894 /// isOperand - Return true if this node is an operand of N.
4896 bool SDValue::isOperandOf(SDNode *N) const {
4897 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4898 if (*this == N->getOperand(i))
4903 bool SDNode::isOperandOf(SDNode *N) const {
4904 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4905 if (this == N->OperandList[i].getVal())
4910 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4911 /// be a chain) reaches the specified operand without crossing any
4912 /// side-effecting instructions. In practice, this looks through token
4913 /// factors and non-volatile loads. In order to remain efficient, this only
4914 /// looks a couple of nodes in, it does not do an exhaustive search.
4915 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
4916 unsigned Depth) const {
4917 if (*this == Dest) return true;
4919 // Don't search too deeply, we just want to be able to see through
4920 // TokenFactor's etc.
4921 if (Depth == 0) return false;
4923 // If this is a token factor, all inputs to the TF happen in parallel. If any
4924 // of the operands of the TF reach dest, then we can do the xform.
4925 if (getOpcode() == ISD::TokenFactor) {
4926 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4927 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4932 // Loads don't have side effects, look through them.
4933 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4934 if (!Ld->isVolatile())
4935 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4941 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4942 SmallPtrSet<SDNode *, 32> &Visited) {
4943 if (found || !Visited.insert(N))
4946 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4947 SDNode *Op = N->getOperand(i).getNode();
4952 findPredecessor(Op, P, found, Visited);
4956 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4957 /// is either an operand of N or it can be reached by recursively traversing
4958 /// up the operands.
4959 /// NOTE: this is an expensive method. Use it carefully.
4960 bool SDNode::isPredecessorOf(SDNode *N) const {
4961 SmallPtrSet<SDNode *, 32> Visited;
4963 findPredecessor(N, this, found, Visited);
4967 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4968 assert(Num < NumOperands && "Invalid child # of SDNode!");
4969 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
4972 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4973 switch (getOpcode()) {
4975 if (getOpcode() < ISD::BUILTIN_OP_END)
4976 return "<<Unknown DAG Node>>";
4977 if (isMachineOpcode()) {
4979 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4980 if (getMachineOpcode() < TII->getNumOpcodes())
4981 return TII->get(getMachineOpcode()).getName();
4982 return "<<Unknown Machine Node>>";
4985 const TargetLowering &TLI = G->getTargetLoweringInfo();
4986 const char *Name = TLI.getTargetNodeName(getOpcode());
4987 if (Name) return Name;
4988 return "<<Unknown Target Node>>";
4990 return "<<Unknown Node>>";
4993 case ISD::DELETED_NODE:
4994 return "<<Deleted Node!>>";
4996 case ISD::PREFETCH: return "Prefetch";
4997 case ISD::MEMBARRIER: return "MemBarrier";
4998 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4999 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5000 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5001 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5002 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5003 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5004 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5005 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5006 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5007 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5008 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5009 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5010 case ISD::PCMARKER: return "PCMarker";
5011 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5012 case ISD::SRCVALUE: return "SrcValue";
5013 case ISD::MEMOPERAND: return "MemOperand";
5014 case ISD::EntryToken: return "EntryToken";
5015 case ISD::TokenFactor: return "TokenFactor";
5016 case ISD::AssertSext: return "AssertSext";
5017 case ISD::AssertZext: return "AssertZext";
5019 case ISD::BasicBlock: return "BasicBlock";
5020 case ISD::ARG_FLAGS: return "ArgFlags";
5021 case ISD::VALUETYPE: return "ValueType";
5022 case ISD::Register: return "Register";
5024 case ISD::Constant: return "Constant";
5025 case ISD::ConstantFP: return "ConstantFP";
5026 case ISD::GlobalAddress: return "GlobalAddress";
5027 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5028 case ISD::FrameIndex: return "FrameIndex";
5029 case ISD::JumpTable: return "JumpTable";
5030 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5031 case ISD::RETURNADDR: return "RETURNADDR";
5032 case ISD::FRAMEADDR: return "FRAMEADDR";
5033 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5034 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5035 case ISD::EHSELECTION: return "EHSELECTION";
5036 case ISD::EH_RETURN: return "EH_RETURN";
5037 case ISD::ConstantPool: return "ConstantPool";
5038 case ISD::ExternalSymbol: return "ExternalSymbol";
5039 case ISD::INTRINSIC_WO_CHAIN: {
5040 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
5041 return Intrinsic::getName((Intrinsic::ID)IID);
5043 case ISD::INTRINSIC_VOID:
5044 case ISD::INTRINSIC_W_CHAIN: {
5045 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
5046 return Intrinsic::getName((Intrinsic::ID)IID);
5049 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5050 case ISD::TargetConstant: return "TargetConstant";
5051 case ISD::TargetConstantFP:return "TargetConstantFP";
5052 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5053 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5054 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5055 case ISD::TargetJumpTable: return "TargetJumpTable";
5056 case ISD::TargetConstantPool: return "TargetConstantPool";
5057 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5059 case ISD::CopyToReg: return "CopyToReg";
5060 case ISD::CopyFromReg: return "CopyFromReg";
5061 case ISD::UNDEF: return "undef";
5062 case ISD::MERGE_VALUES: return "merge_values";
5063 case ISD::INLINEASM: return "inlineasm";
5064 case ISD::DBG_LABEL: return "dbg_label";
5065 case ISD::EH_LABEL: return "eh_label";
5066 case ISD::DECLARE: return "declare";
5067 case ISD::HANDLENODE: return "handlenode";
5068 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
5069 case ISD::CALL: return "call";
5072 case ISD::FABS: return "fabs";
5073 case ISD::FNEG: return "fneg";
5074 case ISD::FSQRT: return "fsqrt";
5075 case ISD::FSIN: return "fsin";
5076 case ISD::FCOS: return "fcos";
5077 case ISD::FPOWI: return "fpowi";
5078 case ISD::FPOW: return "fpow";
5079 case ISD::FTRUNC: return "ftrunc";
5080 case ISD::FFLOOR: return "ffloor";
5081 case ISD::FCEIL: return "fceil";
5082 case ISD::FRINT: return "frint";
5083 case ISD::FNEARBYINT: return "fnearbyint";
5086 case ISD::ADD: return "add";
5087 case ISD::SUB: return "sub";
5088 case ISD::MUL: return "mul";
5089 case ISD::MULHU: return "mulhu";
5090 case ISD::MULHS: return "mulhs";
5091 case ISD::SDIV: return "sdiv";
5092 case ISD::UDIV: return "udiv";
5093 case ISD::SREM: return "srem";
5094 case ISD::UREM: return "urem";
5095 case ISD::SMUL_LOHI: return "smul_lohi";
5096 case ISD::UMUL_LOHI: return "umul_lohi";
5097 case ISD::SDIVREM: return "sdivrem";
5098 case ISD::UDIVREM: return "udivrem";
5099 case ISD::AND: return "and";
5100 case ISD::OR: return "or";
5101 case ISD::XOR: return "xor";
5102 case ISD::SHL: return "shl";
5103 case ISD::SRA: return "sra";
5104 case ISD::SRL: return "srl";
5105 case ISD::ROTL: return "rotl";
5106 case ISD::ROTR: return "rotr";
5107 case ISD::FADD: return "fadd";
5108 case ISD::FSUB: return "fsub";
5109 case ISD::FMUL: return "fmul";
5110 case ISD::FDIV: return "fdiv";
5111 case ISD::FREM: return "frem";
5112 case ISD::FCOPYSIGN: return "fcopysign";
5113 case ISD::FGETSIGN: return "fgetsign";
5115 case ISD::SETCC: return "setcc";
5116 case ISD::VSETCC: return "vsetcc";
5117 case ISD::SELECT: return "select";
5118 case ISD::SELECT_CC: return "select_cc";
5119 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5120 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5121 case ISD::CONCAT_VECTORS: return "concat_vectors";
5122 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5123 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5124 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5125 case ISD::CARRY_FALSE: return "carry_false";
5126 case ISD::ADDC: return "addc";
5127 case ISD::ADDE: return "adde";
5128 case ISD::SADDO: return "saddo";
5129 case ISD::UADDO: return "uaddo";
5130 case ISD::SSUBO: return "ssubo";
5131 case ISD::USUBO: return "usubo";
5132 case ISD::SMULO: return "smulo";
5133 case ISD::UMULO: return "umulo";
5134 case ISD::SUBC: return "subc";
5135 case ISD::SUBE: return "sube";
5136 case ISD::SHL_PARTS: return "shl_parts";
5137 case ISD::SRA_PARTS: return "sra_parts";
5138 case ISD::SRL_PARTS: return "srl_parts";
5140 case ISD::EXTRACT_SUBREG: return "extract_subreg";
5141 case ISD::INSERT_SUBREG: return "insert_subreg";
5143 // Conversion operators.
5144 case ISD::SIGN_EXTEND: return "sign_extend";
5145 case ISD::ZERO_EXTEND: return "zero_extend";
5146 case ISD::ANY_EXTEND: return "any_extend";
5147 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5148 case ISD::TRUNCATE: return "truncate";
5149 case ISD::FP_ROUND: return "fp_round";
5150 case ISD::FLT_ROUNDS_: return "flt_rounds";
5151 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5152 case ISD::FP_EXTEND: return "fp_extend";
5154 case ISD::SINT_TO_FP: return "sint_to_fp";
5155 case ISD::UINT_TO_FP: return "uint_to_fp";
5156 case ISD::FP_TO_SINT: return "fp_to_sint";
5157 case ISD::FP_TO_UINT: return "fp_to_uint";
5158 case ISD::BIT_CONVERT: return "bit_convert";
5160 case ISD::CONVERT_RNDSAT: {
5161 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5162 default: assert(0 && "Unknown cvt code!");
5163 case ISD::CVT_FF: return "cvt_ff";
5164 case ISD::CVT_FS: return "cvt_fs";
5165 case ISD::CVT_FU: return "cvt_fu";
5166 case ISD::CVT_SF: return "cvt_sf";
5167 case ISD::CVT_UF: return "cvt_uf";
5168 case ISD::CVT_SS: return "cvt_ss";
5169 case ISD::CVT_SU: return "cvt_su";
5170 case ISD::CVT_US: return "cvt_us";
5171 case ISD::CVT_UU: return "cvt_uu";
5175 // Control flow instructions
5176 case ISD::BR: return "br";
5177 case ISD::BRIND: return "brind";
5178 case ISD::BR_JT: return "br_jt";
5179 case ISD::BRCOND: return "brcond";
5180 case ISD::BR_CC: return "br_cc";
5181 case ISD::RET: return "ret";
5182 case ISD::CALLSEQ_START: return "callseq_start";
5183 case ISD::CALLSEQ_END: return "callseq_end";
5186 case ISD::LOAD: return "load";
5187 case ISD::STORE: return "store";
5188 case ISD::VAARG: return "vaarg";
5189 case ISD::VACOPY: return "vacopy";
5190 case ISD::VAEND: return "vaend";
5191 case ISD::VASTART: return "vastart";
5192 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5193 case ISD::EXTRACT_ELEMENT: return "extract_element";
5194 case ISD::BUILD_PAIR: return "build_pair";
5195 case ISD::STACKSAVE: return "stacksave";
5196 case ISD::STACKRESTORE: return "stackrestore";
5197 case ISD::TRAP: return "trap";
5200 case ISD::BSWAP: return "bswap";
5201 case ISD::CTPOP: return "ctpop";
5202 case ISD::CTTZ: return "cttz";
5203 case ISD::CTLZ: return "ctlz";
5206 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
5207 case ISD::DEBUG_LOC: return "debug_loc";
5210 case ISD::TRAMPOLINE: return "trampoline";
5213 switch (cast<CondCodeSDNode>(this)->get()) {
5214 default: assert(0 && "Unknown setcc condition!");
5215 case ISD::SETOEQ: return "setoeq";
5216 case ISD::SETOGT: return "setogt";
5217 case ISD::SETOGE: return "setoge";
5218 case ISD::SETOLT: return "setolt";
5219 case ISD::SETOLE: return "setole";
5220 case ISD::SETONE: return "setone";
5222 case ISD::SETO: return "seto";
5223 case ISD::SETUO: return "setuo";
5224 case ISD::SETUEQ: return "setue";
5225 case ISD::SETUGT: return "setugt";
5226 case ISD::SETUGE: return "setuge";
5227 case ISD::SETULT: return "setult";
5228 case ISD::SETULE: return "setule";
5229 case ISD::SETUNE: return "setune";
5231 case ISD::SETEQ: return "seteq";
5232 case ISD::SETGT: return "setgt";
5233 case ISD::SETGE: return "setge";
5234 case ISD::SETLT: return "setlt";
5235 case ISD::SETLE: return "setle";
5236 case ISD::SETNE: return "setne";
5241 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5250 return "<post-inc>";
5252 return "<post-dec>";
5256 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5257 std::string S = "< ";
5271 if (getByValAlign())
5272 S += "byval-align:" + utostr(getByValAlign()) + " ";
5274 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5276 S += "byval-size:" + utostr(getByValSize()) + " ";
5280 void SDNode::dump() const { dump(0); }
5281 void SDNode::dump(const SelectionDAG *G) const {
5286 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5287 OS << (void*)this << ": ";
5289 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5291 if (getValueType(i) == MVT::Other)
5294 OS << getValueType(i).getMVTString();
5296 OS << " = " << getOperationName(G);
5299 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5301 OS << (void*)getOperand(i).getNode();
5302 if (unsigned RN = getOperand(i).getResNo())
5306 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
5307 SDNode *Mask = getOperand(2).getNode();
5309 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
5311 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
5314 OS << cast<ConstantSDNode>(Mask->getOperand(i))->getZExtValue();
5319 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5320 OS << '<' << CSDN->getAPIntValue() << '>';
5321 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5322 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5323 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5324 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5325 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5328 CSDN->getValueAPF().bitcastToAPInt().dump();
5331 } else if (const GlobalAddressSDNode *GADN =
5332 dyn_cast<GlobalAddressSDNode>(this)) {
5333 int64_t offset = GADN->getOffset();
5335 WriteAsOperand(OS, GADN->getGlobal());
5338 OS << " + " << offset;
5340 OS << " " << offset;
5341 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5342 OS << "<" << FIDN->getIndex() << ">";
5343 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5344 OS << "<" << JTDN->getIndex() << ">";
5345 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5346 int offset = CP->getOffset();
5347 if (CP->isMachineConstantPoolEntry())
5348 OS << "<" << *CP->getMachineCPVal() << ">";
5350 OS << "<" << *CP->getConstVal() << ">";
5352 OS << " + " << offset;
5354 OS << " " << offset;
5355 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5357 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5359 OS << LBB->getName() << " ";
5360 OS << (const void*)BBDN->getBasicBlock() << ">";
5361 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5362 if (G && R->getReg() &&
5363 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5364 OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5366 OS << " #" << R->getReg();
5368 } else if (const ExternalSymbolSDNode *ES =
5369 dyn_cast<ExternalSymbolSDNode>(this)) {
5370 OS << "'" << ES->getSymbol() << "'";
5371 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5373 OS << "<" << M->getValue() << ">";
5376 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5377 if (M->MO.getValue())
5378 OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5380 OS << "<null:" << M->MO.getOffset() << ">";
5381 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5382 OS << N->getArgFlags().getArgFlagsString();
5383 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5384 OS << ":" << N->getVT().getMVTString();
5386 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5387 const Value *SrcValue = LD->getSrcValue();
5388 int SrcOffset = LD->getSrcValueOffset();
5394 OS << ":" << SrcOffset << ">";
5397 switch (LD->getExtensionType()) {
5398 default: doExt = false; break;
5399 case ISD::EXTLOAD: OS << " <anyext "; break;
5400 case ISD::SEXTLOAD: OS << " <sext "; break;
5401 case ISD::ZEXTLOAD: OS << " <zext "; break;
5404 OS << LD->getMemoryVT().getMVTString() << ">";
5406 const char *AM = getIndexedModeName(LD->getAddressingMode());
5409 if (LD->isVolatile())
5410 OS << " <volatile>";
5411 OS << " alignment=" << LD->getAlignment();
5412 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5413 const Value *SrcValue = ST->getSrcValue();
5414 int SrcOffset = ST->getSrcValueOffset();
5420 OS << ":" << SrcOffset << ">";
5422 if (ST->isTruncatingStore())
5423 OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
5425 const char *AM = getIndexedModeName(ST->getAddressingMode());
5428 if (ST->isVolatile())
5429 OS << " <volatile>";
5430 OS << " alignment=" << ST->getAlignment();
5431 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5432 const Value *SrcValue = AT->getSrcValue();
5433 int SrcOffset = AT->getSrcValueOffset();
5439 OS << ":" << SrcOffset << ">";
5440 if (AT->isVolatile())
5441 OS << " <volatile>";
5442 OS << " alignment=" << AT->getAlignment();
5446 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5447 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5448 if (N->getOperand(i).getNode()->hasOneUse())
5449 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5451 cerr << "\n" << std::string(indent+2, ' ')
5452 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5455 cerr << "\n" << std::string(indent, ' ');
5459 void SelectionDAG::dump() const {
5460 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5462 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5464 const SDNode *N = I;
5465 if (!N->hasOneUse() && N != getRoot().getNode())
5466 DumpNodes(N, 2, this);
5469 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
5474 const Type *ConstantPoolSDNode::getType() const {
5475 if (isMachineConstantPoolEntry())
5476 return Val.MachineCPVal->getType();
5477 return Val.ConstVal->getType();