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();
2334 case ISD::SIGN_EXTEND:
2335 return getConstant(APInt(Val).sext(VT.getSizeInBits()), VT);
2336 case ISD::ANY_EXTEND:
2337 case ISD::ZERO_EXTEND:
2339 return getConstant(APInt(Val).zextOrTrunc(VT.getSizeInBits()), VT);
2340 case ISD::UINT_TO_FP:
2341 case ISD::SINT_TO_FP: {
2342 const uint64_t zero[] = {0, 0};
2343 // No compile time operations on ppcf128.
2344 if (VT == MVT::ppcf128) break;
2345 APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
2346 (void)apf.convertFromAPInt(Val,
2347 Opcode==ISD::SINT_TO_FP,
2348 APFloat::rmNearestTiesToEven);
2349 return getConstantFP(apf, VT);
2351 case ISD::BIT_CONVERT:
2352 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2353 return getConstantFP(Val.bitsToFloat(), VT);
2354 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2355 return getConstantFP(Val.bitsToDouble(), VT);
2358 return getConstant(Val.byteSwap(), VT);
2360 return getConstant(Val.countPopulation(), VT);
2362 return getConstant(Val.countLeadingZeros(), VT);
2364 return getConstant(Val.countTrailingZeros(), VT);
2368 // Constant fold unary operations with a floating point constant operand.
2369 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2370 APFloat V = C->getValueAPF(); // make copy
2371 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2375 return getConstantFP(V, VT);
2378 return getConstantFP(V, VT);
2380 case ISD::FP_EXTEND: {
2382 // This can return overflow, underflow, or inexact; we don't care.
2383 // FIXME need to be more flexible about rounding mode.
2384 (void)V.convert(*EVTToAPFloatSemantics(VT),
2385 APFloat::rmNearestTiesToEven, &ignored);
2386 return getConstantFP(V, VT);
2388 case ISD::FP_TO_SINT:
2389 case ISD::FP_TO_UINT: {
2392 assert(integerPartWidth >= 64);
2393 // FIXME need to be more flexible about rounding mode.
2394 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2395 Opcode==ISD::FP_TO_SINT,
2396 APFloat::rmTowardZero, &ignored);
2397 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2399 APInt api(VT.getSizeInBits(), 2, x);
2400 return getConstant(api, VT);
2402 case ISD::BIT_CONVERT:
2403 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2404 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2405 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2406 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2412 unsigned OpOpcode = Operand.getNode()->getOpcode();
2414 case ISD::TokenFactor:
2415 case ISD::MERGE_VALUES:
2416 case ISD::CONCAT_VECTORS:
2417 return Operand; // Factor, merge or concat of one node? No need.
2418 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2419 case ISD::FP_EXTEND:
2420 assert(VT.isFloatingPoint() &&
2421 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2422 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2423 assert((!VT.isVector() ||
2424 VT.getVectorNumElements() ==
2425 Operand.getValueType().getVectorNumElements()) &&
2426 "Vector element count mismatch!");
2427 if (Operand.getOpcode() == ISD::UNDEF)
2428 return getUNDEF(VT);
2430 case ISD::SIGN_EXTEND:
2431 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2432 "Invalid SIGN_EXTEND!");
2433 if (Operand.getValueType() == VT) return Operand; // noop extension
2434 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2435 "Invalid sext node, dst < src!");
2436 assert((!VT.isVector() ||
2437 VT.getVectorNumElements() ==
2438 Operand.getValueType().getVectorNumElements()) &&
2439 "Vector element count mismatch!");
2440 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2441 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2443 case ISD::ZERO_EXTEND:
2444 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2445 "Invalid ZERO_EXTEND!");
2446 if (Operand.getValueType() == VT) return Operand; // noop extension
2447 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2448 "Invalid zext node, dst < src!");
2449 assert((!VT.isVector() ||
2450 VT.getVectorNumElements() ==
2451 Operand.getValueType().getVectorNumElements()) &&
2452 "Vector element count mismatch!");
2453 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2454 return getNode(ISD::ZERO_EXTEND, DL, VT,
2455 Operand.getNode()->getOperand(0));
2457 case ISD::ANY_EXTEND:
2458 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2459 "Invalid ANY_EXTEND!");
2460 if (Operand.getValueType() == VT) return Operand; // noop extension
2461 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2462 "Invalid anyext node, dst < src!");
2463 assert((!VT.isVector() ||
2464 VT.getVectorNumElements() ==
2465 Operand.getValueType().getVectorNumElements()) &&
2466 "Vector element count mismatch!");
2467 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2468 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2469 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2472 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2473 "Invalid TRUNCATE!");
2474 if (Operand.getValueType() == VT) return Operand; // noop truncate
2475 assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2476 "Invalid truncate node, src < dst!");
2477 assert((!VT.isVector() ||
2478 VT.getVectorNumElements() ==
2479 Operand.getValueType().getVectorNumElements()) &&
2480 "Vector element count mismatch!");
2481 if (OpOpcode == ISD::TRUNCATE)
2482 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2483 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2484 OpOpcode == ISD::ANY_EXTEND) {
2485 // If the source is smaller than the dest, we still need an extend.
2486 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2487 .bitsLT(VT.getScalarType()))
2488 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2489 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2490 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2492 return Operand.getNode()->getOperand(0);
2495 case ISD::BIT_CONVERT:
2496 // Basic sanity checking.
2497 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2498 && "Cannot BIT_CONVERT between types of different sizes!");
2499 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2500 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2501 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2502 if (OpOpcode == ISD::UNDEF)
2503 return getUNDEF(VT);
2505 case ISD::SCALAR_TO_VECTOR:
2506 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2507 (VT.getVectorElementType() == Operand.getValueType() ||
2508 (VT.getVectorElementType().isInteger() &&
2509 Operand.getValueType().isInteger() &&
2510 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2511 "Illegal SCALAR_TO_VECTOR node!");
2512 if (OpOpcode == ISD::UNDEF)
2513 return getUNDEF(VT);
2514 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2515 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2516 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2517 Operand.getConstantOperandVal(1) == 0 &&
2518 Operand.getOperand(0).getValueType() == VT)
2519 return Operand.getOperand(0);
2522 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2523 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2524 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2525 Operand.getNode()->getOperand(0));
2526 if (OpOpcode == ISD::FNEG) // --X -> X
2527 return Operand.getNode()->getOperand(0);
2530 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2531 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2536 SDVTList VTs = getVTList(VT);
2537 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2538 FoldingSetNodeID ID;
2539 SDValue Ops[1] = { Operand };
2540 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2542 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2543 return SDValue(E, 0);
2545 N = NodeAllocator.Allocate<UnarySDNode>();
2546 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2547 CSEMap.InsertNode(N, IP);
2549 N = NodeAllocator.Allocate<UnarySDNode>();
2550 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2553 AllNodes.push_back(N);
2557 return SDValue(N, 0);
2560 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2562 ConstantSDNode *Cst1,
2563 ConstantSDNode *Cst2) {
2564 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2567 case ISD::ADD: return getConstant(C1 + C2, VT);
2568 case ISD::SUB: return getConstant(C1 - C2, VT);
2569 case ISD::MUL: return getConstant(C1 * C2, VT);
2571 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2574 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2577 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2580 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2582 case ISD::AND: return getConstant(C1 & C2, VT);
2583 case ISD::OR: return getConstant(C1 | C2, VT);
2584 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2585 case ISD::SHL: return getConstant(C1 << C2, VT);
2586 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2587 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2588 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2589 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2596 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2597 SDValue N1, SDValue N2) {
2598 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2599 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2602 case ISD::TokenFactor:
2603 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2604 N2.getValueType() == MVT::Other && "Invalid token factor!");
2605 // Fold trivial token factors.
2606 if (N1.getOpcode() == ISD::EntryToken) return N2;
2607 if (N2.getOpcode() == ISD::EntryToken) return N1;
2608 if (N1 == N2) return N1;
2610 case ISD::CONCAT_VECTORS:
2611 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2612 // one big BUILD_VECTOR.
2613 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2614 N2.getOpcode() == ISD::BUILD_VECTOR) {
2615 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2616 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2617 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2621 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2622 N1.getValueType() == VT && "Binary operator types must match!");
2623 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2624 // worth handling here.
2625 if (N2C && N2C->isNullValue())
2627 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2634 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2635 N1.getValueType() == VT && "Binary operator types must match!");
2636 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2637 // it's worth handling here.
2638 if (N2C && N2C->isNullValue())
2648 assert(VT.isInteger() && "This operator does not apply to FP types!");
2656 if (Opcode == ISD::FADD) {
2658 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2659 if (CFP->getValueAPF().isZero())
2662 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2663 if (CFP->getValueAPF().isZero())
2665 } else if (Opcode == ISD::FSUB) {
2667 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2668 if (CFP->getValueAPF().isZero())
2672 assert(N1.getValueType() == N2.getValueType() &&
2673 N1.getValueType() == VT && "Binary operator types must match!");
2675 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2676 assert(N1.getValueType() == VT &&
2677 N1.getValueType().isFloatingPoint() &&
2678 N2.getValueType().isFloatingPoint() &&
2679 "Invalid FCOPYSIGN!");
2686 assert(VT == N1.getValueType() &&
2687 "Shift operators return type must be the same as their first arg");
2688 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2689 "Shifts only work on integers");
2691 // Always fold shifts of i1 values so the code generator doesn't need to
2692 // handle them. Since we know the size of the shift has to be less than the
2693 // size of the value, the shift/rotate count is guaranteed to be zero.
2696 if (N2C && N2C->isNullValue())
2699 case ISD::FP_ROUND_INREG: {
2700 EVT EVT = cast<VTSDNode>(N2)->getVT();
2701 assert(VT == N1.getValueType() && "Not an inreg round!");
2702 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2703 "Cannot FP_ROUND_INREG integer types");
2704 assert(EVT.isVector() == VT.isVector() &&
2705 "FP_ROUND_INREG type should be vector iff the operand "
2707 assert((!EVT.isVector() ||
2708 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2709 "Vector element counts must match in FP_ROUND_INREG");
2710 assert(EVT.bitsLE(VT) && "Not rounding down!");
2711 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2715 assert(VT.isFloatingPoint() &&
2716 N1.getValueType().isFloatingPoint() &&
2717 VT.bitsLE(N1.getValueType()) &&
2718 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2719 if (N1.getValueType() == VT) return N1; // noop conversion.
2721 case ISD::AssertSext:
2722 case ISD::AssertZext: {
2723 EVT EVT = cast<VTSDNode>(N2)->getVT();
2724 assert(VT == N1.getValueType() && "Not an inreg extend!");
2725 assert(VT.isInteger() && EVT.isInteger() &&
2726 "Cannot *_EXTEND_INREG FP types");
2727 assert(!EVT.isVector() &&
2728 "AssertSExt/AssertZExt type should be the vector element type "
2729 "rather than the vector type!");
2730 assert(EVT.bitsLE(VT) && "Not extending!");
2731 if (VT == EVT) return N1; // noop assertion.
2734 case ISD::SIGN_EXTEND_INREG: {
2735 EVT EVT = cast<VTSDNode>(N2)->getVT();
2736 assert(VT == N1.getValueType() && "Not an inreg extend!");
2737 assert(VT.isInteger() && EVT.isInteger() &&
2738 "Cannot *_EXTEND_INREG FP types");
2739 assert(EVT.isVector() == VT.isVector() &&
2740 "SIGN_EXTEND_INREG type should be vector iff the operand "
2742 assert((!EVT.isVector() ||
2743 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2744 "Vector element counts must match in SIGN_EXTEND_INREG");
2745 assert(EVT.bitsLE(VT) && "Not extending!");
2746 if (EVT == VT) return N1; // Not actually extending
2749 APInt Val = N1C->getAPIntValue();
2750 unsigned FromBits = EVT.getScalarType().getSizeInBits();
2751 Val <<= Val.getBitWidth()-FromBits;
2752 Val = Val.ashr(Val.getBitWidth()-FromBits);
2753 return getConstant(Val, VT);
2757 case ISD::EXTRACT_VECTOR_ELT:
2758 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2759 if (N1.getOpcode() == ISD::UNDEF)
2760 return getUNDEF(VT);
2762 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2763 // expanding copies of large vectors from registers.
2765 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2766 N1.getNumOperands() > 0) {
2768 N1.getOperand(0).getValueType().getVectorNumElements();
2769 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2770 N1.getOperand(N2C->getZExtValue() / Factor),
2771 getConstant(N2C->getZExtValue() % Factor,
2772 N2.getValueType()));
2775 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2776 // expanding large vector constants.
2777 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2778 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2779 EVT VEltTy = N1.getValueType().getVectorElementType();
2780 if (Elt.getValueType() != VEltTy) {
2781 // If the vector element type is not legal, the BUILD_VECTOR operands
2782 // are promoted and implicitly truncated. Make that explicit here.
2783 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2786 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2787 // result is implicitly extended.
2788 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2793 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2794 // operations are lowered to scalars.
2795 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2796 // If the indices are the same, return the inserted element else
2797 // if the indices are known different, extract the element from
2798 // the original vector.
2799 if (N1.getOperand(2) == N2) {
2800 if (VT == N1.getOperand(1).getValueType())
2801 return N1.getOperand(1);
2803 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
2804 } else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2805 isa<ConstantSDNode>(N2))
2806 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2809 case ISD::EXTRACT_ELEMENT:
2810 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2811 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2812 (N1.getValueType().isInteger() == VT.isInteger()) &&
2813 "Wrong types for EXTRACT_ELEMENT!");
2815 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2816 // 64-bit integers into 32-bit parts. Instead of building the extract of
2817 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2818 if (N1.getOpcode() == ISD::BUILD_PAIR)
2819 return N1.getOperand(N2C->getZExtValue());
2821 // EXTRACT_ELEMENT of a constant int is also very common.
2822 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2823 unsigned ElementSize = VT.getSizeInBits();
2824 unsigned Shift = ElementSize * N2C->getZExtValue();
2825 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2826 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2829 case ISD::EXTRACT_SUBVECTOR:
2830 if (N1.getValueType() == VT) // Trivial extraction.
2837 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2838 if (SV.getNode()) return SV;
2839 } else { // Cannonicalize constant to RHS if commutative
2840 if (isCommutativeBinOp(Opcode)) {
2841 std::swap(N1C, N2C);
2847 // Constant fold FP operations.
2848 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2849 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2851 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2852 // Cannonicalize constant to RHS if commutative
2853 std::swap(N1CFP, N2CFP);
2855 } else if (N2CFP && VT != MVT::ppcf128) {
2856 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2857 APFloat::opStatus s;
2860 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2861 if (s != APFloat::opInvalidOp)
2862 return getConstantFP(V1, VT);
2865 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2866 if (s!=APFloat::opInvalidOp)
2867 return getConstantFP(V1, VT);
2870 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2871 if (s!=APFloat::opInvalidOp)
2872 return getConstantFP(V1, VT);
2875 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2876 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2877 return getConstantFP(V1, VT);
2880 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2881 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2882 return getConstantFP(V1, VT);
2884 case ISD::FCOPYSIGN:
2886 return getConstantFP(V1, VT);
2892 // Canonicalize an UNDEF to the RHS, even over a constant.
2893 if (N1.getOpcode() == ISD::UNDEF) {
2894 if (isCommutativeBinOp(Opcode)) {
2898 case ISD::FP_ROUND_INREG:
2899 case ISD::SIGN_EXTEND_INREG:
2905 return N1; // fold op(undef, arg2) -> undef
2913 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2914 // For vectors, we can't easily build an all zero vector, just return
2921 // Fold a bunch of operators when the RHS is undef.
2922 if (N2.getOpcode() == ISD::UNDEF) {
2925 if (N1.getOpcode() == ISD::UNDEF)
2926 // Handle undef ^ undef -> 0 special case. This is a common
2928 return getConstant(0, VT);
2938 return N2; // fold op(arg1, undef) -> undef
2952 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2953 // For vectors, we can't easily build an all zero vector, just return
2958 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2959 // For vectors, we can't easily build an all one vector, just return
2967 // Memoize this node if possible.
2969 SDVTList VTs = getVTList(VT);
2970 if (VT != MVT::Flag) {
2971 SDValue Ops[] = { N1, N2 };
2972 FoldingSetNodeID ID;
2973 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2975 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2976 return SDValue(E, 0);
2978 N = NodeAllocator.Allocate<BinarySDNode>();
2979 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2980 CSEMap.InsertNode(N, IP);
2982 N = NodeAllocator.Allocate<BinarySDNode>();
2983 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2986 AllNodes.push_back(N);
2990 return SDValue(N, 0);
2993 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2994 SDValue N1, SDValue N2, SDValue N3) {
2995 // Perform various simplifications.
2996 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2997 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2999 case ISD::CONCAT_VECTORS:
3000 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3001 // one big BUILD_VECTOR.
3002 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3003 N2.getOpcode() == ISD::BUILD_VECTOR &&
3004 N3.getOpcode() == ISD::BUILD_VECTOR) {
3005 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
3006 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
3007 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
3008 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
3012 // Use FoldSetCC to simplify SETCC's.
3013 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3014 if (Simp.getNode()) return Simp;
3019 if (N1C->getZExtValue())
3020 return N2; // select true, X, Y -> X
3022 return N3; // select false, X, Y -> Y
3025 if (N2 == N3) return N2; // select C, X, X -> X
3029 if (N2C->getZExtValue()) // Unconditional branch
3030 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
3032 return N1; // Never-taken branch
3035 case ISD::VECTOR_SHUFFLE:
3036 llvm_unreachable("should use getVectorShuffle constructor!");
3038 case ISD::BIT_CONVERT:
3039 // Fold bit_convert nodes from a type to themselves.
3040 if (N1.getValueType() == VT)
3045 // Memoize node if it doesn't produce a flag.
3047 SDVTList VTs = getVTList(VT);
3048 if (VT != MVT::Flag) {
3049 SDValue Ops[] = { N1, N2, N3 };
3050 FoldingSetNodeID ID;
3051 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3053 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3054 return SDValue(E, 0);
3056 N = NodeAllocator.Allocate<TernarySDNode>();
3057 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3058 CSEMap.InsertNode(N, IP);
3060 N = NodeAllocator.Allocate<TernarySDNode>();
3061 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3064 AllNodes.push_back(N);
3068 return SDValue(N, 0);
3071 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3072 SDValue N1, SDValue N2, SDValue N3,
3074 SDValue Ops[] = { N1, N2, N3, N4 };
3075 return getNode(Opcode, DL, VT, Ops, 4);
3078 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3079 SDValue N1, SDValue N2, SDValue N3,
3080 SDValue N4, SDValue N5) {
3081 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3082 return getNode(Opcode, DL, VT, Ops, 5);
3085 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3086 /// the incoming stack arguments to be loaded from the stack.
3087 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3088 SmallVector<SDValue, 8> ArgChains;
3090 // Include the original chain at the beginning of the list. When this is
3091 // used by target LowerCall hooks, this helps legalize find the
3092 // CALLSEQ_BEGIN node.
3093 ArgChains.push_back(Chain);
3095 // Add a chain value for each stack argument.
3096 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3097 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3098 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3099 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3100 if (FI->getIndex() < 0)
3101 ArgChains.push_back(SDValue(L, 1));
3103 // Build a tokenfactor for all the chains.
3104 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
3105 &ArgChains[0], ArgChains.size());
3108 /// getMemsetValue - Vectorized representation of the memset value
3110 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3112 unsigned NumBits = VT.getScalarType().getSizeInBits();
3113 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3114 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
3116 for (unsigned i = NumBits; i > 8; i >>= 1) {
3117 Val = (Val << Shift) | Val;
3121 return DAG.getConstant(Val, VT);
3122 return DAG.getConstantFP(APFloat(Val), VT);
3125 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3126 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3128 for (unsigned i = NumBits; i > 8; i >>= 1) {
3129 Value = DAG.getNode(ISD::OR, dl, VT,
3130 DAG.getNode(ISD::SHL, dl, VT, Value,
3131 DAG.getConstant(Shift,
3132 TLI.getShiftAmountTy())),
3140 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3141 /// used when a memcpy is turned into a memset when the source is a constant
3143 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3144 const TargetLowering &TLI,
3145 std::string &Str, unsigned Offset) {
3146 // Handle vector with all elements zero.
3149 return DAG.getConstant(0, VT);
3150 unsigned NumElts = VT.getVectorNumElements();
3151 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3152 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3154 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts)));
3157 assert(!VT.isVector() && "Can't handle vector type here!");
3158 unsigned NumBits = VT.getSizeInBits();
3159 unsigned MSB = NumBits / 8;
3161 if (TLI.isLittleEndian())
3162 Offset = Offset + MSB - 1;
3163 for (unsigned i = 0; i != MSB; ++i) {
3164 Val = (Val << 8) | (unsigned char)Str[Offset];
3165 Offset += TLI.isLittleEndian() ? -1 : 1;
3167 return DAG.getConstant(Val, VT);
3170 /// getMemBasePlusOffset - Returns base and offset node for the
3172 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3173 SelectionDAG &DAG) {
3174 EVT VT = Base.getValueType();
3175 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3176 VT, Base, DAG.getConstant(Offset, VT));
3179 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3181 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3182 unsigned SrcDelta = 0;
3183 GlobalAddressSDNode *G = NULL;
3184 if (Src.getOpcode() == ISD::GlobalAddress)
3185 G = cast<GlobalAddressSDNode>(Src);
3186 else if (Src.getOpcode() == ISD::ADD &&
3187 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3188 Src.getOperand(1).getOpcode() == ISD::Constant) {
3189 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3190 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3195 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3196 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3202 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3203 /// to replace the memset / memcpy is below the threshold. It also returns the
3204 /// types of the sequence of memory ops to perform memset / memcpy.
3206 bool MeetsMaxMemopRequirement(std::vector<EVT> &MemOps,
3207 SDValue Dst, SDValue Src,
3208 unsigned Limit, uint64_t Size, unsigned &Align,
3209 std::string &Str, bool &isSrcStr,
3211 const TargetLowering &TLI) {
3212 isSrcStr = isMemSrcFromString(Src, Str);
3213 bool isSrcConst = isa<ConstantSDNode>(Src);
3214 EVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
3215 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses(VT);
3216 if (VT != MVT::Other) {
3217 const Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3218 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3219 // If source is a string constant, this will require an unaligned load.
3220 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3221 if (Dst.getOpcode() != ISD::FrameIndex) {
3222 // Can't change destination alignment. It requires a unaligned store.
3226 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3227 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3228 if (MFI->isFixedObjectIndex(FI)) {
3229 // Can't change destination alignment. It requires a unaligned store.
3233 // Give the stack frame object a larger alignment if needed.
3234 if (MFI->getObjectAlignment(FI) < NewAlign)
3235 MFI->setObjectAlignment(FI, NewAlign);
3242 if (VT == MVT::Other) {
3243 if (TLI.allowsUnalignedMemoryAccesses(MVT::i64)) {
3246 switch (Align & 7) {
3247 case 0: VT = MVT::i64; break;
3248 case 4: VT = MVT::i32; break;
3249 case 2: VT = MVT::i16; break;
3250 default: VT = MVT::i8; break;
3255 while (!TLI.isTypeLegal(LVT))
3256 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3257 assert(LVT.isInteger());
3263 unsigned NumMemOps = 0;
3265 unsigned VTSize = VT.getSizeInBits() / 8;
3266 while (VTSize > Size) {
3267 // For now, only use non-vector load / store's for the left-over pieces.
3268 if (VT.isVector()) {
3270 while (!TLI.isTypeLegal(VT))
3271 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3272 VTSize = VT.getSizeInBits() / 8;
3274 // This can result in a type that is not legal on the target, e.g.
3275 // 1 or 2 bytes on PPC.
3276 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3281 if (++NumMemOps > Limit)
3283 MemOps.push_back(VT);
3290 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3291 SDValue Chain, SDValue Dst,
3292 SDValue Src, uint64_t Size,
3293 unsigned Align, bool AlwaysInline,
3294 const Value *DstSV, uint64_t DstSVOff,
3295 const Value *SrcSV, uint64_t SrcSVOff){
3296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3298 // Expand memcpy to a series of load and store ops if the size operand falls
3299 // below a certain threshold.
3300 std::vector<EVT> MemOps;
3301 uint64_t Limit = -1ULL;
3303 Limit = TLI.getMaxStoresPerMemcpy();
3304 unsigned DstAlign = Align; // Destination alignment can change.
3307 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3308 Str, CopyFromStr, DAG, TLI))
3312 bool isZeroStr = CopyFromStr && Str.empty();
3313 SmallVector<SDValue, 8> OutChains;
3314 unsigned NumMemOps = MemOps.size();
3315 uint64_t SrcOff = 0, DstOff = 0;
3316 for (unsigned i = 0; i != NumMemOps; ++i) {
3318 unsigned VTSize = VT.getSizeInBits() / 8;
3319 SDValue Value, Store;
3321 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3322 // It's unlikely a store of a vector immediate can be done in a single
3323 // instruction. It would require a load from a constantpool first.
3324 // We also handle store a vector with all zero's.
3325 // FIXME: Handle other cases where store of vector immediate is done in
3326 // a single instruction.
3327 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3328 Store = DAG.getStore(Chain, dl, Value,
3329 getMemBasePlusOffset(Dst, DstOff, DAG),
3330 DstSV, DstSVOff + DstOff, false, false, DstAlign);
3332 // The type might not be legal for the target. This should only happen
3333 // if the type is smaller than a legal type, as on PPC, so the right
3334 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3335 // to Load/Store if NVT==VT.
3336 // FIXME does the case above also need this?
3337 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3338 assert(NVT.bitsGE(VT));
3339 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3340 getMemBasePlusOffset(Src, SrcOff, DAG),
3341 SrcSV, SrcSVOff + SrcOff, VT, false, false, Align);
3342 Store = DAG.getTruncStore(Chain, dl, Value,
3343 getMemBasePlusOffset(Dst, DstOff, DAG),
3344 DstSV, DstSVOff + DstOff, VT, false, false,
3347 OutChains.push_back(Store);
3352 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3353 &OutChains[0], OutChains.size());
3356 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3357 SDValue Chain, SDValue Dst,
3358 SDValue Src, uint64_t Size,
3359 unsigned Align, bool AlwaysInline,
3360 const Value *DstSV, uint64_t DstSVOff,
3361 const Value *SrcSV, uint64_t SrcSVOff){
3362 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3364 // Expand memmove to a series of load and store ops if the size operand falls
3365 // below a certain threshold.
3366 std::vector<EVT> MemOps;
3367 uint64_t Limit = -1ULL;
3369 Limit = TLI.getMaxStoresPerMemmove();
3370 unsigned DstAlign = Align; // Destination alignment can change.
3373 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3374 Str, CopyFromStr, DAG, TLI))
3377 uint64_t SrcOff = 0, DstOff = 0;
3379 SmallVector<SDValue, 8> LoadValues;
3380 SmallVector<SDValue, 8> LoadChains;
3381 SmallVector<SDValue, 8> OutChains;
3382 unsigned NumMemOps = MemOps.size();
3383 for (unsigned i = 0; i < NumMemOps; i++) {
3385 unsigned VTSize = VT.getSizeInBits() / 8;
3386 SDValue Value, Store;
3388 Value = DAG.getLoad(VT, dl, Chain,
3389 getMemBasePlusOffset(Src, SrcOff, DAG),
3390 SrcSV, SrcSVOff + SrcOff, false, false, Align);
3391 LoadValues.push_back(Value);
3392 LoadChains.push_back(Value.getValue(1));
3395 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3396 &LoadChains[0], LoadChains.size());
3398 for (unsigned i = 0; i < NumMemOps; i++) {
3400 unsigned VTSize = VT.getSizeInBits() / 8;
3401 SDValue Value, Store;
3403 Store = DAG.getStore(Chain, dl, LoadValues[i],
3404 getMemBasePlusOffset(Dst, DstOff, DAG),
3405 DstSV, DstSVOff + DstOff, false, false, DstAlign);
3406 OutChains.push_back(Store);
3410 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3411 &OutChains[0], OutChains.size());
3414 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3415 SDValue Chain, SDValue Dst,
3416 SDValue Src, uint64_t Size,
3418 const Value *DstSV, uint64_t DstSVOff) {
3419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3421 // Expand memset to a series of load/store ops if the size operand
3422 // falls below a certain threshold.
3423 std::vector<EVT> MemOps;
3426 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3427 Size, Align, Str, CopyFromStr, DAG, TLI))
3430 SmallVector<SDValue, 8> OutChains;
3431 uint64_t DstOff = 0;
3433 unsigned NumMemOps = MemOps.size();
3434 for (unsigned i = 0; i < NumMemOps; i++) {
3436 unsigned VTSize = VT.getSizeInBits() / 8;
3437 SDValue Value = getMemsetValue(Src, VT, DAG, dl);
3438 SDValue Store = DAG.getStore(Chain, dl, Value,
3439 getMemBasePlusOffset(Dst, DstOff, DAG),
3440 DstSV, DstSVOff + DstOff, false, false, 0);
3441 OutChains.push_back(Store);
3445 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3446 &OutChains[0], OutChains.size());
3449 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3450 SDValue Src, SDValue Size,
3451 unsigned Align, bool AlwaysInline,
3452 const Value *DstSV, uint64_t DstSVOff,
3453 const Value *SrcSV, uint64_t SrcSVOff) {
3455 // Check to see if we should lower the memcpy to loads and stores first.
3456 // For cases within the target-specified limits, this is the best choice.
3457 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3459 // Memcpy with size zero? Just return the original chain.
3460 if (ConstantSize->isNullValue())
3464 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3465 ConstantSize->getZExtValue(),
3466 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3467 if (Result.getNode())
3471 // Then check to see if we should lower the memcpy with target-specific
3472 // code. If the target chooses to do this, this is the next best.
3474 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3476 DstSV, DstSVOff, SrcSV, SrcSVOff);
3477 if (Result.getNode())
3480 // If we really need inline code and the target declined to provide it,
3481 // use a (potentially long) sequence of loads and stores.
3483 assert(ConstantSize && "AlwaysInline requires a constant size!");
3484 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3485 ConstantSize->getZExtValue(), Align, true,
3486 DstSV, DstSVOff, SrcSV, SrcSVOff);
3489 // Emit a library call.
3490 TargetLowering::ArgListTy Args;
3491 TargetLowering::ArgListEntry Entry;
3492 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3493 Entry.Node = Dst; Args.push_back(Entry);
3494 Entry.Node = Src; Args.push_back(Entry);
3495 Entry.Node = Size; Args.push_back(Entry);
3496 // FIXME: pass in DebugLoc
3497 std::pair<SDValue,SDValue> CallResult =
3498 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3499 false, false, false, false, 0,
3500 TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3501 /*isReturnValueUsed=*/false,
3502 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3503 TLI.getPointerTy()),
3505 return CallResult.second;
3508 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3509 SDValue Src, SDValue Size,
3511 const Value *DstSV, uint64_t DstSVOff,
3512 const Value *SrcSV, uint64_t SrcSVOff) {
3514 // Check to see if we should lower the memmove to loads and stores first.
3515 // For cases within the target-specified limits, this is the best choice.
3516 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3518 // Memmove with size zero? Just return the original chain.
3519 if (ConstantSize->isNullValue())
3523 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3524 ConstantSize->getZExtValue(),
3525 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3526 if (Result.getNode())
3530 // Then check to see if we should lower the memmove with target-specific
3531 // code. If the target chooses to do this, this is the next best.
3533 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
3534 DstSV, DstSVOff, SrcSV, SrcSVOff);
3535 if (Result.getNode())
3538 // Emit a library call.
3539 TargetLowering::ArgListTy Args;
3540 TargetLowering::ArgListEntry Entry;
3541 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3542 Entry.Node = Dst; Args.push_back(Entry);
3543 Entry.Node = Src; Args.push_back(Entry);
3544 Entry.Node = Size; Args.push_back(Entry);
3545 // FIXME: pass in DebugLoc
3546 std::pair<SDValue,SDValue> CallResult =
3547 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3548 false, false, false, false, 0,
3549 TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3550 /*isReturnValueUsed=*/false,
3551 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3552 TLI.getPointerTy()),
3554 return CallResult.second;
3557 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3558 SDValue Src, SDValue Size,
3560 const Value *DstSV, uint64_t DstSVOff) {
3562 // Check to see if we should lower the memset to stores first.
3563 // For cases within the target-specified limits, this is the best choice.
3564 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3566 // Memset with size zero? Just return the original chain.
3567 if (ConstantSize->isNullValue())
3571 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3572 Align, DstSV, DstSVOff);
3573 if (Result.getNode())
3577 // Then check to see if we should lower the memset with target-specific
3578 // code. If the target chooses to do this, this is the next best.
3580 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
3582 if (Result.getNode())
3585 // Emit a library call.
3586 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3587 TargetLowering::ArgListTy Args;
3588 TargetLowering::ArgListEntry Entry;
3589 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3590 Args.push_back(Entry);
3591 // Extend or truncate the argument to be an i32 value for the call.
3592 if (Src.getValueType().bitsGT(MVT::i32))
3593 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3595 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3597 Entry.Ty = Type::getInt32Ty(*getContext());
3598 Entry.isSExt = true;
3599 Args.push_back(Entry);
3601 Entry.Ty = IntPtrTy;
3602 Entry.isSExt = false;
3603 Args.push_back(Entry);
3604 // FIXME: pass in DebugLoc
3605 std::pair<SDValue,SDValue> CallResult =
3606 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3607 false, false, false, false, 0,
3608 TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3609 /*isReturnValueUsed=*/false,
3610 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3611 TLI.getPointerTy()),
3613 return CallResult.second;
3616 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3618 SDValue Ptr, SDValue Cmp,
3619 SDValue Swp, const Value* PtrVal,
3620 unsigned Alignment) {
3621 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3622 Alignment = getEVTAlignment(MemVT);
3624 // Check if the memory reference references a frame index
3626 if (const FrameIndexSDNode *FI =
3627 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3628 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3630 MachineFunction &MF = getMachineFunction();
3631 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3633 // For now, atomics are considered to be volatile always.
3634 Flags |= MachineMemOperand::MOVolatile;
3636 MachineMemOperand *MMO =
3637 MF.getMachineMemOperand(PtrVal, Flags, 0,
3638 MemVT.getStoreSize(), Alignment);
3640 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3643 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3645 SDValue Ptr, SDValue Cmp,
3646 SDValue Swp, MachineMemOperand *MMO) {
3647 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3648 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3650 EVT VT = Cmp.getValueType();
3652 SDVTList VTs = getVTList(VT, MVT::Other);
3653 FoldingSetNodeID ID;
3654 ID.AddInteger(MemVT.getRawBits());
3655 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3656 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3658 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3659 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3660 return SDValue(E, 0);
3662 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3663 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3664 CSEMap.InsertNode(N, IP);
3665 AllNodes.push_back(N);
3666 return SDValue(N, 0);
3669 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3671 SDValue Ptr, SDValue Val,
3672 const Value* PtrVal,
3673 unsigned Alignment) {
3674 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3675 Alignment = getEVTAlignment(MemVT);
3677 // Check if the memory reference references a frame index
3679 if (const FrameIndexSDNode *FI =
3680 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3681 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3683 MachineFunction &MF = getMachineFunction();
3684 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3686 // For now, atomics are considered to be volatile always.
3687 Flags |= MachineMemOperand::MOVolatile;
3689 MachineMemOperand *MMO =
3690 MF.getMachineMemOperand(PtrVal, Flags, 0,
3691 MemVT.getStoreSize(), Alignment);
3693 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
3696 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3698 SDValue Ptr, SDValue Val,
3699 MachineMemOperand *MMO) {
3700 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3701 Opcode == ISD::ATOMIC_LOAD_SUB ||
3702 Opcode == ISD::ATOMIC_LOAD_AND ||
3703 Opcode == ISD::ATOMIC_LOAD_OR ||
3704 Opcode == ISD::ATOMIC_LOAD_XOR ||
3705 Opcode == ISD::ATOMIC_LOAD_NAND ||
3706 Opcode == ISD::ATOMIC_LOAD_MIN ||
3707 Opcode == ISD::ATOMIC_LOAD_MAX ||
3708 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3709 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3710 Opcode == ISD::ATOMIC_SWAP) &&
3711 "Invalid Atomic Op");
3713 EVT VT = Val.getValueType();
3715 SDVTList VTs = getVTList(VT, MVT::Other);
3716 FoldingSetNodeID ID;
3717 ID.AddInteger(MemVT.getRawBits());
3718 SDValue Ops[] = {Chain, Ptr, Val};
3719 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3721 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3722 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3723 return SDValue(E, 0);
3725 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3726 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Val, MMO);
3727 CSEMap.InsertNode(N, IP);
3728 AllNodes.push_back(N);
3729 return SDValue(N, 0);
3732 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3733 /// Allowed to return something different (and simpler) if Simplify is true.
3734 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3739 SmallVector<EVT, 4> VTs;
3740 VTs.reserve(NumOps);
3741 for (unsigned i = 0; i < NumOps; ++i)
3742 VTs.push_back(Ops[i].getValueType());
3743 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3748 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3749 const EVT *VTs, unsigned NumVTs,
3750 const SDValue *Ops, unsigned NumOps,
3751 EVT MemVT, const Value *srcValue, int SVOff,
3752 unsigned Align, bool Vol,
3753 bool ReadMem, bool WriteMem) {
3754 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3755 MemVT, srcValue, SVOff, Align, Vol,
3760 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3761 const SDValue *Ops, unsigned NumOps,
3762 EVT MemVT, const Value *srcValue, int SVOff,
3763 unsigned Align, bool Vol,
3764 bool ReadMem, bool WriteMem) {
3765 if (Align == 0) // Ensure that codegen never sees alignment 0
3766 Align = getEVTAlignment(MemVT);
3768 MachineFunction &MF = getMachineFunction();
3771 Flags |= MachineMemOperand::MOStore;
3773 Flags |= MachineMemOperand::MOLoad;
3775 Flags |= MachineMemOperand::MOVolatile;
3776 MachineMemOperand *MMO =
3777 MF.getMachineMemOperand(srcValue, Flags, SVOff,
3778 MemVT.getStoreSize(), Align);
3780 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3784 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3785 const SDValue *Ops, unsigned NumOps,
3786 EVT MemVT, MachineMemOperand *MMO) {
3787 assert((Opcode == ISD::INTRINSIC_VOID ||
3788 Opcode == ISD::INTRINSIC_W_CHAIN ||
3789 (Opcode <= INT_MAX &&
3790 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
3791 "Opcode is not a memory-accessing opcode!");
3793 // Memoize the node unless it returns a flag.
3794 MemIntrinsicSDNode *N;
3795 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3796 FoldingSetNodeID ID;
3797 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3799 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3800 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
3801 return SDValue(E, 0);
3804 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3805 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3806 CSEMap.InsertNode(N, IP);
3808 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3809 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3811 AllNodes.push_back(N);
3812 return SDValue(N, 0);
3816 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3817 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3818 SDValue Ptr, SDValue Offset,
3819 const Value *SV, int SVOffset, EVT MemVT,
3820 bool isVolatile, bool isNonTemporal,
3821 unsigned Alignment) {
3822 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3823 Alignment = getEVTAlignment(VT);
3825 // Check if the memory reference references a frame index
3827 if (const FrameIndexSDNode *FI =
3828 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3829 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3831 MachineFunction &MF = getMachineFunction();
3832 unsigned Flags = MachineMemOperand::MOLoad;
3834 Flags |= MachineMemOperand::MOVolatile;
3836 Flags |= MachineMemOperand::MONonTemporal;
3837 MachineMemOperand *MMO =
3838 MF.getMachineMemOperand(SV, Flags, SVOffset,
3839 MemVT.getStoreSize(), Alignment);
3840 return getLoad(AM, dl, ExtType, VT, Chain, Ptr, Offset, MemVT, MMO);
3844 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3845 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3846 SDValue Ptr, SDValue Offset, EVT MemVT,
3847 MachineMemOperand *MMO) {
3849 ExtType = ISD::NON_EXTLOAD;
3850 } else if (ExtType == ISD::NON_EXTLOAD) {
3851 assert(VT == MemVT && "Non-extending load from different memory type!");
3854 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
3855 "Should only be an extending load, not truncating!");
3856 assert(VT.isInteger() == MemVT.isInteger() &&
3857 "Cannot convert from FP to Int or Int -> FP!");
3858 assert(VT.isVector() == MemVT.isVector() &&
3859 "Cannot use trunc store to convert to or from a vector!");
3860 assert((!VT.isVector() ||
3861 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
3862 "Cannot use trunc store to change the number of vector elements!");
3865 bool Indexed = AM != ISD::UNINDEXED;
3866 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3867 "Unindexed load with an offset!");
3869 SDVTList VTs = Indexed ?
3870 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3871 SDValue Ops[] = { Chain, Ptr, Offset };
3872 FoldingSetNodeID ID;
3873 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3874 ID.AddInteger(MemVT.getRawBits());
3875 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
3876 MMO->isNonTemporal()));
3878 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3879 cast<LoadSDNode>(E)->refineAlignment(MMO);
3880 return SDValue(E, 0);
3882 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3883 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, MemVT, MMO);
3884 CSEMap.InsertNode(N, IP);
3885 AllNodes.push_back(N);
3886 return SDValue(N, 0);
3889 SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
3890 SDValue Chain, SDValue Ptr,
3891 const Value *SV, int SVOffset,
3892 bool isVolatile, bool isNonTemporal,
3893 unsigned Alignment) {
3894 SDValue Undef = getUNDEF(Ptr.getValueType());
3895 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3896 SV, SVOffset, VT, isVolatile, isNonTemporal, Alignment);
3899 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
3900 SDValue Chain, SDValue Ptr,
3902 int SVOffset, EVT MemVT,
3903 bool isVolatile, bool isNonTemporal,
3904 unsigned Alignment) {
3905 SDValue Undef = getUNDEF(Ptr.getValueType());
3906 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3907 SV, SVOffset, MemVT, isVolatile, isNonTemporal, Alignment);
3911 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3912 SDValue Offset, ISD::MemIndexedMode AM) {
3913 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3914 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3915 "Load is already a indexed load!");
3916 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3917 LD->getChain(), Base, Offset, LD->getSrcValue(),
3918 LD->getSrcValueOffset(), LD->getMemoryVT(),
3919 LD->isVolatile(), LD->isNonTemporal(), LD->getAlignment());
3922 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3923 SDValue Ptr, const Value *SV, int SVOffset,
3924 bool isVolatile, bool isNonTemporal,
3925 unsigned Alignment) {
3926 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3927 Alignment = getEVTAlignment(Val.getValueType());
3929 // Check if the memory reference references a frame index
3931 if (const FrameIndexSDNode *FI =
3932 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3933 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3935 MachineFunction &MF = getMachineFunction();
3936 unsigned Flags = MachineMemOperand::MOStore;
3938 Flags |= MachineMemOperand::MOVolatile;
3940 Flags |= MachineMemOperand::MONonTemporal;
3941 MachineMemOperand *MMO =
3942 MF.getMachineMemOperand(SV, Flags, SVOffset,
3943 Val.getValueType().getStoreSize(), Alignment);
3945 return getStore(Chain, dl, Val, Ptr, MMO);
3948 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3949 SDValue Ptr, MachineMemOperand *MMO) {
3950 EVT VT = Val.getValueType();
3951 SDVTList VTs = getVTList(MVT::Other);
3952 SDValue Undef = getUNDEF(Ptr.getValueType());
3953 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3954 FoldingSetNodeID ID;
3955 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3956 ID.AddInteger(VT.getRawBits());
3957 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
3958 MMO->isNonTemporal()));
3960 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3961 cast<StoreSDNode>(E)->refineAlignment(MMO);
3962 return SDValue(E, 0);
3964 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3965 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false, VT, MMO);
3966 CSEMap.InsertNode(N, IP);
3967 AllNodes.push_back(N);
3968 return SDValue(N, 0);
3971 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3972 SDValue Ptr, const Value *SV,
3973 int SVOffset, EVT SVT,
3974 bool isVolatile, bool isNonTemporal,
3975 unsigned Alignment) {
3976 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3977 Alignment = getEVTAlignment(SVT);
3979 // Check if the memory reference references a frame index
3981 if (const FrameIndexSDNode *FI =
3982 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3983 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3985 MachineFunction &MF = getMachineFunction();
3986 unsigned Flags = MachineMemOperand::MOStore;
3988 Flags |= MachineMemOperand::MOVolatile;
3990 Flags |= MachineMemOperand::MONonTemporal;
3991 MachineMemOperand *MMO =
3992 MF.getMachineMemOperand(SV, Flags, SVOffset, SVT.getStoreSize(), Alignment);
3994 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
3997 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3998 SDValue Ptr, EVT SVT,
3999 MachineMemOperand *MMO) {
4000 EVT VT = Val.getValueType();
4003 return getStore(Chain, dl, Val, Ptr, MMO);
4005 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
4006 "Should only be a truncating store, not extending!");
4007 assert(VT.isInteger() == SVT.isInteger() &&
4008 "Can't do FP-INT conversion!");
4009 assert(VT.isVector() == SVT.isVector() &&
4010 "Cannot use trunc store to convert to or from a vector!");
4011 assert((!VT.isVector() ||
4012 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
4013 "Cannot use trunc store to change the number of vector elements!");
4015 SDVTList VTs = getVTList(MVT::Other);
4016 SDValue Undef = getUNDEF(Ptr.getValueType());
4017 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4018 FoldingSetNodeID ID;
4019 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4020 ID.AddInteger(SVT.getRawBits());
4021 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
4022 MMO->isNonTemporal()));
4024 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4025 cast<StoreSDNode>(E)->refineAlignment(MMO);
4026 return SDValue(E, 0);
4028 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
4029 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true, SVT, MMO);
4030 CSEMap.InsertNode(N, IP);
4031 AllNodes.push_back(N);
4032 return SDValue(N, 0);
4036 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
4037 SDValue Offset, ISD::MemIndexedMode AM) {
4038 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4039 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4040 "Store is already a indexed store!");
4041 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4042 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4043 FoldingSetNodeID ID;
4044 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4045 ID.AddInteger(ST->getMemoryVT().getRawBits());
4046 ID.AddInteger(ST->getRawSubclassData());
4048 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4049 return SDValue(E, 0);
4051 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
4052 new (N) StoreSDNode(Ops, dl, VTs, AM,
4053 ST->isTruncatingStore(), ST->getMemoryVT(),
4054 ST->getMemOperand());
4055 CSEMap.InsertNode(N, IP);
4056 AllNodes.push_back(N);
4057 return SDValue(N, 0);
4060 SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
4061 SDValue Chain, SDValue Ptr,
4063 SDValue Ops[] = { Chain, Ptr, SV };
4064 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
4067 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4068 const SDUse *Ops, unsigned NumOps) {
4070 case 0: return getNode(Opcode, DL, VT);
4071 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4072 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4073 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4077 // Copy from an SDUse array into an SDValue array for use with
4078 // the regular getNode logic.
4079 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4080 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4083 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4084 const SDValue *Ops, unsigned NumOps) {
4086 case 0: return getNode(Opcode, DL, VT);
4087 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4088 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4089 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4095 case ISD::SELECT_CC: {
4096 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4097 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4098 "LHS and RHS of condition must have same type!");
4099 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4100 "True and False arms of SelectCC must have same type!");
4101 assert(Ops[2].getValueType() == VT &&
4102 "select_cc node must be of same type as true and false value!");
4106 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4107 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4108 "LHS/RHS of comparison should match types!");
4115 SDVTList VTs = getVTList(VT);
4117 if (VT != MVT::Flag) {
4118 FoldingSetNodeID ID;
4119 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4122 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4123 return SDValue(E, 0);
4125 N = NodeAllocator.Allocate<SDNode>();
4126 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4127 CSEMap.InsertNode(N, IP);
4129 N = NodeAllocator.Allocate<SDNode>();
4130 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4133 AllNodes.push_back(N);
4137 return SDValue(N, 0);
4140 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4141 const std::vector<EVT> &ResultTys,
4142 const SDValue *Ops, unsigned NumOps) {
4143 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4147 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4148 const EVT *VTs, unsigned NumVTs,
4149 const SDValue *Ops, unsigned NumOps) {
4151 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4152 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4155 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4156 const SDValue *Ops, unsigned NumOps) {
4157 if (VTList.NumVTs == 1)
4158 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4162 // FIXME: figure out how to safely handle things like
4163 // int foo(int x) { return 1 << (x & 255); }
4164 // int bar() { return foo(256); }
4165 case ISD::SRA_PARTS:
4166 case ISD::SRL_PARTS:
4167 case ISD::SHL_PARTS:
4168 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4169 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4170 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4171 else if (N3.getOpcode() == ISD::AND)
4172 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4173 // If the and is only masking out bits that cannot effect the shift,
4174 // eliminate the and.
4175 unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
4176 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4177 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4183 // Memoize the node unless it returns a flag.
4185 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4186 FoldingSetNodeID ID;
4187 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4189 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4190 return SDValue(E, 0);
4193 N = NodeAllocator.Allocate<UnarySDNode>();
4194 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4195 } else if (NumOps == 2) {
4196 N = NodeAllocator.Allocate<BinarySDNode>();
4197 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4198 } else if (NumOps == 3) {
4199 N = NodeAllocator.Allocate<TernarySDNode>();
4200 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4202 N = NodeAllocator.Allocate<SDNode>();
4203 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4205 CSEMap.InsertNode(N, IP);
4208 N = NodeAllocator.Allocate<UnarySDNode>();
4209 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4210 } else if (NumOps == 2) {
4211 N = NodeAllocator.Allocate<BinarySDNode>();
4212 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4213 } else if (NumOps == 3) {
4214 N = NodeAllocator.Allocate<TernarySDNode>();
4215 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4217 N = NodeAllocator.Allocate<SDNode>();
4218 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4221 AllNodes.push_back(N);
4225 return SDValue(N, 0);
4228 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4229 return getNode(Opcode, DL, VTList, 0, 0);
4232 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4234 SDValue Ops[] = { N1 };
4235 return getNode(Opcode, DL, VTList, Ops, 1);
4238 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4239 SDValue N1, SDValue N2) {
4240 SDValue Ops[] = { N1, N2 };
4241 return getNode(Opcode, DL, VTList, Ops, 2);
4244 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4245 SDValue N1, SDValue N2, SDValue N3) {
4246 SDValue Ops[] = { N1, N2, N3 };
4247 return getNode(Opcode, DL, VTList, Ops, 3);
4250 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4251 SDValue N1, SDValue N2, SDValue N3,
4253 SDValue Ops[] = { N1, N2, N3, N4 };
4254 return getNode(Opcode, DL, VTList, Ops, 4);
4257 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4258 SDValue N1, SDValue N2, SDValue N3,
4259 SDValue N4, SDValue N5) {
4260 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4261 return getNode(Opcode, DL, VTList, Ops, 5);
4264 SDVTList SelectionDAG::getVTList(EVT VT) {
4265 return makeVTList(SDNode::getValueTypeList(VT), 1);
4268 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4269 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4270 E = VTList.rend(); I != E; ++I)
4271 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4274 EVT *Array = Allocator.Allocate<EVT>(2);
4277 SDVTList Result = makeVTList(Array, 2);
4278 VTList.push_back(Result);
4282 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4283 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4284 E = VTList.rend(); I != E; ++I)
4285 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4289 EVT *Array = Allocator.Allocate<EVT>(3);
4293 SDVTList Result = makeVTList(Array, 3);
4294 VTList.push_back(Result);
4298 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4299 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4300 E = VTList.rend(); I != E; ++I)
4301 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4302 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4305 EVT *Array = Allocator.Allocate<EVT>(4);
4310 SDVTList Result = makeVTList(Array, 4);
4311 VTList.push_back(Result);
4315 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4317 case 0: llvm_unreachable("Cannot have nodes without results!");
4318 case 1: return getVTList(VTs[0]);
4319 case 2: return getVTList(VTs[0], VTs[1]);
4320 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4321 case 4: return getVTList(VTs[0], VTs[1], VTs[2], VTs[3]);
4325 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4326 E = VTList.rend(); I != E; ++I) {
4327 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4330 bool NoMatch = false;
4331 for (unsigned i = 2; i != NumVTs; ++i)
4332 if (VTs[i] != I->VTs[i]) {
4340 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4341 std::copy(VTs, VTs+NumVTs, Array);
4342 SDVTList Result = makeVTList(Array, NumVTs);
4343 VTList.push_back(Result);
4348 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4349 /// specified operands. If the resultant node already exists in the DAG,
4350 /// this does not modify the specified node, instead it returns the node that
4351 /// already exists. If the resultant node does not exist in the DAG, the
4352 /// input node is returned. As a degenerate case, if you specify the same
4353 /// input operands as the node already has, the input node is returned.
4354 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4355 SDNode *N = InN.getNode();
4356 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4358 // Check to see if there is no change.
4359 if (Op == N->getOperand(0)) return InN;
4361 // See if the modified node already exists.
4362 void *InsertPos = 0;
4363 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4364 return SDValue(Existing, InN.getResNo());
4366 // Nope it doesn't. Remove the node from its current place in the maps.
4368 if (!RemoveNodeFromCSEMaps(N))
4371 // Now we update the operands.
4372 N->OperandList[0].set(Op);
4374 // If this gets put into a CSE map, add it.
4375 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4379 SDValue SelectionDAG::
4380 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4381 SDNode *N = InN.getNode();
4382 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4384 // Check to see if there is no change.
4385 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4386 return InN; // No operands changed, just return the input node.
4388 // See if the modified node already exists.
4389 void *InsertPos = 0;
4390 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4391 return SDValue(Existing, InN.getResNo());
4393 // Nope it doesn't. Remove the node from its current place in the maps.
4395 if (!RemoveNodeFromCSEMaps(N))
4398 // Now we update the operands.
4399 if (N->OperandList[0] != Op1)
4400 N->OperandList[0].set(Op1);
4401 if (N->OperandList[1] != Op2)
4402 N->OperandList[1].set(Op2);
4404 // If this gets put into a CSE map, add it.
4405 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4409 SDValue SelectionDAG::
4410 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4411 SDValue Ops[] = { Op1, Op2, Op3 };
4412 return UpdateNodeOperands(N, Ops, 3);
4415 SDValue SelectionDAG::
4416 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4417 SDValue Op3, SDValue Op4) {
4418 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4419 return UpdateNodeOperands(N, Ops, 4);
4422 SDValue SelectionDAG::
4423 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4424 SDValue Op3, SDValue Op4, SDValue Op5) {
4425 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4426 return UpdateNodeOperands(N, Ops, 5);
4429 SDValue SelectionDAG::
4430 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4431 SDNode *N = InN.getNode();
4432 assert(N->getNumOperands() == NumOps &&
4433 "Update with wrong number of operands");
4435 // Check to see if there is no change.
4436 bool AnyChange = false;
4437 for (unsigned i = 0; i != NumOps; ++i) {
4438 if (Ops[i] != N->getOperand(i)) {
4444 // No operands changed, just return the input node.
4445 if (!AnyChange) return InN;
4447 // See if the modified node already exists.
4448 void *InsertPos = 0;
4449 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4450 return SDValue(Existing, InN.getResNo());
4452 // Nope it doesn't. Remove the node from its current place in the maps.
4454 if (!RemoveNodeFromCSEMaps(N))
4457 // Now we update the operands.
4458 for (unsigned i = 0; i != NumOps; ++i)
4459 if (N->OperandList[i] != Ops[i])
4460 N->OperandList[i].set(Ops[i]);
4462 // If this gets put into a CSE map, add it.
4463 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4467 /// DropOperands - Release the operands and set this node to have
4469 void SDNode::DropOperands() {
4470 // Unlike the code in MorphNodeTo that does this, we don't need to
4471 // watch for dead nodes here.
4472 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4478 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4481 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4483 SDVTList VTs = getVTList(VT);
4484 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4487 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4488 EVT VT, SDValue Op1) {
4489 SDVTList VTs = getVTList(VT);
4490 SDValue Ops[] = { Op1 };
4491 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4494 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4495 EVT VT, SDValue Op1,
4497 SDVTList VTs = getVTList(VT);
4498 SDValue Ops[] = { Op1, Op2 };
4499 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4502 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4503 EVT VT, SDValue Op1,
4504 SDValue Op2, SDValue Op3) {
4505 SDVTList VTs = getVTList(VT);
4506 SDValue Ops[] = { Op1, Op2, Op3 };
4507 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4510 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4511 EVT VT, const SDValue *Ops,
4513 SDVTList VTs = getVTList(VT);
4514 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4517 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4518 EVT VT1, EVT VT2, const SDValue *Ops,
4520 SDVTList VTs = getVTList(VT1, VT2);
4521 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4524 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4526 SDVTList VTs = getVTList(VT1, VT2);
4527 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4530 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4531 EVT VT1, EVT VT2, EVT VT3,
4532 const SDValue *Ops, unsigned NumOps) {
4533 SDVTList VTs = getVTList(VT1, VT2, VT3);
4534 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4537 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4538 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4539 const SDValue *Ops, unsigned NumOps) {
4540 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4541 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4544 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4547 SDVTList VTs = getVTList(VT1, VT2);
4548 SDValue Ops[] = { Op1 };
4549 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4552 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4554 SDValue Op1, SDValue Op2) {
4555 SDVTList VTs = getVTList(VT1, VT2);
4556 SDValue Ops[] = { Op1, Op2 };
4557 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4560 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4562 SDValue Op1, SDValue Op2,
4564 SDVTList VTs = getVTList(VT1, VT2);
4565 SDValue Ops[] = { Op1, Op2, Op3 };
4566 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4569 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4570 EVT VT1, EVT VT2, EVT VT3,
4571 SDValue Op1, SDValue Op2,
4573 SDVTList VTs = getVTList(VT1, VT2, VT3);
4574 SDValue Ops[] = { Op1, Op2, Op3 };
4575 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4578 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4579 SDVTList VTs, const SDValue *Ops,
4581 N = MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4582 // Reset the NodeID to -1.
4587 /// MorphNodeTo - This *mutates* the specified node to have the specified
4588 /// return type, opcode, and operands.
4590 /// Note that MorphNodeTo returns the resultant node. If there is already a
4591 /// node of the specified opcode and operands, it returns that node instead of
4592 /// the current one. Note that the DebugLoc need not be the same.
4594 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4595 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4596 /// node, and because it doesn't require CSE recalculation for any of
4597 /// the node's users.
4599 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4600 SDVTList VTs, const SDValue *Ops,
4602 // If an identical node already exists, use it.
4604 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4605 FoldingSetNodeID ID;
4606 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4607 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4611 if (!RemoveNodeFromCSEMaps(N))
4614 // Start the morphing.
4616 N->ValueList = VTs.VTs;
4617 N->NumValues = VTs.NumVTs;
4619 // Clear the operands list, updating used nodes to remove this from their
4620 // use list. Keep track of any operands that become dead as a result.
4621 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4622 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4624 SDNode *Used = Use.getNode();
4626 if (Used->use_empty())
4627 DeadNodeSet.insert(Used);
4630 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
4631 // Initialize the memory references information.
4632 MN->setMemRefs(0, 0);
4633 // If NumOps is larger than the # of operands we can have in a
4634 // MachineSDNode, reallocate the operand list.
4635 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
4636 if (MN->OperandsNeedDelete)
4637 delete[] MN->OperandList;
4638 if (NumOps > array_lengthof(MN->LocalOperands))
4639 // We're creating a final node that will live unmorphed for the
4640 // remainder of the current SelectionDAG iteration, so we can allocate
4641 // the operands directly out of a pool with no recycling metadata.
4642 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4645 MN->InitOperands(MN->LocalOperands, Ops, NumOps);
4646 MN->OperandsNeedDelete = false;
4648 MN->InitOperands(MN->OperandList, Ops, NumOps);
4650 // If NumOps is larger than the # of operands we currently have, reallocate
4651 // the operand list.
4652 if (NumOps > N->NumOperands) {
4653 if (N->OperandsNeedDelete)
4654 delete[] N->OperandList;
4655 N->InitOperands(new SDUse[NumOps], Ops, NumOps);
4656 N->OperandsNeedDelete = true;
4658 N->InitOperands(N->OperandList, Ops, NumOps);
4661 // Delete any nodes that are still dead after adding the uses for the
4663 if (!DeadNodeSet.empty()) {
4664 SmallVector<SDNode *, 16> DeadNodes;
4665 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4666 E = DeadNodeSet.end(); I != E; ++I)
4667 if ((*I)->use_empty())
4668 DeadNodes.push_back(*I);
4669 RemoveDeadNodes(DeadNodes);
4673 CSEMap.InsertNode(N, IP); // Memoize the new node.
4678 /// getMachineNode - These are used for target selectors to create a new node
4679 /// with specified return type(s), MachineInstr opcode, and operands.
4681 /// Note that getMachineNode returns the resultant node. If there is already a
4682 /// node of the specified opcode and operands, it returns that node instead of
4683 /// the current one.
4685 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
4686 SDVTList VTs = getVTList(VT);
4687 return getMachineNode(Opcode, dl, VTs, 0, 0);
4691 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
4692 SDVTList VTs = getVTList(VT);
4693 SDValue Ops[] = { Op1 };
4694 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4698 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4699 SDValue Op1, SDValue Op2) {
4700 SDVTList VTs = getVTList(VT);
4701 SDValue Ops[] = { Op1, Op2 };
4702 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4706 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4707 SDValue Op1, SDValue Op2, SDValue Op3) {
4708 SDVTList VTs = getVTList(VT);
4709 SDValue Ops[] = { Op1, Op2, Op3 };
4710 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4714 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4715 const SDValue *Ops, unsigned NumOps) {
4716 SDVTList VTs = getVTList(VT);
4717 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4721 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
4722 SDVTList VTs = getVTList(VT1, VT2);
4723 return getMachineNode(Opcode, dl, VTs, 0, 0);
4727 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4728 EVT VT1, EVT VT2, SDValue Op1) {
4729 SDVTList VTs = getVTList(VT1, VT2);
4730 SDValue Ops[] = { Op1 };
4731 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4735 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4736 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
4737 SDVTList VTs = getVTList(VT1, VT2);
4738 SDValue Ops[] = { Op1, Op2 };
4739 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4743 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4744 EVT VT1, EVT VT2, SDValue Op1,
4745 SDValue Op2, SDValue Op3) {
4746 SDVTList VTs = getVTList(VT1, VT2);
4747 SDValue Ops[] = { Op1, Op2, Op3 };
4748 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4752 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4754 const SDValue *Ops, unsigned NumOps) {
4755 SDVTList VTs = getVTList(VT1, VT2);
4756 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4760 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4761 EVT VT1, EVT VT2, EVT VT3,
4762 SDValue Op1, SDValue Op2) {
4763 SDVTList VTs = getVTList(VT1, VT2, VT3);
4764 SDValue Ops[] = { Op1, Op2 };
4765 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4769 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4770 EVT VT1, EVT VT2, EVT VT3,
4771 SDValue Op1, SDValue Op2, SDValue Op3) {
4772 SDVTList VTs = getVTList(VT1, VT2, VT3);
4773 SDValue Ops[] = { Op1, Op2, Op3 };
4774 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4778 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4779 EVT VT1, EVT VT2, EVT VT3,
4780 const SDValue *Ops, unsigned NumOps) {
4781 SDVTList VTs = getVTList(VT1, VT2, VT3);
4782 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4786 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4787 EVT VT2, EVT VT3, EVT VT4,
4788 const SDValue *Ops, unsigned NumOps) {
4789 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4790 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4794 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4795 const std::vector<EVT> &ResultTys,
4796 const SDValue *Ops, unsigned NumOps) {
4797 SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
4798 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4802 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
4803 const SDValue *Ops, unsigned NumOps) {
4804 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Flag;
4809 FoldingSetNodeID ID;
4810 AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
4812 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4813 return cast<MachineSDNode>(E);
4816 // Allocate a new MachineSDNode.
4817 N = NodeAllocator.Allocate<MachineSDNode>();
4818 new (N) MachineSDNode(~Opcode, DL, VTs);
4820 // Initialize the operands list.
4821 if (NumOps > array_lengthof(N->LocalOperands))
4822 // We're creating a final node that will live unmorphed for the
4823 // remainder of the current SelectionDAG iteration, so we can allocate
4824 // the operands directly out of a pool with no recycling metadata.
4825 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4828 N->InitOperands(N->LocalOperands, Ops, NumOps);
4829 N->OperandsNeedDelete = false;
4832 CSEMap.InsertNode(N, IP);
4834 AllNodes.push_back(N);
4841 /// getTargetExtractSubreg - A convenience function for creating
4842 /// TargetOpcode::EXTRACT_SUBREG nodes.
4844 SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
4846 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4847 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
4848 VT, Operand, SRIdxVal);
4849 return SDValue(Subreg, 0);
4852 /// getTargetInsertSubreg - A convenience function for creating
4853 /// TargetOpcode::INSERT_SUBREG nodes.
4855 SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
4856 SDValue Operand, SDValue Subreg) {
4857 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4858 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
4859 VT, Operand, Subreg, SRIdxVal);
4860 return SDValue(Result, 0);
4863 /// getNodeIfExists - Get the specified node if it's already available, or
4864 /// else return NULL.
4865 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4866 const SDValue *Ops, unsigned NumOps) {
4867 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4868 FoldingSetNodeID ID;
4869 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4871 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4879 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
4880 /// pointed to by a use iterator is deleted, increment the use iterator
4881 /// so that it doesn't dangle.
4883 /// This class also manages a "downlink" DAGUpdateListener, to forward
4884 /// messages to ReplaceAllUsesWith's callers.
4886 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
4887 SelectionDAG::DAGUpdateListener *DownLink;
4888 SDNode::use_iterator &UI;
4889 SDNode::use_iterator &UE;
4891 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4892 // Increment the iterator as needed.
4893 while (UI != UE && N == *UI)
4896 // Then forward the message.
4897 if (DownLink) DownLink->NodeDeleted(N, E);
4900 virtual void NodeUpdated(SDNode *N) {
4901 // Just forward the message.
4902 if (DownLink) DownLink->NodeUpdated(N);
4906 RAUWUpdateListener(SelectionDAG::DAGUpdateListener *dl,
4907 SDNode::use_iterator &ui,
4908 SDNode::use_iterator &ue)
4909 : DownLink(dl), UI(ui), UE(ue) {}
4914 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4915 /// This can cause recursive merging of nodes in the DAG.
4917 /// This version assumes From has a single result value.
4919 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4920 DAGUpdateListener *UpdateListener) {
4921 SDNode *From = FromN.getNode();
4922 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4923 "Cannot replace with this method!");
4924 assert(From != To.getNode() && "Cannot replace uses of with self");
4926 // Iterate over all the existing uses of From. New uses will be added
4927 // to the beginning of the use list, which we avoid visiting.
4928 // This specifically avoids visiting uses of From that arise while the
4929 // replacement is happening, because any such uses would be the result
4930 // of CSE: If an existing node looks like From after one of its operands
4931 // is replaced by To, we don't want to replace of all its users with To
4932 // too. See PR3018 for more info.
4933 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4934 RAUWUpdateListener Listener(UpdateListener, UI, UE);
4938 // This node is about to morph, remove its old self from the CSE maps.
4939 RemoveNodeFromCSEMaps(User);
4941 // A user can appear in a use list multiple times, and when this
4942 // happens the uses are usually next to each other in the list.
4943 // To help reduce the number of CSE recomputations, process all
4944 // the uses of this user that we can find this way.
4946 SDUse &Use = UI.getUse();
4949 } while (UI != UE && *UI == User);
4951 // Now that we have modified User, add it back to the CSE maps. If it
4952 // already exists there, recursively merge the results together.
4953 AddModifiedNodeToCSEMaps(User, &Listener);
4957 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4958 /// This can cause recursive merging of nodes in the DAG.
4960 /// This version assumes that for each value of From, there is a
4961 /// corresponding value in To in the same position with the same type.
4963 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4964 DAGUpdateListener *UpdateListener) {
4966 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
4967 assert((!From->hasAnyUseOfValue(i) ||
4968 From->getValueType(i) == To->getValueType(i)) &&
4969 "Cannot use this version of ReplaceAllUsesWith!");
4972 // Handle the trivial case.
4976 // Iterate over just the existing users of From. See the comments in
4977 // the ReplaceAllUsesWith above.
4978 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4979 RAUWUpdateListener Listener(UpdateListener, UI, UE);
4983 // This node is about to morph, remove its old self from the CSE maps.
4984 RemoveNodeFromCSEMaps(User);
4986 // A user can appear in a use list multiple times, and when this
4987 // happens the uses are usually next to each other in the list.
4988 // To help reduce the number of CSE recomputations, process all
4989 // the uses of this user that we can find this way.
4991 SDUse &Use = UI.getUse();
4994 } while (UI != UE && *UI == User);
4996 // Now that we have modified User, add it back to the CSE maps. If it
4997 // already exists there, recursively merge the results together.
4998 AddModifiedNodeToCSEMaps(User, &Listener);
5002 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5003 /// This can cause recursive merging of nodes in the DAG.
5005 /// This version can replace From with any result values. To must match the
5006 /// number and types of values returned by From.
5007 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
5009 DAGUpdateListener *UpdateListener) {
5010 if (From->getNumValues() == 1) // Handle the simple case efficiently.
5011 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
5013 // Iterate over just the existing users of From. See the comments in
5014 // the ReplaceAllUsesWith above.
5015 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5016 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5020 // This node is about to morph, remove its old self from the CSE maps.
5021 RemoveNodeFromCSEMaps(User);
5023 // A user can appear in a use list multiple times, and when this
5024 // happens the uses are usually next to each other in the list.
5025 // To help reduce the number of CSE recomputations, process all
5026 // the uses of this user that we can find this way.
5028 SDUse &Use = UI.getUse();
5029 const SDValue &ToOp = To[Use.getResNo()];
5032 } while (UI != UE && *UI == User);
5034 // Now that we have modified User, add it back to the CSE maps. If it
5035 // already exists there, recursively merge the results together.
5036 AddModifiedNodeToCSEMaps(User, &Listener);
5040 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5041 /// uses of other values produced by From.getNode() alone. The Deleted
5042 /// vector is handled the same way as for ReplaceAllUsesWith.
5043 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
5044 DAGUpdateListener *UpdateListener){
5045 // Handle the really simple, really trivial case efficiently.
5046 if (From == To) return;
5048 // Handle the simple, trivial, case efficiently.
5049 if (From.getNode()->getNumValues() == 1) {
5050 ReplaceAllUsesWith(From, To, UpdateListener);
5054 // Iterate over just the existing users of From. See the comments in
5055 // the ReplaceAllUsesWith above.
5056 SDNode::use_iterator UI = From.getNode()->use_begin(),
5057 UE = From.getNode()->use_end();
5058 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5061 bool UserRemovedFromCSEMaps = false;
5063 // A user can appear in a use list multiple times, and when this
5064 // happens the uses are usually next to each other in the list.
5065 // To help reduce the number of CSE recomputations, process all
5066 // the uses of this user that we can find this way.
5068 SDUse &Use = UI.getUse();
5070 // Skip uses of different values from the same node.
5071 if (Use.getResNo() != From.getResNo()) {
5076 // If this node hasn't been modified yet, it's still in the CSE maps,
5077 // so remove its old self from the CSE maps.
5078 if (!UserRemovedFromCSEMaps) {
5079 RemoveNodeFromCSEMaps(User);
5080 UserRemovedFromCSEMaps = true;
5085 } while (UI != UE && *UI == User);
5087 // We are iterating over all uses of the From node, so if a use
5088 // doesn't use the specific value, no changes are made.
5089 if (!UserRemovedFromCSEMaps)
5092 // Now that we have modified User, add it back to the CSE maps. If it
5093 // already exists there, recursively merge the results together.
5094 AddModifiedNodeToCSEMaps(User, &Listener);
5099 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5100 /// to record information about a use.
5107 /// operator< - Sort Memos by User.
5108 bool operator<(const UseMemo &L, const UseMemo &R) {
5109 return (intptr_t)L.User < (intptr_t)R.User;
5113 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5114 /// uses of other values produced by From.getNode() alone. The same value
5115 /// may appear in both the From and To list. The Deleted vector is
5116 /// handled the same way as for ReplaceAllUsesWith.
5117 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5120 DAGUpdateListener *UpdateListener){
5121 // Handle the simple, trivial case efficiently.
5123 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5125 // Read up all the uses and make records of them. This helps
5126 // processing new uses that are introduced during the
5127 // replacement process.
5128 SmallVector<UseMemo, 4> Uses;
5129 for (unsigned i = 0; i != Num; ++i) {
5130 unsigned FromResNo = From[i].getResNo();
5131 SDNode *FromNode = From[i].getNode();
5132 for (SDNode::use_iterator UI = FromNode->use_begin(),
5133 E = FromNode->use_end(); UI != E; ++UI) {
5134 SDUse &Use = UI.getUse();
5135 if (Use.getResNo() == FromResNo) {
5136 UseMemo Memo = { *UI, i, &Use };
5137 Uses.push_back(Memo);
5142 // Sort the uses, so that all the uses from a given User are together.
5143 std::sort(Uses.begin(), Uses.end());
5145 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5146 UseIndex != UseIndexEnd; ) {
5147 // We know that this user uses some value of From. If it is the right
5148 // value, update it.
5149 SDNode *User = Uses[UseIndex].User;
5151 // This node is about to morph, remove its old self from the CSE maps.
5152 RemoveNodeFromCSEMaps(User);
5154 // The Uses array is sorted, so all the uses for a given User
5155 // are next to each other in the list.
5156 // To help reduce the number of CSE recomputations, process all
5157 // the uses of this user that we can find this way.
5159 unsigned i = Uses[UseIndex].Index;
5160 SDUse &Use = *Uses[UseIndex].Use;
5164 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5166 // Now that we have modified User, add it back to the CSE maps. If it
5167 // already exists there, recursively merge the results together.
5168 AddModifiedNodeToCSEMaps(User, UpdateListener);
5172 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5173 /// based on their topological order. It returns the maximum id and a vector
5174 /// of the SDNodes* in assigned order by reference.
5175 unsigned SelectionDAG::AssignTopologicalOrder() {
5177 unsigned DAGSize = 0;
5179 // SortedPos tracks the progress of the algorithm. Nodes before it are
5180 // sorted, nodes after it are unsorted. When the algorithm completes
5181 // it is at the end of the list.
5182 allnodes_iterator SortedPos = allnodes_begin();
5184 // Visit all the nodes. Move nodes with no operands to the front of
5185 // the list immediately. Annotate nodes that do have operands with their
5186 // operand count. Before we do this, the Node Id fields of the nodes
5187 // may contain arbitrary values. After, the Node Id fields for nodes
5188 // before SortedPos will contain the topological sort index, and the
5189 // Node Id fields for nodes At SortedPos and after will contain the
5190 // count of outstanding operands.
5191 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5194 unsigned Degree = N->getNumOperands();
5196 // A node with no uses, add it to the result array immediately.
5197 N->setNodeId(DAGSize++);
5198 allnodes_iterator Q = N;
5200 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5201 assert(SortedPos != AllNodes.end() && "Overran node list");
5204 // Temporarily use the Node Id as scratch space for the degree count.
5205 N->setNodeId(Degree);
5209 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5210 // such that by the time the end is reached all nodes will be sorted.
5211 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5214 // N is in sorted position, so all its uses have one less operand
5215 // that needs to be sorted.
5216 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5219 unsigned Degree = P->getNodeId();
5220 assert(Degree != 0 && "Invalid node degree");
5223 // All of P's operands are sorted, so P may sorted now.
5224 P->setNodeId(DAGSize++);
5226 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5227 assert(SortedPos != AllNodes.end() && "Overran node list");
5230 // Update P's outstanding operand count.
5231 P->setNodeId(Degree);
5234 if (I == SortedPos) {
5237 dbgs() << "Overran sorted position:\n";
5240 llvm_unreachable(0);
5244 assert(SortedPos == AllNodes.end() &&
5245 "Topological sort incomplete!");
5246 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5247 "First node in topological sort is not the entry token!");
5248 assert(AllNodes.front().getNodeId() == 0 &&
5249 "First node in topological sort has non-zero id!");
5250 assert(AllNodes.front().getNumOperands() == 0 &&
5251 "First node in topological sort has operands!");
5252 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5253 "Last node in topologic sort has unexpected id!");
5254 assert(AllNodes.back().use_empty() &&
5255 "Last node in topologic sort has users!");
5256 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5260 /// AssignOrdering - Assign an order to the SDNode.
5261 void SelectionDAG::AssignOrdering(const SDNode *SD, unsigned Order) {
5262 assert(SD && "Trying to assign an order to a null node!");
5263 Ordering->add(SD, Order);
5266 /// GetOrdering - Get the order for the SDNode.
5267 unsigned SelectionDAG::GetOrdering(const SDNode *SD) const {
5268 assert(SD && "Trying to get the order of a null node!");
5269 return Ordering->getOrder(SD);
5272 /// AssignDbgInfo - Assign debug info to the SDNode.
5273 void SelectionDAG::AssignDbgInfo(SDNode* SD, SDDbgValue* db) {
5274 assert(SD && "Trying to assign dbg info to a null node!");
5275 DbgInfo->add(SD, db);
5276 SD->setHasDebugValue(true);
5279 /// RememberDbgInfo - Remember debug info which is not assigned to an SDNode.
5280 void SelectionDAG::RememberDbgInfo(SDDbgValue* db) {
5284 /// GetDbgInfo - Get the debug info, if any, for the SDNode.
5285 SDDbgValue* SelectionDAG::GetDbgInfo(const SDNode *SD) {
5286 assert(SD && "Trying to get the order of a null node!");
5287 if (SD->getHasDebugValue())
5288 return DbgInfo->getSDDbgValue(SD);
5292 //===----------------------------------------------------------------------===//
5294 //===----------------------------------------------------------------------===//
5296 HandleSDNode::~HandleSDNode() {
5300 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA,
5301 EVT VT, int64_t o, unsigned char TF)
5302 : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)),
5303 Offset(o), TargetFlags(TF) {
5304 TheGlobal = const_cast<GlobalValue*>(GA);
5307 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
5308 MachineMemOperand *mmo)
5309 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5310 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5311 MMO->isNonTemporal());
5312 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5313 assert(isNonTemporal() == MMO->isNonTemporal() &&
5314 "Non-temporal encoding error!");
5315 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5318 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5319 const SDValue *Ops, unsigned NumOps, EVT memvt,
5320 MachineMemOperand *mmo)
5321 : SDNode(Opc, dl, VTs, Ops, NumOps),
5322 MemoryVT(memvt), MMO(mmo) {
5323 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5324 MMO->isNonTemporal());
5325 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5326 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5329 /// Profile - Gather unique data for the node.
5331 void SDNode::Profile(FoldingSetNodeID &ID) const {
5332 AddNodeIDNode(ID, this);
5337 std::vector<EVT> VTs;
5340 VTs.reserve(MVT::LAST_VALUETYPE);
5341 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5342 VTs.push_back(MVT((MVT::SimpleValueType)i));
5347 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5348 static ManagedStatic<EVTArray> SimpleVTArray;
5349 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5351 /// getValueTypeList - Return a pointer to the specified value type.
5353 const EVT *SDNode::getValueTypeList(EVT VT) {
5354 if (VT.isExtended()) {
5355 sys::SmartScopedLock<true> Lock(*VTMutex);
5356 return &(*EVTs->insert(VT).first);
5358 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5362 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5363 /// indicated value. This method ignores uses of other values defined by this
5365 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5366 assert(Value < getNumValues() && "Bad value!");
5368 // TODO: Only iterate over uses of a given value of the node
5369 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5370 if (UI.getUse().getResNo() == Value) {
5377 // Found exactly the right number of uses?
5382 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5383 /// value. This method ignores uses of other values defined by this operation.
5384 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5385 assert(Value < getNumValues() && "Bad value!");
5387 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5388 if (UI.getUse().getResNo() == Value)
5395 /// isOnlyUserOf - Return true if this node is the only use of N.
5397 bool SDNode::isOnlyUserOf(SDNode *N) const {
5399 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5410 /// isOperand - Return true if this node is an operand of N.
5412 bool SDValue::isOperandOf(SDNode *N) const {
5413 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5414 if (*this == N->getOperand(i))
5419 bool SDNode::isOperandOf(SDNode *N) const {
5420 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5421 if (this == N->OperandList[i].getNode())
5426 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5427 /// be a chain) reaches the specified operand without crossing any
5428 /// side-effecting instructions. In practice, this looks through token
5429 /// factors and non-volatile loads. In order to remain efficient, this only
5430 /// looks a couple of nodes in, it does not do an exhaustive search.
5431 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5432 unsigned Depth) const {
5433 if (*this == Dest) return true;
5435 // Don't search too deeply, we just want to be able to see through
5436 // TokenFactor's etc.
5437 if (Depth == 0) return false;
5439 // If this is a token factor, all inputs to the TF happen in parallel. If any
5440 // of the operands of the TF reach dest, then we can do the xform.
5441 if (getOpcode() == ISD::TokenFactor) {
5442 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5443 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5448 // Loads don't have side effects, look through them.
5449 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5450 if (!Ld->isVolatile())
5451 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5456 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5457 /// is either an operand of N or it can be reached by traversing up the operands.
5458 /// NOTE: this is an expensive method. Use it carefully.
5459 bool SDNode::isPredecessorOf(SDNode *N) const {
5460 SmallPtrSet<SDNode *, 32> Visited;
5461 SmallVector<SDNode *, 16> Worklist;
5462 Worklist.push_back(N);
5465 N = Worklist.pop_back_val();
5466 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5467 SDNode *Op = N->getOperand(i).getNode();
5470 if (Visited.insert(Op))
5471 Worklist.push_back(Op);
5473 } while (!Worklist.empty());
5478 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5479 assert(Num < NumOperands && "Invalid child # of SDNode!");
5480 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5483 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5484 switch (getOpcode()) {
5486 if (getOpcode() < ISD::BUILTIN_OP_END)
5487 return "<<Unknown DAG Node>>";
5488 if (isMachineOpcode()) {
5490 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5491 if (getMachineOpcode() < TII->getNumOpcodes())
5492 return TII->get(getMachineOpcode()).getName();
5493 return "<<Unknown Machine Node #" + utostr(getOpcode()) + ">>";
5496 const TargetLowering &TLI = G->getTargetLoweringInfo();
5497 const char *Name = TLI.getTargetNodeName(getOpcode());
5498 if (Name) return Name;
5499 return "<<Unknown Target Node #" + utostr(getOpcode()) + ">>";
5501 return "<<Unknown Node #" + utostr(getOpcode()) + ">>";
5504 case ISD::DELETED_NODE:
5505 return "<<Deleted Node!>>";
5507 case ISD::PREFETCH: return "Prefetch";
5508 case ISD::MEMBARRIER: return "MemBarrier";
5509 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5510 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5511 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5512 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5513 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5514 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5515 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5516 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5517 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5518 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5519 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5520 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5521 case ISD::PCMARKER: return "PCMarker";
5522 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5523 case ISD::SRCVALUE: return "SrcValue";
5524 case ISD::EntryToken: return "EntryToken";
5525 case ISD::TokenFactor: return "TokenFactor";
5526 case ISD::AssertSext: return "AssertSext";
5527 case ISD::AssertZext: return "AssertZext";
5529 case ISD::BasicBlock: return "BasicBlock";
5530 case ISD::VALUETYPE: return "ValueType";
5531 case ISD::Register: return "Register";
5533 case ISD::Constant: return "Constant";
5534 case ISD::ConstantFP: return "ConstantFP";
5535 case ISD::GlobalAddress: return "GlobalAddress";
5536 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5537 case ISD::FrameIndex: return "FrameIndex";
5538 case ISD::JumpTable: return "JumpTable";
5539 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5540 case ISD::RETURNADDR: return "RETURNADDR";
5541 case ISD::FRAMEADDR: return "FRAMEADDR";
5542 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5543 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5544 case ISD::LSDAADDR: return "LSDAADDR";
5545 case ISD::EHSELECTION: return "EHSELECTION";
5546 case ISD::EH_RETURN: return "EH_RETURN";
5547 case ISD::ConstantPool: return "ConstantPool";
5548 case ISD::ExternalSymbol: return "ExternalSymbol";
5549 case ISD::BlockAddress: return "BlockAddress";
5550 case ISD::INTRINSIC_WO_CHAIN:
5551 case ISD::INTRINSIC_VOID:
5552 case ISD::INTRINSIC_W_CHAIN: {
5553 unsigned OpNo = getOpcode() == ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
5554 unsigned IID = cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue();
5555 if (IID < Intrinsic::num_intrinsics)
5556 return Intrinsic::getName((Intrinsic::ID)IID);
5557 else if (const TargetIntrinsicInfo *TII = G->getTarget().getIntrinsicInfo())
5558 return TII->getName(IID);
5559 llvm_unreachable("Invalid intrinsic ID");
5562 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5563 case ISD::TargetConstant: return "TargetConstant";
5564 case ISD::TargetConstantFP:return "TargetConstantFP";
5565 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5566 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5567 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5568 case ISD::TargetJumpTable: return "TargetJumpTable";
5569 case ISD::TargetConstantPool: return "TargetConstantPool";
5570 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5571 case ISD::TargetBlockAddress: return "TargetBlockAddress";
5573 case ISD::CopyToReg: return "CopyToReg";
5574 case ISD::CopyFromReg: return "CopyFromReg";
5575 case ISD::UNDEF: return "undef";
5576 case ISD::MERGE_VALUES: return "merge_values";
5577 case ISD::INLINEASM: return "inlineasm";
5578 case ISD::EH_LABEL: return "eh_label";
5579 case ISD::HANDLENODE: return "handlenode";
5582 case ISD::FABS: return "fabs";
5583 case ISD::FNEG: return "fneg";
5584 case ISD::FSQRT: return "fsqrt";
5585 case ISD::FSIN: return "fsin";
5586 case ISD::FCOS: return "fcos";
5587 case ISD::FPOWI: return "fpowi";
5588 case ISD::FPOW: return "fpow";
5589 case ISD::FTRUNC: return "ftrunc";
5590 case ISD::FFLOOR: return "ffloor";
5591 case ISD::FCEIL: return "fceil";
5592 case ISD::FRINT: return "frint";
5593 case ISD::FNEARBYINT: return "fnearbyint";
5596 case ISD::ADD: return "add";
5597 case ISD::SUB: return "sub";
5598 case ISD::MUL: return "mul";
5599 case ISD::MULHU: return "mulhu";
5600 case ISD::MULHS: return "mulhs";
5601 case ISD::SDIV: return "sdiv";
5602 case ISD::UDIV: return "udiv";
5603 case ISD::SREM: return "srem";
5604 case ISD::UREM: return "urem";
5605 case ISD::SMUL_LOHI: return "smul_lohi";
5606 case ISD::UMUL_LOHI: return "umul_lohi";
5607 case ISD::SDIVREM: return "sdivrem";
5608 case ISD::UDIVREM: return "udivrem";
5609 case ISD::AND: return "and";
5610 case ISD::OR: return "or";
5611 case ISD::XOR: return "xor";
5612 case ISD::SHL: return "shl";
5613 case ISD::SRA: return "sra";
5614 case ISD::SRL: return "srl";
5615 case ISD::ROTL: return "rotl";
5616 case ISD::ROTR: return "rotr";
5617 case ISD::FADD: return "fadd";
5618 case ISD::FSUB: return "fsub";
5619 case ISD::FMUL: return "fmul";
5620 case ISD::FDIV: return "fdiv";
5621 case ISD::FREM: return "frem";
5622 case ISD::FCOPYSIGN: return "fcopysign";
5623 case ISD::FGETSIGN: return "fgetsign";
5625 case ISD::SETCC: return "setcc";
5626 case ISD::VSETCC: return "vsetcc";
5627 case ISD::SELECT: return "select";
5628 case ISD::SELECT_CC: return "select_cc";
5629 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5630 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5631 case ISD::CONCAT_VECTORS: return "concat_vectors";
5632 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5633 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5634 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5635 case ISD::CARRY_FALSE: return "carry_false";
5636 case ISD::ADDC: return "addc";
5637 case ISD::ADDE: return "adde";
5638 case ISD::SADDO: return "saddo";
5639 case ISD::UADDO: return "uaddo";
5640 case ISD::SSUBO: return "ssubo";
5641 case ISD::USUBO: return "usubo";
5642 case ISD::SMULO: return "smulo";
5643 case ISD::UMULO: return "umulo";
5644 case ISD::SUBC: return "subc";
5645 case ISD::SUBE: return "sube";
5646 case ISD::SHL_PARTS: return "shl_parts";
5647 case ISD::SRA_PARTS: return "sra_parts";
5648 case ISD::SRL_PARTS: return "srl_parts";
5650 // Conversion operators.
5651 case ISD::SIGN_EXTEND: return "sign_extend";
5652 case ISD::ZERO_EXTEND: return "zero_extend";
5653 case ISD::ANY_EXTEND: return "any_extend";
5654 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5655 case ISD::TRUNCATE: return "truncate";
5656 case ISD::FP_ROUND: return "fp_round";
5657 case ISD::FLT_ROUNDS_: return "flt_rounds";
5658 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5659 case ISD::FP_EXTEND: return "fp_extend";
5661 case ISD::SINT_TO_FP: return "sint_to_fp";
5662 case ISD::UINT_TO_FP: return "uint_to_fp";
5663 case ISD::FP_TO_SINT: return "fp_to_sint";
5664 case ISD::FP_TO_UINT: return "fp_to_uint";
5665 case ISD::BIT_CONVERT: return "bit_convert";
5666 case ISD::FP16_TO_FP32: return "fp16_to_fp32";
5667 case ISD::FP32_TO_FP16: return "fp32_to_fp16";
5669 case ISD::CONVERT_RNDSAT: {
5670 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5671 default: llvm_unreachable("Unknown cvt code!");
5672 case ISD::CVT_FF: return "cvt_ff";
5673 case ISD::CVT_FS: return "cvt_fs";
5674 case ISD::CVT_FU: return "cvt_fu";
5675 case ISD::CVT_SF: return "cvt_sf";
5676 case ISD::CVT_UF: return "cvt_uf";
5677 case ISD::CVT_SS: return "cvt_ss";
5678 case ISD::CVT_SU: return "cvt_su";
5679 case ISD::CVT_US: return "cvt_us";
5680 case ISD::CVT_UU: return "cvt_uu";
5684 // Control flow instructions
5685 case ISD::BR: return "br";
5686 case ISD::BRIND: return "brind";
5687 case ISD::BR_JT: return "br_jt";
5688 case ISD::BRCOND: return "brcond";
5689 case ISD::BR_CC: return "br_cc";
5690 case ISD::CALLSEQ_START: return "callseq_start";
5691 case ISD::CALLSEQ_END: return "callseq_end";
5694 case ISD::LOAD: return "load";
5695 case ISD::STORE: return "store";
5696 case ISD::VAARG: return "vaarg";
5697 case ISD::VACOPY: return "vacopy";
5698 case ISD::VAEND: return "vaend";
5699 case ISD::VASTART: return "vastart";
5700 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5701 case ISD::EXTRACT_ELEMENT: return "extract_element";
5702 case ISD::BUILD_PAIR: return "build_pair";
5703 case ISD::STACKSAVE: return "stacksave";
5704 case ISD::STACKRESTORE: return "stackrestore";
5705 case ISD::TRAP: return "trap";
5708 case ISD::BSWAP: return "bswap";
5709 case ISD::CTPOP: return "ctpop";
5710 case ISD::CTTZ: return "cttz";
5711 case ISD::CTLZ: return "ctlz";
5714 case ISD::TRAMPOLINE: return "trampoline";
5717 switch (cast<CondCodeSDNode>(this)->get()) {
5718 default: llvm_unreachable("Unknown setcc condition!");
5719 case ISD::SETOEQ: return "setoeq";
5720 case ISD::SETOGT: return "setogt";
5721 case ISD::SETOGE: return "setoge";
5722 case ISD::SETOLT: return "setolt";
5723 case ISD::SETOLE: return "setole";
5724 case ISD::SETONE: return "setone";
5726 case ISD::SETO: return "seto";
5727 case ISD::SETUO: return "setuo";
5728 case ISD::SETUEQ: return "setue";
5729 case ISD::SETUGT: return "setugt";
5730 case ISD::SETUGE: return "setuge";
5731 case ISD::SETULT: return "setult";
5732 case ISD::SETULE: return "setule";
5733 case ISD::SETUNE: return "setune";
5735 case ISD::SETEQ: return "seteq";
5736 case ISD::SETGT: return "setgt";
5737 case ISD::SETGE: return "setge";
5738 case ISD::SETLT: return "setlt";
5739 case ISD::SETLE: return "setle";
5740 case ISD::SETNE: return "setne";
5745 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5754 return "<post-inc>";
5756 return "<post-dec>";
5760 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5761 std::string S = "< ";
5775 if (getByValAlign())
5776 S += "byval-align:" + utostr(getByValAlign()) + " ";
5778 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5780 S += "byval-size:" + utostr(getByValSize()) + " ";
5784 void SDNode::dump() const { dump(0); }
5785 void SDNode::dump(const SelectionDAG *G) const {
5789 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
5790 OS << (void*)this << ": ";
5792 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5794 if (getValueType(i) == MVT::Other)
5797 OS << getValueType(i).getEVTString();
5799 OS << " = " << getOperationName(G);
5802 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
5803 if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
5804 if (!MN->memoperands_empty()) {
5807 for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
5808 e = MN->memoperands_end(); i != e; ++i) {
5815 } else if (const ShuffleVectorSDNode *SVN =
5816 dyn_cast<ShuffleVectorSDNode>(this)) {
5818 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
5819 int Idx = SVN->getMaskElt(i);
5827 } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5828 OS << '<' << CSDN->getAPIntValue() << '>';
5829 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5830 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5831 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5832 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5833 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5836 CSDN->getValueAPF().bitcastToAPInt().dump();
5839 } else if (const GlobalAddressSDNode *GADN =
5840 dyn_cast<GlobalAddressSDNode>(this)) {
5841 int64_t offset = GADN->getOffset();
5843 WriteAsOperand(OS, GADN->getGlobal());
5846 OS << " + " << offset;
5848 OS << " " << offset;
5849 if (unsigned int TF = GADN->getTargetFlags())
5850 OS << " [TF=" << TF << ']';
5851 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5852 OS << "<" << FIDN->getIndex() << ">";
5853 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5854 OS << "<" << JTDN->getIndex() << ">";
5855 if (unsigned int TF = JTDN->getTargetFlags())
5856 OS << " [TF=" << TF << ']';
5857 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5858 int offset = CP->getOffset();
5859 if (CP->isMachineConstantPoolEntry())
5860 OS << "<" << *CP->getMachineCPVal() << ">";
5862 OS << "<" << *CP->getConstVal() << ">";
5864 OS << " + " << offset;
5866 OS << " " << offset;
5867 if (unsigned int TF = CP->getTargetFlags())
5868 OS << " [TF=" << TF << ']';
5869 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5871 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5873 OS << LBB->getName() << " ";
5874 OS << (const void*)BBDN->getBasicBlock() << ">";
5875 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5876 if (G && R->getReg() &&
5877 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5878 OS << " %" << G->getTarget().getRegisterInfo()->getName(R->getReg());
5880 OS << " %reg" << R->getReg();
5882 } else if (const ExternalSymbolSDNode *ES =
5883 dyn_cast<ExternalSymbolSDNode>(this)) {
5884 OS << "'" << ES->getSymbol() << "'";
5885 if (unsigned int TF = ES->getTargetFlags())
5886 OS << " [TF=" << TF << ']';
5887 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5889 OS << "<" << M->getValue() << ">";
5892 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5893 OS << ":" << N->getVT().getEVTString();
5895 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5896 OS << "<" << *LD->getMemOperand();
5899 switch (LD->getExtensionType()) {
5900 default: doExt = false; break;
5901 case ISD::EXTLOAD: OS << ", anyext"; break;
5902 case ISD::SEXTLOAD: OS << ", sext"; break;
5903 case ISD::ZEXTLOAD: OS << ", zext"; break;
5906 OS << " from " << LD->getMemoryVT().getEVTString();
5908 const char *AM = getIndexedModeName(LD->getAddressingMode());
5913 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5914 OS << "<" << *ST->getMemOperand();
5916 if (ST->isTruncatingStore())
5917 OS << ", trunc to " << ST->getMemoryVT().getEVTString();
5919 const char *AM = getIndexedModeName(ST->getAddressingMode());
5924 } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
5925 OS << "<" << *M->getMemOperand() << ">";
5926 } else if (const BlockAddressSDNode *BA =
5927 dyn_cast<BlockAddressSDNode>(this)) {
5929 WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
5931 WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
5933 if (unsigned int TF = BA->getTargetFlags())
5934 OS << " [TF=" << TF << ']';
5938 if (unsigned Order = G->GetOrdering(this))
5939 OS << " [ORD=" << Order << ']';
5941 if (getNodeId() != -1)
5942 OS << " [ID=" << getNodeId() << ']';
5945 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5947 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5948 if (i) OS << ", "; else OS << " ";
5949 OS << (void*)getOperand(i).getNode();
5950 if (unsigned RN = getOperand(i).getResNo())
5953 print_details(OS, G);
5956 static void printrWithDepthHelper(raw_ostream &OS, const SDNode *N,
5957 const SelectionDAG *G, unsigned depth,
5970 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5972 printrWithDepthHelper(OS, N->getOperand(i).getNode(), G, depth-1, indent+2);
5976 void SDNode::printrWithDepth(raw_ostream &OS, const SelectionDAG *G,
5977 unsigned depth) const {
5978 printrWithDepthHelper(OS, this, G, depth, 0);
5981 void SDNode::printrFull(raw_ostream &OS, const SelectionDAG *G) const {
5982 // Don't print impossibly deep things.
5983 printrWithDepth(OS, G, 100);
5986 void SDNode::dumprWithDepth(const SelectionDAG *G, unsigned depth) const {
5987 printrWithDepth(dbgs(), G, depth);
5990 void SDNode::dumprFull(const SelectionDAG *G) const {
5991 // Don't print impossibly deep things.
5992 dumprWithDepth(G, 100);
5995 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5996 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5997 if (N->getOperand(i).getNode()->hasOneUse())
5998 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
6000 dbgs() << "\n" << std::string(indent+2, ' ')
6001 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
6005 dbgs().indent(indent);
6009 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6010 assert(N->getNumValues() == 1 &&
6011 "Can't unroll a vector with multiple results!");
6013 EVT VT = N->getValueType(0);
6014 unsigned NE = VT.getVectorNumElements();
6015 EVT EltVT = VT.getVectorElementType();
6016 DebugLoc dl = N->getDebugLoc();
6018 SmallVector<SDValue, 8> Scalars;
6019 SmallVector<SDValue, 4> Operands(N->getNumOperands());
6021 // If ResNE is 0, fully unroll the vector op.
6024 else if (NE > ResNE)
6028 for (i= 0; i != NE; ++i) {
6029 for (unsigned j = 0; j != N->getNumOperands(); ++j) {
6030 SDValue Operand = N->getOperand(j);
6031 EVT OperandVT = Operand.getValueType();
6032 if (OperandVT.isVector()) {
6033 // A vector operand; extract a single element.
6034 EVT OperandEltVT = OperandVT.getVectorElementType();
6035 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6038 getConstant(i, MVT::i32));
6040 // A scalar operand; just use it as is.
6041 Operands[j] = Operand;
6045 switch (N->getOpcode()) {
6047 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6048 &Operands[0], Operands.size()));
6055 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6056 getShiftAmountOperand(Operands[1])));
6058 case ISD::SIGN_EXTEND_INREG:
6059 case ISD::FP_ROUND_INREG: {
6060 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6061 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6063 getValueType(ExtVT)));
6068 for (; i < ResNE; ++i)
6069 Scalars.push_back(getUNDEF(EltVT));
6071 return getNode(ISD::BUILD_VECTOR, dl,
6072 EVT::getVectorVT(*getContext(), EltVT, ResNE),
6073 &Scalars[0], Scalars.size());
6077 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6078 /// location that is 'Dist' units away from the location that the 'Base' load
6079 /// is loading from.
6080 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6081 unsigned Bytes, int Dist) const {
6082 if (LD->getChain() != Base->getChain())
6084 EVT VT = LD->getValueType(0);
6085 if (VT.getSizeInBits() / 8 != Bytes)
6088 SDValue Loc = LD->getOperand(1);
6089 SDValue BaseLoc = Base->getOperand(1);
6090 if (Loc.getOpcode() == ISD::FrameIndex) {
6091 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6093 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6094 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6095 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6096 int FS = MFI->getObjectSize(FI);
6097 int BFS = MFI->getObjectSize(BFI);
6098 if (FS != BFS || FS != (int)Bytes) return false;
6099 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6101 if (Loc.getOpcode() == ISD::ADD && Loc.getOperand(0) == BaseLoc) {
6102 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Loc.getOperand(1));
6103 if (V && (V->getSExtValue() == Dist*Bytes))
6107 GlobalValue *GV1 = NULL;
6108 GlobalValue *GV2 = NULL;
6109 int64_t Offset1 = 0;
6110 int64_t Offset2 = 0;
6111 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6112 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6113 if (isGA1 && isGA2 && GV1 == GV2)
6114 return Offset1 == (Offset2 + Dist*Bytes);
6119 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6120 /// it cannot be inferred.
6121 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6122 // If this is a GlobalAddress + cst, return the alignment.
6124 int64_t GVOffset = 0;
6125 if (TLI.isGAPlusOffset(Ptr.getNode(), GV, GVOffset))
6126 return MinAlign(GV->getAlignment(), GVOffset);
6128 // If this is a direct reference to a stack slot, use information about the
6129 // stack slot's alignment.
6130 int FrameIdx = 1 << 31;
6131 int64_t FrameOffset = 0;
6132 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6133 FrameIdx = FI->getIndex();
6134 } else if (Ptr.getOpcode() == ISD::ADD &&
6135 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
6136 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6137 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6138 FrameOffset = Ptr.getConstantOperandVal(1);
6141 if (FrameIdx != (1 << 31)) {
6142 // FIXME: Handle FI+CST.
6143 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6144 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6146 if (MFI.isFixedObjectIndex(FrameIdx)) {
6147 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
6149 // The alignment of the frame index can be determined from its offset from
6150 // the incoming frame position. If the frame object is at offset 32 and
6151 // the stack is guaranteed to be 16-byte aligned, then we know that the
6152 // object is 16-byte aligned.
6153 unsigned StackAlign = getTarget().getFrameInfo()->getStackAlignment();
6154 unsigned Align = MinAlign(ObjectOffset, StackAlign);
6156 // Finally, the frame object itself may have a known alignment. Factor
6157 // the alignment + offset into a new alignment. For example, if we know
6158 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
6159 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
6160 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
6161 return std::max(Align, FIInfoAlign);
6169 void SelectionDAG::dump() const {
6170 dbgs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
6172 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
6174 const SDNode *N = I;
6175 if (!N->hasOneUse() && N != getRoot().getNode())
6176 DumpNodes(N, 2, this);
6179 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
6184 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
6186 print_details(OS, G);
6189 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
6190 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
6191 const SelectionDAG *G, VisitedSDNodeSet &once) {
6192 if (!once.insert(N)) // If we've been here before, return now.
6195 // Dump the current SDNode, but don't end the line yet.
6196 OS << std::string(indent, ' ');
6199 // Having printed this SDNode, walk the children:
6200 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6201 const SDNode *child = N->getOperand(i).getNode();
6206 if (child->getNumOperands() == 0) {
6207 // This child has no grandchildren; print it inline right here.
6208 child->printr(OS, G);
6210 } else { // Just the address. FIXME: also print the child's opcode.
6212 if (unsigned RN = N->getOperand(i).getResNo())
6219 // Dump children that have grandchildren on their own line(s).
6220 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6221 const SDNode *child = N->getOperand(i).getNode();
6222 DumpNodesr(OS, child, indent+2, G, once);
6226 void SDNode::dumpr() const {
6227 VisitedSDNodeSet once;
6228 DumpNodesr(dbgs(), this, 0, 0, once);
6231 void SDNode::dumpr(const SelectionDAG *G) const {
6232 VisitedSDNodeSet once;
6233 DumpNodesr(dbgs(), this, 0, G, once);
6237 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6238 unsigned GlobalAddressSDNode::getAddressSpace() const {
6239 return getGlobal()->getType()->getAddressSpace();
6243 const Type *ConstantPoolSDNode::getType() const {
6244 if (isMachineConstantPoolEntry())
6245 return Val.MachineCPVal->getType();
6246 return Val.ConstVal->getType();
6249 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6251 unsigned &SplatBitSize,
6253 unsigned MinSplatBits,
6255 EVT VT = getValueType(0);
6256 assert(VT.isVector() && "Expected a vector type");
6257 unsigned sz = VT.getSizeInBits();
6258 if (MinSplatBits > sz)
6261 SplatValue = APInt(sz, 0);
6262 SplatUndef = APInt(sz, 0);
6264 // Get the bits. Bits with undefined values (when the corresponding element
6265 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6266 // in SplatValue. If any of the values are not constant, give up and return
6268 unsigned int nOps = getNumOperands();
6269 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6270 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6272 for (unsigned j = 0; j < nOps; ++j) {
6273 unsigned i = isBigEndian ? nOps-1-j : j;
6274 SDValue OpVal = getOperand(i);
6275 unsigned BitPos = j * EltBitSize;
6277 if (OpVal.getOpcode() == ISD::UNDEF)
6278 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6279 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6280 SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
6281 zextOrTrunc(sz) << BitPos);
6282 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6283 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6288 // The build_vector is all constants or undefs. Find the smallest element
6289 // size that splats the vector.
6291 HasAnyUndefs = (SplatUndef != 0);
6294 unsigned HalfSize = sz / 2;
6295 APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
6296 APInt LowValue = APInt(SplatValue).trunc(HalfSize);
6297 APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
6298 APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
6300 // If the two halves do not match (ignoring undef bits), stop here.
6301 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6302 MinSplatBits > HalfSize)
6305 SplatValue = HighValue | LowValue;
6306 SplatUndef = HighUndef & LowUndef;
6315 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6316 // Find the first non-undef value in the shuffle mask.
6318 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6321 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6323 // Make sure all remaining elements are either undef or the same as the first
6325 for (int Idx = Mask[i]; i != e; ++i)
6326 if (Mask[i] >= 0 && Mask[i] != Idx)
6332 static void checkForCyclesHelper(const SDNode *N,
6333 SmallPtrSet<const SDNode*, 32> &Visited,
6334 SmallPtrSet<const SDNode*, 32> &Checked) {
6335 // If this node has already been checked, don't check it again.
6336 if (Checked.count(N))
6339 // If a node has already been visited on this depth-first walk, reject it as
6341 if (!Visited.insert(N)) {
6342 dbgs() << "Offending node:\n";
6344 errs() << "Detected cycle in SelectionDAG\n";
6348 for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6349 checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked);
6356 void llvm::checkForCycles(const llvm::SDNode *N) {
6358 assert(N && "Checking nonexistant SDNode");
6359 SmallPtrSet<const SDNode*, 32> visited;
6360 SmallPtrSet<const SDNode*, 32> checked;
6361 checkForCyclesHelper(N, visited, checked);
6365 void llvm::checkForCycles(const llvm::SelectionDAG *DAG) {
6366 checkForCycles(DAG->getRoot().getNode());