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 = NodeAllocator.Allocate<ConstantSDNode>();
910 new (N) ConstantSDNode(isT, &Val, EltVT);
911 CSEMap.InsertNode(N, IP);
912 AllNodes.push_back(N);
915 SDValue Result(N, 0);
917 SmallVector<SDValue, 8> Ops;
918 Ops.assign(VT.getVectorNumElements(), Result);
919 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
920 VT, &Ops[0], Ops.size());
925 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
926 return getConstant(Val, TLI.getPointerTy(), isTarget);
930 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
931 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
934 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
935 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
937 EVT EltVT = VT.getScalarType();
939 // Do the map lookup using the actual bit pattern for the floating point
940 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
941 // we don't have issues with SNANs.
942 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
944 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
948 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
950 return SDValue(N, 0);
953 N = NodeAllocator.Allocate<ConstantFPSDNode>();
954 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
955 CSEMap.InsertNode(N, IP);
956 AllNodes.push_back(N);
959 SDValue Result(N, 0);
961 SmallVector<SDValue, 8> Ops;
962 Ops.assign(VT.getVectorNumElements(), Result);
963 // FIXME DebugLoc info might be appropriate here
964 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
965 VT, &Ops[0], Ops.size());
970 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
971 EVT EltVT = VT.getScalarType();
973 return getConstantFP(APFloat((float)Val), VT, isTarget);
975 return getConstantFP(APFloat(Val), VT, isTarget);
978 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
979 EVT VT, int64_t Offset,
981 unsigned char TargetFlags) {
982 assert((TargetFlags == 0 || isTargetGA) &&
983 "Cannot set target flags on target-independent globals");
985 // Truncate (with sign-extension) the offset value to the pointer size.
986 EVT PTy = TLI.getPointerTy();
987 unsigned BitWidth = PTy.getSizeInBits();
989 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
991 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
993 // If GV is an alias then use the aliasee for determining thread-localness.
994 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
995 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
999 if (GVar && GVar->isThreadLocal())
1000 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1002 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1004 FoldingSetNodeID ID;
1005 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1007 ID.AddInteger(Offset);
1008 ID.AddInteger(TargetFlags);
1010 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1011 return SDValue(E, 0);
1013 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
1014 new (N) GlobalAddressSDNode(Opc, GV, VT, Offset, TargetFlags);
1015 CSEMap.InsertNode(N, IP);
1016 AllNodes.push_back(N);
1017 return SDValue(N, 0);
1020 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1021 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1022 FoldingSetNodeID ID;
1023 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1026 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1027 return SDValue(E, 0);
1029 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
1030 new (N) FrameIndexSDNode(FI, VT, isTarget);
1031 CSEMap.InsertNode(N, IP);
1032 AllNodes.push_back(N);
1033 return SDValue(N, 0);
1036 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1037 unsigned char TargetFlags) {
1038 assert((TargetFlags == 0 || isTarget) &&
1039 "Cannot set target flags on target-independent jump tables");
1040 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1041 FoldingSetNodeID ID;
1042 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1044 ID.AddInteger(TargetFlags);
1046 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1047 return SDValue(E, 0);
1049 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1050 new (N) JumpTableSDNode(JTI, VT, isTarget, TargetFlags);
1051 CSEMap.InsertNode(N, IP);
1052 AllNodes.push_back(N);
1053 return SDValue(N, 0);
1056 SDValue SelectionDAG::getConstantPool(Constant *C, EVT VT,
1057 unsigned Alignment, int Offset,
1059 unsigned char TargetFlags) {
1060 assert((TargetFlags == 0 || isTarget) &&
1061 "Cannot set target flags on target-independent globals");
1063 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1064 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1065 FoldingSetNodeID ID;
1066 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1067 ID.AddInteger(Alignment);
1068 ID.AddInteger(Offset);
1070 ID.AddInteger(TargetFlags);
1072 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1073 return SDValue(E, 0);
1075 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1076 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1077 CSEMap.InsertNode(N, IP);
1078 AllNodes.push_back(N);
1079 return SDValue(N, 0);
1083 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1084 unsigned Alignment, int Offset,
1086 unsigned char TargetFlags) {
1087 assert((TargetFlags == 0 || isTarget) &&
1088 "Cannot set target flags on target-independent globals");
1090 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1091 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1092 FoldingSetNodeID ID;
1093 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1094 ID.AddInteger(Alignment);
1095 ID.AddInteger(Offset);
1096 C->AddSelectionDAGCSEId(ID);
1097 ID.AddInteger(TargetFlags);
1099 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1100 return SDValue(E, 0);
1102 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1103 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1104 CSEMap.InsertNode(N, IP);
1105 AllNodes.push_back(N);
1106 return SDValue(N, 0);
1109 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1110 FoldingSetNodeID ID;
1111 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1114 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1115 return SDValue(E, 0);
1117 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1118 new (N) BasicBlockSDNode(MBB);
1119 CSEMap.InsertNode(N, IP);
1120 AllNodes.push_back(N);
1121 return SDValue(N, 0);
1124 SDValue SelectionDAG::getValueType(EVT VT) {
1125 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1126 ValueTypeNodes.size())
1127 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1129 SDNode *&N = VT.isExtended() ?
1130 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1132 if (N) return SDValue(N, 0);
1133 N = NodeAllocator.Allocate<VTSDNode>();
1134 new (N) VTSDNode(VT);
1135 AllNodes.push_back(N);
1136 return SDValue(N, 0);
1139 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1140 SDNode *&N = ExternalSymbols[Sym];
1141 if (N) return SDValue(N, 0);
1142 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1143 new (N) ExternalSymbolSDNode(false, Sym, 0, VT);
1144 AllNodes.push_back(N);
1145 return SDValue(N, 0);
1148 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1149 unsigned char TargetFlags) {
1151 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1153 if (N) return SDValue(N, 0);
1154 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1155 new (N) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1156 AllNodes.push_back(N);
1157 return SDValue(N, 0);
1160 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1161 if ((unsigned)Cond >= CondCodeNodes.size())
1162 CondCodeNodes.resize(Cond+1);
1164 if (CondCodeNodes[Cond] == 0) {
1165 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1166 new (N) CondCodeSDNode(Cond);
1167 CondCodeNodes[Cond] = N;
1168 AllNodes.push_back(N);
1171 return SDValue(CondCodeNodes[Cond], 0);
1174 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1175 // the shuffle mask M that point at N1 to point at N2, and indices that point
1176 // N2 to point at N1.
1177 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1179 int NElts = M.size();
1180 for (int i = 0; i != NElts; ++i) {
1188 SDValue SelectionDAG::getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1,
1189 SDValue N2, const int *Mask) {
1190 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1191 assert(VT.isVector() && N1.getValueType().isVector() &&
1192 "Vector Shuffle VTs must be a vectors");
1193 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1194 && "Vector Shuffle VTs must have same element type");
1196 // Canonicalize shuffle undef, undef -> undef
1197 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1198 return getUNDEF(VT);
1200 // Validate that all indices in Mask are within the range of the elements
1201 // input to the shuffle.
1202 unsigned NElts = VT.getVectorNumElements();
1203 SmallVector<int, 8> MaskVec;
1204 for (unsigned i = 0; i != NElts; ++i) {
1205 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1206 MaskVec.push_back(Mask[i]);
1209 // Canonicalize shuffle v, v -> v, undef
1212 for (unsigned i = 0; i != NElts; ++i)
1213 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1216 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1217 if (N1.getOpcode() == ISD::UNDEF)
1218 commuteShuffle(N1, N2, MaskVec);
1220 // Canonicalize all index into lhs, -> shuffle lhs, undef
1221 // Canonicalize all index into rhs, -> shuffle rhs, undef
1222 bool AllLHS = true, AllRHS = true;
1223 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1224 for (unsigned i = 0; i != NElts; ++i) {
1225 if (MaskVec[i] >= (int)NElts) {
1230 } else if (MaskVec[i] >= 0) {
1234 if (AllLHS && AllRHS)
1235 return getUNDEF(VT);
1236 if (AllLHS && !N2Undef)
1240 commuteShuffle(N1, N2, MaskVec);
1243 // If Identity shuffle, or all shuffle in to undef, return that node.
1244 bool AllUndef = true;
1245 bool Identity = true;
1246 for (unsigned i = 0; i != NElts; ++i) {
1247 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1248 if (MaskVec[i] >= 0) AllUndef = false;
1250 if (Identity && NElts == N1.getValueType().getVectorNumElements())
1253 return getUNDEF(VT);
1255 FoldingSetNodeID ID;
1256 SDValue Ops[2] = { N1, N2 };
1257 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1258 for (unsigned i = 0; i != NElts; ++i)
1259 ID.AddInteger(MaskVec[i]);
1262 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1263 return SDValue(E, 0);
1265 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1266 // SDNode doesn't have access to it. This memory will be "leaked" when
1267 // the node is deallocated, but recovered when the NodeAllocator is released.
1268 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1269 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1271 ShuffleVectorSDNode *N = NodeAllocator.Allocate<ShuffleVectorSDNode>();
1272 new (N) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
1273 CSEMap.InsertNode(N, IP);
1274 AllNodes.push_back(N);
1275 return SDValue(N, 0);
1278 SDValue SelectionDAG::getConvertRndSat(EVT VT, DebugLoc dl,
1279 SDValue Val, SDValue DTy,
1280 SDValue STy, SDValue Rnd, SDValue Sat,
1281 ISD::CvtCode Code) {
1282 // If the src and dest types are the same and the conversion is between
1283 // integer types of the same sign or two floats, no conversion is necessary.
1285 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1288 FoldingSetNodeID ID;
1289 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1290 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5);
1292 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1293 return SDValue(E, 0);
1295 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
1296 new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code);
1297 CSEMap.InsertNode(N, IP);
1298 AllNodes.push_back(N);
1299 return SDValue(N, 0);
1302 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1303 FoldingSetNodeID ID;
1304 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1305 ID.AddInteger(RegNo);
1307 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1308 return SDValue(E, 0);
1310 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1311 new (N) RegisterSDNode(RegNo, VT);
1312 CSEMap.InsertNode(N, IP);
1313 AllNodes.push_back(N);
1314 return SDValue(N, 0);
1317 SDValue SelectionDAG::getEHLabel(DebugLoc dl, SDValue Root, MCSymbol *Label) {
1318 FoldingSetNodeID ID;
1319 SDValue Ops[] = { Root };
1320 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), &Ops[0], 1);
1321 ID.AddPointer(Label);
1323 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1324 return SDValue(E, 0);
1326 SDNode *N = NodeAllocator.Allocate<EHLabelSDNode>();
1327 new (N) EHLabelSDNode(dl, Root, Label);
1328 CSEMap.InsertNode(N, IP);
1329 AllNodes.push_back(N);
1330 return SDValue(N, 0);
1334 SDValue SelectionDAG::getBlockAddress(BlockAddress *BA, EVT VT,
1336 unsigned char TargetFlags) {
1337 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1339 FoldingSetNodeID ID;
1340 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1342 ID.AddInteger(TargetFlags);
1344 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1345 return SDValue(E, 0);
1347 SDNode *N = NodeAllocator.Allocate<BlockAddressSDNode>();
1348 new (N) BlockAddressSDNode(Opc, VT, BA, TargetFlags);
1349 CSEMap.InsertNode(N, IP);
1350 AllNodes.push_back(N);
1351 return SDValue(N, 0);
1354 SDValue SelectionDAG::getSrcValue(const Value *V) {
1355 assert((!V || V->getType()->isPointerTy()) &&
1356 "SrcValue is not a pointer?");
1358 FoldingSetNodeID ID;
1359 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1363 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1364 return SDValue(E, 0);
1366 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1367 new (N) SrcValueSDNode(V);
1368 CSEMap.InsertNode(N, IP);
1369 AllNodes.push_back(N);
1370 return SDValue(N, 0);
1373 /// getShiftAmountOperand - Return the specified value casted to
1374 /// the target's desired shift amount type.
1375 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
1376 EVT OpTy = Op.getValueType();
1377 MVT ShTy = TLI.getShiftAmountTy();
1378 if (OpTy == ShTy || OpTy.isVector()) return Op;
1380 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1381 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
1384 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1385 /// specified value type.
1386 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1387 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1388 unsigned ByteSize = VT.getStoreSize();
1389 const Type *Ty = VT.getTypeForEVT(*getContext());
1390 unsigned StackAlign =
1391 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1393 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1394 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1397 /// CreateStackTemporary - Create a stack temporary suitable for holding
1398 /// either of the specified value types.
1399 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1400 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1401 VT2.getStoreSizeInBits())/8;
1402 const Type *Ty1 = VT1.getTypeForEVT(*getContext());
1403 const Type *Ty2 = VT2.getTypeForEVT(*getContext());
1404 const TargetData *TD = TLI.getTargetData();
1405 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1406 TD->getPrefTypeAlignment(Ty2));
1408 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1409 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1410 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1413 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1414 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1415 // These setcc operations always fold.
1419 case ISD::SETFALSE2: return getConstant(0, VT);
1421 case ISD::SETTRUE2: return getConstant(1, VT);
1433 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1437 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1438 const APInt &C2 = N2C->getAPIntValue();
1439 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1440 const APInt &C1 = N1C->getAPIntValue();
1443 default: llvm_unreachable("Unknown integer setcc!");
1444 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1445 case ISD::SETNE: return getConstant(C1 != C2, VT);
1446 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1447 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1448 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1449 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1450 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1451 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1452 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1453 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1457 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1458 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1459 // No compile time operations on this type yet.
1460 if (N1C->getValueType(0) == MVT::ppcf128)
1463 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1466 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1467 return getUNDEF(VT);
1469 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1470 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1471 return getUNDEF(VT);
1473 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1474 R==APFloat::cmpLessThan, VT);
1475 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1476 return getUNDEF(VT);
1478 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1479 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1480 return getUNDEF(VT);
1482 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1483 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1484 return getUNDEF(VT);
1486 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1487 R==APFloat::cmpEqual, VT);
1488 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1489 return getUNDEF(VT);
1491 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1492 R==APFloat::cmpEqual, VT);
1493 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1494 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1495 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1496 R==APFloat::cmpEqual, VT);
1497 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1498 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1499 R==APFloat::cmpLessThan, VT);
1500 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1501 R==APFloat::cmpUnordered, VT);
1502 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1503 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1506 // Ensure that the constant occurs on the RHS.
1507 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1511 // Could not fold it.
1515 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1516 /// use this predicate to simplify operations downstream.
1517 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1518 // This predicate is not safe for vector operations.
1519 if (Op.getValueType().isVector())
1522 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1523 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1526 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1527 /// this predicate to simplify operations downstream. Mask is known to be zero
1528 /// for bits that V cannot have.
1529 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1530 unsigned Depth) const {
1531 APInt KnownZero, KnownOne;
1532 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1533 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1534 return (KnownZero & Mask) == Mask;
1537 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1538 /// known to be either zero or one and return them in the KnownZero/KnownOne
1539 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1541 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1542 APInt &KnownZero, APInt &KnownOne,
1543 unsigned Depth) const {
1544 unsigned BitWidth = Mask.getBitWidth();
1545 assert(BitWidth == Op.getValueType().getScalarType().getSizeInBits() &&
1546 "Mask size mismatches value type size!");
1548 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1549 if (Depth == 6 || Mask == 0)
1550 return; // Limit search depth.
1552 APInt KnownZero2, KnownOne2;
1554 switch (Op.getOpcode()) {
1556 // We know all of the bits for a constant!
1557 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1558 KnownZero = ~KnownOne & Mask;
1561 // If either the LHS or the RHS are Zero, the result is zero.
1562 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1563 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
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-1 bits are only known if set in both the LHS & RHS.
1569 KnownOne &= KnownOne2;
1570 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1571 KnownZero |= KnownZero2;
1574 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1575 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1576 KnownZero2, KnownOne2, Depth+1);
1577 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1578 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1580 // Output known-0 bits are only known if clear in both the LHS & RHS.
1581 KnownZero &= KnownZero2;
1582 // Output known-1 are known to be set if set in either the LHS | RHS.
1583 KnownOne |= KnownOne2;
1586 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1587 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1588 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1589 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1591 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1592 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1593 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1594 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1595 KnownZero = KnownZeroOut;
1599 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1600 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1601 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1602 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1603 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1605 // If low bits are zero in either operand, output low known-0 bits.
1606 // Also compute a conserative estimate for high known-0 bits.
1607 // More trickiness is possible, but this is sufficient for the
1608 // interesting case of alignment computation.
1610 unsigned TrailZ = KnownZero.countTrailingOnes() +
1611 KnownZero2.countTrailingOnes();
1612 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1613 KnownZero2.countLeadingOnes(),
1614 BitWidth) - BitWidth;
1616 TrailZ = std::min(TrailZ, BitWidth);
1617 LeadZ = std::min(LeadZ, BitWidth);
1618 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1619 APInt::getHighBitsSet(BitWidth, LeadZ);
1624 // For the purposes of computing leading zeros we can conservatively
1625 // treat a udiv as a logical right shift by the power of 2 known to
1626 // be less than the denominator.
1627 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1628 ComputeMaskedBits(Op.getOperand(0),
1629 AllOnes, KnownZero2, KnownOne2, Depth+1);
1630 unsigned LeadZ = KnownZero2.countLeadingOnes();
1634 ComputeMaskedBits(Op.getOperand(1),
1635 AllOnes, KnownZero2, KnownOne2, Depth+1);
1636 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1637 if (RHSUnknownLeadingOnes != BitWidth)
1638 LeadZ = std::min(BitWidth,
1639 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1641 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1645 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1646 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1647 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1648 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1650 // Only known if known in both the LHS and RHS.
1651 KnownOne &= KnownOne2;
1652 KnownZero &= KnownZero2;
1654 case ISD::SELECT_CC:
1655 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1656 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1657 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1658 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1660 // Only known if known in both the LHS and RHS.
1661 KnownOne &= KnownOne2;
1662 KnownZero &= KnownZero2;
1670 if (Op.getResNo() != 1)
1672 // The boolean result conforms to getBooleanContents. Fall through.
1674 // If we know the result of a setcc has the top bits zero, use this info.
1675 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1677 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1680 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1681 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1682 unsigned ShAmt = SA->getZExtValue();
1684 // If the shift count is an invalid immediate, don't do anything.
1685 if (ShAmt >= BitWidth)
1688 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1689 KnownZero, KnownOne, Depth+1);
1690 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1691 KnownZero <<= ShAmt;
1693 // low bits known zero.
1694 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1698 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1699 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1700 unsigned ShAmt = SA->getZExtValue();
1702 // If the shift count is an invalid immediate, don't do anything.
1703 if (ShAmt >= BitWidth)
1706 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1707 KnownZero, KnownOne, Depth+1);
1708 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1709 KnownZero = KnownZero.lshr(ShAmt);
1710 KnownOne = KnownOne.lshr(ShAmt);
1712 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1713 KnownZero |= HighBits; // High bits known zero.
1717 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1718 unsigned ShAmt = SA->getZExtValue();
1720 // If the shift count is an invalid immediate, don't do anything.
1721 if (ShAmt >= BitWidth)
1724 APInt InDemandedMask = (Mask << ShAmt);
1725 // If any of the demanded bits are produced by the sign extension, we also
1726 // demand the input sign bit.
1727 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1728 if (HighBits.getBoolValue())
1729 InDemandedMask |= APInt::getSignBit(BitWidth);
1731 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1733 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1734 KnownZero = KnownZero.lshr(ShAmt);
1735 KnownOne = KnownOne.lshr(ShAmt);
1737 // Handle the sign bits.
1738 APInt SignBit = APInt::getSignBit(BitWidth);
1739 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1741 if (KnownZero.intersects(SignBit)) {
1742 KnownZero |= HighBits; // New bits are known zero.
1743 } else if (KnownOne.intersects(SignBit)) {
1744 KnownOne |= HighBits; // New bits are known one.
1748 case ISD::SIGN_EXTEND_INREG: {
1749 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1750 unsigned EBits = EVT.getScalarType().getSizeInBits();
1752 // Sign extension. Compute the demanded bits in the result that are not
1753 // present in the input.
1754 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1756 APInt InSignBit = APInt::getSignBit(EBits);
1757 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1759 // If the sign extended bits are demanded, we know that the sign
1761 InSignBit.zext(BitWidth);
1762 if (NewBits.getBoolValue())
1763 InputDemandedBits |= InSignBit;
1765 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1766 KnownZero, KnownOne, Depth+1);
1767 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1769 // If the sign bit of the input is known set or clear, then we know the
1770 // top bits of the result.
1771 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1772 KnownZero |= NewBits;
1773 KnownOne &= ~NewBits;
1774 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1775 KnownOne |= NewBits;
1776 KnownZero &= ~NewBits;
1777 } else { // Input sign bit unknown
1778 KnownZero &= ~NewBits;
1779 KnownOne &= ~NewBits;
1786 unsigned LowBits = Log2_32(BitWidth)+1;
1787 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1792 if (ISD::isZEXTLoad(Op.getNode())) {
1793 LoadSDNode *LD = cast<LoadSDNode>(Op);
1794 EVT VT = LD->getMemoryVT();
1795 unsigned MemBits = VT.getScalarType().getSizeInBits();
1796 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1800 case ISD::ZERO_EXTEND: {
1801 EVT InVT = Op.getOperand(0).getValueType();
1802 unsigned InBits = InVT.getScalarType().getSizeInBits();
1803 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1804 APInt InMask = Mask;
1805 InMask.trunc(InBits);
1806 KnownZero.trunc(InBits);
1807 KnownOne.trunc(InBits);
1808 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1809 KnownZero.zext(BitWidth);
1810 KnownOne.zext(BitWidth);
1811 KnownZero |= NewBits;
1814 case ISD::SIGN_EXTEND: {
1815 EVT InVT = Op.getOperand(0).getValueType();
1816 unsigned InBits = InVT.getScalarType().getSizeInBits();
1817 APInt InSignBit = APInt::getSignBit(InBits);
1818 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1819 APInt InMask = Mask;
1820 InMask.trunc(InBits);
1822 // If any of the sign extended bits are demanded, we know that the sign
1823 // bit is demanded. Temporarily set this bit in the mask for our callee.
1824 if (NewBits.getBoolValue())
1825 InMask |= InSignBit;
1827 KnownZero.trunc(InBits);
1828 KnownOne.trunc(InBits);
1829 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1831 // Note if the sign bit is known to be zero or one.
1832 bool SignBitKnownZero = KnownZero.isNegative();
1833 bool SignBitKnownOne = KnownOne.isNegative();
1834 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1835 "Sign bit can't be known to be both zero and one!");
1837 // If the sign bit wasn't actually demanded by our caller, we don't
1838 // want it set in the KnownZero and KnownOne result values. Reset the
1839 // mask and reapply it to the result values.
1841 InMask.trunc(InBits);
1842 KnownZero &= InMask;
1845 KnownZero.zext(BitWidth);
1846 KnownOne.zext(BitWidth);
1848 // If the sign bit is known zero or one, the top bits match.
1849 if (SignBitKnownZero)
1850 KnownZero |= NewBits;
1851 else if (SignBitKnownOne)
1852 KnownOne |= NewBits;
1855 case ISD::ANY_EXTEND: {
1856 EVT InVT = Op.getOperand(0).getValueType();
1857 unsigned InBits = InVT.getScalarType().getSizeInBits();
1858 APInt InMask = Mask;
1859 InMask.trunc(InBits);
1860 KnownZero.trunc(InBits);
1861 KnownOne.trunc(InBits);
1862 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1863 KnownZero.zext(BitWidth);
1864 KnownOne.zext(BitWidth);
1867 case ISD::TRUNCATE: {
1868 EVT InVT = Op.getOperand(0).getValueType();
1869 unsigned InBits = InVT.getScalarType().getSizeInBits();
1870 APInt InMask = Mask;
1871 InMask.zext(InBits);
1872 KnownZero.zext(InBits);
1873 KnownOne.zext(InBits);
1874 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1875 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1876 KnownZero.trunc(BitWidth);
1877 KnownOne.trunc(BitWidth);
1880 case ISD::AssertZext: {
1881 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1882 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1883 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1885 KnownZero |= (~InMask) & Mask;
1889 // All bits are zero except the low bit.
1890 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1894 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1895 // We know that the top bits of C-X are clear if X contains less bits
1896 // than C (i.e. no wrap-around can happen). For example, 20-X is
1897 // positive if we can prove that X is >= 0 and < 16.
1898 if (CLHS->getAPIntValue().isNonNegative()) {
1899 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1900 // NLZ can't be BitWidth with no sign bit
1901 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1902 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1905 // If all of the MaskV bits are known to be zero, then we know the
1906 // output top bits are zero, because we now know that the output is
1908 if ((KnownZero2 & MaskV) == MaskV) {
1909 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1910 // Top bits known zero.
1911 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1918 // Output known-0 bits are known if clear or set in both the low clear bits
1919 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1920 // low 3 bits clear.
1921 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1922 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1923 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1924 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1926 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1927 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1928 KnownZeroOut = std::min(KnownZeroOut,
1929 KnownZero2.countTrailingOnes());
1931 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1935 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1936 const APInt &RA = Rem->getAPIntValue().abs();
1937 if (RA.isPowerOf2()) {
1938 APInt LowBits = RA - 1;
1939 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1940 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1942 // The low bits of the first operand are unchanged by the srem.
1943 KnownZero = KnownZero2 & LowBits;
1944 KnownOne = KnownOne2 & LowBits;
1946 // If the first operand is non-negative or has all low bits zero, then
1947 // the upper bits are all zero.
1948 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1949 KnownZero |= ~LowBits;
1951 // If the first operand is negative and not all low bits are zero, then
1952 // the upper bits are all one.
1953 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
1954 KnownOne |= ~LowBits;
1959 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1964 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1965 const APInt &RA = Rem->getAPIntValue();
1966 if (RA.isPowerOf2()) {
1967 APInt LowBits = (RA - 1);
1968 APInt Mask2 = LowBits & Mask;
1969 KnownZero |= ~LowBits & Mask;
1970 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1971 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1976 // Since the result is less than or equal to either operand, any leading
1977 // zero bits in either operand must also exist in the result.
1978 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1979 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1981 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1984 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1985 KnownZero2.countLeadingOnes());
1987 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1991 // Allow the target to implement this method for its nodes.
1992 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1993 case ISD::INTRINSIC_WO_CHAIN:
1994 case ISD::INTRINSIC_W_CHAIN:
1995 case ISD::INTRINSIC_VOID:
1996 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
2003 /// ComputeNumSignBits - Return the number of times the sign bit of the
2004 /// register is replicated into the other bits. We know that at least 1 bit
2005 /// is always equal to the sign bit (itself), but other cases can give us
2006 /// information. For example, immediately after an "SRA X, 2", we know that
2007 /// the top 3 bits are all equal to each other, so we return 3.
2008 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
2009 EVT VT = Op.getValueType();
2010 assert(VT.isInteger() && "Invalid VT!");
2011 unsigned VTBits = VT.getScalarType().getSizeInBits();
2013 unsigned FirstAnswer = 1;
2016 return 1; // Limit search depth.
2018 switch (Op.getOpcode()) {
2020 case ISD::AssertSext:
2021 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2022 return VTBits-Tmp+1;
2023 case ISD::AssertZext:
2024 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2027 case ISD::Constant: {
2028 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2029 // If negative, return # leading ones.
2030 if (Val.isNegative())
2031 return Val.countLeadingOnes();
2033 // Return # leading zeros.
2034 return Val.countLeadingZeros();
2037 case ISD::SIGN_EXTEND:
2038 Tmp = VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2039 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2041 case ISD::SIGN_EXTEND_INREG:
2042 // Max of the input and what this extends.
2044 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
2047 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2048 return std::max(Tmp, Tmp2);
2051 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2052 // SRA X, C -> adds C sign bits.
2053 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2054 Tmp += C->getZExtValue();
2055 if (Tmp > VTBits) Tmp = VTBits;
2059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2060 // shl destroys sign bits.
2061 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2062 if (C->getZExtValue() >= VTBits || // Bad shift.
2063 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2064 return Tmp - C->getZExtValue();
2069 case ISD::XOR: // NOT is handled here.
2070 // Logical binary ops preserve the number of sign bits at the worst.
2071 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2073 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2074 FirstAnswer = std::min(Tmp, Tmp2);
2075 // We computed what we know about the sign bits as our first
2076 // answer. Now proceed to the generic code that uses
2077 // ComputeMaskedBits, and pick whichever answer is better.
2082 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2083 if (Tmp == 1) return 1; // Early out.
2084 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2085 return std::min(Tmp, Tmp2);
2093 if (Op.getResNo() != 1)
2095 // The boolean result conforms to getBooleanContents. Fall through.
2097 // If setcc returns 0/-1, all bits are sign bits.
2098 if (TLI.getBooleanContents() ==
2099 TargetLowering::ZeroOrNegativeOneBooleanContent)
2104 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2105 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2107 // Handle rotate right by N like a rotate left by 32-N.
2108 if (Op.getOpcode() == ISD::ROTR)
2109 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2111 // If we aren't rotating out all of the known-in sign bits, return the
2112 // number that are left. This handles rotl(sext(x), 1) for example.
2113 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2114 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2118 // Add can have at most one carry bit. Thus we know that the output
2119 // is, at worst, one more bit than the inputs.
2120 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2121 if (Tmp == 1) return 1; // Early out.
2123 // Special case decrementing a value (ADD X, -1):
2124 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2125 if (CRHS->isAllOnesValue()) {
2126 APInt KnownZero, KnownOne;
2127 APInt Mask = APInt::getAllOnesValue(VTBits);
2128 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2130 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2132 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2135 // If we are subtracting one from a positive number, there is no carry
2136 // out of the result.
2137 if (KnownZero.isNegative())
2141 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2142 if (Tmp2 == 1) return 1;
2143 return std::min(Tmp, Tmp2)-1;
2147 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2148 if (Tmp2 == 1) return 1;
2151 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2152 if (CLHS->isNullValue()) {
2153 APInt KnownZero, KnownOne;
2154 APInt Mask = APInt::getAllOnesValue(VTBits);
2155 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2156 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2158 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2161 // If the input is known to be positive (the sign bit is known clear),
2162 // the output of the NEG has the same number of sign bits as the input.
2163 if (KnownZero.isNegative())
2166 // Otherwise, we treat this like a SUB.
2169 // Sub can have at most one carry bit. Thus we know that the output
2170 // is, at worst, one more bit than the inputs.
2171 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2172 if (Tmp == 1) return 1; // Early out.
2173 return std::min(Tmp, Tmp2)-1;
2176 // FIXME: it's tricky to do anything useful for this, but it is an important
2177 // case for targets like X86.
2181 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2182 if (Op.getOpcode() == ISD::LOAD) {
2183 LoadSDNode *LD = cast<LoadSDNode>(Op);
2184 unsigned ExtType = LD->getExtensionType();
2187 case ISD::SEXTLOAD: // '17' bits known
2188 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2189 return VTBits-Tmp+1;
2190 case ISD::ZEXTLOAD: // '16' bits known
2191 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2196 // Allow the target to implement this method for its nodes.
2197 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2198 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2199 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2200 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2201 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2202 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2205 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2206 // use this information.
2207 APInt KnownZero, KnownOne;
2208 APInt Mask = APInt::getAllOnesValue(VTBits);
2209 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2211 if (KnownZero.isNegative()) { // sign bit is 0
2213 } else if (KnownOne.isNegative()) { // sign bit is 1;
2220 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2221 // the number of identical bits in the top of the input value.
2223 Mask <<= Mask.getBitWidth()-VTBits;
2224 // Return # leading zeros. We use 'min' here in case Val was zero before
2225 // shifting. We don't want to return '64' as for an i32 "0".
2226 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2229 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2230 // If we're told that NaNs won't happen, assume they won't.
2231 if (FiniteOnlyFPMath())
2234 // If the value is a constant, we can obviously see if it is a NaN or not.
2235 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2236 return !C->getValueAPF().isNaN();
2238 // TODO: Recognize more cases here.
2243 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2244 // If the value is a constant, we can obviously see if it is a zero or not.
2245 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2246 return !C->isZero();
2248 // TODO: Recognize more cases here.
2253 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2254 // Check the obvious case.
2255 if (A == B) return true;
2257 // For for negative and positive zero.
2258 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2259 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2260 if (CA->isZero() && CB->isZero()) return true;
2262 // Otherwise they may not be equal.
2266 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2267 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2268 if (!GA) return false;
2269 if (GA->getOffset() != 0) return false;
2270 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2271 if (!GV) return false;
2272 MachineModuleInfo *MMI = getMachineModuleInfo();
2273 return MMI && MMI->hasDebugInfo();
2277 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2278 /// element of the result of the vector shuffle.
2279 SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N,
2281 EVT VT = N->getValueType(0);
2282 DebugLoc dl = N->getDebugLoc();
2283 if (N->getMaskElt(i) < 0)
2284 return getUNDEF(VT.getVectorElementType());
2285 unsigned Index = N->getMaskElt(i);
2286 unsigned NumElems = VT.getVectorNumElements();
2287 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2290 if (V.getOpcode() == ISD::BIT_CONVERT) {
2291 V = V.getOperand(0);
2292 EVT VVT = V.getValueType();
2293 if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems)
2296 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2297 return (Index == 0) ? V.getOperand(0)
2298 : getUNDEF(VT.getVectorElementType());
2299 if (V.getOpcode() == ISD::BUILD_VECTOR)
2300 return V.getOperand(Index);
2301 if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V))
2302 return getShuffleScalarElt(SVN, Index);
2307 /// getNode - Gets or creates the specified node.
2309 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
2310 FoldingSetNodeID ID;
2311 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2313 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2314 return SDValue(E, 0);
2316 SDNode *N = NodeAllocator.Allocate<SDNode>();
2317 new (N) SDNode(Opcode, DL, getVTList(VT));
2318 CSEMap.InsertNode(N, IP);
2320 AllNodes.push_back(N);
2324 return SDValue(N, 0);
2327 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2328 EVT VT, SDValue Operand) {
2329 // Constant fold unary operations with an integer constant operand.
2330 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2331 const APInt &Val = C->getAPIntValue();
2332 unsigned BitWidth = VT.getSizeInBits();
2335 case ISD::SIGN_EXTEND:
2336 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2337 case ISD::ANY_EXTEND:
2338 case ISD::ZERO_EXTEND:
2340 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2341 case ISD::UINT_TO_FP:
2342 case ISD::SINT_TO_FP: {
2343 const uint64_t zero[] = {0, 0};
2344 // No compile time operations on this type.
2345 if (VT==MVT::ppcf128)
2347 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2348 (void)apf.convertFromAPInt(Val,
2349 Opcode==ISD::SINT_TO_FP,
2350 APFloat::rmNearestTiesToEven);
2351 return getConstantFP(apf, VT);
2353 case ISD::BIT_CONVERT:
2354 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2355 return getConstantFP(Val.bitsToFloat(), VT);
2356 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2357 return getConstantFP(Val.bitsToDouble(), VT);
2360 return getConstant(Val.byteSwap(), VT);
2362 return getConstant(Val.countPopulation(), VT);
2364 return getConstant(Val.countLeadingZeros(), VT);
2366 return getConstant(Val.countTrailingZeros(), VT);
2370 // Constant fold unary operations with a floating point constant operand.
2371 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2372 APFloat V = C->getValueAPF(); // make copy
2373 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2377 return getConstantFP(V, VT);
2380 return getConstantFP(V, VT);
2382 case ISD::FP_EXTEND: {
2384 // This can return overflow, underflow, or inexact; we don't care.
2385 // FIXME need to be more flexible about rounding mode.
2386 (void)V.convert(*EVTToAPFloatSemantics(VT),
2387 APFloat::rmNearestTiesToEven, &ignored);
2388 return getConstantFP(V, VT);
2390 case ISD::FP_TO_SINT:
2391 case ISD::FP_TO_UINT: {
2394 assert(integerPartWidth >= 64);
2395 // FIXME need to be more flexible about rounding mode.
2396 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2397 Opcode==ISD::FP_TO_SINT,
2398 APFloat::rmTowardZero, &ignored);
2399 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2401 APInt api(VT.getSizeInBits(), 2, x);
2402 return getConstant(api, VT);
2404 case ISD::BIT_CONVERT:
2405 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2406 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2407 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2408 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2414 unsigned OpOpcode = Operand.getNode()->getOpcode();
2416 case ISD::TokenFactor:
2417 case ISD::MERGE_VALUES:
2418 case ISD::CONCAT_VECTORS:
2419 return Operand; // Factor, merge or concat of one node? No need.
2420 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2421 case ISD::FP_EXTEND:
2422 assert(VT.isFloatingPoint() &&
2423 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2424 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2425 assert((!VT.isVector() ||
2426 VT.getVectorNumElements() ==
2427 Operand.getValueType().getVectorNumElements()) &&
2428 "Vector element count mismatch!");
2429 if (Operand.getOpcode() == ISD::UNDEF)
2430 return getUNDEF(VT);
2432 case ISD::SIGN_EXTEND:
2433 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2434 "Invalid SIGN_EXTEND!");
2435 if (Operand.getValueType() == VT) return Operand; // noop extension
2436 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2437 "Invalid sext node, dst < src!");
2438 assert((!VT.isVector() ||
2439 VT.getVectorNumElements() ==
2440 Operand.getValueType().getVectorNumElements()) &&
2441 "Vector element count mismatch!");
2442 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2443 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2445 case ISD::ZERO_EXTEND:
2446 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2447 "Invalid ZERO_EXTEND!");
2448 if (Operand.getValueType() == VT) return Operand; // noop extension
2449 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2450 "Invalid zext node, dst < src!");
2451 assert((!VT.isVector() ||
2452 VT.getVectorNumElements() ==
2453 Operand.getValueType().getVectorNumElements()) &&
2454 "Vector element count mismatch!");
2455 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2456 return getNode(ISD::ZERO_EXTEND, DL, VT,
2457 Operand.getNode()->getOperand(0));
2459 case ISD::ANY_EXTEND:
2460 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2461 "Invalid ANY_EXTEND!");
2462 if (Operand.getValueType() == VT) return Operand; // noop extension
2463 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2464 "Invalid anyext node, dst < src!");
2465 assert((!VT.isVector() ||
2466 VT.getVectorNumElements() ==
2467 Operand.getValueType().getVectorNumElements()) &&
2468 "Vector element count mismatch!");
2469 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2470 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2471 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2474 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2475 "Invalid TRUNCATE!");
2476 if (Operand.getValueType() == VT) return Operand; // noop truncate
2477 assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2478 "Invalid truncate node, src < dst!");
2479 assert((!VT.isVector() ||
2480 VT.getVectorNumElements() ==
2481 Operand.getValueType().getVectorNumElements()) &&
2482 "Vector element count mismatch!");
2483 if (OpOpcode == ISD::TRUNCATE)
2484 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2485 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2486 OpOpcode == ISD::ANY_EXTEND) {
2487 // If the source is smaller than the dest, we still need an extend.
2488 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2489 .bitsLT(VT.getScalarType()))
2490 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2491 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2492 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2494 return Operand.getNode()->getOperand(0);
2497 case ISD::BIT_CONVERT:
2498 // Basic sanity checking.
2499 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2500 && "Cannot BIT_CONVERT between types of different sizes!");
2501 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2502 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2503 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2504 if (OpOpcode == ISD::UNDEF)
2505 return getUNDEF(VT);
2507 case ISD::SCALAR_TO_VECTOR:
2508 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2509 (VT.getVectorElementType() == Operand.getValueType() ||
2510 (VT.getVectorElementType().isInteger() &&
2511 Operand.getValueType().isInteger() &&
2512 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2513 "Illegal SCALAR_TO_VECTOR node!");
2514 if (OpOpcode == ISD::UNDEF)
2515 return getUNDEF(VT);
2516 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2517 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2518 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2519 Operand.getConstantOperandVal(1) == 0 &&
2520 Operand.getOperand(0).getValueType() == VT)
2521 return Operand.getOperand(0);
2524 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2525 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2526 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2527 Operand.getNode()->getOperand(0));
2528 if (OpOpcode == ISD::FNEG) // --X -> X
2529 return Operand.getNode()->getOperand(0);
2532 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2533 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2538 SDVTList VTs = getVTList(VT);
2539 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2540 FoldingSetNodeID ID;
2541 SDValue Ops[1] = { Operand };
2542 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2544 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2545 return SDValue(E, 0);
2547 N = NodeAllocator.Allocate<UnarySDNode>();
2548 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2549 CSEMap.InsertNode(N, IP);
2551 N = NodeAllocator.Allocate<UnarySDNode>();
2552 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2555 AllNodes.push_back(N);
2559 return SDValue(N, 0);
2562 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2564 ConstantSDNode *Cst1,
2565 ConstantSDNode *Cst2) {
2566 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2569 case ISD::ADD: return getConstant(C1 + C2, VT);
2570 case ISD::SUB: return getConstant(C1 - C2, VT);
2571 case ISD::MUL: return getConstant(C1 * C2, VT);
2573 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2576 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2579 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2582 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2584 case ISD::AND: return getConstant(C1 & C2, VT);
2585 case ISD::OR: return getConstant(C1 | C2, VT);
2586 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2587 case ISD::SHL: return getConstant(C1 << C2, VT);
2588 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2589 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2590 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2591 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2598 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2599 SDValue N1, SDValue N2) {
2600 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2601 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2604 case ISD::TokenFactor:
2605 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2606 N2.getValueType() == MVT::Other && "Invalid token factor!");
2607 // Fold trivial token factors.
2608 if (N1.getOpcode() == ISD::EntryToken) return N2;
2609 if (N2.getOpcode() == ISD::EntryToken) return N1;
2610 if (N1 == N2) return N1;
2612 case ISD::CONCAT_VECTORS:
2613 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2614 // one big BUILD_VECTOR.
2615 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2616 N2.getOpcode() == ISD::BUILD_VECTOR) {
2617 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2618 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2619 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2623 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2624 N1.getValueType() == VT && "Binary operator types must match!");
2625 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2626 // worth handling here.
2627 if (N2C && N2C->isNullValue())
2629 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2636 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2637 N1.getValueType() == VT && "Binary operator types must match!");
2638 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2639 // it's worth handling here.
2640 if (N2C && N2C->isNullValue())
2650 assert(VT.isInteger() && "This operator does not apply to FP types!");
2658 if (Opcode == ISD::FADD) {
2660 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2661 if (CFP->getValueAPF().isZero())
2664 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2665 if (CFP->getValueAPF().isZero())
2667 } else if (Opcode == ISD::FSUB) {
2669 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2670 if (CFP->getValueAPF().isZero())
2674 assert(N1.getValueType() == N2.getValueType() &&
2675 N1.getValueType() == VT && "Binary operator types must match!");
2677 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2678 assert(N1.getValueType() == VT &&
2679 N1.getValueType().isFloatingPoint() &&
2680 N2.getValueType().isFloatingPoint() &&
2681 "Invalid FCOPYSIGN!");
2688 assert(VT == N1.getValueType() &&
2689 "Shift operators return type must be the same as their first arg");
2690 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2691 "Shifts only work on integers");
2693 // Always fold shifts of i1 values so the code generator doesn't need to
2694 // handle them. Since we know the size of the shift has to be less than the
2695 // size of the value, the shift/rotate count is guaranteed to be zero.
2698 if (N2C && N2C->isNullValue())
2701 case ISD::FP_ROUND_INREG: {
2702 EVT EVT = cast<VTSDNode>(N2)->getVT();
2703 assert(VT == N1.getValueType() && "Not an inreg round!");
2704 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2705 "Cannot FP_ROUND_INREG integer types");
2706 assert(EVT.isVector() == VT.isVector() &&
2707 "FP_ROUND_INREG type should be vector iff the operand "
2709 assert((!EVT.isVector() ||
2710 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2711 "Vector element counts must match in FP_ROUND_INREG");
2712 assert(EVT.bitsLE(VT) && "Not rounding down!");
2713 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2717 assert(VT.isFloatingPoint() &&
2718 N1.getValueType().isFloatingPoint() &&
2719 VT.bitsLE(N1.getValueType()) &&
2720 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2721 if (N1.getValueType() == VT) return N1; // noop conversion.
2723 case ISD::AssertSext:
2724 case ISD::AssertZext: {
2725 EVT EVT = cast<VTSDNode>(N2)->getVT();
2726 assert(VT == N1.getValueType() && "Not an inreg extend!");
2727 assert(VT.isInteger() && EVT.isInteger() &&
2728 "Cannot *_EXTEND_INREG FP types");
2729 assert(!EVT.isVector() &&
2730 "AssertSExt/AssertZExt type should be the vector element type "
2731 "rather than the vector type!");
2732 assert(EVT.bitsLE(VT) && "Not extending!");
2733 if (VT == EVT) return N1; // noop assertion.
2736 case ISD::SIGN_EXTEND_INREG: {
2737 EVT EVT = cast<VTSDNode>(N2)->getVT();
2738 assert(VT == N1.getValueType() && "Not an inreg extend!");
2739 assert(VT.isInteger() && EVT.isInteger() &&
2740 "Cannot *_EXTEND_INREG FP types");
2741 assert(EVT.isVector() == VT.isVector() &&
2742 "SIGN_EXTEND_INREG type should be vector iff the operand "
2744 assert((!EVT.isVector() ||
2745 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2746 "Vector element counts must match in SIGN_EXTEND_INREG");
2747 assert(EVT.bitsLE(VT) && "Not extending!");
2748 if (EVT == VT) return N1; // Not actually extending
2751 APInt Val = N1C->getAPIntValue();
2752 unsigned FromBits = EVT.getScalarType().getSizeInBits();
2753 Val <<= Val.getBitWidth()-FromBits;
2754 Val = Val.ashr(Val.getBitWidth()-FromBits);
2755 return getConstant(Val, VT);
2759 case ISD::EXTRACT_VECTOR_ELT:
2760 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2761 if (N1.getOpcode() == ISD::UNDEF)
2762 return getUNDEF(VT);
2764 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2765 // expanding copies of large vectors from registers.
2767 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2768 N1.getNumOperands() > 0) {
2770 N1.getOperand(0).getValueType().getVectorNumElements();
2771 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2772 N1.getOperand(N2C->getZExtValue() / Factor),
2773 getConstant(N2C->getZExtValue() % Factor,
2774 N2.getValueType()));
2777 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2778 // expanding large vector constants.
2779 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2780 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2781 EVT VEltTy = N1.getValueType().getVectorElementType();
2782 if (Elt.getValueType() != VEltTy) {
2783 // If the vector element type is not legal, the BUILD_VECTOR operands
2784 // are promoted and implicitly truncated. Make that explicit here.
2785 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2788 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2789 // result is implicitly extended.
2790 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2795 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2796 // operations are lowered to scalars.
2797 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2798 // If the indices are the same, return the inserted element else
2799 // if the indices are known different, extract the element from
2800 // the original vector.
2801 if (N1.getOperand(2) == N2) {
2802 if (VT == N1.getOperand(1).getValueType())
2803 return N1.getOperand(1);
2805 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
2806 } else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2807 isa<ConstantSDNode>(N2))
2808 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2811 case ISD::EXTRACT_ELEMENT:
2812 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2813 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2814 (N1.getValueType().isInteger() == VT.isInteger()) &&
2815 "Wrong types for EXTRACT_ELEMENT!");
2817 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2818 // 64-bit integers into 32-bit parts. Instead of building the extract of
2819 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2820 if (N1.getOpcode() == ISD::BUILD_PAIR)
2821 return N1.getOperand(N2C->getZExtValue());
2823 // EXTRACT_ELEMENT of a constant int is also very common.
2824 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2825 unsigned ElementSize = VT.getSizeInBits();
2826 unsigned Shift = ElementSize * N2C->getZExtValue();
2827 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2828 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2831 case ISD::EXTRACT_SUBVECTOR:
2832 if (N1.getValueType() == VT) // Trivial extraction.
2839 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2840 if (SV.getNode()) return SV;
2841 } else { // Cannonicalize constant to RHS if commutative
2842 if (isCommutativeBinOp(Opcode)) {
2843 std::swap(N1C, N2C);
2849 // Constant fold FP operations.
2850 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2851 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2853 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2854 // Cannonicalize constant to RHS if commutative
2855 std::swap(N1CFP, N2CFP);
2857 } else if (N2CFP && VT != MVT::ppcf128) {
2858 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2859 APFloat::opStatus s;
2862 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2863 if (s != APFloat::opInvalidOp)
2864 return getConstantFP(V1, VT);
2867 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2868 if (s!=APFloat::opInvalidOp)
2869 return getConstantFP(V1, VT);
2872 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2873 if (s!=APFloat::opInvalidOp)
2874 return getConstantFP(V1, VT);
2877 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2878 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2879 return getConstantFP(V1, VT);
2882 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2883 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2884 return getConstantFP(V1, VT);
2886 case ISD::FCOPYSIGN:
2888 return getConstantFP(V1, VT);
2894 // Canonicalize an UNDEF to the RHS, even over a constant.
2895 if (N1.getOpcode() == ISD::UNDEF) {
2896 if (isCommutativeBinOp(Opcode)) {
2900 case ISD::FP_ROUND_INREG:
2901 case ISD::SIGN_EXTEND_INREG:
2907 return N1; // fold op(undef, arg2) -> undef
2915 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2916 // For vectors, we can't easily build an all zero vector, just return
2923 // Fold a bunch of operators when the RHS is undef.
2924 if (N2.getOpcode() == ISD::UNDEF) {
2927 if (N1.getOpcode() == ISD::UNDEF)
2928 // Handle undef ^ undef -> 0 special case. This is a common
2930 return getConstant(0, VT);
2940 return N2; // fold op(arg1, undef) -> undef
2954 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2955 // For vectors, we can't easily build an all zero vector, just return
2960 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2961 // For vectors, we can't easily build an all one vector, just return
2969 // Memoize this node if possible.
2971 SDVTList VTs = getVTList(VT);
2972 if (VT != MVT::Flag) {
2973 SDValue Ops[] = { N1, N2 };
2974 FoldingSetNodeID ID;
2975 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2977 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2978 return SDValue(E, 0);
2980 N = NodeAllocator.Allocate<BinarySDNode>();
2981 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2982 CSEMap.InsertNode(N, IP);
2984 N = NodeAllocator.Allocate<BinarySDNode>();
2985 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2988 AllNodes.push_back(N);
2992 return SDValue(N, 0);
2995 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2996 SDValue N1, SDValue N2, SDValue N3) {
2997 // Perform various simplifications.
2998 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2999 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
3001 case ISD::CONCAT_VECTORS:
3002 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3003 // one big BUILD_VECTOR.
3004 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3005 N2.getOpcode() == ISD::BUILD_VECTOR &&
3006 N3.getOpcode() == ISD::BUILD_VECTOR) {
3007 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
3008 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
3009 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
3010 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
3014 // Use FoldSetCC to simplify SETCC's.
3015 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3016 if (Simp.getNode()) return Simp;
3021 if (N1C->getZExtValue())
3022 return N2; // select true, X, Y -> X
3024 return N3; // select false, X, Y -> Y
3027 if (N2 == N3) return N2; // select C, X, X -> X
3031 if (N2C->getZExtValue()) // Unconditional branch
3032 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
3034 return N1; // Never-taken branch
3037 case ISD::VECTOR_SHUFFLE:
3038 llvm_unreachable("should use getVectorShuffle constructor!");
3040 case ISD::BIT_CONVERT:
3041 // Fold bit_convert nodes from a type to themselves.
3042 if (N1.getValueType() == VT)
3047 // Memoize node if it doesn't produce a flag.
3049 SDVTList VTs = getVTList(VT);
3050 if (VT != MVT::Flag) {
3051 SDValue Ops[] = { N1, N2, N3 };
3052 FoldingSetNodeID ID;
3053 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3055 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3056 return SDValue(E, 0);
3058 N = NodeAllocator.Allocate<TernarySDNode>();
3059 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3060 CSEMap.InsertNode(N, IP);
3062 N = NodeAllocator.Allocate<TernarySDNode>();
3063 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3066 AllNodes.push_back(N);
3070 return SDValue(N, 0);
3073 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3074 SDValue N1, SDValue N2, SDValue N3,
3076 SDValue Ops[] = { N1, N2, N3, N4 };
3077 return getNode(Opcode, DL, VT, Ops, 4);
3080 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3081 SDValue N1, SDValue N2, SDValue N3,
3082 SDValue N4, SDValue N5) {
3083 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3084 return getNode(Opcode, DL, VT, Ops, 5);
3087 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3088 /// the incoming stack arguments to be loaded from the stack.
3089 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3090 SmallVector<SDValue, 8> ArgChains;
3092 // Include the original chain at the beginning of the list. When this is
3093 // used by target LowerCall hooks, this helps legalize find the
3094 // CALLSEQ_BEGIN node.
3095 ArgChains.push_back(Chain);
3097 // Add a chain value for each stack argument.
3098 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3099 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3100 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3101 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3102 if (FI->getIndex() < 0)
3103 ArgChains.push_back(SDValue(L, 1));
3105 // Build a tokenfactor for all the chains.
3106 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
3107 &ArgChains[0], ArgChains.size());
3110 /// getMemsetValue - Vectorized representation of the memset value
3112 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3114 unsigned NumBits = VT.getScalarType().getSizeInBits();
3115 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3116 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
3118 for (unsigned i = NumBits; i > 8; i >>= 1) {
3119 Val = (Val << Shift) | Val;
3123 return DAG.getConstant(Val, VT);
3124 return DAG.getConstantFP(APFloat(Val), VT);
3127 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3128 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3130 for (unsigned i = NumBits; i > 8; i >>= 1) {
3131 Value = DAG.getNode(ISD::OR, dl, VT,
3132 DAG.getNode(ISD::SHL, dl, VT, Value,
3133 DAG.getConstant(Shift,
3134 TLI.getShiftAmountTy())),
3142 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3143 /// used when a memcpy is turned into a memset when the source is a constant
3145 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3146 const TargetLowering &TLI,
3147 std::string &Str, unsigned Offset) {
3148 // Handle vector with all elements zero.
3151 return DAG.getConstant(0, VT);
3152 unsigned NumElts = VT.getVectorNumElements();
3153 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3154 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3156 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts)));
3159 assert(!VT.isVector() && "Can't handle vector type here!");
3160 unsigned NumBits = VT.getSizeInBits();
3161 unsigned MSB = NumBits / 8;
3163 if (TLI.isLittleEndian())
3164 Offset = Offset + MSB - 1;
3165 for (unsigned i = 0; i != MSB; ++i) {
3166 Val = (Val << 8) | (unsigned char)Str[Offset];
3167 Offset += TLI.isLittleEndian() ? -1 : 1;
3169 return DAG.getConstant(Val, VT);
3172 /// getMemBasePlusOffset - Returns base and offset node for the
3174 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3175 SelectionDAG &DAG) {
3176 EVT VT = Base.getValueType();
3177 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3178 VT, Base, DAG.getConstant(Offset, VT));
3181 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3183 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3184 unsigned SrcDelta = 0;
3185 GlobalAddressSDNode *G = NULL;
3186 if (Src.getOpcode() == ISD::GlobalAddress)
3187 G = cast<GlobalAddressSDNode>(Src);
3188 else if (Src.getOpcode() == ISD::ADD &&
3189 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3190 Src.getOperand(1).getOpcode() == ISD::Constant) {
3191 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3192 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3197 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3198 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3204 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3205 /// to replace the memset / memcpy is below the threshold. It also returns the
3206 /// types of the sequence of memory ops to perform memset / memcpy.
3208 bool MeetsMaxMemopRequirement(std::vector<EVT> &MemOps,
3209 SDValue Dst, SDValue Src,
3210 unsigned Limit, uint64_t Size, unsigned &Align,
3211 std::string &Str, bool &isSrcStr,
3213 const TargetLowering &TLI) {
3214 isSrcStr = isMemSrcFromString(Src, Str);
3215 bool isSrcConst = isa<ConstantSDNode>(Src);
3216 EVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
3217 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses(VT);
3218 if (VT != MVT::Other) {
3219 const Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3220 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3221 // If source is a string constant, this will require an unaligned load.
3222 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3223 if (Dst.getOpcode() != ISD::FrameIndex) {
3224 // Can't change destination alignment. It requires a unaligned store.
3228 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3229 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3230 if (MFI->isFixedObjectIndex(FI)) {
3231 // Can't change destination alignment. It requires a unaligned store.
3235 // Give the stack frame object a larger alignment if needed.
3236 if (MFI->getObjectAlignment(FI) < NewAlign)
3237 MFI->setObjectAlignment(FI, NewAlign);
3244 if (VT == MVT::Other) {
3245 if (TLI.allowsUnalignedMemoryAccesses(MVT::i64)) {
3248 switch (Align & 7) {
3249 case 0: VT = MVT::i64; break;
3250 case 4: VT = MVT::i32; break;
3251 case 2: VT = MVT::i16; break;
3252 default: VT = MVT::i8; break;
3257 while (!TLI.isTypeLegal(LVT))
3258 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3259 assert(LVT.isInteger());
3265 unsigned NumMemOps = 0;
3267 unsigned VTSize = VT.getSizeInBits() / 8;
3268 while (VTSize > Size) {
3269 // For now, only use non-vector load / store's for the left-over pieces.
3270 if (VT.isVector()) {
3272 while (!TLI.isTypeLegal(VT))
3273 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3274 VTSize = VT.getSizeInBits() / 8;
3276 // This can result in a type that is not legal on the target, e.g.
3277 // 1 or 2 bytes on PPC.
3278 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3283 if (++NumMemOps > Limit)
3285 MemOps.push_back(VT);
3292 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3293 SDValue Chain, SDValue Dst,
3294 SDValue Src, uint64_t Size,
3295 unsigned Align, bool AlwaysInline,
3296 const Value *DstSV, uint64_t DstSVOff,
3297 const Value *SrcSV, uint64_t SrcSVOff){
3298 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3300 // Expand memcpy to a series of load and store ops if the size operand falls
3301 // below a certain threshold.
3302 std::vector<EVT> MemOps;
3303 uint64_t Limit = -1ULL;
3305 Limit = TLI.getMaxStoresPerMemcpy();
3306 unsigned DstAlign = Align; // Destination alignment can change.
3309 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3310 Str, CopyFromStr, DAG, TLI))
3314 bool isZeroStr = CopyFromStr && Str.empty();
3315 SmallVector<SDValue, 8> OutChains;
3316 unsigned NumMemOps = MemOps.size();
3317 uint64_t SrcOff = 0, DstOff = 0;
3318 for (unsigned i = 0; i != NumMemOps; ++i) {
3320 unsigned VTSize = VT.getSizeInBits() / 8;
3321 SDValue Value, Store;
3323 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3324 // It's unlikely a store of a vector immediate can be done in a single
3325 // instruction. It would require a load from a constantpool first.
3326 // We also handle store a vector with all zero's.
3327 // FIXME: Handle other cases where store of vector immediate is done in
3328 // a single instruction.
3329 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3330 Store = DAG.getStore(Chain, dl, Value,
3331 getMemBasePlusOffset(Dst, DstOff, DAG),
3332 DstSV, DstSVOff + DstOff, false, false, DstAlign);
3334 // The type might not be legal for the target. This should only happen
3335 // if the type is smaller than a legal type, as on PPC, so the right
3336 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3337 // to Load/Store if NVT==VT.
3338 // FIXME does the case above also need this?
3339 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3340 assert(NVT.bitsGE(VT));
3341 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3342 getMemBasePlusOffset(Src, SrcOff, DAG),
3343 SrcSV, SrcSVOff + SrcOff, VT, false, false, Align);
3344 Store = DAG.getTruncStore(Chain, dl, Value,
3345 getMemBasePlusOffset(Dst, DstOff, DAG),
3346 DstSV, DstSVOff + DstOff, VT, false, false,
3349 OutChains.push_back(Store);
3354 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3355 &OutChains[0], OutChains.size());
3358 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3359 SDValue Chain, SDValue Dst,
3360 SDValue Src, uint64_t Size,
3361 unsigned Align, bool AlwaysInline,
3362 const Value *DstSV, uint64_t DstSVOff,
3363 const Value *SrcSV, uint64_t SrcSVOff){
3364 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3366 // Expand memmove to a series of load and store ops if the size operand falls
3367 // below a certain threshold.
3368 std::vector<EVT> MemOps;
3369 uint64_t Limit = -1ULL;
3371 Limit = TLI.getMaxStoresPerMemmove();
3372 unsigned DstAlign = Align; // Destination alignment can change.
3375 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3376 Str, CopyFromStr, DAG, TLI))
3379 uint64_t SrcOff = 0, DstOff = 0;
3381 SmallVector<SDValue, 8> LoadValues;
3382 SmallVector<SDValue, 8> LoadChains;
3383 SmallVector<SDValue, 8> OutChains;
3384 unsigned NumMemOps = MemOps.size();
3385 for (unsigned i = 0; i < NumMemOps; i++) {
3387 unsigned VTSize = VT.getSizeInBits() / 8;
3388 SDValue Value, Store;
3390 Value = DAG.getLoad(VT, dl, Chain,
3391 getMemBasePlusOffset(Src, SrcOff, DAG),
3392 SrcSV, SrcSVOff + SrcOff, false, false, Align);
3393 LoadValues.push_back(Value);
3394 LoadChains.push_back(Value.getValue(1));
3397 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3398 &LoadChains[0], LoadChains.size());
3400 for (unsigned i = 0; i < NumMemOps; i++) {
3402 unsigned VTSize = VT.getSizeInBits() / 8;
3403 SDValue Value, Store;
3405 Store = DAG.getStore(Chain, dl, LoadValues[i],
3406 getMemBasePlusOffset(Dst, DstOff, DAG),
3407 DstSV, DstSVOff + DstOff, false, false, DstAlign);
3408 OutChains.push_back(Store);
3412 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3413 &OutChains[0], OutChains.size());
3416 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3417 SDValue Chain, SDValue Dst,
3418 SDValue Src, uint64_t Size,
3420 const Value *DstSV, uint64_t DstSVOff) {
3421 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3423 // Expand memset to a series of load/store ops if the size operand
3424 // falls below a certain threshold.
3425 std::vector<EVT> MemOps;
3428 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3429 Size, Align, Str, CopyFromStr, DAG, TLI))
3432 SmallVector<SDValue, 8> OutChains;
3433 uint64_t DstOff = 0;
3435 unsigned NumMemOps = MemOps.size();
3436 for (unsigned i = 0; i < NumMemOps; i++) {
3438 unsigned VTSize = VT.getSizeInBits() / 8;
3439 SDValue Value = getMemsetValue(Src, VT, DAG, dl);
3440 SDValue Store = DAG.getStore(Chain, dl, Value,
3441 getMemBasePlusOffset(Dst, DstOff, DAG),
3442 DstSV, DstSVOff + DstOff, false, false, 0);
3443 OutChains.push_back(Store);
3447 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3448 &OutChains[0], OutChains.size());
3451 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3452 SDValue Src, SDValue Size,
3453 unsigned Align, bool AlwaysInline,
3454 const Value *DstSV, uint64_t DstSVOff,
3455 const Value *SrcSV, uint64_t SrcSVOff) {
3457 // Check to see if we should lower the memcpy to loads and stores first.
3458 // For cases within the target-specified limits, this is the best choice.
3459 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3461 // Memcpy with size zero? Just return the original chain.
3462 if (ConstantSize->isNullValue())
3466 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3467 ConstantSize->getZExtValue(),
3468 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3469 if (Result.getNode())
3473 // Then check to see if we should lower the memcpy with target-specific
3474 // code. If the target chooses to do this, this is the next best.
3476 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3478 DstSV, DstSVOff, SrcSV, SrcSVOff);
3479 if (Result.getNode())
3482 // If we really need inline code and the target declined to provide it,
3483 // use a (potentially long) sequence of loads and stores.
3485 assert(ConstantSize && "AlwaysInline requires a constant size!");
3486 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3487 ConstantSize->getZExtValue(), Align, true,
3488 DstSV, DstSVOff, SrcSV, SrcSVOff);
3491 // Emit a library call.
3492 TargetLowering::ArgListTy Args;
3493 TargetLowering::ArgListEntry Entry;
3494 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3495 Entry.Node = Dst; Args.push_back(Entry);
3496 Entry.Node = Src; Args.push_back(Entry);
3497 Entry.Node = Size; Args.push_back(Entry);
3498 // FIXME: pass in DebugLoc
3499 std::pair<SDValue,SDValue> CallResult =
3500 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3501 false, false, false, false, 0,
3502 TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3503 /*isReturnValueUsed=*/false,
3504 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3505 TLI.getPointerTy()),
3507 return CallResult.second;
3510 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3511 SDValue Src, SDValue Size,
3513 const Value *DstSV, uint64_t DstSVOff,
3514 const Value *SrcSV, uint64_t SrcSVOff) {
3516 // Check to see if we should lower the memmove to loads and stores first.
3517 // For cases within the target-specified limits, this is the best choice.
3518 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3520 // Memmove with size zero? Just return the original chain.
3521 if (ConstantSize->isNullValue())
3525 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3526 ConstantSize->getZExtValue(),
3527 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3528 if (Result.getNode())
3532 // Then check to see if we should lower the memmove with target-specific
3533 // code. If the target chooses to do this, this is the next best.
3535 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
3536 DstSV, DstSVOff, SrcSV, SrcSVOff);
3537 if (Result.getNode())
3540 // Emit a library call.
3541 TargetLowering::ArgListTy Args;
3542 TargetLowering::ArgListEntry Entry;
3543 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3544 Entry.Node = Dst; Args.push_back(Entry);
3545 Entry.Node = Src; Args.push_back(Entry);
3546 Entry.Node = Size; Args.push_back(Entry);
3547 // FIXME: pass in DebugLoc
3548 std::pair<SDValue,SDValue> CallResult =
3549 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3550 false, false, false, false, 0,
3551 TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3552 /*isReturnValueUsed=*/false,
3553 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3554 TLI.getPointerTy()),
3556 return CallResult.second;
3559 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3560 SDValue Src, SDValue Size,
3562 const Value *DstSV, uint64_t DstSVOff) {
3564 // Check to see if we should lower the memset to stores first.
3565 // For cases within the target-specified limits, this is the best choice.
3566 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3568 // Memset with size zero? Just return the original chain.
3569 if (ConstantSize->isNullValue())
3573 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3574 Align, DstSV, DstSVOff);
3575 if (Result.getNode())
3579 // Then check to see if we should lower the memset with target-specific
3580 // code. If the target chooses to do this, this is the next best.
3582 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
3584 if (Result.getNode())
3587 // Emit a library call.
3588 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3589 TargetLowering::ArgListTy Args;
3590 TargetLowering::ArgListEntry Entry;
3591 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3592 Args.push_back(Entry);
3593 // Extend or truncate the argument to be an i32 value for the call.
3594 if (Src.getValueType().bitsGT(MVT::i32))
3595 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3597 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3599 Entry.Ty = Type::getInt32Ty(*getContext());
3600 Entry.isSExt = true;
3601 Args.push_back(Entry);
3603 Entry.Ty = IntPtrTy;
3604 Entry.isSExt = false;
3605 Args.push_back(Entry);
3606 // FIXME: pass in DebugLoc
3607 std::pair<SDValue,SDValue> CallResult =
3608 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3609 false, false, false, false, 0,
3610 TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3611 /*isReturnValueUsed=*/false,
3612 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3613 TLI.getPointerTy()),
3615 return CallResult.second;
3618 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3620 SDValue Ptr, SDValue Cmp,
3621 SDValue Swp, const Value* PtrVal,
3622 unsigned Alignment) {
3623 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3624 Alignment = getEVTAlignment(MemVT);
3626 // Check if the memory reference references a frame index
3628 if (const FrameIndexSDNode *FI =
3629 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3630 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3632 MachineFunction &MF = getMachineFunction();
3633 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3635 // For now, atomics are considered to be volatile always.
3636 Flags |= MachineMemOperand::MOVolatile;
3638 MachineMemOperand *MMO =
3639 MF.getMachineMemOperand(PtrVal, Flags, 0,
3640 MemVT.getStoreSize(), Alignment);
3642 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3645 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3647 SDValue Ptr, SDValue Cmp,
3648 SDValue Swp, MachineMemOperand *MMO) {
3649 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3650 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3652 EVT VT = Cmp.getValueType();
3654 SDVTList VTs = getVTList(VT, MVT::Other);
3655 FoldingSetNodeID ID;
3656 ID.AddInteger(MemVT.getRawBits());
3657 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3658 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3660 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3661 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3662 return SDValue(E, 0);
3664 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3665 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3666 CSEMap.InsertNode(N, IP);
3667 AllNodes.push_back(N);
3668 return SDValue(N, 0);
3671 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3673 SDValue Ptr, SDValue Val,
3674 const Value* PtrVal,
3675 unsigned Alignment) {
3676 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3677 Alignment = getEVTAlignment(MemVT);
3679 // Check if the memory reference references a frame index
3681 if (const FrameIndexSDNode *FI =
3682 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3683 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3685 MachineFunction &MF = getMachineFunction();
3686 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3688 // For now, atomics are considered to be volatile always.
3689 Flags |= MachineMemOperand::MOVolatile;
3691 MachineMemOperand *MMO =
3692 MF.getMachineMemOperand(PtrVal, Flags, 0,
3693 MemVT.getStoreSize(), Alignment);
3695 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
3698 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3700 SDValue Ptr, SDValue Val,
3701 MachineMemOperand *MMO) {
3702 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3703 Opcode == ISD::ATOMIC_LOAD_SUB ||
3704 Opcode == ISD::ATOMIC_LOAD_AND ||
3705 Opcode == ISD::ATOMIC_LOAD_OR ||
3706 Opcode == ISD::ATOMIC_LOAD_XOR ||
3707 Opcode == ISD::ATOMIC_LOAD_NAND ||
3708 Opcode == ISD::ATOMIC_LOAD_MIN ||
3709 Opcode == ISD::ATOMIC_LOAD_MAX ||
3710 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3711 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3712 Opcode == ISD::ATOMIC_SWAP) &&
3713 "Invalid Atomic Op");
3715 EVT VT = Val.getValueType();
3717 SDVTList VTs = getVTList(VT, MVT::Other);
3718 FoldingSetNodeID ID;
3719 ID.AddInteger(MemVT.getRawBits());
3720 SDValue Ops[] = {Chain, Ptr, Val};
3721 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3723 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3724 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3725 return SDValue(E, 0);
3727 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3728 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Val, MMO);
3729 CSEMap.InsertNode(N, IP);
3730 AllNodes.push_back(N);
3731 return SDValue(N, 0);
3734 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3735 /// Allowed to return something different (and simpler) if Simplify is true.
3736 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3741 SmallVector<EVT, 4> VTs;
3742 VTs.reserve(NumOps);
3743 for (unsigned i = 0; i < NumOps; ++i)
3744 VTs.push_back(Ops[i].getValueType());
3745 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3750 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3751 const EVT *VTs, unsigned NumVTs,
3752 const SDValue *Ops, unsigned NumOps,
3753 EVT MemVT, const Value *srcValue, int SVOff,
3754 unsigned Align, bool Vol,
3755 bool ReadMem, bool WriteMem) {
3756 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3757 MemVT, srcValue, SVOff, Align, Vol,
3762 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3763 const SDValue *Ops, unsigned NumOps,
3764 EVT MemVT, const Value *srcValue, int SVOff,
3765 unsigned Align, bool Vol,
3766 bool ReadMem, bool WriteMem) {
3767 if (Align == 0) // Ensure that codegen never sees alignment 0
3768 Align = getEVTAlignment(MemVT);
3770 MachineFunction &MF = getMachineFunction();
3773 Flags |= MachineMemOperand::MOStore;
3775 Flags |= MachineMemOperand::MOLoad;
3777 Flags |= MachineMemOperand::MOVolatile;
3778 MachineMemOperand *MMO =
3779 MF.getMachineMemOperand(srcValue, Flags, SVOff,
3780 MemVT.getStoreSize(), Align);
3782 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3786 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3787 const SDValue *Ops, unsigned NumOps,
3788 EVT MemVT, MachineMemOperand *MMO) {
3789 assert((Opcode == ISD::INTRINSIC_VOID ||
3790 Opcode == ISD::INTRINSIC_W_CHAIN ||
3791 (Opcode <= INT_MAX &&
3792 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
3793 "Opcode is not a memory-accessing opcode!");
3795 // Memoize the node unless it returns a flag.
3796 MemIntrinsicSDNode *N;
3797 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3798 FoldingSetNodeID ID;
3799 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3801 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3802 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
3803 return SDValue(E, 0);
3806 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3807 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3808 CSEMap.InsertNode(N, IP);
3810 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3811 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3813 AllNodes.push_back(N);
3814 return SDValue(N, 0);
3818 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3819 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3820 SDValue Ptr, SDValue Offset,
3821 const Value *SV, int SVOffset, EVT MemVT,
3822 bool isVolatile, bool isNonTemporal,
3823 unsigned Alignment) {
3824 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3825 Alignment = getEVTAlignment(VT);
3827 // Check if the memory reference references a frame index
3829 if (const FrameIndexSDNode *FI =
3830 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3831 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3833 MachineFunction &MF = getMachineFunction();
3834 unsigned Flags = MachineMemOperand::MOLoad;
3836 Flags |= MachineMemOperand::MOVolatile;
3838 Flags |= MachineMemOperand::MONonTemporal;
3839 MachineMemOperand *MMO =
3840 MF.getMachineMemOperand(SV, Flags, SVOffset,
3841 MemVT.getStoreSize(), Alignment);
3842 return getLoad(AM, dl, ExtType, VT, Chain, Ptr, Offset, MemVT, MMO);
3846 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3847 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3848 SDValue Ptr, SDValue Offset, EVT MemVT,
3849 MachineMemOperand *MMO) {
3851 ExtType = ISD::NON_EXTLOAD;
3852 } else if (ExtType == ISD::NON_EXTLOAD) {
3853 assert(VT == MemVT && "Non-extending load from different memory type!");
3856 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
3857 "Should only be an extending load, not truncating!");
3858 assert(VT.isInteger() == MemVT.isInteger() &&
3859 "Cannot convert from FP to Int or Int -> FP!");
3860 assert(VT.isVector() == MemVT.isVector() &&
3861 "Cannot use trunc store to convert to or from a vector!");
3862 assert((!VT.isVector() ||
3863 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
3864 "Cannot use trunc store to change the number of vector elements!");
3867 bool Indexed = AM != ISD::UNINDEXED;
3868 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3869 "Unindexed load with an offset!");
3871 SDVTList VTs = Indexed ?
3872 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3873 SDValue Ops[] = { Chain, Ptr, Offset };
3874 FoldingSetNodeID ID;
3875 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3876 ID.AddInteger(MemVT.getRawBits());
3877 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
3878 MMO->isNonTemporal()));
3880 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3881 cast<LoadSDNode>(E)->refineAlignment(MMO);
3882 return SDValue(E, 0);
3884 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3885 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, MemVT, MMO);
3886 CSEMap.InsertNode(N, IP);
3887 AllNodes.push_back(N);
3888 return SDValue(N, 0);
3891 SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
3892 SDValue Chain, SDValue Ptr,
3893 const Value *SV, int SVOffset,
3894 bool isVolatile, bool isNonTemporal,
3895 unsigned Alignment) {
3896 SDValue Undef = getUNDEF(Ptr.getValueType());
3897 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3898 SV, SVOffset, VT, isVolatile, isNonTemporal, Alignment);
3901 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
3902 SDValue Chain, SDValue Ptr,
3904 int SVOffset, EVT MemVT,
3905 bool isVolatile, bool isNonTemporal,
3906 unsigned Alignment) {
3907 SDValue Undef = getUNDEF(Ptr.getValueType());
3908 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3909 SV, SVOffset, MemVT, isVolatile, isNonTemporal, Alignment);
3913 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3914 SDValue Offset, ISD::MemIndexedMode AM) {
3915 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3916 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3917 "Load is already a indexed load!");
3918 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3919 LD->getChain(), Base, Offset, LD->getSrcValue(),
3920 LD->getSrcValueOffset(), LD->getMemoryVT(),
3921 LD->isVolatile(), LD->isNonTemporal(), LD->getAlignment());
3924 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3925 SDValue Ptr, const Value *SV, int SVOffset,
3926 bool isVolatile, bool isNonTemporal,
3927 unsigned Alignment) {
3928 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3929 Alignment = getEVTAlignment(Val.getValueType());
3931 // Check if the memory reference references a frame index
3933 if (const FrameIndexSDNode *FI =
3934 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3935 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3937 MachineFunction &MF = getMachineFunction();
3938 unsigned Flags = MachineMemOperand::MOStore;
3940 Flags |= MachineMemOperand::MOVolatile;
3942 Flags |= MachineMemOperand::MONonTemporal;
3943 MachineMemOperand *MMO =
3944 MF.getMachineMemOperand(SV, Flags, SVOffset,
3945 Val.getValueType().getStoreSize(), Alignment);
3947 return getStore(Chain, dl, Val, Ptr, MMO);
3950 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3951 SDValue Ptr, MachineMemOperand *MMO) {
3952 EVT VT = Val.getValueType();
3953 SDVTList VTs = getVTList(MVT::Other);
3954 SDValue Undef = getUNDEF(Ptr.getValueType());
3955 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3956 FoldingSetNodeID ID;
3957 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3958 ID.AddInteger(VT.getRawBits());
3959 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
3960 MMO->isNonTemporal()));
3962 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3963 cast<StoreSDNode>(E)->refineAlignment(MMO);
3964 return SDValue(E, 0);
3966 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3967 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false, VT, MMO);
3968 CSEMap.InsertNode(N, IP);
3969 AllNodes.push_back(N);
3970 return SDValue(N, 0);
3973 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3974 SDValue Ptr, const Value *SV,
3975 int SVOffset, EVT SVT,
3976 bool isVolatile, bool isNonTemporal,
3977 unsigned Alignment) {
3978 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3979 Alignment = getEVTAlignment(SVT);
3981 // Check if the memory reference references a frame index
3983 if (const FrameIndexSDNode *FI =
3984 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3985 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3987 MachineFunction &MF = getMachineFunction();
3988 unsigned Flags = MachineMemOperand::MOStore;
3990 Flags |= MachineMemOperand::MOVolatile;
3992 Flags |= MachineMemOperand::MONonTemporal;
3993 MachineMemOperand *MMO =
3994 MF.getMachineMemOperand(SV, Flags, SVOffset, SVT.getStoreSize(), Alignment);
3996 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
3999 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
4000 SDValue Ptr, EVT SVT,
4001 MachineMemOperand *MMO) {
4002 EVT VT = Val.getValueType();
4005 return getStore(Chain, dl, Val, Ptr, MMO);
4007 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
4008 "Should only be a truncating store, not extending!");
4009 assert(VT.isInteger() == SVT.isInteger() &&
4010 "Can't do FP-INT conversion!");
4011 assert(VT.isVector() == SVT.isVector() &&
4012 "Cannot use trunc store to convert to or from a vector!");
4013 assert((!VT.isVector() ||
4014 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
4015 "Cannot use trunc store to change the number of vector elements!");
4017 SDVTList VTs = getVTList(MVT::Other);
4018 SDValue Undef = getUNDEF(Ptr.getValueType());
4019 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4020 FoldingSetNodeID ID;
4021 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4022 ID.AddInteger(SVT.getRawBits());
4023 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
4024 MMO->isNonTemporal()));
4026 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4027 cast<StoreSDNode>(E)->refineAlignment(MMO);
4028 return SDValue(E, 0);
4030 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
4031 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true, SVT, MMO);
4032 CSEMap.InsertNode(N, IP);
4033 AllNodes.push_back(N);
4034 return SDValue(N, 0);
4038 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
4039 SDValue Offset, ISD::MemIndexedMode AM) {
4040 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4041 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4042 "Store is already a indexed store!");
4043 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4044 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4045 FoldingSetNodeID ID;
4046 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4047 ID.AddInteger(ST->getMemoryVT().getRawBits());
4048 ID.AddInteger(ST->getRawSubclassData());
4050 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4051 return SDValue(E, 0);
4053 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
4054 new (N) StoreSDNode(Ops, dl, VTs, AM,
4055 ST->isTruncatingStore(), ST->getMemoryVT(),
4056 ST->getMemOperand());
4057 CSEMap.InsertNode(N, IP);
4058 AllNodes.push_back(N);
4059 return SDValue(N, 0);
4062 SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
4063 SDValue Chain, SDValue Ptr,
4065 SDValue Ops[] = { Chain, Ptr, SV };
4066 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
4069 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4070 const SDUse *Ops, unsigned NumOps) {
4072 case 0: return getNode(Opcode, DL, VT);
4073 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4074 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4075 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4079 // Copy from an SDUse array into an SDValue array for use with
4080 // the regular getNode logic.
4081 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4082 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4085 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4086 const SDValue *Ops, unsigned NumOps) {
4088 case 0: return getNode(Opcode, DL, VT);
4089 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4090 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4091 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4097 case ISD::SELECT_CC: {
4098 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4099 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4100 "LHS and RHS of condition must have same type!");
4101 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4102 "True and False arms of SelectCC must have same type!");
4103 assert(Ops[2].getValueType() == VT &&
4104 "select_cc node must be of same type as true and false value!");
4108 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4109 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4110 "LHS/RHS of comparison should match types!");
4117 SDVTList VTs = getVTList(VT);
4119 if (VT != MVT::Flag) {
4120 FoldingSetNodeID ID;
4121 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4124 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4125 return SDValue(E, 0);
4127 N = NodeAllocator.Allocate<SDNode>();
4128 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4129 CSEMap.InsertNode(N, IP);
4131 N = NodeAllocator.Allocate<SDNode>();
4132 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4135 AllNodes.push_back(N);
4139 return SDValue(N, 0);
4142 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4143 const std::vector<EVT> &ResultTys,
4144 const SDValue *Ops, unsigned NumOps) {
4145 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4149 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4150 const EVT *VTs, unsigned NumVTs,
4151 const SDValue *Ops, unsigned NumOps) {
4153 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4154 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4157 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4158 const SDValue *Ops, unsigned NumOps) {
4159 if (VTList.NumVTs == 1)
4160 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4164 // FIXME: figure out how to safely handle things like
4165 // int foo(int x) { return 1 << (x & 255); }
4166 // int bar() { return foo(256); }
4167 case ISD::SRA_PARTS:
4168 case ISD::SRL_PARTS:
4169 case ISD::SHL_PARTS:
4170 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4171 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4172 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4173 else if (N3.getOpcode() == ISD::AND)
4174 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4175 // If the and is only masking out bits that cannot effect the shift,
4176 // eliminate the and.
4177 unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
4178 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4179 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4185 // Memoize the node unless it returns a flag.
4187 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4188 FoldingSetNodeID ID;
4189 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4191 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4192 return SDValue(E, 0);
4195 N = NodeAllocator.Allocate<UnarySDNode>();
4196 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4197 } else if (NumOps == 2) {
4198 N = NodeAllocator.Allocate<BinarySDNode>();
4199 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4200 } else if (NumOps == 3) {
4201 N = NodeAllocator.Allocate<TernarySDNode>();
4202 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4204 N = NodeAllocator.Allocate<SDNode>();
4205 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4207 CSEMap.InsertNode(N, IP);
4210 N = NodeAllocator.Allocate<UnarySDNode>();
4211 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4212 } else if (NumOps == 2) {
4213 N = NodeAllocator.Allocate<BinarySDNode>();
4214 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4215 } else if (NumOps == 3) {
4216 N = NodeAllocator.Allocate<TernarySDNode>();
4217 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4219 N = NodeAllocator.Allocate<SDNode>();
4220 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4223 AllNodes.push_back(N);
4227 return SDValue(N, 0);
4230 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4231 return getNode(Opcode, DL, VTList, 0, 0);
4234 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4236 SDValue Ops[] = { N1 };
4237 return getNode(Opcode, DL, VTList, Ops, 1);
4240 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4241 SDValue N1, SDValue N2) {
4242 SDValue Ops[] = { N1, N2 };
4243 return getNode(Opcode, DL, VTList, Ops, 2);
4246 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4247 SDValue N1, SDValue N2, SDValue N3) {
4248 SDValue Ops[] = { N1, N2, N3 };
4249 return getNode(Opcode, DL, VTList, Ops, 3);
4252 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4253 SDValue N1, SDValue N2, SDValue N3,
4255 SDValue Ops[] = { N1, N2, N3, N4 };
4256 return getNode(Opcode, DL, VTList, Ops, 4);
4259 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4260 SDValue N1, SDValue N2, SDValue N3,
4261 SDValue N4, SDValue N5) {
4262 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4263 return getNode(Opcode, DL, VTList, Ops, 5);
4266 SDVTList SelectionDAG::getVTList(EVT VT) {
4267 return makeVTList(SDNode::getValueTypeList(VT), 1);
4270 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4271 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4272 E = VTList.rend(); I != E; ++I)
4273 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4276 EVT *Array = Allocator.Allocate<EVT>(2);
4279 SDVTList Result = makeVTList(Array, 2);
4280 VTList.push_back(Result);
4284 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4285 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4286 E = VTList.rend(); I != E; ++I)
4287 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4291 EVT *Array = Allocator.Allocate<EVT>(3);
4295 SDVTList Result = makeVTList(Array, 3);
4296 VTList.push_back(Result);
4300 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4301 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4302 E = VTList.rend(); I != E; ++I)
4303 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4304 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4307 EVT *Array = Allocator.Allocate<EVT>(4);
4312 SDVTList Result = makeVTList(Array, 4);
4313 VTList.push_back(Result);
4317 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4319 case 0: llvm_unreachable("Cannot have nodes without results!");
4320 case 1: return getVTList(VTs[0]);
4321 case 2: return getVTList(VTs[0], VTs[1]);
4322 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4323 case 4: return getVTList(VTs[0], VTs[1], VTs[2], VTs[3]);
4327 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4328 E = VTList.rend(); I != E; ++I) {
4329 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4332 bool NoMatch = false;
4333 for (unsigned i = 2; i != NumVTs; ++i)
4334 if (VTs[i] != I->VTs[i]) {
4342 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4343 std::copy(VTs, VTs+NumVTs, Array);
4344 SDVTList Result = makeVTList(Array, NumVTs);
4345 VTList.push_back(Result);
4350 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4351 /// specified operands. If the resultant node already exists in the DAG,
4352 /// this does not modify the specified node, instead it returns the node that
4353 /// already exists. If the resultant node does not exist in the DAG, the
4354 /// input node is returned. As a degenerate case, if you specify the same
4355 /// input operands as the node already has, the input node is returned.
4356 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4357 SDNode *N = InN.getNode();
4358 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4360 // Check to see if there is no change.
4361 if (Op == N->getOperand(0)) return InN;
4363 // See if the modified node already exists.
4364 void *InsertPos = 0;
4365 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4366 return SDValue(Existing, InN.getResNo());
4368 // Nope it doesn't. Remove the node from its current place in the maps.
4370 if (!RemoveNodeFromCSEMaps(N))
4373 // Now we update the operands.
4374 N->OperandList[0].set(Op);
4376 // If this gets put into a CSE map, add it.
4377 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4381 SDValue SelectionDAG::
4382 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4383 SDNode *N = InN.getNode();
4384 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4386 // Check to see if there is no change.
4387 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4388 return InN; // No operands changed, just return the input node.
4390 // See if the modified node already exists.
4391 void *InsertPos = 0;
4392 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4393 return SDValue(Existing, InN.getResNo());
4395 // Nope it doesn't. Remove the node from its current place in the maps.
4397 if (!RemoveNodeFromCSEMaps(N))
4400 // Now we update the operands.
4401 if (N->OperandList[0] != Op1)
4402 N->OperandList[0].set(Op1);
4403 if (N->OperandList[1] != Op2)
4404 N->OperandList[1].set(Op2);
4406 // If this gets put into a CSE map, add it.
4407 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4411 SDValue SelectionDAG::
4412 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4413 SDValue Ops[] = { Op1, Op2, Op3 };
4414 return UpdateNodeOperands(N, Ops, 3);
4417 SDValue SelectionDAG::
4418 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4419 SDValue Op3, SDValue Op4) {
4420 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4421 return UpdateNodeOperands(N, Ops, 4);
4424 SDValue SelectionDAG::
4425 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4426 SDValue Op3, SDValue Op4, SDValue Op5) {
4427 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4428 return UpdateNodeOperands(N, Ops, 5);
4431 SDValue SelectionDAG::
4432 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4433 SDNode *N = InN.getNode();
4434 assert(N->getNumOperands() == NumOps &&
4435 "Update with wrong number of operands");
4437 // Check to see if there is no change.
4438 bool AnyChange = false;
4439 for (unsigned i = 0; i != NumOps; ++i) {
4440 if (Ops[i] != N->getOperand(i)) {
4446 // No operands changed, just return the input node.
4447 if (!AnyChange) return InN;
4449 // See if the modified node already exists.
4450 void *InsertPos = 0;
4451 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4452 return SDValue(Existing, InN.getResNo());
4454 // Nope it doesn't. Remove the node from its current place in the maps.
4456 if (!RemoveNodeFromCSEMaps(N))
4459 // Now we update the operands.
4460 for (unsigned i = 0; i != NumOps; ++i)
4461 if (N->OperandList[i] != Ops[i])
4462 N->OperandList[i].set(Ops[i]);
4464 // If this gets put into a CSE map, add it.
4465 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4469 /// DropOperands - Release the operands and set this node to have
4471 void SDNode::DropOperands() {
4472 // Unlike the code in MorphNodeTo that does this, we don't need to
4473 // watch for dead nodes here.
4474 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4480 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4483 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4485 SDVTList VTs = getVTList(VT);
4486 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4489 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4490 EVT VT, SDValue Op1) {
4491 SDVTList VTs = getVTList(VT);
4492 SDValue Ops[] = { Op1 };
4493 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4496 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4497 EVT VT, SDValue Op1,
4499 SDVTList VTs = getVTList(VT);
4500 SDValue Ops[] = { Op1, Op2 };
4501 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4504 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4505 EVT VT, SDValue Op1,
4506 SDValue Op2, SDValue Op3) {
4507 SDVTList VTs = getVTList(VT);
4508 SDValue Ops[] = { Op1, Op2, Op3 };
4509 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4512 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4513 EVT VT, const SDValue *Ops,
4515 SDVTList VTs = getVTList(VT);
4516 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4519 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4520 EVT VT1, EVT VT2, const SDValue *Ops,
4522 SDVTList VTs = getVTList(VT1, VT2);
4523 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4526 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4528 SDVTList VTs = getVTList(VT1, VT2);
4529 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4532 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4533 EVT VT1, EVT VT2, EVT VT3,
4534 const SDValue *Ops, unsigned NumOps) {
4535 SDVTList VTs = getVTList(VT1, VT2, VT3);
4536 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4539 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4540 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4541 const SDValue *Ops, unsigned NumOps) {
4542 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4543 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4546 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4549 SDVTList VTs = getVTList(VT1, VT2);
4550 SDValue Ops[] = { Op1 };
4551 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4554 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4556 SDValue Op1, SDValue Op2) {
4557 SDVTList VTs = getVTList(VT1, VT2);
4558 SDValue Ops[] = { Op1, Op2 };
4559 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4562 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4564 SDValue Op1, SDValue Op2,
4566 SDVTList VTs = getVTList(VT1, VT2);
4567 SDValue Ops[] = { Op1, Op2, Op3 };
4568 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4571 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4572 EVT VT1, EVT VT2, EVT VT3,
4573 SDValue Op1, SDValue Op2,
4575 SDVTList VTs = getVTList(VT1, VT2, VT3);
4576 SDValue Ops[] = { Op1, Op2, Op3 };
4577 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4580 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4581 SDVTList VTs, const SDValue *Ops,
4583 N = MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4584 // Reset the NodeID to -1.
4589 /// MorphNodeTo - This *mutates* the specified node to have the specified
4590 /// return type, opcode, and operands.
4592 /// Note that MorphNodeTo returns the resultant node. If there is already a
4593 /// node of the specified opcode and operands, it returns that node instead of
4594 /// the current one. Note that the DebugLoc need not be the same.
4596 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4597 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4598 /// node, and because it doesn't require CSE recalculation for any of
4599 /// the node's users.
4601 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4602 SDVTList VTs, const SDValue *Ops,
4604 // If an identical node already exists, use it.
4606 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4607 FoldingSetNodeID ID;
4608 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4609 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4613 if (!RemoveNodeFromCSEMaps(N))
4616 // Start the morphing.
4618 N->ValueList = VTs.VTs;
4619 N->NumValues = VTs.NumVTs;
4621 // Clear the operands list, updating used nodes to remove this from their
4622 // use list. Keep track of any operands that become dead as a result.
4623 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4624 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4626 SDNode *Used = Use.getNode();
4628 if (Used->use_empty())
4629 DeadNodeSet.insert(Used);
4632 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
4633 // Initialize the memory references information.
4634 MN->setMemRefs(0, 0);
4635 // If NumOps is larger than the # of operands we can have in a
4636 // MachineSDNode, reallocate the operand list.
4637 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
4638 if (MN->OperandsNeedDelete)
4639 delete[] MN->OperandList;
4640 if (NumOps > array_lengthof(MN->LocalOperands))
4641 // We're creating a final node that will live unmorphed for the
4642 // remainder of the current SelectionDAG iteration, so we can allocate
4643 // the operands directly out of a pool with no recycling metadata.
4644 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4647 MN->InitOperands(MN->LocalOperands, Ops, NumOps);
4648 MN->OperandsNeedDelete = false;
4650 MN->InitOperands(MN->OperandList, Ops, NumOps);
4652 // If NumOps is larger than the # of operands we currently have, reallocate
4653 // the operand list.
4654 if (NumOps > N->NumOperands) {
4655 if (N->OperandsNeedDelete)
4656 delete[] N->OperandList;
4657 N->InitOperands(new SDUse[NumOps], Ops, NumOps);
4658 N->OperandsNeedDelete = true;
4660 N->InitOperands(N->OperandList, Ops, NumOps);
4663 // Delete any nodes that are still dead after adding the uses for the
4665 if (!DeadNodeSet.empty()) {
4666 SmallVector<SDNode *, 16> DeadNodes;
4667 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4668 E = DeadNodeSet.end(); I != E; ++I)
4669 if ((*I)->use_empty())
4670 DeadNodes.push_back(*I);
4671 RemoveDeadNodes(DeadNodes);
4675 CSEMap.InsertNode(N, IP); // Memoize the new node.
4680 /// getMachineNode - These are used for target selectors to create a new node
4681 /// with specified return type(s), MachineInstr opcode, and operands.
4683 /// Note that getMachineNode returns the resultant node. If there is already a
4684 /// node of the specified opcode and operands, it returns that node instead of
4685 /// the current one.
4687 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
4688 SDVTList VTs = getVTList(VT);
4689 return getMachineNode(Opcode, dl, VTs, 0, 0);
4693 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
4694 SDVTList VTs = getVTList(VT);
4695 SDValue Ops[] = { Op1 };
4696 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4700 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4701 SDValue Op1, SDValue Op2) {
4702 SDVTList VTs = getVTList(VT);
4703 SDValue Ops[] = { Op1, Op2 };
4704 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4708 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4709 SDValue Op1, SDValue Op2, SDValue Op3) {
4710 SDVTList VTs = getVTList(VT);
4711 SDValue Ops[] = { Op1, Op2, Op3 };
4712 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4716 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4717 const SDValue *Ops, unsigned NumOps) {
4718 SDVTList VTs = getVTList(VT);
4719 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4723 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
4724 SDVTList VTs = getVTList(VT1, VT2);
4725 return getMachineNode(Opcode, dl, VTs, 0, 0);
4729 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4730 EVT VT1, EVT VT2, SDValue Op1) {
4731 SDVTList VTs = getVTList(VT1, VT2);
4732 SDValue Ops[] = { Op1 };
4733 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4737 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4738 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
4739 SDVTList VTs = getVTList(VT1, VT2);
4740 SDValue Ops[] = { Op1, Op2 };
4741 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4745 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4746 EVT VT1, EVT VT2, SDValue Op1,
4747 SDValue Op2, SDValue Op3) {
4748 SDVTList VTs = getVTList(VT1, VT2);
4749 SDValue Ops[] = { Op1, Op2, Op3 };
4750 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4754 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4756 const SDValue *Ops, unsigned NumOps) {
4757 SDVTList VTs = getVTList(VT1, VT2);
4758 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4762 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4763 EVT VT1, EVT VT2, EVT VT3,
4764 SDValue Op1, SDValue Op2) {
4765 SDVTList VTs = getVTList(VT1, VT2, VT3);
4766 SDValue Ops[] = { Op1, Op2 };
4767 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4771 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4772 EVT VT1, EVT VT2, EVT VT3,
4773 SDValue Op1, SDValue Op2, SDValue Op3) {
4774 SDVTList VTs = getVTList(VT1, VT2, VT3);
4775 SDValue Ops[] = { Op1, Op2, Op3 };
4776 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4780 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4781 EVT VT1, EVT VT2, EVT VT3,
4782 const SDValue *Ops, unsigned NumOps) {
4783 SDVTList VTs = getVTList(VT1, VT2, VT3);
4784 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4788 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4789 EVT VT2, EVT VT3, EVT VT4,
4790 const SDValue *Ops, unsigned NumOps) {
4791 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4792 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4796 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4797 const std::vector<EVT> &ResultTys,
4798 const SDValue *Ops, unsigned NumOps) {
4799 SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
4800 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4804 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
4805 const SDValue *Ops, unsigned NumOps) {
4806 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Flag;
4811 FoldingSetNodeID ID;
4812 AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
4814 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4815 return cast<MachineSDNode>(E);
4818 // Allocate a new MachineSDNode.
4819 N = NodeAllocator.Allocate<MachineSDNode>();
4820 new (N) MachineSDNode(~Opcode, DL, VTs);
4822 // Initialize the operands list.
4823 if (NumOps > array_lengthof(N->LocalOperands))
4824 // We're creating a final node that will live unmorphed for the
4825 // remainder of the current SelectionDAG iteration, so we can allocate
4826 // the operands directly out of a pool with no recycling metadata.
4827 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4830 N->InitOperands(N->LocalOperands, Ops, NumOps);
4831 N->OperandsNeedDelete = false;
4834 CSEMap.InsertNode(N, IP);
4836 AllNodes.push_back(N);
4843 /// getTargetExtractSubreg - A convenience function for creating
4844 /// TargetOpcode::EXTRACT_SUBREG nodes.
4846 SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
4848 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4849 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
4850 VT, Operand, SRIdxVal);
4851 return SDValue(Subreg, 0);
4854 /// getTargetInsertSubreg - A convenience function for creating
4855 /// TargetOpcode::INSERT_SUBREG nodes.
4857 SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
4858 SDValue Operand, SDValue Subreg) {
4859 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4860 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
4861 VT, Operand, Subreg, SRIdxVal);
4862 return SDValue(Result, 0);
4865 /// getNodeIfExists - Get the specified node if it's already available, or
4866 /// else return NULL.
4867 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4868 const SDValue *Ops, unsigned NumOps) {
4869 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4870 FoldingSetNodeID ID;
4871 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4873 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4881 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
4882 /// pointed to by a use iterator is deleted, increment the use iterator
4883 /// so that it doesn't dangle.
4885 /// This class also manages a "downlink" DAGUpdateListener, to forward
4886 /// messages to ReplaceAllUsesWith's callers.
4888 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
4889 SelectionDAG::DAGUpdateListener *DownLink;
4890 SDNode::use_iterator &UI;
4891 SDNode::use_iterator &UE;
4893 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4894 // Increment the iterator as needed.
4895 while (UI != UE && N == *UI)
4898 // Then forward the message.
4899 if (DownLink) DownLink->NodeDeleted(N, E);
4902 virtual void NodeUpdated(SDNode *N) {
4903 // Just forward the message.
4904 if (DownLink) DownLink->NodeUpdated(N);
4908 RAUWUpdateListener(SelectionDAG::DAGUpdateListener *dl,
4909 SDNode::use_iterator &ui,
4910 SDNode::use_iterator &ue)
4911 : DownLink(dl), UI(ui), UE(ue) {}
4916 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4917 /// This can cause recursive merging of nodes in the DAG.
4919 /// This version assumes From has a single result value.
4921 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4922 DAGUpdateListener *UpdateListener) {
4923 SDNode *From = FromN.getNode();
4924 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4925 "Cannot replace with this method!");
4926 assert(From != To.getNode() && "Cannot replace uses of with self");
4928 // Iterate over all the existing uses of From. New uses will be added
4929 // to the beginning of the use list, which we avoid visiting.
4930 // This specifically avoids visiting uses of From that arise while the
4931 // replacement is happening, because any such uses would be the result
4932 // of CSE: If an existing node looks like From after one of its operands
4933 // is replaced by To, we don't want to replace of all its users with To
4934 // too. See PR3018 for more info.
4935 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4936 RAUWUpdateListener Listener(UpdateListener, UI, UE);
4940 // This node is about to morph, remove its old self from the CSE maps.
4941 RemoveNodeFromCSEMaps(User);
4943 // A user can appear in a use list multiple times, and when this
4944 // happens the uses are usually next to each other in the list.
4945 // To help reduce the number of CSE recomputations, process all
4946 // the uses of this user that we can find this way.
4948 SDUse &Use = UI.getUse();
4951 } while (UI != UE && *UI == User);
4953 // Now that we have modified User, add it back to the CSE maps. If it
4954 // already exists there, recursively merge the results together.
4955 AddModifiedNodeToCSEMaps(User, &Listener);
4959 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4960 /// This can cause recursive merging of nodes in the DAG.
4962 /// This version assumes that for each value of From, there is a
4963 /// corresponding value in To in the same position with the same type.
4965 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4966 DAGUpdateListener *UpdateListener) {
4968 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
4969 assert((!From->hasAnyUseOfValue(i) ||
4970 From->getValueType(i) == To->getValueType(i)) &&
4971 "Cannot use this version of ReplaceAllUsesWith!");
4974 // Handle the trivial case.
4978 // Iterate over just the existing users of From. See the comments in
4979 // the ReplaceAllUsesWith above.
4980 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4981 RAUWUpdateListener Listener(UpdateListener, UI, UE);
4985 // This node is about to morph, remove its old self from the CSE maps.
4986 RemoveNodeFromCSEMaps(User);
4988 // A user can appear in a use list multiple times, and when this
4989 // happens the uses are usually next to each other in the list.
4990 // To help reduce the number of CSE recomputations, process all
4991 // the uses of this user that we can find this way.
4993 SDUse &Use = UI.getUse();
4996 } while (UI != UE && *UI == User);
4998 // Now that we have modified User, add it back to the CSE maps. If it
4999 // already exists there, recursively merge the results together.
5000 AddModifiedNodeToCSEMaps(User, &Listener);
5004 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5005 /// This can cause recursive merging of nodes in the DAG.
5007 /// This version can replace From with any result values. To must match the
5008 /// number and types of values returned by From.
5009 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
5011 DAGUpdateListener *UpdateListener) {
5012 if (From->getNumValues() == 1) // Handle the simple case efficiently.
5013 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
5015 // Iterate over just the existing users of From. See the comments in
5016 // the ReplaceAllUsesWith above.
5017 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5018 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5022 // This node is about to morph, remove its old self from the CSE maps.
5023 RemoveNodeFromCSEMaps(User);
5025 // A user can appear in a use list multiple times, and when this
5026 // happens the uses are usually next to each other in the list.
5027 // To help reduce the number of CSE recomputations, process all
5028 // the uses of this user that we can find this way.
5030 SDUse &Use = UI.getUse();
5031 const SDValue &ToOp = To[Use.getResNo()];
5034 } while (UI != UE && *UI == User);
5036 // Now that we have modified User, add it back to the CSE maps. If it
5037 // already exists there, recursively merge the results together.
5038 AddModifiedNodeToCSEMaps(User, &Listener);
5042 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5043 /// uses of other values produced by From.getNode() alone. The Deleted
5044 /// vector is handled the same way as for ReplaceAllUsesWith.
5045 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
5046 DAGUpdateListener *UpdateListener){
5047 // Handle the really simple, really trivial case efficiently.
5048 if (From == To) return;
5050 // Handle the simple, trivial, case efficiently.
5051 if (From.getNode()->getNumValues() == 1) {
5052 ReplaceAllUsesWith(From, To, UpdateListener);
5056 // Iterate over just the existing users of From. See the comments in
5057 // the ReplaceAllUsesWith above.
5058 SDNode::use_iterator UI = From.getNode()->use_begin(),
5059 UE = From.getNode()->use_end();
5060 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5063 bool UserRemovedFromCSEMaps = false;
5065 // A user can appear in a use list multiple times, and when this
5066 // happens the uses are usually next to each other in the list.
5067 // To help reduce the number of CSE recomputations, process all
5068 // the uses of this user that we can find this way.
5070 SDUse &Use = UI.getUse();
5072 // Skip uses of different values from the same node.
5073 if (Use.getResNo() != From.getResNo()) {
5078 // If this node hasn't been modified yet, it's still in the CSE maps,
5079 // so remove its old self from the CSE maps.
5080 if (!UserRemovedFromCSEMaps) {
5081 RemoveNodeFromCSEMaps(User);
5082 UserRemovedFromCSEMaps = true;
5087 } while (UI != UE && *UI == User);
5089 // We are iterating over all uses of the From node, so if a use
5090 // doesn't use the specific value, no changes are made.
5091 if (!UserRemovedFromCSEMaps)
5094 // Now that we have modified User, add it back to the CSE maps. If it
5095 // already exists there, recursively merge the results together.
5096 AddModifiedNodeToCSEMaps(User, &Listener);
5101 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5102 /// to record information about a use.
5109 /// operator< - Sort Memos by User.
5110 bool operator<(const UseMemo &L, const UseMemo &R) {
5111 return (intptr_t)L.User < (intptr_t)R.User;
5115 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5116 /// uses of other values produced by From.getNode() alone. The same value
5117 /// may appear in both the From and To list. The Deleted vector is
5118 /// handled the same way as for ReplaceAllUsesWith.
5119 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5122 DAGUpdateListener *UpdateListener){
5123 // Handle the simple, trivial case efficiently.
5125 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5127 // Read up all the uses and make records of them. This helps
5128 // processing new uses that are introduced during the
5129 // replacement process.
5130 SmallVector<UseMemo, 4> Uses;
5131 for (unsigned i = 0; i != Num; ++i) {
5132 unsigned FromResNo = From[i].getResNo();
5133 SDNode *FromNode = From[i].getNode();
5134 for (SDNode::use_iterator UI = FromNode->use_begin(),
5135 E = FromNode->use_end(); UI != E; ++UI) {
5136 SDUse &Use = UI.getUse();
5137 if (Use.getResNo() == FromResNo) {
5138 UseMemo Memo = { *UI, i, &Use };
5139 Uses.push_back(Memo);
5144 // Sort the uses, so that all the uses from a given User are together.
5145 std::sort(Uses.begin(), Uses.end());
5147 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5148 UseIndex != UseIndexEnd; ) {
5149 // We know that this user uses some value of From. If it is the right
5150 // value, update it.
5151 SDNode *User = Uses[UseIndex].User;
5153 // This node is about to morph, remove its old self from the CSE maps.
5154 RemoveNodeFromCSEMaps(User);
5156 // The Uses array is sorted, so all the uses for a given User
5157 // are next to each other in the list.
5158 // To help reduce the number of CSE recomputations, process all
5159 // the uses of this user that we can find this way.
5161 unsigned i = Uses[UseIndex].Index;
5162 SDUse &Use = *Uses[UseIndex].Use;
5166 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5168 // Now that we have modified User, add it back to the CSE maps. If it
5169 // already exists there, recursively merge the results together.
5170 AddModifiedNodeToCSEMaps(User, UpdateListener);
5174 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5175 /// based on their topological order. It returns the maximum id and a vector
5176 /// of the SDNodes* in assigned order by reference.
5177 unsigned SelectionDAG::AssignTopologicalOrder() {
5179 unsigned DAGSize = 0;
5181 // SortedPos tracks the progress of the algorithm. Nodes before it are
5182 // sorted, nodes after it are unsorted. When the algorithm completes
5183 // it is at the end of the list.
5184 allnodes_iterator SortedPos = allnodes_begin();
5186 // Visit all the nodes. Move nodes with no operands to the front of
5187 // the list immediately. Annotate nodes that do have operands with their
5188 // operand count. Before we do this, the Node Id fields of the nodes
5189 // may contain arbitrary values. After, the Node Id fields for nodes
5190 // before SortedPos will contain the topological sort index, and the
5191 // Node Id fields for nodes At SortedPos and after will contain the
5192 // count of outstanding operands.
5193 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5196 unsigned Degree = N->getNumOperands();
5198 // A node with no uses, add it to the result array immediately.
5199 N->setNodeId(DAGSize++);
5200 allnodes_iterator Q = N;
5202 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5203 assert(SortedPos != AllNodes.end() && "Overran node list");
5206 // Temporarily use the Node Id as scratch space for the degree count.
5207 N->setNodeId(Degree);
5211 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5212 // such that by the time the end is reached all nodes will be sorted.
5213 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5216 // N is in sorted position, so all its uses have one less operand
5217 // that needs to be sorted.
5218 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5221 unsigned Degree = P->getNodeId();
5222 assert(Degree != 0 && "Invalid node degree");
5225 // All of P's operands are sorted, so P may sorted now.
5226 P->setNodeId(DAGSize++);
5228 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5229 assert(SortedPos != AllNodes.end() && "Overran node list");
5232 // Update P's outstanding operand count.
5233 P->setNodeId(Degree);
5236 if (I == SortedPos) {
5239 dbgs() << "Overran sorted position:\n";
5242 llvm_unreachable(0);
5246 assert(SortedPos == AllNodes.end() &&
5247 "Topological sort incomplete!");
5248 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5249 "First node in topological sort is not the entry token!");
5250 assert(AllNodes.front().getNodeId() == 0 &&
5251 "First node in topological sort has non-zero id!");
5252 assert(AllNodes.front().getNumOperands() == 0 &&
5253 "First node in topological sort has operands!");
5254 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5255 "Last node in topologic sort has unexpected id!");
5256 assert(AllNodes.back().use_empty() &&
5257 "Last node in topologic sort has users!");
5258 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5262 /// AssignOrdering - Assign an order to the SDNode.
5263 void SelectionDAG::AssignOrdering(const SDNode *SD, unsigned Order) {
5264 assert(SD && "Trying to assign an order to a null node!");
5265 Ordering->add(SD, Order);
5268 /// GetOrdering - Get the order for the SDNode.
5269 unsigned SelectionDAG::GetOrdering(const SDNode *SD) const {
5270 assert(SD && "Trying to get the order of a null node!");
5271 return Ordering->getOrder(SD);
5274 /// AssignDbgInfo - Assign debug info to the SDNode.
5275 void SelectionDAG::AssignDbgInfo(SDNode* SD, SDDbgValue* db) {
5276 assert(SD && "Trying to assign dbg info to a null node!");
5277 DbgInfo->add(SD, db);
5278 SD->setHasDebugValue(true);
5281 /// RememberDbgInfo - Remember debug info which is not assigned to an SDNode.
5282 void SelectionDAG::RememberDbgInfo(SDDbgValue* db) {
5286 /// GetDbgInfo - Get the debug info, if any, for the SDNode.
5287 SDDbgValue* SelectionDAG::GetDbgInfo(const SDNode *SD) {
5288 assert(SD && "Trying to get the order of a null node!");
5289 if (SD->getHasDebugValue())
5290 return DbgInfo->getSDDbgValue(SD);
5294 //===----------------------------------------------------------------------===//
5296 //===----------------------------------------------------------------------===//
5298 HandleSDNode::~HandleSDNode() {
5302 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA,
5303 EVT VT, int64_t o, unsigned char TF)
5304 : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)),
5305 Offset(o), TargetFlags(TF) {
5306 TheGlobal = const_cast<GlobalValue*>(GA);
5309 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
5310 MachineMemOperand *mmo)
5311 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5312 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5313 MMO->isNonTemporal());
5314 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5315 assert(isNonTemporal() == MMO->isNonTemporal() &&
5316 "Non-temporal encoding error!");
5317 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5320 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5321 const SDValue *Ops, unsigned NumOps, EVT memvt,
5322 MachineMemOperand *mmo)
5323 : SDNode(Opc, dl, VTs, Ops, NumOps),
5324 MemoryVT(memvt), MMO(mmo) {
5325 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5326 MMO->isNonTemporal());
5327 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5328 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5331 /// Profile - Gather unique data for the node.
5333 void SDNode::Profile(FoldingSetNodeID &ID) const {
5334 AddNodeIDNode(ID, this);
5339 std::vector<EVT> VTs;
5342 VTs.reserve(MVT::LAST_VALUETYPE);
5343 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5344 VTs.push_back(MVT((MVT::SimpleValueType)i));
5349 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5350 static ManagedStatic<EVTArray> SimpleVTArray;
5351 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5353 /// getValueTypeList - Return a pointer to the specified value type.
5355 const EVT *SDNode::getValueTypeList(EVT VT) {
5356 if (VT.isExtended()) {
5357 sys::SmartScopedLock<true> Lock(*VTMutex);
5358 return &(*EVTs->insert(VT).first);
5360 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5364 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5365 /// indicated value. This method ignores uses of other values defined by this
5367 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5368 assert(Value < getNumValues() && "Bad value!");
5370 // TODO: Only iterate over uses of a given value of the node
5371 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5372 if (UI.getUse().getResNo() == Value) {
5379 // Found exactly the right number of uses?
5384 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5385 /// value. This method ignores uses of other values defined by this operation.
5386 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5387 assert(Value < getNumValues() && "Bad value!");
5389 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5390 if (UI.getUse().getResNo() == Value)
5397 /// isOnlyUserOf - Return true if this node is the only use of N.
5399 bool SDNode::isOnlyUserOf(SDNode *N) const {
5401 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5412 /// isOperand - Return true if this node is an operand of N.
5414 bool SDValue::isOperandOf(SDNode *N) const {
5415 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5416 if (*this == N->getOperand(i))
5421 bool SDNode::isOperandOf(SDNode *N) const {
5422 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5423 if (this == N->OperandList[i].getNode())
5428 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5429 /// be a chain) reaches the specified operand without crossing any
5430 /// side-effecting instructions. In practice, this looks through token
5431 /// factors and non-volatile loads. In order to remain efficient, this only
5432 /// looks a couple of nodes in, it does not do an exhaustive search.
5433 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5434 unsigned Depth) const {
5435 if (*this == Dest) return true;
5437 // Don't search too deeply, we just want to be able to see through
5438 // TokenFactor's etc.
5439 if (Depth == 0) return false;
5441 // If this is a token factor, all inputs to the TF happen in parallel. If any
5442 // of the operands of the TF reach dest, then we can do the xform.
5443 if (getOpcode() == ISD::TokenFactor) {
5444 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5445 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5450 // Loads don't have side effects, look through them.
5451 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5452 if (!Ld->isVolatile())
5453 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5458 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5459 /// is either an operand of N or it can be reached by traversing up the operands.
5460 /// NOTE: this is an expensive method. Use it carefully.
5461 bool SDNode::isPredecessorOf(SDNode *N) const {
5462 SmallPtrSet<SDNode *, 32> Visited;
5463 SmallVector<SDNode *, 16> Worklist;
5464 Worklist.push_back(N);
5467 N = Worklist.pop_back_val();
5468 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5469 SDNode *Op = N->getOperand(i).getNode();
5472 if (Visited.insert(Op))
5473 Worklist.push_back(Op);
5475 } while (!Worklist.empty());
5480 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5481 assert(Num < NumOperands && "Invalid child # of SDNode!");
5482 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5485 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5486 switch (getOpcode()) {
5488 if (getOpcode() < ISD::BUILTIN_OP_END)
5489 return "<<Unknown DAG Node>>";
5490 if (isMachineOpcode()) {
5492 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5493 if (getMachineOpcode() < TII->getNumOpcodes())
5494 return TII->get(getMachineOpcode()).getName();
5495 return "<<Unknown Machine Node #" + utostr(getOpcode()) + ">>";
5498 const TargetLowering &TLI = G->getTargetLoweringInfo();
5499 const char *Name = TLI.getTargetNodeName(getOpcode());
5500 if (Name) return Name;
5501 return "<<Unknown Target Node #" + utostr(getOpcode()) + ">>";
5503 return "<<Unknown Node #" + utostr(getOpcode()) + ">>";
5506 case ISD::DELETED_NODE:
5507 return "<<Deleted Node!>>";
5509 case ISD::PREFETCH: return "Prefetch";
5510 case ISD::MEMBARRIER: return "MemBarrier";
5511 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5512 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5513 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5514 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5515 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5516 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5517 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5518 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5519 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5520 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5521 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5522 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5523 case ISD::PCMARKER: return "PCMarker";
5524 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5525 case ISD::SRCVALUE: return "SrcValue";
5526 case ISD::EntryToken: return "EntryToken";
5527 case ISD::TokenFactor: return "TokenFactor";
5528 case ISD::AssertSext: return "AssertSext";
5529 case ISD::AssertZext: return "AssertZext";
5531 case ISD::BasicBlock: return "BasicBlock";
5532 case ISD::VALUETYPE: return "ValueType";
5533 case ISD::Register: return "Register";
5535 case ISD::Constant: return "Constant";
5536 case ISD::ConstantFP: return "ConstantFP";
5537 case ISD::GlobalAddress: return "GlobalAddress";
5538 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5539 case ISD::FrameIndex: return "FrameIndex";
5540 case ISD::JumpTable: return "JumpTable";
5541 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5542 case ISD::RETURNADDR: return "RETURNADDR";
5543 case ISD::FRAMEADDR: return "FRAMEADDR";
5544 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5545 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5546 case ISD::LSDAADDR: return "LSDAADDR";
5547 case ISD::EHSELECTION: return "EHSELECTION";
5548 case ISD::EH_RETURN: return "EH_RETURN";
5549 case ISD::ConstantPool: return "ConstantPool";
5550 case ISD::ExternalSymbol: return "ExternalSymbol";
5551 case ISD::BlockAddress: return "BlockAddress";
5552 case ISD::INTRINSIC_WO_CHAIN:
5553 case ISD::INTRINSIC_VOID:
5554 case ISD::INTRINSIC_W_CHAIN: {
5555 unsigned OpNo = getOpcode() == ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
5556 unsigned IID = cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue();
5557 if (IID < Intrinsic::num_intrinsics)
5558 return Intrinsic::getName((Intrinsic::ID)IID);
5559 else if (const TargetIntrinsicInfo *TII = G->getTarget().getIntrinsicInfo())
5560 return TII->getName(IID);
5561 llvm_unreachable("Invalid intrinsic ID");
5564 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5565 case ISD::TargetConstant: return "TargetConstant";
5566 case ISD::TargetConstantFP:return "TargetConstantFP";
5567 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5568 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5569 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5570 case ISD::TargetJumpTable: return "TargetJumpTable";
5571 case ISD::TargetConstantPool: return "TargetConstantPool";
5572 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5573 case ISD::TargetBlockAddress: return "TargetBlockAddress";
5575 case ISD::CopyToReg: return "CopyToReg";
5576 case ISD::CopyFromReg: return "CopyFromReg";
5577 case ISD::UNDEF: return "undef";
5578 case ISD::MERGE_VALUES: return "merge_values";
5579 case ISD::INLINEASM: return "inlineasm";
5580 case ISD::EH_LABEL: return "eh_label";
5581 case ISD::HANDLENODE: return "handlenode";
5584 case ISD::FABS: return "fabs";
5585 case ISD::FNEG: return "fneg";
5586 case ISD::FSQRT: return "fsqrt";
5587 case ISD::FSIN: return "fsin";
5588 case ISD::FCOS: return "fcos";
5589 case ISD::FPOWI: return "fpowi";
5590 case ISD::FPOW: return "fpow";
5591 case ISD::FTRUNC: return "ftrunc";
5592 case ISD::FFLOOR: return "ffloor";
5593 case ISD::FCEIL: return "fceil";
5594 case ISD::FRINT: return "frint";
5595 case ISD::FNEARBYINT: return "fnearbyint";
5598 case ISD::ADD: return "add";
5599 case ISD::SUB: return "sub";
5600 case ISD::MUL: return "mul";
5601 case ISD::MULHU: return "mulhu";
5602 case ISD::MULHS: return "mulhs";
5603 case ISD::SDIV: return "sdiv";
5604 case ISD::UDIV: return "udiv";
5605 case ISD::SREM: return "srem";
5606 case ISD::UREM: return "urem";
5607 case ISD::SMUL_LOHI: return "smul_lohi";
5608 case ISD::UMUL_LOHI: return "umul_lohi";
5609 case ISD::SDIVREM: return "sdivrem";
5610 case ISD::UDIVREM: return "udivrem";
5611 case ISD::AND: return "and";
5612 case ISD::OR: return "or";
5613 case ISD::XOR: return "xor";
5614 case ISD::SHL: return "shl";
5615 case ISD::SRA: return "sra";
5616 case ISD::SRL: return "srl";
5617 case ISD::ROTL: return "rotl";
5618 case ISD::ROTR: return "rotr";
5619 case ISD::FADD: return "fadd";
5620 case ISD::FSUB: return "fsub";
5621 case ISD::FMUL: return "fmul";
5622 case ISD::FDIV: return "fdiv";
5623 case ISD::FREM: return "frem";
5624 case ISD::FCOPYSIGN: return "fcopysign";
5625 case ISD::FGETSIGN: return "fgetsign";
5627 case ISD::SETCC: return "setcc";
5628 case ISD::VSETCC: return "vsetcc";
5629 case ISD::SELECT: return "select";
5630 case ISD::SELECT_CC: return "select_cc";
5631 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5632 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5633 case ISD::CONCAT_VECTORS: return "concat_vectors";
5634 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5635 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5636 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5637 case ISD::CARRY_FALSE: return "carry_false";
5638 case ISD::ADDC: return "addc";
5639 case ISD::ADDE: return "adde";
5640 case ISD::SADDO: return "saddo";
5641 case ISD::UADDO: return "uaddo";
5642 case ISD::SSUBO: return "ssubo";
5643 case ISD::USUBO: return "usubo";
5644 case ISD::SMULO: return "smulo";
5645 case ISD::UMULO: return "umulo";
5646 case ISD::SUBC: return "subc";
5647 case ISD::SUBE: return "sube";
5648 case ISD::SHL_PARTS: return "shl_parts";
5649 case ISD::SRA_PARTS: return "sra_parts";
5650 case ISD::SRL_PARTS: return "srl_parts";
5652 // Conversion operators.
5653 case ISD::SIGN_EXTEND: return "sign_extend";
5654 case ISD::ZERO_EXTEND: return "zero_extend";
5655 case ISD::ANY_EXTEND: return "any_extend";
5656 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5657 case ISD::TRUNCATE: return "truncate";
5658 case ISD::FP_ROUND: return "fp_round";
5659 case ISD::FLT_ROUNDS_: return "flt_rounds";
5660 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5661 case ISD::FP_EXTEND: return "fp_extend";
5663 case ISD::SINT_TO_FP: return "sint_to_fp";
5664 case ISD::UINT_TO_FP: return "uint_to_fp";
5665 case ISD::FP_TO_SINT: return "fp_to_sint";
5666 case ISD::FP_TO_UINT: return "fp_to_uint";
5667 case ISD::BIT_CONVERT: return "bit_convert";
5668 case ISD::FP16_TO_FP32: return "fp16_to_fp32";
5669 case ISD::FP32_TO_FP16: return "fp32_to_fp16";
5671 case ISD::CONVERT_RNDSAT: {
5672 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5673 default: llvm_unreachable("Unknown cvt code!");
5674 case ISD::CVT_FF: return "cvt_ff";
5675 case ISD::CVT_FS: return "cvt_fs";
5676 case ISD::CVT_FU: return "cvt_fu";
5677 case ISD::CVT_SF: return "cvt_sf";
5678 case ISD::CVT_UF: return "cvt_uf";
5679 case ISD::CVT_SS: return "cvt_ss";
5680 case ISD::CVT_SU: return "cvt_su";
5681 case ISD::CVT_US: return "cvt_us";
5682 case ISD::CVT_UU: return "cvt_uu";
5686 // Control flow instructions
5687 case ISD::BR: return "br";
5688 case ISD::BRIND: return "brind";
5689 case ISD::BR_JT: return "br_jt";
5690 case ISD::BRCOND: return "brcond";
5691 case ISD::BR_CC: return "br_cc";
5692 case ISD::CALLSEQ_START: return "callseq_start";
5693 case ISD::CALLSEQ_END: return "callseq_end";
5696 case ISD::LOAD: return "load";
5697 case ISD::STORE: return "store";
5698 case ISD::VAARG: return "vaarg";
5699 case ISD::VACOPY: return "vacopy";
5700 case ISD::VAEND: return "vaend";
5701 case ISD::VASTART: return "vastart";
5702 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5703 case ISD::EXTRACT_ELEMENT: return "extract_element";
5704 case ISD::BUILD_PAIR: return "build_pair";
5705 case ISD::STACKSAVE: return "stacksave";
5706 case ISD::STACKRESTORE: return "stackrestore";
5707 case ISD::TRAP: return "trap";
5710 case ISD::BSWAP: return "bswap";
5711 case ISD::CTPOP: return "ctpop";
5712 case ISD::CTTZ: return "cttz";
5713 case ISD::CTLZ: return "ctlz";
5716 case ISD::TRAMPOLINE: return "trampoline";
5719 switch (cast<CondCodeSDNode>(this)->get()) {
5720 default: llvm_unreachable("Unknown setcc condition!");
5721 case ISD::SETOEQ: return "setoeq";
5722 case ISD::SETOGT: return "setogt";
5723 case ISD::SETOGE: return "setoge";
5724 case ISD::SETOLT: return "setolt";
5725 case ISD::SETOLE: return "setole";
5726 case ISD::SETONE: return "setone";
5728 case ISD::SETO: return "seto";
5729 case ISD::SETUO: return "setuo";
5730 case ISD::SETUEQ: return "setue";
5731 case ISD::SETUGT: return "setugt";
5732 case ISD::SETUGE: return "setuge";
5733 case ISD::SETULT: return "setult";
5734 case ISD::SETULE: return "setule";
5735 case ISD::SETUNE: return "setune";
5737 case ISD::SETEQ: return "seteq";
5738 case ISD::SETGT: return "setgt";
5739 case ISD::SETGE: return "setge";
5740 case ISD::SETLT: return "setlt";
5741 case ISD::SETLE: return "setle";
5742 case ISD::SETNE: return "setne";
5747 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5756 return "<post-inc>";
5758 return "<post-dec>";
5762 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5763 std::string S = "< ";
5777 if (getByValAlign())
5778 S += "byval-align:" + utostr(getByValAlign()) + " ";
5780 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5782 S += "byval-size:" + utostr(getByValSize()) + " ";
5786 void SDNode::dump() const { dump(0); }
5787 void SDNode::dump(const SelectionDAG *G) const {
5791 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
5792 OS << (void*)this << ": ";
5794 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5796 if (getValueType(i) == MVT::Other)
5799 OS << getValueType(i).getEVTString();
5801 OS << " = " << getOperationName(G);
5804 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
5805 if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
5806 if (!MN->memoperands_empty()) {
5809 for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
5810 e = MN->memoperands_end(); i != e; ++i) {
5817 } else if (const ShuffleVectorSDNode *SVN =
5818 dyn_cast<ShuffleVectorSDNode>(this)) {
5820 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
5821 int Idx = SVN->getMaskElt(i);
5829 } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5830 OS << '<' << CSDN->getAPIntValue() << '>';
5831 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5832 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5833 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5834 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5835 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5838 CSDN->getValueAPF().bitcastToAPInt().dump();
5841 } else if (const GlobalAddressSDNode *GADN =
5842 dyn_cast<GlobalAddressSDNode>(this)) {
5843 int64_t offset = GADN->getOffset();
5845 WriteAsOperand(OS, GADN->getGlobal());
5848 OS << " + " << offset;
5850 OS << " " << offset;
5851 if (unsigned int TF = GADN->getTargetFlags())
5852 OS << " [TF=" << TF << ']';
5853 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5854 OS << "<" << FIDN->getIndex() << ">";
5855 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5856 OS << "<" << JTDN->getIndex() << ">";
5857 if (unsigned int TF = JTDN->getTargetFlags())
5858 OS << " [TF=" << TF << ']';
5859 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5860 int offset = CP->getOffset();
5861 if (CP->isMachineConstantPoolEntry())
5862 OS << "<" << *CP->getMachineCPVal() << ">";
5864 OS << "<" << *CP->getConstVal() << ">";
5866 OS << " + " << offset;
5868 OS << " " << offset;
5869 if (unsigned int TF = CP->getTargetFlags())
5870 OS << " [TF=" << TF << ']';
5871 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5873 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5875 OS << LBB->getName() << " ";
5876 OS << (const void*)BBDN->getBasicBlock() << ">";
5877 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5878 if (G && R->getReg() &&
5879 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5880 OS << " %" << G->getTarget().getRegisterInfo()->getName(R->getReg());
5882 OS << " %reg" << R->getReg();
5884 } else if (const ExternalSymbolSDNode *ES =
5885 dyn_cast<ExternalSymbolSDNode>(this)) {
5886 OS << "'" << ES->getSymbol() << "'";
5887 if (unsigned int TF = ES->getTargetFlags())
5888 OS << " [TF=" << TF << ']';
5889 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5891 OS << "<" << M->getValue() << ">";
5894 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5895 OS << ":" << N->getVT().getEVTString();
5897 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5898 OS << "<" << *LD->getMemOperand();
5901 switch (LD->getExtensionType()) {
5902 default: doExt = false; break;
5903 case ISD::EXTLOAD: OS << ", anyext"; break;
5904 case ISD::SEXTLOAD: OS << ", sext"; break;
5905 case ISD::ZEXTLOAD: OS << ", zext"; break;
5908 OS << " from " << LD->getMemoryVT().getEVTString();
5910 const char *AM = getIndexedModeName(LD->getAddressingMode());
5915 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5916 OS << "<" << *ST->getMemOperand();
5918 if (ST->isTruncatingStore())
5919 OS << ", trunc to " << ST->getMemoryVT().getEVTString();
5921 const char *AM = getIndexedModeName(ST->getAddressingMode());
5926 } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
5927 OS << "<" << *M->getMemOperand() << ">";
5928 } else if (const BlockAddressSDNode *BA =
5929 dyn_cast<BlockAddressSDNode>(this)) {
5931 WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
5933 WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
5935 if (unsigned int TF = BA->getTargetFlags())
5936 OS << " [TF=" << TF << ']';
5940 if (unsigned Order = G->GetOrdering(this))
5941 OS << " [ORD=" << Order << ']';
5943 if (getNodeId() != -1)
5944 OS << " [ID=" << getNodeId() << ']';
5947 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5949 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5950 if (i) OS << ", "; else OS << " ";
5951 OS << (void*)getOperand(i).getNode();
5952 if (unsigned RN = getOperand(i).getResNo())
5955 print_details(OS, G);
5958 static void printrWithDepthHelper(raw_ostream &OS, const SDNode *N,
5959 const SelectionDAG *G, unsigned depth,
5972 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5974 printrWithDepthHelper(OS, N->getOperand(i).getNode(), G, depth-1, indent+2);
5978 void SDNode::printrWithDepth(raw_ostream &OS, const SelectionDAG *G,
5979 unsigned depth) const {
5980 printrWithDepthHelper(OS, this, G, depth, 0);
5983 void SDNode::printrFull(raw_ostream &OS, const SelectionDAG *G) const {
5984 // Don't print impossibly deep things.
5985 printrWithDepth(OS, G, 100);
5988 void SDNode::dumprWithDepth(const SelectionDAG *G, unsigned depth) const {
5989 printrWithDepth(dbgs(), G, depth);
5992 void SDNode::dumprFull(const SelectionDAG *G) const {
5993 // Don't print impossibly deep things.
5994 dumprWithDepth(G, 100);
5997 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5998 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5999 if (N->getOperand(i).getNode()->hasOneUse())
6000 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
6002 dbgs() << "\n" << std::string(indent+2, ' ')
6003 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
6007 dbgs().indent(indent);
6011 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6012 assert(N->getNumValues() == 1 &&
6013 "Can't unroll a vector with multiple results!");
6015 EVT VT = N->getValueType(0);
6016 unsigned NE = VT.getVectorNumElements();
6017 EVT EltVT = VT.getVectorElementType();
6018 DebugLoc dl = N->getDebugLoc();
6020 SmallVector<SDValue, 8> Scalars;
6021 SmallVector<SDValue, 4> Operands(N->getNumOperands());
6023 // If ResNE is 0, fully unroll the vector op.
6026 else if (NE > ResNE)
6030 for (i= 0; i != NE; ++i) {
6031 for (unsigned j = 0; j != N->getNumOperands(); ++j) {
6032 SDValue Operand = N->getOperand(j);
6033 EVT OperandVT = Operand.getValueType();
6034 if (OperandVT.isVector()) {
6035 // A vector operand; extract a single element.
6036 EVT OperandEltVT = OperandVT.getVectorElementType();
6037 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6040 getConstant(i, MVT::i32));
6042 // A scalar operand; just use it as is.
6043 Operands[j] = Operand;
6047 switch (N->getOpcode()) {
6049 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6050 &Operands[0], Operands.size()));
6057 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6058 getShiftAmountOperand(Operands[1])));
6060 case ISD::SIGN_EXTEND_INREG:
6061 case ISD::FP_ROUND_INREG: {
6062 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6063 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6065 getValueType(ExtVT)));
6070 for (; i < ResNE; ++i)
6071 Scalars.push_back(getUNDEF(EltVT));
6073 return getNode(ISD::BUILD_VECTOR, dl,
6074 EVT::getVectorVT(*getContext(), EltVT, ResNE),
6075 &Scalars[0], Scalars.size());
6079 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6080 /// location that is 'Dist' units away from the location that the 'Base' load
6081 /// is loading from.
6082 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6083 unsigned Bytes, int Dist) const {
6084 if (LD->getChain() != Base->getChain())
6086 EVT VT = LD->getValueType(0);
6087 if (VT.getSizeInBits() / 8 != Bytes)
6090 SDValue Loc = LD->getOperand(1);
6091 SDValue BaseLoc = Base->getOperand(1);
6092 if (Loc.getOpcode() == ISD::FrameIndex) {
6093 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6095 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6096 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6097 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6098 int FS = MFI->getObjectSize(FI);
6099 int BFS = MFI->getObjectSize(BFI);
6100 if (FS != BFS || FS != (int)Bytes) return false;
6101 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6103 if (Loc.getOpcode() == ISD::ADD && Loc.getOperand(0) == BaseLoc) {
6104 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Loc.getOperand(1));
6105 if (V && (V->getSExtValue() == Dist*Bytes))
6109 GlobalValue *GV1 = NULL;
6110 GlobalValue *GV2 = NULL;
6111 int64_t Offset1 = 0;
6112 int64_t Offset2 = 0;
6113 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6114 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6115 if (isGA1 && isGA2 && GV1 == GV2)
6116 return Offset1 == (Offset2 + Dist*Bytes);
6121 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6122 /// it cannot be inferred.
6123 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6124 // If this is a GlobalAddress + cst, return the alignment.
6126 int64_t GVOffset = 0;
6127 if (TLI.isGAPlusOffset(Ptr.getNode(), GV, GVOffset))
6128 return MinAlign(GV->getAlignment(), GVOffset);
6130 // If this is a direct reference to a stack slot, use information about the
6131 // stack slot's alignment.
6132 int FrameIdx = 1 << 31;
6133 int64_t FrameOffset = 0;
6134 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6135 FrameIdx = FI->getIndex();
6136 } else if (Ptr.getOpcode() == ISD::ADD &&
6137 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
6138 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6139 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6140 FrameOffset = Ptr.getConstantOperandVal(1);
6143 if (FrameIdx != (1 << 31)) {
6144 // FIXME: Handle FI+CST.
6145 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6146 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6148 if (MFI.isFixedObjectIndex(FrameIdx)) {
6149 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
6151 // The alignment of the frame index can be determined from its offset from
6152 // the incoming frame position. If the frame object is at offset 32 and
6153 // the stack is guaranteed to be 16-byte aligned, then we know that the
6154 // object is 16-byte aligned.
6155 unsigned StackAlign = getTarget().getFrameInfo()->getStackAlignment();
6156 unsigned Align = MinAlign(ObjectOffset, StackAlign);
6158 // Finally, the frame object itself may have a known alignment. Factor
6159 // the alignment + offset into a new alignment. For example, if we know
6160 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
6161 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
6162 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
6163 return std::max(Align, FIInfoAlign);
6171 void SelectionDAG::dump() const {
6172 dbgs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
6174 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
6176 const SDNode *N = I;
6177 if (!N->hasOneUse() && N != getRoot().getNode())
6178 DumpNodes(N, 2, this);
6181 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
6186 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
6188 print_details(OS, G);
6191 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
6192 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
6193 const SelectionDAG *G, VisitedSDNodeSet &once) {
6194 if (!once.insert(N)) // If we've been here before, return now.
6197 // Dump the current SDNode, but don't end the line yet.
6198 OS << std::string(indent, ' ');
6201 // Having printed this SDNode, walk the children:
6202 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6203 const SDNode *child = N->getOperand(i).getNode();
6208 if (child->getNumOperands() == 0) {
6209 // This child has no grandchildren; print it inline right here.
6210 child->printr(OS, G);
6212 } else { // Just the address. FIXME: also print the child's opcode.
6214 if (unsigned RN = N->getOperand(i).getResNo())
6221 // Dump children that have grandchildren on their own line(s).
6222 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6223 const SDNode *child = N->getOperand(i).getNode();
6224 DumpNodesr(OS, child, indent+2, G, once);
6228 void SDNode::dumpr() const {
6229 VisitedSDNodeSet once;
6230 DumpNodesr(dbgs(), this, 0, 0, once);
6233 void SDNode::dumpr(const SelectionDAG *G) const {
6234 VisitedSDNodeSet once;
6235 DumpNodesr(dbgs(), this, 0, G, once);
6239 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6240 unsigned GlobalAddressSDNode::getAddressSpace() const {
6241 return getGlobal()->getType()->getAddressSpace();
6245 const Type *ConstantPoolSDNode::getType() const {
6246 if (isMachineConstantPoolEntry())
6247 return Val.MachineCPVal->getType();
6248 return Val.ConstVal->getType();
6251 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6253 unsigned &SplatBitSize,
6255 unsigned MinSplatBits,
6257 EVT VT = getValueType(0);
6258 assert(VT.isVector() && "Expected a vector type");
6259 unsigned sz = VT.getSizeInBits();
6260 if (MinSplatBits > sz)
6263 SplatValue = APInt(sz, 0);
6264 SplatUndef = APInt(sz, 0);
6266 // Get the bits. Bits with undefined values (when the corresponding element
6267 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6268 // in SplatValue. If any of the values are not constant, give up and return
6270 unsigned int nOps = getNumOperands();
6271 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6272 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6274 for (unsigned j = 0; j < nOps; ++j) {
6275 unsigned i = isBigEndian ? nOps-1-j : j;
6276 SDValue OpVal = getOperand(i);
6277 unsigned BitPos = j * EltBitSize;
6279 if (OpVal.getOpcode() == ISD::UNDEF)
6280 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6281 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6282 SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
6283 zextOrTrunc(sz) << BitPos);
6284 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6285 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6290 // The build_vector is all constants or undefs. Find the smallest element
6291 // size that splats the vector.
6293 HasAnyUndefs = (SplatUndef != 0);
6296 unsigned HalfSize = sz / 2;
6297 APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
6298 APInt LowValue = APInt(SplatValue).trunc(HalfSize);
6299 APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
6300 APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
6302 // If the two halves do not match (ignoring undef bits), stop here.
6303 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6304 MinSplatBits > HalfSize)
6307 SplatValue = HighValue | LowValue;
6308 SplatUndef = HighUndef & LowUndef;
6317 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6318 // Find the first non-undef value in the shuffle mask.
6320 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6323 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6325 // Make sure all remaining elements are either undef or the same as the first
6327 for (int Idx = Mask[i]; i != e; ++i)
6328 if (Mask[i] >= 0 && Mask[i] != Idx)
6334 static void checkForCyclesHelper(const SDNode *N,
6335 SmallPtrSet<const SDNode*, 32> &Visited,
6336 SmallPtrSet<const SDNode*, 32> &Checked) {
6337 // If this node has already been checked, don't check it again.
6338 if (Checked.count(N))
6341 // If a node has already been visited on this depth-first walk, reject it as
6343 if (!Visited.insert(N)) {
6344 dbgs() << "Offending node:\n";
6346 errs() << "Detected cycle in SelectionDAG\n";
6350 for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6351 checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked);
6358 void llvm::checkForCycles(const llvm::SDNode *N) {
6360 assert(N && "Checking nonexistant SDNode");
6361 SmallPtrSet<const SDNode*, 32> visited;
6362 SmallPtrSet<const SDNode*, 32> checked;
6363 checkForCyclesHelper(N, visited, checked);
6367 void llvm::checkForCycles(const llvm::SelectionDAG *DAG) {
6368 checkForCycles(DAG->getRoot().getNode());