1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "SDNodeOrdering.h"
16 #include "SDNodeDbgValue.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 #include "llvm/Function.h"
20 #include "llvm/GlobalAlias.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Assembly/Writer.h"
25 #include "llvm/CallingConv.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/PseudoSourceValue.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetFrameInfo.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetIntrinsicInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/ManagedStatic.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/System/Mutex.h"
46 #include "llvm/ADT/SetVector.h"
47 #include "llvm/ADT/SmallPtrSet.h"
48 #include "llvm/ADT/SmallSet.h"
49 #include "llvm/ADT/SmallVector.h"
50 #include "llvm/ADT/StringExtras.h"
55 /// makeVTList - Return an instance of the SDVTList struct initialized with the
56 /// specified members.
57 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
58 SDVTList Res = {VTs, NumVTs};
62 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
63 switch (VT.getSimpleVT().SimpleTy) {
64 default: llvm_unreachable("Unknown FP format");
65 case MVT::f32: return &APFloat::IEEEsingle;
66 case MVT::f64: return &APFloat::IEEEdouble;
67 case MVT::f80: return &APFloat::x87DoubleExtended;
68 case MVT::f128: return &APFloat::IEEEquad;
69 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
73 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
75 //===----------------------------------------------------------------------===//
76 // ConstantFPSDNode Class
77 //===----------------------------------------------------------------------===//
79 /// isExactlyValue - We don't rely on operator== working on double values, as
80 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
81 /// As such, this method can be used to do an exact bit-for-bit comparison of
82 /// two floating point values.
83 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
84 return getValueAPF().bitwiseIsEqual(V);
87 bool ConstantFPSDNode::isValueValidForType(EVT VT,
89 assert(VT.isFloatingPoint() && "Can only convert between FP types");
91 // PPC long double cannot be converted to any other type.
92 if (VT == MVT::ppcf128 ||
93 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
96 // convert modifies in place, so make a copy.
97 APFloat Val2 = APFloat(Val);
99 (void) Val2.convert(*EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
104 //===----------------------------------------------------------------------===//
106 //===----------------------------------------------------------------------===//
108 /// isBuildVectorAllOnes - Return true if the specified node is a
109 /// BUILD_VECTOR where all of the elements are ~0 or undef.
110 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
111 // Look through a bit convert.
112 if (N->getOpcode() == ISD::BIT_CONVERT)
113 N = N->getOperand(0).getNode();
115 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
117 unsigned i = 0, e = N->getNumOperands();
119 // Skip over all of the undef values.
120 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
123 // Do not accept an all-undef vector.
124 if (i == e) return false;
126 // Do not accept build_vectors that aren't all constants or which have non-~0
128 SDValue NotZero = N->getOperand(i);
129 if (isa<ConstantSDNode>(NotZero)) {
130 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
132 } else if (isa<ConstantFPSDNode>(NotZero)) {
133 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
134 bitcastToAPInt().isAllOnesValue())
139 // Okay, we have at least one ~0 value, check to see if the rest match or are
141 for (++i; i != e; ++i)
142 if (N->getOperand(i) != NotZero &&
143 N->getOperand(i).getOpcode() != ISD::UNDEF)
149 /// isBuildVectorAllZeros - Return true if the specified node is a
150 /// BUILD_VECTOR where all of the elements are 0 or undef.
151 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
152 // Look through a bit convert.
153 if (N->getOpcode() == ISD::BIT_CONVERT)
154 N = N->getOperand(0).getNode();
156 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
158 unsigned i = 0, e = N->getNumOperands();
160 // Skip over all of the undef values.
161 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
164 // Do not accept an all-undef vector.
165 if (i == e) return false;
167 // Do not accept build_vectors that aren't all constants or which have non-0
169 SDValue Zero = N->getOperand(i);
170 if (isa<ConstantSDNode>(Zero)) {
171 if (!cast<ConstantSDNode>(Zero)->isNullValue())
173 } else if (isa<ConstantFPSDNode>(Zero)) {
174 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
179 // Okay, we have at least one 0 value, check to see if the rest match or are
181 for (++i; i != e; ++i)
182 if (N->getOperand(i) != Zero &&
183 N->getOperand(i).getOpcode() != ISD::UNDEF)
188 /// isScalarToVector - Return true if the specified node is a
189 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
190 /// element is not an undef.
191 bool ISD::isScalarToVector(const SDNode *N) {
192 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
195 if (N->getOpcode() != ISD::BUILD_VECTOR)
197 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
199 unsigned NumElems = N->getNumOperands();
200 for (unsigned i = 1; i < NumElems; ++i) {
201 SDValue V = N->getOperand(i);
202 if (V.getOpcode() != ISD::UNDEF)
208 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
209 /// when given the operation for (X op Y).
210 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
211 // To perform this operation, we just need to swap the L and G bits of the
213 unsigned OldL = (Operation >> 2) & 1;
214 unsigned OldG = (Operation >> 1) & 1;
215 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
216 (OldL << 1) | // New G bit
217 (OldG << 2)); // New L bit.
220 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
221 /// 'op' is a valid SetCC operation.
222 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
223 unsigned Operation = Op;
225 Operation ^= 7; // Flip L, G, E bits, but not U.
227 Operation ^= 15; // Flip all of the condition bits.
229 if (Operation > ISD::SETTRUE2)
230 Operation &= ~8; // Don't let N and U bits get set.
232 return ISD::CondCode(Operation);
236 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
237 /// signed operation and 2 if the result is an unsigned comparison. Return zero
238 /// if the operation does not depend on the sign of the input (setne and seteq).
239 static int isSignedOp(ISD::CondCode Opcode) {
241 default: llvm_unreachable("Illegal integer setcc operation!");
243 case ISD::SETNE: return 0;
247 case ISD::SETGE: return 1;
251 case ISD::SETUGE: return 2;
255 /// getSetCCOrOperation - Return the result of a logical OR between different
256 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
257 /// returns SETCC_INVALID if it is not possible to represent the resultant
259 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
261 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
262 // Cannot fold a signed integer setcc with an unsigned integer setcc.
263 return ISD::SETCC_INVALID;
265 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
267 // If the N and U bits get set then the resultant comparison DOES suddenly
268 // care about orderedness, and is true when ordered.
269 if (Op > ISD::SETTRUE2)
270 Op &= ~16; // Clear the U bit if the N bit is set.
272 // Canonicalize illegal integer setcc's.
273 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
276 return ISD::CondCode(Op);
279 /// getSetCCAndOperation - Return the result of a logical AND between different
280 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
281 /// function returns zero if it is not possible to represent the resultant
283 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
285 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
286 // Cannot fold a signed setcc with an unsigned setcc.
287 return ISD::SETCC_INVALID;
289 // Combine all of the condition bits.
290 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
292 // Canonicalize illegal integer setcc's.
296 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
297 case ISD::SETOEQ: // SETEQ & SETU[LG]E
298 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
299 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
300 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
307 const TargetMachine &SelectionDAG::getTarget() const {
308 return MF->getTarget();
311 //===----------------------------------------------------------------------===//
312 // SDNode Profile Support
313 //===----------------------------------------------------------------------===//
315 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
317 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
321 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
322 /// solely with their pointer.
323 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
324 ID.AddPointer(VTList.VTs);
327 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
329 static void AddNodeIDOperands(FoldingSetNodeID &ID,
330 const SDValue *Ops, unsigned NumOps) {
331 for (; NumOps; --NumOps, ++Ops) {
332 ID.AddPointer(Ops->getNode());
333 ID.AddInteger(Ops->getResNo());
337 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
339 static void AddNodeIDOperands(FoldingSetNodeID &ID,
340 const SDUse *Ops, unsigned NumOps) {
341 for (; NumOps; --NumOps, ++Ops) {
342 ID.AddPointer(Ops->getNode());
343 ID.AddInteger(Ops->getResNo());
347 static void AddNodeIDNode(FoldingSetNodeID &ID,
348 unsigned short OpC, SDVTList VTList,
349 const SDValue *OpList, unsigned N) {
350 AddNodeIDOpcode(ID, OpC);
351 AddNodeIDValueTypes(ID, VTList);
352 AddNodeIDOperands(ID, OpList, N);
355 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
357 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
358 switch (N->getOpcode()) {
359 case ISD::TargetExternalSymbol:
360 case ISD::ExternalSymbol:
361 llvm_unreachable("Should only be used on nodes with operands");
362 default: break; // Normal nodes don't need extra info.
363 case ISD::TargetConstant:
365 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
367 case ISD::TargetConstantFP:
368 case ISD::ConstantFP: {
369 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
372 case ISD::TargetGlobalAddress:
373 case ISD::GlobalAddress:
374 case ISD::TargetGlobalTLSAddress:
375 case ISD::GlobalTLSAddress: {
376 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
377 ID.AddPointer(GA->getGlobal());
378 ID.AddInteger(GA->getOffset());
379 ID.AddInteger(GA->getTargetFlags());
382 case ISD::BasicBlock:
383 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
386 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
390 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
392 case ISD::FrameIndex:
393 case ISD::TargetFrameIndex:
394 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
397 case ISD::TargetJumpTable:
398 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
399 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
401 case ISD::ConstantPool:
402 case ISD::TargetConstantPool: {
403 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
404 ID.AddInteger(CP->getAlignment());
405 ID.AddInteger(CP->getOffset());
406 if (CP->isMachineConstantPoolEntry())
407 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
409 ID.AddPointer(CP->getConstVal());
410 ID.AddInteger(CP->getTargetFlags());
414 const LoadSDNode *LD = cast<LoadSDNode>(N);
415 ID.AddInteger(LD->getMemoryVT().getRawBits());
416 ID.AddInteger(LD->getRawSubclassData());
420 const StoreSDNode *ST = cast<StoreSDNode>(N);
421 ID.AddInteger(ST->getMemoryVT().getRawBits());
422 ID.AddInteger(ST->getRawSubclassData());
425 case ISD::ATOMIC_CMP_SWAP:
426 case ISD::ATOMIC_SWAP:
427 case ISD::ATOMIC_LOAD_ADD:
428 case ISD::ATOMIC_LOAD_SUB:
429 case ISD::ATOMIC_LOAD_AND:
430 case ISD::ATOMIC_LOAD_OR:
431 case ISD::ATOMIC_LOAD_XOR:
432 case ISD::ATOMIC_LOAD_NAND:
433 case ISD::ATOMIC_LOAD_MIN:
434 case ISD::ATOMIC_LOAD_MAX:
435 case ISD::ATOMIC_LOAD_UMIN:
436 case ISD::ATOMIC_LOAD_UMAX: {
437 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
438 ID.AddInteger(AT->getMemoryVT().getRawBits());
439 ID.AddInteger(AT->getRawSubclassData());
442 case ISD::VECTOR_SHUFFLE: {
443 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
444 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
446 ID.AddInteger(SVN->getMaskElt(i));
449 case ISD::TargetBlockAddress:
450 case ISD::BlockAddress: {
451 ID.AddPointer(cast<BlockAddressSDNode>(N)->getBlockAddress());
452 ID.AddInteger(cast<BlockAddressSDNode>(N)->getTargetFlags());
455 } // end switch (N->getOpcode())
458 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
460 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
461 AddNodeIDOpcode(ID, N->getOpcode());
462 // Add the return value info.
463 AddNodeIDValueTypes(ID, N->getVTList());
464 // Add the operand info.
465 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
467 // Handle SDNode leafs with special info.
468 AddNodeIDCustom(ID, N);
471 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
472 /// the CSE map that carries volatility, temporalness, indexing mode, and
473 /// extension/truncation information.
475 static inline unsigned
476 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile,
477 bool isNonTemporal) {
478 assert((ConvType & 3) == ConvType &&
479 "ConvType may not require more than 2 bits!");
480 assert((AM & 7) == AM &&
481 "AM may not require more than 3 bits!");
485 (isNonTemporal << 6);
488 //===----------------------------------------------------------------------===//
489 // SelectionDAG Class
490 //===----------------------------------------------------------------------===//
492 /// doNotCSE - Return true if CSE should not be performed for this node.
493 static bool doNotCSE(SDNode *N) {
494 if (N->getValueType(0) == MVT::Flag)
495 return true; // Never CSE anything that produces a flag.
497 switch (N->getOpcode()) {
499 case ISD::HANDLENODE:
501 return true; // Never CSE these nodes.
504 // Check that remaining values produced are not flags.
505 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
506 if (N->getValueType(i) == MVT::Flag)
507 return true; // Never CSE anything that produces a flag.
512 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
514 void SelectionDAG::RemoveDeadNodes() {
515 // Create a dummy node (which is not added to allnodes), that adds a reference
516 // to the root node, preventing it from being deleted.
517 HandleSDNode Dummy(getRoot());
519 SmallVector<SDNode*, 128> DeadNodes;
521 // Add all obviously-dead nodes to the DeadNodes worklist.
522 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
524 DeadNodes.push_back(I);
526 RemoveDeadNodes(DeadNodes);
528 // If the root changed (e.g. it was a dead load, update the root).
529 setRoot(Dummy.getValue());
532 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
533 /// given list, and any nodes that become unreachable as a result.
534 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
535 DAGUpdateListener *UpdateListener) {
537 // Process the worklist, deleting the nodes and adding their uses to the
539 while (!DeadNodes.empty()) {
540 SDNode *N = DeadNodes.pop_back_val();
543 UpdateListener->NodeDeleted(N, 0);
545 // Take the node out of the appropriate CSE map.
546 RemoveNodeFromCSEMaps(N);
548 // Next, brutally remove the operand list. This is safe to do, as there are
549 // no cycles in the graph.
550 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
552 SDNode *Operand = Use.getNode();
555 // Now that we removed this operand, see if there are no uses of it left.
556 if (Operand->use_empty())
557 DeadNodes.push_back(Operand);
564 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
565 SmallVector<SDNode*, 16> DeadNodes(1, N);
566 RemoveDeadNodes(DeadNodes, UpdateListener);
569 void SelectionDAG::DeleteNode(SDNode *N) {
570 // First take this out of the appropriate CSE map.
571 RemoveNodeFromCSEMaps(N);
573 // Finally, remove uses due to operands of this node, remove from the
574 // AllNodes list, and delete the node.
575 DeleteNodeNotInCSEMaps(N);
578 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
579 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
580 assert(N->use_empty() && "Cannot delete a node that is not dead!");
582 // Drop all of the operands and decrement used node's use counts.
588 void SelectionDAG::DeallocateNode(SDNode *N) {
589 if (N->OperandsNeedDelete)
590 delete[] N->OperandList;
592 // Set the opcode to DELETED_NODE to help catch bugs when node
593 // memory is reallocated.
594 N->NodeType = ISD::DELETED_NODE;
596 NodeAllocator.Deallocate(AllNodes.remove(N));
598 // Remove the ordering of this node.
601 // And its entry in the debug info table, if any.
605 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
606 /// correspond to it. This is useful when we're about to delete or repurpose
607 /// the node. We don't want future request for structurally identical nodes
608 /// to return N anymore.
609 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
611 switch (N->getOpcode()) {
612 case ISD::EntryToken:
613 llvm_unreachable("EntryToken should not be in CSEMaps!");
615 case ISD::HANDLENODE: return false; // noop.
617 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
618 "Cond code doesn't exist!");
619 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
620 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
622 case ISD::ExternalSymbol:
623 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
625 case ISD::TargetExternalSymbol: {
626 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
627 Erased = TargetExternalSymbols.erase(
628 std::pair<std::string,unsigned char>(ESN->getSymbol(),
629 ESN->getTargetFlags()));
632 case ISD::VALUETYPE: {
633 EVT VT = cast<VTSDNode>(N)->getVT();
634 if (VT.isExtended()) {
635 Erased = ExtendedValueTypeNodes.erase(VT);
637 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
638 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
643 // Remove it from the CSE Map.
644 Erased = CSEMap.RemoveNode(N);
648 // Verify that the node was actually in one of the CSE maps, unless it has a
649 // flag result (which cannot be CSE'd) or is one of the special cases that are
650 // not subject to CSE.
651 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
652 !N->isMachineOpcode() && !doNotCSE(N)) {
655 llvm_unreachable("Node is not in map!");
661 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
662 /// maps and modified in place. Add it back to the CSE maps, unless an identical
663 /// node already exists, in which case transfer all its users to the existing
664 /// node. This transfer can potentially trigger recursive merging.
667 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
668 DAGUpdateListener *UpdateListener) {
669 // For node types that aren't CSE'd, just act as if no identical node
672 SDNode *Existing = CSEMap.GetOrInsertNode(N);
674 // If there was already an existing matching node, use ReplaceAllUsesWith
675 // to replace the dead one with the existing one. This can cause
676 // recursive merging of other unrelated nodes down the line.
677 ReplaceAllUsesWith(N, Existing, UpdateListener);
679 // N is now dead. Inform the listener if it exists and delete it.
681 UpdateListener->NodeDeleted(N, Existing);
682 DeleteNodeNotInCSEMaps(N);
687 // If the node doesn't already exist, we updated it. Inform a listener if
690 UpdateListener->NodeUpdated(N);
693 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
694 /// were replaced with those specified. If this node is never memoized,
695 /// return null, otherwise return a pointer to the slot it would take. If a
696 /// node already exists with these operands, the slot will be non-null.
697 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
702 SDValue Ops[] = { Op };
704 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
705 AddNodeIDCustom(ID, N);
706 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
710 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
711 /// were replaced with those specified. If this node is never memoized,
712 /// return null, otherwise return a pointer to the slot it would take. If a
713 /// node already exists with these operands, the slot will be non-null.
714 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
715 SDValue Op1, SDValue Op2,
720 SDValue Ops[] = { Op1, Op2 };
722 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
723 AddNodeIDCustom(ID, N);
724 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
729 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
730 /// were replaced with those specified. If this node is never memoized,
731 /// return null, otherwise return a pointer to the slot it would take. If a
732 /// node already exists with these operands, the slot will be non-null.
733 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
734 const SDValue *Ops,unsigned NumOps,
740 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
741 AddNodeIDCustom(ID, N);
742 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
746 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
747 void SelectionDAG::VerifyNode(SDNode *N) {
748 switch (N->getOpcode()) {
751 case ISD::BUILD_PAIR: {
752 EVT VT = N->getValueType(0);
753 assert(N->getNumValues() == 1 && "Too many results!");
754 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
755 "Wrong return type!");
756 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
757 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
758 "Mismatched operand types!");
759 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
760 "Wrong operand type!");
761 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
762 "Wrong return type size");
765 case ISD::BUILD_VECTOR: {
766 assert(N->getNumValues() == 1 && "Too many results!");
767 assert(N->getValueType(0).isVector() && "Wrong return type!");
768 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
769 "Wrong number of operands!");
770 EVT EltVT = N->getValueType(0).getVectorElementType();
771 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
772 assert((I->getValueType() == EltVT ||
773 (EltVT.isInteger() && I->getValueType().isInteger() &&
774 EltVT.bitsLE(I->getValueType()))) &&
775 "Wrong operand type!");
781 /// getEVTAlignment - Compute the default alignment value for the
784 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
785 const Type *Ty = VT == MVT::iPTR ?
786 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
787 VT.getTypeForEVT(*getContext());
789 return TLI.getTargetData()->getABITypeAlignment(Ty);
792 // EntryNode could meaningfully have debug info if we can find it...
793 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
794 : TLI(tli), FLI(fli), DW(0),
795 EntryNode(ISD::EntryToken, DebugLoc::getUnknownLoc(),
796 getVTList(MVT::Other)),
797 Root(getEntryNode()), Ordering(0) {
798 AllNodes.push_back(&EntryNode);
799 Ordering = new SDNodeOrdering();
800 DbgInfo = new SDDbgInfo();
803 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
808 Context = &mf.getFunction()->getContext();
811 SelectionDAG::~SelectionDAG() {
817 void SelectionDAG::allnodes_clear() {
818 assert(&*AllNodes.begin() == &EntryNode);
819 AllNodes.remove(AllNodes.begin());
820 while (!AllNodes.empty())
821 DeallocateNode(AllNodes.begin());
824 void SelectionDAG::clear() {
826 OperandAllocator.Reset();
829 ExtendedValueTypeNodes.clear();
830 ExternalSymbols.clear();
831 TargetExternalSymbols.clear();
832 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
833 static_cast<CondCodeSDNode*>(0));
834 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
835 static_cast<SDNode*>(0));
837 EntryNode.UseList = 0;
838 AllNodes.push_back(&EntryNode);
839 Root = getEntryNode();
841 Ordering = new SDNodeOrdering();
843 DbgInfo = new SDDbgInfo();
846 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
847 return VT.bitsGT(Op.getValueType()) ?
848 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
849 getNode(ISD::TRUNCATE, DL, VT, Op);
852 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
853 return VT.bitsGT(Op.getValueType()) ?
854 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
855 getNode(ISD::TRUNCATE, DL, VT, Op);
858 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, EVT VT) {
859 assert(!VT.isVector() &&
860 "getZeroExtendInReg should use the vector element type instead of "
862 if (Op.getValueType() == VT) return Op;
863 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
864 APInt Imm = APInt::getLowBitsSet(BitWidth,
866 return getNode(ISD::AND, DL, Op.getValueType(), Op,
867 getConstant(Imm, Op.getValueType()));
870 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
872 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, EVT VT) {
873 EVT EltVT = VT.getScalarType();
875 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
876 return getNode(ISD::XOR, DL, VT, Val, NegOne);
879 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
880 EVT EltVT = VT.getScalarType();
881 assert((EltVT.getSizeInBits() >= 64 ||
882 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
883 "getConstant with a uint64_t value that doesn't fit in the type!");
884 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
887 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
888 return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
891 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
892 assert(VT.isInteger() && "Cannot create FP integer constant!");
894 EVT EltVT = VT.getScalarType();
895 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
896 "APInt size does not match type size!");
898 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
900 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
904 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
906 return SDValue(N, 0);
909 N = new (NodeAllocator) ConstantSDNode(isT, &Val, EltVT);
910 CSEMap.InsertNode(N, IP);
911 AllNodes.push_back(N);
914 SDValue Result(N, 0);
916 SmallVector<SDValue, 8> Ops;
917 Ops.assign(VT.getVectorNumElements(), Result);
918 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
919 VT, &Ops[0], Ops.size());
924 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
925 return getConstant(Val, TLI.getPointerTy(), isTarget);
929 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
930 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
933 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
934 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
936 EVT EltVT = VT.getScalarType();
938 // Do the map lookup using the actual bit pattern for the floating point
939 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
940 // we don't have issues with SNANs.
941 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
943 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
947 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
949 return SDValue(N, 0);
952 N = new (NodeAllocator) ConstantFPSDNode(isTarget, &V, EltVT);
953 CSEMap.InsertNode(N, IP);
954 AllNodes.push_back(N);
957 SDValue Result(N, 0);
959 SmallVector<SDValue, 8> Ops;
960 Ops.assign(VT.getVectorNumElements(), Result);
961 // FIXME DebugLoc info might be appropriate here
962 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
963 VT, &Ops[0], Ops.size());
968 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
969 EVT EltVT = VT.getScalarType();
971 return getConstantFP(APFloat((float)Val), VT, isTarget);
973 return getConstantFP(APFloat(Val), VT, isTarget);
976 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
977 EVT VT, int64_t Offset,
979 unsigned char TargetFlags) {
980 assert((TargetFlags == 0 || isTargetGA) &&
981 "Cannot set target flags on target-independent globals");
983 // Truncate (with sign-extension) the offset value to the pointer size.
984 EVT PTy = TLI.getPointerTy();
985 unsigned BitWidth = PTy.getSizeInBits();
987 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
989 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
991 // If GV is an alias then use the aliasee for determining thread-localness.
992 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
993 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
997 if (GVar && GVar->isThreadLocal())
998 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1000 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1002 FoldingSetNodeID ID;
1003 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1005 ID.AddInteger(Offset);
1006 ID.AddInteger(TargetFlags);
1008 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1009 return SDValue(E, 0);
1011 SDNode *N = new (NodeAllocator) GlobalAddressSDNode(Opc, GV, VT,
1012 Offset, TargetFlags);
1013 CSEMap.InsertNode(N, IP);
1014 AllNodes.push_back(N);
1015 return SDValue(N, 0);
1018 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1019 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1020 FoldingSetNodeID ID;
1021 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1024 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1025 return SDValue(E, 0);
1027 SDNode *N = new (NodeAllocator) FrameIndexSDNode(FI, VT, isTarget);
1028 CSEMap.InsertNode(N, IP);
1029 AllNodes.push_back(N);
1030 return SDValue(N, 0);
1033 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1034 unsigned char TargetFlags) {
1035 assert((TargetFlags == 0 || isTarget) &&
1036 "Cannot set target flags on target-independent jump tables");
1037 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1038 FoldingSetNodeID ID;
1039 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1041 ID.AddInteger(TargetFlags);
1043 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1044 return SDValue(E, 0);
1046 SDNode *N = new (NodeAllocator) JumpTableSDNode(JTI, VT, isTarget,
1048 CSEMap.InsertNode(N, IP);
1049 AllNodes.push_back(N);
1050 return SDValue(N, 0);
1053 SDValue SelectionDAG::getConstantPool(Constant *C, EVT VT,
1054 unsigned Alignment, int Offset,
1056 unsigned char TargetFlags) {
1057 assert((TargetFlags == 0 || isTarget) &&
1058 "Cannot set target flags on target-independent globals");
1060 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1061 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1062 FoldingSetNodeID ID;
1063 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1064 ID.AddInteger(Alignment);
1065 ID.AddInteger(Offset);
1067 ID.AddInteger(TargetFlags);
1069 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1070 return SDValue(E, 0);
1072 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1073 Alignment, TargetFlags);
1074 CSEMap.InsertNode(N, IP);
1075 AllNodes.push_back(N);
1076 return SDValue(N, 0);
1080 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1081 unsigned Alignment, int Offset,
1083 unsigned char TargetFlags) {
1084 assert((TargetFlags == 0 || isTarget) &&
1085 "Cannot set target flags on target-independent globals");
1087 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1088 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1089 FoldingSetNodeID ID;
1090 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1091 ID.AddInteger(Alignment);
1092 ID.AddInteger(Offset);
1093 C->AddSelectionDAGCSEId(ID);
1094 ID.AddInteger(TargetFlags);
1096 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1097 return SDValue(E, 0);
1099 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1100 Alignment, TargetFlags);
1101 CSEMap.InsertNode(N, IP);
1102 AllNodes.push_back(N);
1103 return SDValue(N, 0);
1106 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1107 FoldingSetNodeID ID;
1108 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1111 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1112 return SDValue(E, 0);
1114 SDNode *N = new (NodeAllocator) BasicBlockSDNode(MBB);
1115 CSEMap.InsertNode(N, IP);
1116 AllNodes.push_back(N);
1117 return SDValue(N, 0);
1120 SDValue SelectionDAG::getValueType(EVT VT) {
1121 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1122 ValueTypeNodes.size())
1123 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1125 SDNode *&N = VT.isExtended() ?
1126 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1128 if (N) return SDValue(N, 0);
1129 N = new (NodeAllocator) VTSDNode(VT);
1130 AllNodes.push_back(N);
1131 return SDValue(N, 0);
1134 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1135 SDNode *&N = ExternalSymbols[Sym];
1136 if (N) return SDValue(N, 0);
1137 N = new (NodeAllocator) ExternalSymbolSDNode(false, Sym, 0, VT);
1138 AllNodes.push_back(N);
1139 return SDValue(N, 0);
1142 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1143 unsigned char TargetFlags) {
1145 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1147 if (N) return SDValue(N, 0);
1148 N = new (NodeAllocator) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1149 AllNodes.push_back(N);
1150 return SDValue(N, 0);
1153 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1154 if ((unsigned)Cond >= CondCodeNodes.size())
1155 CondCodeNodes.resize(Cond+1);
1157 if (CondCodeNodes[Cond] == 0) {
1158 CondCodeSDNode *N = new (NodeAllocator) CondCodeSDNode(Cond);
1159 CondCodeNodes[Cond] = N;
1160 AllNodes.push_back(N);
1163 return SDValue(CondCodeNodes[Cond], 0);
1166 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1167 // the shuffle mask M that point at N1 to point at N2, and indices that point
1168 // N2 to point at N1.
1169 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1171 int NElts = M.size();
1172 for (int i = 0; i != NElts; ++i) {
1180 SDValue SelectionDAG::getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1,
1181 SDValue N2, const int *Mask) {
1182 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1183 assert(VT.isVector() && N1.getValueType().isVector() &&
1184 "Vector Shuffle VTs must be a vectors");
1185 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1186 && "Vector Shuffle VTs must have same element type");
1188 // Canonicalize shuffle undef, undef -> undef
1189 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1190 return getUNDEF(VT);
1192 // Validate that all indices in Mask are within the range of the elements
1193 // input to the shuffle.
1194 unsigned NElts = VT.getVectorNumElements();
1195 SmallVector<int, 8> MaskVec;
1196 for (unsigned i = 0; i != NElts; ++i) {
1197 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1198 MaskVec.push_back(Mask[i]);
1201 // Canonicalize shuffle v, v -> v, undef
1204 for (unsigned i = 0; i != NElts; ++i)
1205 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1208 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1209 if (N1.getOpcode() == ISD::UNDEF)
1210 commuteShuffle(N1, N2, MaskVec);
1212 // Canonicalize all index into lhs, -> shuffle lhs, undef
1213 // Canonicalize all index into rhs, -> shuffle rhs, undef
1214 bool AllLHS = true, AllRHS = true;
1215 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1216 for (unsigned i = 0; i != NElts; ++i) {
1217 if (MaskVec[i] >= (int)NElts) {
1222 } else if (MaskVec[i] >= 0) {
1226 if (AllLHS && AllRHS)
1227 return getUNDEF(VT);
1228 if (AllLHS && !N2Undef)
1232 commuteShuffle(N1, N2, MaskVec);
1235 // If Identity shuffle, or all shuffle in to undef, return that node.
1236 bool AllUndef = true;
1237 bool Identity = true;
1238 for (unsigned i = 0; i != NElts; ++i) {
1239 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1240 if (MaskVec[i] >= 0) AllUndef = false;
1242 if (Identity && NElts == N1.getValueType().getVectorNumElements())
1245 return getUNDEF(VT);
1247 FoldingSetNodeID ID;
1248 SDValue Ops[2] = { N1, N2 };
1249 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1250 for (unsigned i = 0; i != NElts; ++i)
1251 ID.AddInteger(MaskVec[i]);
1254 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1255 return SDValue(E, 0);
1257 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1258 // SDNode doesn't have access to it. This memory will be "leaked" when
1259 // the node is deallocated, but recovered when the NodeAllocator is released.
1260 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1261 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1263 ShuffleVectorSDNode *N =
1264 new (NodeAllocator) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
1265 CSEMap.InsertNode(N, IP);
1266 AllNodes.push_back(N);
1267 return SDValue(N, 0);
1270 SDValue SelectionDAG::getConvertRndSat(EVT VT, DebugLoc dl,
1271 SDValue Val, SDValue DTy,
1272 SDValue STy, SDValue Rnd, SDValue Sat,
1273 ISD::CvtCode Code) {
1274 // If the src and dest types are the same and the conversion is between
1275 // integer types of the same sign or two floats, no conversion is necessary.
1277 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1280 FoldingSetNodeID ID;
1281 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1282 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5);
1284 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1285 return SDValue(E, 0);
1287 CvtRndSatSDNode *N = new (NodeAllocator) CvtRndSatSDNode(VT, dl, Ops, 5,
1289 CSEMap.InsertNode(N, IP);
1290 AllNodes.push_back(N);
1291 return SDValue(N, 0);
1294 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1295 FoldingSetNodeID ID;
1296 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1297 ID.AddInteger(RegNo);
1299 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1300 return SDValue(E, 0);
1302 SDNode *N = new (NodeAllocator) RegisterSDNode(RegNo, VT);
1303 CSEMap.InsertNode(N, IP);
1304 AllNodes.push_back(N);
1305 return SDValue(N, 0);
1308 SDValue SelectionDAG::getEHLabel(DebugLoc dl, SDValue Root, MCSymbol *Label) {
1309 FoldingSetNodeID ID;
1310 SDValue Ops[] = { Root };
1311 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), &Ops[0], 1);
1312 ID.AddPointer(Label);
1314 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1315 return SDValue(E, 0);
1317 SDNode *N = new (NodeAllocator) EHLabelSDNode(dl, Root, Label);
1318 CSEMap.InsertNode(N, IP);
1319 AllNodes.push_back(N);
1320 return SDValue(N, 0);
1324 SDValue SelectionDAG::getBlockAddress(BlockAddress *BA, EVT VT,
1326 unsigned char TargetFlags) {
1327 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1329 FoldingSetNodeID ID;
1330 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1332 ID.AddInteger(TargetFlags);
1334 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1335 return SDValue(E, 0);
1337 SDNode *N = new (NodeAllocator) BlockAddressSDNode(Opc, VT, BA, TargetFlags);
1338 CSEMap.InsertNode(N, IP);
1339 AllNodes.push_back(N);
1340 return SDValue(N, 0);
1343 SDValue SelectionDAG::getSrcValue(const Value *V) {
1344 assert((!V || V->getType()->isPointerTy()) &&
1345 "SrcValue is not a pointer?");
1347 FoldingSetNodeID ID;
1348 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1352 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1353 return SDValue(E, 0);
1355 SDNode *N = new (NodeAllocator) SrcValueSDNode(V);
1356 CSEMap.InsertNode(N, IP);
1357 AllNodes.push_back(N);
1358 return SDValue(N, 0);
1361 /// getShiftAmountOperand - Return the specified value casted to
1362 /// the target's desired shift amount type.
1363 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
1364 EVT OpTy = Op.getValueType();
1365 MVT ShTy = TLI.getShiftAmountTy();
1366 if (OpTy == ShTy || OpTy.isVector()) return Op;
1368 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1369 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
1372 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1373 /// specified value type.
1374 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1375 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1376 unsigned ByteSize = VT.getStoreSize();
1377 const Type *Ty = VT.getTypeForEVT(*getContext());
1378 unsigned StackAlign =
1379 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1381 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1382 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1385 /// CreateStackTemporary - Create a stack temporary suitable for holding
1386 /// either of the specified value types.
1387 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1388 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1389 VT2.getStoreSizeInBits())/8;
1390 const Type *Ty1 = VT1.getTypeForEVT(*getContext());
1391 const Type *Ty2 = VT2.getTypeForEVT(*getContext());
1392 const TargetData *TD = TLI.getTargetData();
1393 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1394 TD->getPrefTypeAlignment(Ty2));
1396 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1397 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1398 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1401 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1402 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1403 // These setcc operations always fold.
1407 case ISD::SETFALSE2: return getConstant(0, VT);
1409 case ISD::SETTRUE2: return getConstant(1, VT);
1421 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1425 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1426 const APInt &C2 = N2C->getAPIntValue();
1427 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1428 const APInt &C1 = N1C->getAPIntValue();
1431 default: llvm_unreachable("Unknown integer setcc!");
1432 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1433 case ISD::SETNE: return getConstant(C1 != C2, VT);
1434 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1435 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1436 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1437 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1438 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1439 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1440 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1441 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1445 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1446 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1447 // No compile time operations on this type yet.
1448 if (N1C->getValueType(0) == MVT::ppcf128)
1451 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1454 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1455 return getUNDEF(VT);
1457 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1458 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1459 return getUNDEF(VT);
1461 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1462 R==APFloat::cmpLessThan, VT);
1463 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1464 return getUNDEF(VT);
1466 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1467 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1468 return getUNDEF(VT);
1470 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1471 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1472 return getUNDEF(VT);
1474 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1475 R==APFloat::cmpEqual, VT);
1476 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1477 return getUNDEF(VT);
1479 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1480 R==APFloat::cmpEqual, VT);
1481 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1482 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1483 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1484 R==APFloat::cmpEqual, VT);
1485 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1486 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1487 R==APFloat::cmpLessThan, VT);
1488 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1489 R==APFloat::cmpUnordered, VT);
1490 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1491 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1494 // Ensure that the constant occurs on the RHS.
1495 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1499 // Could not fold it.
1503 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1504 /// use this predicate to simplify operations downstream.
1505 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1506 // This predicate is not safe for vector operations.
1507 if (Op.getValueType().isVector())
1510 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1511 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1514 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1515 /// this predicate to simplify operations downstream. Mask is known to be zero
1516 /// for bits that V cannot have.
1517 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1518 unsigned Depth) const {
1519 APInt KnownZero, KnownOne;
1520 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1521 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1522 return (KnownZero & Mask) == Mask;
1525 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1526 /// known to be either zero or one and return them in the KnownZero/KnownOne
1527 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1529 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1530 APInt &KnownZero, APInt &KnownOne,
1531 unsigned Depth) const {
1532 unsigned BitWidth = Mask.getBitWidth();
1533 assert(BitWidth == Op.getValueType().getScalarType().getSizeInBits() &&
1534 "Mask size mismatches value type size!");
1536 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1537 if (Depth == 6 || Mask == 0)
1538 return; // Limit search depth.
1540 APInt KnownZero2, KnownOne2;
1542 switch (Op.getOpcode()) {
1544 // We know all of the bits for a constant!
1545 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1546 KnownZero = ~KnownOne & Mask;
1549 // If either the LHS or the RHS are Zero, the result is zero.
1550 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1551 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1552 KnownZero2, KnownOne2, Depth+1);
1553 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1554 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1556 // Output known-1 bits are only known if set in both the LHS & RHS.
1557 KnownOne &= KnownOne2;
1558 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1559 KnownZero |= KnownZero2;
1562 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1563 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1564 KnownZero2, KnownOne2, Depth+1);
1565 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1566 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1568 // Output known-0 bits are only known if clear in both the LHS & RHS.
1569 KnownZero &= KnownZero2;
1570 // Output known-1 are known to be set if set in either the LHS | RHS.
1571 KnownOne |= KnownOne2;
1574 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1575 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1576 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1577 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1579 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1580 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1581 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1582 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1583 KnownZero = KnownZeroOut;
1587 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1588 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1589 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1590 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1591 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1593 // If low bits are zero in either operand, output low known-0 bits.
1594 // Also compute a conserative estimate for high known-0 bits.
1595 // More trickiness is possible, but this is sufficient for the
1596 // interesting case of alignment computation.
1598 unsigned TrailZ = KnownZero.countTrailingOnes() +
1599 KnownZero2.countTrailingOnes();
1600 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1601 KnownZero2.countLeadingOnes(),
1602 BitWidth) - BitWidth;
1604 TrailZ = std::min(TrailZ, BitWidth);
1605 LeadZ = std::min(LeadZ, BitWidth);
1606 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1607 APInt::getHighBitsSet(BitWidth, LeadZ);
1612 // For the purposes of computing leading zeros we can conservatively
1613 // treat a udiv as a logical right shift by the power of 2 known to
1614 // be less than the denominator.
1615 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1616 ComputeMaskedBits(Op.getOperand(0),
1617 AllOnes, KnownZero2, KnownOne2, Depth+1);
1618 unsigned LeadZ = KnownZero2.countLeadingOnes();
1622 ComputeMaskedBits(Op.getOperand(1),
1623 AllOnes, KnownZero2, KnownOne2, Depth+1);
1624 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1625 if (RHSUnknownLeadingOnes != BitWidth)
1626 LeadZ = std::min(BitWidth,
1627 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1629 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1633 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1634 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1635 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1636 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1638 // Only known if known in both the LHS and RHS.
1639 KnownOne &= KnownOne2;
1640 KnownZero &= KnownZero2;
1642 case ISD::SELECT_CC:
1643 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1644 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1645 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1646 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1648 // Only known if known in both the LHS and RHS.
1649 KnownOne &= KnownOne2;
1650 KnownZero &= KnownZero2;
1658 if (Op.getResNo() != 1)
1660 // The boolean result conforms to getBooleanContents. Fall through.
1662 // If we know the result of a setcc has the top bits zero, use this info.
1663 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1665 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1668 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1669 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1670 unsigned ShAmt = SA->getZExtValue();
1672 // If the shift count is an invalid immediate, don't do anything.
1673 if (ShAmt >= BitWidth)
1676 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1677 KnownZero, KnownOne, Depth+1);
1678 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1679 KnownZero <<= ShAmt;
1681 // low bits known zero.
1682 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1686 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1687 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1688 unsigned ShAmt = SA->getZExtValue();
1690 // If the shift count is an invalid immediate, don't do anything.
1691 if (ShAmt >= BitWidth)
1694 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1695 KnownZero, KnownOne, Depth+1);
1696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1697 KnownZero = KnownZero.lshr(ShAmt);
1698 KnownOne = KnownOne.lshr(ShAmt);
1700 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1701 KnownZero |= HighBits; // High bits known zero.
1705 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1706 unsigned ShAmt = SA->getZExtValue();
1708 // If the shift count is an invalid immediate, don't do anything.
1709 if (ShAmt >= BitWidth)
1712 APInt InDemandedMask = (Mask << ShAmt);
1713 // If any of the demanded bits are produced by the sign extension, we also
1714 // demand the input sign bit.
1715 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1716 if (HighBits.getBoolValue())
1717 InDemandedMask |= APInt::getSignBit(BitWidth);
1719 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1721 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1722 KnownZero = KnownZero.lshr(ShAmt);
1723 KnownOne = KnownOne.lshr(ShAmt);
1725 // Handle the sign bits.
1726 APInt SignBit = APInt::getSignBit(BitWidth);
1727 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1729 if (KnownZero.intersects(SignBit)) {
1730 KnownZero |= HighBits; // New bits are known zero.
1731 } else if (KnownOne.intersects(SignBit)) {
1732 KnownOne |= HighBits; // New bits are known one.
1736 case ISD::SIGN_EXTEND_INREG: {
1737 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1738 unsigned EBits = EVT.getScalarType().getSizeInBits();
1740 // Sign extension. Compute the demanded bits in the result that are not
1741 // present in the input.
1742 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1744 APInt InSignBit = APInt::getSignBit(EBits);
1745 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1747 // If the sign extended bits are demanded, we know that the sign
1749 InSignBit.zext(BitWidth);
1750 if (NewBits.getBoolValue())
1751 InputDemandedBits |= InSignBit;
1753 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1754 KnownZero, KnownOne, Depth+1);
1755 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1757 // If the sign bit of the input is known set or clear, then we know the
1758 // top bits of the result.
1759 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1760 KnownZero |= NewBits;
1761 KnownOne &= ~NewBits;
1762 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1763 KnownOne |= NewBits;
1764 KnownZero &= ~NewBits;
1765 } else { // Input sign bit unknown
1766 KnownZero &= ~NewBits;
1767 KnownOne &= ~NewBits;
1774 unsigned LowBits = Log2_32(BitWidth)+1;
1775 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1780 if (ISD::isZEXTLoad(Op.getNode())) {
1781 LoadSDNode *LD = cast<LoadSDNode>(Op);
1782 EVT VT = LD->getMemoryVT();
1783 unsigned MemBits = VT.getScalarType().getSizeInBits();
1784 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1788 case ISD::ZERO_EXTEND: {
1789 EVT InVT = Op.getOperand(0).getValueType();
1790 unsigned InBits = InVT.getScalarType().getSizeInBits();
1791 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1792 APInt InMask = Mask;
1793 InMask.trunc(InBits);
1794 KnownZero.trunc(InBits);
1795 KnownOne.trunc(InBits);
1796 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1797 KnownZero.zext(BitWidth);
1798 KnownOne.zext(BitWidth);
1799 KnownZero |= NewBits;
1802 case ISD::SIGN_EXTEND: {
1803 EVT InVT = Op.getOperand(0).getValueType();
1804 unsigned InBits = InVT.getScalarType().getSizeInBits();
1805 APInt InSignBit = APInt::getSignBit(InBits);
1806 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1807 APInt InMask = Mask;
1808 InMask.trunc(InBits);
1810 // If any of the sign extended bits are demanded, we know that the sign
1811 // bit is demanded. Temporarily set this bit in the mask for our callee.
1812 if (NewBits.getBoolValue())
1813 InMask |= InSignBit;
1815 KnownZero.trunc(InBits);
1816 KnownOne.trunc(InBits);
1817 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1819 // Note if the sign bit is known to be zero or one.
1820 bool SignBitKnownZero = KnownZero.isNegative();
1821 bool SignBitKnownOne = KnownOne.isNegative();
1822 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1823 "Sign bit can't be known to be both zero and one!");
1825 // If the sign bit wasn't actually demanded by our caller, we don't
1826 // want it set in the KnownZero and KnownOne result values. Reset the
1827 // mask and reapply it to the result values.
1829 InMask.trunc(InBits);
1830 KnownZero &= InMask;
1833 KnownZero.zext(BitWidth);
1834 KnownOne.zext(BitWidth);
1836 // If the sign bit is known zero or one, the top bits match.
1837 if (SignBitKnownZero)
1838 KnownZero |= NewBits;
1839 else if (SignBitKnownOne)
1840 KnownOne |= NewBits;
1843 case ISD::ANY_EXTEND: {
1844 EVT InVT = Op.getOperand(0).getValueType();
1845 unsigned InBits = InVT.getScalarType().getSizeInBits();
1846 APInt InMask = Mask;
1847 InMask.trunc(InBits);
1848 KnownZero.trunc(InBits);
1849 KnownOne.trunc(InBits);
1850 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1851 KnownZero.zext(BitWidth);
1852 KnownOne.zext(BitWidth);
1855 case ISD::TRUNCATE: {
1856 EVT InVT = Op.getOperand(0).getValueType();
1857 unsigned InBits = InVT.getScalarType().getSizeInBits();
1858 APInt InMask = Mask;
1859 InMask.zext(InBits);
1860 KnownZero.zext(InBits);
1861 KnownOne.zext(InBits);
1862 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1863 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1864 KnownZero.trunc(BitWidth);
1865 KnownOne.trunc(BitWidth);
1868 case ISD::AssertZext: {
1869 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1870 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1871 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1873 KnownZero |= (~InMask) & Mask;
1877 // All bits are zero except the low bit.
1878 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1882 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1883 // We know that the top bits of C-X are clear if X contains less bits
1884 // than C (i.e. no wrap-around can happen). For example, 20-X is
1885 // positive if we can prove that X is >= 0 and < 16.
1886 if (CLHS->getAPIntValue().isNonNegative()) {
1887 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1888 // NLZ can't be BitWidth with no sign bit
1889 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1890 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1893 // If all of the MaskV bits are known to be zero, then we know the
1894 // output top bits are zero, because we now know that the output is
1896 if ((KnownZero2 & MaskV) == MaskV) {
1897 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1898 // Top bits known zero.
1899 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1906 // Output known-0 bits are known if clear or set in both the low clear bits
1907 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1908 // low 3 bits clear.
1909 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1910 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1911 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1912 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1914 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1915 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1916 KnownZeroOut = std::min(KnownZeroOut,
1917 KnownZero2.countTrailingOnes());
1919 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1923 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1924 const APInt &RA = Rem->getAPIntValue().abs();
1925 if (RA.isPowerOf2()) {
1926 APInt LowBits = RA - 1;
1927 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1928 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1930 // The low bits of the first operand are unchanged by the srem.
1931 KnownZero = KnownZero2 & LowBits;
1932 KnownOne = KnownOne2 & LowBits;
1934 // If the first operand is non-negative or has all low bits zero, then
1935 // the upper bits are all zero.
1936 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1937 KnownZero |= ~LowBits;
1939 // If the first operand is negative and not all low bits are zero, then
1940 // the upper bits are all one.
1941 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1942 KnownOne |= ~LowBits;
1947 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1952 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1953 const APInt &RA = Rem->getAPIntValue();
1954 if (RA.isPowerOf2()) {
1955 APInt LowBits = (RA - 1);
1956 APInt Mask2 = LowBits & Mask;
1957 KnownZero |= ~LowBits & Mask;
1958 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1959 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1964 // Since the result is less than or equal to either operand, any leading
1965 // zero bits in either operand must also exist in the result.
1966 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1967 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1969 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1972 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1973 KnownZero2.countLeadingOnes());
1975 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1979 // Allow the target to implement this method for its nodes.
1980 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1981 case ISD::INTRINSIC_WO_CHAIN:
1982 case ISD::INTRINSIC_W_CHAIN:
1983 case ISD::INTRINSIC_VOID:
1984 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
1991 /// ComputeNumSignBits - Return the number of times the sign bit of the
1992 /// register is replicated into the other bits. We know that at least 1 bit
1993 /// is always equal to the sign bit (itself), but other cases can give us
1994 /// information. For example, immediately after an "SRA X, 2", we know that
1995 /// the top 3 bits are all equal to each other, so we return 3.
1996 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1997 EVT VT = Op.getValueType();
1998 assert(VT.isInteger() && "Invalid VT!");
1999 unsigned VTBits = VT.getScalarType().getSizeInBits();
2001 unsigned FirstAnswer = 1;
2004 return 1; // Limit search depth.
2006 switch (Op.getOpcode()) {
2008 case ISD::AssertSext:
2009 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2010 return VTBits-Tmp+1;
2011 case ISD::AssertZext:
2012 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2015 case ISD::Constant: {
2016 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2017 // If negative, return # leading ones.
2018 if (Val.isNegative())
2019 return Val.countLeadingOnes();
2021 // Return # leading zeros.
2022 return Val.countLeadingZeros();
2025 case ISD::SIGN_EXTEND:
2026 Tmp = VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2027 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2029 case ISD::SIGN_EXTEND_INREG:
2030 // Max of the input and what this extends.
2032 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
2035 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2036 return std::max(Tmp, Tmp2);
2039 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2040 // SRA X, C -> adds C sign bits.
2041 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2042 Tmp += C->getZExtValue();
2043 if (Tmp > VTBits) Tmp = VTBits;
2047 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2048 // shl destroys sign bits.
2049 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2050 if (C->getZExtValue() >= VTBits || // Bad shift.
2051 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2052 return Tmp - C->getZExtValue();
2057 case ISD::XOR: // NOT is handled here.
2058 // Logical binary ops preserve the number of sign bits at the worst.
2059 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2061 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2062 FirstAnswer = std::min(Tmp, Tmp2);
2063 // We computed what we know about the sign bits as our first
2064 // answer. Now proceed to the generic code that uses
2065 // ComputeMaskedBits, and pick whichever answer is better.
2070 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2071 if (Tmp == 1) return 1; // Early out.
2072 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2073 return std::min(Tmp, Tmp2);
2081 if (Op.getResNo() != 1)
2083 // The boolean result conforms to getBooleanContents. Fall through.
2085 // If setcc returns 0/-1, all bits are sign bits.
2086 if (TLI.getBooleanContents() ==
2087 TargetLowering::ZeroOrNegativeOneBooleanContent)
2092 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2093 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2095 // Handle rotate right by N like a rotate left by 32-N.
2096 if (Op.getOpcode() == ISD::ROTR)
2097 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2099 // If we aren't rotating out all of the known-in sign bits, return the
2100 // number that are left. This handles rotl(sext(x), 1) for example.
2101 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2102 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2106 // Add can have at most one carry bit. Thus we know that the output
2107 // is, at worst, one more bit than the inputs.
2108 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2109 if (Tmp == 1) return 1; // Early out.
2111 // Special case decrementing a value (ADD X, -1):
2112 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2113 if (CRHS->isAllOnesValue()) {
2114 APInt KnownZero, KnownOne;
2115 APInt Mask = APInt::getAllOnesValue(VTBits);
2116 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2118 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2120 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2123 // If we are subtracting one from a positive number, there is no carry
2124 // out of the result.
2125 if (KnownZero.isNegative())
2129 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2130 if (Tmp2 == 1) return 1;
2131 return std::min(Tmp, Tmp2)-1;
2135 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2136 if (Tmp2 == 1) return 1;
2139 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2140 if (CLHS->isNullValue()) {
2141 APInt KnownZero, KnownOne;
2142 APInt Mask = APInt::getAllOnesValue(VTBits);
2143 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2144 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2146 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2149 // If the input is known to be positive (the sign bit is known clear),
2150 // the output of the NEG has the same number of sign bits as the input.
2151 if (KnownZero.isNegative())
2154 // Otherwise, we treat this like a SUB.
2157 // Sub can have at most one carry bit. Thus we know that the output
2158 // is, at worst, one more bit than the inputs.
2159 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2160 if (Tmp == 1) return 1; // Early out.
2161 return std::min(Tmp, Tmp2)-1;
2164 // FIXME: it's tricky to do anything useful for this, but it is an important
2165 // case for targets like X86.
2169 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2170 if (Op.getOpcode() == ISD::LOAD) {
2171 LoadSDNode *LD = cast<LoadSDNode>(Op);
2172 unsigned ExtType = LD->getExtensionType();
2175 case ISD::SEXTLOAD: // '17' bits known
2176 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2177 return VTBits-Tmp+1;
2178 case ISD::ZEXTLOAD: // '16' bits known
2179 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2184 // Allow the target to implement this method for its nodes.
2185 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2186 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2187 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2188 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2189 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2190 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2193 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2194 // use this information.
2195 APInt KnownZero, KnownOne;
2196 APInt Mask = APInt::getAllOnesValue(VTBits);
2197 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2199 if (KnownZero.isNegative()) { // sign bit is 0
2201 } else if (KnownOne.isNegative()) { // sign bit is 1;
2208 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2209 // the number of identical bits in the top of the input value.
2211 Mask <<= Mask.getBitWidth()-VTBits;
2212 // Return # leading zeros. We use 'min' here in case Val was zero before
2213 // shifting. We don't want to return '64' as for an i32 "0".
2214 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2217 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2218 // If we're told that NaNs won't happen, assume they won't.
2219 if (FiniteOnlyFPMath())
2222 // If the value is a constant, we can obviously see if it is a NaN or not.
2223 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2224 return !C->getValueAPF().isNaN();
2226 // TODO: Recognize more cases here.
2231 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2232 // If the value is a constant, we can obviously see if it is a zero or not.
2233 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2234 return !C->isZero();
2236 // TODO: Recognize more cases here.
2241 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2242 // Check the obvious case.
2243 if (A == B) return true;
2245 // For for negative and positive zero.
2246 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2247 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2248 if (CA->isZero() && CB->isZero()) return true;
2250 // Otherwise they may not be equal.
2254 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2255 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2256 if (!GA) return false;
2257 if (GA->getOffset() != 0) return false;
2258 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2259 if (!GV) return false;
2260 MachineModuleInfo *MMI = getMachineModuleInfo();
2261 return MMI && MMI->hasDebugInfo();
2265 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2266 /// element of the result of the vector shuffle.
2267 SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N,
2269 EVT VT = N->getValueType(0);
2270 DebugLoc dl = N->getDebugLoc();
2271 if (N->getMaskElt(i) < 0)
2272 return getUNDEF(VT.getVectorElementType());
2273 unsigned Index = N->getMaskElt(i);
2274 unsigned NumElems = VT.getVectorNumElements();
2275 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2278 if (V.getOpcode() == ISD::BIT_CONVERT) {
2279 V = V.getOperand(0);
2280 EVT VVT = V.getValueType();
2281 if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems)
2284 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2285 return (Index == 0) ? V.getOperand(0)
2286 : getUNDEF(VT.getVectorElementType());
2287 if (V.getOpcode() == ISD::BUILD_VECTOR)
2288 return V.getOperand(Index);
2289 if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V))
2290 return getShuffleScalarElt(SVN, Index);
2295 /// getNode - Gets or creates the specified node.
2297 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
2298 FoldingSetNodeID ID;
2299 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2301 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2302 return SDValue(E, 0);
2304 SDNode *N = new (NodeAllocator) SDNode(Opcode, DL, getVTList(VT));
2305 CSEMap.InsertNode(N, IP);
2307 AllNodes.push_back(N);
2311 return SDValue(N, 0);
2314 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2315 EVT VT, SDValue Operand) {
2316 // Constant fold unary operations with an integer constant operand.
2317 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2318 const APInt &Val = C->getAPIntValue();
2321 case ISD::SIGN_EXTEND:
2322 return getConstant(APInt(Val).sextOrTrunc(VT.getSizeInBits()), VT);
2323 case ISD::ANY_EXTEND:
2324 case ISD::ZERO_EXTEND:
2326 return getConstant(APInt(Val).zextOrTrunc(VT.getSizeInBits()), VT);
2327 case ISD::UINT_TO_FP:
2328 case ISD::SINT_TO_FP: {
2329 const uint64_t zero[] = {0, 0};
2330 // No compile time operations on ppcf128.
2331 if (VT == MVT::ppcf128) break;
2332 APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
2333 (void)apf.convertFromAPInt(Val,
2334 Opcode==ISD::SINT_TO_FP,
2335 APFloat::rmNearestTiesToEven);
2336 return getConstantFP(apf, VT);
2338 case ISD::BIT_CONVERT:
2339 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2340 return getConstantFP(Val.bitsToFloat(), VT);
2341 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2342 return getConstantFP(Val.bitsToDouble(), VT);
2345 return getConstant(Val.byteSwap(), VT);
2347 return getConstant(Val.countPopulation(), VT);
2349 return getConstant(Val.countLeadingZeros(), VT);
2351 return getConstant(Val.countTrailingZeros(), VT);
2355 // Constant fold unary operations with a floating point constant operand.
2356 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2357 APFloat V = C->getValueAPF(); // make copy
2358 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2362 return getConstantFP(V, VT);
2365 return getConstantFP(V, VT);
2367 case ISD::FP_EXTEND: {
2369 // This can return overflow, underflow, or inexact; we don't care.
2370 // FIXME need to be more flexible about rounding mode.
2371 (void)V.convert(*EVTToAPFloatSemantics(VT),
2372 APFloat::rmNearestTiesToEven, &ignored);
2373 return getConstantFP(V, VT);
2375 case ISD::FP_TO_SINT:
2376 case ISD::FP_TO_UINT: {
2379 assert(integerPartWidth >= 64);
2380 // FIXME need to be more flexible about rounding mode.
2381 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2382 Opcode==ISD::FP_TO_SINT,
2383 APFloat::rmTowardZero, &ignored);
2384 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2386 APInt api(VT.getSizeInBits(), 2, x);
2387 return getConstant(api, VT);
2389 case ISD::BIT_CONVERT:
2390 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2391 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2392 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2393 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2399 unsigned OpOpcode = Operand.getNode()->getOpcode();
2401 case ISD::TokenFactor:
2402 case ISD::MERGE_VALUES:
2403 case ISD::CONCAT_VECTORS:
2404 return Operand; // Factor, merge or concat of one node? No need.
2405 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2406 case ISD::FP_EXTEND:
2407 assert(VT.isFloatingPoint() &&
2408 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2409 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2410 assert((!VT.isVector() ||
2411 VT.getVectorNumElements() ==
2412 Operand.getValueType().getVectorNumElements()) &&
2413 "Vector element count mismatch!");
2414 if (Operand.getOpcode() == ISD::UNDEF)
2415 return getUNDEF(VT);
2417 case ISD::SIGN_EXTEND:
2418 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2419 "Invalid SIGN_EXTEND!");
2420 if (Operand.getValueType() == VT) return Operand; // noop extension
2421 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2422 "Invalid sext node, dst < src!");
2423 assert((!VT.isVector() ||
2424 VT.getVectorNumElements() ==
2425 Operand.getValueType().getVectorNumElements()) &&
2426 "Vector element count mismatch!");
2427 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2428 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2430 case ISD::ZERO_EXTEND:
2431 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2432 "Invalid ZERO_EXTEND!");
2433 if (Operand.getValueType() == VT) return Operand; // noop extension
2434 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2435 "Invalid zext node, dst < src!");
2436 assert((!VT.isVector() ||
2437 VT.getVectorNumElements() ==
2438 Operand.getValueType().getVectorNumElements()) &&
2439 "Vector element count mismatch!");
2440 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2441 return getNode(ISD::ZERO_EXTEND, DL, VT,
2442 Operand.getNode()->getOperand(0));
2444 case ISD::ANY_EXTEND:
2445 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2446 "Invalid ANY_EXTEND!");
2447 if (Operand.getValueType() == VT) return Operand; // noop extension
2448 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2449 "Invalid anyext node, dst < src!");
2450 assert((!VT.isVector() ||
2451 VT.getVectorNumElements() ==
2452 Operand.getValueType().getVectorNumElements()) &&
2453 "Vector element count mismatch!");
2454 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2455 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2456 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2459 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2460 "Invalid TRUNCATE!");
2461 if (Operand.getValueType() == VT) return Operand; // noop truncate
2462 assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2463 "Invalid truncate node, src < dst!");
2464 assert((!VT.isVector() ||
2465 VT.getVectorNumElements() ==
2466 Operand.getValueType().getVectorNumElements()) &&
2467 "Vector element count mismatch!");
2468 if (OpOpcode == ISD::TRUNCATE)
2469 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2470 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2471 OpOpcode == ISD::ANY_EXTEND) {
2472 // If the source is smaller than the dest, we still need an extend.
2473 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2474 .bitsLT(VT.getScalarType()))
2475 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2476 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2477 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2479 return Operand.getNode()->getOperand(0);
2482 case ISD::BIT_CONVERT:
2483 // Basic sanity checking.
2484 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2485 && "Cannot BIT_CONVERT between types of different sizes!");
2486 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2487 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2488 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2489 if (OpOpcode == ISD::UNDEF)
2490 return getUNDEF(VT);
2492 case ISD::SCALAR_TO_VECTOR:
2493 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2494 (VT.getVectorElementType() == Operand.getValueType() ||
2495 (VT.getVectorElementType().isInteger() &&
2496 Operand.getValueType().isInteger() &&
2497 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2498 "Illegal SCALAR_TO_VECTOR node!");
2499 if (OpOpcode == ISD::UNDEF)
2500 return getUNDEF(VT);
2501 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2502 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2503 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2504 Operand.getConstantOperandVal(1) == 0 &&
2505 Operand.getOperand(0).getValueType() == VT)
2506 return Operand.getOperand(0);
2509 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2510 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2511 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2512 Operand.getNode()->getOperand(0));
2513 if (OpOpcode == ISD::FNEG) // --X -> X
2514 return Operand.getNode()->getOperand(0);
2517 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2518 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2523 SDVTList VTs = getVTList(VT);
2524 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2525 FoldingSetNodeID ID;
2526 SDValue Ops[1] = { Operand };
2527 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2529 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2530 return SDValue(E, 0);
2532 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTs, Operand);
2533 CSEMap.InsertNode(N, IP);
2535 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTs, Operand);
2538 AllNodes.push_back(N);
2542 return SDValue(N, 0);
2545 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2547 ConstantSDNode *Cst1,
2548 ConstantSDNode *Cst2) {
2549 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2552 case ISD::ADD: return getConstant(C1 + C2, VT);
2553 case ISD::SUB: return getConstant(C1 - C2, VT);
2554 case ISD::MUL: return getConstant(C1 * C2, VT);
2556 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2559 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2562 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2565 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2567 case ISD::AND: return getConstant(C1 & C2, VT);
2568 case ISD::OR: return getConstant(C1 | C2, VT);
2569 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2570 case ISD::SHL: return getConstant(C1 << C2, VT);
2571 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2572 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2573 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2574 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2581 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2582 SDValue N1, SDValue N2) {
2583 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2584 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2587 case ISD::TokenFactor:
2588 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2589 N2.getValueType() == MVT::Other && "Invalid token factor!");
2590 // Fold trivial token factors.
2591 if (N1.getOpcode() == ISD::EntryToken) return N2;
2592 if (N2.getOpcode() == ISD::EntryToken) return N1;
2593 if (N1 == N2) return N1;
2595 case ISD::CONCAT_VECTORS:
2596 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2597 // one big BUILD_VECTOR.
2598 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2599 N2.getOpcode() == ISD::BUILD_VECTOR) {
2600 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2601 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2602 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2606 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2607 N1.getValueType() == VT && "Binary operator types must match!");
2608 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2609 // worth handling here.
2610 if (N2C && N2C->isNullValue())
2612 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2619 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2620 N1.getValueType() == VT && "Binary operator types must match!");
2621 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2622 // it's worth handling here.
2623 if (N2C && N2C->isNullValue())
2633 assert(VT.isInteger() && "This operator does not apply to FP types!");
2641 if (Opcode == ISD::FADD) {
2643 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2644 if (CFP->getValueAPF().isZero())
2647 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2648 if (CFP->getValueAPF().isZero())
2650 } else if (Opcode == ISD::FSUB) {
2652 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2653 if (CFP->getValueAPF().isZero())
2657 assert(N1.getValueType() == N2.getValueType() &&
2658 N1.getValueType() == VT && "Binary operator types must match!");
2660 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2661 assert(N1.getValueType() == VT &&
2662 N1.getValueType().isFloatingPoint() &&
2663 N2.getValueType().isFloatingPoint() &&
2664 "Invalid FCOPYSIGN!");
2671 assert(VT == N1.getValueType() &&
2672 "Shift operators return type must be the same as their first arg");
2673 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2674 "Shifts only work on integers");
2676 // Always fold shifts of i1 values so the code generator doesn't need to
2677 // handle them. Since we know the size of the shift has to be less than the
2678 // size of the value, the shift/rotate count is guaranteed to be zero.
2681 if (N2C && N2C->isNullValue())
2684 case ISD::FP_ROUND_INREG: {
2685 EVT EVT = cast<VTSDNode>(N2)->getVT();
2686 assert(VT == N1.getValueType() && "Not an inreg round!");
2687 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2688 "Cannot FP_ROUND_INREG integer types");
2689 assert(EVT.isVector() == VT.isVector() &&
2690 "FP_ROUND_INREG type should be vector iff the operand "
2692 assert((!EVT.isVector() ||
2693 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2694 "Vector element counts must match in FP_ROUND_INREG");
2695 assert(EVT.bitsLE(VT) && "Not rounding down!");
2696 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2700 assert(VT.isFloatingPoint() &&
2701 N1.getValueType().isFloatingPoint() &&
2702 VT.bitsLE(N1.getValueType()) &&
2703 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2704 if (N1.getValueType() == VT) return N1; // noop conversion.
2706 case ISD::AssertSext:
2707 case ISD::AssertZext: {
2708 EVT EVT = cast<VTSDNode>(N2)->getVT();
2709 assert(VT == N1.getValueType() && "Not an inreg extend!");
2710 assert(VT.isInteger() && EVT.isInteger() &&
2711 "Cannot *_EXTEND_INREG FP types");
2712 assert(!EVT.isVector() &&
2713 "AssertSExt/AssertZExt type should be the vector element type "
2714 "rather than the vector type!");
2715 assert(EVT.bitsLE(VT) && "Not extending!");
2716 if (VT == EVT) return N1; // noop assertion.
2719 case ISD::SIGN_EXTEND_INREG: {
2720 EVT EVT = cast<VTSDNode>(N2)->getVT();
2721 assert(VT == N1.getValueType() && "Not an inreg extend!");
2722 assert(VT.isInteger() && EVT.isInteger() &&
2723 "Cannot *_EXTEND_INREG FP types");
2724 assert(EVT.isVector() == VT.isVector() &&
2725 "SIGN_EXTEND_INREG type should be vector iff the operand "
2727 assert((!EVT.isVector() ||
2728 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2729 "Vector element counts must match in SIGN_EXTEND_INREG");
2730 assert(EVT.bitsLE(VT) && "Not extending!");
2731 if (EVT == VT) return N1; // Not actually extending
2734 APInt Val = N1C->getAPIntValue();
2735 unsigned FromBits = EVT.getScalarType().getSizeInBits();
2736 Val <<= Val.getBitWidth()-FromBits;
2737 Val = Val.ashr(Val.getBitWidth()-FromBits);
2738 return getConstant(Val, VT);
2742 case ISD::EXTRACT_VECTOR_ELT:
2743 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2744 if (N1.getOpcode() == ISD::UNDEF)
2745 return getUNDEF(VT);
2747 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2748 // expanding copies of large vectors from registers.
2750 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2751 N1.getNumOperands() > 0) {
2753 N1.getOperand(0).getValueType().getVectorNumElements();
2754 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2755 N1.getOperand(N2C->getZExtValue() / Factor),
2756 getConstant(N2C->getZExtValue() % Factor,
2757 N2.getValueType()));
2760 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2761 // expanding large vector constants.
2762 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2763 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2764 EVT VEltTy = N1.getValueType().getVectorElementType();
2765 if (Elt.getValueType() != VEltTy) {
2766 // If the vector element type is not legal, the BUILD_VECTOR operands
2767 // are promoted and implicitly truncated. Make that explicit here.
2768 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2771 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2772 // result is implicitly extended.
2773 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2778 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2779 // operations are lowered to scalars.
2780 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2781 // If the indices are the same, return the inserted element else
2782 // if the indices are known different, extract the element from
2783 // the original vector.
2784 if (N1.getOperand(2) == N2) {
2785 if (VT == N1.getOperand(1).getValueType())
2786 return N1.getOperand(1);
2788 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
2789 } else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2790 isa<ConstantSDNode>(N2))
2791 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2794 case ISD::EXTRACT_ELEMENT:
2795 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2796 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2797 (N1.getValueType().isInteger() == VT.isInteger()) &&
2798 "Wrong types for EXTRACT_ELEMENT!");
2800 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2801 // 64-bit integers into 32-bit parts. Instead of building the extract of
2802 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2803 if (N1.getOpcode() == ISD::BUILD_PAIR)
2804 return N1.getOperand(N2C->getZExtValue());
2806 // EXTRACT_ELEMENT of a constant int is also very common.
2807 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2808 unsigned ElementSize = VT.getSizeInBits();
2809 unsigned Shift = ElementSize * N2C->getZExtValue();
2810 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2811 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2814 case ISD::EXTRACT_SUBVECTOR:
2815 if (N1.getValueType() == VT) // Trivial extraction.
2822 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2823 if (SV.getNode()) return SV;
2824 } else { // Cannonicalize constant to RHS if commutative
2825 if (isCommutativeBinOp(Opcode)) {
2826 std::swap(N1C, N2C);
2832 // Constant fold FP operations.
2833 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2834 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2836 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2837 // Cannonicalize constant to RHS if commutative
2838 std::swap(N1CFP, N2CFP);
2840 } else if (N2CFP && VT != MVT::ppcf128) {
2841 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2842 APFloat::opStatus s;
2845 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2846 if (s != APFloat::opInvalidOp)
2847 return getConstantFP(V1, VT);
2850 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2851 if (s!=APFloat::opInvalidOp)
2852 return getConstantFP(V1, VT);
2855 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2856 if (s!=APFloat::opInvalidOp)
2857 return getConstantFP(V1, VT);
2860 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2861 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2862 return getConstantFP(V1, VT);
2865 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2866 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2867 return getConstantFP(V1, VT);
2869 case ISD::FCOPYSIGN:
2871 return getConstantFP(V1, VT);
2877 // Canonicalize an UNDEF to the RHS, even over a constant.
2878 if (N1.getOpcode() == ISD::UNDEF) {
2879 if (isCommutativeBinOp(Opcode)) {
2883 case ISD::FP_ROUND_INREG:
2884 case ISD::SIGN_EXTEND_INREG:
2890 return N1; // fold op(undef, arg2) -> undef
2898 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2899 // For vectors, we can't easily build an all zero vector, just return
2906 // Fold a bunch of operators when the RHS is undef.
2907 if (N2.getOpcode() == ISD::UNDEF) {
2910 if (N1.getOpcode() == ISD::UNDEF)
2911 // Handle undef ^ undef -> 0 special case. This is a common
2913 return getConstant(0, VT);
2923 return N2; // fold op(arg1, undef) -> undef
2937 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2938 // For vectors, we can't easily build an all zero vector, just return
2943 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2944 // For vectors, we can't easily build an all one vector, just return
2952 // Memoize this node if possible.
2954 SDVTList VTs = getVTList(VT);
2955 if (VT != MVT::Flag) {
2956 SDValue Ops[] = { N1, N2 };
2957 FoldingSetNodeID ID;
2958 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2960 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2961 return SDValue(E, 0);
2963 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTs, N1, N2);
2964 CSEMap.InsertNode(N, IP);
2966 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTs, N1, N2);
2969 AllNodes.push_back(N);
2973 return SDValue(N, 0);
2976 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2977 SDValue N1, SDValue N2, SDValue N3) {
2978 // Perform various simplifications.
2979 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2980 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2982 case ISD::CONCAT_VECTORS:
2983 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2984 // one big BUILD_VECTOR.
2985 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2986 N2.getOpcode() == ISD::BUILD_VECTOR &&
2987 N3.getOpcode() == ISD::BUILD_VECTOR) {
2988 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2989 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2990 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2991 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2995 // Use FoldSetCC to simplify SETCC's.
2996 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
2997 if (Simp.getNode()) return Simp;
3002 if (N1C->getZExtValue())
3003 return N2; // select true, X, Y -> X
3005 return N3; // select false, X, Y -> Y
3008 if (N2 == N3) return N2; // select C, X, X -> X
3012 if (N2C->getZExtValue()) // Unconditional branch
3013 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
3015 return N1; // Never-taken branch
3018 case ISD::VECTOR_SHUFFLE:
3019 llvm_unreachable("should use getVectorShuffle constructor!");
3021 case ISD::BIT_CONVERT:
3022 // Fold bit_convert nodes from a type to themselves.
3023 if (N1.getValueType() == VT)
3028 // Memoize node if it doesn't produce a flag.
3030 SDVTList VTs = getVTList(VT);
3031 if (VT != MVT::Flag) {
3032 SDValue Ops[] = { N1, N2, N3 };
3033 FoldingSetNodeID ID;
3034 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3036 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3037 return SDValue(E, 0);
3039 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3040 CSEMap.InsertNode(N, IP);
3042 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3045 AllNodes.push_back(N);
3049 return SDValue(N, 0);
3052 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3053 SDValue N1, SDValue N2, SDValue N3,
3055 SDValue Ops[] = { N1, N2, N3, N4 };
3056 return getNode(Opcode, DL, VT, Ops, 4);
3059 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3060 SDValue N1, SDValue N2, SDValue N3,
3061 SDValue N4, SDValue N5) {
3062 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3063 return getNode(Opcode, DL, VT, Ops, 5);
3066 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3067 /// the incoming stack arguments to be loaded from the stack.
3068 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3069 SmallVector<SDValue, 8> ArgChains;
3071 // Include the original chain at the beginning of the list. When this is
3072 // used by target LowerCall hooks, this helps legalize find the
3073 // CALLSEQ_BEGIN node.
3074 ArgChains.push_back(Chain);
3076 // Add a chain value for each stack argument.
3077 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3078 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3079 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3080 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3081 if (FI->getIndex() < 0)
3082 ArgChains.push_back(SDValue(L, 1));
3084 // Build a tokenfactor for all the chains.
3085 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
3086 &ArgChains[0], ArgChains.size());
3089 /// getMemsetValue - Vectorized representation of the memset value
3091 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3093 unsigned NumBits = VT.getScalarType().getSizeInBits();
3094 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3095 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
3097 for (unsigned i = NumBits; i > 8; i >>= 1) {
3098 Val = (Val << Shift) | Val;
3102 return DAG.getConstant(Val, VT);
3103 return DAG.getConstantFP(APFloat(Val), VT);
3106 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3107 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3109 for (unsigned i = NumBits; i > 8; i >>= 1) {
3110 Value = DAG.getNode(ISD::OR, dl, VT,
3111 DAG.getNode(ISD::SHL, dl, VT, Value,
3112 DAG.getConstant(Shift,
3113 TLI.getShiftAmountTy())),
3121 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3122 /// used when a memcpy is turned into a memset when the source is a constant
3124 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3125 const TargetLowering &TLI,
3126 std::string &Str, unsigned Offset) {
3127 // Handle vector with all elements zero.
3130 return DAG.getConstant(0, VT);
3131 unsigned NumElts = VT.getVectorNumElements();
3132 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3133 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3135 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts)));
3138 assert(!VT.isVector() && "Can't handle vector type here!");
3139 unsigned NumBits = VT.getSizeInBits();
3140 unsigned MSB = NumBits / 8;
3142 if (TLI.isLittleEndian())
3143 Offset = Offset + MSB - 1;
3144 for (unsigned i = 0; i != MSB; ++i) {
3145 Val = (Val << 8) | (unsigned char)Str[Offset];
3146 Offset += TLI.isLittleEndian() ? -1 : 1;
3148 return DAG.getConstant(Val, VT);
3151 /// getMemBasePlusOffset - Returns base and offset node for the
3153 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3154 SelectionDAG &DAG) {
3155 EVT VT = Base.getValueType();
3156 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3157 VT, Base, DAG.getConstant(Offset, VT));
3160 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3162 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3163 unsigned SrcDelta = 0;
3164 GlobalAddressSDNode *G = NULL;
3165 if (Src.getOpcode() == ISD::GlobalAddress)
3166 G = cast<GlobalAddressSDNode>(Src);
3167 else if (Src.getOpcode() == ISD::ADD &&
3168 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3169 Src.getOperand(1).getOpcode() == ISD::Constant) {
3170 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3171 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3176 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3177 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3183 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3184 /// to replace the memset / memcpy is below the threshold. It also returns the
3185 /// types of the sequence of memory ops to perform memset / memcpy.
3187 bool MeetsMaxMemopRequirement(std::vector<EVT> &MemOps,
3188 SDValue Dst, SDValue Src,
3189 unsigned Limit, uint64_t Size, unsigned &Align,
3190 std::string &Str, bool &isSrcStr,
3192 const TargetLowering &TLI) {
3193 isSrcStr = isMemSrcFromString(Src, Str);
3194 bool isSrcConst = isa<ConstantSDNode>(Src);
3195 EVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
3196 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses(VT);
3197 if (VT != MVT::Other) {
3198 const Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3199 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3200 // If source is a string constant, this will require an unaligned load.
3201 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3202 if (Dst.getOpcode() != ISD::FrameIndex) {
3203 // Can't change destination alignment. It requires a unaligned store.
3207 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3208 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3209 if (MFI->isFixedObjectIndex(FI)) {
3210 // Can't change destination alignment. It requires a unaligned store.
3214 // Give the stack frame object a larger alignment if needed.
3215 if (MFI->getObjectAlignment(FI) < NewAlign)
3216 MFI->setObjectAlignment(FI, NewAlign);
3223 if (VT == MVT::Other) {
3224 if (TLI.allowsUnalignedMemoryAccesses(MVT::i64)) {
3227 switch (Align & 7) {
3228 case 0: VT = MVT::i64; break;
3229 case 4: VT = MVT::i32; break;
3230 case 2: VT = MVT::i16; break;
3231 default: VT = MVT::i8; break;
3236 while (!TLI.isTypeLegal(LVT))
3237 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3238 assert(LVT.isInteger());
3244 unsigned NumMemOps = 0;
3246 unsigned VTSize = VT.getSizeInBits() / 8;
3247 while (VTSize > Size) {
3248 // For now, only use non-vector load / store's for the left-over pieces.
3249 if (VT.isVector()) {
3251 while (!TLI.isTypeLegal(VT))
3252 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3253 VTSize = VT.getSizeInBits() / 8;
3255 // This can result in a type that is not legal on the target, e.g.
3256 // 1 or 2 bytes on PPC.
3257 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3262 if (++NumMemOps > Limit)
3264 MemOps.push_back(VT);
3271 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3272 SDValue Chain, SDValue Dst,
3273 SDValue Src, uint64_t Size,
3274 unsigned Align, bool AlwaysInline,
3275 const Value *DstSV, uint64_t DstSVOff,
3276 const Value *SrcSV, uint64_t SrcSVOff){
3277 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3279 // Expand memcpy to a series of load and store ops if the size operand falls
3280 // below a certain threshold.
3281 std::vector<EVT> MemOps;
3282 uint64_t Limit = -1ULL;
3284 Limit = TLI.getMaxStoresPerMemcpy();
3285 unsigned DstAlign = Align; // Destination alignment can change.
3288 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3289 Str, CopyFromStr, DAG, TLI))
3293 bool isZeroStr = CopyFromStr && Str.empty();
3294 SmallVector<SDValue, 8> OutChains;
3295 unsigned NumMemOps = MemOps.size();
3296 uint64_t SrcOff = 0, DstOff = 0;
3297 for (unsigned i = 0; i != NumMemOps; ++i) {
3299 unsigned VTSize = VT.getSizeInBits() / 8;
3300 SDValue Value, Store;
3302 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3303 // It's unlikely a store of a vector immediate can be done in a single
3304 // instruction. It would require a load from a constantpool first.
3305 // We also handle store a vector with all zero's.
3306 // FIXME: Handle other cases where store of vector immediate is done in
3307 // a single instruction.
3308 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3309 Store = DAG.getStore(Chain, dl, Value,
3310 getMemBasePlusOffset(Dst, DstOff, DAG),
3311 DstSV, DstSVOff + DstOff, false, false, DstAlign);
3313 // The type might not be legal for the target. This should only happen
3314 // if the type is smaller than a legal type, as on PPC, so the right
3315 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3316 // to Load/Store if NVT==VT.
3317 // FIXME does the case above also need this?
3318 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3319 assert(NVT.bitsGE(VT));
3320 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3321 getMemBasePlusOffset(Src, SrcOff, DAG),
3322 SrcSV, SrcSVOff + SrcOff, VT, false, false, Align);
3323 Store = DAG.getTruncStore(Chain, dl, Value,
3324 getMemBasePlusOffset(Dst, DstOff, DAG),
3325 DstSV, DstSVOff + DstOff, VT, false, false,
3328 OutChains.push_back(Store);
3333 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3334 &OutChains[0], OutChains.size());
3337 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3338 SDValue Chain, SDValue Dst,
3339 SDValue Src, uint64_t Size,
3340 unsigned Align, bool AlwaysInline,
3341 const Value *DstSV, uint64_t DstSVOff,
3342 const Value *SrcSV, uint64_t SrcSVOff){
3343 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3345 // Expand memmove to a series of load and store ops if the size operand falls
3346 // below a certain threshold.
3347 std::vector<EVT> MemOps;
3348 uint64_t Limit = -1ULL;
3350 Limit = TLI.getMaxStoresPerMemmove();
3351 unsigned DstAlign = Align; // Destination alignment can change.
3354 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3355 Str, CopyFromStr, DAG, TLI))
3358 uint64_t SrcOff = 0, DstOff = 0;
3360 SmallVector<SDValue, 8> LoadValues;
3361 SmallVector<SDValue, 8> LoadChains;
3362 SmallVector<SDValue, 8> OutChains;
3363 unsigned NumMemOps = MemOps.size();
3364 for (unsigned i = 0; i < NumMemOps; i++) {
3366 unsigned VTSize = VT.getSizeInBits() / 8;
3367 SDValue Value, Store;
3369 Value = DAG.getLoad(VT, dl, Chain,
3370 getMemBasePlusOffset(Src, SrcOff, DAG),
3371 SrcSV, SrcSVOff + SrcOff, false, false, Align);
3372 LoadValues.push_back(Value);
3373 LoadChains.push_back(Value.getValue(1));
3376 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3377 &LoadChains[0], LoadChains.size());
3379 for (unsigned i = 0; i < NumMemOps; i++) {
3381 unsigned VTSize = VT.getSizeInBits() / 8;
3382 SDValue Value, Store;
3384 Store = DAG.getStore(Chain, dl, LoadValues[i],
3385 getMemBasePlusOffset(Dst, DstOff, DAG),
3386 DstSV, DstSVOff + DstOff, false, false, DstAlign);
3387 OutChains.push_back(Store);
3391 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3392 &OutChains[0], OutChains.size());
3395 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3396 SDValue Chain, SDValue Dst,
3397 SDValue Src, uint64_t Size,
3399 const Value *DstSV, uint64_t DstSVOff) {
3400 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3402 // Expand memset to a series of load/store ops if the size operand
3403 // falls below a certain threshold.
3404 std::vector<EVT> MemOps;
3407 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3408 Size, Align, Str, CopyFromStr, DAG, TLI))
3411 SmallVector<SDValue, 8> OutChains;
3412 uint64_t DstOff = 0;
3414 unsigned NumMemOps = MemOps.size();
3415 for (unsigned i = 0; i < NumMemOps; i++) {
3417 unsigned VTSize = VT.getSizeInBits() / 8;
3418 SDValue Value = getMemsetValue(Src, VT, DAG, dl);
3419 SDValue Store = DAG.getStore(Chain, dl, Value,
3420 getMemBasePlusOffset(Dst, DstOff, DAG),
3421 DstSV, DstSVOff + DstOff, false, false, 0);
3422 OutChains.push_back(Store);
3426 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3427 &OutChains[0], OutChains.size());
3430 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3431 SDValue Src, SDValue Size,
3432 unsigned Align, bool AlwaysInline,
3433 const Value *DstSV, uint64_t DstSVOff,
3434 const Value *SrcSV, uint64_t SrcSVOff) {
3436 // Check to see if we should lower the memcpy to loads and stores first.
3437 // For cases within the target-specified limits, this is the best choice.
3438 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3440 // Memcpy with size zero? Just return the original chain.
3441 if (ConstantSize->isNullValue())
3445 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3446 ConstantSize->getZExtValue(),
3447 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3448 if (Result.getNode())
3452 // Then check to see if we should lower the memcpy with target-specific
3453 // code. If the target chooses to do this, this is the next best.
3455 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3457 DstSV, DstSVOff, SrcSV, SrcSVOff);
3458 if (Result.getNode())
3461 // If we really need inline code and the target declined to provide it,
3462 // use a (potentially long) sequence of loads and stores.
3464 assert(ConstantSize && "AlwaysInline requires a constant size!");
3465 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3466 ConstantSize->getZExtValue(), Align, true,
3467 DstSV, DstSVOff, SrcSV, SrcSVOff);
3470 // Emit a library call.
3471 TargetLowering::ArgListTy Args;
3472 TargetLowering::ArgListEntry Entry;
3473 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3474 Entry.Node = Dst; Args.push_back(Entry);
3475 Entry.Node = Src; Args.push_back(Entry);
3476 Entry.Node = Size; Args.push_back(Entry);
3477 // FIXME: pass in DebugLoc
3478 std::pair<SDValue,SDValue> CallResult =
3479 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3480 false, false, false, false, 0,
3481 TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3482 /*isReturnValueUsed=*/false,
3483 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3484 TLI.getPointerTy()),
3486 return CallResult.second;
3489 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3490 SDValue Src, SDValue Size,
3492 const Value *DstSV, uint64_t DstSVOff,
3493 const Value *SrcSV, uint64_t SrcSVOff) {
3495 // Check to see if we should lower the memmove to loads and stores first.
3496 // For cases within the target-specified limits, this is the best choice.
3497 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3499 // Memmove with size zero? Just return the original chain.
3500 if (ConstantSize->isNullValue())
3504 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3505 ConstantSize->getZExtValue(),
3506 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3507 if (Result.getNode())
3511 // Then check to see if we should lower the memmove with target-specific
3512 // code. If the target chooses to do this, this is the next best.
3514 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
3515 DstSV, DstSVOff, SrcSV, SrcSVOff);
3516 if (Result.getNode())
3519 // Emit a library call.
3520 TargetLowering::ArgListTy Args;
3521 TargetLowering::ArgListEntry Entry;
3522 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3523 Entry.Node = Dst; Args.push_back(Entry);
3524 Entry.Node = Src; Args.push_back(Entry);
3525 Entry.Node = Size; Args.push_back(Entry);
3526 // FIXME: pass in DebugLoc
3527 std::pair<SDValue,SDValue> CallResult =
3528 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3529 false, false, false, false, 0,
3530 TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3531 /*isReturnValueUsed=*/false,
3532 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3533 TLI.getPointerTy()),
3535 return CallResult.second;
3538 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3539 SDValue Src, SDValue Size,
3541 const Value *DstSV, uint64_t DstSVOff) {
3543 // Check to see if we should lower the memset to stores first.
3544 // For cases within the target-specified limits, this is the best choice.
3545 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3547 // Memset with size zero? Just return the original chain.
3548 if (ConstantSize->isNullValue())
3552 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3553 Align, DstSV, DstSVOff);
3554 if (Result.getNode())
3558 // Then check to see if we should lower the memset with target-specific
3559 // code. If the target chooses to do this, this is the next best.
3561 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
3563 if (Result.getNode())
3566 // Emit a library call.
3567 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3568 TargetLowering::ArgListTy Args;
3569 TargetLowering::ArgListEntry Entry;
3570 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3571 Args.push_back(Entry);
3572 // Extend or truncate the argument to be an i32 value for the call.
3573 if (Src.getValueType().bitsGT(MVT::i32))
3574 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3576 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3578 Entry.Ty = Type::getInt32Ty(*getContext());
3579 Entry.isSExt = true;
3580 Args.push_back(Entry);
3582 Entry.Ty = IntPtrTy;
3583 Entry.isSExt = false;
3584 Args.push_back(Entry);
3585 // FIXME: pass in DebugLoc
3586 std::pair<SDValue,SDValue> CallResult =
3587 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3588 false, false, false, false, 0,
3589 TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3590 /*isReturnValueUsed=*/false,
3591 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3592 TLI.getPointerTy()),
3594 return CallResult.second;
3597 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3599 SDValue Ptr, SDValue Cmp,
3600 SDValue Swp, const Value* PtrVal,
3601 unsigned Alignment) {
3602 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3603 Alignment = getEVTAlignment(MemVT);
3605 // Check if the memory reference references a frame index
3607 if (const FrameIndexSDNode *FI =
3608 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3609 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3611 MachineFunction &MF = getMachineFunction();
3612 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3614 // For now, atomics are considered to be volatile always.
3615 Flags |= MachineMemOperand::MOVolatile;
3617 MachineMemOperand *MMO =
3618 MF.getMachineMemOperand(PtrVal, Flags, 0,
3619 MemVT.getStoreSize(), Alignment);
3621 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3624 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3626 SDValue Ptr, SDValue Cmp,
3627 SDValue Swp, MachineMemOperand *MMO) {
3628 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3629 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3631 EVT VT = Cmp.getValueType();
3633 SDVTList VTs = getVTList(VT, MVT::Other);
3634 FoldingSetNodeID ID;
3635 ID.AddInteger(MemVT.getRawBits());
3636 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3637 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3639 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3640 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3641 return SDValue(E, 0);
3643 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain,
3644 Ptr, Cmp, Swp, MMO);
3645 CSEMap.InsertNode(N, IP);
3646 AllNodes.push_back(N);
3647 return SDValue(N, 0);
3650 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3652 SDValue Ptr, SDValue Val,
3653 const Value* PtrVal,
3654 unsigned Alignment) {
3655 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3656 Alignment = getEVTAlignment(MemVT);
3658 // Check if the memory reference references a frame index
3660 if (const FrameIndexSDNode *FI =
3661 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3662 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3664 MachineFunction &MF = getMachineFunction();
3665 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3667 // For now, atomics are considered to be volatile always.
3668 Flags |= MachineMemOperand::MOVolatile;
3670 MachineMemOperand *MMO =
3671 MF.getMachineMemOperand(PtrVal, Flags, 0,
3672 MemVT.getStoreSize(), Alignment);
3674 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
3677 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3679 SDValue Ptr, SDValue Val,
3680 MachineMemOperand *MMO) {
3681 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3682 Opcode == ISD::ATOMIC_LOAD_SUB ||
3683 Opcode == ISD::ATOMIC_LOAD_AND ||
3684 Opcode == ISD::ATOMIC_LOAD_OR ||
3685 Opcode == ISD::ATOMIC_LOAD_XOR ||
3686 Opcode == ISD::ATOMIC_LOAD_NAND ||
3687 Opcode == ISD::ATOMIC_LOAD_MIN ||
3688 Opcode == ISD::ATOMIC_LOAD_MAX ||
3689 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3690 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3691 Opcode == ISD::ATOMIC_SWAP) &&
3692 "Invalid Atomic Op");
3694 EVT VT = Val.getValueType();
3696 SDVTList VTs = getVTList(VT, MVT::Other);
3697 FoldingSetNodeID ID;
3698 ID.AddInteger(MemVT.getRawBits());
3699 SDValue Ops[] = {Chain, Ptr, Val};
3700 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3702 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3703 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3704 return SDValue(E, 0);
3706 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain,
3708 CSEMap.InsertNode(N, IP);
3709 AllNodes.push_back(N);
3710 return SDValue(N, 0);
3713 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3714 /// Allowed to return something different (and simpler) if Simplify is true.
3715 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3720 SmallVector<EVT, 4> VTs;
3721 VTs.reserve(NumOps);
3722 for (unsigned i = 0; i < NumOps; ++i)
3723 VTs.push_back(Ops[i].getValueType());
3724 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3729 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3730 const EVT *VTs, unsigned NumVTs,
3731 const SDValue *Ops, unsigned NumOps,
3732 EVT MemVT, const Value *srcValue, int SVOff,
3733 unsigned Align, bool Vol,
3734 bool ReadMem, bool WriteMem) {
3735 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3736 MemVT, srcValue, SVOff, Align, Vol,
3741 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3742 const SDValue *Ops, unsigned NumOps,
3743 EVT MemVT, const Value *srcValue, int SVOff,
3744 unsigned Align, bool Vol,
3745 bool ReadMem, bool WriteMem) {
3746 if (Align == 0) // Ensure that codegen never sees alignment 0
3747 Align = getEVTAlignment(MemVT);
3749 MachineFunction &MF = getMachineFunction();
3752 Flags |= MachineMemOperand::MOStore;
3754 Flags |= MachineMemOperand::MOLoad;
3756 Flags |= MachineMemOperand::MOVolatile;
3757 MachineMemOperand *MMO =
3758 MF.getMachineMemOperand(srcValue, Flags, SVOff,
3759 MemVT.getStoreSize(), Align);
3761 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3765 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3766 const SDValue *Ops, unsigned NumOps,
3767 EVT MemVT, MachineMemOperand *MMO) {
3768 assert((Opcode == ISD::INTRINSIC_VOID ||
3769 Opcode == ISD::INTRINSIC_W_CHAIN ||
3770 (Opcode <= INT_MAX &&
3771 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
3772 "Opcode is not a memory-accessing opcode!");
3774 // Memoize the node unless it returns a flag.
3775 MemIntrinsicSDNode *N;
3776 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3777 FoldingSetNodeID ID;
3778 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3780 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3781 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
3782 return SDValue(E, 0);
3785 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps,
3787 CSEMap.InsertNode(N, IP);
3789 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps,
3792 AllNodes.push_back(N);
3793 return SDValue(N, 0);
3797 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3798 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3799 SDValue Ptr, SDValue Offset,
3800 const Value *SV, int SVOffset, EVT MemVT,
3801 bool isVolatile, bool isNonTemporal,
3802 unsigned Alignment) {
3803 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3804 Alignment = getEVTAlignment(VT);
3806 // Check if the memory reference references a frame index
3808 if (const FrameIndexSDNode *FI =
3809 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3810 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3812 MachineFunction &MF = getMachineFunction();
3813 unsigned Flags = MachineMemOperand::MOLoad;
3815 Flags |= MachineMemOperand::MOVolatile;
3817 Flags |= MachineMemOperand::MONonTemporal;
3818 MachineMemOperand *MMO =
3819 MF.getMachineMemOperand(SV, Flags, SVOffset,
3820 MemVT.getStoreSize(), Alignment);
3821 return getLoad(AM, dl, ExtType, VT, Chain, Ptr, Offset, MemVT, MMO);
3825 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3826 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3827 SDValue Ptr, SDValue Offset, EVT MemVT,
3828 MachineMemOperand *MMO) {
3830 ExtType = ISD::NON_EXTLOAD;
3831 } else if (ExtType == ISD::NON_EXTLOAD) {
3832 assert(VT == MemVT && "Non-extending load from different memory type!");
3835 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
3836 "Should only be an extending load, not truncating!");
3837 assert(VT.isInteger() == MemVT.isInteger() &&
3838 "Cannot convert from FP to Int or Int -> FP!");
3839 assert(VT.isVector() == MemVT.isVector() &&
3840 "Cannot use trunc store to convert to or from a vector!");
3841 assert((!VT.isVector() ||
3842 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
3843 "Cannot use trunc store to change the number of vector elements!");
3846 bool Indexed = AM != ISD::UNINDEXED;
3847 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3848 "Unindexed load with an offset!");
3850 SDVTList VTs = Indexed ?
3851 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3852 SDValue Ops[] = { Chain, Ptr, Offset };
3853 FoldingSetNodeID ID;
3854 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3855 ID.AddInteger(MemVT.getRawBits());
3856 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
3857 MMO->isNonTemporal()));
3859 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3860 cast<LoadSDNode>(E)->refineAlignment(MMO);
3861 return SDValue(E, 0);
3863 SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl, VTs, AM, ExtType,
3865 CSEMap.InsertNode(N, IP);
3866 AllNodes.push_back(N);
3867 return SDValue(N, 0);
3870 SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
3871 SDValue Chain, SDValue Ptr,
3872 const Value *SV, int SVOffset,
3873 bool isVolatile, bool isNonTemporal,
3874 unsigned Alignment) {
3875 SDValue Undef = getUNDEF(Ptr.getValueType());
3876 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3877 SV, SVOffset, VT, isVolatile, isNonTemporal, Alignment);
3880 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
3881 SDValue Chain, SDValue Ptr,
3883 int SVOffset, EVT MemVT,
3884 bool isVolatile, bool isNonTemporal,
3885 unsigned Alignment) {
3886 SDValue Undef = getUNDEF(Ptr.getValueType());
3887 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3888 SV, SVOffset, MemVT, isVolatile, isNonTemporal, Alignment);
3892 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3893 SDValue Offset, ISD::MemIndexedMode AM) {
3894 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3895 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3896 "Load is already a indexed load!");
3897 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3898 LD->getChain(), Base, Offset, LD->getSrcValue(),
3899 LD->getSrcValueOffset(), LD->getMemoryVT(),
3900 LD->isVolatile(), LD->isNonTemporal(), LD->getAlignment());
3903 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3904 SDValue Ptr, const Value *SV, int SVOffset,
3905 bool isVolatile, bool isNonTemporal,
3906 unsigned Alignment) {
3907 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3908 Alignment = getEVTAlignment(Val.getValueType());
3910 // Check if the memory reference references a frame index
3912 if (const FrameIndexSDNode *FI =
3913 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3914 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3916 MachineFunction &MF = getMachineFunction();
3917 unsigned Flags = MachineMemOperand::MOStore;
3919 Flags |= MachineMemOperand::MOVolatile;
3921 Flags |= MachineMemOperand::MONonTemporal;
3922 MachineMemOperand *MMO =
3923 MF.getMachineMemOperand(SV, Flags, SVOffset,
3924 Val.getValueType().getStoreSize(), Alignment);
3926 return getStore(Chain, dl, Val, Ptr, MMO);
3929 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3930 SDValue Ptr, MachineMemOperand *MMO) {
3931 EVT VT = Val.getValueType();
3932 SDVTList VTs = getVTList(MVT::Other);
3933 SDValue Undef = getUNDEF(Ptr.getValueType());
3934 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3935 FoldingSetNodeID ID;
3936 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3937 ID.AddInteger(VT.getRawBits());
3938 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
3939 MMO->isNonTemporal()));
3941 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3942 cast<StoreSDNode>(E)->refineAlignment(MMO);
3943 return SDValue(E, 0);
3945 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED,
3947 CSEMap.InsertNode(N, IP);
3948 AllNodes.push_back(N);
3949 return SDValue(N, 0);
3952 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3953 SDValue Ptr, const Value *SV,
3954 int SVOffset, EVT SVT,
3955 bool isVolatile, bool isNonTemporal,
3956 unsigned Alignment) {
3957 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3958 Alignment = getEVTAlignment(SVT);
3960 // Check if the memory reference references a frame index
3962 if (const FrameIndexSDNode *FI =
3963 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3964 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3966 MachineFunction &MF = getMachineFunction();
3967 unsigned Flags = MachineMemOperand::MOStore;
3969 Flags |= MachineMemOperand::MOVolatile;
3971 Flags |= MachineMemOperand::MONonTemporal;
3972 MachineMemOperand *MMO =
3973 MF.getMachineMemOperand(SV, Flags, SVOffset, SVT.getStoreSize(), Alignment);
3975 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
3978 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3979 SDValue Ptr, EVT SVT,
3980 MachineMemOperand *MMO) {
3981 EVT VT = Val.getValueType();
3984 return getStore(Chain, dl, Val, Ptr, MMO);
3986 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
3987 "Should only be a truncating store, not extending!");
3988 assert(VT.isInteger() == SVT.isInteger() &&
3989 "Can't do FP-INT conversion!");
3990 assert(VT.isVector() == SVT.isVector() &&
3991 "Cannot use trunc store to convert to or from a vector!");
3992 assert((!VT.isVector() ||
3993 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
3994 "Cannot use trunc store to change the number of vector elements!");
3996 SDVTList VTs = getVTList(MVT::Other);
3997 SDValue Undef = getUNDEF(Ptr.getValueType());
3998 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3999 FoldingSetNodeID ID;
4000 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4001 ID.AddInteger(SVT.getRawBits());
4002 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
4003 MMO->isNonTemporal()));
4005 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4006 cast<StoreSDNode>(E)->refineAlignment(MMO);
4007 return SDValue(E, 0);
4009 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED,
4011 CSEMap.InsertNode(N, IP);
4012 AllNodes.push_back(N);
4013 return SDValue(N, 0);
4017 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
4018 SDValue Offset, ISD::MemIndexedMode AM) {
4019 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4020 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4021 "Store is already a indexed store!");
4022 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4023 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4024 FoldingSetNodeID ID;
4025 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4026 ID.AddInteger(ST->getMemoryVT().getRawBits());
4027 ID.AddInteger(ST->getRawSubclassData());
4029 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4030 return SDValue(E, 0);
4032 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, AM,
4033 ST->isTruncatingStore(),
4035 ST->getMemOperand());
4036 CSEMap.InsertNode(N, IP);
4037 AllNodes.push_back(N);
4038 return SDValue(N, 0);
4041 SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
4042 SDValue Chain, SDValue Ptr,
4044 SDValue Ops[] = { Chain, Ptr, SV };
4045 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
4048 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4049 const SDUse *Ops, unsigned NumOps) {
4051 case 0: return getNode(Opcode, DL, VT);
4052 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4053 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4054 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4058 // Copy from an SDUse array into an SDValue array for use with
4059 // the regular getNode logic.
4060 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4061 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4064 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4065 const SDValue *Ops, unsigned NumOps) {
4067 case 0: return getNode(Opcode, DL, VT);
4068 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4069 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4070 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4076 case ISD::SELECT_CC: {
4077 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4078 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4079 "LHS and RHS of condition must have same type!");
4080 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4081 "True and False arms of SelectCC must have same type!");
4082 assert(Ops[2].getValueType() == VT &&
4083 "select_cc node must be of same type as true and false value!");
4087 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4088 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4089 "LHS/RHS of comparison should match types!");
4096 SDVTList VTs = getVTList(VT);
4098 if (VT != MVT::Flag) {
4099 FoldingSetNodeID ID;
4100 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4103 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4104 return SDValue(E, 0);
4106 N = new (NodeAllocator) SDNode(Opcode, DL, VTs, Ops, NumOps);
4107 CSEMap.InsertNode(N, IP);
4109 N = new (NodeAllocator) SDNode(Opcode, DL, VTs, Ops, NumOps);
4112 AllNodes.push_back(N);
4116 return SDValue(N, 0);
4119 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4120 const std::vector<EVT> &ResultTys,
4121 const SDValue *Ops, unsigned NumOps) {
4122 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4126 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4127 const EVT *VTs, unsigned NumVTs,
4128 const SDValue *Ops, unsigned NumOps) {
4130 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4131 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4134 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4135 const SDValue *Ops, unsigned NumOps) {
4136 if (VTList.NumVTs == 1)
4137 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4141 // FIXME: figure out how to safely handle things like
4142 // int foo(int x) { return 1 << (x & 255); }
4143 // int bar() { return foo(256); }
4144 case ISD::SRA_PARTS:
4145 case ISD::SRL_PARTS:
4146 case ISD::SHL_PARTS:
4147 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4148 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4149 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4150 else if (N3.getOpcode() == ISD::AND)
4151 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4152 // If the and is only masking out bits that cannot effect the shift,
4153 // eliminate the and.
4154 unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
4155 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4156 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4162 // Memoize the node unless it returns a flag.
4164 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4165 FoldingSetNodeID ID;
4166 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4168 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4169 return SDValue(E, 0);
4172 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4173 } else if (NumOps == 2) {
4174 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4175 } else if (NumOps == 3) {
4176 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1],
4179 N = new (NodeAllocator) SDNode(Opcode, DL, VTList, Ops, NumOps);
4181 CSEMap.InsertNode(N, IP);
4184 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4185 } else if (NumOps == 2) {
4186 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4187 } else if (NumOps == 3) {
4188 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1],
4191 N = new (NodeAllocator) SDNode(Opcode, DL, VTList, Ops, NumOps);
4194 AllNodes.push_back(N);
4198 return SDValue(N, 0);
4201 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4202 return getNode(Opcode, DL, VTList, 0, 0);
4205 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4207 SDValue Ops[] = { N1 };
4208 return getNode(Opcode, DL, VTList, Ops, 1);
4211 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4212 SDValue N1, SDValue N2) {
4213 SDValue Ops[] = { N1, N2 };
4214 return getNode(Opcode, DL, VTList, Ops, 2);
4217 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4218 SDValue N1, SDValue N2, SDValue N3) {
4219 SDValue Ops[] = { N1, N2, N3 };
4220 return getNode(Opcode, DL, VTList, Ops, 3);
4223 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4224 SDValue N1, SDValue N2, SDValue N3,
4226 SDValue Ops[] = { N1, N2, N3, N4 };
4227 return getNode(Opcode, DL, VTList, Ops, 4);
4230 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4231 SDValue N1, SDValue N2, SDValue N3,
4232 SDValue N4, SDValue N5) {
4233 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4234 return getNode(Opcode, DL, VTList, Ops, 5);
4237 SDVTList SelectionDAG::getVTList(EVT VT) {
4238 return makeVTList(SDNode::getValueTypeList(VT), 1);
4241 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4242 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4243 E = VTList.rend(); I != E; ++I)
4244 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4247 EVT *Array = Allocator.Allocate<EVT>(2);
4250 SDVTList Result = makeVTList(Array, 2);
4251 VTList.push_back(Result);
4255 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4256 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4257 E = VTList.rend(); I != E; ++I)
4258 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4262 EVT *Array = Allocator.Allocate<EVT>(3);
4266 SDVTList Result = makeVTList(Array, 3);
4267 VTList.push_back(Result);
4271 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4272 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4273 E = VTList.rend(); I != E; ++I)
4274 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4275 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4278 EVT *Array = Allocator.Allocate<EVT>(4);
4283 SDVTList Result = makeVTList(Array, 4);
4284 VTList.push_back(Result);
4288 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4290 case 0: llvm_unreachable("Cannot have nodes without results!");
4291 case 1: return getVTList(VTs[0]);
4292 case 2: return getVTList(VTs[0], VTs[1]);
4293 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4294 case 4: return getVTList(VTs[0], VTs[1], VTs[2], VTs[3]);
4298 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4299 E = VTList.rend(); I != E; ++I) {
4300 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4303 bool NoMatch = false;
4304 for (unsigned i = 2; i != NumVTs; ++i)
4305 if (VTs[i] != I->VTs[i]) {
4313 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4314 std::copy(VTs, VTs+NumVTs, Array);
4315 SDVTList Result = makeVTList(Array, NumVTs);
4316 VTList.push_back(Result);
4321 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4322 /// specified operands. If the resultant node already exists in the DAG,
4323 /// this does not modify the specified node, instead it returns the node that
4324 /// already exists. If the resultant node does not exist in the DAG, the
4325 /// input node is returned. As a degenerate case, if you specify the same
4326 /// input operands as the node already has, the input node is returned.
4327 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4328 SDNode *N = InN.getNode();
4329 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4331 // Check to see if there is no change.
4332 if (Op == N->getOperand(0)) return InN;
4334 // See if the modified node already exists.
4335 void *InsertPos = 0;
4336 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4337 return SDValue(Existing, InN.getResNo());
4339 // Nope it doesn't. Remove the node from its current place in the maps.
4341 if (!RemoveNodeFromCSEMaps(N))
4344 // Now we update the operands.
4345 N->OperandList[0].set(Op);
4347 // If this gets put into a CSE map, add it.
4348 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4352 SDValue SelectionDAG::
4353 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4354 SDNode *N = InN.getNode();
4355 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4357 // Check to see if there is no change.
4358 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4359 return InN; // No operands changed, just return the input node.
4361 // See if the modified node already exists.
4362 void *InsertPos = 0;
4363 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4364 return SDValue(Existing, InN.getResNo());
4366 // Nope it doesn't. Remove the node from its current place in the maps.
4368 if (!RemoveNodeFromCSEMaps(N))
4371 // Now we update the operands.
4372 if (N->OperandList[0] != Op1)
4373 N->OperandList[0].set(Op1);
4374 if (N->OperandList[1] != Op2)
4375 N->OperandList[1].set(Op2);
4377 // If this gets put into a CSE map, add it.
4378 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4382 SDValue SelectionDAG::
4383 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4384 SDValue Ops[] = { Op1, Op2, Op3 };
4385 return UpdateNodeOperands(N, Ops, 3);
4388 SDValue SelectionDAG::
4389 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4390 SDValue Op3, SDValue Op4) {
4391 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4392 return UpdateNodeOperands(N, Ops, 4);
4395 SDValue SelectionDAG::
4396 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4397 SDValue Op3, SDValue Op4, SDValue Op5) {
4398 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4399 return UpdateNodeOperands(N, Ops, 5);
4402 SDValue SelectionDAG::
4403 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4404 SDNode *N = InN.getNode();
4405 assert(N->getNumOperands() == NumOps &&
4406 "Update with wrong number of operands");
4408 // Check to see if there is no change.
4409 bool AnyChange = false;
4410 for (unsigned i = 0; i != NumOps; ++i) {
4411 if (Ops[i] != N->getOperand(i)) {
4417 // No operands changed, just return the input node.
4418 if (!AnyChange) return InN;
4420 // See if the modified node already exists.
4421 void *InsertPos = 0;
4422 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4423 return SDValue(Existing, InN.getResNo());
4425 // Nope it doesn't. Remove the node from its current place in the maps.
4427 if (!RemoveNodeFromCSEMaps(N))
4430 // Now we update the operands.
4431 for (unsigned i = 0; i != NumOps; ++i)
4432 if (N->OperandList[i] != Ops[i])
4433 N->OperandList[i].set(Ops[i]);
4435 // If this gets put into a CSE map, add it.
4436 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4440 /// DropOperands - Release the operands and set this node to have
4442 void SDNode::DropOperands() {
4443 // Unlike the code in MorphNodeTo that does this, we don't need to
4444 // watch for dead nodes here.
4445 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4451 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4454 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4456 SDVTList VTs = getVTList(VT);
4457 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4460 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4461 EVT VT, SDValue Op1) {
4462 SDVTList VTs = getVTList(VT);
4463 SDValue Ops[] = { Op1 };
4464 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4467 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4468 EVT VT, SDValue Op1,
4470 SDVTList VTs = getVTList(VT);
4471 SDValue Ops[] = { Op1, Op2 };
4472 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4475 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4476 EVT VT, SDValue Op1,
4477 SDValue Op2, SDValue Op3) {
4478 SDVTList VTs = getVTList(VT);
4479 SDValue Ops[] = { Op1, Op2, Op3 };
4480 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4483 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4484 EVT VT, const SDValue *Ops,
4486 SDVTList VTs = getVTList(VT);
4487 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4490 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4491 EVT VT1, EVT VT2, const SDValue *Ops,
4493 SDVTList VTs = getVTList(VT1, VT2);
4494 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4497 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4499 SDVTList VTs = getVTList(VT1, VT2);
4500 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4503 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4504 EVT VT1, EVT VT2, EVT VT3,
4505 const SDValue *Ops, unsigned NumOps) {
4506 SDVTList VTs = getVTList(VT1, VT2, VT3);
4507 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4510 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4511 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4512 const SDValue *Ops, unsigned NumOps) {
4513 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4514 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4517 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4520 SDVTList VTs = getVTList(VT1, VT2);
4521 SDValue Ops[] = { Op1 };
4522 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4525 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4527 SDValue Op1, SDValue Op2) {
4528 SDVTList VTs = getVTList(VT1, VT2);
4529 SDValue Ops[] = { Op1, Op2 };
4530 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4533 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4535 SDValue Op1, SDValue Op2,
4537 SDVTList VTs = getVTList(VT1, VT2);
4538 SDValue Ops[] = { Op1, Op2, Op3 };
4539 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4542 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4543 EVT VT1, EVT VT2, EVT VT3,
4544 SDValue Op1, SDValue Op2,
4546 SDVTList VTs = getVTList(VT1, VT2, VT3);
4547 SDValue Ops[] = { Op1, Op2, Op3 };
4548 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4551 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4552 SDVTList VTs, const SDValue *Ops,
4554 N = MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4555 // Reset the NodeID to -1.
4560 /// MorphNodeTo - This *mutates* the specified node to have the specified
4561 /// return type, opcode, and operands.
4563 /// Note that MorphNodeTo returns the resultant node. If there is already a
4564 /// node of the specified opcode and operands, it returns that node instead of
4565 /// the current one. Note that the DebugLoc need not be the same.
4567 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4568 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4569 /// node, and because it doesn't require CSE recalculation for any of
4570 /// the node's users.
4572 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4573 SDVTList VTs, const SDValue *Ops,
4575 // If an identical node already exists, use it.
4577 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4578 FoldingSetNodeID ID;
4579 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4580 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4584 if (!RemoveNodeFromCSEMaps(N))
4587 // Start the morphing.
4589 N->ValueList = VTs.VTs;
4590 N->NumValues = VTs.NumVTs;
4592 // Clear the operands list, updating used nodes to remove this from their
4593 // use list. Keep track of any operands that become dead as a result.
4594 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4595 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4597 SDNode *Used = Use.getNode();
4599 if (Used->use_empty())
4600 DeadNodeSet.insert(Used);
4603 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
4604 // Initialize the memory references information.
4605 MN->setMemRefs(0, 0);
4606 // If NumOps is larger than the # of operands we can have in a
4607 // MachineSDNode, reallocate the operand list.
4608 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
4609 if (MN->OperandsNeedDelete)
4610 delete[] MN->OperandList;
4611 if (NumOps > array_lengthof(MN->LocalOperands))
4612 // We're creating a final node that will live unmorphed for the
4613 // remainder of the current SelectionDAG iteration, so we can allocate
4614 // the operands directly out of a pool with no recycling metadata.
4615 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4618 MN->InitOperands(MN->LocalOperands, Ops, NumOps);
4619 MN->OperandsNeedDelete = false;
4621 MN->InitOperands(MN->OperandList, Ops, NumOps);
4623 // If NumOps is larger than the # of operands we currently have, reallocate
4624 // the operand list.
4625 if (NumOps > N->NumOperands) {
4626 if (N->OperandsNeedDelete)
4627 delete[] N->OperandList;
4628 N->InitOperands(new SDUse[NumOps], Ops, NumOps);
4629 N->OperandsNeedDelete = true;
4631 N->InitOperands(N->OperandList, Ops, NumOps);
4634 // Delete any nodes that are still dead after adding the uses for the
4636 if (!DeadNodeSet.empty()) {
4637 SmallVector<SDNode *, 16> DeadNodes;
4638 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4639 E = DeadNodeSet.end(); I != E; ++I)
4640 if ((*I)->use_empty())
4641 DeadNodes.push_back(*I);
4642 RemoveDeadNodes(DeadNodes);
4646 CSEMap.InsertNode(N, IP); // Memoize the new node.
4651 /// getMachineNode - These are used for target selectors to create a new node
4652 /// with specified return type(s), MachineInstr opcode, and operands.
4654 /// Note that getMachineNode returns the resultant node. If there is already a
4655 /// node of the specified opcode and operands, it returns that node instead of
4656 /// the current one.
4658 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
4659 SDVTList VTs = getVTList(VT);
4660 return getMachineNode(Opcode, dl, VTs, 0, 0);
4664 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
4665 SDVTList VTs = getVTList(VT);
4666 SDValue Ops[] = { Op1 };
4667 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4671 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4672 SDValue Op1, SDValue Op2) {
4673 SDVTList VTs = getVTList(VT);
4674 SDValue Ops[] = { Op1, Op2 };
4675 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4679 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4680 SDValue Op1, SDValue Op2, SDValue Op3) {
4681 SDVTList VTs = getVTList(VT);
4682 SDValue Ops[] = { Op1, Op2, Op3 };
4683 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4687 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4688 const SDValue *Ops, unsigned NumOps) {
4689 SDVTList VTs = getVTList(VT);
4690 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4694 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
4695 SDVTList VTs = getVTList(VT1, VT2);
4696 return getMachineNode(Opcode, dl, VTs, 0, 0);
4700 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4701 EVT VT1, EVT VT2, SDValue Op1) {
4702 SDVTList VTs = getVTList(VT1, VT2);
4703 SDValue Ops[] = { Op1 };
4704 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4708 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4709 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
4710 SDVTList VTs = getVTList(VT1, VT2);
4711 SDValue Ops[] = { Op1, Op2 };
4712 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4716 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4717 EVT VT1, EVT VT2, SDValue Op1,
4718 SDValue Op2, SDValue Op3) {
4719 SDVTList VTs = getVTList(VT1, VT2);
4720 SDValue Ops[] = { Op1, Op2, Op3 };
4721 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4725 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4727 const SDValue *Ops, unsigned NumOps) {
4728 SDVTList VTs = getVTList(VT1, VT2);
4729 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4733 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4734 EVT VT1, EVT VT2, EVT VT3,
4735 SDValue Op1, SDValue Op2) {
4736 SDVTList VTs = getVTList(VT1, VT2, VT3);
4737 SDValue Ops[] = { Op1, Op2 };
4738 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4742 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4743 EVT VT1, EVT VT2, EVT VT3,
4744 SDValue Op1, SDValue Op2, SDValue Op3) {
4745 SDVTList VTs = getVTList(VT1, VT2, VT3);
4746 SDValue Ops[] = { Op1, Op2, Op3 };
4747 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4751 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4752 EVT VT1, EVT VT2, EVT VT3,
4753 const SDValue *Ops, unsigned NumOps) {
4754 SDVTList VTs = getVTList(VT1, VT2, VT3);
4755 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4759 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4760 EVT VT2, EVT VT3, EVT VT4,
4761 const SDValue *Ops, unsigned NumOps) {
4762 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4763 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4767 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4768 const std::vector<EVT> &ResultTys,
4769 const SDValue *Ops, unsigned NumOps) {
4770 SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
4771 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4775 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
4776 const SDValue *Ops, unsigned NumOps) {
4777 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Flag;
4782 FoldingSetNodeID ID;
4783 AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
4785 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4786 return cast<MachineSDNode>(E);
4789 // Allocate a new MachineSDNode.
4790 N = new (NodeAllocator) MachineSDNode(~Opcode, DL, VTs);
4792 // Initialize the operands list.
4793 if (NumOps > array_lengthof(N->LocalOperands))
4794 // We're creating a final node that will live unmorphed for the
4795 // remainder of the current SelectionDAG iteration, so we can allocate
4796 // the operands directly out of a pool with no recycling metadata.
4797 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4800 N->InitOperands(N->LocalOperands, Ops, NumOps);
4801 N->OperandsNeedDelete = false;
4804 CSEMap.InsertNode(N, IP);
4806 AllNodes.push_back(N);
4813 /// getTargetExtractSubreg - A convenience function for creating
4814 /// TargetOpcode::EXTRACT_SUBREG nodes.
4816 SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
4818 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4819 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
4820 VT, Operand, SRIdxVal);
4821 return SDValue(Subreg, 0);
4824 /// getTargetInsertSubreg - A convenience function for creating
4825 /// TargetOpcode::INSERT_SUBREG nodes.
4827 SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
4828 SDValue Operand, SDValue Subreg) {
4829 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4830 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
4831 VT, Operand, Subreg, SRIdxVal);
4832 return SDValue(Result, 0);
4835 /// getNodeIfExists - Get the specified node if it's already available, or
4836 /// else return NULL.
4837 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4838 const SDValue *Ops, unsigned NumOps) {
4839 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4840 FoldingSetNodeID ID;
4841 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4843 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4851 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
4852 /// pointed to by a use iterator is deleted, increment the use iterator
4853 /// so that it doesn't dangle.
4855 /// This class also manages a "downlink" DAGUpdateListener, to forward
4856 /// messages to ReplaceAllUsesWith's callers.
4858 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
4859 SelectionDAG::DAGUpdateListener *DownLink;
4860 SDNode::use_iterator &UI;
4861 SDNode::use_iterator &UE;
4863 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4864 // Increment the iterator as needed.
4865 while (UI != UE && N == *UI)
4868 // Then forward the message.
4869 if (DownLink) DownLink->NodeDeleted(N, E);
4872 virtual void NodeUpdated(SDNode *N) {
4873 // Just forward the message.
4874 if (DownLink) DownLink->NodeUpdated(N);
4878 RAUWUpdateListener(SelectionDAG::DAGUpdateListener *dl,
4879 SDNode::use_iterator &ui,
4880 SDNode::use_iterator &ue)
4881 : DownLink(dl), UI(ui), UE(ue) {}
4886 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4887 /// This can cause recursive merging of nodes in the DAG.
4889 /// This version assumes From has a single result value.
4891 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4892 DAGUpdateListener *UpdateListener) {
4893 SDNode *From = FromN.getNode();
4894 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4895 "Cannot replace with this method!");
4896 assert(From != To.getNode() && "Cannot replace uses of with self");
4898 // Iterate over all the existing uses of From. New uses will be added
4899 // to the beginning of the use list, which we avoid visiting.
4900 // This specifically avoids visiting uses of From that arise while the
4901 // replacement is happening, because any such uses would be the result
4902 // of CSE: If an existing node looks like From after one of its operands
4903 // is replaced by To, we don't want to replace of all its users with To
4904 // too. See PR3018 for more info.
4905 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4906 RAUWUpdateListener Listener(UpdateListener, UI, UE);
4910 // This node is about to morph, remove its old self from the CSE maps.
4911 RemoveNodeFromCSEMaps(User);
4913 // A user can appear in a use list multiple times, and when this
4914 // happens the uses are usually next to each other in the list.
4915 // To help reduce the number of CSE recomputations, process all
4916 // the uses of this user that we can find this way.
4918 SDUse &Use = UI.getUse();
4921 } while (UI != UE && *UI == User);
4923 // Now that we have modified User, add it back to the CSE maps. If it
4924 // already exists there, recursively merge the results together.
4925 AddModifiedNodeToCSEMaps(User, &Listener);
4929 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4930 /// This can cause recursive merging of nodes in the DAG.
4932 /// This version assumes that for each value of From, there is a
4933 /// corresponding value in To in the same position with the same type.
4935 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4936 DAGUpdateListener *UpdateListener) {
4938 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
4939 assert((!From->hasAnyUseOfValue(i) ||
4940 From->getValueType(i) == To->getValueType(i)) &&
4941 "Cannot use this version of ReplaceAllUsesWith!");
4944 // Handle the trivial case.
4948 // Iterate over just the existing users of From. See the comments in
4949 // the ReplaceAllUsesWith above.
4950 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4951 RAUWUpdateListener Listener(UpdateListener, UI, UE);
4955 // This node is about to morph, remove its old self from the CSE maps.
4956 RemoveNodeFromCSEMaps(User);
4958 // A user can appear in a use list multiple times, and when this
4959 // happens the uses are usually next to each other in the list.
4960 // To help reduce the number of CSE recomputations, process all
4961 // the uses of this user that we can find this way.
4963 SDUse &Use = UI.getUse();
4966 } while (UI != UE && *UI == User);
4968 // Now that we have modified User, add it back to the CSE maps. If it
4969 // already exists there, recursively merge the results together.
4970 AddModifiedNodeToCSEMaps(User, &Listener);
4974 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4975 /// This can cause recursive merging of nodes in the DAG.
4977 /// This version can replace From with any result values. To must match the
4978 /// number and types of values returned by From.
4979 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4981 DAGUpdateListener *UpdateListener) {
4982 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4983 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4985 // Iterate over just the existing users of From. See the comments in
4986 // the ReplaceAllUsesWith above.
4987 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4988 RAUWUpdateListener Listener(UpdateListener, UI, UE);
4992 // This node is about to morph, remove its old self from the CSE maps.
4993 RemoveNodeFromCSEMaps(User);
4995 // A user can appear in a use list multiple times, and when this
4996 // happens the uses are usually next to each other in the list.
4997 // To help reduce the number of CSE recomputations, process all
4998 // the uses of this user that we can find this way.
5000 SDUse &Use = UI.getUse();
5001 const SDValue &ToOp = To[Use.getResNo()];
5004 } while (UI != UE && *UI == User);
5006 // Now that we have modified User, add it back to the CSE maps. If it
5007 // already exists there, recursively merge the results together.
5008 AddModifiedNodeToCSEMaps(User, &Listener);
5012 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5013 /// uses of other values produced by From.getNode() alone. The Deleted
5014 /// vector is handled the same way as for ReplaceAllUsesWith.
5015 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
5016 DAGUpdateListener *UpdateListener){
5017 // Handle the really simple, really trivial case efficiently.
5018 if (From == To) return;
5020 // Handle the simple, trivial, case efficiently.
5021 if (From.getNode()->getNumValues() == 1) {
5022 ReplaceAllUsesWith(From, To, UpdateListener);
5026 // Iterate over just the existing users of From. See the comments in
5027 // the ReplaceAllUsesWith above.
5028 SDNode::use_iterator UI = From.getNode()->use_begin(),
5029 UE = From.getNode()->use_end();
5030 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5033 bool UserRemovedFromCSEMaps = false;
5035 // A user can appear in a use list multiple times, and when this
5036 // happens the uses are usually next to each other in the list.
5037 // To help reduce the number of CSE recomputations, process all
5038 // the uses of this user that we can find this way.
5040 SDUse &Use = UI.getUse();
5042 // Skip uses of different values from the same node.
5043 if (Use.getResNo() != From.getResNo()) {
5048 // If this node hasn't been modified yet, it's still in the CSE maps,
5049 // so remove its old self from the CSE maps.
5050 if (!UserRemovedFromCSEMaps) {
5051 RemoveNodeFromCSEMaps(User);
5052 UserRemovedFromCSEMaps = true;
5057 } while (UI != UE && *UI == User);
5059 // We are iterating over all uses of the From node, so if a use
5060 // doesn't use the specific value, no changes are made.
5061 if (!UserRemovedFromCSEMaps)
5064 // Now that we have modified User, add it back to the CSE maps. If it
5065 // already exists there, recursively merge the results together.
5066 AddModifiedNodeToCSEMaps(User, &Listener);
5071 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5072 /// to record information about a use.
5079 /// operator< - Sort Memos by User.
5080 bool operator<(const UseMemo &L, const UseMemo &R) {
5081 return (intptr_t)L.User < (intptr_t)R.User;
5085 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5086 /// uses of other values produced by From.getNode() alone. The same value
5087 /// may appear in both the From and To list. The Deleted vector is
5088 /// handled the same way as for ReplaceAllUsesWith.
5089 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5092 DAGUpdateListener *UpdateListener){
5093 // Handle the simple, trivial case efficiently.
5095 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5097 // Read up all the uses and make records of them. This helps
5098 // processing new uses that are introduced during the
5099 // replacement process.
5100 SmallVector<UseMemo, 4> Uses;
5101 for (unsigned i = 0; i != Num; ++i) {
5102 unsigned FromResNo = From[i].getResNo();
5103 SDNode *FromNode = From[i].getNode();
5104 for (SDNode::use_iterator UI = FromNode->use_begin(),
5105 E = FromNode->use_end(); UI != E; ++UI) {
5106 SDUse &Use = UI.getUse();
5107 if (Use.getResNo() == FromResNo) {
5108 UseMemo Memo = { *UI, i, &Use };
5109 Uses.push_back(Memo);
5114 // Sort the uses, so that all the uses from a given User are together.
5115 std::sort(Uses.begin(), Uses.end());
5117 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5118 UseIndex != UseIndexEnd; ) {
5119 // We know that this user uses some value of From. If it is the right
5120 // value, update it.
5121 SDNode *User = Uses[UseIndex].User;
5123 // This node is about to morph, remove its old self from the CSE maps.
5124 RemoveNodeFromCSEMaps(User);
5126 // The Uses array is sorted, so all the uses for a given User
5127 // are next to each other in the list.
5128 // To help reduce the number of CSE recomputations, process all
5129 // the uses of this user that we can find this way.
5131 unsigned i = Uses[UseIndex].Index;
5132 SDUse &Use = *Uses[UseIndex].Use;
5136 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5138 // Now that we have modified User, add it back to the CSE maps. If it
5139 // already exists there, recursively merge the results together.
5140 AddModifiedNodeToCSEMaps(User, UpdateListener);
5144 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5145 /// based on their topological order. It returns the maximum id and a vector
5146 /// of the SDNodes* in assigned order by reference.
5147 unsigned SelectionDAG::AssignTopologicalOrder() {
5149 unsigned DAGSize = 0;
5151 // SortedPos tracks the progress of the algorithm. Nodes before it are
5152 // sorted, nodes after it are unsorted. When the algorithm completes
5153 // it is at the end of the list.
5154 allnodes_iterator SortedPos = allnodes_begin();
5156 // Visit all the nodes. Move nodes with no operands to the front of
5157 // the list immediately. Annotate nodes that do have operands with their
5158 // operand count. Before we do this, the Node Id fields of the nodes
5159 // may contain arbitrary values. After, the Node Id fields for nodes
5160 // before SortedPos will contain the topological sort index, and the
5161 // Node Id fields for nodes At SortedPos and after will contain the
5162 // count of outstanding operands.
5163 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5166 unsigned Degree = N->getNumOperands();
5168 // A node with no uses, add it to the result array immediately.
5169 N->setNodeId(DAGSize++);
5170 allnodes_iterator Q = N;
5172 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5173 assert(SortedPos != AllNodes.end() && "Overran node list");
5176 // Temporarily use the Node Id as scratch space for the degree count.
5177 N->setNodeId(Degree);
5181 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5182 // such that by the time the end is reached all nodes will be sorted.
5183 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5186 // N is in sorted position, so all its uses have one less operand
5187 // that needs to be sorted.
5188 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5191 unsigned Degree = P->getNodeId();
5192 assert(Degree != 0 && "Invalid node degree");
5195 // All of P's operands are sorted, so P may sorted now.
5196 P->setNodeId(DAGSize++);
5198 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5199 assert(SortedPos != AllNodes.end() && "Overran node list");
5202 // Update P's outstanding operand count.
5203 P->setNodeId(Degree);
5206 if (I == SortedPos) {
5209 dbgs() << "Overran sorted position:\n";
5212 llvm_unreachable(0);
5216 assert(SortedPos == AllNodes.end() &&
5217 "Topological sort incomplete!");
5218 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5219 "First node in topological sort is not the entry token!");
5220 assert(AllNodes.front().getNodeId() == 0 &&
5221 "First node in topological sort has non-zero id!");
5222 assert(AllNodes.front().getNumOperands() == 0 &&
5223 "First node in topological sort has operands!");
5224 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5225 "Last node in topologic sort has unexpected id!");
5226 assert(AllNodes.back().use_empty() &&
5227 "Last node in topologic sort has users!");
5228 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5232 /// AssignOrdering - Assign an order to the SDNode.
5233 void SelectionDAG::AssignOrdering(const SDNode *SD, unsigned Order) {
5234 assert(SD && "Trying to assign an order to a null node!");
5235 Ordering->add(SD, Order);
5238 /// GetOrdering - Get the order for the SDNode.
5239 unsigned SelectionDAG::GetOrdering(const SDNode *SD) const {
5240 assert(SD && "Trying to get the order of a null node!");
5241 return Ordering->getOrder(SD);
5244 /// AssignDbgInfo - Assign debug info to the SDNode.
5245 void SelectionDAG::AssignDbgInfo(SDNode* SD, SDDbgValue* db) {
5246 assert(SD && "Trying to assign dbg info to a null node!");
5247 DbgInfo->add(SD, db);
5248 SD->setHasDebugValue(true);
5251 /// RememberDbgInfo - Remember debug info which is not assigned to an SDNode.
5252 void SelectionDAG::RememberDbgInfo(SDDbgValue* db) {
5256 /// GetDbgInfo - Get the debug info, if any, for the SDNode.
5257 SDDbgValue* SelectionDAG::GetDbgInfo(const SDNode *SD) {
5258 assert(SD && "Trying to get the order of a null node!");
5259 if (SD->getHasDebugValue())
5260 return DbgInfo->getSDDbgValue(SD);
5264 //===----------------------------------------------------------------------===//
5266 //===----------------------------------------------------------------------===//
5268 HandleSDNode::~HandleSDNode() {
5272 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA,
5273 EVT VT, int64_t o, unsigned char TF)
5274 : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)),
5275 Offset(o), TargetFlags(TF) {
5276 TheGlobal = const_cast<GlobalValue*>(GA);
5279 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
5280 MachineMemOperand *mmo)
5281 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5282 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5283 MMO->isNonTemporal());
5284 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5285 assert(isNonTemporal() == MMO->isNonTemporal() &&
5286 "Non-temporal encoding error!");
5287 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5290 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5291 const SDValue *Ops, unsigned NumOps, EVT memvt,
5292 MachineMemOperand *mmo)
5293 : SDNode(Opc, dl, VTs, Ops, NumOps),
5294 MemoryVT(memvt), MMO(mmo) {
5295 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5296 MMO->isNonTemporal());
5297 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5298 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5301 /// Profile - Gather unique data for the node.
5303 void SDNode::Profile(FoldingSetNodeID &ID) const {
5304 AddNodeIDNode(ID, this);
5309 std::vector<EVT> VTs;
5312 VTs.reserve(MVT::LAST_VALUETYPE);
5313 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5314 VTs.push_back(MVT((MVT::SimpleValueType)i));
5319 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5320 static ManagedStatic<EVTArray> SimpleVTArray;
5321 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5323 /// getValueTypeList - Return a pointer to the specified value type.
5325 const EVT *SDNode::getValueTypeList(EVT VT) {
5326 if (VT.isExtended()) {
5327 sys::SmartScopedLock<true> Lock(*VTMutex);
5328 return &(*EVTs->insert(VT).first);
5330 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5334 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5335 /// indicated value. This method ignores uses of other values defined by this
5337 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5338 assert(Value < getNumValues() && "Bad value!");
5340 // TODO: Only iterate over uses of a given value of the node
5341 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5342 if (UI.getUse().getResNo() == Value) {
5349 // Found exactly the right number of uses?
5354 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5355 /// value. This method ignores uses of other values defined by this operation.
5356 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5357 assert(Value < getNumValues() && "Bad value!");
5359 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5360 if (UI.getUse().getResNo() == Value)
5367 /// isOnlyUserOf - Return true if this node is the only use of N.
5369 bool SDNode::isOnlyUserOf(SDNode *N) const {
5371 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5382 /// isOperand - Return true if this node is an operand of N.
5384 bool SDValue::isOperandOf(SDNode *N) const {
5385 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5386 if (*this == N->getOperand(i))
5391 bool SDNode::isOperandOf(SDNode *N) const {
5392 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5393 if (this == N->OperandList[i].getNode())
5398 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5399 /// be a chain) reaches the specified operand without crossing any
5400 /// side-effecting instructions. In practice, this looks through token
5401 /// factors and non-volatile loads. In order to remain efficient, this only
5402 /// looks a couple of nodes in, it does not do an exhaustive search.
5403 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5404 unsigned Depth) const {
5405 if (*this == Dest) return true;
5407 // Don't search too deeply, we just want to be able to see through
5408 // TokenFactor's etc.
5409 if (Depth == 0) return false;
5411 // If this is a token factor, all inputs to the TF happen in parallel. If any
5412 // of the operands of the TF reach dest, then we can do the xform.
5413 if (getOpcode() == ISD::TokenFactor) {
5414 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5415 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5420 // Loads don't have side effects, look through them.
5421 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5422 if (!Ld->isVolatile())
5423 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5428 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5429 /// is either an operand of N or it can be reached by traversing up the operands.
5430 /// NOTE: this is an expensive method. Use it carefully.
5431 bool SDNode::isPredecessorOf(SDNode *N) const {
5432 SmallPtrSet<SDNode *, 32> Visited;
5433 SmallVector<SDNode *, 16> Worklist;
5434 Worklist.push_back(N);
5437 N = Worklist.pop_back_val();
5438 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5439 SDNode *Op = N->getOperand(i).getNode();
5442 if (Visited.insert(Op))
5443 Worklist.push_back(Op);
5445 } while (!Worklist.empty());
5450 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5451 assert(Num < NumOperands && "Invalid child # of SDNode!");
5452 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5455 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5456 switch (getOpcode()) {
5458 if (getOpcode() < ISD::BUILTIN_OP_END)
5459 return "<<Unknown DAG Node>>";
5460 if (isMachineOpcode()) {
5462 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5463 if (getMachineOpcode() < TII->getNumOpcodes())
5464 return TII->get(getMachineOpcode()).getName();
5465 return "<<Unknown Machine Node #" + utostr(getOpcode()) + ">>";
5468 const TargetLowering &TLI = G->getTargetLoweringInfo();
5469 const char *Name = TLI.getTargetNodeName(getOpcode());
5470 if (Name) return Name;
5471 return "<<Unknown Target Node #" + utostr(getOpcode()) + ">>";
5473 return "<<Unknown Node #" + utostr(getOpcode()) + ">>";
5476 case ISD::DELETED_NODE:
5477 return "<<Deleted Node!>>";
5479 case ISD::PREFETCH: return "Prefetch";
5480 case ISD::MEMBARRIER: return "MemBarrier";
5481 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5482 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5483 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5484 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5485 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5486 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5487 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5488 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5489 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5490 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5491 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5492 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5493 case ISD::PCMARKER: return "PCMarker";
5494 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5495 case ISD::SRCVALUE: return "SrcValue";
5496 case ISD::EntryToken: return "EntryToken";
5497 case ISD::TokenFactor: return "TokenFactor";
5498 case ISD::AssertSext: return "AssertSext";
5499 case ISD::AssertZext: return "AssertZext";
5501 case ISD::BasicBlock: return "BasicBlock";
5502 case ISD::VALUETYPE: return "ValueType";
5503 case ISD::Register: return "Register";
5505 case ISD::Constant: return "Constant";
5506 case ISD::ConstantFP: return "ConstantFP";
5507 case ISD::GlobalAddress: return "GlobalAddress";
5508 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5509 case ISD::FrameIndex: return "FrameIndex";
5510 case ISD::JumpTable: return "JumpTable";
5511 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5512 case ISD::RETURNADDR: return "RETURNADDR";
5513 case ISD::FRAMEADDR: return "FRAMEADDR";
5514 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5515 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5516 case ISD::LSDAADDR: return "LSDAADDR";
5517 case ISD::EHSELECTION: return "EHSELECTION";
5518 case ISD::EH_RETURN: return "EH_RETURN";
5519 case ISD::ConstantPool: return "ConstantPool";
5520 case ISD::ExternalSymbol: return "ExternalSymbol";
5521 case ISD::BlockAddress: return "BlockAddress";
5522 case ISD::INTRINSIC_WO_CHAIN:
5523 case ISD::INTRINSIC_VOID:
5524 case ISD::INTRINSIC_W_CHAIN: {
5525 unsigned OpNo = getOpcode() == ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
5526 unsigned IID = cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue();
5527 if (IID < Intrinsic::num_intrinsics)
5528 return Intrinsic::getName((Intrinsic::ID)IID);
5529 else if (const TargetIntrinsicInfo *TII = G->getTarget().getIntrinsicInfo())
5530 return TII->getName(IID);
5531 llvm_unreachable("Invalid intrinsic ID");
5534 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5535 case ISD::TargetConstant: return "TargetConstant";
5536 case ISD::TargetConstantFP:return "TargetConstantFP";
5537 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5538 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5539 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5540 case ISD::TargetJumpTable: return "TargetJumpTable";
5541 case ISD::TargetConstantPool: return "TargetConstantPool";
5542 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5543 case ISD::TargetBlockAddress: return "TargetBlockAddress";
5545 case ISD::CopyToReg: return "CopyToReg";
5546 case ISD::CopyFromReg: return "CopyFromReg";
5547 case ISD::UNDEF: return "undef";
5548 case ISD::MERGE_VALUES: return "merge_values";
5549 case ISD::INLINEASM: return "inlineasm";
5550 case ISD::EH_LABEL: return "eh_label";
5551 case ISD::HANDLENODE: return "handlenode";
5554 case ISD::FABS: return "fabs";
5555 case ISD::FNEG: return "fneg";
5556 case ISD::FSQRT: return "fsqrt";
5557 case ISD::FSIN: return "fsin";
5558 case ISD::FCOS: return "fcos";
5559 case ISD::FPOWI: return "fpowi";
5560 case ISD::FPOW: return "fpow";
5561 case ISD::FTRUNC: return "ftrunc";
5562 case ISD::FFLOOR: return "ffloor";
5563 case ISD::FCEIL: return "fceil";
5564 case ISD::FRINT: return "frint";
5565 case ISD::FNEARBYINT: return "fnearbyint";
5568 case ISD::ADD: return "add";
5569 case ISD::SUB: return "sub";
5570 case ISD::MUL: return "mul";
5571 case ISD::MULHU: return "mulhu";
5572 case ISD::MULHS: return "mulhs";
5573 case ISD::SDIV: return "sdiv";
5574 case ISD::UDIV: return "udiv";
5575 case ISD::SREM: return "srem";
5576 case ISD::UREM: return "urem";
5577 case ISD::SMUL_LOHI: return "smul_lohi";
5578 case ISD::UMUL_LOHI: return "umul_lohi";
5579 case ISD::SDIVREM: return "sdivrem";
5580 case ISD::UDIVREM: return "udivrem";
5581 case ISD::AND: return "and";
5582 case ISD::OR: return "or";
5583 case ISD::XOR: return "xor";
5584 case ISD::SHL: return "shl";
5585 case ISD::SRA: return "sra";
5586 case ISD::SRL: return "srl";
5587 case ISD::ROTL: return "rotl";
5588 case ISD::ROTR: return "rotr";
5589 case ISD::FADD: return "fadd";
5590 case ISD::FSUB: return "fsub";
5591 case ISD::FMUL: return "fmul";
5592 case ISD::FDIV: return "fdiv";
5593 case ISD::FREM: return "frem";
5594 case ISD::FCOPYSIGN: return "fcopysign";
5595 case ISD::FGETSIGN: return "fgetsign";
5597 case ISD::SETCC: return "setcc";
5598 case ISD::VSETCC: return "vsetcc";
5599 case ISD::SELECT: return "select";
5600 case ISD::SELECT_CC: return "select_cc";
5601 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5602 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5603 case ISD::CONCAT_VECTORS: return "concat_vectors";
5604 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5605 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5606 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5607 case ISD::CARRY_FALSE: return "carry_false";
5608 case ISD::ADDC: return "addc";
5609 case ISD::ADDE: return "adde";
5610 case ISD::SADDO: return "saddo";
5611 case ISD::UADDO: return "uaddo";
5612 case ISD::SSUBO: return "ssubo";
5613 case ISD::USUBO: return "usubo";
5614 case ISD::SMULO: return "smulo";
5615 case ISD::UMULO: return "umulo";
5616 case ISD::SUBC: return "subc";
5617 case ISD::SUBE: return "sube";
5618 case ISD::SHL_PARTS: return "shl_parts";
5619 case ISD::SRA_PARTS: return "sra_parts";
5620 case ISD::SRL_PARTS: return "srl_parts";
5622 // Conversion operators.
5623 case ISD::SIGN_EXTEND: return "sign_extend";
5624 case ISD::ZERO_EXTEND: return "zero_extend";
5625 case ISD::ANY_EXTEND: return "any_extend";
5626 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5627 case ISD::TRUNCATE: return "truncate";
5628 case ISD::FP_ROUND: return "fp_round";
5629 case ISD::FLT_ROUNDS_: return "flt_rounds";
5630 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5631 case ISD::FP_EXTEND: return "fp_extend";
5633 case ISD::SINT_TO_FP: return "sint_to_fp";
5634 case ISD::UINT_TO_FP: return "uint_to_fp";
5635 case ISD::FP_TO_SINT: return "fp_to_sint";
5636 case ISD::FP_TO_UINT: return "fp_to_uint";
5637 case ISD::BIT_CONVERT: return "bit_convert";
5638 case ISD::FP16_TO_FP32: return "fp16_to_fp32";
5639 case ISD::FP32_TO_FP16: return "fp32_to_fp16";
5641 case ISD::CONVERT_RNDSAT: {
5642 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5643 default: llvm_unreachable("Unknown cvt code!");
5644 case ISD::CVT_FF: return "cvt_ff";
5645 case ISD::CVT_FS: return "cvt_fs";
5646 case ISD::CVT_FU: return "cvt_fu";
5647 case ISD::CVT_SF: return "cvt_sf";
5648 case ISD::CVT_UF: return "cvt_uf";
5649 case ISD::CVT_SS: return "cvt_ss";
5650 case ISD::CVT_SU: return "cvt_su";
5651 case ISD::CVT_US: return "cvt_us";
5652 case ISD::CVT_UU: return "cvt_uu";
5656 // Control flow instructions
5657 case ISD::BR: return "br";
5658 case ISD::BRIND: return "brind";
5659 case ISD::BR_JT: return "br_jt";
5660 case ISD::BRCOND: return "brcond";
5661 case ISD::BR_CC: return "br_cc";
5662 case ISD::CALLSEQ_START: return "callseq_start";
5663 case ISD::CALLSEQ_END: return "callseq_end";
5666 case ISD::LOAD: return "load";
5667 case ISD::STORE: return "store";
5668 case ISD::VAARG: return "vaarg";
5669 case ISD::VACOPY: return "vacopy";
5670 case ISD::VAEND: return "vaend";
5671 case ISD::VASTART: return "vastart";
5672 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5673 case ISD::EXTRACT_ELEMENT: return "extract_element";
5674 case ISD::BUILD_PAIR: return "build_pair";
5675 case ISD::STACKSAVE: return "stacksave";
5676 case ISD::STACKRESTORE: return "stackrestore";
5677 case ISD::TRAP: return "trap";
5680 case ISD::BSWAP: return "bswap";
5681 case ISD::CTPOP: return "ctpop";
5682 case ISD::CTTZ: return "cttz";
5683 case ISD::CTLZ: return "ctlz";
5686 case ISD::TRAMPOLINE: return "trampoline";
5689 switch (cast<CondCodeSDNode>(this)->get()) {
5690 default: llvm_unreachable("Unknown setcc condition!");
5691 case ISD::SETOEQ: return "setoeq";
5692 case ISD::SETOGT: return "setogt";
5693 case ISD::SETOGE: return "setoge";
5694 case ISD::SETOLT: return "setolt";
5695 case ISD::SETOLE: return "setole";
5696 case ISD::SETONE: return "setone";
5698 case ISD::SETO: return "seto";
5699 case ISD::SETUO: return "setuo";
5700 case ISD::SETUEQ: return "setue";
5701 case ISD::SETUGT: return "setugt";
5702 case ISD::SETUGE: return "setuge";
5703 case ISD::SETULT: return "setult";
5704 case ISD::SETULE: return "setule";
5705 case ISD::SETUNE: return "setune";
5707 case ISD::SETEQ: return "seteq";
5708 case ISD::SETGT: return "setgt";
5709 case ISD::SETGE: return "setge";
5710 case ISD::SETLT: return "setlt";
5711 case ISD::SETLE: return "setle";
5712 case ISD::SETNE: return "setne";
5717 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5726 return "<post-inc>";
5728 return "<post-dec>";
5732 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5733 std::string S = "< ";
5747 if (getByValAlign())
5748 S += "byval-align:" + utostr(getByValAlign()) + " ";
5750 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5752 S += "byval-size:" + utostr(getByValSize()) + " ";
5756 void SDNode::dump() const { dump(0); }
5757 void SDNode::dump(const SelectionDAG *G) const {
5761 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
5762 OS << (void*)this << ": ";
5764 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5766 if (getValueType(i) == MVT::Other)
5769 OS << getValueType(i).getEVTString();
5771 OS << " = " << getOperationName(G);
5774 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
5775 if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
5776 if (!MN->memoperands_empty()) {
5779 for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
5780 e = MN->memoperands_end(); i != e; ++i) {
5787 } else if (const ShuffleVectorSDNode *SVN =
5788 dyn_cast<ShuffleVectorSDNode>(this)) {
5790 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
5791 int Idx = SVN->getMaskElt(i);
5799 } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5800 OS << '<' << CSDN->getAPIntValue() << '>';
5801 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5802 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5803 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5804 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5805 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5808 CSDN->getValueAPF().bitcastToAPInt().dump();
5811 } else if (const GlobalAddressSDNode *GADN =
5812 dyn_cast<GlobalAddressSDNode>(this)) {
5813 int64_t offset = GADN->getOffset();
5815 WriteAsOperand(OS, GADN->getGlobal());
5818 OS << " + " << offset;
5820 OS << " " << offset;
5821 if (unsigned int TF = GADN->getTargetFlags())
5822 OS << " [TF=" << TF << ']';
5823 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5824 OS << "<" << FIDN->getIndex() << ">";
5825 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5826 OS << "<" << JTDN->getIndex() << ">";
5827 if (unsigned int TF = JTDN->getTargetFlags())
5828 OS << " [TF=" << TF << ']';
5829 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5830 int offset = CP->getOffset();
5831 if (CP->isMachineConstantPoolEntry())
5832 OS << "<" << *CP->getMachineCPVal() << ">";
5834 OS << "<" << *CP->getConstVal() << ">";
5836 OS << " + " << offset;
5838 OS << " " << offset;
5839 if (unsigned int TF = CP->getTargetFlags())
5840 OS << " [TF=" << TF << ']';
5841 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5843 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5845 OS << LBB->getName() << " ";
5846 OS << (const void*)BBDN->getBasicBlock() << ">";
5847 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5848 if (G && R->getReg() &&
5849 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5850 OS << " %" << G->getTarget().getRegisterInfo()->getName(R->getReg());
5852 OS << " %reg" << R->getReg();
5854 } else if (const ExternalSymbolSDNode *ES =
5855 dyn_cast<ExternalSymbolSDNode>(this)) {
5856 OS << "'" << ES->getSymbol() << "'";
5857 if (unsigned int TF = ES->getTargetFlags())
5858 OS << " [TF=" << TF << ']';
5859 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5861 OS << "<" << M->getValue() << ">";
5864 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5865 OS << ":" << N->getVT().getEVTString();
5867 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5868 OS << "<" << *LD->getMemOperand();
5871 switch (LD->getExtensionType()) {
5872 default: doExt = false; break;
5873 case ISD::EXTLOAD: OS << ", anyext"; break;
5874 case ISD::SEXTLOAD: OS << ", sext"; break;
5875 case ISD::ZEXTLOAD: OS << ", zext"; break;
5878 OS << " from " << LD->getMemoryVT().getEVTString();
5880 const char *AM = getIndexedModeName(LD->getAddressingMode());
5885 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5886 OS << "<" << *ST->getMemOperand();
5888 if (ST->isTruncatingStore())
5889 OS << ", trunc to " << ST->getMemoryVT().getEVTString();
5891 const char *AM = getIndexedModeName(ST->getAddressingMode());
5896 } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
5897 OS << "<" << *M->getMemOperand() << ">";
5898 } else if (const BlockAddressSDNode *BA =
5899 dyn_cast<BlockAddressSDNode>(this)) {
5901 WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
5903 WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
5905 if (unsigned int TF = BA->getTargetFlags())
5906 OS << " [TF=" << TF << ']';
5910 if (unsigned Order = G->GetOrdering(this))
5911 OS << " [ORD=" << Order << ']';
5913 if (getNodeId() != -1)
5914 OS << " [ID=" << getNodeId() << ']';
5917 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5919 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5920 if (i) OS << ", "; else OS << " ";
5921 OS << (void*)getOperand(i).getNode();
5922 if (unsigned RN = getOperand(i).getResNo())
5925 print_details(OS, G);
5928 static void printrWithDepthHelper(raw_ostream &OS, const SDNode *N,
5929 const SelectionDAG *G, unsigned depth,
5942 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5944 printrWithDepthHelper(OS, N->getOperand(i).getNode(), G, depth-1, indent+2);
5948 void SDNode::printrWithDepth(raw_ostream &OS, const SelectionDAG *G,
5949 unsigned depth) const {
5950 printrWithDepthHelper(OS, this, G, depth, 0);
5953 void SDNode::printrFull(raw_ostream &OS, const SelectionDAG *G) const {
5954 // Don't print impossibly deep things.
5955 printrWithDepth(OS, G, 100);
5958 void SDNode::dumprWithDepth(const SelectionDAG *G, unsigned depth) const {
5959 printrWithDepth(dbgs(), G, depth);
5962 void SDNode::dumprFull(const SelectionDAG *G) const {
5963 // Don't print impossibly deep things.
5964 dumprWithDepth(G, 100);
5967 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5968 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5969 if (N->getOperand(i).getNode()->hasOneUse())
5970 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5972 dbgs() << "\n" << std::string(indent+2, ' ')
5973 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5977 dbgs().indent(indent);
5981 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
5982 assert(N->getNumValues() == 1 &&
5983 "Can't unroll a vector with multiple results!");
5985 EVT VT = N->getValueType(0);
5986 unsigned NE = VT.getVectorNumElements();
5987 EVT EltVT = VT.getVectorElementType();
5988 DebugLoc dl = N->getDebugLoc();
5990 SmallVector<SDValue, 8> Scalars;
5991 SmallVector<SDValue, 4> Operands(N->getNumOperands());
5993 // If ResNE is 0, fully unroll the vector op.
5996 else if (NE > ResNE)
6000 for (i= 0; i != NE; ++i) {
6001 for (unsigned j = 0; j != N->getNumOperands(); ++j) {
6002 SDValue Operand = N->getOperand(j);
6003 EVT OperandVT = Operand.getValueType();
6004 if (OperandVT.isVector()) {
6005 // A vector operand; extract a single element.
6006 EVT OperandEltVT = OperandVT.getVectorElementType();
6007 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6010 getConstant(i, MVT::i32));
6012 // A scalar operand; just use it as is.
6013 Operands[j] = Operand;
6017 switch (N->getOpcode()) {
6019 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6020 &Operands[0], Operands.size()));
6027 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6028 getShiftAmountOperand(Operands[1])));
6030 case ISD::SIGN_EXTEND_INREG:
6031 case ISD::FP_ROUND_INREG: {
6032 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6033 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6035 getValueType(ExtVT)));
6040 for (; i < ResNE; ++i)
6041 Scalars.push_back(getUNDEF(EltVT));
6043 return getNode(ISD::BUILD_VECTOR, dl,
6044 EVT::getVectorVT(*getContext(), EltVT, ResNE),
6045 &Scalars[0], Scalars.size());
6049 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6050 /// location that is 'Dist' units away from the location that the 'Base' load
6051 /// is loading from.
6052 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6053 unsigned Bytes, int Dist) const {
6054 if (LD->getChain() != Base->getChain())
6056 EVT VT = LD->getValueType(0);
6057 if (VT.getSizeInBits() / 8 != Bytes)
6060 SDValue Loc = LD->getOperand(1);
6061 SDValue BaseLoc = Base->getOperand(1);
6062 if (Loc.getOpcode() == ISD::FrameIndex) {
6063 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6065 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6066 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6067 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6068 int FS = MFI->getObjectSize(FI);
6069 int BFS = MFI->getObjectSize(BFI);
6070 if (FS != BFS || FS != (int)Bytes) return false;
6071 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6073 if (Loc.getOpcode() == ISD::ADD && Loc.getOperand(0) == BaseLoc) {
6074 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Loc.getOperand(1));
6075 if (V && (V->getSExtValue() == Dist*Bytes))
6079 GlobalValue *GV1 = NULL;
6080 GlobalValue *GV2 = NULL;
6081 int64_t Offset1 = 0;
6082 int64_t Offset2 = 0;
6083 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6084 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6085 if (isGA1 && isGA2 && GV1 == GV2)
6086 return Offset1 == (Offset2 + Dist*Bytes);
6091 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6092 /// it cannot be inferred.
6093 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6094 // If this is a GlobalAddress + cst, return the alignment.
6096 int64_t GVOffset = 0;
6097 if (TLI.isGAPlusOffset(Ptr.getNode(), GV, GVOffset))
6098 return MinAlign(GV->getAlignment(), GVOffset);
6100 // If this is a direct reference to a stack slot, use information about the
6101 // stack slot's alignment.
6102 int FrameIdx = 1 << 31;
6103 int64_t FrameOffset = 0;
6104 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6105 FrameIdx = FI->getIndex();
6106 } else if (Ptr.getOpcode() == ISD::ADD &&
6107 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
6108 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6109 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6110 FrameOffset = Ptr.getConstantOperandVal(1);
6113 if (FrameIdx != (1 << 31)) {
6114 // FIXME: Handle FI+CST.
6115 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6116 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6118 if (MFI.isFixedObjectIndex(FrameIdx)) {
6119 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
6121 // The alignment of the frame index can be determined from its offset from
6122 // the incoming frame position. If the frame object is at offset 32 and
6123 // the stack is guaranteed to be 16-byte aligned, then we know that the
6124 // object is 16-byte aligned.
6125 unsigned StackAlign = getTarget().getFrameInfo()->getStackAlignment();
6126 unsigned Align = MinAlign(ObjectOffset, StackAlign);
6128 // Finally, the frame object itself may have a known alignment. Factor
6129 // the alignment + offset into a new alignment. For example, if we know
6130 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
6131 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
6132 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
6133 return std::max(Align, FIInfoAlign);
6141 void SelectionDAG::dump() const {
6142 dbgs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
6144 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
6146 const SDNode *N = I;
6147 if (!N->hasOneUse() && N != getRoot().getNode())
6148 DumpNodes(N, 2, this);
6151 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
6156 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
6158 print_details(OS, G);
6161 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
6162 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
6163 const SelectionDAG *G, VisitedSDNodeSet &once) {
6164 if (!once.insert(N)) // If we've been here before, return now.
6167 // Dump the current SDNode, but don't end the line yet.
6168 OS << std::string(indent, ' ');
6171 // Having printed this SDNode, walk the children:
6172 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6173 const SDNode *child = N->getOperand(i).getNode();
6178 if (child->getNumOperands() == 0) {
6179 // This child has no grandchildren; print it inline right here.
6180 child->printr(OS, G);
6182 } else { // Just the address. FIXME: also print the child's opcode.
6184 if (unsigned RN = N->getOperand(i).getResNo())
6191 // Dump children that have grandchildren on their own line(s).
6192 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6193 const SDNode *child = N->getOperand(i).getNode();
6194 DumpNodesr(OS, child, indent+2, G, once);
6198 void SDNode::dumpr() const {
6199 VisitedSDNodeSet once;
6200 DumpNodesr(dbgs(), this, 0, 0, once);
6203 void SDNode::dumpr(const SelectionDAG *G) const {
6204 VisitedSDNodeSet once;
6205 DumpNodesr(dbgs(), this, 0, G, once);
6209 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6210 unsigned GlobalAddressSDNode::getAddressSpace() const {
6211 return getGlobal()->getType()->getAddressSpace();
6215 const Type *ConstantPoolSDNode::getType() const {
6216 if (isMachineConstantPoolEntry())
6217 return Val.MachineCPVal->getType();
6218 return Val.ConstVal->getType();
6221 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6223 unsigned &SplatBitSize,
6225 unsigned MinSplatBits,
6227 EVT VT = getValueType(0);
6228 assert(VT.isVector() && "Expected a vector type");
6229 unsigned sz = VT.getSizeInBits();
6230 if (MinSplatBits > sz)
6233 SplatValue = APInt(sz, 0);
6234 SplatUndef = APInt(sz, 0);
6236 // Get the bits. Bits with undefined values (when the corresponding element
6237 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6238 // in SplatValue. If any of the values are not constant, give up and return
6240 unsigned int nOps = getNumOperands();
6241 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6242 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6244 for (unsigned j = 0; j < nOps; ++j) {
6245 unsigned i = isBigEndian ? nOps-1-j : j;
6246 SDValue OpVal = getOperand(i);
6247 unsigned BitPos = j * EltBitSize;
6249 if (OpVal.getOpcode() == ISD::UNDEF)
6250 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6251 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6252 SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
6253 zextOrTrunc(sz) << BitPos);
6254 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6255 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6260 // The build_vector is all constants or undefs. Find the smallest element
6261 // size that splats the vector.
6263 HasAnyUndefs = (SplatUndef != 0);
6266 unsigned HalfSize = sz / 2;
6267 APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
6268 APInt LowValue = APInt(SplatValue).trunc(HalfSize);
6269 APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
6270 APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
6272 // If the two halves do not match (ignoring undef bits), stop here.
6273 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6274 MinSplatBits > HalfSize)
6277 SplatValue = HighValue | LowValue;
6278 SplatUndef = HighUndef & LowUndef;
6287 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6288 // Find the first non-undef value in the shuffle mask.
6290 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6293 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6295 // Make sure all remaining elements are either undef or the same as the first
6297 for (int Idx = Mask[i]; i != e; ++i)
6298 if (Mask[i] >= 0 && Mask[i] != Idx)
6304 static void checkForCyclesHelper(const SDNode *N,
6305 SmallPtrSet<const SDNode*, 32> &Visited,
6306 SmallPtrSet<const SDNode*, 32> &Checked) {
6307 // If this node has already been checked, don't check it again.
6308 if (Checked.count(N))
6311 // If a node has already been visited on this depth-first walk, reject it as
6313 if (!Visited.insert(N)) {
6314 dbgs() << "Offending node:\n";
6316 errs() << "Detected cycle in SelectionDAG\n";
6320 for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6321 checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked);
6328 void llvm::checkForCycles(const llvm::SDNode *N) {
6330 assert(N && "Checking nonexistant SDNode");
6331 SmallPtrSet<const SDNode*, 32> visited;
6332 SmallPtrSet<const SDNode*, 32> checked;
6333 checkForCyclesHelper(N, visited, checked);
6337 void llvm::checkForCycles(const llvm::SelectionDAG *DAG) {
6338 checkForCycles(DAG->getRoot().getNode());