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 "SDNodeDbgValue.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/KnownBits.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Mutex.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetIntrinsicInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
50 #include "llvm/Target/TargetSubtargetInfo.h"
57 /// makeVTList - Return an instance of the SDVTList struct initialized with the
58 /// specified members.
59 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
60 SDVTList Res = {VTs, NumVTs};
64 // Default null implementations of the callbacks.
65 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
66 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
68 //===----------------------------------------------------------------------===//
69 // ConstantFPSDNode Class
70 //===----------------------------------------------------------------------===//
72 /// isExactlyValue - We don't rely on operator== working on double values, as
73 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
74 /// As such, this method can be used to do an exact bit-for-bit comparison of
75 /// two floating point values.
76 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
77 return getValueAPF().bitwiseIsEqual(V);
80 bool ConstantFPSDNode::isValueValidForType(EVT VT,
82 assert(VT.isFloatingPoint() && "Can only convert between FP types");
84 // convert modifies in place, so make a copy.
85 APFloat Val2 = APFloat(Val);
87 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
88 APFloat::rmNearestTiesToEven,
93 //===----------------------------------------------------------------------===//
95 //===----------------------------------------------------------------------===//
97 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
98 auto *BV = dyn_cast<BuildVectorSDNode>(N);
103 unsigned SplatBitSize;
105 EVT EltVT = N->getValueType(0).getVectorElementType();
106 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs) &&
107 EltVT.getSizeInBits() >= SplatBitSize;
110 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
111 // specializations of the more general isConstantSplatVector()?
113 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
114 // Look through a bit convert.
115 while (N->getOpcode() == ISD::BITCAST)
116 N = N->getOperand(0).getNode();
118 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
120 unsigned i = 0, e = N->getNumOperands();
122 // Skip over all of the undef values.
123 while (i != e && N->getOperand(i).isUndef())
126 // Do not accept an all-undef vector.
127 if (i == e) return false;
129 // Do not accept build_vectors that aren't all constants or which have non-~0
130 // elements. We have to be a bit careful here, as the type of the constant
131 // may not be the same as the type of the vector elements due to type
132 // legalization (the elements are promoted to a legal type for the target and
133 // a vector of a type may be legal when the base element type is not).
134 // We only want to check enough bits to cover the vector elements, because
135 // we care if the resultant vector is all ones, not whether the individual
137 SDValue NotZero = N->getOperand(i);
138 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
139 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
140 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
142 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
143 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
148 // Okay, we have at least one ~0 value, check to see if the rest match or are
149 // undefs. Even with the above element type twiddling, this should be OK, as
150 // the same type legalization should have applied to all the elements.
151 for (++i; i != e; ++i)
152 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
157 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
158 // Look through a bit convert.
159 while (N->getOpcode() == ISD::BITCAST)
160 N = N->getOperand(0).getNode();
162 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
164 bool IsAllUndef = true;
165 for (const SDValue &Op : N->op_values()) {
169 // Do not accept build_vectors that aren't all constants or which have non-0
170 // elements. We have to be a bit careful here, as the type of the constant
171 // may not be the same as the type of the vector elements due to type
172 // legalization (the elements are promoted to a legal type for the target
173 // and a vector of a type may be legal when the base element type is not).
174 // We only want to check enough bits to cover the vector elements, because
175 // we care if the resultant vector is all zeros, not whether the individual
177 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
178 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
179 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
181 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
182 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
188 // Do not accept an all-undef vector.
194 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
195 if (N->getOpcode() != ISD::BUILD_VECTOR)
198 for (const SDValue &Op : N->op_values()) {
201 if (!isa<ConstantSDNode>(Op))
207 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
208 if (N->getOpcode() != ISD::BUILD_VECTOR)
211 for (const SDValue &Op : N->op_values()) {
214 if (!isa<ConstantFPSDNode>(Op))
220 bool ISD::allOperandsUndef(const SDNode *N) {
221 // Return false if the node has no operands.
222 // This is "logically inconsistent" with the definition of "all" but
223 // is probably the desired behavior.
224 if (N->getNumOperands() == 0)
227 for (const SDValue &Op : N->op_values())
234 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
237 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
239 return ISD::SIGN_EXTEND;
241 return ISD::ZERO_EXTEND;
246 llvm_unreachable("Invalid LoadExtType");
249 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
250 // To perform this operation, we just need to swap the L and G bits of the
252 unsigned OldL = (Operation >> 2) & 1;
253 unsigned OldG = (Operation >> 1) & 1;
254 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
255 (OldL << 1) | // New G bit
256 (OldG << 2)); // New L bit.
259 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
260 unsigned Operation = Op;
262 Operation ^= 7; // Flip L, G, E bits, but not U.
264 Operation ^= 15; // Flip all of the condition bits.
266 if (Operation > ISD::SETTRUE2)
267 Operation &= ~8; // Don't let N and U bits get set.
269 return ISD::CondCode(Operation);
273 /// For an integer comparison, return 1 if the comparison is a signed operation
274 /// and 2 if the result is an unsigned comparison. Return zero if the operation
275 /// does not depend on the sign of the input (setne and seteq).
276 static int isSignedOp(ISD::CondCode Opcode) {
278 default: llvm_unreachable("Illegal integer setcc operation!");
280 case ISD::SETNE: return 0;
284 case ISD::SETGE: return 1;
288 case ISD::SETUGE: return 2;
292 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
294 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
295 // Cannot fold a signed integer setcc with an unsigned integer setcc.
296 return ISD::SETCC_INVALID;
298 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
300 // If the N and U bits get set, then the resultant comparison DOES suddenly
301 // care about orderedness, and it is true when ordered.
302 if (Op > ISD::SETTRUE2)
303 Op &= ~16; // Clear the U bit if the N bit is set.
305 // Canonicalize illegal integer setcc's.
306 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
309 return ISD::CondCode(Op);
312 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
314 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
315 // Cannot fold a signed setcc with an unsigned setcc.
316 return ISD::SETCC_INVALID;
318 // Combine all of the condition bits.
319 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
321 // Canonicalize illegal integer setcc's.
325 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
326 case ISD::SETOEQ: // SETEQ & SETU[LG]E
327 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
328 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
329 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
336 //===----------------------------------------------------------------------===//
337 // SDNode Profile Support
338 //===----------------------------------------------------------------------===//
340 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
342 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
346 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
347 /// solely with their pointer.
348 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
349 ID.AddPointer(VTList.VTs);
352 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
354 static void AddNodeIDOperands(FoldingSetNodeID &ID,
355 ArrayRef<SDValue> Ops) {
356 for (auto& Op : Ops) {
357 ID.AddPointer(Op.getNode());
358 ID.AddInteger(Op.getResNo());
362 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
364 static void AddNodeIDOperands(FoldingSetNodeID &ID,
365 ArrayRef<SDUse> Ops) {
366 for (auto& Op : Ops) {
367 ID.AddPointer(Op.getNode());
368 ID.AddInteger(Op.getResNo());
372 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
373 SDVTList VTList, ArrayRef<SDValue> OpList) {
374 AddNodeIDOpcode(ID, OpC);
375 AddNodeIDValueTypes(ID, VTList);
376 AddNodeIDOperands(ID, OpList);
379 /// If this is an SDNode with special info, add this info to the NodeID data.
380 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
381 switch (N->getOpcode()) {
382 case ISD::TargetExternalSymbol:
383 case ISD::ExternalSymbol:
385 llvm_unreachable("Should only be used on nodes with operands");
386 default: break; // Normal nodes don't need extra info.
387 case ISD::TargetConstant:
388 case ISD::Constant: {
389 const ConstantSDNode *C = cast<ConstantSDNode>(N);
390 ID.AddPointer(C->getConstantIntValue());
391 ID.AddBoolean(C->isOpaque());
394 case ISD::TargetConstantFP:
395 case ISD::ConstantFP: {
396 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
399 case ISD::TargetGlobalAddress:
400 case ISD::GlobalAddress:
401 case ISD::TargetGlobalTLSAddress:
402 case ISD::GlobalTLSAddress: {
403 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
404 ID.AddPointer(GA->getGlobal());
405 ID.AddInteger(GA->getOffset());
406 ID.AddInteger(GA->getTargetFlags());
409 case ISD::BasicBlock:
410 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
413 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
415 case ISD::RegisterMask:
416 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
419 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
421 case ISD::FrameIndex:
422 case ISD::TargetFrameIndex:
423 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
426 case ISD::TargetJumpTable:
427 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
428 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
430 case ISD::ConstantPool:
431 case ISD::TargetConstantPool: {
432 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
433 ID.AddInteger(CP->getAlignment());
434 ID.AddInteger(CP->getOffset());
435 if (CP->isMachineConstantPoolEntry())
436 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
438 ID.AddPointer(CP->getConstVal());
439 ID.AddInteger(CP->getTargetFlags());
442 case ISD::TargetIndex: {
443 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
444 ID.AddInteger(TI->getIndex());
445 ID.AddInteger(TI->getOffset());
446 ID.AddInteger(TI->getTargetFlags());
450 const LoadSDNode *LD = cast<LoadSDNode>(N);
451 ID.AddInteger(LD->getMemoryVT().getRawBits());
452 ID.AddInteger(LD->getRawSubclassData());
453 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
457 const StoreSDNode *ST = cast<StoreSDNode>(N);
458 ID.AddInteger(ST->getMemoryVT().getRawBits());
459 ID.AddInteger(ST->getRawSubclassData());
460 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
463 case ISD::ATOMIC_CMP_SWAP:
464 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
465 case ISD::ATOMIC_SWAP:
466 case ISD::ATOMIC_LOAD_ADD:
467 case ISD::ATOMIC_LOAD_SUB:
468 case ISD::ATOMIC_LOAD_AND:
469 case ISD::ATOMIC_LOAD_OR:
470 case ISD::ATOMIC_LOAD_XOR:
471 case ISD::ATOMIC_LOAD_NAND:
472 case ISD::ATOMIC_LOAD_MIN:
473 case ISD::ATOMIC_LOAD_MAX:
474 case ISD::ATOMIC_LOAD_UMIN:
475 case ISD::ATOMIC_LOAD_UMAX:
476 case ISD::ATOMIC_LOAD:
477 case ISD::ATOMIC_STORE: {
478 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
479 ID.AddInteger(AT->getMemoryVT().getRawBits());
480 ID.AddInteger(AT->getRawSubclassData());
481 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
484 case ISD::PREFETCH: {
485 const MemSDNode *PF = cast<MemSDNode>(N);
486 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
489 case ISD::VECTOR_SHUFFLE: {
490 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
491 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
493 ID.AddInteger(SVN->getMaskElt(i));
496 case ISD::TargetBlockAddress:
497 case ISD::BlockAddress: {
498 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
499 ID.AddPointer(BA->getBlockAddress());
500 ID.AddInteger(BA->getOffset());
501 ID.AddInteger(BA->getTargetFlags());
504 } // end switch (N->getOpcode())
506 // Target specific memory nodes could also have address spaces to check.
507 if (N->isTargetMemoryOpcode())
508 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
511 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
513 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
514 AddNodeIDOpcode(ID, N->getOpcode());
515 // Add the return value info.
516 AddNodeIDValueTypes(ID, N->getVTList());
517 // Add the operand info.
518 AddNodeIDOperands(ID, N->ops());
520 // Handle SDNode leafs with special info.
521 AddNodeIDCustom(ID, N);
524 //===----------------------------------------------------------------------===//
525 // SelectionDAG Class
526 //===----------------------------------------------------------------------===//
528 /// doNotCSE - Return true if CSE should not be performed for this node.
529 static bool doNotCSE(SDNode *N) {
530 if (N->getValueType(0) == MVT::Glue)
531 return true; // Never CSE anything that produces a flag.
533 switch (N->getOpcode()) {
535 case ISD::HANDLENODE:
537 return true; // Never CSE these nodes.
540 // Check that remaining values produced are not flags.
541 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
542 if (N->getValueType(i) == MVT::Glue)
543 return true; // Never CSE anything that produces a flag.
548 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
550 void SelectionDAG::RemoveDeadNodes() {
551 // Create a dummy node (which is not added to allnodes), that adds a reference
552 // to the root node, preventing it from being deleted.
553 HandleSDNode Dummy(getRoot());
555 SmallVector<SDNode*, 128> DeadNodes;
557 // Add all obviously-dead nodes to the DeadNodes worklist.
558 for (SDNode &Node : allnodes())
559 if (Node.use_empty())
560 DeadNodes.push_back(&Node);
562 RemoveDeadNodes(DeadNodes);
564 // If the root changed (e.g. it was a dead load, update the root).
565 setRoot(Dummy.getValue());
568 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
569 /// given list, and any nodes that become unreachable as a result.
570 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
572 // Process the worklist, deleting the nodes and adding their uses to the
574 while (!DeadNodes.empty()) {
575 SDNode *N = DeadNodes.pop_back_val();
577 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
578 DUL->NodeDeleted(N, nullptr);
580 // Take the node out of the appropriate CSE map.
581 RemoveNodeFromCSEMaps(N);
583 // Next, brutally remove the operand list. This is safe to do, as there are
584 // no cycles in the graph.
585 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
587 SDNode *Operand = Use.getNode();
590 // Now that we removed this operand, see if there are no uses of it left.
591 if (Operand->use_empty())
592 DeadNodes.push_back(Operand);
599 void SelectionDAG::RemoveDeadNode(SDNode *N){
600 SmallVector<SDNode*, 16> DeadNodes(1, N);
602 // Create a dummy node that adds a reference to the root node, preventing
603 // it from being deleted. (This matters if the root is an operand of the
605 HandleSDNode Dummy(getRoot());
607 RemoveDeadNodes(DeadNodes);
610 void SelectionDAG::DeleteNode(SDNode *N) {
611 // First take this out of the appropriate CSE map.
612 RemoveNodeFromCSEMaps(N);
614 // Finally, remove uses due to operands of this node, remove from the
615 // AllNodes list, and delete the node.
616 DeleteNodeNotInCSEMaps(N);
619 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
620 assert(N->getIterator() != AllNodes.begin() &&
621 "Cannot delete the entry node!");
622 assert(N->use_empty() && "Cannot delete a node that is not dead!");
624 // Drop all of the operands and decrement used node's use counts.
630 void SDDbgInfo::erase(const SDNode *Node) {
631 DbgValMapType::iterator I = DbgValMap.find(Node);
632 if (I == DbgValMap.end())
634 for (auto &Val: I->second)
635 Val->setIsInvalidated();
639 void SelectionDAG::DeallocateNode(SDNode *N) {
640 // If we have operands, deallocate them.
643 NodeAllocator.Deallocate(AllNodes.remove(N));
645 // Set the opcode to DELETED_NODE to help catch bugs when node
646 // memory is reallocated.
647 // FIXME: There are places in SDag that have grown a dependency on the opcode
648 // value in the released node.
649 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
650 N->NodeType = ISD::DELETED_NODE;
652 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
653 // them and forget about that node.
658 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
659 static void VerifySDNode(SDNode *N) {
660 switch (N->getOpcode()) {
663 case ISD::BUILD_PAIR: {
664 EVT VT = N->getValueType(0);
665 assert(N->getNumValues() == 1 && "Too many results!");
666 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
667 "Wrong return type!");
668 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
669 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
670 "Mismatched operand types!");
671 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
672 "Wrong operand type!");
673 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
674 "Wrong return type size");
677 case ISD::BUILD_VECTOR: {
678 assert(N->getNumValues() == 1 && "Too many results!");
679 assert(N->getValueType(0).isVector() && "Wrong return type!");
680 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
681 "Wrong number of operands!");
682 EVT EltVT = N->getValueType(0).getVectorElementType();
683 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
684 assert((I->getValueType() == EltVT ||
685 (EltVT.isInteger() && I->getValueType().isInteger() &&
686 EltVT.bitsLE(I->getValueType()))) &&
687 "Wrong operand type!");
688 assert(I->getValueType() == N->getOperand(0).getValueType() &&
689 "Operands must all have the same type");
697 /// \brief Insert a newly allocated node into the DAG.
699 /// Handles insertion into the all nodes list and CSE map, as well as
700 /// verification and other common operations when a new node is allocated.
701 void SelectionDAG::InsertNode(SDNode *N) {
702 AllNodes.push_back(N);
704 N->PersistentId = NextPersistentId++;
709 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
710 /// correspond to it. This is useful when we're about to delete or repurpose
711 /// the node. We don't want future request for structurally identical nodes
712 /// to return N anymore.
713 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
715 switch (N->getOpcode()) {
716 case ISD::HANDLENODE: return false; // noop.
718 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
719 "Cond code doesn't exist!");
720 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
721 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
723 case ISD::ExternalSymbol:
724 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
726 case ISD::TargetExternalSymbol: {
727 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
728 Erased = TargetExternalSymbols.erase(
729 std::pair<std::string,unsigned char>(ESN->getSymbol(),
730 ESN->getTargetFlags()));
733 case ISD::MCSymbol: {
734 auto *MCSN = cast<MCSymbolSDNode>(N);
735 Erased = MCSymbols.erase(MCSN->getMCSymbol());
738 case ISD::VALUETYPE: {
739 EVT VT = cast<VTSDNode>(N)->getVT();
740 if (VT.isExtended()) {
741 Erased = ExtendedValueTypeNodes.erase(VT);
743 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
744 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
749 // Remove it from the CSE Map.
750 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
751 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
752 Erased = CSEMap.RemoveNode(N);
756 // Verify that the node was actually in one of the CSE maps, unless it has a
757 // flag result (which cannot be CSE'd) or is one of the special cases that are
758 // not subject to CSE.
759 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
760 !N->isMachineOpcode() && !doNotCSE(N)) {
763 llvm_unreachable("Node is not in map!");
769 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
770 /// maps and modified in place. Add it back to the CSE maps, unless an identical
771 /// node already exists, in which case transfer all its users to the existing
772 /// node. This transfer can potentially trigger recursive merging.
775 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
776 // For node types that aren't CSE'd, just act as if no identical node
779 SDNode *Existing = CSEMap.GetOrInsertNode(N);
781 // If there was already an existing matching node, use ReplaceAllUsesWith
782 // to replace the dead one with the existing one. This can cause
783 // recursive merging of other unrelated nodes down the line.
784 ReplaceAllUsesWith(N, Existing);
786 // N is now dead. Inform the listeners and delete it.
787 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
788 DUL->NodeDeleted(N, Existing);
789 DeleteNodeNotInCSEMaps(N);
794 // If the node doesn't already exist, we updated it. Inform listeners.
795 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
799 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
800 /// were replaced with those specified. If this node is never memoized,
801 /// return null, otherwise return a pointer to the slot it would take. If a
802 /// node already exists with these operands, the slot will be non-null.
803 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
808 SDValue Ops[] = { Op };
810 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
811 AddNodeIDCustom(ID, N);
812 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
814 Node->intersectFlagsWith(N->getFlags());
818 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
819 /// were replaced with those specified. If this node is never memoized,
820 /// return null, otherwise return a pointer to the slot it would take. If a
821 /// node already exists with these operands, the slot will be non-null.
822 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
823 SDValue Op1, SDValue Op2,
828 SDValue Ops[] = { Op1, Op2 };
830 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
831 AddNodeIDCustom(ID, N);
832 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
834 Node->intersectFlagsWith(N->getFlags());
839 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
840 /// were replaced with those specified. If this node is never memoized,
841 /// return null, otherwise return a pointer to the slot it would take. If a
842 /// node already exists with these operands, the slot will be non-null.
843 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
849 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
850 AddNodeIDCustom(ID, N);
851 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
853 Node->intersectFlagsWith(N->getFlags());
857 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
858 Type *Ty = VT == MVT::iPTR ?
859 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
860 VT.getTypeForEVT(*getContext());
862 return getDataLayout().getABITypeAlignment(Ty);
865 // EntryNode could meaningfully have debug info if we can find it...
866 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
867 : TM(tm), TSI(nullptr), TLI(nullptr), OptLevel(OL),
868 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
869 Root(getEntryNode()), NewNodesMustHaveLegalTypes(false),
870 UpdateListeners(nullptr) {
871 InsertNode(&EntryNode);
872 DbgInfo = new SDDbgInfo();
875 void SelectionDAG::init(MachineFunction &NewMF,
876 OptimizationRemarkEmitter &NewORE) {
879 TLI = getSubtarget().getTargetLowering();
880 TSI = getSubtarget().getSelectionDAGInfo();
881 Context = &MF->getFunction()->getContext();
884 SelectionDAG::~SelectionDAG() {
885 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
887 OperandRecycler.clear(OperandAllocator);
891 void SelectionDAG::allnodes_clear() {
892 assert(&*AllNodes.begin() == &EntryNode);
893 AllNodes.remove(AllNodes.begin());
894 while (!AllNodes.empty())
895 DeallocateNode(&AllNodes.front());
897 NextPersistentId = 0;
901 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
903 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
905 switch (N->getOpcode()) {
908 case ISD::ConstantFP:
909 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
910 "debug location. Use another overload.");
916 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
917 const SDLoc &DL, void *&InsertPos) {
918 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
920 switch (N->getOpcode()) {
922 case ISD::ConstantFP:
923 // Erase debug location from the node if the node is used at several
924 // different places. Do not propagate one location to all uses as it
925 // will cause a worse single stepping debugging experience.
926 if (N->getDebugLoc() != DL.getDebugLoc())
927 N->setDebugLoc(DebugLoc());
930 // When the node's point of use is located earlier in the instruction
931 // sequence than its prior point of use, update its debug info to the
933 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
934 N->setDebugLoc(DL.getDebugLoc());
941 void SelectionDAG::clear() {
943 OperandRecycler.clear(OperandAllocator);
944 OperandAllocator.Reset();
947 ExtendedValueTypeNodes.clear();
948 ExternalSymbols.clear();
949 TargetExternalSymbols.clear();
951 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
952 static_cast<CondCodeSDNode*>(nullptr));
953 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
954 static_cast<SDNode*>(nullptr));
956 EntryNode.UseList = nullptr;
957 InsertNode(&EntryNode);
958 Root = getEntryNode();
962 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
963 return VT.bitsGT(Op.getValueType())
964 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
965 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
968 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
969 return VT.bitsGT(Op.getValueType()) ?
970 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
971 getNode(ISD::TRUNCATE, DL, VT, Op);
974 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
975 return VT.bitsGT(Op.getValueType()) ?
976 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
977 getNode(ISD::TRUNCATE, DL, VT, Op);
980 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
981 return VT.bitsGT(Op.getValueType()) ?
982 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
983 getNode(ISD::TRUNCATE, DL, VT, Op);
986 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
988 if (VT.bitsLE(Op.getValueType()))
989 return getNode(ISD::TRUNCATE, SL, VT, Op);
991 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
992 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
995 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
996 assert(!VT.isVector() &&
997 "getZeroExtendInReg should use the vector element type instead of "
999 if (Op.getValueType() == VT) return Op;
1000 unsigned BitWidth = Op.getScalarValueSizeInBits();
1001 APInt Imm = APInt::getLowBitsSet(BitWidth,
1002 VT.getSizeInBits());
1003 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1004 getConstant(Imm, DL, Op.getValueType()));
1007 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL,
1009 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1010 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1011 "The sizes of the input and result must match in order to perform the "
1012 "extend in-register.");
1013 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1014 "The destination vector type must have fewer lanes than the input.");
1015 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1018 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL,
1020 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1021 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1022 "The sizes of the input and result must match in order to perform the "
1023 "extend in-register.");
1024 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1025 "The destination vector type must have fewer lanes than the input.");
1026 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1029 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL,
1031 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1032 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1033 "The sizes of the input and result must match in order to perform the "
1034 "extend in-register.");
1035 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1036 "The destination vector type must have fewer lanes than the input.");
1037 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1040 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1042 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1043 EVT EltVT = VT.getScalarType();
1045 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1046 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1049 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1050 EVT EltVT = VT.getScalarType();
1052 switch (TLI->getBooleanContents(VT)) {
1053 case TargetLowering::ZeroOrOneBooleanContent:
1054 case TargetLowering::UndefinedBooleanContent:
1055 TrueValue = getConstant(1, DL, VT);
1057 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1058 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL,
1062 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1065 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1066 bool isT, bool isO) {
1067 EVT EltVT = VT.getScalarType();
1068 assert((EltVT.getSizeInBits() >= 64 ||
1069 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1070 "getConstant with a uint64_t value that doesn't fit in the type!");
1071 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1074 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1075 bool isT, bool isO) {
1076 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1079 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1080 EVT VT, bool isT, bool isO) {
1081 assert(VT.isInteger() && "Cannot create FP integer constant!");
1083 EVT EltVT = VT.getScalarType();
1084 const ConstantInt *Elt = &Val;
1086 // In some cases the vector type is legal but the element type is illegal and
1087 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1088 // inserted value (the type does not need to match the vector element type).
1089 // Any extra bits introduced will be truncated away.
1090 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1091 TargetLowering::TypePromoteInteger) {
1092 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1093 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1094 Elt = ConstantInt::get(*getContext(), NewVal);
1096 // In other cases the element type is illegal and needs to be expanded, for
1097 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1098 // the value into n parts and use a vector type with n-times the elements.
1099 // Then bitcast to the type requested.
1100 // Legalizing constants too early makes the DAGCombiner's job harder so we
1101 // only legalize if the DAG tells us we must produce legal types.
1102 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1103 TLI->getTypeAction(*getContext(), EltVT) ==
1104 TargetLowering::TypeExpandInteger) {
1105 const APInt &NewVal = Elt->getValue();
1106 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1107 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1108 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1109 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1111 // Check the temporary vector is the correct size. If this fails then
1112 // getTypeToTransformTo() probably returned a type whose size (in bits)
1113 // isn't a power-of-2 factor of the requested type size.
1114 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1116 SmallVector<SDValue, 2> EltParts;
1117 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1118 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1119 .zextOrTrunc(ViaEltSizeInBits), DL,
1120 ViaEltVT, isT, isO));
1123 // EltParts is currently in little endian order. If we actually want
1124 // big-endian order then reverse it now.
1125 if (getDataLayout().isBigEndian())
1126 std::reverse(EltParts.begin(), EltParts.end());
1128 // The elements must be reversed when the element order is different
1129 // to the endianness of the elements (because the BITCAST is itself a
1130 // vector shuffle in this situation). However, we do not need any code to
1131 // perform this reversal because getConstant() is producing a vector
1133 // This situation occurs in MIPS MSA.
1135 SmallVector<SDValue, 8> Ops;
1136 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1137 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1138 return getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1141 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1142 "APInt size does not match type size!");
1143 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1144 FoldingSetNodeID ID;
1145 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1149 SDNode *N = nullptr;
1150 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1152 return SDValue(N, 0);
1155 N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT);
1156 CSEMap.InsertNode(N, IP);
1160 SDValue Result(N, 0);
1162 Result = getSplatBuildVector(VT, DL, Result);
1166 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1168 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1171 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1173 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1176 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1177 EVT VT, bool isTarget) {
1178 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1180 EVT EltVT = VT.getScalarType();
1182 // Do the map lookup using the actual bit pattern for the floating point
1183 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1184 // we don't have issues with SNANs.
1185 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1186 FoldingSetNodeID ID;
1187 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1190 SDNode *N = nullptr;
1191 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1193 return SDValue(N, 0);
1196 N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT);
1197 CSEMap.InsertNode(N, IP);
1201 SDValue Result(N, 0);
1203 Result = getSplatBuildVector(VT, DL, Result);
1207 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1209 EVT EltVT = VT.getScalarType();
1210 if (EltVT == MVT::f32)
1211 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1212 else if (EltVT == MVT::f64)
1213 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1214 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1215 EltVT == MVT::f16) {
1217 APFloat APF = APFloat(Val);
1218 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1220 return getConstantFP(APF, DL, VT, isTarget);
1222 llvm_unreachable("Unsupported type in getConstantFP");
1225 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1226 EVT VT, int64_t Offset, bool isTargetGA,
1227 unsigned char TargetFlags) {
1228 assert((TargetFlags == 0 || isTargetGA) &&
1229 "Cannot set target flags on target-independent globals");
1231 // Truncate (with sign-extension) the offset value to the pointer size.
1232 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1234 Offset = SignExtend64(Offset, BitWidth);
1237 if (GV->isThreadLocal())
1238 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1240 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1242 FoldingSetNodeID ID;
1243 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1245 ID.AddInteger(Offset);
1246 ID.AddInteger(TargetFlags);
1248 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1249 return SDValue(E, 0);
1251 auto *N = newSDNode<GlobalAddressSDNode>(
1252 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1253 CSEMap.InsertNode(N, IP);
1255 return SDValue(N, 0);
1258 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1259 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1260 FoldingSetNodeID ID;
1261 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1264 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1265 return SDValue(E, 0);
1267 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1268 CSEMap.InsertNode(N, IP);
1270 return SDValue(N, 0);
1273 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1274 unsigned char TargetFlags) {
1275 assert((TargetFlags == 0 || isTarget) &&
1276 "Cannot set target flags on target-independent jump tables");
1277 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1278 FoldingSetNodeID ID;
1279 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1281 ID.AddInteger(TargetFlags);
1283 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1284 return SDValue(E, 0);
1286 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1287 CSEMap.InsertNode(N, IP);
1289 return SDValue(N, 0);
1292 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1293 unsigned Alignment, int Offset,
1295 unsigned char TargetFlags) {
1296 assert((TargetFlags == 0 || isTarget) &&
1297 "Cannot set target flags on target-independent globals");
1299 Alignment = MF->getFunction()->optForSize()
1300 ? getDataLayout().getABITypeAlignment(C->getType())
1301 : getDataLayout().getPrefTypeAlignment(C->getType());
1302 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1303 FoldingSetNodeID ID;
1304 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1305 ID.AddInteger(Alignment);
1306 ID.AddInteger(Offset);
1308 ID.AddInteger(TargetFlags);
1310 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1311 return SDValue(E, 0);
1313 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1315 CSEMap.InsertNode(N, IP);
1317 return SDValue(N, 0);
1321 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1322 unsigned Alignment, int Offset,
1324 unsigned char TargetFlags) {
1325 assert((TargetFlags == 0 || isTarget) &&
1326 "Cannot set target flags on target-independent globals");
1328 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1329 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1330 FoldingSetNodeID ID;
1331 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1332 ID.AddInteger(Alignment);
1333 ID.AddInteger(Offset);
1334 C->addSelectionDAGCSEId(ID);
1335 ID.AddInteger(TargetFlags);
1337 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1338 return SDValue(E, 0);
1340 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1342 CSEMap.InsertNode(N, IP);
1344 return SDValue(N, 0);
1347 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1348 unsigned char TargetFlags) {
1349 FoldingSetNodeID ID;
1350 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1351 ID.AddInteger(Index);
1352 ID.AddInteger(Offset);
1353 ID.AddInteger(TargetFlags);
1355 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1356 return SDValue(E, 0);
1358 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1359 CSEMap.InsertNode(N, IP);
1361 return SDValue(N, 0);
1364 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1365 FoldingSetNodeID ID;
1366 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1369 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1370 return SDValue(E, 0);
1372 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1373 CSEMap.InsertNode(N, IP);
1375 return SDValue(N, 0);
1378 SDValue SelectionDAG::getValueType(EVT VT) {
1379 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1380 ValueTypeNodes.size())
1381 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1383 SDNode *&N = VT.isExtended() ?
1384 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1386 if (N) return SDValue(N, 0);
1387 N = newSDNode<VTSDNode>(VT);
1389 return SDValue(N, 0);
1392 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1393 SDNode *&N = ExternalSymbols[Sym];
1394 if (N) return SDValue(N, 0);
1395 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1397 return SDValue(N, 0);
1400 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1401 SDNode *&N = MCSymbols[Sym];
1403 return SDValue(N, 0);
1404 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1406 return SDValue(N, 0);
1409 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1410 unsigned char TargetFlags) {
1412 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1414 if (N) return SDValue(N, 0);
1415 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1417 return SDValue(N, 0);
1420 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1421 if ((unsigned)Cond >= CondCodeNodes.size())
1422 CondCodeNodes.resize(Cond+1);
1424 if (!CondCodeNodes[Cond]) {
1425 auto *N = newSDNode<CondCodeSDNode>(Cond);
1426 CondCodeNodes[Cond] = N;
1430 return SDValue(CondCodeNodes[Cond], 0);
1433 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1434 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1435 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1437 ShuffleVectorSDNode::commuteMask(M);
1440 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1441 SDValue N2, ArrayRef<int> Mask) {
1442 assert(VT.getVectorNumElements() == Mask.size() &&
1443 "Must have the same number of vector elements as mask elements!");
1444 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1445 "Invalid VECTOR_SHUFFLE");
1447 // Canonicalize shuffle undef, undef -> undef
1448 if (N1.isUndef() && N2.isUndef())
1449 return getUNDEF(VT);
1451 // Validate that all indices in Mask are within the range of the elements
1452 // input to the shuffle.
1453 int NElts = Mask.size();
1454 assert(all_of(Mask, [&](int M) { return M < (NElts * 2); }) &&
1455 "Index out of range");
1457 // Copy the mask so we can do any needed cleanup.
1458 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1460 // Canonicalize shuffle v, v -> v, undef
1463 for (int i = 0; i != NElts; ++i)
1464 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1467 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1469 commuteShuffle(N1, N2, MaskVec);
1471 // If shuffling a splat, try to blend the splat instead. We do this here so
1472 // that even when this arises during lowering we don't have to re-handle it.
1473 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1474 BitVector UndefElements;
1475 SDValue Splat = BV->getSplatValue(&UndefElements);
1479 for (int i = 0; i < NElts; ++i) {
1480 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1483 // If this input comes from undef, mark it as such.
1484 if (UndefElements[MaskVec[i] - Offset]) {
1489 // If we can blend a non-undef lane, use that instead.
1490 if (!UndefElements[i])
1491 MaskVec[i] = i + Offset;
1494 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1495 BlendSplat(N1BV, 0);
1496 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1497 BlendSplat(N2BV, NElts);
1499 // Canonicalize all index into lhs, -> shuffle lhs, undef
1500 // Canonicalize all index into rhs, -> shuffle rhs, undef
1501 bool AllLHS = true, AllRHS = true;
1502 bool N2Undef = N2.isUndef();
1503 for (int i = 0; i != NElts; ++i) {
1504 if (MaskVec[i] >= NElts) {
1509 } else if (MaskVec[i] >= 0) {
1513 if (AllLHS && AllRHS)
1514 return getUNDEF(VT);
1515 if (AllLHS && !N2Undef)
1519 commuteShuffle(N1, N2, MaskVec);
1521 // Reset our undef status after accounting for the mask.
1522 N2Undef = N2.isUndef();
1523 // Re-check whether both sides ended up undef.
1524 if (N1.isUndef() && N2Undef)
1525 return getUNDEF(VT);
1527 // If Identity shuffle return that node.
1528 bool Identity = true, AllSame = true;
1529 for (int i = 0; i != NElts; ++i) {
1530 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1531 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1533 if (Identity && NElts)
1536 // Shuffling a constant splat doesn't change the result.
1540 // Look through any bitcasts. We check that these don't change the number
1541 // (and size) of elements and just changes their types.
1542 while (V.getOpcode() == ISD::BITCAST)
1543 V = V->getOperand(0);
1545 // A splat should always show up as a build vector node.
1546 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1547 BitVector UndefElements;
1548 SDValue Splat = BV->getSplatValue(&UndefElements);
1549 // If this is a splat of an undef, shuffling it is also undef.
1550 if (Splat && Splat.isUndef())
1551 return getUNDEF(VT);
1554 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1556 // We only have a splat which can skip shuffles if there is a splatted
1557 // value and no undef lanes rearranged by the shuffle.
1558 if (Splat && UndefElements.none()) {
1559 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1560 // number of elements match or the value splatted is a zero constant.
1563 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1564 if (C->isNullValue())
1568 // If the shuffle itself creates a splat, build the vector directly.
1569 if (AllSame && SameNumElts) {
1570 EVT BuildVT = BV->getValueType(0);
1571 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1572 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1574 // We may have jumped through bitcasts, so the type of the
1575 // BUILD_VECTOR may not match the type of the shuffle.
1577 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1583 FoldingSetNodeID ID;
1584 SDValue Ops[2] = { N1, N2 };
1585 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1586 for (int i = 0; i != NElts; ++i)
1587 ID.AddInteger(MaskVec[i]);
1590 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1591 return SDValue(E, 0);
1593 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1594 // SDNode doesn't have access to it. This memory will be "leaked" when
1595 // the node is deallocated, but recovered when the NodeAllocator is released.
1596 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1597 std::copy(MaskVec.begin(), MaskVec.end(), MaskAlloc);
1599 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1600 dl.getDebugLoc(), MaskAlloc);
1601 createOperands(N, Ops);
1603 CSEMap.InsertNode(N, IP);
1605 return SDValue(N, 0);
1608 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1609 MVT VT = SV.getSimpleValueType(0);
1610 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1611 ShuffleVectorSDNode::commuteMask(MaskVec);
1613 SDValue Op0 = SV.getOperand(0);
1614 SDValue Op1 = SV.getOperand(1);
1615 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1618 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1619 FoldingSetNodeID ID;
1620 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1621 ID.AddInteger(RegNo);
1623 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1624 return SDValue(E, 0);
1626 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1627 CSEMap.InsertNode(N, IP);
1629 return SDValue(N, 0);
1632 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1633 FoldingSetNodeID ID;
1634 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1635 ID.AddPointer(RegMask);
1637 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1638 return SDValue(E, 0);
1640 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1641 CSEMap.InsertNode(N, IP);
1643 return SDValue(N, 0);
1646 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1648 FoldingSetNodeID ID;
1649 SDValue Ops[] = { Root };
1650 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops);
1651 ID.AddPointer(Label);
1653 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1654 return SDValue(E, 0);
1656 auto *N = newSDNode<EHLabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1657 createOperands(N, Ops);
1659 CSEMap.InsertNode(N, IP);
1661 return SDValue(N, 0);
1664 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1667 unsigned char TargetFlags) {
1668 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1670 FoldingSetNodeID ID;
1671 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1673 ID.AddInteger(Offset);
1674 ID.AddInteger(TargetFlags);
1676 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1677 return SDValue(E, 0);
1679 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1680 CSEMap.InsertNode(N, IP);
1682 return SDValue(N, 0);
1685 SDValue SelectionDAG::getSrcValue(const Value *V) {
1686 assert((!V || V->getType()->isPointerTy()) &&
1687 "SrcValue is not a pointer?");
1689 FoldingSetNodeID ID;
1690 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1694 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1695 return SDValue(E, 0);
1697 auto *N = newSDNode<SrcValueSDNode>(V);
1698 CSEMap.InsertNode(N, IP);
1700 return SDValue(N, 0);
1703 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1704 FoldingSetNodeID ID;
1705 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1709 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1710 return SDValue(E, 0);
1712 auto *N = newSDNode<MDNodeSDNode>(MD);
1713 CSEMap.InsertNode(N, IP);
1715 return SDValue(N, 0);
1718 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1719 if (VT == V.getValueType())
1722 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1725 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1726 unsigned SrcAS, unsigned DestAS) {
1727 SDValue Ops[] = {Ptr};
1728 FoldingSetNodeID ID;
1729 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1730 ID.AddInteger(SrcAS);
1731 ID.AddInteger(DestAS);
1734 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1735 return SDValue(E, 0);
1737 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1739 createOperands(N, Ops);
1741 CSEMap.InsertNode(N, IP);
1743 return SDValue(N, 0);
1746 /// getShiftAmountOperand - Return the specified value casted to
1747 /// the target's desired shift amount type.
1748 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1749 EVT OpTy = Op.getValueType();
1750 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1751 if (OpTy == ShTy || OpTy.isVector()) return Op;
1753 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1756 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1758 const TargetLowering &TLI = getTargetLoweringInfo();
1759 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1760 EVT VT = Node->getValueType(0);
1761 SDValue Tmp1 = Node->getOperand(0);
1762 SDValue Tmp2 = Node->getOperand(1);
1763 unsigned Align = Node->getConstantOperandVal(3);
1765 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1766 Tmp2, MachinePointerInfo(V));
1767 SDValue VAList = VAListLoad;
1769 if (Align > TLI.getMinStackArgumentAlignment()) {
1770 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1772 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1773 getConstant(Align - 1, dl, VAList.getValueType()));
1775 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1776 getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1779 // Increment the pointer, VAList, to the next vaarg
1780 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1781 getConstant(getDataLayout().getTypeAllocSize(
1782 VT.getTypeForEVT(*getContext())),
1783 dl, VAList.getValueType()));
1784 // Store the incremented VAList to the legalized pointer
1786 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1787 // Load the actual argument out of the pointer VAList
1788 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1791 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1793 const TargetLowering &TLI = getTargetLoweringInfo();
1794 // This defaults to loading a pointer from the input and storing it to the
1795 // output, returning the chain.
1796 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1797 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1799 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1800 Node->getOperand(2), MachinePointerInfo(VS));
1801 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1802 MachinePointerInfo(VD));
1805 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1806 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1807 unsigned ByteSize = VT.getStoreSize();
1808 Type *Ty = VT.getTypeForEVT(*getContext());
1809 unsigned StackAlign =
1810 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1812 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1813 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1816 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1817 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1818 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1819 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1820 const DataLayout &DL = getDataLayout();
1822 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1824 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1825 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1826 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1829 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1830 ISD::CondCode Cond, const SDLoc &dl) {
1831 // These setcc operations always fold.
1835 case ISD::SETFALSE2: return getConstant(0, dl, VT);
1837 case ISD::SETTRUE2: {
1838 TargetLowering::BooleanContent Cnt =
1839 TLI->getBooleanContents(N1->getValueType(0));
1841 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1855 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1859 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1860 const APInt &C2 = N2C->getAPIntValue();
1861 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1862 const APInt &C1 = N1C->getAPIntValue();
1865 default: llvm_unreachable("Unknown integer setcc!");
1866 case ISD::SETEQ: return getConstant(C1 == C2, dl, VT);
1867 case ISD::SETNE: return getConstant(C1 != C2, dl, VT);
1868 case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT);
1869 case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT);
1870 case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT);
1871 case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT);
1872 case ISD::SETLT: return getConstant(C1.slt(C2), dl, VT);
1873 case ISD::SETGT: return getConstant(C1.sgt(C2), dl, VT);
1874 case ISD::SETLE: return getConstant(C1.sle(C2), dl, VT);
1875 case ISD::SETGE: return getConstant(C1.sge(C2), dl, VT);
1879 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1880 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1881 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1884 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1885 return getUNDEF(VT);
1887 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT);
1888 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1889 return getUNDEF(VT);
1891 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1892 R==APFloat::cmpLessThan, dl, VT);
1893 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1894 return getUNDEF(VT);
1896 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT);
1897 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1898 return getUNDEF(VT);
1900 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT);
1901 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1902 return getUNDEF(VT);
1904 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1905 R==APFloat::cmpEqual, dl, VT);
1906 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1907 return getUNDEF(VT);
1909 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1910 R==APFloat::cmpEqual, dl, VT);
1911 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, dl, VT);
1912 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, dl, VT);
1913 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1914 R==APFloat::cmpEqual, dl, VT);
1915 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT);
1916 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1917 R==APFloat::cmpLessThan, dl, VT);
1918 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1919 R==APFloat::cmpUnordered, dl, VT);
1920 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT);
1921 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT);
1924 // Ensure that the constant occurs on the RHS.
1925 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1926 MVT CompVT = N1.getValueType().getSimpleVT();
1927 if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
1930 return getSetCC(dl, VT, N2, N1, SwappedCond);
1934 // Could not fold it.
1938 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1939 /// use this predicate to simplify operations downstream.
1940 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1941 unsigned BitWidth = Op.getScalarValueSizeInBits();
1942 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
1945 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1946 /// this predicate to simplify operations downstream. Mask is known to be zero
1947 /// for bits that V cannot have.
1948 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1949 unsigned Depth) const {
1951 computeKnownBits(Op, Known, Depth);
1952 return Mask.isSubsetOf(Known.Zero);
1955 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
1956 /// is less than the element bit-width of the shift node, return it.
1957 static const APInt *getValidShiftAmountConstant(SDValue V) {
1958 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
1959 // Shifting more than the bitwidth is not valid.
1960 const APInt &ShAmt = SA->getAPIntValue();
1961 if (ShAmt.ult(V.getScalarValueSizeInBits()))
1967 /// Determine which bits of Op are known to be either zero or one and return
1968 /// them in Known. For vectors, the known bits are those that are shared by
1969 /// every vector element.
1970 void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known,
1971 unsigned Depth) const {
1972 EVT VT = Op.getValueType();
1973 APInt DemandedElts = VT.isVector()
1974 ? APInt::getAllOnesValue(VT.getVectorNumElements())
1976 computeKnownBits(Op, Known, DemandedElts, Depth);
1979 /// Determine which bits of Op are known to be either zero or one and return
1980 /// them in Known. The DemandedElts argument allows us to only collect the known
1981 /// bits that are shared by the requested vector elements.
1982 void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known,
1983 const APInt &DemandedElts,
1984 unsigned Depth) const {
1985 unsigned BitWidth = Op.getScalarValueSizeInBits();
1987 Known = KnownBits(BitWidth); // Don't know anything.
1989 return; // Limit search depth.
1992 unsigned NumElts = DemandedElts.getBitWidth();
1995 return; // No demanded elts, better to assume we don't know anything.
1997 unsigned Opcode = Op.getOpcode();
2000 // We know all of the bits for a constant!
2001 Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
2002 Known.Zero = ~Known.One;
2004 case ISD::BUILD_VECTOR:
2005 // Collect the known bits that are shared by every demanded vector element.
2006 assert(NumElts == Op.getValueType().getVectorNumElements() &&
2007 "Unexpected vector size");
2008 Known.Zero.setAllBits(); Known.One.setAllBits();
2009 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2010 if (!DemandedElts[i])
2013 SDValue SrcOp = Op.getOperand(i);
2014 computeKnownBits(SrcOp, Known2, Depth + 1);
2016 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2017 if (SrcOp.getValueSizeInBits() != BitWidth) {
2018 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2019 "Expected BUILD_VECTOR implicit truncation");
2020 Known2 = Known2.trunc(BitWidth);
2023 // Known bits are the values that are shared by every demanded element.
2024 Known.One &= Known2.One;
2025 Known.Zero &= Known2.Zero;
2027 // If we don't know any bits, early out.
2028 if (!Known.One && !Known.Zero)
2032 case ISD::VECTOR_SHUFFLE: {
2033 // Collect the known bits that are shared by every vector element referenced
2035 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2036 Known.Zero.setAllBits(); Known.One.setAllBits();
2037 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2038 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2039 for (unsigned i = 0; i != NumElts; ++i) {
2040 if (!DemandedElts[i])
2043 int M = SVN->getMaskElt(i);
2045 // For UNDEF elements, we don't know anything about the common state of
2046 // the shuffle result.
2048 DemandedLHS.clearAllBits();
2049 DemandedRHS.clearAllBits();
2053 if ((unsigned)M < NumElts)
2054 DemandedLHS.setBit((unsigned)M % NumElts);
2056 DemandedRHS.setBit((unsigned)M % NumElts);
2058 // Known bits are the values that are shared by every demanded element.
2059 if (!!DemandedLHS) {
2060 SDValue LHS = Op.getOperand(0);
2061 computeKnownBits(LHS, Known2, DemandedLHS, Depth + 1);
2062 Known.One &= Known2.One;
2063 Known.Zero &= Known2.Zero;
2065 // If we don't know any bits, early out.
2066 if (!Known.One && !Known.Zero)
2068 if (!!DemandedRHS) {
2069 SDValue RHS = Op.getOperand(1);
2070 computeKnownBits(RHS, Known2, DemandedRHS, Depth + 1);
2071 Known.One &= Known2.One;
2072 Known.Zero &= Known2.Zero;
2076 case ISD::CONCAT_VECTORS: {
2077 // Split DemandedElts and test each of the demanded subvectors.
2078 Known.Zero.setAllBits(); Known.One.setAllBits();
2079 EVT SubVectorVT = Op.getOperand(0).getValueType();
2080 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2081 unsigned NumSubVectors = Op.getNumOperands();
2082 for (unsigned i = 0; i != NumSubVectors; ++i) {
2083 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2084 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2085 if (!!DemandedSub) {
2086 SDValue Sub = Op.getOperand(i);
2087 computeKnownBits(Sub, Known2, DemandedSub, Depth + 1);
2088 Known.One &= Known2.One;
2089 Known.Zero &= Known2.Zero;
2091 // If we don't know any bits, early out.
2092 if (!Known.One && !Known.Zero)
2097 case ISD::EXTRACT_SUBVECTOR: {
2098 // If we know the element index, just demand that subvector elements,
2099 // otherwise demand them all.
2100 SDValue Src = Op.getOperand(0);
2101 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2102 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2103 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2104 // Offset the demanded elts by the subvector index.
2105 uint64_t Idx = SubIdx->getZExtValue();
2106 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
2107 computeKnownBits(Src, Known, DemandedSrc, Depth + 1);
2109 computeKnownBits(Src, Known, Depth + 1);
2113 case ISD::BITCAST: {
2114 SDValue N0 = Op.getOperand(0);
2115 unsigned SubBitWidth = N0.getScalarValueSizeInBits();
2117 // Ignore bitcasts from floating point.
2118 if (!N0.getValueType().isInteger())
2121 // Fast handling of 'identity' bitcasts.
2122 if (BitWidth == SubBitWidth) {
2123 computeKnownBits(N0, Known, DemandedElts, Depth + 1);
2127 // Support big-endian targets when it becomes useful.
2128 bool IsLE = getDataLayout().isLittleEndian();
2132 // Bitcast 'small element' vector to 'large element' scalar/vector.
2133 if ((BitWidth % SubBitWidth) == 0) {
2134 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2136 // Collect known bits for the (larger) output by collecting the known
2137 // bits from each set of sub elements and shift these into place.
2138 // We need to separately call computeKnownBits for each set of
2139 // sub elements as the knownbits for each is likely to be different.
2140 unsigned SubScale = BitWidth / SubBitWidth;
2141 APInt SubDemandedElts(NumElts * SubScale, 0);
2142 for (unsigned i = 0; i != NumElts; ++i)
2143 if (DemandedElts[i])
2144 SubDemandedElts.setBit(i * SubScale);
2146 for (unsigned i = 0; i != SubScale; ++i) {
2147 computeKnownBits(N0, Known2, SubDemandedElts.shl(i),
2149 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * i);
2150 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * i);
2154 // Bitcast 'large element' scalar/vector to 'small element' vector.
2155 if ((SubBitWidth % BitWidth) == 0) {
2156 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2158 // Collect known bits for the (smaller) output by collecting the known
2159 // bits from the overlapping larger input elements and extracting the
2160 // sub sections we actually care about.
2161 unsigned SubScale = SubBitWidth / BitWidth;
2162 APInt SubDemandedElts(NumElts / SubScale, 0);
2163 for (unsigned i = 0; i != NumElts; ++i)
2164 if (DemandedElts[i])
2165 SubDemandedElts.setBit(i / SubScale);
2167 computeKnownBits(N0, Known2, SubDemandedElts, Depth + 1);
2169 Known.Zero.setAllBits(); Known.One.setAllBits();
2170 for (unsigned i = 0; i != NumElts; ++i)
2171 if (DemandedElts[i]) {
2172 unsigned Offset = (i % SubScale) * BitWidth;
2173 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2174 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2175 // If we don't know any bits, early out.
2176 if (!Known.One && !Known.Zero)
2183 // If either the LHS or the RHS are Zero, the result is zero.
2184 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2185 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2187 // Output known-1 bits are only known if set in both the LHS & RHS.
2188 Known.One &= Known2.One;
2189 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2190 Known.Zero |= Known2.Zero;
2193 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2194 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2196 // Output known-0 bits are only known if clear in both the LHS & RHS.
2197 Known.Zero &= Known2.Zero;
2198 // Output known-1 are known to be set if set in either the LHS | RHS.
2199 Known.One |= Known2.One;
2202 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2203 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2205 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2206 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2207 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2208 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2209 Known.Zero = KnownZeroOut;
2213 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2214 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2216 // If low bits are zero in either operand, output low known-0 bits.
2217 // Also compute a conservative estimate for high known-0 bits.
2218 // More trickiness is possible, but this is sufficient for the
2219 // interesting case of alignment computation.
2220 unsigned TrailZ = Known.Zero.countTrailingOnes() +
2221 Known2.Zero.countTrailingOnes();
2222 unsigned LeadZ = std::max(Known.Zero.countLeadingOnes() +
2223 Known2.Zero.countLeadingOnes(),
2224 BitWidth) - BitWidth;
2227 Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2228 Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2232 // For the purposes of computing leading zeros we can conservatively
2233 // treat a udiv as a logical right shift by the power of 2 known to
2234 // be less than the denominator.
2235 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2236 unsigned LeadZ = Known2.Zero.countLeadingOnes();
2238 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2239 unsigned RHSUnknownLeadingOnes = Known2.One.countLeadingZeros();
2240 if (RHSUnknownLeadingOnes != BitWidth)
2241 LeadZ = std::min(BitWidth,
2242 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
2244 Known.Zero.setHighBits(LeadZ);
2248 computeKnownBits(Op.getOperand(2), Known, Depth+1);
2249 // If we don't know any bits, early out.
2250 if (!Known.One && !Known.Zero)
2252 computeKnownBits(Op.getOperand(1), Known2, Depth+1);
2254 // Only known if known in both the LHS and RHS.
2255 Known.One &= Known2.One;
2256 Known.Zero &= Known2.Zero;
2258 case ISD::SELECT_CC:
2259 computeKnownBits(Op.getOperand(3), Known, Depth+1);
2260 // If we don't know any bits, early out.
2261 if (!Known.One && !Known.Zero)
2263 computeKnownBits(Op.getOperand(2), Known2, Depth+1);
2265 // Only known if known in both the LHS and RHS.
2266 Known.One &= Known2.One;
2267 Known.Zero &= Known2.Zero;
2271 if (Op.getResNo() != 1)
2273 // The boolean result conforms to getBooleanContents.
2274 // If we know the result of a setcc has the top bits zero, use this info.
2275 // We know that we have an integer-based boolean since these operations
2276 // are only available for integer.
2277 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2278 TargetLowering::ZeroOrOneBooleanContent &&
2280 Known.Zero.setBitsFrom(1);
2283 // If we know the result of a setcc has the top bits zero, use this info.
2284 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2285 TargetLowering::ZeroOrOneBooleanContent &&
2287 Known.Zero.setBitsFrom(1);
2290 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2291 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2292 Known.Zero <<= *ShAmt;
2293 Known.One <<= *ShAmt;
2294 // Low bits are known zero.
2295 Known.Zero.setLowBits(ShAmt->getZExtValue());
2299 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2300 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2301 Known.Zero.lshrInPlace(*ShAmt);
2302 Known.One.lshrInPlace(*ShAmt);
2303 // High bits are known zero.
2304 Known.Zero.setHighBits(ShAmt->getZExtValue());
2308 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2309 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2310 Known.Zero.lshrInPlace(*ShAmt);
2311 Known.One.lshrInPlace(*ShAmt);
2312 // If we know the value of the sign bit, then we know it is copied across
2313 // the high bits by the shift amount.
2314 APInt SignMask = APInt::getSignMask(BitWidth);
2315 SignMask.lshrInPlace(*ShAmt); // Adjust to where it is now in the mask.
2316 if (Known.Zero.intersects(SignMask)) {
2317 Known.Zero.setHighBits(ShAmt->getZExtValue());// New bits are known zero.
2318 } else if (Known.One.intersects(SignMask)) {
2319 Known.One.setHighBits(ShAmt->getZExtValue()); // New bits are known one.
2323 case ISD::SIGN_EXTEND_INREG: {
2324 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2325 unsigned EBits = EVT.getScalarSizeInBits();
2327 // Sign extension. Compute the demanded bits in the result that are not
2328 // present in the input.
2329 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2331 APInt InSignMask = APInt::getSignMask(EBits);
2332 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2334 // If the sign extended bits are demanded, we know that the sign
2336 InSignMask = InSignMask.zext(BitWidth);
2337 if (NewBits.getBoolValue())
2338 InputDemandedBits |= InSignMask;
2340 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2341 Known.One &= InputDemandedBits;
2342 Known.Zero &= InputDemandedBits;
2344 // If the sign bit of the input is known set or clear, then we know the
2345 // top bits of the result.
2346 if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2347 Known.Zero |= NewBits;
2348 Known.One &= ~NewBits;
2349 } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2350 Known.One |= NewBits;
2351 Known.Zero &= ~NewBits;
2352 } else { // Input sign bit unknown
2353 Known.Zero &= ~NewBits;
2354 Known.One &= ~NewBits;
2359 case ISD::CTTZ_ZERO_UNDEF: {
2360 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2361 // If we have a known 1, its position is our upper bound.
2362 unsigned PossibleTZ = Known2.One.countTrailingZeros();
2363 unsigned LowBits = Log2_32(PossibleTZ) + 1;
2364 Known.Zero.setBitsFrom(LowBits);
2368 case ISD::CTLZ_ZERO_UNDEF: {
2369 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2370 // If we have a known 1, its position is our upper bound.
2371 unsigned PossibleLZ = Known2.One.countLeadingZeros();
2372 unsigned LowBits = Log2_32(PossibleLZ) + 1;
2373 Known.Zero.setBitsFrom(LowBits);
2377 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2378 // If we know some of the bits are zero, they can't be one.
2379 unsigned PossibleOnes = BitWidth - Known2.Zero.countPopulation();
2380 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2384 LoadSDNode *LD = cast<LoadSDNode>(Op);
2385 // If this is a ZEXTLoad and we are looking at the loaded value.
2386 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2387 EVT VT = LD->getMemoryVT();
2388 unsigned MemBits = VT.getScalarSizeInBits();
2389 Known.Zero.setBitsFrom(MemBits);
2390 } else if (const MDNode *Ranges = LD->getRanges()) {
2391 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2392 computeKnownBitsFromRangeMetadata(*Ranges, Known);
2396 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2397 EVT InVT = Op.getOperand(0).getValueType();
2398 unsigned InBits = InVT.getScalarSizeInBits();
2399 Known = Known.trunc(InBits);
2400 computeKnownBits(Op.getOperand(0), Known,
2401 DemandedElts.zext(InVT.getVectorNumElements()),
2403 Known = Known.zext(BitWidth);
2404 Known.Zero.setBitsFrom(InBits);
2407 case ISD::ZERO_EXTEND: {
2408 EVT InVT = Op.getOperand(0).getValueType();
2409 unsigned InBits = InVT.getScalarSizeInBits();
2410 Known = Known.trunc(InBits);
2411 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2412 Known = Known.zext(BitWidth);
2413 Known.Zero.setBitsFrom(InBits);
2416 // TODO ISD::SIGN_EXTEND_VECTOR_INREG
2417 case ISD::SIGN_EXTEND: {
2418 EVT InVT = Op.getOperand(0).getValueType();
2419 unsigned InBits = InVT.getScalarSizeInBits();
2421 Known = Known.trunc(InBits);
2422 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2424 // If the sign bit is known to be zero or one, then sext will extend
2425 // it to the top bits, else it will just zext.
2426 Known = Known.sext(BitWidth);
2429 case ISD::ANY_EXTEND: {
2430 EVT InVT = Op.getOperand(0).getValueType();
2431 unsigned InBits = InVT.getScalarSizeInBits();
2432 Known = Known.trunc(InBits);
2433 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2434 Known = Known.zext(BitWidth);
2437 case ISD::TRUNCATE: {
2438 EVT InVT = Op.getOperand(0).getValueType();
2439 unsigned InBits = InVT.getScalarSizeInBits();
2440 Known = Known.zext(InBits);
2441 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2442 Known = Known.trunc(BitWidth);
2445 case ISD::AssertZext: {
2446 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2447 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2448 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2449 Known.Zero |= (~InMask);
2450 Known.One &= (~Known.Zero);
2454 // All bits are zero except the low bit.
2455 Known.Zero.setBitsFrom(1);
2459 if (Op.getResNo() == 1) {
2460 // If we know the result of a setcc has the top bits zero, use this info.
2461 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2462 TargetLowering::ZeroOrOneBooleanContent &&
2464 Known.Zero.setBitsFrom(1);
2470 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
2471 // We know that the top bits of C-X are clear if X contains less bits
2472 // than C (i.e. no wrap-around can happen). For example, 20-X is
2473 // positive if we can prove that X is >= 0 and < 16.
2474 if (CLHS->getAPIntValue().isNonNegative()) {
2475 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2476 // NLZ can't be BitWidth with no sign bit
2477 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2478 computeKnownBits(Op.getOperand(1), Known2, DemandedElts,
2481 // If all of the MaskV bits are known to be zero, then we know the
2482 // output top bits are zero, because we now know that the output is
2484 if ((Known2.Zero & MaskV) == MaskV) {
2485 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2486 // Top bits known zero.
2487 Known.Zero.setHighBits(NLZ2);
2492 // If low bits are know to be zero in both operands, then we know they are
2493 // going to be 0 in the result. Both addition and complement operations
2494 // preserve the low zero bits.
2495 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2496 unsigned KnownZeroLow = Known2.Zero.countTrailingOnes();
2497 if (KnownZeroLow == 0)
2500 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2501 KnownZeroLow = std::min(KnownZeroLow,
2502 Known2.Zero.countTrailingOnes());
2503 Known.Zero.setLowBits(KnownZeroLow);
2509 if (Op.getResNo() == 1) {
2510 // If we know the result of a setcc has the top bits zero, use this info.
2511 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2512 TargetLowering::ZeroOrOneBooleanContent &&
2514 Known.Zero.setBitsFrom(1);
2521 // Output known-0 bits are known if clear or set in both the low clear bits
2522 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2523 // low 3 bits clear.
2524 // Output known-0 bits are also known if the top bits of each input are
2525 // known to be clear. For example, if one input has the top 10 bits clear
2526 // and the other has the top 8 bits clear, we know the top 7 bits of the
2527 // output must be clear.
2528 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2529 unsigned KnownZeroHigh = Known2.Zero.countLeadingOnes();
2530 unsigned KnownZeroLow = Known2.Zero.countTrailingOnes();
2532 computeKnownBits(Op.getOperand(1), Known2, DemandedElts,
2534 KnownZeroHigh = std::min(KnownZeroHigh,
2535 Known2.Zero.countLeadingOnes());
2536 KnownZeroLow = std::min(KnownZeroLow,
2537 Known2.Zero.countTrailingOnes());
2539 if (Opcode == ISD::ADDE || Opcode == ISD::ADDCARRY) {
2540 // With ADDE and ADDCARRY, a carry bit may be added in, so we can only
2541 // use this information if we know (at least) that the low two bits are
2542 // clear. We then return to the caller that the low bit is unknown but
2543 // that other bits are known zero.
2544 if (KnownZeroLow >= 2)
2545 Known.Zero.setBits(1, KnownZeroLow);
2549 Known.Zero.setLowBits(KnownZeroLow);
2550 if (KnownZeroHigh > 1)
2551 Known.Zero.setHighBits(KnownZeroHigh - 1);
2555 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2556 const APInt &RA = Rem->getAPIntValue().abs();
2557 if (RA.isPowerOf2()) {
2558 APInt LowBits = RA - 1;
2559 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2561 // The low bits of the first operand are unchanged by the srem.
2562 Known.Zero = Known2.Zero & LowBits;
2563 Known.One = Known2.One & LowBits;
2565 // If the first operand is non-negative or has all low bits zero, then
2566 // the upper bits are all zero.
2567 if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
2568 Known.Zero |= ~LowBits;
2570 // If the first operand is negative and not all low bits are zero, then
2571 // the upper bits are all one.
2572 if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
2573 Known.One |= ~LowBits;
2574 assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
2579 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2580 const APInt &RA = Rem->getAPIntValue();
2581 if (RA.isPowerOf2()) {
2582 APInt LowBits = (RA - 1);
2583 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2585 // The upper bits are all zero, the lower ones are unchanged.
2586 Known.Zero = Known2.Zero | ~LowBits;
2587 Known.One = Known2.One & LowBits;
2592 // Since the result is less than or equal to either operand, any leading
2593 // zero bits in either operand must also exist in the result.
2594 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2595 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2597 uint32_t Leaders = std::max(Known.Zero.countLeadingOnes(),
2598 Known2.Zero.countLeadingOnes());
2600 Known.Zero.setHighBits(Leaders);
2603 case ISD::EXTRACT_ELEMENT: {
2604 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2605 const unsigned Index = Op.getConstantOperandVal(1);
2606 const unsigned BitWidth = Op.getValueSizeInBits();
2608 // Remove low part of known bits mask
2609 Known.Zero = Known.Zero.getHiBits(Known.Zero.getBitWidth() - Index * BitWidth);
2610 Known.One = Known.One.getHiBits(Known.One.getBitWidth() - Index * BitWidth);
2612 // Remove high part of known bit mask
2613 Known = Known.trunc(BitWidth);
2616 case ISD::EXTRACT_VECTOR_ELT: {
2617 SDValue InVec = Op.getOperand(0);
2618 SDValue EltNo = Op.getOperand(1);
2619 EVT VecVT = InVec.getValueType();
2620 const unsigned BitWidth = Op.getValueSizeInBits();
2621 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
2622 const unsigned NumSrcElts = VecVT.getVectorNumElements();
2623 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2624 // anything about the extended bits.
2625 if (BitWidth > EltBitWidth)
2626 Known = Known.trunc(EltBitWidth);
2627 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
2628 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
2629 // If we know the element index, just demand that vector element.
2630 unsigned Idx = ConstEltNo->getZExtValue();
2631 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
2632 computeKnownBits(InVec, Known, DemandedElt, Depth + 1);
2634 // Unknown element index, so ignore DemandedElts and demand them all.
2635 computeKnownBits(InVec, Known, Depth + 1);
2637 if (BitWidth > EltBitWidth)
2638 Known = Known.zext(BitWidth);
2641 case ISD::INSERT_VECTOR_ELT: {
2642 SDValue InVec = Op.getOperand(0);
2643 SDValue InVal = Op.getOperand(1);
2644 SDValue EltNo = Op.getOperand(2);
2646 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
2647 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
2648 // If we know the element index, split the demand between the
2649 // source vector and the inserted element.
2650 Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
2651 unsigned EltIdx = CEltNo->getZExtValue();
2653 // If we demand the inserted element then add its common known bits.
2654 if (DemandedElts[EltIdx]) {
2655 computeKnownBits(InVal, Known2, Depth + 1);
2656 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
2657 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());;
2660 // If we demand the source vector then add its common known bits, ensuring
2661 // that we don't demand the inserted element.
2662 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
2664 computeKnownBits(InVec, Known2, VectorElts, Depth + 1);
2665 Known.One &= Known2.One;
2666 Known.Zero &= Known2.Zero;
2669 // Unknown element index, so ignore DemandedElts and demand them all.
2670 computeKnownBits(InVec, Known, Depth + 1);
2671 computeKnownBits(InVal, Known2, Depth + 1);
2672 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
2673 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());;
2677 case ISD::BITREVERSE: {
2678 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2679 Known.Zero = Known2.Zero.reverseBits();
2680 Known.One = Known2.One.reverseBits();
2684 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2685 Known.Zero = Known2.Zero.byteSwap();
2686 Known.One = Known2.One.byteSwap();
2690 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2692 // If the source's MSB is zero then we know the rest of the bits already.
2693 if (Known2.isNonNegative()) {
2694 Known.Zero = Known2.Zero;
2695 Known.One = Known2.One;
2699 // We only know that the absolute values's MSB will be zero iff there is
2700 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
2701 Known2.One.clearSignBit();
2702 if (Known2.One.getBoolValue()) {
2703 Known.Zero = APInt::getSignMask(BitWidth);
2709 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2710 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2712 // UMIN - we know that the result will have the maximum of the
2713 // known zero leading bits of the inputs.
2714 unsigned LeadZero = Known.Zero.countLeadingOnes();
2715 LeadZero = std::max(LeadZero, Known2.Zero.countLeadingOnes());
2717 Known.Zero &= Known2.Zero;
2718 Known.One &= Known2.One;
2719 Known.Zero.setHighBits(LeadZero);
2723 computeKnownBits(Op.getOperand(0), Known, DemandedElts,
2725 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2727 // UMAX - we know that the result will have the maximum of the
2728 // known one leading bits of the inputs.
2729 unsigned LeadOne = Known.One.countLeadingOnes();
2730 LeadOne = std::max(LeadOne, Known2.One.countLeadingOnes());
2732 Known.Zero &= Known2.Zero;
2733 Known.One &= Known2.One;
2734 Known.One.setHighBits(LeadOne);
2739 computeKnownBits(Op.getOperand(0), Known, DemandedElts,
2741 // If we don't know any bits, early out.
2742 if (!Known.One && !Known.Zero)
2744 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2745 Known.Zero &= Known2.Zero;
2746 Known.One &= Known2.One;
2749 case ISD::FrameIndex:
2750 case ISD::TargetFrameIndex:
2751 if (unsigned Align = InferPtrAlignment(Op)) {
2752 // The low bits are known zero if the pointer is aligned.
2753 Known.Zero.setLowBits(Log2_32(Align));
2759 if (Opcode < ISD::BUILTIN_OP_END)
2762 case ISD::INTRINSIC_WO_CHAIN:
2763 case ISD::INTRINSIC_W_CHAIN:
2764 case ISD::INTRINSIC_VOID:
2765 // Allow the target to implement this method for its nodes.
2766 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
2770 assert((Known.Zero & Known.One) == 0 && "Bits known to be one AND zero?");
2773 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
2775 // X + 0 never overflow
2776 if (isNullConstant(N1))
2780 computeKnownBits(N1, N1Known);
2781 if (N1Known.Zero.getBoolValue()) {
2783 computeKnownBits(N0, N0Known);
2786 (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
2791 // mulhi + 1 never overflow
2792 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
2793 (~N1Known.Zero & 0x01) == ~N1Known.Zero)
2796 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
2798 computeKnownBits(N0, N0Known);
2800 if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
2804 return OFK_Sometime;
2807 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
2808 EVT OpVT = Val.getValueType();
2809 unsigned BitWidth = OpVT.getScalarSizeInBits();
2811 // Is the constant a known power of 2?
2812 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
2813 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2815 // A left-shift of a constant one will have exactly one bit set because
2816 // shifting the bit off the end is undefined.
2817 if (Val.getOpcode() == ISD::SHL) {
2818 auto *C = isConstOrConstSplat(Val.getOperand(0));
2819 if (C && C->getAPIntValue() == 1)
2823 // Similarly, a logical right-shift of a constant sign-bit will have exactly
2825 if (Val.getOpcode() == ISD::SRL) {
2826 auto *C = isConstOrConstSplat(Val.getOperand(0));
2827 if (C && C->getAPIntValue().isSignMask())
2831 // Are all operands of a build vector constant powers of two?
2832 if (Val.getOpcode() == ISD::BUILD_VECTOR)
2833 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
2834 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
2835 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2840 // More could be done here, though the above checks are enough
2841 // to handle some common cases.
2843 // Fall back to computeKnownBits to catch other known cases.
2845 computeKnownBits(Val, Known);
2846 return (Known.Zero.countPopulation() == BitWidth - 1) &&
2847 (Known.One.countPopulation() == 1);
2850 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
2851 EVT VT = Op.getValueType();
2852 APInt DemandedElts = VT.isVector()
2853 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2855 return ComputeNumSignBits(Op, DemandedElts, Depth);
2858 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
2859 unsigned Depth) const {
2860 EVT VT = Op.getValueType();
2861 assert(VT.isInteger() && "Invalid VT!");
2862 unsigned VTBits = VT.getScalarSizeInBits();
2864 unsigned FirstAnswer = 1;
2867 return 1; // Limit search depth.
2870 return 1; // No demanded elts, better to assume we don't know anything.
2872 switch (Op.getOpcode()) {
2874 case ISD::AssertSext:
2875 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2876 return VTBits-Tmp+1;
2877 case ISD::AssertZext:
2878 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2881 case ISD::Constant: {
2882 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2883 return Val.getNumSignBits();
2886 case ISD::BUILD_VECTOR:
2888 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
2889 if (!DemandedElts[i])
2892 SDValue SrcOp = Op.getOperand(i);
2893 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
2895 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2896 if (SrcOp.getValueSizeInBits() != VTBits) {
2897 assert(SrcOp.getValueSizeInBits() > VTBits &&
2898 "Expected BUILD_VECTOR implicit truncation");
2899 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
2900 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
2902 Tmp = std::min(Tmp, Tmp2);
2906 case ISD::SIGN_EXTEND:
2907 case ISD::SIGN_EXTEND_VECTOR_INREG:
2908 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
2909 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2911 case ISD::SIGN_EXTEND_INREG:
2912 // Max of the input and what this extends.
2913 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
2916 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2917 return std::max(Tmp, Tmp2);
2920 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
2921 // SRA X, C -> adds C sign bits.
2922 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2923 APInt ShiftVal = C->getAPIntValue();
2925 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
2929 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1))) {
2930 // shl destroys sign bits.
2931 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2932 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
2933 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
2934 return Tmp - C->getZExtValue();
2939 case ISD::XOR: // NOT is handled here.
2940 // Logical binary ops preserve the number of sign bits at the worst.
2941 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2943 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2944 FirstAnswer = std::min(Tmp, Tmp2);
2945 // We computed what we know about the sign bits as our first
2946 // answer. Now proceed to the generic code that uses
2947 // computeKnownBits, and pick whichever answer is better.
2952 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2953 if (Tmp == 1) return 1; // Early out.
2954 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2955 return std::min(Tmp, Tmp2);
2956 case ISD::SELECT_CC:
2957 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2958 if (Tmp == 1) return 1; // Early out.
2959 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1);
2960 return std::min(Tmp, Tmp2);
2965 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
2967 return 1; // Early out.
2968 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
2969 return std::min(Tmp, Tmp2);
2976 if (Op.getResNo() != 1)
2978 // The boolean result conforms to getBooleanContents. Fall through.
2979 // If setcc returns 0/-1, all bits are sign bits.
2980 // We know that we have an integer-based boolean since these operations
2981 // are only available for integer.
2982 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2983 TargetLowering::ZeroOrNegativeOneBooleanContent)
2987 // If setcc returns 0/-1, all bits are sign bits.
2988 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2989 TargetLowering::ZeroOrNegativeOneBooleanContent)
2994 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2995 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2997 // Handle rotate right by N like a rotate left by 32-N.
2998 if (Op.getOpcode() == ISD::ROTR)
2999 RotAmt = (VTBits-RotAmt) & (VTBits-1);
3001 // If we aren't rotating out all of the known-in sign bits, return the
3002 // number that are left. This handles rotl(sext(x), 1) for example.
3003 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3004 if (Tmp > RotAmt+1) return Tmp-RotAmt;
3009 // Add can have at most one carry bit. Thus we know that the output
3010 // is, at worst, one more bit than the inputs.
3011 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3012 if (Tmp == 1) return 1; // Early out.
3014 // Special case decrementing a value (ADD X, -1):
3015 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3016 if (CRHS->isAllOnesValue()) {
3018 computeKnownBits(Op.getOperand(0), Known, Depth+1);
3020 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3022 if ((Known.Zero | 1).isAllOnesValue())
3025 // If we are subtracting one from a positive number, there is no carry
3026 // out of the result.
3027 if (Known.isNonNegative())
3031 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3032 if (Tmp2 == 1) return 1;
3033 return std::min(Tmp, Tmp2)-1;
3036 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3037 if (Tmp2 == 1) return 1;
3040 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3041 if (CLHS->isNullValue()) {
3043 computeKnownBits(Op.getOperand(1), Known, Depth+1);
3044 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3046 if ((Known.Zero | 1).isAllOnesValue())
3049 // If the input is known to be positive (the sign bit is known clear),
3050 // the output of the NEG has the same number of sign bits as the input.
3051 if (Known.isNonNegative())
3054 // Otherwise, we treat this like a SUB.
3057 // Sub can have at most one carry bit. Thus we know that the output
3058 // is, at worst, one more bit than the inputs.
3059 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3060 if (Tmp == 1) return 1; // Early out.
3061 return std::min(Tmp, Tmp2)-1;
3062 case ISD::TRUNCATE: {
3063 // Check if the sign bits of source go down as far as the truncated value.
3064 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3065 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3066 if (NumSrcSignBits > (NumSrcBits - VTBits))
3067 return NumSrcSignBits - (NumSrcBits - VTBits);
3070 case ISD::EXTRACT_ELEMENT: {
3071 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3072 const int BitWidth = Op.getValueSizeInBits();
3073 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3075 // Get reverse index (starting from 1), Op1 value indexes elements from
3076 // little end. Sign starts at big end.
3077 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3079 // If the sign portion ends in our element the subtraction gives correct
3080 // result. Otherwise it gives either negative or > bitwidth result
3081 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3083 case ISD::INSERT_VECTOR_ELT: {
3084 SDValue InVec = Op.getOperand(0);
3085 SDValue InVal = Op.getOperand(1);
3086 SDValue EltNo = Op.getOperand(2);
3087 unsigned NumElts = InVec.getValueType().getVectorNumElements();
3089 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3090 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3091 // If we know the element index, split the demand between the
3092 // source vector and the inserted element.
3093 unsigned EltIdx = CEltNo->getZExtValue();
3095 // If we demand the inserted element then get its sign bits.
3097 if (DemandedElts[EltIdx]) {
3098 // TODO - handle implicit truncation of inserted elements.
3099 if (InVal.getScalarValueSizeInBits() != VTBits)
3101 Tmp = ComputeNumSignBits(InVal, Depth + 1);
3104 // If we demand the source vector then get its sign bits, and determine
3106 APInt VectorElts = DemandedElts;
3107 VectorElts.clearBit(EltIdx);
3109 Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3110 Tmp = std::min(Tmp, Tmp2);
3113 // Unknown element index, so ignore DemandedElts and demand them all.
3114 Tmp = ComputeNumSignBits(InVec, Depth + 1);
3115 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3116 Tmp = std::min(Tmp, Tmp2);
3118 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3121 case ISD::EXTRACT_VECTOR_ELT: {
3122 SDValue InVec = Op.getOperand(0);
3123 SDValue EltNo = Op.getOperand(1);
3124 EVT VecVT = InVec.getValueType();
3125 const unsigned BitWidth = Op.getValueSizeInBits();
3126 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3127 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3129 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3130 // anything about sign bits. But if the sizes match we can derive knowledge
3131 // about sign bits from the vector operand.
3132 if (BitWidth != EltBitWidth)
3135 // If we know the element index, just demand that vector element, else for
3136 // an unknown element index, ignore DemandedElts and demand them all.
3137 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3138 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3139 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3141 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3143 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3145 case ISD::EXTRACT_SUBVECTOR:
3146 return ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3147 case ISD::CONCAT_VECTORS:
3148 // Determine the minimum number of sign bits across all input vectors.
3149 // Early out if the result is already 1.
3150 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3151 for (unsigned i = 1, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i)
3152 Tmp = std::min(Tmp, ComputeNumSignBits(Op.getOperand(i), Depth + 1));
3156 // If we are looking at the loaded value of the SDNode.
3157 if (Op.getResNo() == 0) {
3158 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3159 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3160 unsigned ExtType = LD->getExtensionType();
3163 case ISD::SEXTLOAD: // '17' bits known
3164 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3165 return VTBits-Tmp+1;
3166 case ISD::ZEXTLOAD: // '16' bits known
3167 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3173 // Allow the target to implement this method for its nodes.
3174 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3175 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3176 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3177 Op.getOpcode() == ISD::INTRINSIC_VOID) {
3179 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3181 FirstAnswer = std::max(FirstAnswer, NumBits);
3184 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3185 // use this information.
3187 computeKnownBits(Op, Known, DemandedElts, Depth);
3190 if (Known.isNonNegative()) { // sign bit is 0
3192 } else if (Known.isNegative()) { // sign bit is 1;
3199 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3200 // the number of identical bits in the top of the input value.
3202 Mask <<= Mask.getBitWidth()-VTBits;
3203 // Return # leading zeros. We use 'min' here in case Val was zero before
3204 // shifting. We don't want to return '64' as for an i32 "0".
3205 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3208 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3209 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3210 !isa<ConstantSDNode>(Op.getOperand(1)))
3213 if (Op.getOpcode() == ISD::OR &&
3214 !MaskedValueIsZero(Op.getOperand(0),
3215 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3221 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
3222 // If we're told that NaNs won't happen, assume they won't.
3223 if (getTarget().Options.NoNaNsFPMath)
3226 if (Op->getFlags().hasNoNaNs())
3229 // If the value is a constant, we can obviously see if it is a NaN or not.
3230 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3231 return !C->getValueAPF().isNaN();
3233 // TODO: Recognize more cases here.
3238 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3239 // If the value is a constant, we can obviously see if it is a zero or not.
3240 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3241 return !C->isZero();
3243 // TODO: Recognize more cases here.
3244 switch (Op.getOpcode()) {
3247 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3248 return !C->isNullValue();
3255 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3256 // Check the obvious case.
3257 if (A == B) return true;
3259 // For for negative and positive zero.
3260 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3261 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3262 if (CA->isZero() && CB->isZero()) return true;
3264 // Otherwise they may not be equal.
3268 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3269 assert(A.getValueType() == B.getValueType() &&
3270 "Values must have the same type");
3271 KnownBits AKnown, BKnown;
3272 computeKnownBits(A, AKnown);
3273 computeKnownBits(B, BKnown);
3274 return (AKnown.Zero | BKnown.Zero).isAllOnesValue();
3277 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
3278 ArrayRef<SDValue> Ops,
3279 llvm::SelectionDAG &DAG) {
3280 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
3281 assert(llvm::all_of(Ops,
3283 return Ops[0].getValueType() == Op.getValueType();
3285 "Concatenation of vectors with inconsistent value types!");
3286 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
3287 VT.getVectorNumElements() &&
3288 "Incorrect element count in vector concatenation!");
3290 if (Ops.size() == 1)
3293 // Concat of UNDEFs is UNDEF.
3294 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3295 return DAG.getUNDEF(VT);
3297 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
3298 // simplified to one big BUILD_VECTOR.
3299 // FIXME: Add support for SCALAR_TO_VECTOR as well.
3300 EVT SVT = VT.getScalarType();
3301 SmallVector<SDValue, 16> Elts;
3302 for (SDValue Op : Ops) {
3303 EVT OpVT = Op.getValueType();
3305 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
3306 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
3307 Elts.append(Op->op_begin(), Op->op_end());
3312 // BUILD_VECTOR requires all inputs to be of the same type, find the
3313 // maximum type and extend them all.
3314 for (SDValue Op : Elts)
3315 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
3317 if (SVT.bitsGT(VT.getScalarType()))
3318 for (SDValue &Op : Elts)
3319 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
3320 ? DAG.getZExtOrTrunc(Op, DL, SVT)
3321 : DAG.getSExtOrTrunc(Op, DL, SVT);
3323 return DAG.getBuildVector(VT, DL, Elts);
3326 /// Gets or creates the specified node.
3327 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
3328 FoldingSetNodeID ID;
3329 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
3331 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3332 return SDValue(E, 0);
3334 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
3336 CSEMap.InsertNode(N, IP);
3339 return SDValue(N, 0);
3342 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3343 SDValue Operand, const SDNodeFlags Flags) {
3344 // Constant fold unary operations with an integer constant operand. Even
3345 // opaque constant will be folded, because the folding of unary operations
3346 // doesn't create new constants with different values. Nevertheless, the
3347 // opaque flag is preserved during folding to prevent future folding with
3349 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
3350 const APInt &Val = C->getAPIntValue();
3353 case ISD::SIGN_EXTEND:
3354 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
3355 C->isTargetOpcode(), C->isOpaque());
3356 case ISD::ANY_EXTEND:
3357 case ISD::ZERO_EXTEND:
3359 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
3360 C->isTargetOpcode(), C->isOpaque());
3361 case ISD::UINT_TO_FP:
3362 case ISD::SINT_TO_FP: {
3363 APFloat apf(EVTToAPFloatSemantics(VT),
3364 APInt::getNullValue(VT.getSizeInBits()));
3365 (void)apf.convertFromAPInt(Val,
3366 Opcode==ISD::SINT_TO_FP,
3367 APFloat::rmNearestTiesToEven);
3368 return getConstantFP(apf, DL, VT);
3371 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
3372 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
3373 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
3374 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
3375 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
3376 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
3377 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
3378 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
3381 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
3383 case ISD::BITREVERSE:
3384 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
3387 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
3390 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
3393 case ISD::CTLZ_ZERO_UNDEF:
3394 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
3397 case ISD::CTTZ_ZERO_UNDEF:
3398 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
3400 case ISD::FP16_TO_FP: {
3402 APFloat FPV(APFloat::IEEEhalf(),
3403 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
3405 // This can return overflow, underflow, or inexact; we don't care.
3406 // FIXME need to be more flexible about rounding mode.
3407 (void)FPV.convert(EVTToAPFloatSemantics(VT),
3408 APFloat::rmNearestTiesToEven, &Ignored);
3409 return getConstantFP(FPV, DL, VT);
3414 // Constant fold unary operations with a floating point constant operand.
3415 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
3416 APFloat V = C->getValueAPF(); // make copy
3420 return getConstantFP(V, DL, VT);
3423 return getConstantFP(V, DL, VT);
3425 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
3426 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3427 return getConstantFP(V, DL, VT);
3431 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
3432 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3433 return getConstantFP(V, DL, VT);
3437 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
3438 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3439 return getConstantFP(V, DL, VT);
3442 case ISD::FP_EXTEND: {
3444 // This can return overflow, underflow, or inexact; we don't care.
3445 // FIXME need to be more flexible about rounding mode.
3446 (void)V.convert(EVTToAPFloatSemantics(VT),
3447 APFloat::rmNearestTiesToEven, &ignored);
3448 return getConstantFP(V, DL, VT);
3450 case ISD::FP_TO_SINT:
3451 case ISD::FP_TO_UINT: {
3453 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
3454 // FIXME need to be more flexible about rounding mode.
3455 APFloat::opStatus s =
3456 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
3457 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
3459 return getConstant(IntVal, DL, VT);
3462 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3463 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3464 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3465 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3466 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3467 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3469 case ISD::FP_TO_FP16: {
3471 // This can return overflow, underflow, or inexact; we don't care.
3472 // FIXME need to be more flexible about rounding mode.
3473 (void)V.convert(APFloat::IEEEhalf(),
3474 APFloat::rmNearestTiesToEven, &Ignored);
3475 return getConstant(V.bitcastToAPInt(), DL, VT);
3480 // Constant fold unary operations with a vector integer or float operand.
3481 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3482 if (BV->isConstant()) {
3485 // FIXME: Entirely reasonable to perform folding of other unary
3486 // operations here as the need arises.
3493 case ISD::FP_EXTEND:
3494 case ISD::FP_TO_SINT:
3495 case ISD::FP_TO_UINT:
3497 case ISD::UINT_TO_FP:
3498 case ISD::SINT_TO_FP:
3500 case ISD::BITREVERSE:
3503 case ISD::CTLZ_ZERO_UNDEF:
3505 case ISD::CTTZ_ZERO_UNDEF:
3507 SDValue Ops = { Operand };
3508 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3515 unsigned OpOpcode = Operand.getNode()->getOpcode();
3517 case ISD::TokenFactor:
3518 case ISD::MERGE_VALUES:
3519 case ISD::CONCAT_VECTORS:
3520 return Operand; // Factor, merge or concat of one node? No need.
3521 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
3522 case ISD::FP_EXTEND:
3523 assert(VT.isFloatingPoint() &&
3524 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
3525 if (Operand.getValueType() == VT) return Operand; // noop conversion.
3526 assert((!VT.isVector() ||
3527 VT.getVectorNumElements() ==
3528 Operand.getValueType().getVectorNumElements()) &&
3529 "Vector element count mismatch!");
3530 assert(Operand.getValueType().bitsLT(VT) &&
3531 "Invalid fpext node, dst < src!");
3532 if (Operand.isUndef())
3533 return getUNDEF(VT);
3535 case ISD::SIGN_EXTEND:
3536 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3537 "Invalid SIGN_EXTEND!");
3538 if (Operand.getValueType() == VT) return Operand; // noop extension
3539 assert((!VT.isVector() ||
3540 VT.getVectorNumElements() ==
3541 Operand.getValueType().getVectorNumElements()) &&
3542 "Vector element count mismatch!");
3543 assert(Operand.getValueType().bitsLT(VT) &&
3544 "Invalid sext node, dst < src!");
3545 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
3546 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3547 else if (OpOpcode == ISD::UNDEF)
3548 // sext(undef) = 0, because the top bits will all be the same.
3549 return getConstant(0, DL, VT);
3551 case ISD::ZERO_EXTEND:
3552 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3553 "Invalid ZERO_EXTEND!");
3554 if (Operand.getValueType() == VT) return Operand; // noop extension
3555 assert((!VT.isVector() ||
3556 VT.getVectorNumElements() ==
3557 Operand.getValueType().getVectorNumElements()) &&
3558 "Vector element count mismatch!");
3559 assert(Operand.getValueType().bitsLT(VT) &&
3560 "Invalid zext node, dst < src!");
3561 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
3562 return getNode(ISD::ZERO_EXTEND, DL, VT,
3563 Operand.getNode()->getOperand(0));
3564 else if (OpOpcode == ISD::UNDEF)
3565 // zext(undef) = 0, because the top bits will be zero.
3566 return getConstant(0, DL, VT);
3568 case ISD::ANY_EXTEND:
3569 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3570 "Invalid ANY_EXTEND!");
3571 if (Operand.getValueType() == VT) return Operand; // noop extension
3572 assert((!VT.isVector() ||
3573 VT.getVectorNumElements() ==
3574 Operand.getValueType().getVectorNumElements()) &&
3575 "Vector element count mismatch!");
3576 assert(Operand.getValueType().bitsLT(VT) &&
3577 "Invalid anyext node, dst < src!");
3579 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3580 OpOpcode == ISD::ANY_EXTEND)
3581 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
3582 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3583 else if (OpOpcode == ISD::UNDEF)
3584 return getUNDEF(VT);
3586 // (ext (trunx x)) -> x
3587 if (OpOpcode == ISD::TRUNCATE) {
3588 SDValue OpOp = Operand.getNode()->getOperand(0);
3589 if (OpOp.getValueType() == VT)
3594 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3595 "Invalid TRUNCATE!");
3596 if (Operand.getValueType() == VT) return Operand; // noop truncate
3597 assert((!VT.isVector() ||
3598 VT.getVectorNumElements() ==
3599 Operand.getValueType().getVectorNumElements()) &&
3600 "Vector element count mismatch!");
3601 assert(Operand.getValueType().bitsGT(VT) &&
3602 "Invalid truncate node, src < dst!");
3603 if (OpOpcode == ISD::TRUNCATE)
3604 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3605 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3606 OpOpcode == ISD::ANY_EXTEND) {
3607 // If the source is smaller than the dest, we still need an extend.
3608 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
3609 .bitsLT(VT.getScalarType()))
3610 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3611 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
3612 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3613 return Operand.getNode()->getOperand(0);
3615 if (OpOpcode == ISD::UNDEF)
3616 return getUNDEF(VT);
3619 assert(VT.isInteger() && VT == Operand.getValueType() &&
3621 if (OpOpcode == ISD::UNDEF)
3622 return getUNDEF(VT);
3625 assert(VT.isInteger() && VT == Operand.getValueType() &&
3627 assert((VT.getScalarSizeInBits() % 16 == 0) &&
3628 "BSWAP types must be a multiple of 16 bits!");
3629 if (OpOpcode == ISD::UNDEF)
3630 return getUNDEF(VT);
3632 case ISD::BITREVERSE:
3633 assert(VT.isInteger() && VT == Operand.getValueType() &&
3634 "Invalid BITREVERSE!");
3635 if (OpOpcode == ISD::UNDEF)
3636 return getUNDEF(VT);
3639 // Basic sanity checking.
3640 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
3641 "Cannot BITCAST between types of different sizes!");
3642 if (VT == Operand.getValueType()) return Operand; // noop conversion.
3643 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
3644 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
3645 if (OpOpcode == ISD::UNDEF)
3646 return getUNDEF(VT);
3648 case ISD::SCALAR_TO_VECTOR:
3649 assert(VT.isVector() && !Operand.getValueType().isVector() &&
3650 (VT.getVectorElementType() == Operand.getValueType() ||
3651 (VT.getVectorElementType().isInteger() &&
3652 Operand.getValueType().isInteger() &&
3653 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
3654 "Illegal SCALAR_TO_VECTOR node!");
3655 if (OpOpcode == ISD::UNDEF)
3656 return getUNDEF(VT);
3657 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
3658 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
3659 isa<ConstantSDNode>(Operand.getOperand(1)) &&
3660 Operand.getConstantOperandVal(1) == 0 &&
3661 Operand.getOperand(0).getValueType() == VT)
3662 return Operand.getOperand(0);
3665 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
3666 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
3667 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags?
3668 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
3669 Operand.getNode()->getOperand(0),
3670 Operand.getNode()->getFlags());
3671 if (OpOpcode == ISD::FNEG) // --X -> X
3672 return Operand.getNode()->getOperand(0);
3675 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
3676 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
3681 SDVTList VTs = getVTList(VT);
3682 SDValue Ops[] = {Operand};
3683 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
3684 FoldingSetNodeID ID;
3685 AddNodeIDNode(ID, Opcode, VTs, Ops);
3687 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
3688 E->intersectFlagsWith(Flags);
3689 return SDValue(E, 0);
3692 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3694 createOperands(N, Ops);
3695 CSEMap.InsertNode(N, IP);
3697 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3698 createOperands(N, Ops);
3702 return SDValue(N, 0);
3705 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
3708 case ISD::ADD: return std::make_pair(C1 + C2, true);
3709 case ISD::SUB: return std::make_pair(C1 - C2, true);
3710 case ISD::MUL: return std::make_pair(C1 * C2, true);
3711 case ISD::AND: return std::make_pair(C1 & C2, true);
3712 case ISD::OR: return std::make_pair(C1 | C2, true);
3713 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
3714 case ISD::SHL: return std::make_pair(C1 << C2, true);
3715 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
3716 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
3717 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
3718 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
3719 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
3720 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
3721 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
3722 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
3724 if (!C2.getBoolValue())
3726 return std::make_pair(C1.udiv(C2), true);
3728 if (!C2.getBoolValue())
3730 return std::make_pair(C1.urem(C2), true);
3732 if (!C2.getBoolValue())
3734 return std::make_pair(C1.sdiv(C2), true);
3736 if (!C2.getBoolValue())
3738 return std::make_pair(C1.srem(C2), true);
3740 return std::make_pair(APInt(1, 0), false);
3743 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3744 EVT VT, const ConstantSDNode *Cst1,
3745 const ConstantSDNode *Cst2) {
3746 if (Cst1->isOpaque() || Cst2->isOpaque())
3749 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
3750 Cst2->getAPIntValue());
3753 return getConstant(Folded.first, DL, VT);
3756 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
3757 const GlobalAddressSDNode *GA,
3759 if (GA->getOpcode() != ISD::GlobalAddress)
3761 if (!TLI->isOffsetFoldingLegal(GA))
3763 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
3766 int64_t Offset = Cst2->getSExtValue();
3768 case ISD::ADD: break;
3769 case ISD::SUB: Offset = -uint64_t(Offset); break;
3770 default: return SDValue();
3772 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
3773 GA->getOffset() + uint64_t(Offset));
3776 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
3782 // If a divisor is zero/undef or any element of a divisor vector is
3783 // zero/undef, the whole op is undef.
3784 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
3785 SDValue Divisor = Ops[1];
3786 if (Divisor.isUndef() || isNullConstant(Divisor))
3789 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
3790 any_of(Divisor->op_values(),
3791 [](SDValue V) { return V.isUndef() || isNullConstant(V); });
3792 // TODO: Handle signed overflow.
3794 // TODO: Handle oversized shifts.
3800 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3801 EVT VT, SDNode *Cst1,
3803 // If the opcode is a target-specific ISD node, there's nothing we can
3804 // do here and the operand rules may not line up with the below, so
3806 if (Opcode >= ISD::BUILTIN_OP_END)
3809 if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)}))
3810 return getUNDEF(VT);
3812 // Handle the case of two scalars.
3813 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
3814 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
3815 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
3816 assert((!Folded || !VT.isVector()) &&
3817 "Can't fold vectors ops with scalar operands");
3822 // fold (add Sym, c) -> Sym+c
3823 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
3824 return FoldSymbolOffset(Opcode, VT, GA, Cst2);
3825 if (isCommutativeBinOp(Opcode))
3826 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
3827 return FoldSymbolOffset(Opcode, VT, GA, Cst1);
3829 // For vectors extract each constant element into Inputs so we can constant
3830 // fold them individually.
3831 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
3832 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
3836 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
3838 EVT SVT = VT.getScalarType();
3839 SmallVector<SDValue, 4> Outputs;
3840 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
3841 SDValue V1 = BV1->getOperand(I);
3842 SDValue V2 = BV2->getOperand(I);
3844 // Avoid BUILD_VECTOR nodes that perform implicit truncation.
3845 // FIXME: This is valid and could be handled by truncation.
3846 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
3849 // Fold one vector element.
3850 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
3852 // Scalar folding only succeeded if the result is a constant or UNDEF.
3853 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3854 ScalarResult.getOpcode() != ISD::ConstantFP)
3856 Outputs.push_back(ScalarResult);
3859 assert(VT.getVectorNumElements() == Outputs.size() &&
3860 "Vector size mismatch!");
3862 // We may have a vector type but a scalar result. Create a splat.
3863 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
3865 // Build a big vector out of the scalar elements we generated.
3866 return getBuildVector(VT, SDLoc(), Outputs);
3869 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
3870 const SDLoc &DL, EVT VT,
3871 ArrayRef<SDValue> Ops,
3872 const SDNodeFlags Flags) {
3873 // If the opcode is a target-specific ISD node, there's nothing we can
3874 // do here and the operand rules may not line up with the below, so
3876 if (Opcode >= ISD::BUILTIN_OP_END)
3879 if (isUndef(Opcode, Ops))
3880 return getUNDEF(VT);
3882 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
3886 unsigned NumElts = VT.getVectorNumElements();
3888 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
3889 return !Op.getValueType().isVector() ||
3890 Op.getValueType().getVectorNumElements() == NumElts;
3893 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
3894 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
3895 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
3896 (BV && BV->isConstant());
3899 // All operands must be vector types with the same number of elements as
3900 // the result type and must be either UNDEF or a build vector of constant
3901 // or UNDEF scalars.
3902 if (!all_of(Ops, IsConstantBuildVectorOrUndef) ||
3903 !all_of(Ops, IsScalarOrSameVectorSize))
3906 // If we are comparing vectors, then the result needs to be a i1 boolean
3907 // that is then sign-extended back to the legal result type.
3908 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
3910 // Find legal integer scalar type for constant promotion and
3911 // ensure that its scalar size is at least as large as source.
3912 EVT LegalSVT = VT.getScalarType();
3913 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
3914 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3915 if (LegalSVT.bitsLT(VT.getScalarType()))
3919 // Constant fold each scalar lane separately.
3920 SmallVector<SDValue, 4> ScalarResults;
3921 for (unsigned i = 0; i != NumElts; i++) {
3922 SmallVector<SDValue, 4> ScalarOps;
3923 for (SDValue Op : Ops) {
3924 EVT InSVT = Op.getValueType().getScalarType();
3925 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
3927 // We've checked that this is UNDEF or a constant of some kind.
3929 ScalarOps.push_back(getUNDEF(InSVT));
3931 ScalarOps.push_back(Op);
3935 SDValue ScalarOp = InBV->getOperand(i);
3936 EVT ScalarVT = ScalarOp.getValueType();
3938 // Build vector (integer) scalar operands may need implicit
3939 // truncation - do this before constant folding.
3940 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
3941 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
3943 ScalarOps.push_back(ScalarOp);
3946 // Constant fold the scalar operands.
3947 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
3949 // Legalize the (integer) scalar constant if necessary.
3950 if (LegalSVT != SVT)
3951 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
3953 // Scalar folding only succeeded if the result is a constant or UNDEF.
3954 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3955 ScalarResult.getOpcode() != ISD::ConstantFP)
3957 ScalarResults.push_back(ScalarResult);
3960 return getBuildVector(VT, DL, ScalarResults);
3963 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3964 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
3965 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3966 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3967 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3968 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3970 // Canonicalize constant to RHS if commutative.
3971 if (isCommutativeBinOp(Opcode)) {
3973 std::swap(N1C, N2C);
3975 } else if (N1CFP && !N2CFP) {
3976 std::swap(N1CFP, N2CFP);
3983 case ISD::TokenFactor:
3984 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
3985 N2.getValueType() == MVT::Other && "Invalid token factor!");
3986 // Fold trivial token factors.
3987 if (N1.getOpcode() == ISD::EntryToken) return N2;
3988 if (N2.getOpcode() == ISD::EntryToken) return N1;
3989 if (N1 == N2) return N1;
3991 case ISD::CONCAT_VECTORS: {
3992 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
3993 SDValue Ops[] = {N1, N2};
3994 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
3999 assert(VT.isInteger() && "This operator does not apply to FP types!");
4000 assert(N1.getValueType() == N2.getValueType() &&
4001 N1.getValueType() == VT && "Binary operator types must match!");
4002 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
4003 // worth handling here.
4004 if (N2C && N2C->isNullValue())
4006 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
4013 assert(VT.isInteger() && "This operator does not apply to FP types!");
4014 assert(N1.getValueType() == N2.getValueType() &&
4015 N1.getValueType() == VT && "Binary operator types must match!");
4016 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
4017 // it's worth handling here.
4018 if (N2C && N2C->isNullValue())
4032 assert(VT.isInteger() && "This operator does not apply to FP types!");
4033 assert(N1.getValueType() == N2.getValueType() &&
4034 N1.getValueType() == VT && "Binary operator types must match!");
4041 if (getTarget().Options.UnsafeFPMath) {
4042 if (Opcode == ISD::FADD) {
4044 if (N2CFP && N2CFP->getValueAPF().isZero())
4046 } else if (Opcode == ISD::FSUB) {
4048 if (N2CFP && N2CFP->getValueAPF().isZero())
4050 } else if (Opcode == ISD::FMUL) {
4052 if (N2CFP && N2CFP->isZero())
4055 if (N2CFP && N2CFP->isExactlyValue(1.0))
4059 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4060 assert(N1.getValueType() == N2.getValueType() &&
4061 N1.getValueType() == VT && "Binary operator types must match!");
4063 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
4064 assert(N1.getValueType() == VT &&
4065 N1.getValueType().isFloatingPoint() &&
4066 N2.getValueType().isFloatingPoint() &&
4067 "Invalid FCOPYSIGN!");
4074 assert(VT == N1.getValueType() &&
4075 "Shift operators return type must be the same as their first arg");
4076 assert(VT.isInteger() && N2.getValueType().isInteger() &&
4077 "Shifts only work on integers");
4078 assert((!VT.isVector() || VT == N2.getValueType()) &&
4079 "Vector shift amounts must be in the same as their first arg");
4080 // Verify that the shift amount VT is bit enough to hold valid shift
4081 // amounts. This catches things like trying to shift an i1024 value by an
4082 // i8, which is easy to fall into in generic code that uses
4083 // TLI.getShiftAmount().
4084 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4085 "Invalid use of small shift amount with oversized value!");
4087 // Always fold shifts of i1 values so the code generator doesn't need to
4088 // handle them. Since we know the size of the shift has to be less than the
4089 // size of the value, the shift/rotate count is guaranteed to be zero.
4092 if (N2C && N2C->isNullValue())
4095 case ISD::FP_ROUND_INREG: {
4096 EVT EVT = cast<VTSDNode>(N2)->getVT();
4097 assert(VT == N1.getValueType() && "Not an inreg round!");
4098 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4099 "Cannot FP_ROUND_INREG integer types");
4100 assert(EVT.isVector() == VT.isVector() &&
4101 "FP_ROUND_INREG type should be vector iff the operand "
4103 assert((!EVT.isVector() ||
4104 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4105 "Vector element counts must match in FP_ROUND_INREG");
4106 assert(EVT.bitsLE(VT) && "Not rounding down!");
4108 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
4112 assert(VT.isFloatingPoint() &&
4113 N1.getValueType().isFloatingPoint() &&
4114 VT.bitsLE(N1.getValueType()) &&
4115 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4116 "Invalid FP_ROUND!");
4117 if (N1.getValueType() == VT) return N1; // noop conversion.
4119 case ISD::AssertSext:
4120 case ISD::AssertZext: {
4121 EVT EVT = cast<VTSDNode>(N2)->getVT();
4122 assert(VT == N1.getValueType() && "Not an inreg extend!");
4123 assert(VT.isInteger() && EVT.isInteger() &&
4124 "Cannot *_EXTEND_INREG FP types");
4125 assert(!EVT.isVector() &&
4126 "AssertSExt/AssertZExt type should be the vector element type "
4127 "rather than the vector type!");
4128 assert(EVT.bitsLE(VT) && "Not extending!");
4129 if (VT == EVT) return N1; // noop assertion.
4132 case ISD::SIGN_EXTEND_INREG: {
4133 EVT EVT = cast<VTSDNode>(N2)->getVT();
4134 assert(VT == N1.getValueType() && "Not an inreg extend!");
4135 assert(VT.isInteger() && EVT.isInteger() &&
4136 "Cannot *_EXTEND_INREG FP types");
4137 assert(EVT.isVector() == VT.isVector() &&
4138 "SIGN_EXTEND_INREG type should be vector iff the operand "
4140 assert((!EVT.isVector() ||
4141 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4142 "Vector element counts must match in SIGN_EXTEND_INREG");
4143 assert(EVT.bitsLE(VT) && "Not extending!");
4144 if (EVT == VT) return N1; // Not actually extending
4146 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4147 unsigned FromBits = EVT.getScalarSizeInBits();
4148 Val <<= Val.getBitWidth() - FromBits;
4149 Val.ashrInPlace(Val.getBitWidth() - FromBits);
4150 return getConstant(Val, DL, ConstantVT);
4154 const APInt &Val = N1C->getAPIntValue();
4155 return SignExtendInReg(Val, VT);
4157 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4158 SmallVector<SDValue, 8> Ops;
4159 llvm::EVT OpVT = N1.getOperand(0).getValueType();
4160 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4161 SDValue Op = N1.getOperand(i);
4163 Ops.push_back(getUNDEF(OpVT));
4166 ConstantSDNode *C = cast<ConstantSDNode>(Op);
4167 APInt Val = C->getAPIntValue();
4168 Ops.push_back(SignExtendInReg(Val, OpVT));
4170 return getBuildVector(VT, DL, Ops);
4174 case ISD::EXTRACT_VECTOR_ELT:
4175 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4177 return getUNDEF(VT);
4179 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4180 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4181 return getUNDEF(VT);
4183 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4184 // expanding copies of large vectors from registers.
4186 N1.getOpcode() == ISD::CONCAT_VECTORS &&
4187 N1.getNumOperands() > 0) {
4189 N1.getOperand(0).getValueType().getVectorNumElements();
4190 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4191 N1.getOperand(N2C->getZExtValue() / Factor),
4192 getConstant(N2C->getZExtValue() % Factor, DL,
4193 N2.getValueType()));
4196 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4197 // expanding large vector constants.
4198 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4199 SDValue Elt = N1.getOperand(N2C->getZExtValue());
4201 if (VT != Elt.getValueType())
4202 // If the vector element type is not legal, the BUILD_VECTOR operands
4203 // are promoted and implicitly truncated, and the result implicitly
4204 // extended. Make that explicit here.
4205 Elt = getAnyExtOrTrunc(Elt, DL, VT);
4210 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
4211 // operations are lowered to scalars.
4212 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
4213 // If the indices are the same, return the inserted element else
4214 // if the indices are known different, extract the element from
4215 // the original vector.
4216 SDValue N1Op2 = N1.getOperand(2);
4217 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
4219 if (N1Op2C && N2C) {
4220 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
4221 if (VT == N1.getOperand(1).getValueType())
4222 return N1.getOperand(1);
4224 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
4227 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
4231 case ISD::EXTRACT_ELEMENT:
4232 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
4233 assert(!N1.getValueType().isVector() && !VT.isVector() &&
4234 (N1.getValueType().isInteger() == VT.isInteger()) &&
4235 N1.getValueType() != VT &&
4236 "Wrong types for EXTRACT_ELEMENT!");
4238 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
4239 // 64-bit integers into 32-bit parts. Instead of building the extract of
4240 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
4241 if (N1.getOpcode() == ISD::BUILD_PAIR)
4242 return N1.getOperand(N2C->getZExtValue());
4244 // EXTRACT_ELEMENT of a constant int is also very common.
4246 unsigned ElementSize = VT.getSizeInBits();
4247 unsigned Shift = ElementSize * N2C->getZExtValue();
4248 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
4249 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
4252 case ISD::EXTRACT_SUBVECTOR:
4253 if (VT.isSimple() && N1.getValueType().isSimple()) {
4254 assert(VT.isVector() && N1.getValueType().isVector() &&
4255 "Extract subvector VTs must be a vectors!");
4256 assert(VT.getVectorElementType() ==
4257 N1.getValueType().getVectorElementType() &&
4258 "Extract subvector VTs must have the same element type!");
4259 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
4260 "Extract subvector must be from larger vector to smaller vector!");
4263 assert((VT.getVectorNumElements() + N2C->getZExtValue()
4264 <= N1.getValueType().getVectorNumElements())
4265 && "Extract subvector overflow!");
4268 // Trivial extraction.
4269 if (VT.getSimpleVT() == N1.getSimpleValueType())
4272 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
4274 return getUNDEF(VT);
4276 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
4277 // the concat have the same type as the extract.
4278 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
4279 N1.getNumOperands() > 0 &&
4280 VT == N1.getOperand(0).getValueType()) {
4281 unsigned Factor = VT.getVectorNumElements();
4282 return N1.getOperand(N2C->getZExtValue() / Factor);
4285 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
4286 // during shuffle legalization.
4287 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
4288 VT == N1.getOperand(1).getValueType())
4289 return N1.getOperand(1);
4294 // Perform trivial constant folding.
4296 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
4299 // Constant fold FP operations.
4300 bool HasFPExceptions = TLI->hasFloatingPointExceptions();
4303 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
4304 APFloat::opStatus s;
4307 s = V1.add(V2, APFloat::rmNearestTiesToEven);
4308 if (!HasFPExceptions || s != APFloat::opInvalidOp)
4309 return getConstantFP(V1, DL, VT);
4312 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
4313 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4314 return getConstantFP(V1, DL, VT);
4317 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
4318 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4319 return getConstantFP(V1, DL, VT);
4322 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
4323 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4324 s!=APFloat::opDivByZero)) {
4325 return getConstantFP(V1, DL, VT);
4330 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4331 s!=APFloat::opDivByZero)) {
4332 return getConstantFP(V1, DL, VT);
4335 case ISD::FCOPYSIGN:
4337 return getConstantFP(V1, DL, VT);
4342 if (Opcode == ISD::FP_ROUND) {
4343 APFloat V = N1CFP->getValueAPF(); // make copy
4345 // This can return overflow, underflow, or inexact; we don't care.
4346 // FIXME need to be more flexible about rounding mode.
4347 (void)V.convert(EVTToAPFloatSemantics(VT),
4348 APFloat::rmNearestTiesToEven, &ignored);
4349 return getConstantFP(V, DL, VT);
4353 // Canonicalize an UNDEF to the RHS, even over a constant.
4355 if (isCommutativeBinOp(Opcode)) {
4359 case ISD::FP_ROUND_INREG:
4360 case ISD::SIGN_EXTEND_INREG:
4366 return N1; // fold op(undef, arg2) -> undef
4374 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
4375 // For vectors, we can't easily build an all zero vector, just return
4382 // Fold a bunch of operators when the RHS is undef.
4387 // Handle undef ^ undef -> 0 special case. This is a common
4389 return getConstant(0, DL, VT);
4399 return N2; // fold op(arg1, undef) -> undef
4405 if (getTarget().Options.UnsafeFPMath)
4413 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
4414 // For vectors, we can't easily build an all zero vector, just return
4419 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
4420 // For vectors, we can't easily build an all one vector, just return
4428 // Memoize this node if possible.
4430 SDVTList VTs = getVTList(VT);
4431 SDValue Ops[] = {N1, N2};
4432 if (VT != MVT::Glue) {
4433 FoldingSetNodeID ID;
4434 AddNodeIDNode(ID, Opcode, VTs, Ops);
4436 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4437 E->intersectFlagsWith(Flags);
4438 return SDValue(E, 0);
4441 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4443 createOperands(N, Ops);
4444 CSEMap.InsertNode(N, IP);
4446 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4447 createOperands(N, Ops);
4451 return SDValue(N, 0);
4454 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4455 SDValue N1, SDValue N2, SDValue N3) {
4456 // Perform various simplifications.
4459 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4460 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4461 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
4462 if (N1CFP && N2CFP && N3CFP) {
4463 APFloat V1 = N1CFP->getValueAPF();
4464 const APFloat &V2 = N2CFP->getValueAPF();
4465 const APFloat &V3 = N3CFP->getValueAPF();
4466 APFloat::opStatus s =
4467 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
4468 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
4469 return getConstantFP(V1, DL, VT);
4473 case ISD::CONCAT_VECTORS: {
4474 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4475 SDValue Ops[] = {N1, N2, N3};
4476 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4481 // Use FoldSetCC to simplify SETCC's.
4482 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
4484 // Vector constant folding.
4485 SDValue Ops[] = {N1, N2, N3};
4486 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4491 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
4492 if (N1C->getZExtValue())
4493 return N2; // select true, X, Y -> X
4494 return N3; // select false, X, Y -> Y
4497 if (N2 == N3) return N2; // select C, X, X -> X
4499 case ISD::VECTOR_SHUFFLE:
4500 llvm_unreachable("should use getVectorShuffle constructor!");
4501 case ISD::INSERT_VECTOR_ELT: {
4502 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
4503 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
4504 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4505 return getUNDEF(VT);
4508 case ISD::INSERT_SUBVECTOR: {
4510 if (VT.isSimple() && N1.getValueType().isSimple()
4511 && N2.getValueType().isSimple()) {
4512 assert(VT.isVector() && N1.getValueType().isVector() &&
4513 N2.getValueType().isVector() &&
4514 "Insert subvector VTs must be a vectors");
4515 assert(VT == N1.getValueType() &&
4516 "Dest and insert subvector source types must match!");
4517 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
4518 "Insert subvector must be from smaller vector to larger vector!");
4519 if (isa<ConstantSDNode>(Index)) {
4520 assert((N2.getValueType().getVectorNumElements() +
4521 cast<ConstantSDNode>(Index)->getZExtValue()
4522 <= VT.getVectorNumElements())
4523 && "Insert subvector overflow!");
4526 // Trivial insertion.
4527 if (VT.getSimpleVT() == N2.getSimpleValueType())
4533 // Fold bit_convert nodes from a type to themselves.
4534 if (N1.getValueType() == VT)
4539 // Memoize node if it doesn't produce a flag.
4541 SDVTList VTs = getVTList(VT);
4542 SDValue Ops[] = {N1, N2, N3};
4543 if (VT != MVT::Glue) {
4544 FoldingSetNodeID ID;
4545 AddNodeIDNode(ID, Opcode, VTs, Ops);
4547 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4548 return SDValue(E, 0);
4550 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4551 createOperands(N, Ops);
4552 CSEMap.InsertNode(N, IP);
4554 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4555 createOperands(N, Ops);
4559 return SDValue(N, 0);
4562 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4563 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
4564 SDValue Ops[] = { N1, N2, N3, N4 };
4565 return getNode(Opcode, DL, VT, Ops);
4568 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4569 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
4571 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4572 return getNode(Opcode, DL, VT, Ops);
4575 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
4576 /// the incoming stack arguments to be loaded from the stack.
4577 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
4578 SmallVector<SDValue, 8> ArgChains;
4580 // Include the original chain at the beginning of the list. When this is
4581 // used by target LowerCall hooks, this helps legalize find the
4582 // CALLSEQ_BEGIN node.
4583 ArgChains.push_back(Chain);
4585 // Add a chain value for each stack argument.
4586 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
4587 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
4588 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4589 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4590 if (FI->getIndex() < 0)
4591 ArgChains.push_back(SDValue(L, 1));
4593 // Build a tokenfactor for all the chains.
4594 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4597 /// getMemsetValue - Vectorized representation of the memset value
4599 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
4601 assert(!Value.isUndef());
4603 unsigned NumBits = VT.getScalarSizeInBits();
4604 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4605 assert(C->getAPIntValue().getBitWidth() == 8);
4606 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
4608 return DAG.getConstant(Val, dl, VT);
4609 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
4613 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
4614 EVT IntVT = VT.getScalarType();
4615 if (!IntVT.isInteger())
4616 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
4618 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
4620 // Use a multiplication with 0x010101... to extend the input to the
4622 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
4623 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
4624 DAG.getConstant(Magic, dl, IntVT));
4627 if (VT != Value.getValueType() && !VT.isInteger())
4628 Value = DAG.getBitcast(VT.getScalarType(), Value);
4629 if (VT != Value.getValueType())
4630 Value = DAG.getSplatBuildVector(VT, dl, Value);
4635 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4636 /// used when a memcpy is turned into a memset when the source is a constant
4638 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
4639 const TargetLowering &TLI, StringRef Str) {
4640 // Handle vector with all elements zero.
4643 return DAG.getConstant(0, dl, VT);
4644 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
4645 return DAG.getConstantFP(0.0, dl, VT);
4646 else if (VT.isVector()) {
4647 unsigned NumElts = VT.getVectorNumElements();
4648 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4649 return DAG.getNode(ISD::BITCAST, dl, VT,
4650 DAG.getConstant(0, dl,
4651 EVT::getVectorVT(*DAG.getContext(),
4654 llvm_unreachable("Expected type!");
4657 assert(!VT.isVector() && "Can't handle vector type here!");
4658 unsigned NumVTBits = VT.getSizeInBits();
4659 unsigned NumVTBytes = NumVTBits / 8;
4660 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
4662 APInt Val(NumVTBits, 0);
4663 if (DAG.getDataLayout().isLittleEndian()) {
4664 for (unsigned i = 0; i != NumBytes; ++i)
4665 Val |= (uint64_t)(unsigned char)Str[i] << i*8;
4667 for (unsigned i = 0; i != NumBytes; ++i)
4668 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
4671 // If the "cost" of materializing the integer immediate is less than the cost
4672 // of a load, then it is cost effective to turn the load into the immediate.
4673 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
4674 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
4675 return DAG.getConstant(Val, dl, VT);
4676 return SDValue(nullptr, 0);
4679 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
4681 EVT VT = Base.getValueType();
4682 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
4685 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
4687 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
4688 uint64_t SrcDelta = 0;
4689 GlobalAddressSDNode *G = nullptr;
4690 if (Src.getOpcode() == ISD::GlobalAddress)
4691 G = cast<GlobalAddressSDNode>(Src);
4692 else if (Src.getOpcode() == ISD::ADD &&
4693 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4694 Src.getOperand(1).getOpcode() == ISD::Constant) {
4695 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
4696 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
4701 return getConstantStringInfo(G->getGlobal(), Str,
4702 SrcDelta + G->getOffset(), false);
4705 /// Determines the optimal series of memory ops to replace the memset / memcpy.
4706 /// Return true if the number of memory ops is below the threshold (Limit).
4707 /// It returns the types of the sequence of memory ops to perform
4708 /// memset / memcpy by reference.
4709 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
4710 unsigned Limit, uint64_t Size,
4711 unsigned DstAlign, unsigned SrcAlign,
4716 unsigned DstAS, unsigned SrcAS,
4718 const TargetLowering &TLI) {
4719 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
4720 "Expecting memcpy / memset source to meet alignment requirement!");
4721 // If 'SrcAlign' is zero, that means the memory operation does not need to
4722 // load the value, i.e. memset or memcpy from constant string. Otherwise,
4723 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
4724 // is the specified alignment of the memory operation. If it is zero, that
4725 // means it's possible to change the alignment of the destination.
4726 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
4727 // not need to be loaded.
4728 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
4729 IsMemset, ZeroMemset, MemcpyStrSrc,
4730 DAG.getMachineFunction());
4732 if (VT == MVT::Other) {
4733 if (DstAlign >= DAG.getDataLayout().getPointerPrefAlignment(DstAS) ||
4734 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign)) {
4735 VT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
4737 switch (DstAlign & 7) {
4738 case 0: VT = MVT::i64; break;
4739 case 4: VT = MVT::i32; break;
4740 case 2: VT = MVT::i16; break;
4741 default: VT = MVT::i8; break;
4746 while (!TLI.isTypeLegal(LVT))
4747 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
4748 assert(LVT.isInteger());
4754 unsigned NumMemOps = 0;
4756 unsigned VTSize = VT.getSizeInBits() / 8;
4757 while (VTSize > Size) {
4758 // For now, only use non-vector load / store's for the left-over pieces.
4763 if (VT.isVector() || VT.isFloatingPoint()) {
4764 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
4765 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
4766 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
4768 else if (NewVT == MVT::i64 &&
4769 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
4770 TLI.isSafeMemOpType(MVT::f64)) {
4771 // i64 is usually not legal on 32-bit targets, but f64 may be.
4779 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
4780 if (NewVT == MVT::i8)
4782 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
4784 NewVTSize = NewVT.getSizeInBits() / 8;
4786 // If the new VT cannot cover all of the remaining bits, then consider
4787 // issuing a (or a pair of) unaligned and overlapping load / store.
4788 // FIXME: Only does this for 64-bit or more since we don't have proper
4789 // cost model for unaligned load / store.
4791 if (NumMemOps && AllowOverlap &&
4792 VTSize >= 8 && NewVTSize < Size &&
4793 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
4801 if (++NumMemOps > Limit)
4804 MemOps.push_back(VT);
4811 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
4812 // On Darwin, -Os means optimize for size without hurting performance, so
4813 // only really optimize for size when -Oz (MinSize) is used.
4814 if (MF.getTarget().getTargetTriple().isOSDarwin())
4815 return MF.getFunction()->optForMinSize();
4816 return MF.getFunction()->optForSize();
4819 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4820 SDValue Chain, SDValue Dst, SDValue Src,
4821 uint64_t Size, unsigned Align,
4822 bool isVol, bool AlwaysInline,
4823 MachinePointerInfo DstPtrInfo,
4824 MachinePointerInfo SrcPtrInfo) {
4825 // Turn a memcpy of undef to nop.
4829 // Expand memcpy to a series of load and store ops if the size operand falls
4830 // below a certain threshold.
4831 // TODO: In the AlwaysInline case, if the size is big then generate a loop
4832 // rather than maybe a humongous number of loads and stores.
4833 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4834 std::vector<EVT> MemOps;
4835 bool DstAlignCanChange = false;
4836 MachineFunction &MF = DAG.getMachineFunction();
4837 MachineFrameInfo &MFI = MF.getFrameInfo();
4838 bool OptSize = shouldLowerMemFuncForSize(MF);
4839 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4840 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4841 DstAlignCanChange = true;
4842 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4843 if (Align > SrcAlign)
4846 bool CopyFromStr = isMemSrcFromString(Src, Str);
4847 bool isZeroStr = CopyFromStr && Str.empty();
4848 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4850 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4851 (DstAlignCanChange ? 0 : Align),
4852 (isZeroStr ? 0 : SrcAlign),
4853 false, false, CopyFromStr, true,
4854 DstPtrInfo.getAddrSpace(),
4855 SrcPtrInfo.getAddrSpace(),
4859 if (DstAlignCanChange) {
4860 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4861 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4863 // Don't promote to an alignment that would require dynamic stack
4865 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4866 if (!TRI->needsStackRealignment(MF))
4867 while (NewAlign > Align &&
4868 DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign))
4871 if (NewAlign > Align) {
4872 // Give the stack frame object a larger alignment if needed.
4873 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4874 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4879 MachineMemOperand::Flags MMOFlags =
4880 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4881 SmallVector<SDValue, 8> OutChains;
4882 unsigned NumMemOps = MemOps.size();
4883 uint64_t SrcOff = 0, DstOff = 0;
4884 for (unsigned i = 0; i != NumMemOps; ++i) {
4886 unsigned VTSize = VT.getSizeInBits() / 8;
4887 SDValue Value, Store;
4889 if (VTSize > Size) {
4890 // Issuing an unaligned load / store pair that overlaps with the previous
4891 // pair. Adjust the offset accordingly.
4892 assert(i == NumMemOps-1 && i != 0);
4893 SrcOff -= VTSize - Size;
4894 DstOff -= VTSize - Size;
4898 (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
4899 // It's unlikely a store of a vector immediate can be done in a single
4900 // instruction. It would require a load from a constantpool first.
4901 // We only handle zero vectors here.
4902 // FIXME: Handle other cases where store of vector immediate is done in
4903 // a single instruction.
4904 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
4905 if (Value.getNode())
4906 Store = DAG.getStore(Chain, dl, Value,
4907 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4908 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
4911 if (!Store.getNode()) {
4912 // The type might not be legal for the target. This should only happen
4913 // if the type is smaller than a legal type, as on PPC, so the right
4914 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
4915 // to Load/Store if NVT==VT.
4916 // FIXME does the case above also need this?
4917 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4918 assert(NVT.bitsGE(VT));
4919 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
4920 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4921 SrcPtrInfo.getWithOffset(SrcOff), VT,
4922 MinAlign(SrcAlign, SrcOff), MMOFlags);
4923 OutChains.push_back(Value.getValue(1));
4924 Store = DAG.getTruncStore(
4925 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4926 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
4928 OutChains.push_back(Store);
4934 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4937 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4938 SDValue Chain, SDValue Dst, SDValue Src,
4939 uint64_t Size, unsigned Align,
4940 bool isVol, bool AlwaysInline,
4941 MachinePointerInfo DstPtrInfo,
4942 MachinePointerInfo SrcPtrInfo) {
4943 // Turn a memmove of undef to nop.
4947 // Expand memmove to a series of load and store ops if the size operand falls
4948 // below a certain threshold.
4949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4950 std::vector<EVT> MemOps;
4951 bool DstAlignCanChange = false;
4952 MachineFunction &MF = DAG.getMachineFunction();
4953 MachineFrameInfo &MFI = MF.getFrameInfo();
4954 bool OptSize = shouldLowerMemFuncForSize(MF);
4955 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4956 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
4957 DstAlignCanChange = true;
4958 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4959 if (Align > SrcAlign)
4961 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
4963 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4964 (DstAlignCanChange ? 0 : Align), SrcAlign,
4965 false, false, false, false,
4966 DstPtrInfo.getAddrSpace(),
4967 SrcPtrInfo.getAddrSpace(),
4971 if (DstAlignCanChange) {
4972 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4973 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4974 if (NewAlign > Align) {
4975 // Give the stack frame object a larger alignment if needed.
4976 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
4977 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
4982 MachineMemOperand::Flags MMOFlags =
4983 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4984 uint64_t SrcOff = 0, DstOff = 0;
4985 SmallVector<SDValue, 8> LoadValues;
4986 SmallVector<SDValue, 8> LoadChains;
4987 SmallVector<SDValue, 8> OutChains;
4988 unsigned NumMemOps = MemOps.size();
4989 for (unsigned i = 0; i < NumMemOps; i++) {
4991 unsigned VTSize = VT.getSizeInBits() / 8;
4995 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4996 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, MMOFlags);
4997 LoadValues.push_back(Value);
4998 LoadChains.push_back(Value.getValue(1));
5001 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5003 for (unsigned i = 0; i < NumMemOps; i++) {
5005 unsigned VTSize = VT.getSizeInBits() / 8;
5008 Store = DAG.getStore(Chain, dl, LoadValues[i],
5009 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5010 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5011 OutChains.push_back(Store);
5015 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5018 /// \brief Lower the call to 'memset' intrinsic function into a series of store
5021 /// \param DAG Selection DAG where lowered code is placed.
5022 /// \param dl Link to corresponding IR location.
5023 /// \param Chain Control flow dependency.
5024 /// \param Dst Pointer to destination memory location.
5025 /// \param Src Value of byte to write into the memory.
5026 /// \param Size Number of bytes to write.
5027 /// \param Align Alignment of the destination in bytes.
5028 /// \param isVol True if destination is volatile.
5029 /// \param DstPtrInfo IR information on the memory pointer.
5030 /// \returns New head in the control flow, if lowering was successful, empty
5031 /// SDValue otherwise.
5033 /// The function tries to replace 'llvm.memset' intrinsic with several store
5034 /// operations and value calculation code. This is usually profitable for small
5036 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5037 SDValue Chain, SDValue Dst, SDValue Src,
5038 uint64_t Size, unsigned Align, bool isVol,
5039 MachinePointerInfo DstPtrInfo) {
5040 // Turn a memset of undef to nop.
5044 // Expand memset to a series of load/store ops if the size operand
5045 // falls below a certain threshold.
5046 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5047 std::vector<EVT> MemOps;
5048 bool DstAlignCanChange = false;
5049 MachineFunction &MF = DAG.getMachineFunction();
5050 MachineFrameInfo &MFI = MF.getFrameInfo();
5051 bool OptSize = shouldLowerMemFuncForSize(MF);
5052 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5053 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5054 DstAlignCanChange = true;
5056 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5057 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5058 Size, (DstAlignCanChange ? 0 : Align), 0,
5059 true, IsZeroVal, false, true,
5060 DstPtrInfo.getAddrSpace(), ~0u,
5064 if (DstAlignCanChange) {
5065 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5066 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5067 if (NewAlign > Align) {
5068 // Give the stack frame object a larger alignment if needed.
5069 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5070 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5075 SmallVector<SDValue, 8> OutChains;
5076 uint64_t DstOff = 0;
5077 unsigned NumMemOps = MemOps.size();
5079 // Find the largest store and generate the bit pattern for it.
5080 EVT LargestVT = MemOps[0];
5081 for (unsigned i = 1; i < NumMemOps; i++)
5082 if (MemOps[i].bitsGT(LargestVT))
5083 LargestVT = MemOps[i];
5084 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5086 for (unsigned i = 0; i < NumMemOps; i++) {
5088 unsigned VTSize = VT.getSizeInBits() / 8;
5089 if (VTSize > Size) {
5090 // Issuing an unaligned load / store pair that overlaps with the previous
5091 // pair. Adjust the offset accordingly.
5092 assert(i == NumMemOps-1 && i != 0);
5093 DstOff -= VTSize - Size;
5096 // If this store is smaller than the largest store see whether we can get
5097 // the smaller value for free with a truncate.
5098 SDValue Value = MemSetValue;
5099 if (VT.bitsLT(LargestVT)) {
5100 if (!LargestVT.isVector() && !VT.isVector() &&
5101 TLI.isTruncateFree(LargestVT, VT))
5102 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5104 Value = getMemsetValue(Src, VT, DAG, dl);
5106 assert(Value.getValueType() == VT && "Value with wrong type.");
5107 SDValue Store = DAG.getStore(
5108 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5109 DstPtrInfo.getWithOffset(DstOff), Align,
5110 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5111 OutChains.push_back(Store);
5112 DstOff += VT.getSizeInBits() / 8;
5116 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5119 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5121 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5122 // pointer operands can be losslessly bitcasted to pointers of address space 0
5123 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5124 report_fatal_error("cannot lower memory intrinsic in address space " +
5129 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
5130 SDValue Src, SDValue Size, unsigned Align,
5131 bool isVol, bool AlwaysInline, bool isTailCall,
5132 MachinePointerInfo DstPtrInfo,
5133 MachinePointerInfo SrcPtrInfo) {
5134 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5136 // Check to see if we should lower the memcpy to loads and stores first.
5137 // For cases within the target-specified limits, this is the best choice.
5138 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5140 // Memcpy with size zero? Just return the original chain.
5141 if (ConstantSize->isNullValue())
5144 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5145 ConstantSize->getZExtValue(),Align,
5146 isVol, false, DstPtrInfo, SrcPtrInfo);
5147 if (Result.getNode())
5151 // Then check to see if we should lower the memcpy with target-specific
5152 // code. If the target chooses to do this, this is the next best.
5154 SDValue Result = TSI->EmitTargetCodeForMemcpy(
5155 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
5156 DstPtrInfo, SrcPtrInfo);
5157 if (Result.getNode())
5161 // If we really need inline code and the target declined to provide it,
5162 // use a (potentially long) sequence of loads and stores.
5164 assert(ConstantSize && "AlwaysInline requires a constant size!");
5165 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5166 ConstantSize->getZExtValue(), Align, isVol,
5167 true, DstPtrInfo, SrcPtrInfo);
5170 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5171 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5173 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
5174 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
5175 // respect volatile, so they may do things like read or write memory
5176 // beyond the given memory regions. But fixing this isn't easy, and most
5177 // people don't care.
5179 // Emit a library call.
5180 TargetLowering::ArgListTy Args;
5181 TargetLowering::ArgListEntry Entry;
5182 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5183 Entry.Node = Dst; Args.push_back(Entry);
5184 Entry.Node = Src; Args.push_back(Entry);
5185 Entry.Node = Size; Args.push_back(Entry);
5186 // FIXME: pass in SDLoc
5187 TargetLowering::CallLoweringInfo CLI(*this);
5190 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
5191 Dst.getValueType().getTypeForEVT(*getContext()),
5192 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
5193 TLI->getPointerTy(getDataLayout())),
5196 .setTailCall(isTailCall);
5198 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5199 return CallResult.second;
5202 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
5203 SDValue Src, SDValue Size, unsigned Align,
5204 bool isVol, bool isTailCall,
5205 MachinePointerInfo DstPtrInfo,
5206 MachinePointerInfo SrcPtrInfo) {
5207 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5209 // Check to see if we should lower the memmove to loads and stores first.
5210 // For cases within the target-specified limits, this is the best choice.
5211 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5213 // Memmove with size zero? Just return the original chain.
5214 if (ConstantSize->isNullValue())
5218 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
5219 ConstantSize->getZExtValue(), Align, isVol,
5220 false, DstPtrInfo, SrcPtrInfo);
5221 if (Result.getNode())
5225 // Then check to see if we should lower the memmove with target-specific
5226 // code. If the target chooses to do this, this is the next best.
5228 SDValue Result = TSI->EmitTargetCodeForMemmove(
5229 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
5230 if (Result.getNode())
5234 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5235 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5237 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
5238 // not be safe. See memcpy above for more details.
5240 // Emit a library call.
5241 TargetLowering::ArgListTy Args;
5242 TargetLowering::ArgListEntry Entry;
5243 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5244 Entry.Node = Dst; Args.push_back(Entry);
5245 Entry.Node = Src; Args.push_back(Entry);
5246 Entry.Node = Size; Args.push_back(Entry);
5247 // FIXME: pass in SDLoc
5248 TargetLowering::CallLoweringInfo CLI(*this);
5251 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
5252 Dst.getValueType().getTypeForEVT(*getContext()),
5253 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
5254 TLI->getPointerTy(getDataLayout())),
5257 .setTailCall(isTailCall);
5259 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5260 return CallResult.second;
5263 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
5264 SDValue Src, SDValue Size, unsigned Align,
5265 bool isVol, bool isTailCall,
5266 MachinePointerInfo DstPtrInfo) {
5267 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5269 // Check to see if we should lower the memset to stores first.
5270 // For cases within the target-specified limits, this is the best choice.
5271 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5273 // Memset with size zero? Just return the original chain.
5274 if (ConstantSize->isNullValue())
5278 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
5279 Align, isVol, DstPtrInfo);
5281 if (Result.getNode())
5285 // Then check to see if we should lower the memset with target-specific
5286 // code. If the target chooses to do this, this is the next best.
5288 SDValue Result = TSI->EmitTargetCodeForMemset(
5289 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
5290 if (Result.getNode())
5294 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5296 // Emit a library call.
5297 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
5298 TargetLowering::ArgListTy Args;
5299 TargetLowering::ArgListEntry Entry;
5300 Entry.Node = Dst; Entry.Ty = IntPtrTy;
5301 Args.push_back(Entry);
5303 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
5304 Args.push_back(Entry);
5306 Entry.Ty = IntPtrTy;
5307 Args.push_back(Entry);
5309 // FIXME: pass in SDLoc
5310 TargetLowering::CallLoweringInfo CLI(*this);
5313 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
5314 Dst.getValueType().getTypeForEVT(*getContext()),
5315 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
5316 TLI->getPointerTy(getDataLayout())),
5319 .setTailCall(isTailCall);
5321 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5322 return CallResult.second;
5325 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5326 SDVTList VTList, ArrayRef<SDValue> Ops,
5327 MachineMemOperand *MMO) {
5328 FoldingSetNodeID ID;
5329 ID.AddInteger(MemVT.getRawBits());
5330 AddNodeIDNode(ID, Opcode, VTList, Ops);
5331 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5333 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5334 cast<AtomicSDNode>(E)->refineAlignment(MMO);
5335 return SDValue(E, 0);
5338 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5339 VTList, MemVT, MMO);
5340 createOperands(N, Ops);
5342 CSEMap.InsertNode(N, IP);
5344 return SDValue(N, 0);
5347 SDValue SelectionDAG::getAtomicCmpSwap(
5348 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
5349 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
5350 unsigned Alignment, AtomicOrdering SuccessOrdering,
5351 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
5352 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5353 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5354 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5356 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5357 Alignment = getEVTAlignment(MemVT);
5359 MachineFunction &MF = getMachineFunction();
5361 // FIXME: Volatile isn't really correct; we should keep track of atomic
5362 // orderings in the memoperand.
5363 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
5364 MachineMemOperand::MOStore;
5365 MachineMemOperand *MMO =
5366 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
5367 AAMDNodes(), nullptr, SynchScope, SuccessOrdering,
5370 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
5373 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
5374 EVT MemVT, SDVTList VTs, SDValue Chain,
5375 SDValue Ptr, SDValue Cmp, SDValue Swp,
5376 MachineMemOperand *MMO) {
5377 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5378 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5379 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5381 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
5382 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5385 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5386 SDValue Chain, SDValue Ptr, SDValue Val,
5387 const Value *PtrVal, unsigned Alignment,
5388 AtomicOrdering Ordering,
5389 SynchronizationScope SynchScope) {
5390 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5391 Alignment = getEVTAlignment(MemVT);
5393 MachineFunction &MF = getMachineFunction();
5394 // An atomic store does not load. An atomic load does not store.
5395 // (An atomicrmw obviously both loads and stores.)
5396 // For now, atomics are considered to be volatile always, and they are
5398 // FIXME: Volatile isn't really correct; we should keep track of atomic
5399 // orderings in the memoperand.
5400 auto Flags = MachineMemOperand::MOVolatile;
5401 if (Opcode != ISD::ATOMIC_STORE)
5402 Flags |= MachineMemOperand::MOLoad;
5403 if (Opcode != ISD::ATOMIC_LOAD)
5404 Flags |= MachineMemOperand::MOStore;
5406 MachineMemOperand *MMO =
5407 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
5408 MemVT.getStoreSize(), Alignment, AAMDNodes(),
5409 nullptr, SynchScope, Ordering);
5411 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
5414 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5415 SDValue Chain, SDValue Ptr, SDValue Val,
5416 MachineMemOperand *MMO) {
5417 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
5418 Opcode == ISD::ATOMIC_LOAD_SUB ||
5419 Opcode == ISD::ATOMIC_LOAD_AND ||
5420 Opcode == ISD::ATOMIC_LOAD_OR ||
5421 Opcode == ISD::ATOMIC_LOAD_XOR ||
5422 Opcode == ISD::ATOMIC_LOAD_NAND ||
5423 Opcode == ISD::ATOMIC_LOAD_MIN ||
5424 Opcode == ISD::ATOMIC_LOAD_MAX ||
5425 Opcode == ISD::ATOMIC_LOAD_UMIN ||
5426 Opcode == ISD::ATOMIC_LOAD_UMAX ||
5427 Opcode == ISD::ATOMIC_SWAP ||
5428 Opcode == ISD::ATOMIC_STORE) &&
5429 "Invalid Atomic Op");
5431 EVT VT = Val.getValueType();
5433 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
5434 getVTList(VT, MVT::Other);
5435 SDValue Ops[] = {Chain, Ptr, Val};
5436 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5439 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5440 EVT VT, SDValue Chain, SDValue Ptr,
5441 MachineMemOperand *MMO) {
5442 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
5444 SDVTList VTs = getVTList(VT, MVT::Other);
5445 SDValue Ops[] = {Chain, Ptr};
5446 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5449 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
5450 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
5451 if (Ops.size() == 1)
5454 SmallVector<EVT, 4> VTs;
5455 VTs.reserve(Ops.size());
5456 for (unsigned i = 0; i < Ops.size(); ++i)
5457 VTs.push_back(Ops[i].getValueType());
5458 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
5461 SDValue SelectionDAG::getMemIntrinsicNode(
5462 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
5463 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
5464 bool ReadMem, bool WriteMem, unsigned Size) {
5465 if (Align == 0) // Ensure that codegen never sees alignment 0
5466 Align = getEVTAlignment(MemVT);
5468 MachineFunction &MF = getMachineFunction();
5469 auto Flags = MachineMemOperand::MONone;
5471 Flags |= MachineMemOperand::MOStore;
5473 Flags |= MachineMemOperand::MOLoad;
5475 Flags |= MachineMemOperand::MOVolatile;
5477 Size = MemVT.getStoreSize();
5478 MachineMemOperand *MMO =
5479 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
5481 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
5484 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
5486 ArrayRef<SDValue> Ops, EVT MemVT,
5487 MachineMemOperand *MMO) {
5488 assert((Opcode == ISD::INTRINSIC_VOID ||
5489 Opcode == ISD::INTRINSIC_W_CHAIN ||
5490 Opcode == ISD::PREFETCH ||
5491 Opcode == ISD::LIFETIME_START ||
5492 Opcode == ISD::LIFETIME_END ||
5493 (Opcode <= INT_MAX &&
5494 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
5495 "Opcode is not a memory-accessing opcode!");
5497 // Memoize the node unless it returns a flag.
5498 MemIntrinsicSDNode *N;
5499 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5500 FoldingSetNodeID ID;
5501 AddNodeIDNode(ID, Opcode, VTList, Ops);
5502 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5504 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5505 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
5506 return SDValue(E, 0);
5509 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5510 VTList, MemVT, MMO);
5511 createOperands(N, Ops);
5513 CSEMap.InsertNode(N, IP);
5515 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5516 VTList, MemVT, MMO);
5517 createOperands(N, Ops);
5520 return SDValue(N, 0);
5523 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5524 /// MachinePointerInfo record from it. This is particularly useful because the
5525 /// code generator has many cases where it doesn't bother passing in a
5526 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5527 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5528 int64_t Offset = 0) {
5529 // If this is FI+Offset, we can model it.
5530 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5531 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5532 FI->getIndex(), Offset);
5534 // If this is (FI+Offset1)+Offset2, we can model it.
5535 if (Ptr.getOpcode() != ISD::ADD ||
5536 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5537 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5538 return MachinePointerInfo();
5540 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5541 return MachinePointerInfo::getFixedStack(
5542 DAG.getMachineFunction(), FI,
5543 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5546 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5547 /// MachinePointerInfo record from it. This is particularly useful because the
5548 /// code generator has many cases where it doesn't bother passing in a
5549 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5550 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5552 // If the 'Offset' value isn't a constant, we can't handle this.
5553 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5554 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5555 if (OffsetOp.isUndef())
5556 return InferPointerInfo(DAG, Ptr);
5557 return MachinePointerInfo();
5560 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5561 EVT VT, const SDLoc &dl, SDValue Chain,
5562 SDValue Ptr, SDValue Offset,
5563 MachinePointerInfo PtrInfo, EVT MemVT,
5565 MachineMemOperand::Flags MMOFlags,
5566 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5567 assert(Chain.getValueType() == MVT::Other &&
5568 "Invalid chain type");
5569 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5570 Alignment = getEVTAlignment(MemVT);
5572 MMOFlags |= MachineMemOperand::MOLoad;
5573 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5574 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5576 if (PtrInfo.V.isNull())
5577 PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5579 MachineFunction &MF = getMachineFunction();
5580 MachineMemOperand *MMO = MF.getMachineMemOperand(
5581 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5582 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5585 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5586 EVT VT, const SDLoc &dl, SDValue Chain,
5587 SDValue Ptr, SDValue Offset, EVT MemVT,
5588 MachineMemOperand *MMO) {
5590 ExtType = ISD::NON_EXTLOAD;
5591 } else if (ExtType == ISD::NON_EXTLOAD) {
5592 assert(VT == MemVT && "Non-extending load from different memory type!");
5595 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5596 "Should only be an extending load, not truncating!");
5597 assert(VT.isInteger() == MemVT.isInteger() &&
5598 "Cannot convert from FP to Int or Int -> FP!");
5599 assert(VT.isVector() == MemVT.isVector() &&
5600 "Cannot use an ext load to convert to or from a vector!");
5601 assert((!VT.isVector() ||
5602 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5603 "Cannot use an ext load to change the number of vector elements!");
5606 bool Indexed = AM != ISD::UNINDEXED;
5607 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5609 SDVTList VTs = Indexed ?
5610 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5611 SDValue Ops[] = { Chain, Ptr, Offset };
5612 FoldingSetNodeID ID;
5613 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5614 ID.AddInteger(MemVT.getRawBits());
5615 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
5616 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
5617 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5619 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5620 cast<LoadSDNode>(E)->refineAlignment(MMO);
5621 return SDValue(E, 0);
5623 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5624 ExtType, MemVT, MMO);
5625 createOperands(N, Ops);
5627 CSEMap.InsertNode(N, IP);
5629 return SDValue(N, 0);
5632 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5633 SDValue Ptr, MachinePointerInfo PtrInfo,
5635 MachineMemOperand::Flags MMOFlags,
5636 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5637 SDValue Undef = getUNDEF(Ptr.getValueType());
5638 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5639 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5642 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5643 SDValue Ptr, MachineMemOperand *MMO) {
5644 SDValue Undef = getUNDEF(Ptr.getValueType());
5645 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5649 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5650 EVT VT, SDValue Chain, SDValue Ptr,
5651 MachinePointerInfo PtrInfo, EVT MemVT,
5653 MachineMemOperand::Flags MMOFlags,
5654 const AAMDNodes &AAInfo) {
5655 SDValue Undef = getUNDEF(Ptr.getValueType());
5656 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5657 MemVT, Alignment, MMOFlags, AAInfo);
5660 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5661 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5662 MachineMemOperand *MMO) {
5663 SDValue Undef = getUNDEF(Ptr.getValueType());
5664 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5668 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5669 SDValue Base, SDValue Offset,
5670 ISD::MemIndexedMode AM) {
5671 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5672 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5673 // Don't propagate the invariant or dereferenceable flags.
5675 LD->getMemOperand()->getFlags() &
5676 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5677 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5678 LD->getChain(), Base, Offset, LD->getPointerInfo(),
5679 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
5683 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5684 SDValue Ptr, MachinePointerInfo PtrInfo,
5686 MachineMemOperand::Flags MMOFlags,
5687 const AAMDNodes &AAInfo) {
5688 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5689 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5690 Alignment = getEVTAlignment(Val.getValueType());
5692 MMOFlags |= MachineMemOperand::MOStore;
5693 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5695 if (PtrInfo.V.isNull())
5696 PtrInfo = InferPointerInfo(*this, Ptr);
5698 MachineFunction &MF = getMachineFunction();
5699 MachineMemOperand *MMO = MF.getMachineMemOperand(
5700 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5701 return getStore(Chain, dl, Val, Ptr, MMO);
5704 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5705 SDValue Ptr, MachineMemOperand *MMO) {
5706 assert(Chain.getValueType() == MVT::Other &&
5707 "Invalid chain type");
5708 EVT VT = Val.getValueType();
5709 SDVTList VTs = getVTList(MVT::Other);
5710 SDValue Undef = getUNDEF(Ptr.getValueType());
5711 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5712 FoldingSetNodeID ID;
5713 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5714 ID.AddInteger(VT.getRawBits());
5715 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5716 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
5717 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5719 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5720 cast<StoreSDNode>(E)->refineAlignment(MMO);
5721 return SDValue(E, 0);
5723 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5724 ISD::UNINDEXED, false, VT, MMO);
5725 createOperands(N, Ops);
5727 CSEMap.InsertNode(N, IP);
5729 return SDValue(N, 0);
5732 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5733 SDValue Ptr, MachinePointerInfo PtrInfo,
5734 EVT SVT, unsigned Alignment,
5735 MachineMemOperand::Flags MMOFlags,
5736 const AAMDNodes &AAInfo) {
5737 assert(Chain.getValueType() == MVT::Other &&
5738 "Invalid chain type");
5739 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5740 Alignment = getEVTAlignment(SVT);
5742 MMOFlags |= MachineMemOperand::MOStore;
5743 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5745 if (PtrInfo.V.isNull())
5746 PtrInfo = InferPointerInfo(*this, Ptr);
5748 MachineFunction &MF = getMachineFunction();
5749 MachineMemOperand *MMO = MF.getMachineMemOperand(
5750 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
5751 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
5754 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5755 SDValue Ptr, EVT SVT,
5756 MachineMemOperand *MMO) {
5757 EVT VT = Val.getValueType();
5759 assert(Chain.getValueType() == MVT::Other &&
5760 "Invalid chain type");
5762 return getStore(Chain, dl, Val, Ptr, MMO);
5764 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5765 "Should only be a truncating store, not extending!");
5766 assert(VT.isInteger() == SVT.isInteger() &&
5767 "Can't do FP-INT conversion!");
5768 assert(VT.isVector() == SVT.isVector() &&
5769 "Cannot use trunc store to convert to or from a vector!");
5770 assert((!VT.isVector() ||
5771 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5772 "Cannot use trunc store to change the number of vector elements!");
5774 SDVTList VTs = getVTList(MVT::Other);
5775 SDValue Undef = getUNDEF(Ptr.getValueType());
5776 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5777 FoldingSetNodeID ID;
5778 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5779 ID.AddInteger(SVT.getRawBits());
5780 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
5781 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
5782 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5784 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5785 cast<StoreSDNode>(E)->refineAlignment(MMO);
5786 return SDValue(E, 0);
5788 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5789 ISD::UNINDEXED, true, SVT, MMO);
5790 createOperands(N, Ops);
5792 CSEMap.InsertNode(N, IP);
5794 return SDValue(N, 0);
5797 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
5798 SDValue Base, SDValue Offset,
5799 ISD::MemIndexedMode AM) {
5800 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5801 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
5802 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5803 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5804 FoldingSetNodeID ID;
5805 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5806 ID.AddInteger(ST->getMemoryVT().getRawBits());
5807 ID.AddInteger(ST->getRawSubclassData());
5808 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5810 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
5811 return SDValue(E, 0);
5813 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5814 ST->isTruncatingStore(), ST->getMemoryVT(),
5815 ST->getMemOperand());
5816 createOperands(N, Ops);
5818 CSEMap.InsertNode(N, IP);
5820 return SDValue(N, 0);
5823 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5824 SDValue Ptr, SDValue Mask, SDValue Src0,
5825 EVT MemVT, MachineMemOperand *MMO,
5826 ISD::LoadExtType ExtTy, bool isExpanding) {
5828 SDVTList VTs = getVTList(VT, MVT::Other);
5829 SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5830 FoldingSetNodeID ID;
5831 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5832 ID.AddInteger(VT.getRawBits());
5833 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
5834 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
5835 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5837 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5838 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5839 return SDValue(E, 0);
5841 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5842 ExtTy, isExpanding, MemVT, MMO);
5843 createOperands(N, Ops);
5845 CSEMap.InsertNode(N, IP);
5847 return SDValue(N, 0);
5850 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
5851 SDValue Val, SDValue Ptr, SDValue Mask,
5852 EVT MemVT, MachineMemOperand *MMO,
5853 bool IsTruncating, bool IsCompressing) {
5854 assert(Chain.getValueType() == MVT::Other &&
5855 "Invalid chain type");
5856 EVT VT = Val.getValueType();
5857 SDVTList VTs = getVTList(MVT::Other);
5858 SDValue Ops[] = { Chain, Ptr, Mask, Val };
5859 FoldingSetNodeID ID;
5860 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5861 ID.AddInteger(VT.getRawBits());
5862 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
5863 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
5864 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5866 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5867 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5868 return SDValue(E, 0);
5870 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5871 IsTruncating, IsCompressing, MemVT, MMO);
5872 createOperands(N, Ops);
5874 CSEMap.InsertNode(N, IP);
5876 return SDValue(N, 0);
5879 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
5880 ArrayRef<SDValue> Ops,
5881 MachineMemOperand *MMO) {
5882 assert(Ops.size() == 5 && "Incompatible number of operands");
5884 FoldingSetNodeID ID;
5885 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5886 ID.AddInteger(VT.getRawBits());
5887 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
5888 dl.getIROrder(), VTs, VT, MMO));
5889 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5891 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5892 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5893 return SDValue(E, 0);
5896 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5898 createOperands(N, Ops);
5900 assert(N->getValue().getValueType() == N->getValueType(0) &&
5901 "Incompatible type of the PassThru value in MaskedGatherSDNode");
5902 assert(N->getMask().getValueType().getVectorNumElements() ==
5903 N->getValueType(0).getVectorNumElements() &&
5904 "Vector width mismatch between mask and data");
5905 assert(N->getIndex().getValueType().getVectorNumElements() ==
5906 N->getValueType(0).getVectorNumElements() &&
5907 "Vector width mismatch between index and data");
5909 CSEMap.InsertNode(N, IP);
5911 return SDValue(N, 0);
5914 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
5915 ArrayRef<SDValue> Ops,
5916 MachineMemOperand *MMO) {
5917 assert(Ops.size() == 5 && "Incompatible number of operands");
5919 FoldingSetNodeID ID;
5920 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
5921 ID.AddInteger(VT.getRawBits());
5922 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
5923 dl.getIROrder(), VTs, VT, MMO));
5924 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5926 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5927 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
5928 return SDValue(E, 0);
5930 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5932 createOperands(N, Ops);
5934 assert(N->getMask().getValueType().getVectorNumElements() ==
5935 N->getValue().getValueType().getVectorNumElements() &&
5936 "Vector width mismatch between mask and data");
5937 assert(N->getIndex().getValueType().getVectorNumElements() ==
5938 N->getValue().getValueType().getVectorNumElements() &&
5939 "Vector width mismatch between index and data");
5941 CSEMap.InsertNode(N, IP);
5943 return SDValue(N, 0);
5946 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
5947 SDValue Ptr, SDValue SV, unsigned Align) {
5948 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
5949 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
5952 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5953 ArrayRef<SDUse> Ops) {
5954 switch (Ops.size()) {
5955 case 0: return getNode(Opcode, DL, VT);
5956 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
5957 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
5958 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5962 // Copy from an SDUse array into an SDValue array for use with
5963 // the regular getNode logic.
5964 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
5965 return getNode(Opcode, DL, VT, NewOps);
5968 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5969 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
5970 unsigned NumOps = Ops.size();
5972 case 0: return getNode(Opcode, DL, VT);
5973 case 1: return getNode(Opcode, DL, VT, Ops[0]);
5974 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
5975 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5981 case ISD::CONCAT_VECTORS: {
5982 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
5983 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
5987 case ISD::SELECT_CC: {
5988 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
5989 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
5990 "LHS and RHS of condition must have same type!");
5991 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
5992 "True and False arms of SelectCC must have same type!");
5993 assert(Ops[2].getValueType() == VT &&
5994 "select_cc node must be of same type as true and false value!");
5998 assert(NumOps == 5 && "BR_CC takes 5 operands!");
5999 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6000 "LHS/RHS of comparison should match types!");
6007 SDVTList VTs = getVTList(VT);
6009 if (VT != MVT::Glue) {
6010 FoldingSetNodeID ID;
6011 AddNodeIDNode(ID, Opcode, VTs, Ops);
6014 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6015 return SDValue(E, 0);
6017 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6018 createOperands(N, Ops);
6020 CSEMap.InsertNode(N, IP);
6022 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6023 createOperands(N, Ops);
6027 return SDValue(N, 0);
6030 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6031 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
6032 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
6035 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6036 ArrayRef<SDValue> Ops) {
6037 if (VTList.NumVTs == 1)
6038 return getNode(Opcode, DL, VTList.VTs[0], Ops);
6042 // FIXME: figure out how to safely handle things like
6043 // int foo(int x) { return 1 << (x & 255); }
6044 // int bar() { return foo(256); }
6045 case ISD::SRA_PARTS:
6046 case ISD::SRL_PARTS:
6047 case ISD::SHL_PARTS:
6048 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6049 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
6050 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6051 else if (N3.getOpcode() == ISD::AND)
6052 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
6053 // If the and is only masking out bits that cannot effect the shift,
6054 // eliminate the and.
6055 unsigned NumBits = VT.getScalarSizeInBits()*2;
6056 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
6057 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6063 // Memoize the node unless it returns a flag.
6065 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6066 FoldingSetNodeID ID;
6067 AddNodeIDNode(ID, Opcode, VTList, Ops);
6069 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6070 return SDValue(E, 0);
6072 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6073 createOperands(N, Ops);
6074 CSEMap.InsertNode(N, IP);
6076 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6077 createOperands(N, Ops);
6080 return SDValue(N, 0);
6083 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6085 return getNode(Opcode, DL, VTList, None);
6088 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6090 SDValue Ops[] = { N1 };
6091 return getNode(Opcode, DL, VTList, Ops);
6094 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6095 SDValue N1, SDValue N2) {
6096 SDValue Ops[] = { N1, N2 };
6097 return getNode(Opcode, DL, VTList, Ops);
6100 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6101 SDValue N1, SDValue N2, SDValue N3) {
6102 SDValue Ops[] = { N1, N2, N3 };
6103 return getNode(Opcode, DL, VTList, Ops);
6106 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6107 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6108 SDValue Ops[] = { N1, N2, N3, N4 };
6109 return getNode(Opcode, DL, VTList, Ops);
6112 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6113 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6115 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6116 return getNode(Opcode, DL, VTList, Ops);
6119 SDVTList SelectionDAG::getVTList(EVT VT) {
6120 return makeVTList(SDNode::getValueTypeList(VT), 1);
6123 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
6124 FoldingSetNodeID ID;
6126 ID.AddInteger(VT1.getRawBits());
6127 ID.AddInteger(VT2.getRawBits());
6130 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6132 EVT *Array = Allocator.Allocate<EVT>(2);
6135 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
6136 VTListMap.InsertNode(Result, IP);
6138 return Result->getSDVTList();
6141 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
6142 FoldingSetNodeID ID;
6144 ID.AddInteger(VT1.getRawBits());
6145 ID.AddInteger(VT2.getRawBits());
6146 ID.AddInteger(VT3.getRawBits());
6149 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6151 EVT *Array = Allocator.Allocate<EVT>(3);
6155 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
6156 VTListMap.InsertNode(Result, IP);
6158 return Result->getSDVTList();
6161 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
6162 FoldingSetNodeID ID;
6164 ID.AddInteger(VT1.getRawBits());
6165 ID.AddInteger(VT2.getRawBits());
6166 ID.AddInteger(VT3.getRawBits());
6167 ID.AddInteger(VT4.getRawBits());
6170 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6172 EVT *Array = Allocator.Allocate<EVT>(4);
6177 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
6178 VTListMap.InsertNode(Result, IP);
6180 return Result->getSDVTList();
6183 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
6184 unsigned NumVTs = VTs.size();
6185 FoldingSetNodeID ID;
6186 ID.AddInteger(NumVTs);
6187 for (unsigned index = 0; index < NumVTs; index++) {
6188 ID.AddInteger(VTs[index].getRawBits());
6192 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6194 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
6195 std::copy(VTs.begin(), VTs.end(), Array);
6196 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
6197 VTListMap.InsertNode(Result, IP);
6199 return Result->getSDVTList();
6203 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
6204 /// specified operands. If the resultant node already exists in the DAG,
6205 /// this does not modify the specified node, instead it returns the node that
6206 /// already exists. If the resultant node does not exist in the DAG, the
6207 /// input node is returned. As a degenerate case, if you specify the same
6208 /// input operands as the node already has, the input node is returned.
6209 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
6210 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
6212 // Check to see if there is no change.
6213 if (Op == N->getOperand(0)) return N;
6215 // See if the modified node already exists.
6216 void *InsertPos = nullptr;
6217 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
6220 // Nope it doesn't. Remove the node from its current place in the maps.
6222 if (!RemoveNodeFromCSEMaps(N))
6223 InsertPos = nullptr;
6225 // Now we update the operands.
6226 N->OperandList[0].set(Op);
6228 // If this gets put into a CSE map, add it.
6229 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6233 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
6234 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
6236 // Check to see if there is no change.
6237 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
6238 return N; // No operands changed, just return the input node.
6240 // See if the modified node already exists.
6241 void *InsertPos = nullptr;
6242 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
6245 // Nope it doesn't. Remove the node from its current place in the maps.
6247 if (!RemoveNodeFromCSEMaps(N))
6248 InsertPos = nullptr;
6250 // Now we update the operands.
6251 if (N->OperandList[0] != Op1)
6252 N->OperandList[0].set(Op1);
6253 if (N->OperandList[1] != Op2)
6254 N->OperandList[1].set(Op2);
6256 // If this gets put into a CSE map, add it.
6257 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6261 SDNode *SelectionDAG::
6262 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
6263 SDValue Ops[] = { Op1, Op2, Op3 };
6264 return UpdateNodeOperands(N, Ops);
6267 SDNode *SelectionDAG::
6268 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6269 SDValue Op3, SDValue Op4) {
6270 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
6271 return UpdateNodeOperands(N, Ops);
6274 SDNode *SelectionDAG::
6275 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6276 SDValue Op3, SDValue Op4, SDValue Op5) {
6277 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
6278 return UpdateNodeOperands(N, Ops);
6281 SDNode *SelectionDAG::
6282 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
6283 unsigned NumOps = Ops.size();
6284 assert(N->getNumOperands() == NumOps &&
6285 "Update with wrong number of operands");
6287 // If no operands changed just return the input node.
6288 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
6291 // See if the modified node already exists.
6292 void *InsertPos = nullptr;
6293 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
6296 // Nope it doesn't. Remove the node from its current place in the maps.
6298 if (!RemoveNodeFromCSEMaps(N))
6299 InsertPos = nullptr;
6301 // Now we update the operands.
6302 for (unsigned i = 0; i != NumOps; ++i)
6303 if (N->OperandList[i] != Ops[i])
6304 N->OperandList[i].set(Ops[i]);
6306 // If this gets put into a CSE map, add it.
6307 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6311 /// DropOperands - Release the operands and set this node to have
6313 void SDNode::DropOperands() {
6314 // Unlike the code in MorphNodeTo that does this, we don't need to
6315 // watch for dead nodes here.
6316 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
6322 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
6325 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6327 SDVTList VTs = getVTList(VT);
6328 return SelectNodeTo(N, MachineOpc, VTs, None);
6331 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6332 EVT VT, SDValue Op1) {
6333 SDVTList VTs = getVTList(VT);
6334 SDValue Ops[] = { Op1 };
6335 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6338 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6339 EVT VT, SDValue Op1,
6341 SDVTList VTs = getVTList(VT);
6342 SDValue Ops[] = { Op1, Op2 };
6343 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6346 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6347 EVT VT, SDValue Op1,
6348 SDValue Op2, SDValue Op3) {
6349 SDVTList VTs = getVTList(VT);
6350 SDValue Ops[] = { Op1, Op2, Op3 };
6351 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6354 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6355 EVT VT, ArrayRef<SDValue> Ops) {
6356 SDVTList VTs = getVTList(VT);
6357 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6360 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6361 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
6362 SDVTList VTs = getVTList(VT1, VT2);
6363 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6366 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6368 SDVTList VTs = getVTList(VT1, VT2);
6369 return SelectNodeTo(N, MachineOpc, VTs, None);
6372 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6373 EVT VT1, EVT VT2, EVT VT3,
6374 ArrayRef<SDValue> Ops) {
6375 SDVTList VTs = getVTList(VT1, VT2, VT3);
6376 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6379 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6381 SDValue Op1, SDValue Op2) {
6382 SDVTList VTs = getVTList(VT1, VT2);
6383 SDValue Ops[] = { Op1, Op2 };
6384 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6387 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6388 SDVTList VTs,ArrayRef<SDValue> Ops) {
6389 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
6390 // Reset the NodeID to -1.
6393 ReplaceAllUsesWith(N, New);
6399 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
6400 /// the line number information on the merged node since it is not possible to
6401 /// preserve the information that operation is associated with multiple lines.
6402 /// This will make the debugger working better at -O0, were there is a higher
6403 /// probability having other instructions associated with that line.
6405 /// For IROrder, we keep the smaller of the two
6406 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
6407 DebugLoc NLoc = N->getDebugLoc();
6408 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
6409 N->setDebugLoc(DebugLoc());
6411 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
6412 N->setIROrder(Order);
6416 /// MorphNodeTo - This *mutates* the specified node to have the specified
6417 /// return type, opcode, and operands.
6419 /// Note that MorphNodeTo returns the resultant node. If there is already a
6420 /// node of the specified opcode and operands, it returns that node instead of
6421 /// the current one. Note that the SDLoc need not be the same.
6423 /// Using MorphNodeTo is faster than creating a new node and swapping it in
6424 /// with ReplaceAllUsesWith both because it often avoids allocating a new
6425 /// node, and because it doesn't require CSE recalculation for any of
6426 /// the node's users.
6428 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
6429 /// As a consequence it isn't appropriate to use from within the DAG combiner or
6430 /// the legalizer which maintain worklists that would need to be updated when
6431 /// deleting things.
6432 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
6433 SDVTList VTs, ArrayRef<SDValue> Ops) {
6434 // If an identical node already exists, use it.
6436 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
6437 FoldingSetNodeID ID;
6438 AddNodeIDNode(ID, Opc, VTs, Ops);
6439 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
6440 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
6443 if (!RemoveNodeFromCSEMaps(N))
6446 // Start the morphing.
6448 N->ValueList = VTs.VTs;
6449 N->NumValues = VTs.NumVTs;
6451 // Clear the operands list, updating used nodes to remove this from their
6452 // use list. Keep track of any operands that become dead as a result.
6453 SmallPtrSet<SDNode*, 16> DeadNodeSet;
6454 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
6456 SDNode *Used = Use.getNode();
6458 if (Used->use_empty())
6459 DeadNodeSet.insert(Used);
6462 // For MachineNode, initialize the memory references information.
6463 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
6464 MN->setMemRefs(nullptr, nullptr);
6466 // Swap for an appropriately sized array from the recycler.
6468 createOperands(N, Ops);
6470 // Delete any nodes that are still dead after adding the uses for the
6472 if (!DeadNodeSet.empty()) {
6473 SmallVector<SDNode *, 16> DeadNodes;
6474 for (SDNode *N : DeadNodeSet)
6476 DeadNodes.push_back(N);
6477 RemoveDeadNodes(DeadNodes);
6481 CSEMap.InsertNode(N, IP); // Memoize the new node.
6486 /// getMachineNode - These are used for target selectors to create a new node
6487 /// with specified return type(s), MachineInstr opcode, and operands.
6489 /// Note that getMachineNode returns the resultant node. If there is already a
6490 /// node of the specified opcode and operands, it returns that node instead of
6491 /// the current one.
6492 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6494 SDVTList VTs = getVTList(VT);
6495 return getMachineNode(Opcode, dl, VTs, None);
6498 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6499 EVT VT, SDValue Op1) {
6500 SDVTList VTs = getVTList(VT);
6501 SDValue Ops[] = { Op1 };
6502 return getMachineNode(Opcode, dl, VTs, Ops);
6505 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6506 EVT VT, SDValue Op1, SDValue Op2) {
6507 SDVTList VTs = getVTList(VT);
6508 SDValue Ops[] = { Op1, Op2 };
6509 return getMachineNode(Opcode, dl, VTs, Ops);
6512 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6513 EVT VT, SDValue Op1, SDValue Op2,
6515 SDVTList VTs = getVTList(VT);
6516 SDValue Ops[] = { Op1, Op2, Op3 };
6517 return getMachineNode(Opcode, dl, VTs, Ops);
6520 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6521 EVT VT, ArrayRef<SDValue> Ops) {
6522 SDVTList VTs = getVTList(VT);
6523 return getMachineNode(Opcode, dl, VTs, Ops);
6526 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6527 EVT VT1, EVT VT2, SDValue Op1,
6529 SDVTList VTs = getVTList(VT1, VT2);
6530 SDValue Ops[] = { Op1, Op2 };
6531 return getMachineNode(Opcode, dl, VTs, Ops);
6534 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6535 EVT VT1, EVT VT2, SDValue Op1,
6536 SDValue Op2, SDValue Op3) {
6537 SDVTList VTs = getVTList(VT1, VT2);
6538 SDValue Ops[] = { Op1, Op2, Op3 };
6539 return getMachineNode(Opcode, dl, VTs, Ops);
6542 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6544 ArrayRef<SDValue> Ops) {
6545 SDVTList VTs = getVTList(VT1, VT2);
6546 return getMachineNode(Opcode, dl, VTs, Ops);
6549 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6550 EVT VT1, EVT VT2, EVT VT3,
6551 SDValue Op1, SDValue Op2) {
6552 SDVTList VTs = getVTList(VT1, VT2, VT3);
6553 SDValue Ops[] = { Op1, Op2 };
6554 return getMachineNode(Opcode, dl, VTs, Ops);
6557 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6558 EVT VT1, EVT VT2, EVT VT3,
6559 SDValue Op1, SDValue Op2,
6561 SDVTList VTs = getVTList(VT1, VT2, VT3);
6562 SDValue Ops[] = { Op1, Op2, Op3 };
6563 return getMachineNode(Opcode, dl, VTs, Ops);
6566 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6567 EVT VT1, EVT VT2, EVT VT3,
6568 ArrayRef<SDValue> Ops) {
6569 SDVTList VTs = getVTList(VT1, VT2, VT3);
6570 return getMachineNode(Opcode, dl, VTs, Ops);
6573 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6574 ArrayRef<EVT> ResultTys,
6575 ArrayRef<SDValue> Ops) {
6576 SDVTList VTs = getVTList(ResultTys);
6577 return getMachineNode(Opcode, dl, VTs, Ops);
6580 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6582 ArrayRef<SDValue> Ops) {
6583 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6588 FoldingSetNodeID ID;
6589 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6591 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6592 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
6596 // Allocate a new MachineSDNode.
6597 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6598 createOperands(N, Ops);
6601 CSEMap.InsertNode(N, IP);
6607 /// getTargetExtractSubreg - A convenience function for creating
6608 /// TargetOpcode::EXTRACT_SUBREG nodes.
6609 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6611 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6612 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6613 VT, Operand, SRIdxVal);
6614 return SDValue(Subreg, 0);
6617 /// getTargetInsertSubreg - A convenience function for creating
6618 /// TargetOpcode::INSERT_SUBREG nodes.
6619 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6620 SDValue Operand, SDValue Subreg) {
6621 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6622 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6623 VT, Operand, Subreg, SRIdxVal);
6624 return SDValue(Result, 0);
6627 /// getNodeIfExists - Get the specified node if it's already available, or
6628 /// else return NULL.
6629 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6630 ArrayRef<SDValue> Ops,
6631 const SDNodeFlags Flags) {
6632 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6633 FoldingSetNodeID ID;
6634 AddNodeIDNode(ID, Opcode, VTList, Ops);
6636 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6637 E->intersectFlagsWith(Flags);
6644 /// getDbgValue - Creates a SDDbgValue node.
6647 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
6648 unsigned R, bool IsIndirect, uint64_t Off,
6649 const DebugLoc &DL, unsigned O) {
6650 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6651 "Expected inlined-at fields to agree");
6652 return new (DbgInfo->getAlloc())
6653 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
6657 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6658 const Value *C, uint64_t Off,
6659 const DebugLoc &DL, unsigned O) {
6660 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6661 "Expected inlined-at fields to agree");
6662 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O);
6666 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6667 unsigned FI, uint64_t Off,
6670 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6671 "Expected inlined-at fields to agree");
6672 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O);
6677 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6678 /// pointed to by a use iterator is deleted, increment the use iterator
6679 /// so that it doesn't dangle.
6681 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6682 SDNode::use_iterator &UI;
6683 SDNode::use_iterator &UE;
6685 void NodeDeleted(SDNode *N, SDNode *E) override {
6686 // Increment the iterator as needed.
6687 while (UI != UE && N == *UI)
6692 RAUWUpdateListener(SelectionDAG &d,
6693 SDNode::use_iterator &ui,
6694 SDNode::use_iterator &ue)
6695 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6700 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6701 /// This can cause recursive merging of nodes in the DAG.
6703 /// This version assumes From has a single result value.
6705 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6706 SDNode *From = FromN.getNode();
6707 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6708 "Cannot replace with this method!");
6709 assert(From != To.getNode() && "Cannot replace uses of with self");
6711 // Preserve Debug Values
6712 TransferDbgValues(FromN, To);
6714 // Iterate over all the existing uses of From. New uses will be added
6715 // to the beginning of the use list, which we avoid visiting.
6716 // This specifically avoids visiting uses of From that arise while the
6717 // replacement is happening, because any such uses would be the result
6718 // of CSE: If an existing node looks like From after one of its operands
6719 // is replaced by To, we don't want to replace of all its users with To
6720 // too. See PR3018 for more info.
6721 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6722 RAUWUpdateListener Listener(*this, UI, UE);
6726 // This node is about to morph, remove its old self from the CSE maps.
6727 RemoveNodeFromCSEMaps(User);
6729 // A user can appear in a use list multiple times, and when this
6730 // happens the uses are usually next to each other in the list.
6731 // To help reduce the number of CSE recomputations, process all
6732 // the uses of this user that we can find this way.
6734 SDUse &Use = UI.getUse();
6737 } while (UI != UE && *UI == User);
6739 // Now that we have modified User, add it back to the CSE maps. If it
6740 // already exists there, recursively merge the results together.
6741 AddModifiedNodeToCSEMaps(User);
6745 // If we just RAUW'd the root, take note.
6746 if (FromN == getRoot())
6750 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6751 /// This can cause recursive merging of nodes in the DAG.
6753 /// This version assumes that for each value of From, there is a
6754 /// corresponding value in To in the same position with the same type.
6756 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6758 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6759 assert((!From->hasAnyUseOfValue(i) ||
6760 From->getValueType(i) == To->getValueType(i)) &&
6761 "Cannot use this version of ReplaceAllUsesWith!");
6764 // Handle the trivial case.
6768 // Preserve Debug Info. Only do this if there's a use.
6769 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6770 if (From->hasAnyUseOfValue(i)) {
6771 assert((i < To->getNumValues()) && "Invalid To location");
6772 TransferDbgValues(SDValue(From, i), SDValue(To, i));
6775 // Iterate over just the existing users of From. See the comments in
6776 // the ReplaceAllUsesWith above.
6777 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6778 RAUWUpdateListener Listener(*this, UI, UE);
6782 // This node is about to morph, remove its old self from the CSE maps.
6783 RemoveNodeFromCSEMaps(User);
6785 // A user can appear in a use list multiple times, and when this
6786 // happens the uses are usually next to each other in the list.
6787 // To help reduce the number of CSE recomputations, process all
6788 // the uses of this user that we can find this way.
6790 SDUse &Use = UI.getUse();
6793 } while (UI != UE && *UI == User);
6795 // Now that we have modified User, add it back to the CSE maps. If it
6796 // already exists there, recursively merge the results together.
6797 AddModifiedNodeToCSEMaps(User);
6800 // If we just RAUW'd the root, take note.
6801 if (From == getRoot().getNode())
6802 setRoot(SDValue(To, getRoot().getResNo()));
6805 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6806 /// This can cause recursive merging of nodes in the DAG.
6808 /// This version can replace From with any result values. To must match the
6809 /// number and types of values returned by From.
6810 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6811 if (From->getNumValues() == 1) // Handle the simple case efficiently.
6812 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6814 // Preserve Debug Info.
6815 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6816 TransferDbgValues(SDValue(From, i), *To);
6818 // Iterate over just the existing users of From. See the comments in
6819 // the ReplaceAllUsesWith above.
6820 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6821 RAUWUpdateListener Listener(*this, UI, UE);
6825 // This node is about to morph, remove its old self from the CSE maps.
6826 RemoveNodeFromCSEMaps(User);
6828 // A user can appear in a use list multiple times, and when this
6829 // happens the uses are usually next to each other in the list.
6830 // To help reduce the number of CSE recomputations, process all
6831 // the uses of this user that we can find this way.
6833 SDUse &Use = UI.getUse();
6834 const SDValue &ToOp = To[Use.getResNo()];
6837 } while (UI != UE && *UI == User);
6839 // Now that we have modified User, add it back to the CSE maps. If it
6840 // already exists there, recursively merge the results together.
6841 AddModifiedNodeToCSEMaps(User);
6844 // If we just RAUW'd the root, take note.
6845 if (From == getRoot().getNode())
6846 setRoot(SDValue(To[getRoot().getResNo()]));
6849 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6850 /// uses of other values produced by From.getNode() alone. The Deleted
6851 /// vector is handled the same way as for ReplaceAllUsesWith.
6852 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6853 // Handle the really simple, really trivial case efficiently.
6854 if (From == To) return;
6856 // Handle the simple, trivial, case efficiently.
6857 if (From.getNode()->getNumValues() == 1) {
6858 ReplaceAllUsesWith(From, To);
6862 // Preserve Debug Info.
6863 TransferDbgValues(From, To);
6865 // Iterate over just the existing users of From. See the comments in
6866 // the ReplaceAllUsesWith above.
6867 SDNode::use_iterator UI = From.getNode()->use_begin(),
6868 UE = From.getNode()->use_end();
6869 RAUWUpdateListener Listener(*this, UI, UE);
6872 bool UserRemovedFromCSEMaps = false;
6874 // A user can appear in a use list multiple times, and when this
6875 // happens the uses are usually next to each other in the list.
6876 // To help reduce the number of CSE recomputations, process all
6877 // the uses of this user that we can find this way.
6879 SDUse &Use = UI.getUse();
6881 // Skip uses of different values from the same node.
6882 if (Use.getResNo() != From.getResNo()) {
6887 // If this node hasn't been modified yet, it's still in the CSE maps,
6888 // so remove its old self from the CSE maps.
6889 if (!UserRemovedFromCSEMaps) {
6890 RemoveNodeFromCSEMaps(User);
6891 UserRemovedFromCSEMaps = true;
6896 } while (UI != UE && *UI == User);
6898 // We are iterating over all uses of the From node, so if a use
6899 // doesn't use the specific value, no changes are made.
6900 if (!UserRemovedFromCSEMaps)
6903 // Now that we have modified User, add it back to the CSE maps. If it
6904 // already exists there, recursively merge the results together.
6905 AddModifiedNodeToCSEMaps(User);
6908 // If we just RAUW'd the root, take note.
6909 if (From == getRoot())
6914 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
6915 /// to record information about a use.
6922 /// operator< - Sort Memos by User.
6923 bool operator<(const UseMemo &L, const UseMemo &R) {
6924 return (intptr_t)L.User < (intptr_t)R.User;
6928 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
6929 /// uses of other values produced by From.getNode() alone. The same value
6930 /// may appear in both the From and To list. The Deleted vector is
6931 /// handled the same way as for ReplaceAllUsesWith.
6932 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
6935 // Handle the simple, trivial case efficiently.
6937 return ReplaceAllUsesOfValueWith(*From, *To);
6939 TransferDbgValues(*From, *To);
6941 // Read up all the uses and make records of them. This helps
6942 // processing new uses that are introduced during the
6943 // replacement process.
6944 SmallVector<UseMemo, 4> Uses;
6945 for (unsigned i = 0; i != Num; ++i) {
6946 unsigned FromResNo = From[i].getResNo();
6947 SDNode *FromNode = From[i].getNode();
6948 for (SDNode::use_iterator UI = FromNode->use_begin(),
6949 E = FromNode->use_end(); UI != E; ++UI) {
6950 SDUse &Use = UI.getUse();
6951 if (Use.getResNo() == FromResNo) {
6952 UseMemo Memo = { *UI, i, &Use };
6953 Uses.push_back(Memo);
6958 // Sort the uses, so that all the uses from a given User are together.
6959 std::sort(Uses.begin(), Uses.end());
6961 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
6962 UseIndex != UseIndexEnd; ) {
6963 // We know that this user uses some value of From. If it is the right
6964 // value, update it.
6965 SDNode *User = Uses[UseIndex].User;
6967 // This node is about to morph, remove its old self from the CSE maps.
6968 RemoveNodeFromCSEMaps(User);
6970 // The Uses array is sorted, so all the uses for a given User
6971 // are next to each other in the list.
6972 // To help reduce the number of CSE recomputations, process all
6973 // the uses of this user that we can find this way.
6975 unsigned i = Uses[UseIndex].Index;
6976 SDUse &Use = *Uses[UseIndex].Use;
6980 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
6982 // Now that we have modified User, add it back to the CSE maps. If it
6983 // already exists there, recursively merge the results together.
6984 AddModifiedNodeToCSEMaps(User);
6988 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
6989 /// based on their topological order. It returns the maximum id and a vector
6990 /// of the SDNodes* in assigned order by reference.
6991 unsigned SelectionDAG::AssignTopologicalOrder() {
6993 unsigned DAGSize = 0;
6995 // SortedPos tracks the progress of the algorithm. Nodes before it are
6996 // sorted, nodes after it are unsorted. When the algorithm completes
6997 // it is at the end of the list.
6998 allnodes_iterator SortedPos = allnodes_begin();
7000 // Visit all the nodes. Move nodes with no operands to the front of
7001 // the list immediately. Annotate nodes that do have operands with their
7002 // operand count. Before we do this, the Node Id fields of the nodes
7003 // may contain arbitrary values. After, the Node Id fields for nodes
7004 // before SortedPos will contain the topological sort index, and the
7005 // Node Id fields for nodes At SortedPos and after will contain the
7006 // count of outstanding operands.
7007 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
7009 checkForCycles(N, this);
7010 unsigned Degree = N->getNumOperands();
7012 // A node with no uses, add it to the result array immediately.
7013 N->setNodeId(DAGSize++);
7014 allnodes_iterator Q(N);
7016 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
7017 assert(SortedPos != AllNodes.end() && "Overran node list");
7020 // Temporarily use the Node Id as scratch space for the degree count.
7021 N->setNodeId(Degree);
7025 // Visit all the nodes. As we iterate, move nodes into sorted order,
7026 // such that by the time the end is reached all nodes will be sorted.
7027 for (SDNode &Node : allnodes()) {
7029 checkForCycles(N, this);
7030 // N is in sorted position, so all its uses have one less operand
7031 // that needs to be sorted.
7032 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7035 unsigned Degree = P->getNodeId();
7036 assert(Degree != 0 && "Invalid node degree");
7039 // All of P's operands are sorted, so P may sorted now.
7040 P->setNodeId(DAGSize++);
7041 if (P->getIterator() != SortedPos)
7042 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
7043 assert(SortedPos != AllNodes.end() && "Overran node list");
7046 // Update P's outstanding operand count.
7047 P->setNodeId(Degree);
7050 if (Node.getIterator() == SortedPos) {
7052 allnodes_iterator I(N);
7054 dbgs() << "Overran sorted position:\n";
7055 S->dumprFull(this); dbgs() << "\n";
7056 dbgs() << "Checking if this is due to cycles\n";
7057 checkForCycles(this, true);
7059 llvm_unreachable(nullptr);
7063 assert(SortedPos == AllNodes.end() &&
7064 "Topological sort incomplete!");
7065 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
7066 "First node in topological sort is not the entry token!");
7067 assert(AllNodes.front().getNodeId() == 0 &&
7068 "First node in topological sort has non-zero id!");
7069 assert(AllNodes.front().getNumOperands() == 0 &&
7070 "First node in topological sort has operands!");
7071 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
7072 "Last node in topologic sort has unexpected id!");
7073 assert(AllNodes.back().use_empty() &&
7074 "Last node in topologic sort has users!");
7075 assert(DAGSize == allnodes_size() && "Node count mismatch!");
7079 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
7080 /// value is produced by SD.
7081 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
7083 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
7084 SD->setHasDebugValue(true);
7086 DbgInfo->add(DB, SD, isParameter);
7089 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes.
7090 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
7091 if (From == To || !From.getNode()->getHasDebugValue())
7093 SDNode *FromNode = From.getNode();
7094 SDNode *ToNode = To.getNode();
7095 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
7096 SmallVector<SDDbgValue *, 2> ClonedDVs;
7097 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
7099 SDDbgValue *Dbg = *I;
7100 // Only add Dbgvalues attached to same ResNo.
7101 if (Dbg->getKind() == SDDbgValue::SDNODE &&
7102 Dbg->getSDNode() == From.getNode() &&
7103 Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) {
7104 assert(FromNode != ToNode &&
7105 "Should not transfer Debug Values intranode");
7107 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
7108 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
7109 Dbg->getDebugLoc(), Dbg->getOrder());
7110 ClonedDVs.push_back(Clone);
7111 Dbg->setIsInvalidated();
7114 for (SDDbgValue *I : ClonedDVs)
7115 AddDbgValue(I, ToNode, false);
7118 //===----------------------------------------------------------------------===//
7120 //===----------------------------------------------------------------------===//
7122 bool llvm::isNullConstant(SDValue V) {
7123 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7124 return Const != nullptr && Const->isNullValue();
7127 bool llvm::isNullFPConstant(SDValue V) {
7128 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
7129 return Const != nullptr && Const->isZero() && !Const->isNegative();
7132 bool llvm::isAllOnesConstant(SDValue V) {
7133 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7134 return Const != nullptr && Const->isAllOnesValue();
7137 bool llvm::isOneConstant(SDValue V) {
7138 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7139 return Const != nullptr && Const->isOne();
7142 bool llvm::isBitwiseNot(SDValue V) {
7143 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
7146 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
7147 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
7150 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7151 BitVector UndefElements;
7152 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
7154 // BuildVectors can truncate their operands. Ignore that case here.
7155 // FIXME: We blindly ignore splats which include undef which is overly
7157 if (CN && UndefElements.none() &&
7158 CN->getValueType(0) == N.getValueType().getScalarType())
7165 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
7166 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
7169 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7170 BitVector UndefElements;
7171 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
7173 if (CN && UndefElements.none())
7180 HandleSDNode::~HandleSDNode() {
7184 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
7186 const GlobalValue *GA, EVT VT,
7187 int64_t o, unsigned char TF)
7188 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
7192 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
7193 EVT VT, unsigned SrcAS,
7195 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
7196 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
7198 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
7199 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
7200 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
7201 MemSDNodeBits.IsVolatile = MMO->isVolatile();
7202 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
7203 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
7204 MemSDNodeBits.IsInvariant = MMO->isInvariant();
7206 // We check here that the size of the memory operand fits within the size of
7207 // the MMO. This is because the MMO might indicate only a possible address
7208 // range instead of specifying the affected memory addresses precisely.
7209 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
7212 /// Profile - Gather unique data for the node.
7214 void SDNode::Profile(FoldingSetNodeID &ID) const {
7215 AddNodeIDNode(ID, this);
7220 std::vector<EVT> VTs;
7223 VTs.reserve(MVT::LAST_VALUETYPE);
7224 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
7225 VTs.push_back(MVT((MVT::SimpleValueType)i));
7230 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
7231 static ManagedStatic<EVTArray> SimpleVTArray;
7232 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
7234 /// getValueTypeList - Return a pointer to the specified value type.
7236 const EVT *SDNode::getValueTypeList(EVT VT) {
7237 if (VT.isExtended()) {
7238 sys::SmartScopedLock<true> Lock(*VTMutex);
7239 return &(*EVTs->insert(VT).first);
7241 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
7242 "Value type out of range!");
7243 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
7247 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
7248 /// indicated value. This method ignores uses of other values defined by this
7250 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
7251 assert(Value < getNumValues() && "Bad value!");
7253 // TODO: Only iterate over uses of a given value of the node
7254 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
7255 if (UI.getUse().getResNo() == Value) {
7262 // Found exactly the right number of uses?
7267 /// hasAnyUseOfValue - Return true if there are any use of the indicated
7268 /// value. This method ignores uses of other values defined by this operation.
7269 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
7270 assert(Value < getNumValues() && "Bad value!");
7272 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
7273 if (UI.getUse().getResNo() == Value)
7280 /// isOnlyUserOf - Return true if this node is the only use of N.
7282 bool SDNode::isOnlyUserOf(const SDNode *N) const {
7284 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7295 /// Return true if the only users of N are contained in Nodes.
7296 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
7298 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7300 if (llvm::any_of(Nodes,
7301 [&User](const SDNode *Node) { return User == Node; }))
7310 /// isOperand - Return true if this node is an operand of N.
7312 bool SDValue::isOperandOf(const SDNode *N) const {
7313 for (const SDValue &Op : N->op_values())
7319 bool SDNode::isOperandOf(const SDNode *N) const {
7320 for (const SDValue &Op : N->op_values())
7321 if (this == Op.getNode())
7326 /// reachesChainWithoutSideEffects - Return true if this operand (which must
7327 /// be a chain) reaches the specified operand without crossing any
7328 /// side-effecting instructions on any chain path. In practice, this looks
7329 /// through token factors and non-volatile loads. In order to remain efficient,
7330 /// this only looks a couple of nodes in, it does not do an exhaustive search.
7332 /// Note that we only need to examine chains when we're searching for
7333 /// side-effects; SelectionDAG requires that all side-effects are represented
7334 /// by chains, even if another operand would force a specific ordering. This
7335 /// constraint is necessary to allow transformations like splitting loads.
7336 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
7337 unsigned Depth) const {
7338 if (*this == Dest) return true;
7340 // Don't search too deeply, we just want to be able to see through
7341 // TokenFactor's etc.
7342 if (Depth == 0) return false;
7344 // If this is a token factor, all inputs to the TF happen in parallel.
7345 if (getOpcode() == ISD::TokenFactor) {
7346 // First, try a shallow search.
7347 if (is_contained((*this)->ops(), Dest)) {
7348 // We found the chain we want as an operand of this TokenFactor.
7349 // Essentially, we reach the chain without side-effects if we could
7350 // serialize the TokenFactor into a simple chain of operations with
7351 // Dest as the last operation. This is automatically true if the
7352 // chain has one use: there are no other ordering constraints.
7353 // If the chain has more than one use, we give up: some other
7354 // use of Dest might force a side-effect between Dest and the current
7356 if (Dest.hasOneUse())
7359 // Next, try a deep search: check whether every operand of the TokenFactor
7361 return all_of((*this)->ops(), [=](SDValue Op) {
7362 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
7366 // Loads don't have side effects, look through them.
7367 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
7368 if (!Ld->isVolatile())
7369 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
7374 bool SDNode::hasPredecessor(const SDNode *N) const {
7375 SmallPtrSet<const SDNode *, 32> Visited;
7376 SmallVector<const SDNode *, 16> Worklist;
7377 Worklist.push_back(this);
7378 return hasPredecessorHelper(N, Visited, Worklist);
7381 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
7382 this->Flags.intersectWith(Flags);
7385 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
7386 assert(N->getNumValues() == 1 &&
7387 "Can't unroll a vector with multiple results!");
7389 EVT VT = N->getValueType(0);
7390 unsigned NE = VT.getVectorNumElements();
7391 EVT EltVT = VT.getVectorElementType();
7394 SmallVector<SDValue, 8> Scalars;
7395 SmallVector<SDValue, 4> Operands(N->getNumOperands());
7397 // If ResNE is 0, fully unroll the vector op.
7400 else if (NE > ResNE)
7404 for (i= 0; i != NE; ++i) {
7405 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
7406 SDValue Operand = N->getOperand(j);
7407 EVT OperandVT = Operand.getValueType();
7408 if (OperandVT.isVector()) {
7409 // A vector operand; extract a single element.
7410 EVT OperandEltVT = OperandVT.getVectorElementType();
7412 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
7413 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
7415 // A scalar operand; just use it as is.
7416 Operands[j] = Operand;
7420 switch (N->getOpcode()) {
7422 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
7427 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
7434 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
7435 getShiftAmountOperand(Operands[0].getValueType(),
7438 case ISD::SIGN_EXTEND_INREG:
7439 case ISD::FP_ROUND_INREG: {
7440 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
7441 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
7443 getValueType(ExtVT)));
7448 for (; i < ResNE; ++i)
7449 Scalars.push_back(getUNDEF(EltVT));
7451 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
7452 return getBuildVector(VecVT, dl, Scalars);
7455 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
7459 if (LD->isVolatile() || Base->isVolatile())
7461 if (LD->isIndexed() || Base->isIndexed())
7463 if (LD->getChain() != Base->getChain())
7465 EVT VT = LD->getValueType(0);
7466 if (VT.getSizeInBits() / 8 != Bytes)
7469 SDValue Loc = LD->getOperand(1);
7470 SDValue BaseLoc = Base->getOperand(1);
7471 if (Loc.getOpcode() == ISD::FrameIndex) {
7472 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7474 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7475 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7476 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7477 int FS = MFI.getObjectSize(FI);
7478 int BFS = MFI.getObjectSize(BFI);
7479 if (FS != BFS || FS != (int)Bytes) return false;
7480 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
7484 if (isBaseWithConstantOffset(Loc)) {
7485 int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
7486 if (Loc.getOperand(0) == BaseLoc) {
7487 // If the base location is a simple address with no offset itself, then
7488 // the second load's first add operand should be the base address.
7489 if (LocOffset == Dist * (int)Bytes)
7491 } else if (isBaseWithConstantOffset(BaseLoc)) {
7492 // The base location itself has an offset, so subtract that value from the
7493 // second load's offset before comparing to distance * size.
7495 cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
7496 if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
7497 if ((LocOffset - BOffset) == Dist * (int)Bytes)
7502 const GlobalValue *GV1 = nullptr;
7503 const GlobalValue *GV2 = nullptr;
7504 int64_t Offset1 = 0;
7505 int64_t Offset2 = 0;
7506 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7507 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7508 if (isGA1 && isGA2 && GV1 == GV2)
7509 return Offset1 == (Offset2 + Dist*Bytes);
7514 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
7515 /// it cannot be inferred.
7516 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
7517 // If this is a GlobalAddress + cst, return the alignment.
7518 const GlobalValue *GV;
7519 int64_t GVOffset = 0;
7520 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
7521 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
7522 KnownBits Known(PtrWidth);
7523 llvm::computeKnownBits(const_cast<GlobalValue *>(GV), Known,
7525 unsigned AlignBits = Known.Zero.countTrailingOnes();
7526 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7528 return MinAlign(Align, GVOffset);
7531 // If this is a direct reference to a stack slot, use information about the
7532 // stack slot's alignment.
7533 int FrameIdx = 1 << 31;
7534 int64_t FrameOffset = 0;
7535 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7536 FrameIdx = FI->getIndex();
7537 } else if (isBaseWithConstantOffset(Ptr) &&
7538 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7540 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7541 FrameOffset = Ptr.getConstantOperandVal(1);
7544 if (FrameIdx != (1 << 31)) {
7545 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7546 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7554 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7555 /// which is split (or expanded) into two not necessarily identical pieces.
7556 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7557 // Currently all types are split in half.
7560 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7562 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
7564 return std::make_pair(LoVT, HiVT);
7567 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7569 std::pair<SDValue, SDValue>
7570 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7572 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7573 N.getValueType().getVectorNumElements() &&
7574 "More vector elements requested than available!");
7576 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7577 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7578 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7579 getConstant(LoVT.getVectorNumElements(), DL,
7580 TLI->getVectorIdxTy(getDataLayout())));
7581 return std::make_pair(Lo, Hi);
7584 void SelectionDAG::ExtractVectorElements(SDValue Op,
7585 SmallVectorImpl<SDValue> &Args,
7586 unsigned Start, unsigned Count) {
7587 EVT VT = Op.getValueType();
7589 Count = VT.getVectorNumElements();
7591 EVT EltVT = VT.getVectorElementType();
7592 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7594 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7595 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7596 Op, getConstant(i, SL, IdxTy)));
7600 // getAddressSpace - Return the address space this GlobalAddress belongs to.
7601 unsigned GlobalAddressSDNode::getAddressSpace() const {
7602 return getGlobal()->getType()->getAddressSpace();
7606 Type *ConstantPoolSDNode::getType() const {
7607 if (isMachineConstantPoolEntry())
7608 return Val.MachineCPVal->getType();
7609 return Val.ConstVal->getType();
7612 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
7613 unsigned &SplatBitSize,
7615 unsigned MinSplatBits,
7616 bool IsBigEndian) const {
7617 EVT VT = getValueType(0);
7618 assert(VT.isVector() && "Expected a vector type");
7619 unsigned VecWidth = VT.getSizeInBits();
7620 if (MinSplatBits > VecWidth)
7623 // FIXME: The widths are based on this node's type, but build vectors can
7624 // truncate their operands.
7625 SplatValue = APInt(VecWidth, 0);
7626 SplatUndef = APInt(VecWidth, 0);
7628 // Get the bits. Bits with undefined values (when the corresponding element
7629 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
7630 // in SplatValue. If any of the values are not constant, give up and return
7632 unsigned int NumOps = getNumOperands();
7633 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
7634 unsigned EltWidth = VT.getScalarSizeInBits();
7636 for (unsigned j = 0; j < NumOps; ++j) {
7637 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
7638 SDValue OpVal = getOperand(i);
7639 unsigned BitPos = j * EltWidth;
7641 if (OpVal.isUndef())
7642 SplatUndef.setBits(BitPos, BitPos + EltWidth);
7643 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
7644 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
7645 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
7646 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
7651 // The build_vector is all constants or undefs. Find the smallest element
7652 // size that splats the vector.
7653 HasAnyUndefs = (SplatUndef != 0);
7655 // FIXME: This does not work for vectors with elements less than 8 bits.
7656 while (VecWidth > 8) {
7657 unsigned HalfSize = VecWidth / 2;
7658 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
7659 APInt LowValue = SplatValue.trunc(HalfSize);
7660 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
7661 APInt LowUndef = SplatUndef.trunc(HalfSize);
7663 // If the two halves do not match (ignoring undef bits), stop here.
7664 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
7665 MinSplatBits > HalfSize)
7668 SplatValue = HighValue | LowValue;
7669 SplatUndef = HighUndef & LowUndef;
7671 VecWidth = HalfSize;
7674 SplatBitSize = VecWidth;
7678 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
7679 if (UndefElements) {
7680 UndefElements->clear();
7681 UndefElements->resize(getNumOperands());
7684 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
7685 SDValue Op = getOperand(i);
7688 (*UndefElements)[i] = true;
7689 } else if (!Splatted) {
7691 } else if (Splatted != Op) {
7697 assert(getOperand(0).isUndef() &&
7698 "Can only have a splat without a constant for all undefs.");
7699 return getOperand(0);
7706 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
7707 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
7711 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
7712 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
7716 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
7717 uint32_t BitWidth) const {
7718 if (ConstantFPSDNode *CN =
7719 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
7721 APSInt IntVal(BitWidth);
7722 const APFloat &APF = CN->getValueAPF();
7723 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
7728 return IntVal.exactLogBase2();
7733 bool BuildVectorSDNode::isConstant() const {
7734 for (const SDValue &Op : op_values()) {
7735 unsigned Opc = Op.getOpcode();
7736 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
7742 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
7743 // Find the first non-undef value in the shuffle mask.
7745 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
7748 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7750 // Make sure all remaining elements are either undef or the same as the first
7752 for (int Idx = Mask[i]; i != e; ++i)
7753 if (Mask[i] >= 0 && Mask[i] != Idx)
7758 // \brief Returns the SDNode if it is a constant integer BuildVector
7759 // or constant integer.
7760 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
7761 if (isa<ConstantSDNode>(N))
7763 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
7765 // Treat a GlobalAddress supporting constant offset folding as a
7766 // constant integer.
7767 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
7768 if (GA->getOpcode() == ISD::GlobalAddress &&
7769 TLI->isOffsetFoldingLegal(GA))
7774 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
7775 if (isa<ConstantFPSDNode>(N))
7778 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
7785 static void checkForCyclesHelper(const SDNode *N,
7786 SmallPtrSetImpl<const SDNode*> &Visited,
7787 SmallPtrSetImpl<const SDNode*> &Checked,
7788 const llvm::SelectionDAG *DAG) {
7789 // If this node has already been checked, don't check it again.
7790 if (Checked.count(N))
7793 // If a node has already been visited on this depth-first walk, reject it as
7795 if (!Visited.insert(N).second) {
7796 errs() << "Detected cycle in SelectionDAG\n";
7797 dbgs() << "Offending node:\n";
7798 N->dumprFull(DAG); dbgs() << "\n";
7802 for (const SDValue &Op : N->op_values())
7803 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
7810 void llvm::checkForCycles(const llvm::SDNode *N,
7811 const llvm::SelectionDAG *DAG,
7815 #ifdef EXPENSIVE_CHECKS
7817 #endif // EXPENSIVE_CHECKS
7819 assert(N && "Checking nonexistent SDNode");
7820 SmallPtrSet<const SDNode*, 32> visited;
7821 SmallPtrSet<const SDNode*, 32> checked;
7822 checkForCyclesHelper(N, visited, checked, DAG);
7827 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7828 checkForCycles(DAG->getRoot().getNode(), DAG, force);