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/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/APSInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/CodeGen/ISDOpcodes.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineConstantPool.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineMemOperand.h"
35 #include "llvm/CodeGen/MachineValueType.h"
36 #include "llvm/CodeGen/RuntimeLibcalls.h"
37 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
38 #include "llvm/CodeGen/SelectionDAGNodes.h"
39 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
40 #include "llvm/CodeGen/TargetLowering.h"
41 #include "llvm/CodeGen/TargetRegisterInfo.h"
42 #include "llvm/CodeGen/TargetSubtargetInfo.h"
43 #include "llvm/CodeGen/ValueTypes.h"
44 #include "llvm/IR/Constant.h"
45 #include "llvm/IR/Constants.h"
46 #include "llvm/IR/DataLayout.h"
47 #include "llvm/IR/DebugInfoMetadata.h"
48 #include "llvm/IR/DebugLoc.h"
49 #include "llvm/IR/DerivedTypes.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/GlobalValue.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Type.h"
54 #include "llvm/IR/Value.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/CodeGen.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/KnownBits.h"
61 #include "llvm/Support/ManagedStatic.h"
62 #include "llvm/Support/MathExtras.h"
63 #include "llvm/Support/Mutex.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Target/TargetMachine.h"
66 #include "llvm/Target/TargetOptions.h"
79 /// makeVTList - Return an instance of the SDVTList struct initialized with the
80 /// specified members.
81 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
82 SDVTList Res = {VTs, NumVTs};
86 // Default null implementations of the callbacks.
87 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
88 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
90 #define DEBUG_TYPE "selectiondag"
92 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
99 //===----------------------------------------------------------------------===//
100 // ConstantFPSDNode Class
101 //===----------------------------------------------------------------------===//
103 /// isExactlyValue - We don't rely on operator== working on double values, as
104 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
105 /// As such, this method can be used to do an exact bit-for-bit comparison of
106 /// two floating point values.
107 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
108 return getValueAPF().bitwiseIsEqual(V);
111 bool ConstantFPSDNode::isValueValidForType(EVT VT,
112 const APFloat& Val) {
113 assert(VT.isFloatingPoint() && "Can only convert between FP types");
115 // convert modifies in place, so make a copy.
116 APFloat Val2 = APFloat(Val);
118 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
119 APFloat::rmNearestTiesToEven,
124 //===----------------------------------------------------------------------===//
126 //===----------------------------------------------------------------------===//
128 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
129 auto *BV = dyn_cast<BuildVectorSDNode>(N);
134 unsigned SplatBitSize;
136 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
137 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
139 EltSize == SplatBitSize;
142 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
143 // specializations of the more general isConstantSplatVector()?
145 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
146 // Look through a bit convert.
147 while (N->getOpcode() == ISD::BITCAST)
148 N = N->getOperand(0).getNode();
150 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
152 unsigned i = 0, e = N->getNumOperands();
154 // Skip over all of the undef values.
155 while (i != e && N->getOperand(i).isUndef())
158 // Do not accept an all-undef vector.
159 if (i == e) return false;
161 // Do not accept build_vectors that aren't all constants or which have non-~0
162 // elements. We have to be a bit careful here, as the type of the constant
163 // may not be the same as the type of the vector elements due to type
164 // legalization (the elements are promoted to a legal type for the target and
165 // a vector of a type may be legal when the base element type is not).
166 // We only want to check enough bits to cover the vector elements, because
167 // we care if the resultant vector is all ones, not whether the individual
169 SDValue NotZero = N->getOperand(i);
170 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
171 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
172 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
174 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
175 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
180 // Okay, we have at least one ~0 value, check to see if the rest match or are
181 // undefs. Even with the above element type twiddling, this should be OK, as
182 // the same type legalization should have applied to all the elements.
183 for (++i; i != e; ++i)
184 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
189 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
190 // Look through a bit convert.
191 while (N->getOpcode() == ISD::BITCAST)
192 N = N->getOperand(0).getNode();
194 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
196 bool IsAllUndef = true;
197 for (const SDValue &Op : N->op_values()) {
201 // Do not accept build_vectors that aren't all constants or which have non-0
202 // elements. We have to be a bit careful here, as the type of the constant
203 // may not be the same as the type of the vector elements due to type
204 // legalization (the elements are promoted to a legal type for the target
205 // and a vector of a type may be legal when the base element type is not).
206 // We only want to check enough bits to cover the vector elements, because
207 // we care if the resultant vector is all zeros, not whether the individual
209 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
210 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
211 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
213 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
214 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
220 // Do not accept an all-undef vector.
226 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
227 if (N->getOpcode() != ISD::BUILD_VECTOR)
230 for (const SDValue &Op : N->op_values()) {
233 if (!isa<ConstantSDNode>(Op))
239 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
240 if (N->getOpcode() != ISD::BUILD_VECTOR)
243 for (const SDValue &Op : N->op_values()) {
246 if (!isa<ConstantFPSDNode>(Op))
252 bool ISD::allOperandsUndef(const SDNode *N) {
253 // Return false if the node has no operands.
254 // This is "logically inconsistent" with the definition of "all" but
255 // is probably the desired behavior.
256 if (N->getNumOperands() == 0)
259 for (const SDValue &Op : N->op_values())
266 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
269 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
271 return ISD::SIGN_EXTEND;
273 return ISD::ZERO_EXTEND;
278 llvm_unreachable("Invalid LoadExtType");
281 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
282 // To perform this operation, we just need to swap the L and G bits of the
284 unsigned OldL = (Operation >> 2) & 1;
285 unsigned OldG = (Operation >> 1) & 1;
286 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
287 (OldL << 1) | // New G bit
288 (OldG << 2)); // New L bit.
291 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
292 unsigned Operation = Op;
294 Operation ^= 7; // Flip L, G, E bits, but not U.
296 Operation ^= 15; // Flip all of the condition bits.
298 if (Operation > ISD::SETTRUE2)
299 Operation &= ~8; // Don't let N and U bits get set.
301 return ISD::CondCode(Operation);
304 /// For an integer comparison, return 1 if the comparison is a signed operation
305 /// and 2 if the result is an unsigned comparison. Return zero if the operation
306 /// does not depend on the sign of the input (setne and seteq).
307 static int isSignedOp(ISD::CondCode Opcode) {
309 default: llvm_unreachable("Illegal integer setcc operation!");
311 case ISD::SETNE: return 0;
315 case ISD::SETGE: return 1;
319 case ISD::SETUGE: return 2;
323 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
325 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
326 // Cannot fold a signed integer setcc with an unsigned integer setcc.
327 return ISD::SETCC_INVALID;
329 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
331 // If the N and U bits get set, then the resultant comparison DOES suddenly
332 // care about orderedness, and it is true when ordered.
333 if (Op > ISD::SETTRUE2)
334 Op &= ~16; // Clear the U bit if the N bit is set.
336 // Canonicalize illegal integer setcc's.
337 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
340 return ISD::CondCode(Op);
343 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
345 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
346 // Cannot fold a signed setcc with an unsigned setcc.
347 return ISD::SETCC_INVALID;
349 // Combine all of the condition bits.
350 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
352 // Canonicalize illegal integer setcc's.
356 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
357 case ISD::SETOEQ: // SETEQ & SETU[LG]E
358 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
359 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
360 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
367 //===----------------------------------------------------------------------===//
368 // SDNode Profile Support
369 //===----------------------------------------------------------------------===//
371 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
372 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
376 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
377 /// solely with their pointer.
378 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
379 ID.AddPointer(VTList.VTs);
382 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
383 static void AddNodeIDOperands(FoldingSetNodeID &ID,
384 ArrayRef<SDValue> Ops) {
385 for (auto& Op : Ops) {
386 ID.AddPointer(Op.getNode());
387 ID.AddInteger(Op.getResNo());
391 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
392 static void AddNodeIDOperands(FoldingSetNodeID &ID,
393 ArrayRef<SDUse> Ops) {
394 for (auto& Op : Ops) {
395 ID.AddPointer(Op.getNode());
396 ID.AddInteger(Op.getResNo());
400 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
401 SDVTList VTList, ArrayRef<SDValue> OpList) {
402 AddNodeIDOpcode(ID, OpC);
403 AddNodeIDValueTypes(ID, VTList);
404 AddNodeIDOperands(ID, OpList);
407 /// If this is an SDNode with special info, add this info to the NodeID data.
408 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
409 switch (N->getOpcode()) {
410 case ISD::TargetExternalSymbol:
411 case ISD::ExternalSymbol:
413 llvm_unreachable("Should only be used on nodes with operands");
414 default: break; // Normal nodes don't need extra info.
415 case ISD::TargetConstant:
416 case ISD::Constant: {
417 const ConstantSDNode *C = cast<ConstantSDNode>(N);
418 ID.AddPointer(C->getConstantIntValue());
419 ID.AddBoolean(C->isOpaque());
422 case ISD::TargetConstantFP:
423 case ISD::ConstantFP:
424 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
426 case ISD::TargetGlobalAddress:
427 case ISD::GlobalAddress:
428 case ISD::TargetGlobalTLSAddress:
429 case ISD::GlobalTLSAddress: {
430 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
431 ID.AddPointer(GA->getGlobal());
432 ID.AddInteger(GA->getOffset());
433 ID.AddInteger(GA->getTargetFlags());
436 case ISD::BasicBlock:
437 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
440 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
442 case ISD::RegisterMask:
443 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
446 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
448 case ISD::FrameIndex:
449 case ISD::TargetFrameIndex:
450 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
453 case ISD::TargetJumpTable:
454 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
455 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
457 case ISD::ConstantPool:
458 case ISD::TargetConstantPool: {
459 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
460 ID.AddInteger(CP->getAlignment());
461 ID.AddInteger(CP->getOffset());
462 if (CP->isMachineConstantPoolEntry())
463 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
465 ID.AddPointer(CP->getConstVal());
466 ID.AddInteger(CP->getTargetFlags());
469 case ISD::TargetIndex: {
470 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
471 ID.AddInteger(TI->getIndex());
472 ID.AddInteger(TI->getOffset());
473 ID.AddInteger(TI->getTargetFlags());
477 const LoadSDNode *LD = cast<LoadSDNode>(N);
478 ID.AddInteger(LD->getMemoryVT().getRawBits());
479 ID.AddInteger(LD->getRawSubclassData());
480 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
484 const StoreSDNode *ST = cast<StoreSDNode>(N);
485 ID.AddInteger(ST->getMemoryVT().getRawBits());
486 ID.AddInteger(ST->getRawSubclassData());
487 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
490 case ISD::ATOMIC_CMP_SWAP:
491 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
492 case ISD::ATOMIC_SWAP:
493 case ISD::ATOMIC_LOAD_ADD:
494 case ISD::ATOMIC_LOAD_SUB:
495 case ISD::ATOMIC_LOAD_AND:
496 case ISD::ATOMIC_LOAD_OR:
497 case ISD::ATOMIC_LOAD_XOR:
498 case ISD::ATOMIC_LOAD_NAND:
499 case ISD::ATOMIC_LOAD_MIN:
500 case ISD::ATOMIC_LOAD_MAX:
501 case ISD::ATOMIC_LOAD_UMIN:
502 case ISD::ATOMIC_LOAD_UMAX:
503 case ISD::ATOMIC_LOAD:
504 case ISD::ATOMIC_STORE: {
505 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
506 ID.AddInteger(AT->getMemoryVT().getRawBits());
507 ID.AddInteger(AT->getRawSubclassData());
508 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
511 case ISD::PREFETCH: {
512 const MemSDNode *PF = cast<MemSDNode>(N);
513 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
516 case ISD::VECTOR_SHUFFLE: {
517 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
518 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
520 ID.AddInteger(SVN->getMaskElt(i));
523 case ISD::TargetBlockAddress:
524 case ISD::BlockAddress: {
525 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
526 ID.AddPointer(BA->getBlockAddress());
527 ID.AddInteger(BA->getOffset());
528 ID.AddInteger(BA->getTargetFlags());
531 } // end switch (N->getOpcode())
533 // Target specific memory nodes could also have address spaces to check.
534 if (N->isTargetMemoryOpcode())
535 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
538 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
540 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
541 AddNodeIDOpcode(ID, N->getOpcode());
542 // Add the return value info.
543 AddNodeIDValueTypes(ID, N->getVTList());
544 // Add the operand info.
545 AddNodeIDOperands(ID, N->ops());
547 // Handle SDNode leafs with special info.
548 AddNodeIDCustom(ID, N);
551 //===----------------------------------------------------------------------===//
552 // SelectionDAG Class
553 //===----------------------------------------------------------------------===//
555 /// doNotCSE - Return true if CSE should not be performed for this node.
556 static bool doNotCSE(SDNode *N) {
557 if (N->getValueType(0) == MVT::Glue)
558 return true; // Never CSE anything that produces a flag.
560 switch (N->getOpcode()) {
562 case ISD::HANDLENODE:
564 return true; // Never CSE these nodes.
567 // Check that remaining values produced are not flags.
568 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
569 if (N->getValueType(i) == MVT::Glue)
570 return true; // Never CSE anything that produces a flag.
575 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
577 void SelectionDAG::RemoveDeadNodes() {
578 // Create a dummy node (which is not added to allnodes), that adds a reference
579 // to the root node, preventing it from being deleted.
580 HandleSDNode Dummy(getRoot());
582 SmallVector<SDNode*, 128> DeadNodes;
584 // Add all obviously-dead nodes to the DeadNodes worklist.
585 for (SDNode &Node : allnodes())
586 if (Node.use_empty())
587 DeadNodes.push_back(&Node);
589 RemoveDeadNodes(DeadNodes);
591 // If the root changed (e.g. it was a dead load, update the root).
592 setRoot(Dummy.getValue());
595 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
596 /// given list, and any nodes that become unreachable as a result.
597 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
599 // Process the worklist, deleting the nodes and adding their uses to the
601 while (!DeadNodes.empty()) {
602 SDNode *N = DeadNodes.pop_back_val();
603 // Skip to next node if we've already managed to delete the node. This could
604 // happen if replacing a node causes a node previously added to the node to
606 if (N->getOpcode() == ISD::DELETED_NODE)
609 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
610 DUL->NodeDeleted(N, nullptr);
612 // Take the node out of the appropriate CSE map.
613 RemoveNodeFromCSEMaps(N);
615 // Next, brutally remove the operand list. This is safe to do, as there are
616 // no cycles in the graph.
617 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
619 SDNode *Operand = Use.getNode();
622 // Now that we removed this operand, see if there are no uses of it left.
623 if (Operand->use_empty())
624 DeadNodes.push_back(Operand);
631 void SelectionDAG::RemoveDeadNode(SDNode *N){
632 SmallVector<SDNode*, 16> DeadNodes(1, N);
634 // Create a dummy node that adds a reference to the root node, preventing
635 // it from being deleted. (This matters if the root is an operand of the
637 HandleSDNode Dummy(getRoot());
639 RemoveDeadNodes(DeadNodes);
642 void SelectionDAG::DeleteNode(SDNode *N) {
643 // First take this out of the appropriate CSE map.
644 RemoveNodeFromCSEMaps(N);
646 // Finally, remove uses due to operands of this node, remove from the
647 // AllNodes list, and delete the node.
648 DeleteNodeNotInCSEMaps(N);
651 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
652 assert(N->getIterator() != AllNodes.begin() &&
653 "Cannot delete the entry node!");
654 assert(N->use_empty() && "Cannot delete a node that is not dead!");
656 // Drop all of the operands and decrement used node's use counts.
662 void SDDbgInfo::erase(const SDNode *Node) {
663 DbgValMapType::iterator I = DbgValMap.find(Node);
664 if (I == DbgValMap.end())
666 for (auto &Val: I->second)
667 Val->setIsInvalidated();
671 void SelectionDAG::DeallocateNode(SDNode *N) {
672 // If we have operands, deallocate them.
675 NodeAllocator.Deallocate(AllNodes.remove(N));
677 // Set the opcode to DELETED_NODE to help catch bugs when node
678 // memory is reallocated.
679 // FIXME: There are places in SDag that have grown a dependency on the opcode
680 // value in the released node.
681 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
682 N->NodeType = ISD::DELETED_NODE;
684 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
685 // them and forget about that node.
690 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
691 static void VerifySDNode(SDNode *N) {
692 switch (N->getOpcode()) {
695 case ISD::BUILD_PAIR: {
696 EVT VT = N->getValueType(0);
697 assert(N->getNumValues() == 1 && "Too many results!");
698 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
699 "Wrong return type!");
700 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
701 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
702 "Mismatched operand types!");
703 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
704 "Wrong operand type!");
705 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
706 "Wrong return type size");
709 case ISD::BUILD_VECTOR: {
710 assert(N->getNumValues() == 1 && "Too many results!");
711 assert(N->getValueType(0).isVector() && "Wrong return type!");
712 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
713 "Wrong number of operands!");
714 EVT EltVT = N->getValueType(0).getVectorElementType();
715 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
716 assert((I->getValueType() == EltVT ||
717 (EltVT.isInteger() && I->getValueType().isInteger() &&
718 EltVT.bitsLE(I->getValueType()))) &&
719 "Wrong operand type!");
720 assert(I->getValueType() == N->getOperand(0).getValueType() &&
721 "Operands must all have the same type");
729 /// \brief Insert a newly allocated node into the DAG.
731 /// Handles insertion into the all nodes list and CSE map, as well as
732 /// verification and other common operations when a new node is allocated.
733 void SelectionDAG::InsertNode(SDNode *N) {
734 AllNodes.push_back(N);
736 N->PersistentId = NextPersistentId++;
741 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
742 /// correspond to it. This is useful when we're about to delete or repurpose
743 /// the node. We don't want future request for structurally identical nodes
744 /// to return N anymore.
745 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
747 switch (N->getOpcode()) {
748 case ISD::HANDLENODE: return false; // noop.
750 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
751 "Cond code doesn't exist!");
752 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
753 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
755 case ISD::ExternalSymbol:
756 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
758 case ISD::TargetExternalSymbol: {
759 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
760 Erased = TargetExternalSymbols.erase(
761 std::pair<std::string,unsigned char>(ESN->getSymbol(),
762 ESN->getTargetFlags()));
765 case ISD::MCSymbol: {
766 auto *MCSN = cast<MCSymbolSDNode>(N);
767 Erased = MCSymbols.erase(MCSN->getMCSymbol());
770 case ISD::VALUETYPE: {
771 EVT VT = cast<VTSDNode>(N)->getVT();
772 if (VT.isExtended()) {
773 Erased = ExtendedValueTypeNodes.erase(VT);
775 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
776 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
781 // Remove it from the CSE Map.
782 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
783 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
784 Erased = CSEMap.RemoveNode(N);
788 // Verify that the node was actually in one of the CSE maps, unless it has a
789 // flag result (which cannot be CSE'd) or is one of the special cases that are
790 // not subject to CSE.
791 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
792 !N->isMachineOpcode() && !doNotCSE(N)) {
795 llvm_unreachable("Node is not in map!");
801 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
802 /// maps and modified in place. Add it back to the CSE maps, unless an identical
803 /// node already exists, in which case transfer all its users to the existing
804 /// node. This transfer can potentially trigger recursive merging.
806 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
807 // For node types that aren't CSE'd, just act as if no identical node
810 SDNode *Existing = CSEMap.GetOrInsertNode(N);
812 // If there was already an existing matching node, use ReplaceAllUsesWith
813 // to replace the dead one with the existing one. This can cause
814 // recursive merging of other unrelated nodes down the line.
815 ReplaceAllUsesWith(N, Existing);
817 // N is now dead. Inform the listeners and delete it.
818 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
819 DUL->NodeDeleted(N, Existing);
820 DeleteNodeNotInCSEMaps(N);
825 // If the node doesn't already exist, we updated it. Inform listeners.
826 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
830 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
831 /// were replaced with those specified. If this node is never memoized,
832 /// return null, otherwise return a pointer to the slot it would take. If a
833 /// node already exists with these operands, the slot will be non-null.
834 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
839 SDValue Ops[] = { Op };
841 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
842 AddNodeIDCustom(ID, N);
843 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
845 Node->intersectFlagsWith(N->getFlags());
849 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
850 /// were replaced with those specified. If this node is never memoized,
851 /// return null, otherwise return a pointer to the slot it would take. If a
852 /// node already exists with these operands, the slot will be non-null.
853 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
854 SDValue Op1, SDValue Op2,
859 SDValue Ops[] = { Op1, Op2 };
861 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
862 AddNodeIDCustom(ID, N);
863 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
865 Node->intersectFlagsWith(N->getFlags());
869 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
870 /// were replaced with those specified. If this node is never memoized,
871 /// return null, otherwise return a pointer to the slot it would take. If a
872 /// node already exists with these operands, the slot will be non-null.
873 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
879 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
880 AddNodeIDCustom(ID, N);
881 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
883 Node->intersectFlagsWith(N->getFlags());
887 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
888 Type *Ty = VT == MVT::iPTR ?
889 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
890 VT.getTypeForEVT(*getContext());
892 return getDataLayout().getABITypeAlignment(Ty);
895 // EntryNode could meaningfully have debug info if we can find it...
896 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
897 : TM(tm), OptLevel(OL),
898 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
899 Root(getEntryNode()) {
900 InsertNode(&EntryNode);
901 DbgInfo = new SDDbgInfo();
904 void SelectionDAG::init(MachineFunction &NewMF,
905 OptimizationRemarkEmitter &NewORE,
908 SDAGISelPass = PassPtr;
910 TLI = getSubtarget().getTargetLowering();
911 TSI = getSubtarget().getSelectionDAGInfo();
912 Context = &MF->getFunction()->getContext();
915 SelectionDAG::~SelectionDAG() {
916 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
918 OperandRecycler.clear(OperandAllocator);
922 void SelectionDAG::allnodes_clear() {
923 assert(&*AllNodes.begin() == &EntryNode);
924 AllNodes.remove(AllNodes.begin());
925 while (!AllNodes.empty())
926 DeallocateNode(&AllNodes.front());
928 NextPersistentId = 0;
932 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
934 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
936 switch (N->getOpcode()) {
939 case ISD::ConstantFP:
940 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
941 "debug location. Use another overload.");
947 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
948 const SDLoc &DL, void *&InsertPos) {
949 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
951 switch (N->getOpcode()) {
953 case ISD::ConstantFP:
954 // Erase debug location from the node if the node is used at several
955 // different places. Do not propagate one location to all uses as it
956 // will cause a worse single stepping debugging experience.
957 if (N->getDebugLoc() != DL.getDebugLoc())
958 N->setDebugLoc(DebugLoc());
961 // When the node's point of use is located earlier in the instruction
962 // sequence than its prior point of use, update its debug info to the
964 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
965 N->setDebugLoc(DL.getDebugLoc());
972 void SelectionDAG::clear() {
974 OperandRecycler.clear(OperandAllocator);
975 OperandAllocator.Reset();
978 ExtendedValueTypeNodes.clear();
979 ExternalSymbols.clear();
980 TargetExternalSymbols.clear();
982 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
983 static_cast<CondCodeSDNode*>(nullptr));
984 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
985 static_cast<SDNode*>(nullptr));
987 EntryNode.UseList = nullptr;
988 InsertNode(&EntryNode);
989 Root = getEntryNode();
993 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
994 return VT.bitsGT(Op.getValueType())
995 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
996 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
999 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1000 return VT.bitsGT(Op.getValueType()) ?
1001 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1002 getNode(ISD::TRUNCATE, DL, VT, Op);
1005 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1006 return VT.bitsGT(Op.getValueType()) ?
1007 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1008 getNode(ISD::TRUNCATE, DL, VT, Op);
1011 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1012 return VT.bitsGT(Op.getValueType()) ?
1013 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1014 getNode(ISD::TRUNCATE, DL, VT, Op);
1017 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1019 if (VT.bitsLE(Op.getValueType()))
1020 return getNode(ISD::TRUNCATE, SL, VT, Op);
1022 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1023 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1026 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1027 assert(!VT.isVector() &&
1028 "getZeroExtendInReg should use the vector element type instead of "
1029 "the vector type!");
1030 if (Op.getValueType().getScalarType() == VT) return Op;
1031 unsigned BitWidth = Op.getScalarValueSizeInBits();
1032 APInt Imm = APInt::getLowBitsSet(BitWidth,
1033 VT.getSizeInBits());
1034 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1035 getConstant(Imm, DL, Op.getValueType()));
1038 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL,
1040 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1041 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1042 "The sizes of the input and result must match in order to perform the "
1043 "extend in-register.");
1044 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1045 "The destination vector type must have fewer lanes than the input.");
1046 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1049 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL,
1051 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1052 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1053 "The sizes of the input and result must match in order to perform the "
1054 "extend in-register.");
1055 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1056 "The destination vector type must have fewer lanes than the input.");
1057 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1060 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL,
1062 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1063 assert(VT.getSizeInBits() == Op.getValueSizeInBits() &&
1064 "The sizes of the input and result must match in order to perform the "
1065 "extend in-register.");
1066 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1067 "The destination vector type must have fewer lanes than the input.");
1068 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1071 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1072 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1073 EVT EltVT = VT.getScalarType();
1075 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1076 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1079 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1080 EVT EltVT = VT.getScalarType();
1082 switch (TLI->getBooleanContents(VT)) {
1083 case TargetLowering::ZeroOrOneBooleanContent:
1084 case TargetLowering::UndefinedBooleanContent:
1085 TrueValue = getConstant(1, DL, VT);
1087 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1088 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL,
1092 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1095 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1096 bool isT, bool isO) {
1097 EVT EltVT = VT.getScalarType();
1098 assert((EltVT.getSizeInBits() >= 64 ||
1099 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1100 "getConstant with a uint64_t value that doesn't fit in the type!");
1101 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1104 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1105 bool isT, bool isO) {
1106 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1109 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1110 EVT VT, bool isT, bool isO) {
1111 assert(VT.isInteger() && "Cannot create FP integer constant!");
1113 EVT EltVT = VT.getScalarType();
1114 const ConstantInt *Elt = &Val;
1116 // In some cases the vector type is legal but the element type is illegal and
1117 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1118 // inserted value (the type does not need to match the vector element type).
1119 // Any extra bits introduced will be truncated away.
1120 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1121 TargetLowering::TypePromoteInteger) {
1122 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1123 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1124 Elt = ConstantInt::get(*getContext(), NewVal);
1126 // In other cases the element type is illegal and needs to be expanded, for
1127 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1128 // the value into n parts and use a vector type with n-times the elements.
1129 // Then bitcast to the type requested.
1130 // Legalizing constants too early makes the DAGCombiner's job harder so we
1131 // only legalize if the DAG tells us we must produce legal types.
1132 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1133 TLI->getTypeAction(*getContext(), EltVT) ==
1134 TargetLowering::TypeExpandInteger) {
1135 const APInt &NewVal = Elt->getValue();
1136 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1137 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1138 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1139 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1141 // Check the temporary vector is the correct size. If this fails then
1142 // getTypeToTransformTo() probably returned a type whose size (in bits)
1143 // isn't a power-of-2 factor of the requested type size.
1144 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1146 SmallVector<SDValue, 2> EltParts;
1147 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1148 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1149 .zextOrTrunc(ViaEltSizeInBits), DL,
1150 ViaEltVT, isT, isO));
1153 // EltParts is currently in little endian order. If we actually want
1154 // big-endian order then reverse it now.
1155 if (getDataLayout().isBigEndian())
1156 std::reverse(EltParts.begin(), EltParts.end());
1158 // The elements must be reversed when the element order is different
1159 // to the endianness of the elements (because the BITCAST is itself a
1160 // vector shuffle in this situation). However, we do not need any code to
1161 // perform this reversal because getConstant() is producing a vector
1163 // This situation occurs in MIPS MSA.
1165 SmallVector<SDValue, 8> Ops;
1166 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1167 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1169 SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1170 NewSDValueDbgMsg(V, "Creating constant: ", this);
1174 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1175 "APInt size does not match type size!");
1176 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1177 FoldingSetNodeID ID;
1178 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1182 SDNode *N = nullptr;
1183 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1185 return SDValue(N, 0);
1188 N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT);
1189 CSEMap.InsertNode(N, IP);
1193 SDValue Result(N, 0);
1195 Result = getSplatBuildVector(VT, DL, Result);
1197 NewSDValueDbgMsg(Result, "Creating constant: ", this);
1201 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1203 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1206 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1208 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1211 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1212 EVT VT, bool isTarget) {
1213 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1215 EVT EltVT = VT.getScalarType();
1217 // Do the map lookup using the actual bit pattern for the floating point
1218 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1219 // we don't have issues with SNANs.
1220 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1221 FoldingSetNodeID ID;
1222 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1225 SDNode *N = nullptr;
1226 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1228 return SDValue(N, 0);
1231 N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT);
1232 CSEMap.InsertNode(N, IP);
1236 SDValue Result(N, 0);
1238 Result = getSplatBuildVector(VT, DL, Result);
1239 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1243 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1245 EVT EltVT = VT.getScalarType();
1246 if (EltVT == MVT::f32)
1247 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1248 else if (EltVT == MVT::f64)
1249 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1250 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1251 EltVT == MVT::f16) {
1253 APFloat APF = APFloat(Val);
1254 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1256 return getConstantFP(APF, DL, VT, isTarget);
1258 llvm_unreachable("Unsupported type in getConstantFP");
1261 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1262 EVT VT, int64_t Offset, bool isTargetGA,
1263 unsigned char TargetFlags) {
1264 assert((TargetFlags == 0 || isTargetGA) &&
1265 "Cannot set target flags on target-independent globals");
1267 // Truncate (with sign-extension) the offset value to the pointer size.
1268 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1270 Offset = SignExtend64(Offset, BitWidth);
1273 if (GV->isThreadLocal())
1274 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1276 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1278 FoldingSetNodeID ID;
1279 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1281 ID.AddInteger(Offset);
1282 ID.AddInteger(TargetFlags);
1284 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1285 return SDValue(E, 0);
1287 auto *N = newSDNode<GlobalAddressSDNode>(
1288 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1289 CSEMap.InsertNode(N, IP);
1291 return SDValue(N, 0);
1294 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1295 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1296 FoldingSetNodeID ID;
1297 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1300 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1301 return SDValue(E, 0);
1303 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1304 CSEMap.InsertNode(N, IP);
1306 return SDValue(N, 0);
1309 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1310 unsigned char TargetFlags) {
1311 assert((TargetFlags == 0 || isTarget) &&
1312 "Cannot set target flags on target-independent jump tables");
1313 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1314 FoldingSetNodeID ID;
1315 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1317 ID.AddInteger(TargetFlags);
1319 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1320 return SDValue(E, 0);
1322 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1323 CSEMap.InsertNode(N, IP);
1325 return SDValue(N, 0);
1328 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1329 unsigned Alignment, int Offset,
1331 unsigned char TargetFlags) {
1332 assert((TargetFlags == 0 || isTarget) &&
1333 "Cannot set target flags on target-independent globals");
1335 Alignment = MF->getFunction()->optForSize()
1336 ? getDataLayout().getABITypeAlignment(C->getType())
1337 : getDataLayout().getPrefTypeAlignment(C->getType());
1338 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1339 FoldingSetNodeID ID;
1340 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1341 ID.AddInteger(Alignment);
1342 ID.AddInteger(Offset);
1344 ID.AddInteger(TargetFlags);
1346 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1347 return SDValue(E, 0);
1349 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1351 CSEMap.InsertNode(N, IP);
1353 return SDValue(N, 0);
1356 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1357 unsigned Alignment, int Offset,
1359 unsigned char TargetFlags) {
1360 assert((TargetFlags == 0 || isTarget) &&
1361 "Cannot set target flags on target-independent globals");
1363 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1364 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1365 FoldingSetNodeID ID;
1366 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1367 ID.AddInteger(Alignment);
1368 ID.AddInteger(Offset);
1369 C->addSelectionDAGCSEId(ID);
1370 ID.AddInteger(TargetFlags);
1372 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1373 return SDValue(E, 0);
1375 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1377 CSEMap.InsertNode(N, IP);
1379 return SDValue(N, 0);
1382 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1383 unsigned char TargetFlags) {
1384 FoldingSetNodeID ID;
1385 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1386 ID.AddInteger(Index);
1387 ID.AddInteger(Offset);
1388 ID.AddInteger(TargetFlags);
1390 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1391 return SDValue(E, 0);
1393 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1394 CSEMap.InsertNode(N, IP);
1396 return SDValue(N, 0);
1399 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1400 FoldingSetNodeID ID;
1401 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1404 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1405 return SDValue(E, 0);
1407 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1408 CSEMap.InsertNode(N, IP);
1410 return SDValue(N, 0);
1413 SDValue SelectionDAG::getValueType(EVT VT) {
1414 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1415 ValueTypeNodes.size())
1416 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1418 SDNode *&N = VT.isExtended() ?
1419 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1421 if (N) return SDValue(N, 0);
1422 N = newSDNode<VTSDNode>(VT);
1424 return SDValue(N, 0);
1427 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1428 SDNode *&N = ExternalSymbols[Sym];
1429 if (N) return SDValue(N, 0);
1430 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1432 return SDValue(N, 0);
1435 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1436 SDNode *&N = MCSymbols[Sym];
1438 return SDValue(N, 0);
1439 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1441 return SDValue(N, 0);
1444 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1445 unsigned char TargetFlags) {
1447 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1449 if (N) return SDValue(N, 0);
1450 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1452 return SDValue(N, 0);
1455 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1456 if ((unsigned)Cond >= CondCodeNodes.size())
1457 CondCodeNodes.resize(Cond+1);
1459 if (!CondCodeNodes[Cond]) {
1460 auto *N = newSDNode<CondCodeSDNode>(Cond);
1461 CondCodeNodes[Cond] = N;
1465 return SDValue(CondCodeNodes[Cond], 0);
1468 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1469 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1470 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1472 ShuffleVectorSDNode::commuteMask(M);
1475 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1476 SDValue N2, ArrayRef<int> Mask) {
1477 assert(VT.getVectorNumElements() == Mask.size() &&
1478 "Must have the same number of vector elements as mask elements!");
1479 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1480 "Invalid VECTOR_SHUFFLE");
1482 // Canonicalize shuffle undef, undef -> undef
1483 if (N1.isUndef() && N2.isUndef())
1484 return getUNDEF(VT);
1486 // Validate that all indices in Mask are within the range of the elements
1487 // input to the shuffle.
1488 int NElts = Mask.size();
1489 assert(llvm::all_of(Mask,
1490 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1491 "Index out of range");
1493 // Copy the mask so we can do any needed cleanup.
1494 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1496 // Canonicalize shuffle v, v -> v, undef
1499 for (int i = 0; i != NElts; ++i)
1500 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1503 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1505 commuteShuffle(N1, N2, MaskVec);
1507 // If shuffling a splat, try to blend the splat instead. We do this here so
1508 // that even when this arises during lowering we don't have to re-handle it.
1509 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1510 BitVector UndefElements;
1511 SDValue Splat = BV->getSplatValue(&UndefElements);
1515 for (int i = 0; i < NElts; ++i) {
1516 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1519 // If this input comes from undef, mark it as such.
1520 if (UndefElements[MaskVec[i] - Offset]) {
1525 // If we can blend a non-undef lane, use that instead.
1526 if (!UndefElements[i])
1527 MaskVec[i] = i + Offset;
1530 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1531 BlendSplat(N1BV, 0);
1532 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1533 BlendSplat(N2BV, NElts);
1535 // Canonicalize all index into lhs, -> shuffle lhs, undef
1536 // Canonicalize all index into rhs, -> shuffle rhs, undef
1537 bool AllLHS = true, AllRHS = true;
1538 bool N2Undef = N2.isUndef();
1539 for (int i = 0; i != NElts; ++i) {
1540 if (MaskVec[i] >= NElts) {
1545 } else if (MaskVec[i] >= 0) {
1549 if (AllLHS && AllRHS)
1550 return getUNDEF(VT);
1551 if (AllLHS && !N2Undef)
1555 commuteShuffle(N1, N2, MaskVec);
1557 // Reset our undef status after accounting for the mask.
1558 N2Undef = N2.isUndef();
1559 // Re-check whether both sides ended up undef.
1560 if (N1.isUndef() && N2Undef)
1561 return getUNDEF(VT);
1563 // If Identity shuffle return that node.
1564 bool Identity = true, AllSame = true;
1565 for (int i = 0; i != NElts; ++i) {
1566 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1567 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1569 if (Identity && NElts)
1572 // Shuffling a constant splat doesn't change the result.
1576 // Look through any bitcasts. We check that these don't change the number
1577 // (and size) of elements and just changes their types.
1578 while (V.getOpcode() == ISD::BITCAST)
1579 V = V->getOperand(0);
1581 // A splat should always show up as a build vector node.
1582 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1583 BitVector UndefElements;
1584 SDValue Splat = BV->getSplatValue(&UndefElements);
1585 // If this is a splat of an undef, shuffling it is also undef.
1586 if (Splat && Splat.isUndef())
1587 return getUNDEF(VT);
1590 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1592 // We only have a splat which can skip shuffles if there is a splatted
1593 // value and no undef lanes rearranged by the shuffle.
1594 if (Splat && UndefElements.none()) {
1595 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1596 // number of elements match or the value splatted is a zero constant.
1599 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1600 if (C->isNullValue())
1604 // If the shuffle itself creates a splat, build the vector directly.
1605 if (AllSame && SameNumElts) {
1606 EVT BuildVT = BV->getValueType(0);
1607 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1608 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1610 // We may have jumped through bitcasts, so the type of the
1611 // BUILD_VECTOR may not match the type of the shuffle.
1613 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1619 FoldingSetNodeID ID;
1620 SDValue Ops[2] = { N1, N2 };
1621 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1622 for (int i = 0; i != NElts; ++i)
1623 ID.AddInteger(MaskVec[i]);
1626 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1627 return SDValue(E, 0);
1629 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1630 // SDNode doesn't have access to it. This memory will be "leaked" when
1631 // the node is deallocated, but recovered when the NodeAllocator is released.
1632 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1633 std::copy(MaskVec.begin(), MaskVec.end(), MaskAlloc);
1635 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1636 dl.getDebugLoc(), MaskAlloc);
1637 createOperands(N, Ops);
1639 CSEMap.InsertNode(N, IP);
1641 SDValue V = SDValue(N, 0);
1642 NewSDValueDbgMsg(V, "Creating new node: ", this);
1646 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1647 MVT VT = SV.getSimpleValueType(0);
1648 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1649 ShuffleVectorSDNode::commuteMask(MaskVec);
1651 SDValue Op0 = SV.getOperand(0);
1652 SDValue Op1 = SV.getOperand(1);
1653 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1656 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1657 FoldingSetNodeID ID;
1658 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1659 ID.AddInteger(RegNo);
1661 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1662 return SDValue(E, 0);
1664 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1665 CSEMap.InsertNode(N, IP);
1667 return SDValue(N, 0);
1670 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1671 FoldingSetNodeID ID;
1672 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1673 ID.AddPointer(RegMask);
1675 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1676 return SDValue(E, 0);
1678 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1679 CSEMap.InsertNode(N, IP);
1681 return SDValue(N, 0);
1684 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1686 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1689 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1690 SDValue Root, MCSymbol *Label) {
1691 FoldingSetNodeID ID;
1692 SDValue Ops[] = { Root };
1693 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1694 ID.AddPointer(Label);
1696 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1697 return SDValue(E, 0);
1699 auto *N = newSDNode<LabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1700 createOperands(N, Ops);
1702 CSEMap.InsertNode(N, IP);
1704 return SDValue(N, 0);
1707 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1710 unsigned char TargetFlags) {
1711 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1713 FoldingSetNodeID ID;
1714 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1716 ID.AddInteger(Offset);
1717 ID.AddInteger(TargetFlags);
1719 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1720 return SDValue(E, 0);
1722 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1723 CSEMap.InsertNode(N, IP);
1725 return SDValue(N, 0);
1728 SDValue SelectionDAG::getSrcValue(const Value *V) {
1729 assert((!V || V->getType()->isPointerTy()) &&
1730 "SrcValue is not a pointer?");
1732 FoldingSetNodeID ID;
1733 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1737 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1738 return SDValue(E, 0);
1740 auto *N = newSDNode<SrcValueSDNode>(V);
1741 CSEMap.InsertNode(N, IP);
1743 return SDValue(N, 0);
1746 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1747 FoldingSetNodeID ID;
1748 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1752 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1753 return SDValue(E, 0);
1755 auto *N = newSDNode<MDNodeSDNode>(MD);
1756 CSEMap.InsertNode(N, IP);
1758 return SDValue(N, 0);
1761 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1762 if (VT == V.getValueType())
1765 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1768 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1769 unsigned SrcAS, unsigned DestAS) {
1770 SDValue Ops[] = {Ptr};
1771 FoldingSetNodeID ID;
1772 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1773 ID.AddInteger(SrcAS);
1774 ID.AddInteger(DestAS);
1777 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1778 return SDValue(E, 0);
1780 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1782 createOperands(N, Ops);
1784 CSEMap.InsertNode(N, IP);
1786 return SDValue(N, 0);
1789 /// getShiftAmountOperand - Return the specified value casted to
1790 /// the target's desired shift amount type.
1791 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1792 EVT OpTy = Op.getValueType();
1793 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1794 if (OpTy == ShTy || OpTy.isVector()) return Op;
1796 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1799 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1801 const TargetLowering &TLI = getTargetLoweringInfo();
1802 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1803 EVT VT = Node->getValueType(0);
1804 SDValue Tmp1 = Node->getOperand(0);
1805 SDValue Tmp2 = Node->getOperand(1);
1806 unsigned Align = Node->getConstantOperandVal(3);
1808 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1809 Tmp2, MachinePointerInfo(V));
1810 SDValue VAList = VAListLoad;
1812 if (Align > TLI.getMinStackArgumentAlignment()) {
1813 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1815 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1816 getConstant(Align - 1, dl, VAList.getValueType()));
1818 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1819 getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1822 // Increment the pointer, VAList, to the next vaarg
1823 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1824 getConstant(getDataLayout().getTypeAllocSize(
1825 VT.getTypeForEVT(*getContext())),
1826 dl, VAList.getValueType()));
1827 // Store the incremented VAList to the legalized pointer
1829 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1830 // Load the actual argument out of the pointer VAList
1831 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1834 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1836 const TargetLowering &TLI = getTargetLoweringInfo();
1837 // This defaults to loading a pointer from the input and storing it to the
1838 // output, returning the chain.
1839 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1840 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1842 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1843 Node->getOperand(2), MachinePointerInfo(VS));
1844 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1845 MachinePointerInfo(VD));
1848 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1849 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1850 unsigned ByteSize = VT.getStoreSize();
1851 Type *Ty = VT.getTypeForEVT(*getContext());
1852 unsigned StackAlign =
1853 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1855 int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1856 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1859 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1860 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1861 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1862 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1863 const DataLayout &DL = getDataLayout();
1865 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1867 MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1868 int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1869 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1872 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1873 ISD::CondCode Cond, const SDLoc &dl) {
1874 // These setcc operations always fold.
1878 case ISD::SETFALSE2: return getConstant(0, dl, VT);
1880 case ISD::SETTRUE2: {
1881 TargetLowering::BooleanContent Cnt =
1882 TLI->getBooleanContents(N1->getValueType(0));
1884 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1898 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1902 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1903 const APInt &C2 = N2C->getAPIntValue();
1904 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1905 const APInt &C1 = N1C->getAPIntValue();
1908 default: llvm_unreachable("Unknown integer setcc!");
1909 case ISD::SETEQ: return getConstant(C1 == C2, dl, VT);
1910 case ISD::SETNE: return getConstant(C1 != C2, dl, VT);
1911 case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT);
1912 case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT);
1913 case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT);
1914 case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT);
1915 case ISD::SETLT: return getConstant(C1.slt(C2), dl, VT);
1916 case ISD::SETGT: return getConstant(C1.sgt(C2), dl, VT);
1917 case ISD::SETLE: return getConstant(C1.sle(C2), dl, VT);
1918 case ISD::SETGE: return getConstant(C1.sge(C2), dl, VT);
1922 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1923 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1924 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1927 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1928 return getUNDEF(VT);
1930 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT);
1931 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1932 return getUNDEF(VT);
1934 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1935 R==APFloat::cmpLessThan, dl, VT);
1936 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1937 return getUNDEF(VT);
1939 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT);
1940 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1941 return getUNDEF(VT);
1943 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT);
1944 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1945 return getUNDEF(VT);
1947 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1948 R==APFloat::cmpEqual, dl, VT);
1949 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1950 return getUNDEF(VT);
1952 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1953 R==APFloat::cmpEqual, dl, VT);
1954 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, dl, VT);
1955 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, dl, VT);
1956 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1957 R==APFloat::cmpEqual, dl, VT);
1958 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT);
1959 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1960 R==APFloat::cmpLessThan, dl, VT);
1961 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1962 R==APFloat::cmpUnordered, dl, VT);
1963 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT);
1964 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT);
1967 // Ensure that the constant occurs on the RHS.
1968 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1969 MVT CompVT = N1.getValueType().getSimpleVT();
1970 if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
1973 return getSetCC(dl, VT, N2, N1, SwappedCond);
1977 // Could not fold it.
1981 /// See if the specified operand can be simplified with the knowledge that only
1982 /// the bits specified by Mask are used.
1983 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &Mask) {
1984 switch (V.getOpcode()) {
1987 case ISD::Constant: {
1988 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
1989 assert(CV && "Const value should be ConstSDNode.");
1990 const APInt &CVal = CV->getAPIntValue();
1991 APInt NewVal = CVal & Mask;
1993 return getConstant(NewVal, SDLoc(V), V.getValueType());
1998 // If the LHS or RHS don't contribute bits to the or, drop them.
1999 if (MaskedValueIsZero(V.getOperand(0), Mask))
2000 return V.getOperand(1);
2001 if (MaskedValueIsZero(V.getOperand(1), Mask))
2002 return V.getOperand(0);
2005 // Only look at single-use SRLs.
2006 if (!V.getNode()->hasOneUse())
2008 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2009 // See if we can recursively simplify the LHS.
2010 unsigned Amt = RHSC->getZExtValue();
2012 // Watch out for shift count overflow though.
2013 if (Amt >= Mask.getBitWidth())
2015 APInt NewMask = Mask << Amt;
2016 if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
2017 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2022 // X & -1 -> X (ignoring bits which aren't demanded).
2023 ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
2024 if (AndVal && Mask.isSubsetOf(AndVal->getAPIntValue()))
2025 return V.getOperand(0);
2028 case ISD::ANY_EXTEND: {
2029 SDValue Src = V.getOperand(0);
2030 unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
2031 // Being conservative here - only peek through if we only demand bits in the
2032 // non-extended source (even though the extended bits are technically undef).
2033 if (Mask.getActiveBits() > SrcBitWidth)
2035 APInt SrcMask = Mask.trunc(SrcBitWidth);
2036 if (SDValue DemandedSrc = GetDemandedBits(Src, SrcMask))
2037 return getNode(ISD::ANY_EXTEND, SDLoc(V), V.getValueType(), DemandedSrc);
2044 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2045 /// use this predicate to simplify operations downstream.
2046 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2047 unsigned BitWidth = Op.getScalarValueSizeInBits();
2048 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2051 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2052 /// this predicate to simplify operations downstream. Mask is known to be zero
2053 /// for bits that V cannot have.
2054 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
2055 unsigned Depth) const {
2057 computeKnownBits(Op, Known, Depth);
2058 return Mask.isSubsetOf(Known.Zero);
2061 /// Helper function that checks to see if a node is a constant or a
2062 /// build vector of splat constants at least within the demanded elts.
2063 static ConstantSDNode *isConstOrDemandedConstSplat(SDValue N,
2064 const APInt &DemandedElts) {
2065 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
2067 if (N.getOpcode() != ISD::BUILD_VECTOR)
2069 EVT VT = N.getValueType();
2070 ConstantSDNode *Cst = nullptr;
2071 unsigned NumElts = VT.getVectorNumElements();
2072 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected vector size");
2073 for (unsigned i = 0; i != NumElts; ++i) {
2074 if (!DemandedElts[i])
2076 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(i));
2077 if (!C || (Cst && Cst->getAPIntValue() != C->getAPIntValue()) ||
2078 C->getValueType(0) != VT.getScalarType())
2085 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
2086 /// is less than the element bit-width of the shift node, return it.
2087 static const APInt *getValidShiftAmountConstant(SDValue V) {
2088 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
2089 // Shifting more than the bitwidth is not valid.
2090 const APInt &ShAmt = SA->getAPIntValue();
2091 if (ShAmt.ult(V.getScalarValueSizeInBits()))
2097 /// Determine which bits of Op are known to be either zero or one and return
2098 /// them in Known. For vectors, the known bits are those that are shared by
2099 /// every vector element.
2100 void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known,
2101 unsigned Depth) const {
2102 EVT VT = Op.getValueType();
2103 APInt DemandedElts = VT.isVector()
2104 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2106 computeKnownBits(Op, Known, DemandedElts, Depth);
2109 /// Determine which bits of Op are known to be either zero or one and return
2110 /// them in Known. The DemandedElts argument allows us to only collect the known
2111 /// bits that are shared by the requested vector elements.
2112 void SelectionDAG::computeKnownBits(SDValue Op, KnownBits &Known,
2113 const APInt &DemandedElts,
2114 unsigned Depth) const {
2115 unsigned BitWidth = Op.getScalarValueSizeInBits();
2117 Known = KnownBits(BitWidth); // Don't know anything.
2119 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2120 // We know all of the bits for a constant!
2121 Known.One = C->getAPIntValue();
2122 Known.Zero = ~Known.One;
2125 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2126 // We know all of the bits for a constant fp!
2127 Known.One = C->getValueAPF().bitcastToAPInt();
2128 Known.Zero = ~Known.One;
2133 return; // Limit search depth.
2136 unsigned NumElts = DemandedElts.getBitWidth();
2139 return; // No demanded elts, better to assume we don't know anything.
2141 unsigned Opcode = Op.getOpcode();
2143 case ISD::BUILD_VECTOR:
2144 // Collect the known bits that are shared by every demanded vector element.
2145 assert(NumElts == Op.getValueType().getVectorNumElements() &&
2146 "Unexpected vector size");
2147 Known.Zero.setAllBits(); Known.One.setAllBits();
2148 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2149 if (!DemandedElts[i])
2152 SDValue SrcOp = Op.getOperand(i);
2153 computeKnownBits(SrcOp, Known2, Depth + 1);
2155 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2156 if (SrcOp.getValueSizeInBits() != BitWidth) {
2157 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2158 "Expected BUILD_VECTOR implicit truncation");
2159 Known2 = Known2.trunc(BitWidth);
2162 // Known bits are the values that are shared by every demanded element.
2163 Known.One &= Known2.One;
2164 Known.Zero &= Known2.Zero;
2166 // If we don't know any bits, early out.
2167 if (Known.isUnknown())
2171 case ISD::VECTOR_SHUFFLE: {
2172 // Collect the known bits that are shared by every vector element referenced
2174 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2175 Known.Zero.setAllBits(); Known.One.setAllBits();
2176 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2177 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2178 for (unsigned i = 0; i != NumElts; ++i) {
2179 if (!DemandedElts[i])
2182 int M = SVN->getMaskElt(i);
2184 // For UNDEF elements, we don't know anything about the common state of
2185 // the shuffle result.
2187 DemandedLHS.clearAllBits();
2188 DemandedRHS.clearAllBits();
2192 if ((unsigned)M < NumElts)
2193 DemandedLHS.setBit((unsigned)M % NumElts);
2195 DemandedRHS.setBit((unsigned)M % NumElts);
2197 // Known bits are the values that are shared by every demanded element.
2198 if (!!DemandedLHS) {
2199 SDValue LHS = Op.getOperand(0);
2200 computeKnownBits(LHS, Known2, DemandedLHS, Depth + 1);
2201 Known.One &= Known2.One;
2202 Known.Zero &= Known2.Zero;
2204 // If we don't know any bits, early out.
2205 if (Known.isUnknown())
2207 if (!!DemandedRHS) {
2208 SDValue RHS = Op.getOperand(1);
2209 computeKnownBits(RHS, Known2, DemandedRHS, Depth + 1);
2210 Known.One &= Known2.One;
2211 Known.Zero &= Known2.Zero;
2215 case ISD::CONCAT_VECTORS: {
2216 // Split DemandedElts and test each of the demanded subvectors.
2217 Known.Zero.setAllBits(); Known.One.setAllBits();
2218 EVT SubVectorVT = Op.getOperand(0).getValueType();
2219 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2220 unsigned NumSubVectors = Op.getNumOperands();
2221 for (unsigned i = 0; i != NumSubVectors; ++i) {
2222 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2223 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2224 if (!!DemandedSub) {
2225 SDValue Sub = Op.getOperand(i);
2226 computeKnownBits(Sub, Known2, DemandedSub, Depth + 1);
2227 Known.One &= Known2.One;
2228 Known.Zero &= Known2.Zero;
2230 // If we don't know any bits, early out.
2231 if (Known.isUnknown())
2236 case ISD::INSERT_SUBVECTOR: {
2237 // If we know the element index, demand any elements from the subvector and
2238 // the remainder from the src its inserted into, otherwise demand them all.
2239 SDValue Src = Op.getOperand(0);
2240 SDValue Sub = Op.getOperand(1);
2241 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2242 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2243 if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
2244 Known.One.setAllBits();
2245 Known.Zero.setAllBits();
2246 uint64_t Idx = SubIdx->getZExtValue();
2247 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2248 if (!!DemandedSubElts) {
2249 computeKnownBits(Sub, Known, DemandedSubElts, Depth + 1);
2250 if (Known.isUnknown())
2251 break; // early-out.
2253 APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
2254 APInt DemandedSrcElts = DemandedElts & ~SubMask;
2255 if (!!DemandedSrcElts) {
2256 computeKnownBits(Src, Known2, DemandedSrcElts, Depth + 1);
2257 Known.One &= Known2.One;
2258 Known.Zero &= Known2.Zero;
2261 computeKnownBits(Sub, Known, Depth + 1);
2262 if (Known.isUnknown())
2263 break; // early-out.
2264 computeKnownBits(Src, Known2, Depth + 1);
2265 Known.One &= Known2.One;
2266 Known.Zero &= Known2.Zero;
2270 case ISD::EXTRACT_SUBVECTOR: {
2271 // If we know the element index, just demand that subvector elements,
2272 // otherwise demand them all.
2273 SDValue Src = Op.getOperand(0);
2274 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2275 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2276 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2277 // Offset the demanded elts by the subvector index.
2278 uint64_t Idx = SubIdx->getZExtValue();
2279 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
2280 computeKnownBits(Src, Known, DemandedSrc, Depth + 1);
2282 computeKnownBits(Src, Known, Depth + 1);
2286 case ISD::BITCAST: {
2287 SDValue N0 = Op.getOperand(0);
2288 EVT SubVT = N0.getValueType();
2289 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2291 // Ignore bitcasts from unsupported types.
2292 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2295 // Fast handling of 'identity' bitcasts.
2296 if (BitWidth == SubBitWidth) {
2297 computeKnownBits(N0, Known, DemandedElts, Depth + 1);
2301 // Support big-endian targets when it becomes useful.
2302 bool IsLE = getDataLayout().isLittleEndian();
2306 // Bitcast 'small element' vector to 'large element' scalar/vector.
2307 if ((BitWidth % SubBitWidth) == 0) {
2308 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2310 // Collect known bits for the (larger) output by collecting the known
2311 // bits from each set of sub elements and shift these into place.
2312 // We need to separately call computeKnownBits for each set of
2313 // sub elements as the knownbits for each is likely to be different.
2314 unsigned SubScale = BitWidth / SubBitWidth;
2315 APInt SubDemandedElts(NumElts * SubScale, 0);
2316 for (unsigned i = 0; i != NumElts; ++i)
2317 if (DemandedElts[i])
2318 SubDemandedElts.setBit(i * SubScale);
2320 for (unsigned i = 0; i != SubScale; ++i) {
2321 computeKnownBits(N0, Known2, SubDemandedElts.shl(i),
2323 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * i);
2324 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * i);
2328 // Bitcast 'large element' scalar/vector to 'small element' vector.
2329 if ((SubBitWidth % BitWidth) == 0) {
2330 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2332 // Collect known bits for the (smaller) output by collecting the known
2333 // bits from the overlapping larger input elements and extracting the
2334 // sub sections we actually care about.
2335 unsigned SubScale = SubBitWidth / BitWidth;
2336 APInt SubDemandedElts(NumElts / SubScale, 0);
2337 for (unsigned i = 0; i != NumElts; ++i)
2338 if (DemandedElts[i])
2339 SubDemandedElts.setBit(i / SubScale);
2341 computeKnownBits(N0, Known2, SubDemandedElts, Depth + 1);
2343 Known.Zero.setAllBits(); Known.One.setAllBits();
2344 for (unsigned i = 0; i != NumElts; ++i)
2345 if (DemandedElts[i]) {
2346 unsigned Offset = (i % SubScale) * BitWidth;
2347 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2348 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2349 // If we don't know any bits, early out.
2350 if (Known.isUnknown())
2357 // If either the LHS or the RHS are Zero, the result is zero.
2358 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2359 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2361 // Output known-1 bits are only known if set in both the LHS & RHS.
2362 Known.One &= Known2.One;
2363 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2364 Known.Zero |= Known2.Zero;
2367 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2368 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2370 // Output known-0 bits are only known if clear in both the LHS & RHS.
2371 Known.Zero &= Known2.Zero;
2372 // Output known-1 are known to be set if set in either the LHS | RHS.
2373 Known.One |= Known2.One;
2376 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2377 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2379 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2380 APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2381 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2382 Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2383 Known.Zero = KnownZeroOut;
2387 computeKnownBits(Op.getOperand(1), Known, DemandedElts, Depth + 1);
2388 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2390 // If low bits are zero in either operand, output low known-0 bits.
2391 // Also compute a conservative estimate for high known-0 bits.
2392 // More trickiness is possible, but this is sufficient for the
2393 // interesting case of alignment computation.
2394 unsigned TrailZ = Known.countMinTrailingZeros() +
2395 Known2.countMinTrailingZeros();
2396 unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
2397 Known2.countMinLeadingZeros(),
2398 BitWidth) - BitWidth;
2401 Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2402 Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2406 // For the purposes of computing leading zeros we can conservatively
2407 // treat a udiv as a logical right shift by the power of 2 known to
2408 // be less than the denominator.
2409 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2410 unsigned LeadZ = Known2.countMinLeadingZeros();
2412 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2413 unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2414 if (RHSMaxLeadingZeros != BitWidth)
2415 LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2417 Known.Zero.setHighBits(LeadZ);
2422 computeKnownBits(Op.getOperand(2), Known, DemandedElts, Depth+1);
2423 // If we don't know any bits, early out.
2424 if (Known.isUnknown())
2426 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth+1);
2428 // Only known if known in both the LHS and RHS.
2429 Known.One &= Known2.One;
2430 Known.Zero &= Known2.Zero;
2432 case ISD::SELECT_CC:
2433 computeKnownBits(Op.getOperand(3), Known, DemandedElts, Depth+1);
2434 // If we don't know any bits, early out.
2435 if (Known.isUnknown())
2437 computeKnownBits(Op.getOperand(2), Known2, DemandedElts, Depth+1);
2439 // Only known if known in both the LHS and RHS.
2440 Known.One &= Known2.One;
2441 Known.Zero &= Known2.Zero;
2445 if (Op.getResNo() != 1)
2447 // The boolean result conforms to getBooleanContents.
2448 // If we know the result of a setcc has the top bits zero, use this info.
2449 // We know that we have an integer-based boolean since these operations
2450 // are only available for integer.
2451 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2452 TargetLowering::ZeroOrOneBooleanContent &&
2454 Known.Zero.setBitsFrom(1);
2457 // If we know the result of a setcc has the top bits zero, use this info.
2458 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2459 TargetLowering::ZeroOrOneBooleanContent &&
2461 Known.Zero.setBitsFrom(1);
2464 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2465 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2466 Known.Zero <<= *ShAmt;
2467 Known.One <<= *ShAmt;
2468 // Low bits are known zero.
2469 Known.Zero.setLowBits(ShAmt->getZExtValue());
2473 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2474 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2475 Known.Zero.lshrInPlace(*ShAmt);
2476 Known.One.lshrInPlace(*ShAmt);
2477 // High bits are known zero.
2478 Known.Zero.setHighBits(ShAmt->getZExtValue());
2482 if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2483 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2484 // Sign extend known zero/one bit (else is unknown).
2485 Known.Zero.ashrInPlace(*ShAmt);
2486 Known.One.ashrInPlace(*ShAmt);
2489 case ISD::SIGN_EXTEND_INREG: {
2490 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2491 unsigned EBits = EVT.getScalarSizeInBits();
2493 // Sign extension. Compute the demanded bits in the result that are not
2494 // present in the input.
2495 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2497 APInt InSignMask = APInt::getSignMask(EBits);
2498 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2500 // If the sign extended bits are demanded, we know that the sign
2502 InSignMask = InSignMask.zext(BitWidth);
2503 if (NewBits.getBoolValue())
2504 InputDemandedBits |= InSignMask;
2506 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2507 Known.One &= InputDemandedBits;
2508 Known.Zero &= InputDemandedBits;
2510 // If the sign bit of the input is known set or clear, then we know the
2511 // top bits of the result.
2512 if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
2513 Known.Zero |= NewBits;
2514 Known.One &= ~NewBits;
2515 } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
2516 Known.One |= NewBits;
2517 Known.Zero &= ~NewBits;
2518 } else { // Input sign bit unknown
2519 Known.Zero &= ~NewBits;
2520 Known.One &= ~NewBits;
2525 case ISD::CTTZ_ZERO_UNDEF: {
2526 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2527 // If we have a known 1, its position is our upper bound.
2528 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2529 unsigned LowBits = Log2_32(PossibleTZ) + 1;
2530 Known.Zero.setBitsFrom(LowBits);
2534 case ISD::CTLZ_ZERO_UNDEF: {
2535 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2536 // If we have a known 1, its position is our upper bound.
2537 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2538 unsigned LowBits = Log2_32(PossibleLZ) + 1;
2539 Known.Zero.setBitsFrom(LowBits);
2543 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2544 // If we know some of the bits are zero, they can't be one.
2545 unsigned PossibleOnes = Known2.countMaxPopulation();
2546 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2550 LoadSDNode *LD = cast<LoadSDNode>(Op);
2551 // If this is a ZEXTLoad and we are looking at the loaded value.
2552 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2553 EVT VT = LD->getMemoryVT();
2554 unsigned MemBits = VT.getScalarSizeInBits();
2555 Known.Zero.setBitsFrom(MemBits);
2556 } else if (const MDNode *Ranges = LD->getRanges()) {
2557 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2558 computeKnownBitsFromRangeMetadata(*Ranges, Known);
2562 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2563 EVT InVT = Op.getOperand(0).getValueType();
2564 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
2565 computeKnownBits(Op.getOperand(0), Known, InDemandedElts, Depth + 1);
2566 Known = Known.zext(BitWidth);
2567 Known.Zero.setBitsFrom(InVT.getScalarSizeInBits());
2570 case ISD::ZERO_EXTEND: {
2571 EVT InVT = Op.getOperand(0).getValueType();
2572 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2573 Known = Known.zext(BitWidth);
2574 Known.Zero.setBitsFrom(InVT.getScalarSizeInBits());
2577 // TODO ISD::SIGN_EXTEND_VECTOR_INREG
2578 case ISD::SIGN_EXTEND: {
2579 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2580 // If the sign bit is known to be zero or one, then sext will extend
2581 // it to the top bits, else it will just zext.
2582 Known = Known.sext(BitWidth);
2585 case ISD::ANY_EXTEND: {
2586 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2587 Known = Known.zext(BitWidth);
2590 case ISD::TRUNCATE: {
2591 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2592 Known = Known.trunc(BitWidth);
2595 case ISD::AssertZext: {
2596 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2597 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2598 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2599 Known.Zero |= (~InMask);
2600 Known.One &= (~Known.Zero);
2604 // All bits are zero except the low bit.
2605 Known.Zero.setBitsFrom(1);
2609 if (Op.getResNo() == 1) {
2610 // If we know the result of a setcc has the top bits zero, use this info.
2611 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2612 TargetLowering::ZeroOrOneBooleanContent &&
2614 Known.Zero.setBitsFrom(1);
2620 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
2621 // We know that the top bits of C-X are clear if X contains less bits
2622 // than C (i.e. no wrap-around can happen). For example, 20-X is
2623 // positive if we can prove that X is >= 0 and < 16.
2624 if (CLHS->getAPIntValue().isNonNegative()) {
2625 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2626 // NLZ can't be BitWidth with no sign bit
2627 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2628 computeKnownBits(Op.getOperand(1), Known2, DemandedElts,
2631 // If all of the MaskV bits are known to be zero, then we know the
2632 // output top bits are zero, because we now know that the output is
2634 if ((Known2.Zero & MaskV) == MaskV) {
2635 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2636 // Top bits known zero.
2637 Known.Zero.setHighBits(NLZ2);
2642 // If low bits are know to be zero in both operands, then we know they are
2643 // going to be 0 in the result. Both addition and complement operations
2644 // preserve the low zero bits.
2645 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2646 unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2647 if (KnownZeroLow == 0)
2650 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2651 KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2652 Known.Zero.setLowBits(KnownZeroLow);
2658 if (Op.getResNo() == 1) {
2659 // If we know the result of a setcc has the top bits zero, use this info.
2660 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2661 TargetLowering::ZeroOrOneBooleanContent &&
2663 Known.Zero.setBitsFrom(1);
2670 // Output known-0 bits are known if clear or set in both the low clear bits
2671 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2672 // low 3 bits clear.
2673 // Output known-0 bits are also known if the top bits of each input are
2674 // known to be clear. For example, if one input has the top 10 bits clear
2675 // and the other has the top 8 bits clear, we know the top 7 bits of the
2676 // output must be clear.
2677 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2678 unsigned KnownZeroHigh = Known2.countMinLeadingZeros();
2679 unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2681 computeKnownBits(Op.getOperand(1), Known2, DemandedElts,
2683 KnownZeroHigh = std::min(KnownZeroHigh, Known2.countMinLeadingZeros());
2684 KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2686 if (Opcode == ISD::ADDE || Opcode == ISD::ADDCARRY) {
2687 // With ADDE and ADDCARRY, a carry bit may be added in, so we can only
2688 // use this information if we know (at least) that the low two bits are
2689 // clear. We then return to the caller that the low bit is unknown but
2690 // that other bits are known zero.
2691 if (KnownZeroLow >= 2)
2692 Known.Zero.setBits(1, KnownZeroLow);
2696 Known.Zero.setLowBits(KnownZeroLow);
2697 if (KnownZeroHigh > 1)
2698 Known.Zero.setHighBits(KnownZeroHigh - 1);
2702 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2703 const APInt &RA = Rem->getAPIntValue().abs();
2704 if (RA.isPowerOf2()) {
2705 APInt LowBits = RA - 1;
2706 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2708 // The low bits of the first operand are unchanged by the srem.
2709 Known.Zero = Known2.Zero & LowBits;
2710 Known.One = Known2.One & LowBits;
2712 // If the first operand is non-negative or has all low bits zero, then
2713 // the upper bits are all zero.
2714 if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
2715 Known.Zero |= ~LowBits;
2717 // If the first operand is negative and not all low bits are zero, then
2718 // the upper bits are all one.
2719 if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
2720 Known.One |= ~LowBits;
2721 assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
2726 if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2727 const APInt &RA = Rem->getAPIntValue();
2728 if (RA.isPowerOf2()) {
2729 APInt LowBits = (RA - 1);
2730 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2732 // The upper bits are all zero, the lower ones are unchanged.
2733 Known.Zero = Known2.Zero | ~LowBits;
2734 Known.One = Known2.One & LowBits;
2739 // Since the result is less than or equal to either operand, any leading
2740 // zero bits in either operand must also exist in the result.
2741 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2742 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2745 std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
2747 Known.Zero.setHighBits(Leaders);
2750 case ISD::EXTRACT_ELEMENT: {
2751 computeKnownBits(Op.getOperand(0), Known, Depth+1);
2752 const unsigned Index = Op.getConstantOperandVal(1);
2753 const unsigned BitWidth = Op.getValueSizeInBits();
2755 // Remove low part of known bits mask
2756 Known.Zero = Known.Zero.getHiBits(Known.Zero.getBitWidth() - Index * BitWidth);
2757 Known.One = Known.One.getHiBits(Known.One.getBitWidth() - Index * BitWidth);
2759 // Remove high part of known bit mask
2760 Known = Known.trunc(BitWidth);
2763 case ISD::EXTRACT_VECTOR_ELT: {
2764 SDValue InVec = Op.getOperand(0);
2765 SDValue EltNo = Op.getOperand(1);
2766 EVT VecVT = InVec.getValueType();
2767 const unsigned BitWidth = Op.getValueSizeInBits();
2768 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
2769 const unsigned NumSrcElts = VecVT.getVectorNumElements();
2770 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2771 // anything about the extended bits.
2772 if (BitWidth > EltBitWidth)
2773 Known = Known.trunc(EltBitWidth);
2774 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
2775 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
2776 // If we know the element index, just demand that vector element.
2777 unsigned Idx = ConstEltNo->getZExtValue();
2778 APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
2779 computeKnownBits(InVec, Known, DemandedElt, Depth + 1);
2781 // Unknown element index, so ignore DemandedElts and demand them all.
2782 computeKnownBits(InVec, Known, Depth + 1);
2784 if (BitWidth > EltBitWidth)
2785 Known = Known.zext(BitWidth);
2788 case ISD::INSERT_VECTOR_ELT: {
2789 SDValue InVec = Op.getOperand(0);
2790 SDValue InVal = Op.getOperand(1);
2791 SDValue EltNo = Op.getOperand(2);
2793 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
2794 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
2795 // If we know the element index, split the demand between the
2796 // source vector and the inserted element.
2797 Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
2798 unsigned EltIdx = CEltNo->getZExtValue();
2800 // If we demand the inserted element then add its common known bits.
2801 if (DemandedElts[EltIdx]) {
2802 computeKnownBits(InVal, Known2, Depth + 1);
2803 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
2804 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
2807 // If we demand the source vector then add its common known bits, ensuring
2808 // that we don't demand the inserted element.
2809 APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
2811 computeKnownBits(InVec, Known2, VectorElts, Depth + 1);
2812 Known.One &= Known2.One;
2813 Known.Zero &= Known2.Zero;
2816 // Unknown element index, so ignore DemandedElts and demand them all.
2817 computeKnownBits(InVec, Known, Depth + 1);
2818 computeKnownBits(InVal, Known2, Depth + 1);
2819 Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
2820 Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
2824 case ISD::BITREVERSE: {
2825 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2826 Known.Zero = Known2.Zero.reverseBits();
2827 Known.One = Known2.One.reverseBits();
2831 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2832 Known.Zero = Known2.Zero.byteSwap();
2833 Known.One = Known2.One.byteSwap();
2837 computeKnownBits(Op.getOperand(0), Known2, DemandedElts, Depth + 1);
2839 // If the source's MSB is zero then we know the rest of the bits already.
2840 if (Known2.isNonNegative()) {
2841 Known.Zero = Known2.Zero;
2842 Known.One = Known2.One;
2846 // We only know that the absolute values's MSB will be zero iff there is
2847 // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
2848 Known2.One.clearSignBit();
2849 if (Known2.One.getBoolValue()) {
2850 Known.Zero = APInt::getSignMask(BitWidth);
2856 computeKnownBits(Op.getOperand(0), Known, DemandedElts, Depth + 1);
2857 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2859 // UMIN - we know that the result will have the maximum of the
2860 // known zero leading bits of the inputs.
2861 unsigned LeadZero = Known.countMinLeadingZeros();
2862 LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
2864 Known.Zero &= Known2.Zero;
2865 Known.One &= Known2.One;
2866 Known.Zero.setHighBits(LeadZero);
2870 computeKnownBits(Op.getOperand(0), Known, DemandedElts,
2872 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2874 // UMAX - we know that the result will have the maximum of the
2875 // known one leading bits of the inputs.
2876 unsigned LeadOne = Known.countMinLeadingOnes();
2877 LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
2879 Known.Zero &= Known2.Zero;
2880 Known.One &= Known2.One;
2881 Known.One.setHighBits(LeadOne);
2886 computeKnownBits(Op.getOperand(0), Known, DemandedElts,
2888 // If we don't know any bits, early out.
2889 if (Known.isUnknown())
2891 computeKnownBits(Op.getOperand(1), Known2, DemandedElts, Depth + 1);
2892 Known.Zero &= Known2.Zero;
2893 Known.One &= Known2.One;
2896 case ISD::FrameIndex:
2897 case ISD::TargetFrameIndex:
2898 TLI->computeKnownBitsForFrameIndex(Op, Known, DemandedElts, *this, Depth);
2902 if (Opcode < ISD::BUILTIN_OP_END)
2905 case ISD::INTRINSIC_WO_CHAIN:
2906 case ISD::INTRINSIC_W_CHAIN:
2907 case ISD::INTRINSIC_VOID:
2908 // Allow the target to implement this method for its nodes.
2909 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
2913 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2916 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
2918 // X + 0 never overflow
2919 if (isNullConstant(N1))
2923 computeKnownBits(N1, N1Known);
2924 if (N1Known.Zero.getBoolValue()) {
2926 computeKnownBits(N0, N0Known);
2929 (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
2934 // mulhi + 1 never overflow
2935 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
2936 (~N1Known.Zero & 0x01) == ~N1Known.Zero)
2939 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
2941 computeKnownBits(N0, N0Known);
2943 if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
2947 return OFK_Sometime;
2950 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
2951 EVT OpVT = Val.getValueType();
2952 unsigned BitWidth = OpVT.getScalarSizeInBits();
2954 // Is the constant a known power of 2?
2955 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
2956 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2958 // A left-shift of a constant one will have exactly one bit set because
2959 // shifting the bit off the end is undefined.
2960 if (Val.getOpcode() == ISD::SHL) {
2961 auto *C = isConstOrConstSplat(Val.getOperand(0));
2962 if (C && C->getAPIntValue() == 1)
2966 // Similarly, a logical right-shift of a constant sign-bit will have exactly
2968 if (Val.getOpcode() == ISD::SRL) {
2969 auto *C = isConstOrConstSplat(Val.getOperand(0));
2970 if (C && C->getAPIntValue().isSignMask())
2974 // Are all operands of a build vector constant powers of two?
2975 if (Val.getOpcode() == ISD::BUILD_VECTOR)
2976 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
2977 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
2978 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
2983 // More could be done here, though the above checks are enough
2984 // to handle some common cases.
2986 // Fall back to computeKnownBits to catch other known cases.
2988 computeKnownBits(Val, Known);
2989 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
2992 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
2993 EVT VT = Op.getValueType();
2994 APInt DemandedElts = VT.isVector()
2995 ? APInt::getAllOnesValue(VT.getVectorNumElements())
2997 return ComputeNumSignBits(Op, DemandedElts, Depth);
3000 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3001 unsigned Depth) const {
3002 EVT VT = Op.getValueType();
3003 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3004 unsigned VTBits = VT.getScalarSizeInBits();
3005 unsigned NumElts = DemandedElts.getBitWidth();
3007 unsigned FirstAnswer = 1;
3009 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3010 const APInt &Val = C->getAPIntValue();
3011 return Val.getNumSignBits();
3015 return 1; // Limit search depth.
3018 return 1; // No demanded elts, better to assume we don't know anything.
3020 switch (Op.getOpcode()) {
3022 case ISD::AssertSext:
3023 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3024 return VTBits-Tmp+1;
3025 case ISD::AssertZext:
3026 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3029 case ISD::BUILD_VECTOR:
3031 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3032 if (!DemandedElts[i])
3035 SDValue SrcOp = Op.getOperand(i);
3036 Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
3038 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3039 if (SrcOp.getValueSizeInBits() != VTBits) {
3040 assert(SrcOp.getValueSizeInBits() > VTBits &&
3041 "Expected BUILD_VECTOR implicit truncation");
3042 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3043 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3045 Tmp = std::min(Tmp, Tmp2);
3049 case ISD::VECTOR_SHUFFLE: {
3050 // Collect the minimum number of sign bits that are shared by every vector
3051 // element referenced by the shuffle.
3052 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3053 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3054 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3055 for (unsigned i = 0; i != NumElts; ++i) {
3056 int M = SVN->getMaskElt(i);
3057 if (!DemandedElts[i])
3059 // For UNDEF elements, we don't know anything about the common state of
3060 // the shuffle result.
3063 if ((unsigned)M < NumElts)
3064 DemandedLHS.setBit((unsigned)M % NumElts);
3066 DemandedRHS.setBit((unsigned)M % NumElts);
3068 Tmp = std::numeric_limits<unsigned>::max();
3070 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3071 if (!!DemandedRHS) {
3072 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3073 Tmp = std::min(Tmp, Tmp2);
3075 // If we don't know anything, early out and try computeKnownBits fall-back.
3078 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3082 case ISD::BITCAST: {
3083 SDValue N0 = Op.getOperand(0);
3084 EVT SrcVT = N0.getValueType();
3085 unsigned SrcBits = SrcVT.getScalarSizeInBits();
3087 // Ignore bitcasts from unsupported types..
3088 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3091 // Fast handling of 'identity' bitcasts.
3092 if (VTBits == SrcBits)
3093 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3095 // Bitcast 'large element' scalar/vector to 'small element' vector.
3096 // TODO: Handle cases other than 'sign splat' when we have a use case.
3097 // Requires handling of DemandedElts and Endianness.
3098 if ((SrcBits % VTBits) == 0) {
3099 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3100 Tmp = ComputeNumSignBits(N0, Depth + 1);
3107 case ISD::SIGN_EXTEND:
3108 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3109 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3110 case ISD::SIGN_EXTEND_INREG:
3111 // Max of the input and what this extends.
3112 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3114 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3115 return std::max(Tmp, Tmp2);
3116 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3117 SDValue Src = Op.getOperand(0);
3118 EVT SrcVT = Src.getValueType();
3119 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
3120 Tmp = VTBits - SrcVT.getScalarSizeInBits();
3121 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3125 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3126 // SRA X, C -> adds C sign bits.
3127 if (ConstantSDNode *C =
3128 isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)) {
3129 APInt ShiftVal = C->getAPIntValue();
3131 Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
3135 if (ConstantSDNode *C =
3136 isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)) {
3137 // shl destroys sign bits.
3138 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3139 if (C->getAPIntValue().uge(VTBits) || // Bad shift.
3140 C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
3141 return Tmp - C->getZExtValue();
3146 case ISD::XOR: // NOT is handled here.
3147 // Logical binary ops preserve the number of sign bits at the worst.
3148 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3150 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3151 FirstAnswer = std::min(Tmp, Tmp2);
3152 // We computed what we know about the sign bits as our first
3153 // answer. Now proceed to the generic code that uses
3154 // computeKnownBits, and pick whichever answer is better.
3160 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3161 if (Tmp == 1) return 1; // Early out.
3162 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3163 return std::min(Tmp, Tmp2);
3164 case ISD::SELECT_CC:
3165 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3166 if (Tmp == 1) return 1; // Early out.
3167 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3168 return std::min(Tmp, Tmp2);
3174 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3176 return 1; // Early out.
3177 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3178 return std::min(Tmp, Tmp2);
3185 if (Op.getResNo() != 1)
3187 // The boolean result conforms to getBooleanContents. Fall through.
3188 // If setcc returns 0/-1, all bits are sign bits.
3189 // We know that we have an integer-based boolean since these operations
3190 // are only available for integer.
3191 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3192 TargetLowering::ZeroOrNegativeOneBooleanContent)
3196 // If setcc returns 0/-1, all bits are sign bits.
3197 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3198 TargetLowering::ZeroOrNegativeOneBooleanContent)
3203 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3204 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3206 // Handle rotate right by N like a rotate left by 32-N.
3207 if (Op.getOpcode() == ISD::ROTR)
3208 RotAmt = (VTBits - RotAmt) % VTBits;
3210 // If we aren't rotating out all of the known-in sign bits, return the
3211 // number that are left. This handles rotl(sext(x), 1) for example.
3212 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3213 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3218 // Add can have at most one carry bit. Thus we know that the output
3219 // is, at worst, one more bit than the inputs.
3220 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3221 if (Tmp == 1) return 1; // Early out.
3223 // Special case decrementing a value (ADD X, -1):
3224 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3225 if (CRHS->isAllOnesValue()) {
3227 computeKnownBits(Op.getOperand(0), Known, Depth+1);
3229 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3231 if ((Known.Zero | 1).isAllOnesValue())
3234 // If we are subtracting one from a positive number, there is no carry
3235 // out of the result.
3236 if (Known.isNonNegative())
3240 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3241 if (Tmp2 == 1) return 1;
3242 return std::min(Tmp, Tmp2)-1;
3245 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3246 if (Tmp2 == 1) return 1;
3249 if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3250 if (CLHS->isNullValue()) {
3252 computeKnownBits(Op.getOperand(1), Known, Depth+1);
3253 // If the input is known to be 0 or 1, the output is 0/-1, which is all
3255 if ((Known.Zero | 1).isAllOnesValue())
3258 // If the input is known to be positive (the sign bit is known clear),
3259 // the output of the NEG has the same number of sign bits as the input.
3260 if (Known.isNonNegative())
3263 // Otherwise, we treat this like a SUB.
3266 // Sub can have at most one carry bit. Thus we know that the output
3267 // is, at worst, one more bit than the inputs.
3268 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3269 if (Tmp == 1) return 1; // Early out.
3270 return std::min(Tmp, Tmp2)-1;
3271 case ISD::TRUNCATE: {
3272 // Check if the sign bits of source go down as far as the truncated value.
3273 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3274 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3275 if (NumSrcSignBits > (NumSrcBits - VTBits))
3276 return NumSrcSignBits - (NumSrcBits - VTBits);
3279 case ISD::EXTRACT_ELEMENT: {
3280 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3281 const int BitWidth = Op.getValueSizeInBits();
3282 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3284 // Get reverse index (starting from 1), Op1 value indexes elements from
3285 // little end. Sign starts at big end.
3286 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3288 // If the sign portion ends in our element the subtraction gives correct
3289 // result. Otherwise it gives either negative or > bitwidth result
3290 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3292 case ISD::INSERT_VECTOR_ELT: {
3293 SDValue InVec = Op.getOperand(0);
3294 SDValue InVal = Op.getOperand(1);
3295 SDValue EltNo = Op.getOperand(2);
3296 unsigned NumElts = InVec.getValueType().getVectorNumElements();
3298 ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3299 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3300 // If we know the element index, split the demand between the
3301 // source vector and the inserted element.
3302 unsigned EltIdx = CEltNo->getZExtValue();
3304 // If we demand the inserted element then get its sign bits.
3305 Tmp = std::numeric_limits<unsigned>::max();
3306 if (DemandedElts[EltIdx]) {
3307 // TODO - handle implicit truncation of inserted elements.
3308 if (InVal.getScalarValueSizeInBits() != VTBits)
3310 Tmp = ComputeNumSignBits(InVal, Depth + 1);
3313 // If we demand the source vector then get its sign bits, and determine
3315 APInt VectorElts = DemandedElts;
3316 VectorElts.clearBit(EltIdx);
3318 Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3319 Tmp = std::min(Tmp, Tmp2);
3322 // Unknown element index, so ignore DemandedElts and demand them all.
3323 Tmp = ComputeNumSignBits(InVec, Depth + 1);
3324 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3325 Tmp = std::min(Tmp, Tmp2);
3327 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3330 case ISD::EXTRACT_VECTOR_ELT: {
3331 SDValue InVec = Op.getOperand(0);
3332 SDValue EltNo = Op.getOperand(1);
3333 EVT VecVT = InVec.getValueType();
3334 const unsigned BitWidth = Op.getValueSizeInBits();
3335 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3336 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3338 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3339 // anything about sign bits. But if the sizes match we can derive knowledge
3340 // about sign bits from the vector operand.
3341 if (BitWidth != EltBitWidth)
3344 // If we know the element index, just demand that vector element, else for
3345 // an unknown element index, ignore DemandedElts and demand them all.
3346 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3347 ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3348 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3350 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3352 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3354 case ISD::EXTRACT_SUBVECTOR: {
3355 // If we know the element index, just demand that subvector elements,
3356 // otherwise demand them all.
3357 SDValue Src = Op.getOperand(0);
3358 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3359 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3360 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3361 // Offset the demanded elts by the subvector index.
3362 uint64_t Idx = SubIdx->getZExtValue();
3363 APInt DemandedSrc = DemandedElts.zext(NumSrcElts).shl(Idx);
3364 return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3366 return ComputeNumSignBits(Src, Depth + 1);
3368 case ISD::CONCAT_VECTORS:
3369 // Determine the minimum number of sign bits across all demanded
3370 // elts of the input vectors. Early out if the result is already 1.
3371 Tmp = std::numeric_limits<unsigned>::max();
3372 EVT SubVectorVT = Op.getOperand(0).getValueType();
3373 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3374 unsigned NumSubVectors = Op.getNumOperands();
3375 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3376 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3377 DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3380 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3381 Tmp = std::min(Tmp, Tmp2);
3383 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3387 // If we are looking at the loaded value of the SDNode.
3388 if (Op.getResNo() == 0) {
3389 // Handle LOADX separately here. EXTLOAD case will fallthrough.
3390 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3391 unsigned ExtType = LD->getExtensionType();
3394 case ISD::SEXTLOAD: // '17' bits known
3395 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3396 return VTBits-Tmp+1;
3397 case ISD::ZEXTLOAD: // '16' bits known
3398 Tmp = LD->getMemoryVT().getScalarSizeInBits();
3404 // Allow the target to implement this method for its nodes.
3405 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3406 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3407 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3408 Op.getOpcode() == ISD::INTRINSIC_VOID) {
3410 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3412 FirstAnswer = std::max(FirstAnswer, NumBits);
3415 // Finally, if we can prove that the top bits of the result are 0's or 1's,
3416 // use this information.
3418 computeKnownBits(Op, Known, DemandedElts, Depth);
3421 if (Known.isNonNegative()) { // sign bit is 0
3423 } else if (Known.isNegative()) { // sign bit is 1;
3430 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
3431 // the number of identical bits in the top of the input value.
3433 Mask <<= Mask.getBitWidth()-VTBits;
3434 // Return # leading zeros. We use 'min' here in case Val was zero before
3435 // shifting. We don't want to return '64' as for an i32 "0".
3436 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3439 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3440 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3441 !isa<ConstantSDNode>(Op.getOperand(1)))
3444 if (Op.getOpcode() == ISD::OR &&
3445 !MaskedValueIsZero(Op.getOperand(0),
3446 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3452 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
3453 // If we're told that NaNs won't happen, assume they won't.
3454 if (getTarget().Options.NoNaNsFPMath)
3457 if (Op->getFlags().hasNoNaNs())
3460 // If the value is a constant, we can obviously see if it is a NaN or not.
3461 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3462 return !C->getValueAPF().isNaN();
3464 // TODO: Recognize more cases here.
3469 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3470 // If the value is a constant, we can obviously see if it is a zero or not.
3471 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3472 return !C->isZero();
3474 // TODO: Recognize more cases here.
3475 switch (Op.getOpcode()) {
3478 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3479 return !C->isNullValue();
3486 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3487 // Check the obvious case.
3488 if (A == B) return true;
3490 // For for negative and positive zero.
3491 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3492 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3493 if (CA->isZero() && CB->isZero()) return true;
3495 // Otherwise they may not be equal.
3499 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3500 assert(A.getValueType() == B.getValueType() &&
3501 "Values must have the same type");
3502 KnownBits AKnown, BKnown;
3503 computeKnownBits(A, AKnown);
3504 computeKnownBits(B, BKnown);
3505 return (AKnown.Zero | BKnown.Zero).isAllOnesValue();
3508 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
3509 ArrayRef<SDValue> Ops,
3510 SelectionDAG &DAG) {
3511 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
3512 assert(llvm::all_of(Ops,
3514 return Ops[0].getValueType() == Op.getValueType();
3516 "Concatenation of vectors with inconsistent value types!");
3517 assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
3518 VT.getVectorNumElements() &&
3519 "Incorrect element count in vector concatenation!");
3521 if (Ops.size() == 1)
3524 // Concat of UNDEFs is UNDEF.
3525 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3526 return DAG.getUNDEF(VT);
3528 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
3529 // simplified to one big BUILD_VECTOR.
3530 // FIXME: Add support for SCALAR_TO_VECTOR as well.
3531 EVT SVT = VT.getScalarType();
3532 SmallVector<SDValue, 16> Elts;
3533 for (SDValue Op : Ops) {
3534 EVT OpVT = Op.getValueType();
3536 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
3537 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
3538 Elts.append(Op->op_begin(), Op->op_end());
3543 // BUILD_VECTOR requires all inputs to be of the same type, find the
3544 // maximum type and extend them all.
3545 for (SDValue Op : Elts)
3546 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
3548 if (SVT.bitsGT(VT.getScalarType()))
3549 for (SDValue &Op : Elts)
3550 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
3551 ? DAG.getZExtOrTrunc(Op, DL, SVT)
3552 : DAG.getSExtOrTrunc(Op, DL, SVT);
3554 SDValue V = DAG.getBuildVector(VT, DL, Elts);
3555 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
3559 /// Gets or creates the specified node.
3560 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
3561 FoldingSetNodeID ID;
3562 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
3564 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3565 return SDValue(E, 0);
3567 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
3569 CSEMap.InsertNode(N, IP);
3572 SDValue V = SDValue(N, 0);
3573 NewSDValueDbgMsg(V, "Creating new node: ", this);
3577 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3578 SDValue Operand, const SDNodeFlags Flags) {
3579 // Constant fold unary operations with an integer constant operand. Even
3580 // opaque constant will be folded, because the folding of unary operations
3581 // doesn't create new constants with different values. Nevertheless, the
3582 // opaque flag is preserved during folding to prevent future folding with
3584 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
3585 const APInt &Val = C->getAPIntValue();
3588 case ISD::SIGN_EXTEND:
3589 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
3590 C->isTargetOpcode(), C->isOpaque());
3591 case ISD::ANY_EXTEND:
3592 case ISD::ZERO_EXTEND:
3594 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
3595 C->isTargetOpcode(), C->isOpaque());
3596 case ISD::UINT_TO_FP:
3597 case ISD::SINT_TO_FP: {
3598 APFloat apf(EVTToAPFloatSemantics(VT),
3599 APInt::getNullValue(VT.getSizeInBits()));
3600 (void)apf.convertFromAPInt(Val,
3601 Opcode==ISD::SINT_TO_FP,
3602 APFloat::rmNearestTiesToEven);
3603 return getConstantFP(apf, DL, VT);
3606 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
3607 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
3608 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
3609 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
3610 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
3611 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
3612 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
3613 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
3616 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
3618 case ISD::BITREVERSE:
3619 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
3622 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
3625 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
3628 case ISD::CTLZ_ZERO_UNDEF:
3629 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
3632 case ISD::CTTZ_ZERO_UNDEF:
3633 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
3635 case ISD::FP16_TO_FP: {
3637 APFloat FPV(APFloat::IEEEhalf(),
3638 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
3640 // This can return overflow, underflow, or inexact; we don't care.
3641 // FIXME need to be more flexible about rounding mode.
3642 (void)FPV.convert(EVTToAPFloatSemantics(VT),
3643 APFloat::rmNearestTiesToEven, &Ignored);
3644 return getConstantFP(FPV, DL, VT);
3649 // Constant fold unary operations with a floating point constant operand.
3650 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
3651 APFloat V = C->getValueAPF(); // make copy
3655 return getConstantFP(V, DL, VT);
3658 return getConstantFP(V, DL, VT);
3660 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
3661 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3662 return getConstantFP(V, DL, VT);
3666 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
3667 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3668 return getConstantFP(V, DL, VT);
3672 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
3673 if (fs == APFloat::opOK || fs == APFloat::opInexact)
3674 return getConstantFP(V, DL, VT);
3677 case ISD::FP_EXTEND: {
3679 // This can return overflow, underflow, or inexact; we don't care.
3680 // FIXME need to be more flexible about rounding mode.
3681 (void)V.convert(EVTToAPFloatSemantics(VT),
3682 APFloat::rmNearestTiesToEven, &ignored);
3683 return getConstantFP(V, DL, VT);
3685 case ISD::FP_TO_SINT:
3686 case ISD::FP_TO_UINT: {
3688 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
3689 // FIXME need to be more flexible about rounding mode.
3690 APFloat::opStatus s =
3691 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
3692 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
3694 return getConstant(IntVal, DL, VT);
3697 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3698 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3699 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3700 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3701 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3702 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3704 case ISD::FP_TO_FP16: {
3706 // This can return overflow, underflow, or inexact; we don't care.
3707 // FIXME need to be more flexible about rounding mode.
3708 (void)V.convert(APFloat::IEEEhalf(),
3709 APFloat::rmNearestTiesToEven, &Ignored);
3710 return getConstant(V.bitcastToAPInt(), DL, VT);
3715 // Constant fold unary operations with a vector integer or float operand.
3716 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3717 if (BV->isConstant()) {
3720 // FIXME: Entirely reasonable to perform folding of other unary
3721 // operations here as the need arises.
3728 case ISD::FP_EXTEND:
3729 case ISD::FP_TO_SINT:
3730 case ISD::FP_TO_UINT:
3732 case ISD::UINT_TO_FP:
3733 case ISD::SINT_TO_FP:
3735 case ISD::BITREVERSE:
3738 case ISD::CTLZ_ZERO_UNDEF:
3740 case ISD::CTTZ_ZERO_UNDEF:
3742 SDValue Ops = { Operand };
3743 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3750 unsigned OpOpcode = Operand.getNode()->getOpcode();
3752 case ISD::TokenFactor:
3753 case ISD::MERGE_VALUES:
3754 case ISD::CONCAT_VECTORS:
3755 return Operand; // Factor, merge or concat of one node? No need.
3756 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
3757 case ISD::FP_EXTEND:
3758 assert(VT.isFloatingPoint() &&
3759 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
3760 if (Operand.getValueType() == VT) return Operand; // noop conversion.
3761 assert((!VT.isVector() ||
3762 VT.getVectorNumElements() ==
3763 Operand.getValueType().getVectorNumElements()) &&
3764 "Vector element count mismatch!");
3765 assert(Operand.getValueType().bitsLT(VT) &&
3766 "Invalid fpext node, dst < src!");
3767 if (Operand.isUndef())
3768 return getUNDEF(VT);
3770 case ISD::SIGN_EXTEND:
3771 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3772 "Invalid SIGN_EXTEND!");
3773 if (Operand.getValueType() == VT) return Operand; // noop extension
3774 assert((!VT.isVector() ||
3775 VT.getVectorNumElements() ==
3776 Operand.getValueType().getVectorNumElements()) &&
3777 "Vector element count mismatch!");
3778 assert(Operand.getValueType().bitsLT(VT) &&
3779 "Invalid sext node, dst < src!");
3780 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
3781 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3782 else if (OpOpcode == ISD::UNDEF)
3783 // sext(undef) = 0, because the top bits will all be the same.
3784 return getConstant(0, DL, VT);
3786 case ISD::ZERO_EXTEND:
3787 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3788 "Invalid ZERO_EXTEND!");
3789 if (Operand.getValueType() == VT) return Operand; // noop extension
3790 assert((!VT.isVector() ||
3791 VT.getVectorNumElements() ==
3792 Operand.getValueType().getVectorNumElements()) &&
3793 "Vector element count mismatch!");
3794 assert(Operand.getValueType().bitsLT(VT) &&
3795 "Invalid zext node, dst < src!");
3796 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
3797 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
3798 else if (OpOpcode == ISD::UNDEF)
3799 // zext(undef) = 0, because the top bits will be zero.
3800 return getConstant(0, DL, VT);
3802 case ISD::ANY_EXTEND:
3803 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3804 "Invalid ANY_EXTEND!");
3805 if (Operand.getValueType() == VT) return Operand; // noop extension
3806 assert((!VT.isVector() ||
3807 VT.getVectorNumElements() ==
3808 Operand.getValueType().getVectorNumElements()) &&
3809 "Vector element count mismatch!");
3810 assert(Operand.getValueType().bitsLT(VT) &&
3811 "Invalid anyext node, dst < src!");
3813 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3814 OpOpcode == ISD::ANY_EXTEND)
3815 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
3816 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3817 else if (OpOpcode == ISD::UNDEF)
3818 return getUNDEF(VT);
3820 // (ext (trunx x)) -> x
3821 if (OpOpcode == ISD::TRUNCATE) {
3822 SDValue OpOp = Operand.getOperand(0);
3823 if (OpOp.getValueType() == VT)
3828 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3829 "Invalid TRUNCATE!");
3830 if (Operand.getValueType() == VT) return Operand; // noop truncate
3831 assert((!VT.isVector() ||
3832 VT.getVectorNumElements() ==
3833 Operand.getValueType().getVectorNumElements()) &&
3834 "Vector element count mismatch!");
3835 assert(Operand.getValueType().bitsGT(VT) &&
3836 "Invalid truncate node, src < dst!");
3837 if (OpOpcode == ISD::TRUNCATE)
3838 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
3839 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3840 OpOpcode == ISD::ANY_EXTEND) {
3841 // If the source is smaller than the dest, we still need an extend.
3842 if (Operand.getOperand(0).getValueType().getScalarType()
3843 .bitsLT(VT.getScalarType()))
3844 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
3845 if (Operand.getOperand(0).getValueType().bitsGT(VT))
3846 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
3847 return Operand.getOperand(0);
3849 if (OpOpcode == ISD::UNDEF)
3850 return getUNDEF(VT);
3853 assert(VT.isInteger() && VT == Operand.getValueType() &&
3855 if (OpOpcode == ISD::UNDEF)
3856 return getUNDEF(VT);
3859 assert(VT.isInteger() && VT == Operand.getValueType() &&
3861 assert((VT.getScalarSizeInBits() % 16 == 0) &&
3862 "BSWAP types must be a multiple of 16 bits!");
3863 if (OpOpcode == ISD::UNDEF)
3864 return getUNDEF(VT);
3866 case ISD::BITREVERSE:
3867 assert(VT.isInteger() && VT == Operand.getValueType() &&
3868 "Invalid BITREVERSE!");
3869 if (OpOpcode == ISD::UNDEF)
3870 return getUNDEF(VT);
3873 // Basic sanity checking.
3874 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
3875 "Cannot BITCAST between types of different sizes!");
3876 if (VT == Operand.getValueType()) return Operand; // noop conversion.
3877 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
3878 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
3879 if (OpOpcode == ISD::UNDEF)
3880 return getUNDEF(VT);
3882 case ISD::SCALAR_TO_VECTOR:
3883 assert(VT.isVector() && !Operand.getValueType().isVector() &&
3884 (VT.getVectorElementType() == Operand.getValueType() ||
3885 (VT.getVectorElementType().isInteger() &&
3886 Operand.getValueType().isInteger() &&
3887 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
3888 "Illegal SCALAR_TO_VECTOR node!");
3889 if (OpOpcode == ISD::UNDEF)
3890 return getUNDEF(VT);
3891 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
3892 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
3893 isa<ConstantSDNode>(Operand.getOperand(1)) &&
3894 Operand.getConstantOperandVal(1) == 0 &&
3895 Operand.getOperand(0).getValueType() == VT)
3896 return Operand.getOperand(0);
3899 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
3900 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
3901 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags?
3902 return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
3903 Operand.getOperand(0), Operand.getNode()->getFlags());
3904 if (OpOpcode == ISD::FNEG) // --X -> X
3905 return Operand.getOperand(0);
3908 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
3909 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
3914 SDVTList VTs = getVTList(VT);
3915 SDValue Ops[] = {Operand};
3916 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
3917 FoldingSetNodeID ID;
3918 AddNodeIDNode(ID, Opcode, VTs, Ops);
3920 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
3921 E->intersectFlagsWith(Flags);
3922 return SDValue(E, 0);
3925 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3927 createOperands(N, Ops);
3928 CSEMap.InsertNode(N, IP);
3930 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3931 createOperands(N, Ops);
3935 SDValue V = SDValue(N, 0);
3936 NewSDValueDbgMsg(V, "Creating new node: ", this);
3940 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
3943 case ISD::ADD: return std::make_pair(C1 + C2, true);
3944 case ISD::SUB: return std::make_pair(C1 - C2, true);
3945 case ISD::MUL: return std::make_pair(C1 * C2, true);
3946 case ISD::AND: return std::make_pair(C1 & C2, true);
3947 case ISD::OR: return std::make_pair(C1 | C2, true);
3948 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
3949 case ISD::SHL: return std::make_pair(C1 << C2, true);
3950 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
3951 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
3952 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
3953 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
3954 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
3955 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
3956 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
3957 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
3959 if (!C2.getBoolValue())
3961 return std::make_pair(C1.udiv(C2), true);
3963 if (!C2.getBoolValue())
3965 return std::make_pair(C1.urem(C2), true);
3967 if (!C2.getBoolValue())
3969 return std::make_pair(C1.sdiv(C2), true);
3971 if (!C2.getBoolValue())
3973 return std::make_pair(C1.srem(C2), true);
3975 return std::make_pair(APInt(1, 0), false);
3978 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3979 EVT VT, const ConstantSDNode *Cst1,
3980 const ConstantSDNode *Cst2) {
3981 if (Cst1->isOpaque() || Cst2->isOpaque())
3984 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
3985 Cst2->getAPIntValue());
3988 return getConstant(Folded.first, DL, VT);
3991 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
3992 const GlobalAddressSDNode *GA,
3994 if (GA->getOpcode() != ISD::GlobalAddress)
3996 if (!TLI->isOffsetFoldingLegal(GA))
3998 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
4001 int64_t Offset = Cst2->getSExtValue();
4003 case ISD::ADD: break;
4004 case ISD::SUB: Offset = -uint64_t(Offset); break;
4005 default: return SDValue();
4007 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
4008 GA->getOffset() + uint64_t(Offset));
4011 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4017 // If a divisor is zero/undef or any element of a divisor vector is
4018 // zero/undef, the whole op is undef.
4019 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4020 SDValue Divisor = Ops[1];
4021 if (Divisor.isUndef() || isNullConstant(Divisor))
4024 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4025 llvm::any_of(Divisor->op_values(),
4026 [](SDValue V) { return V.isUndef() ||
4027 isNullConstant(V); });
4028 // TODO: Handle signed overflow.
4030 // TODO: Handle oversized shifts.
4036 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4037 EVT VT, SDNode *Cst1,
4039 // If the opcode is a target-specific ISD node, there's nothing we can
4040 // do here and the operand rules may not line up with the below, so
4042 if (Opcode >= ISD::BUILTIN_OP_END)
4045 if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)}))
4046 return getUNDEF(VT);
4048 // Handle the case of two scalars.
4049 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
4050 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
4051 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
4052 assert((!Folded || !VT.isVector()) &&
4053 "Can't fold vectors ops with scalar operands");
4058 // fold (add Sym, c) -> Sym+c
4059 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
4060 return FoldSymbolOffset(Opcode, VT, GA, Cst2);
4061 if (TLI->isCommutativeBinOp(Opcode))
4062 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
4063 return FoldSymbolOffset(Opcode, VT, GA, Cst1);
4065 // For vectors extract each constant element into Inputs so we can constant
4066 // fold them individually.
4067 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
4068 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
4072 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
4074 EVT SVT = VT.getScalarType();
4076 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4077 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4078 if (LegalSVT.bitsLT(SVT))
4081 SmallVector<SDValue, 4> Outputs;
4082 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
4083 SDValue V1 = BV1->getOperand(I);
4084 SDValue V2 = BV2->getOperand(I);
4086 if (SVT.isInteger()) {
4087 if (V1->getValueType(0).bitsGT(SVT))
4088 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
4089 if (V2->getValueType(0).bitsGT(SVT))
4090 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
4093 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
4096 // Fold one vector element.
4097 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
4098 if (LegalSVT != SVT)
4099 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4101 // Scalar folding only succeeded if the result is a constant or UNDEF.
4102 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4103 ScalarResult.getOpcode() != ISD::ConstantFP)
4105 Outputs.push_back(ScalarResult);
4108 assert(VT.getVectorNumElements() == Outputs.size() &&
4109 "Vector size mismatch!");
4111 // We may have a vector type but a scalar result. Create a splat.
4112 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
4114 // Build a big vector out of the scalar elements we generated.
4115 return getBuildVector(VT, SDLoc(), Outputs);
4118 // TODO: Merge with FoldConstantArithmetic
4119 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
4120 const SDLoc &DL, EVT VT,
4121 ArrayRef<SDValue> Ops,
4122 const SDNodeFlags Flags) {
4123 // If the opcode is a target-specific ISD node, there's nothing we can
4124 // do here and the operand rules may not line up with the below, so
4126 if (Opcode >= ISD::BUILTIN_OP_END)
4129 if (isUndef(Opcode, Ops))
4130 return getUNDEF(VT);
4132 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
4136 unsigned NumElts = VT.getVectorNumElements();
4138 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
4139 return !Op.getValueType().isVector() ||
4140 Op.getValueType().getVectorNumElements() == NumElts;
4143 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
4144 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
4145 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
4146 (BV && BV->isConstant());
4149 // All operands must be vector types with the same number of elements as
4150 // the result type and must be either UNDEF or a build vector of constant
4151 // or UNDEF scalars.
4152 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
4153 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
4156 // If we are comparing vectors, then the result needs to be a i1 boolean
4157 // that is then sign-extended back to the legal result type.
4158 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
4160 // Find legal integer scalar type for constant promotion and
4161 // ensure that its scalar size is at least as large as source.
4162 EVT LegalSVT = VT.getScalarType();
4163 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4164 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4165 if (LegalSVT.bitsLT(VT.getScalarType()))
4169 // Constant fold each scalar lane separately.
4170 SmallVector<SDValue, 4> ScalarResults;
4171 for (unsigned i = 0; i != NumElts; i++) {
4172 SmallVector<SDValue, 4> ScalarOps;
4173 for (SDValue Op : Ops) {
4174 EVT InSVT = Op.getValueType().getScalarType();
4175 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
4177 // We've checked that this is UNDEF or a constant of some kind.
4179 ScalarOps.push_back(getUNDEF(InSVT));
4181 ScalarOps.push_back(Op);
4185 SDValue ScalarOp = InBV->getOperand(i);
4186 EVT ScalarVT = ScalarOp.getValueType();
4188 // Build vector (integer) scalar operands may need implicit
4189 // truncation - do this before constant folding.
4190 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
4191 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
4193 ScalarOps.push_back(ScalarOp);
4196 // Constant fold the scalar operands.
4197 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
4199 // Legalize the (integer) scalar constant if necessary.
4200 if (LegalSVT != SVT)
4201 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4203 // Scalar folding only succeeded if the result is a constant or UNDEF.
4204 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4205 ScalarResult.getOpcode() != ISD::ConstantFP)
4207 ScalarResults.push_back(ScalarResult);
4210 SDValue V = getBuildVector(VT, DL, ScalarResults);
4211 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
4215 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4216 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
4217 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4218 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4219 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4220 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4222 // Canonicalize constant to RHS if commutative.
4223 if (TLI->isCommutativeBinOp(Opcode)) {
4225 std::swap(N1C, N2C);
4227 } else if (N1CFP && !N2CFP) {
4228 std::swap(N1CFP, N2CFP);
4235 case ISD::TokenFactor:
4236 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
4237 N2.getValueType() == MVT::Other && "Invalid token factor!");
4238 // Fold trivial token factors.
4239 if (N1.getOpcode() == ISD::EntryToken) return N2;
4240 if (N2.getOpcode() == ISD::EntryToken) return N1;
4241 if (N1 == N2) return N1;
4243 case ISD::CONCAT_VECTORS: {
4244 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4245 SDValue Ops[] = {N1, N2};
4246 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4251 assert(VT.isInteger() && "This operator does not apply to FP types!");
4252 assert(N1.getValueType() == N2.getValueType() &&
4253 N1.getValueType() == VT && "Binary operator types must match!");
4254 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
4255 // worth handling here.
4256 if (N2C && N2C->isNullValue())
4258 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
4265 assert(VT.isInteger() && "This operator does not apply to FP types!");
4266 assert(N1.getValueType() == N2.getValueType() &&
4267 N1.getValueType() == VT && "Binary operator types must match!");
4268 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
4269 // it's worth handling here.
4270 if (N2C && N2C->isNullValue())
4284 assert(VT.isInteger() && "This operator does not apply to FP types!");
4285 assert(N1.getValueType() == N2.getValueType() &&
4286 N1.getValueType() == VT && "Binary operator types must match!");
4293 if (getTarget().Options.UnsafeFPMath) {
4294 if (Opcode == ISD::FADD) {
4296 if (N2CFP && N2CFP->getValueAPF().isZero())
4298 } else if (Opcode == ISD::FSUB) {
4300 if (N2CFP && N2CFP->getValueAPF().isZero())
4302 } else if (Opcode == ISD::FMUL) {
4304 if (N2CFP && N2CFP->isZero())
4307 if (N2CFP && N2CFP->isExactlyValue(1.0))
4311 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4312 assert(N1.getValueType() == N2.getValueType() &&
4313 N1.getValueType() == VT && "Binary operator types must match!");
4315 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
4316 assert(N1.getValueType() == VT &&
4317 N1.getValueType().isFloatingPoint() &&
4318 N2.getValueType().isFloatingPoint() &&
4319 "Invalid FCOPYSIGN!");
4326 assert(VT == N1.getValueType() &&
4327 "Shift operators return type must be the same as their first arg");
4328 assert(VT.isInteger() && N2.getValueType().isInteger() &&
4329 "Shifts only work on integers");
4330 assert((!VT.isVector() || VT == N2.getValueType()) &&
4331 "Vector shift amounts must be in the same as their first arg");
4332 // Verify that the shift amount VT is bit enough to hold valid shift
4333 // amounts. This catches things like trying to shift an i1024 value by an
4334 // i8, which is easy to fall into in generic code that uses
4335 // TLI.getShiftAmount().
4336 assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4337 "Invalid use of small shift amount with oversized value!");
4339 // Always fold shifts of i1 values so the code generator doesn't need to
4340 // handle them. Since we know the size of the shift has to be less than the
4341 // size of the value, the shift/rotate count is guaranteed to be zero.
4344 if (N2C && N2C->isNullValue())
4347 case ISD::FP_ROUND_INREG: {
4348 EVT EVT = cast<VTSDNode>(N2)->getVT();
4349 assert(VT == N1.getValueType() && "Not an inreg round!");
4350 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4351 "Cannot FP_ROUND_INREG integer types");
4352 assert(EVT.isVector() == VT.isVector() &&
4353 "FP_ROUND_INREG type should be vector iff the operand "
4355 assert((!EVT.isVector() ||
4356 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4357 "Vector element counts must match in FP_ROUND_INREG");
4358 assert(EVT.bitsLE(VT) && "Not rounding down!");
4360 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
4364 assert(VT.isFloatingPoint() &&
4365 N1.getValueType().isFloatingPoint() &&
4366 VT.bitsLE(N1.getValueType()) &&
4367 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4368 "Invalid FP_ROUND!");
4369 if (N1.getValueType() == VT) return N1; // noop conversion.
4371 case ISD::AssertSext:
4372 case ISD::AssertZext: {
4373 EVT EVT = cast<VTSDNode>(N2)->getVT();
4374 assert(VT == N1.getValueType() && "Not an inreg extend!");
4375 assert(VT.isInteger() && EVT.isInteger() &&
4376 "Cannot *_EXTEND_INREG FP types");
4377 assert(!EVT.isVector() &&
4378 "AssertSExt/AssertZExt type should be the vector element type "
4379 "rather than the vector type!");
4380 assert(EVT.bitsLE(VT) && "Not extending!");
4381 if (VT == EVT) return N1; // noop assertion.
4384 case ISD::SIGN_EXTEND_INREG: {
4385 EVT EVT = cast<VTSDNode>(N2)->getVT();
4386 assert(VT == N1.getValueType() && "Not an inreg extend!");
4387 assert(VT.isInteger() && EVT.isInteger() &&
4388 "Cannot *_EXTEND_INREG FP types");
4389 assert(EVT.isVector() == VT.isVector() &&
4390 "SIGN_EXTEND_INREG type should be vector iff the operand "
4392 assert((!EVT.isVector() ||
4393 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4394 "Vector element counts must match in SIGN_EXTEND_INREG");
4395 assert(EVT.bitsLE(VT) && "Not extending!");
4396 if (EVT == VT) return N1; // Not actually extending
4398 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4399 unsigned FromBits = EVT.getScalarSizeInBits();
4400 Val <<= Val.getBitWidth() - FromBits;
4401 Val.ashrInPlace(Val.getBitWidth() - FromBits);
4402 return getConstant(Val, DL, ConstantVT);
4406 const APInt &Val = N1C->getAPIntValue();
4407 return SignExtendInReg(Val, VT);
4409 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4410 SmallVector<SDValue, 8> Ops;
4411 llvm::EVT OpVT = N1.getOperand(0).getValueType();
4412 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4413 SDValue Op = N1.getOperand(i);
4415 Ops.push_back(getUNDEF(OpVT));
4418 ConstantSDNode *C = cast<ConstantSDNode>(Op);
4419 APInt Val = C->getAPIntValue();
4420 Ops.push_back(SignExtendInReg(Val, OpVT));
4422 return getBuildVector(VT, DL, Ops);
4426 case ISD::EXTRACT_VECTOR_ELT:
4427 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4429 return getUNDEF(VT);
4431 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4432 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4433 return getUNDEF(VT);
4435 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4436 // expanding copies of large vectors from registers.
4438 N1.getOpcode() == ISD::CONCAT_VECTORS &&
4439 N1.getNumOperands() > 0) {
4441 N1.getOperand(0).getValueType().getVectorNumElements();
4442 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4443 N1.getOperand(N2C->getZExtValue() / Factor),
4444 getConstant(N2C->getZExtValue() % Factor, DL,
4445 N2.getValueType()));
4448 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4449 // expanding large vector constants.
4450 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4451 SDValue Elt = N1.getOperand(N2C->getZExtValue());
4453 if (VT != Elt.getValueType())
4454 // If the vector element type is not legal, the BUILD_VECTOR operands
4455 // are promoted and implicitly truncated, and the result implicitly
4456 // extended. Make that explicit here.
4457 Elt = getAnyExtOrTrunc(Elt, DL, VT);
4462 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
4463 // operations are lowered to scalars.
4464 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
4465 // If the indices are the same, return the inserted element else
4466 // if the indices are known different, extract the element from
4467 // the original vector.
4468 SDValue N1Op2 = N1.getOperand(2);
4469 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
4471 if (N1Op2C && N2C) {
4472 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
4473 if (VT == N1.getOperand(1).getValueType())
4474 return N1.getOperand(1);
4476 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
4479 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
4483 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
4484 // when vector types are scalarized and v1iX is legal.
4485 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx)
4486 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4487 N1.getValueType().getVectorNumElements() == 1) {
4488 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
4492 case ISD::EXTRACT_ELEMENT:
4493 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
4494 assert(!N1.getValueType().isVector() && !VT.isVector() &&
4495 (N1.getValueType().isInteger() == VT.isInteger()) &&
4496 N1.getValueType() != VT &&
4497 "Wrong types for EXTRACT_ELEMENT!");
4499 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
4500 // 64-bit integers into 32-bit parts. Instead of building the extract of
4501 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
4502 if (N1.getOpcode() == ISD::BUILD_PAIR)
4503 return N1.getOperand(N2C->getZExtValue());
4505 // EXTRACT_ELEMENT of a constant int is also very common.
4507 unsigned ElementSize = VT.getSizeInBits();
4508 unsigned Shift = ElementSize * N2C->getZExtValue();
4509 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
4510 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
4513 case ISD::EXTRACT_SUBVECTOR:
4514 if (VT.isSimple() && N1.getValueType().isSimple()) {
4515 assert(VT.isVector() && N1.getValueType().isVector() &&
4516 "Extract subvector VTs must be a vectors!");
4517 assert(VT.getVectorElementType() ==
4518 N1.getValueType().getVectorElementType() &&
4519 "Extract subvector VTs must have the same element type!");
4520 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
4521 "Extract subvector must be from larger vector to smaller vector!");
4524 assert((VT.getVectorNumElements() + N2C->getZExtValue()
4525 <= N1.getValueType().getVectorNumElements())
4526 && "Extract subvector overflow!");
4529 // Trivial extraction.
4530 if (VT.getSimpleVT() == N1.getSimpleValueType())
4533 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
4535 return getUNDEF(VT);
4537 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
4538 // the concat have the same type as the extract.
4539 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
4540 N1.getNumOperands() > 0 &&
4541 VT == N1.getOperand(0).getValueType()) {
4542 unsigned Factor = VT.getVectorNumElements();
4543 return N1.getOperand(N2C->getZExtValue() / Factor);
4546 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
4547 // during shuffle legalization.
4548 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
4549 VT == N1.getOperand(1).getValueType())
4550 return N1.getOperand(1);
4555 // Perform trivial constant folding.
4557 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
4560 // Constant fold FP operations.
4561 bool HasFPExceptions = TLI->hasFloatingPointExceptions();
4564 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
4565 APFloat::opStatus s;
4568 s = V1.add(V2, APFloat::rmNearestTiesToEven);
4569 if (!HasFPExceptions || s != APFloat::opInvalidOp)
4570 return getConstantFP(V1, DL, VT);
4573 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
4574 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4575 return getConstantFP(V1, DL, VT);
4578 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
4579 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
4580 return getConstantFP(V1, DL, VT);
4583 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
4584 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4585 s!=APFloat::opDivByZero)) {
4586 return getConstantFP(V1, DL, VT);
4591 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
4592 s!=APFloat::opDivByZero)) {
4593 return getConstantFP(V1, DL, VT);
4596 case ISD::FCOPYSIGN:
4598 return getConstantFP(V1, DL, VT);
4603 if (Opcode == ISD::FP_ROUND) {
4604 APFloat V = N1CFP->getValueAPF(); // make copy
4606 // This can return overflow, underflow, or inexact; we don't care.
4607 // FIXME need to be more flexible about rounding mode.
4608 (void)V.convert(EVTToAPFloatSemantics(VT),
4609 APFloat::rmNearestTiesToEven, &ignored);
4610 return getConstantFP(V, DL, VT);
4614 // Canonicalize an UNDEF to the RHS, even over a constant.
4616 if (TLI->isCommutativeBinOp(Opcode)) {
4620 case ISD::FP_ROUND_INREG:
4621 case ISD::SIGN_EXTEND_INREG:
4627 return N1; // fold op(undef, arg2) -> undef
4635 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
4636 // For vectors, we can't easily build an all zero vector, just return
4643 // Fold a bunch of operators when the RHS is undef.
4648 // Handle undef ^ undef -> 0 special case. This is a common
4650 return getConstant(0, DL, VT);
4660 return N2; // fold op(arg1, undef) -> undef
4666 if (getTarget().Options.UnsafeFPMath)
4674 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
4675 // For vectors, we can't easily build an all zero vector, just return
4680 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
4681 // For vectors, we can't easily build an all one vector, just return
4689 // Memoize this node if possible.
4691 SDVTList VTs = getVTList(VT);
4692 SDValue Ops[] = {N1, N2};
4693 if (VT != MVT::Glue) {
4694 FoldingSetNodeID ID;
4695 AddNodeIDNode(ID, Opcode, VTs, Ops);
4697 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4698 E->intersectFlagsWith(Flags);
4699 return SDValue(E, 0);
4702 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4704 createOperands(N, Ops);
4705 CSEMap.InsertNode(N, IP);
4707 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4708 createOperands(N, Ops);
4712 SDValue V = SDValue(N, 0);
4713 NewSDValueDbgMsg(V, "Creating new node: ", this);
4717 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4718 SDValue N1, SDValue N2, SDValue N3) {
4719 // Perform various simplifications.
4722 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4723 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4724 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
4725 if (N1CFP && N2CFP && N3CFP) {
4726 APFloat V1 = N1CFP->getValueAPF();
4727 const APFloat &V2 = N2CFP->getValueAPF();
4728 const APFloat &V3 = N3CFP->getValueAPF();
4729 APFloat::opStatus s =
4730 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
4731 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
4732 return getConstantFP(V1, DL, VT);
4736 case ISD::CONCAT_VECTORS: {
4737 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4738 SDValue Ops[] = {N1, N2, N3};
4739 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4744 // Use FoldSetCC to simplify SETCC's.
4745 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
4747 // Vector constant folding.
4748 SDValue Ops[] = {N1, N2, N3};
4749 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
4750 NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
4756 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
4757 if (N1C->getZExtValue())
4758 return N2; // select true, X, Y -> X
4759 return N3; // select false, X, Y -> Y
4762 if (N2 == N3) return N2; // select C, X, X -> X
4764 case ISD::VECTOR_SHUFFLE:
4765 llvm_unreachable("should use getVectorShuffle constructor!");
4766 case ISD::INSERT_VECTOR_ELT: {
4767 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
4768 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
4769 if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
4770 return getUNDEF(VT);
4773 case ISD::INSERT_SUBVECTOR: {
4775 if (VT.isSimple() && N1.getValueType().isSimple()
4776 && N2.getValueType().isSimple()) {
4777 assert(VT.isVector() && N1.getValueType().isVector() &&
4778 N2.getValueType().isVector() &&
4779 "Insert subvector VTs must be a vectors");
4780 assert(VT == N1.getValueType() &&
4781 "Dest and insert subvector source types must match!");
4782 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
4783 "Insert subvector must be from smaller vector to larger vector!");
4784 if (isa<ConstantSDNode>(Index)) {
4785 assert((N2.getValueType().getVectorNumElements() +
4786 cast<ConstantSDNode>(Index)->getZExtValue()
4787 <= VT.getVectorNumElements())
4788 && "Insert subvector overflow!");
4791 // Trivial insertion.
4792 if (VT.getSimpleVT() == N2.getSimpleValueType())
4798 // Fold bit_convert nodes from a type to themselves.
4799 if (N1.getValueType() == VT)
4804 // Memoize node if it doesn't produce a flag.
4806 SDVTList VTs = getVTList(VT);
4807 SDValue Ops[] = {N1, N2, N3};
4808 if (VT != MVT::Glue) {
4809 FoldingSetNodeID ID;
4810 AddNodeIDNode(ID, Opcode, VTs, Ops);
4812 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4813 return SDValue(E, 0);
4815 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4816 createOperands(N, Ops);
4817 CSEMap.InsertNode(N, IP);
4819 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4820 createOperands(N, Ops);
4824 SDValue V = SDValue(N, 0);
4825 NewSDValueDbgMsg(V, "Creating new node: ", this);
4829 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4830 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
4831 SDValue Ops[] = { N1, N2, N3, N4 };
4832 return getNode(Opcode, DL, VT, Ops);
4835 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4836 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
4838 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4839 return getNode(Opcode, DL, VT, Ops);
4842 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
4843 /// the incoming stack arguments to be loaded from the stack.
4844 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
4845 SmallVector<SDValue, 8> ArgChains;
4847 // Include the original chain at the beginning of the list. When this is
4848 // used by target LowerCall hooks, this helps legalize find the
4849 // CALLSEQ_BEGIN node.
4850 ArgChains.push_back(Chain);
4852 // Add a chain value for each stack argument.
4853 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
4854 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
4855 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4856 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4857 if (FI->getIndex() < 0)
4858 ArgChains.push_back(SDValue(L, 1));
4860 // Build a tokenfactor for all the chains.
4861 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4864 /// getMemsetValue - Vectorized representation of the memset value
4866 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
4868 assert(!Value.isUndef());
4870 unsigned NumBits = VT.getScalarSizeInBits();
4871 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4872 assert(C->getAPIntValue().getBitWidth() == 8);
4873 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
4875 return DAG.getConstant(Val, dl, VT);
4876 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
4880 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
4881 EVT IntVT = VT.getScalarType();
4882 if (!IntVT.isInteger())
4883 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
4885 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
4887 // Use a multiplication with 0x010101... to extend the input to the
4889 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
4890 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
4891 DAG.getConstant(Magic, dl, IntVT));
4894 if (VT != Value.getValueType() && !VT.isInteger())
4895 Value = DAG.getBitcast(VT.getScalarType(), Value);
4896 if (VT != Value.getValueType())
4897 Value = DAG.getSplatBuildVector(VT, dl, Value);
4902 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4903 /// used when a memcpy is turned into a memset when the source is a constant
4905 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
4906 const TargetLowering &TLI,
4907 const ConstantDataArraySlice &Slice) {
4908 // Handle vector with all elements zero.
4909 if (Slice.Array == nullptr) {
4911 return DAG.getConstant(0, dl, VT);
4912 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
4913 return DAG.getConstantFP(0.0, dl, VT);
4914 else if (VT.isVector()) {
4915 unsigned NumElts = VT.getVectorNumElements();
4916 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4917 return DAG.getNode(ISD::BITCAST, dl, VT,
4918 DAG.getConstant(0, dl,
4919 EVT::getVectorVT(*DAG.getContext(),
4922 llvm_unreachable("Expected type!");
4925 assert(!VT.isVector() && "Can't handle vector type here!");
4926 unsigned NumVTBits = VT.getSizeInBits();
4927 unsigned NumVTBytes = NumVTBits / 8;
4928 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
4930 APInt Val(NumVTBits, 0);
4931 if (DAG.getDataLayout().isLittleEndian()) {
4932 for (unsigned i = 0; i != NumBytes; ++i)
4933 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
4935 for (unsigned i = 0; i != NumBytes; ++i)
4936 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
4939 // If the "cost" of materializing the integer immediate is less than the cost
4940 // of a load, then it is cost effective to turn the load into the immediate.
4941 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
4942 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
4943 return DAG.getConstant(Val, dl, VT);
4944 return SDValue(nullptr, 0);
4947 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
4949 EVT VT = Base.getValueType();
4950 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
4953 /// Returns true if memcpy source is constant data.
4954 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
4955 uint64_t SrcDelta = 0;
4956 GlobalAddressSDNode *G = nullptr;
4957 if (Src.getOpcode() == ISD::GlobalAddress)
4958 G = cast<GlobalAddressSDNode>(Src);
4959 else if (Src.getOpcode() == ISD::ADD &&
4960 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4961 Src.getOperand(1).getOpcode() == ISD::Constant) {
4962 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
4963 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
4968 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
4969 SrcDelta + G->getOffset());
4972 /// Determines the optimal series of memory ops to replace the memset / memcpy.
4973 /// Return true if the number of memory ops is below the threshold (Limit).
4974 /// It returns the types of the sequence of memory ops to perform
4975 /// memset / memcpy by reference.
4976 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
4977 unsigned Limit, uint64_t Size,
4978 unsigned DstAlign, unsigned SrcAlign,
4983 unsigned DstAS, unsigned SrcAS,
4985 const TargetLowering &TLI) {
4986 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
4987 "Expecting memcpy / memset source to meet alignment requirement!");
4988 // If 'SrcAlign' is zero, that means the memory operation does not need to
4989 // load the value, i.e. memset or memcpy from constant string. Otherwise,
4990 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
4991 // is the specified alignment of the memory operation. If it is zero, that
4992 // means it's possible to change the alignment of the destination.
4993 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
4994 // not need to be loaded.
4995 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
4996 IsMemset, ZeroMemset, MemcpyStrSrc,
4997 DAG.getMachineFunction());
4999 if (VT == MVT::Other) {
5000 // Use the largest integer type whose alignment constraints are satisfied.
5001 // We only need to check DstAlign here as SrcAlign is always greater or
5002 // equal to DstAlign (or zero).
5004 while (DstAlign && DstAlign < VT.getSizeInBits() / 8 &&
5005 !TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign))
5006 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
5007 assert(VT.isInteger());
5009 // Find the largest legal integer type.
5011 while (!TLI.isTypeLegal(LVT))
5012 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
5013 assert(LVT.isInteger());
5015 // If the type we've chosen is larger than the largest legal integer type
5016 // then use that instead.
5021 unsigned NumMemOps = 0;
5023 unsigned VTSize = VT.getSizeInBits() / 8;
5024 while (VTSize > Size) {
5025 // For now, only use non-vector load / store's for the left-over pieces.
5030 if (VT.isVector() || VT.isFloatingPoint()) {
5031 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
5032 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
5033 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
5035 else if (NewVT == MVT::i64 &&
5036 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
5037 TLI.isSafeMemOpType(MVT::f64)) {
5038 // i64 is usually not legal on 32-bit targets, but f64 may be.
5046 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
5047 if (NewVT == MVT::i8)
5049 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
5051 NewVTSize = NewVT.getSizeInBits() / 8;
5053 // If the new VT cannot cover all of the remaining bits, then consider
5054 // issuing a (or a pair of) unaligned and overlapping load / store.
5055 // FIXME: Only does this for 64-bit or more since we don't have proper
5056 // cost model for unaligned load / store.
5058 if (NumMemOps && AllowOverlap &&
5059 VTSize >= 8 && NewVTSize < Size &&
5060 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
5068 if (++NumMemOps > Limit)
5071 MemOps.push_back(VT);
5078 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
5079 // On Darwin, -Os means optimize for size without hurting performance, so
5080 // only really optimize for size when -Oz (MinSize) is used.
5081 if (MF.getTarget().getTargetTriple().isOSDarwin())
5082 return MF.getFunction()->optForMinSize();
5083 return MF.getFunction()->optForSize();
5086 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5087 SDValue Chain, SDValue Dst, SDValue Src,
5088 uint64_t Size, unsigned Align,
5089 bool isVol, bool AlwaysInline,
5090 MachinePointerInfo DstPtrInfo,
5091 MachinePointerInfo SrcPtrInfo) {
5092 // Turn a memcpy of undef to nop.
5096 // Expand memcpy to a series of load and store ops if the size operand falls
5097 // below a certain threshold.
5098 // TODO: In the AlwaysInline case, if the size is big then generate a loop
5099 // rather than maybe a humongous number of loads and stores.
5100 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5101 const DataLayout &DL = DAG.getDataLayout();
5102 LLVMContext &C = *DAG.getContext();
5103 std::vector<EVT> MemOps;
5104 bool DstAlignCanChange = false;
5105 MachineFunction &MF = DAG.getMachineFunction();
5106 MachineFrameInfo &MFI = MF.getFrameInfo();
5107 bool OptSize = shouldLowerMemFuncForSize(MF);
5108 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5109 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5110 DstAlignCanChange = true;
5111 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5112 if (Align > SrcAlign)
5114 ConstantDataArraySlice Slice;
5115 bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
5116 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
5117 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
5119 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5120 (DstAlignCanChange ? 0 : Align),
5121 (isZeroConstant ? 0 : SrcAlign),
5122 false, false, CopyFromConstant, true,
5123 DstPtrInfo.getAddrSpace(),
5124 SrcPtrInfo.getAddrSpace(),
5128 if (DstAlignCanChange) {
5129 Type *Ty = MemOps[0].getTypeForEVT(C);
5130 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5132 // Don't promote to an alignment that would require dynamic stack
5134 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
5135 if (!TRI->needsStackRealignment(MF))
5136 while (NewAlign > Align &&
5137 DL.exceedsNaturalStackAlignment(NewAlign))
5140 if (NewAlign > Align) {
5141 // Give the stack frame object a larger alignment if needed.
5142 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5143 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5148 MachineMemOperand::Flags MMOFlags =
5149 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5150 SmallVector<SDValue, 8> OutChains;
5151 unsigned NumMemOps = MemOps.size();
5152 uint64_t SrcOff = 0, DstOff = 0;
5153 for (unsigned i = 0; i != NumMemOps; ++i) {
5155 unsigned VTSize = VT.getSizeInBits() / 8;
5156 SDValue Value, Store;
5158 if (VTSize > Size) {
5159 // Issuing an unaligned load / store pair that overlaps with the previous
5160 // pair. Adjust the offset accordingly.
5161 assert(i == NumMemOps-1 && i != 0);
5162 SrcOff -= VTSize - Size;
5163 DstOff -= VTSize - Size;
5166 if (CopyFromConstant &&
5167 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
5168 // It's unlikely a store of a vector immediate can be done in a single
5169 // instruction. It would require a load from a constantpool first.
5170 // We only handle zero vectors here.
5171 // FIXME: Handle other cases where store of vector immediate is done in
5172 // a single instruction.
5173 ConstantDataArraySlice SubSlice;
5174 if (SrcOff < Slice.Length) {
5176 SubSlice.move(SrcOff);
5178 // This is an out-of-bounds access and hence UB. Pretend we read zero.
5179 SubSlice.Array = nullptr;
5180 SubSlice.Offset = 0;
5181 SubSlice.Length = VTSize;
5183 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
5184 if (Value.getNode())
5185 Store = DAG.getStore(Chain, dl, Value,
5186 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5187 DstPtrInfo.getWithOffset(DstOff), Align,
5191 if (!Store.getNode()) {
5192 // The type might not be legal for the target. This should only happen
5193 // if the type is smaller than a legal type, as on PPC, so the right
5194 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
5195 // to Load/Store if NVT==VT.
5196 // FIXME does the case above also need this?
5197 EVT NVT = TLI.getTypeToTransformTo(C, VT);
5198 assert(NVT.bitsGE(VT));
5200 bool isDereferenceable =
5201 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5202 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5203 if (isDereferenceable)
5204 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5206 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
5207 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5208 SrcPtrInfo.getWithOffset(SrcOff), VT,
5209 MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
5210 OutChains.push_back(Value.getValue(1));
5211 Store = DAG.getTruncStore(
5212 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5213 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5215 OutChains.push_back(Store);
5221 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5224 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5225 SDValue Chain, SDValue Dst, SDValue Src,
5226 uint64_t Size, unsigned Align,
5227 bool isVol, bool AlwaysInline,
5228 MachinePointerInfo DstPtrInfo,
5229 MachinePointerInfo SrcPtrInfo) {
5230 // Turn a memmove of undef to nop.
5234 // Expand memmove to a series of load and store ops if the size operand falls
5235 // below a certain threshold.
5236 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5237 const DataLayout &DL = DAG.getDataLayout();
5238 LLVMContext &C = *DAG.getContext();
5239 std::vector<EVT> MemOps;
5240 bool DstAlignCanChange = false;
5241 MachineFunction &MF = DAG.getMachineFunction();
5242 MachineFrameInfo &MFI = MF.getFrameInfo();
5243 bool OptSize = shouldLowerMemFuncForSize(MF);
5244 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5245 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5246 DstAlignCanChange = true;
5247 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5248 if (Align > SrcAlign)
5250 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5252 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5253 (DstAlignCanChange ? 0 : Align), SrcAlign,
5254 false, false, false, false,
5255 DstPtrInfo.getAddrSpace(),
5256 SrcPtrInfo.getAddrSpace(),
5260 if (DstAlignCanChange) {
5261 Type *Ty = MemOps[0].getTypeForEVT(C);
5262 unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5263 if (NewAlign > Align) {
5264 // Give the stack frame object a larger alignment if needed.
5265 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5266 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5271 MachineMemOperand::Flags MMOFlags =
5272 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5273 uint64_t SrcOff = 0, DstOff = 0;
5274 SmallVector<SDValue, 8> LoadValues;
5275 SmallVector<SDValue, 8> LoadChains;
5276 SmallVector<SDValue, 8> OutChains;
5277 unsigned NumMemOps = MemOps.size();
5278 for (unsigned i = 0; i < NumMemOps; i++) {
5280 unsigned VTSize = VT.getSizeInBits() / 8;
5283 bool isDereferenceable =
5284 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5285 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5286 if (isDereferenceable)
5287 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5290 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5291 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
5292 LoadValues.push_back(Value);
5293 LoadChains.push_back(Value.getValue(1));
5296 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5298 for (unsigned i = 0; i < NumMemOps; i++) {
5300 unsigned VTSize = VT.getSizeInBits() / 8;
5303 Store = DAG.getStore(Chain, dl, LoadValues[i],
5304 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5305 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5306 OutChains.push_back(Store);
5310 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5313 /// \brief Lower the call to 'memset' intrinsic function into a series of store
5316 /// \param DAG Selection DAG where lowered code is placed.
5317 /// \param dl Link to corresponding IR location.
5318 /// \param Chain Control flow dependency.
5319 /// \param Dst Pointer to destination memory location.
5320 /// \param Src Value of byte to write into the memory.
5321 /// \param Size Number of bytes to write.
5322 /// \param Align Alignment of the destination in bytes.
5323 /// \param isVol True if destination is volatile.
5324 /// \param DstPtrInfo IR information on the memory pointer.
5325 /// \returns New head in the control flow, if lowering was successful, empty
5326 /// SDValue otherwise.
5328 /// The function tries to replace 'llvm.memset' intrinsic with several store
5329 /// operations and value calculation code. This is usually profitable for small
5331 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5332 SDValue Chain, SDValue Dst, SDValue Src,
5333 uint64_t Size, unsigned Align, bool isVol,
5334 MachinePointerInfo DstPtrInfo) {
5335 // Turn a memset of undef to nop.
5339 // Expand memset to a series of load/store ops if the size operand
5340 // falls below a certain threshold.
5341 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5342 std::vector<EVT> MemOps;
5343 bool DstAlignCanChange = false;
5344 MachineFunction &MF = DAG.getMachineFunction();
5345 MachineFrameInfo &MFI = MF.getFrameInfo();
5346 bool OptSize = shouldLowerMemFuncForSize(MF);
5347 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5348 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5349 DstAlignCanChange = true;
5351 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5352 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5353 Size, (DstAlignCanChange ? 0 : Align), 0,
5354 true, IsZeroVal, false, true,
5355 DstPtrInfo.getAddrSpace(), ~0u,
5359 if (DstAlignCanChange) {
5360 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5361 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5362 if (NewAlign > Align) {
5363 // Give the stack frame object a larger alignment if needed.
5364 if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5365 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5370 SmallVector<SDValue, 8> OutChains;
5371 uint64_t DstOff = 0;
5372 unsigned NumMemOps = MemOps.size();
5374 // Find the largest store and generate the bit pattern for it.
5375 EVT LargestVT = MemOps[0];
5376 for (unsigned i = 1; i < NumMemOps; i++)
5377 if (MemOps[i].bitsGT(LargestVT))
5378 LargestVT = MemOps[i];
5379 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5381 for (unsigned i = 0; i < NumMemOps; i++) {
5383 unsigned VTSize = VT.getSizeInBits() / 8;
5384 if (VTSize > Size) {
5385 // Issuing an unaligned load / store pair that overlaps with the previous
5386 // pair. Adjust the offset accordingly.
5387 assert(i == NumMemOps-1 && i != 0);
5388 DstOff -= VTSize - Size;
5391 // If this store is smaller than the largest store see whether we can get
5392 // the smaller value for free with a truncate.
5393 SDValue Value = MemSetValue;
5394 if (VT.bitsLT(LargestVT)) {
5395 if (!LargestVT.isVector() && !VT.isVector() &&
5396 TLI.isTruncateFree(LargestVT, VT))
5397 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5399 Value = getMemsetValue(Src, VT, DAG, dl);
5401 assert(Value.getValueType() == VT && "Value with wrong type.");
5402 SDValue Store = DAG.getStore(
5403 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5404 DstPtrInfo.getWithOffset(DstOff), Align,
5405 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5406 OutChains.push_back(Store);
5407 DstOff += VT.getSizeInBits() / 8;
5411 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5414 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5416 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5417 // pointer operands can be losslessly bitcasted to pointers of address space 0
5418 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5419 report_fatal_error("cannot lower memory intrinsic in address space " +
5424 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
5425 SDValue Src, SDValue Size, unsigned Align,
5426 bool isVol, bool AlwaysInline, bool isTailCall,
5427 MachinePointerInfo DstPtrInfo,
5428 MachinePointerInfo SrcPtrInfo) {
5429 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5431 // Check to see if we should lower the memcpy to loads and stores first.
5432 // For cases within the target-specified limits, this is the best choice.
5433 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5435 // Memcpy with size zero? Just return the original chain.
5436 if (ConstantSize->isNullValue())
5439 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5440 ConstantSize->getZExtValue(),Align,
5441 isVol, false, DstPtrInfo, SrcPtrInfo);
5442 if (Result.getNode())
5446 // Then check to see if we should lower the memcpy with target-specific
5447 // code. If the target chooses to do this, this is the next best.
5449 SDValue Result = TSI->EmitTargetCodeForMemcpy(
5450 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
5451 DstPtrInfo, SrcPtrInfo);
5452 if (Result.getNode())
5456 // If we really need inline code and the target declined to provide it,
5457 // use a (potentially long) sequence of loads and stores.
5459 assert(ConstantSize && "AlwaysInline requires a constant size!");
5460 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
5461 ConstantSize->getZExtValue(), Align, isVol,
5462 true, DstPtrInfo, SrcPtrInfo);
5465 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5466 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5468 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
5469 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
5470 // respect volatile, so they may do things like read or write memory
5471 // beyond the given memory regions. But fixing this isn't easy, and most
5472 // people don't care.
5474 // Emit a library call.
5475 TargetLowering::ArgListTy Args;
5476 TargetLowering::ArgListEntry Entry;
5477 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5478 Entry.Node = Dst; Args.push_back(Entry);
5479 Entry.Node = Src; Args.push_back(Entry);
5480 Entry.Node = Size; Args.push_back(Entry);
5481 // FIXME: pass in SDLoc
5482 TargetLowering::CallLoweringInfo CLI(*this);
5485 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
5486 Dst.getValueType().getTypeForEVT(*getContext()),
5487 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
5488 TLI->getPointerTy(getDataLayout())),
5491 .setTailCall(isTailCall);
5493 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5494 return CallResult.second;
5497 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
5498 SDValue Src, SDValue Size, unsigned Align,
5499 bool isVol, bool isTailCall,
5500 MachinePointerInfo DstPtrInfo,
5501 MachinePointerInfo SrcPtrInfo) {
5502 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5504 // Check to see if we should lower the memmove to loads and stores first.
5505 // For cases within the target-specified limits, this is the best choice.
5506 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5508 // Memmove with size zero? Just return the original chain.
5509 if (ConstantSize->isNullValue())
5513 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
5514 ConstantSize->getZExtValue(), Align, isVol,
5515 false, DstPtrInfo, SrcPtrInfo);
5516 if (Result.getNode())
5520 // Then check to see if we should lower the memmove with target-specific
5521 // code. If the target chooses to do this, this is the next best.
5523 SDValue Result = TSI->EmitTargetCodeForMemmove(
5524 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
5525 if (Result.getNode())
5529 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5530 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
5532 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
5533 // not be safe. See memcpy above for more details.
5535 // Emit a library call.
5536 TargetLowering::ArgListTy Args;
5537 TargetLowering::ArgListEntry Entry;
5538 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
5539 Entry.Node = Dst; Args.push_back(Entry);
5540 Entry.Node = Src; Args.push_back(Entry);
5541 Entry.Node = Size; Args.push_back(Entry);
5542 // FIXME: pass in SDLoc
5543 TargetLowering::CallLoweringInfo CLI(*this);
5546 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
5547 Dst.getValueType().getTypeForEVT(*getContext()),
5548 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
5549 TLI->getPointerTy(getDataLayout())),
5552 .setTailCall(isTailCall);
5554 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5555 return CallResult.second;
5558 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
5559 SDValue Src, SDValue Size, unsigned Align,
5560 bool isVol, bool isTailCall,
5561 MachinePointerInfo DstPtrInfo) {
5562 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
5564 // Check to see if we should lower the memset to stores first.
5565 // For cases within the target-specified limits, this is the best choice.
5566 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5568 // Memset with size zero? Just return the original chain.
5569 if (ConstantSize->isNullValue())
5573 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
5574 Align, isVol, DstPtrInfo);
5576 if (Result.getNode())
5580 // Then check to see if we should lower the memset with target-specific
5581 // code. If the target chooses to do this, this is the next best.
5583 SDValue Result = TSI->EmitTargetCodeForMemset(
5584 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
5585 if (Result.getNode())
5589 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
5591 // Emit a library call.
5592 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
5593 TargetLowering::ArgListTy Args;
5594 TargetLowering::ArgListEntry Entry;
5595 Entry.Node = Dst; Entry.Ty = IntPtrTy;
5596 Args.push_back(Entry);
5598 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
5599 Args.push_back(Entry);
5601 Entry.Ty = IntPtrTy;
5602 Args.push_back(Entry);
5604 // FIXME: pass in SDLoc
5605 TargetLowering::CallLoweringInfo CLI(*this);
5608 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
5609 Dst.getValueType().getTypeForEVT(*getContext()),
5610 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
5611 TLI->getPointerTy(getDataLayout())),
5614 .setTailCall(isTailCall);
5616 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
5617 return CallResult.second;
5620 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5621 SDVTList VTList, ArrayRef<SDValue> Ops,
5622 MachineMemOperand *MMO) {
5623 FoldingSetNodeID ID;
5624 ID.AddInteger(MemVT.getRawBits());
5625 AddNodeIDNode(ID, Opcode, VTList, Ops);
5626 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5628 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5629 cast<AtomicSDNode>(E)->refineAlignment(MMO);
5630 return SDValue(E, 0);
5633 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5634 VTList, MemVT, MMO);
5635 createOperands(N, Ops);
5637 CSEMap.InsertNode(N, IP);
5639 return SDValue(N, 0);
5642 SDValue SelectionDAG::getAtomicCmpSwap(
5643 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
5644 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
5645 unsigned Alignment, AtomicOrdering SuccessOrdering,
5646 AtomicOrdering FailureOrdering, SyncScope::ID SSID) {
5647 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5648 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5649 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5651 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5652 Alignment = getEVTAlignment(MemVT);
5654 MachineFunction &MF = getMachineFunction();
5656 // FIXME: Volatile isn't really correct; we should keep track of atomic
5657 // orderings in the memoperand.
5658 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
5659 MachineMemOperand::MOStore;
5660 MachineMemOperand *MMO =
5661 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
5662 AAMDNodes(), nullptr, SSID, SuccessOrdering,
5665 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
5668 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
5669 EVT MemVT, SDVTList VTs, SDValue Chain,
5670 SDValue Ptr, SDValue Cmp, SDValue Swp,
5671 MachineMemOperand *MMO) {
5672 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
5673 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
5674 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
5676 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
5677 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5680 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5681 SDValue Chain, SDValue Ptr, SDValue Val,
5682 const Value *PtrVal, unsigned Alignment,
5683 AtomicOrdering Ordering,
5684 SyncScope::ID SSID) {
5685 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5686 Alignment = getEVTAlignment(MemVT);
5688 MachineFunction &MF = getMachineFunction();
5689 // An atomic store does not load. An atomic load does not store.
5690 // (An atomicrmw obviously both loads and stores.)
5691 // For now, atomics are considered to be volatile always, and they are
5693 // FIXME: Volatile isn't really correct; we should keep track of atomic
5694 // orderings in the memoperand.
5695 auto Flags = MachineMemOperand::MOVolatile;
5696 if (Opcode != ISD::ATOMIC_STORE)
5697 Flags |= MachineMemOperand::MOLoad;
5698 if (Opcode != ISD::ATOMIC_LOAD)
5699 Flags |= MachineMemOperand::MOStore;
5701 MachineMemOperand *MMO =
5702 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
5703 MemVT.getStoreSize(), Alignment, AAMDNodes(),
5704 nullptr, SSID, Ordering);
5706 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
5709 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5710 SDValue Chain, SDValue Ptr, SDValue Val,
5711 MachineMemOperand *MMO) {
5712 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
5713 Opcode == ISD::ATOMIC_LOAD_SUB ||
5714 Opcode == ISD::ATOMIC_LOAD_AND ||
5715 Opcode == ISD::ATOMIC_LOAD_OR ||
5716 Opcode == ISD::ATOMIC_LOAD_XOR ||
5717 Opcode == ISD::ATOMIC_LOAD_NAND ||
5718 Opcode == ISD::ATOMIC_LOAD_MIN ||
5719 Opcode == ISD::ATOMIC_LOAD_MAX ||
5720 Opcode == ISD::ATOMIC_LOAD_UMIN ||
5721 Opcode == ISD::ATOMIC_LOAD_UMAX ||
5722 Opcode == ISD::ATOMIC_SWAP ||
5723 Opcode == ISD::ATOMIC_STORE) &&
5724 "Invalid Atomic Op");
5726 EVT VT = Val.getValueType();
5728 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
5729 getVTList(VT, MVT::Other);
5730 SDValue Ops[] = {Chain, Ptr, Val};
5731 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5734 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
5735 EVT VT, SDValue Chain, SDValue Ptr,
5736 MachineMemOperand *MMO) {
5737 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
5739 SDVTList VTs = getVTList(VT, MVT::Other);
5740 SDValue Ops[] = {Chain, Ptr};
5741 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
5744 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
5745 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
5746 if (Ops.size() == 1)
5749 SmallVector<EVT, 4> VTs;
5750 VTs.reserve(Ops.size());
5751 for (unsigned i = 0; i < Ops.size(); ++i)
5752 VTs.push_back(Ops[i].getValueType());
5753 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
5756 SDValue SelectionDAG::getMemIntrinsicNode(
5757 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
5758 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
5759 bool ReadMem, bool WriteMem, unsigned Size) {
5760 if (Align == 0) // Ensure that codegen never sees alignment 0
5761 Align = getEVTAlignment(MemVT);
5763 MachineFunction &MF = getMachineFunction();
5764 auto Flags = MachineMemOperand::MONone;
5766 Flags |= MachineMemOperand::MOStore;
5768 Flags |= MachineMemOperand::MOLoad;
5770 Flags |= MachineMemOperand::MOVolatile;
5772 Size = MemVT.getStoreSize();
5773 MachineMemOperand *MMO =
5774 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
5776 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
5779 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
5781 ArrayRef<SDValue> Ops, EVT MemVT,
5782 MachineMemOperand *MMO) {
5783 assert((Opcode == ISD::INTRINSIC_VOID ||
5784 Opcode == ISD::INTRINSIC_W_CHAIN ||
5785 Opcode == ISD::PREFETCH ||
5786 Opcode == ISD::LIFETIME_START ||
5787 Opcode == ISD::LIFETIME_END ||
5788 ((int)Opcode <= std::numeric_limits<int>::max() &&
5789 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
5790 "Opcode is not a memory-accessing opcode!");
5792 // Memoize the node unless it returns a flag.
5793 MemIntrinsicSDNode *N;
5794 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5795 FoldingSetNodeID ID;
5796 AddNodeIDNode(ID, Opcode, VTList, Ops);
5797 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
5798 Opcode, dl.getIROrder(), VTList, MemVT, MMO));
5799 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5801 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5802 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
5803 return SDValue(E, 0);
5806 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5807 VTList, MemVT, MMO);
5808 createOperands(N, Ops);
5810 CSEMap.InsertNode(N, IP);
5812 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5813 VTList, MemVT, MMO);
5814 createOperands(N, Ops);
5817 return SDValue(N, 0);
5820 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5821 /// MachinePointerInfo record from it. This is particularly useful because the
5822 /// code generator has many cases where it doesn't bother passing in a
5823 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5824 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5825 int64_t Offset = 0) {
5826 // If this is FI+Offset, we can model it.
5827 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5828 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5829 FI->getIndex(), Offset);
5831 // If this is (FI+Offset1)+Offset2, we can model it.
5832 if (Ptr.getOpcode() != ISD::ADD ||
5833 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5834 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5835 return MachinePointerInfo();
5837 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5838 return MachinePointerInfo::getFixedStack(
5839 DAG.getMachineFunction(), FI,
5840 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5843 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5844 /// MachinePointerInfo record from it. This is particularly useful because the
5845 /// code generator has many cases where it doesn't bother passing in a
5846 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5847 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5849 // If the 'Offset' value isn't a constant, we can't handle this.
5850 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5851 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5852 if (OffsetOp.isUndef())
5853 return InferPointerInfo(DAG, Ptr);
5854 return MachinePointerInfo();
5857 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5858 EVT VT, const SDLoc &dl, SDValue Chain,
5859 SDValue Ptr, SDValue Offset,
5860 MachinePointerInfo PtrInfo, EVT MemVT,
5862 MachineMemOperand::Flags MMOFlags,
5863 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5864 assert(Chain.getValueType() == MVT::Other &&
5865 "Invalid chain type");
5866 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5867 Alignment = getEVTAlignment(MemVT);
5869 MMOFlags |= MachineMemOperand::MOLoad;
5870 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5871 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5873 if (PtrInfo.V.isNull())
5874 PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5876 MachineFunction &MF = getMachineFunction();
5877 MachineMemOperand *MMO = MF.getMachineMemOperand(
5878 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5879 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5882 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5883 EVT VT, const SDLoc &dl, SDValue Chain,
5884 SDValue Ptr, SDValue Offset, EVT MemVT,
5885 MachineMemOperand *MMO) {
5887 ExtType = ISD::NON_EXTLOAD;
5888 } else if (ExtType == ISD::NON_EXTLOAD) {
5889 assert(VT == MemVT && "Non-extending load from different memory type!");
5892 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5893 "Should only be an extending load, not truncating!");
5894 assert(VT.isInteger() == MemVT.isInteger() &&
5895 "Cannot convert from FP to Int or Int -> FP!");
5896 assert(VT.isVector() == MemVT.isVector() &&
5897 "Cannot use an ext load to convert to or from a vector!");
5898 assert((!VT.isVector() ||
5899 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5900 "Cannot use an ext load to change the number of vector elements!");
5903 bool Indexed = AM != ISD::UNINDEXED;
5904 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5906 SDVTList VTs = Indexed ?
5907 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5908 SDValue Ops[] = { Chain, Ptr, Offset };
5909 FoldingSetNodeID ID;
5910 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5911 ID.AddInteger(MemVT.getRawBits());
5912 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
5913 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
5914 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5916 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5917 cast<LoadSDNode>(E)->refineAlignment(MMO);
5918 return SDValue(E, 0);
5920 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5921 ExtType, MemVT, MMO);
5922 createOperands(N, Ops);
5924 CSEMap.InsertNode(N, IP);
5926 return SDValue(N, 0);
5929 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5930 SDValue Ptr, MachinePointerInfo PtrInfo,
5932 MachineMemOperand::Flags MMOFlags,
5933 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5934 SDValue Undef = getUNDEF(Ptr.getValueType());
5935 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5936 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5939 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5940 SDValue Ptr, MachineMemOperand *MMO) {
5941 SDValue Undef = getUNDEF(Ptr.getValueType());
5942 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5946 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5947 EVT VT, SDValue Chain, SDValue Ptr,
5948 MachinePointerInfo PtrInfo, EVT MemVT,
5950 MachineMemOperand::Flags MMOFlags,
5951 const AAMDNodes &AAInfo) {
5952 SDValue Undef = getUNDEF(Ptr.getValueType());
5953 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5954 MemVT, Alignment, MMOFlags, AAInfo);
5957 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5958 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5959 MachineMemOperand *MMO) {
5960 SDValue Undef = getUNDEF(Ptr.getValueType());
5961 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5965 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5966 SDValue Base, SDValue Offset,
5967 ISD::MemIndexedMode AM) {
5968 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5969 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5970 // Don't propagate the invariant or dereferenceable flags.
5972 LD->getMemOperand()->getFlags() &
5973 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
5974 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5975 LD->getChain(), Base, Offset, LD->getPointerInfo(),
5976 LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
5980 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5981 SDValue Ptr, MachinePointerInfo PtrInfo,
5983 MachineMemOperand::Flags MMOFlags,
5984 const AAMDNodes &AAInfo) {
5985 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5986 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5987 Alignment = getEVTAlignment(Val.getValueType());
5989 MMOFlags |= MachineMemOperand::MOStore;
5990 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5992 if (PtrInfo.V.isNull())
5993 PtrInfo = InferPointerInfo(*this, Ptr);
5995 MachineFunction &MF = getMachineFunction();
5996 MachineMemOperand *MMO = MF.getMachineMemOperand(
5997 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5998 return getStore(Chain, dl, Val, Ptr, MMO);
6001 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6002 SDValue Ptr, MachineMemOperand *MMO) {
6003 assert(Chain.getValueType() == MVT::Other &&
6004 "Invalid chain type");
6005 EVT VT = Val.getValueType();
6006 SDVTList VTs = getVTList(MVT::Other);
6007 SDValue Undef = getUNDEF(Ptr.getValueType());
6008 SDValue Ops[] = { Chain, Val, Ptr, Undef };
6009 FoldingSetNodeID ID;
6010 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6011 ID.AddInteger(VT.getRawBits());
6012 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6013 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
6014 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6016 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6017 cast<StoreSDNode>(E)->refineAlignment(MMO);
6018 return SDValue(E, 0);
6020 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6021 ISD::UNINDEXED, false, VT, MMO);
6022 createOperands(N, Ops);
6024 CSEMap.InsertNode(N, IP);
6026 return SDValue(N, 0);
6029 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6030 SDValue Ptr, MachinePointerInfo PtrInfo,
6031 EVT SVT, unsigned Alignment,
6032 MachineMemOperand::Flags MMOFlags,
6033 const AAMDNodes &AAInfo) {
6034 assert(Chain.getValueType() == MVT::Other &&
6035 "Invalid chain type");
6036 if (Alignment == 0) // Ensure that codegen never sees alignment 0
6037 Alignment = getEVTAlignment(SVT);
6039 MMOFlags |= MachineMemOperand::MOStore;
6040 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6042 if (PtrInfo.V.isNull())
6043 PtrInfo = InferPointerInfo(*this, Ptr);
6045 MachineFunction &MF = getMachineFunction();
6046 MachineMemOperand *MMO = MF.getMachineMemOperand(
6047 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
6048 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
6051 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6052 SDValue Ptr, EVT SVT,
6053 MachineMemOperand *MMO) {
6054 EVT VT = Val.getValueType();
6056 assert(Chain.getValueType() == MVT::Other &&
6057 "Invalid chain type");
6059 return getStore(Chain, dl, Val, Ptr, MMO);
6061 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
6062 "Should only be a truncating store, not extending!");
6063 assert(VT.isInteger() == SVT.isInteger() &&
6064 "Can't do FP-INT conversion!");
6065 assert(VT.isVector() == SVT.isVector() &&
6066 "Cannot use trunc store to convert to or from a vector!");
6067 assert((!VT.isVector() ||
6068 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
6069 "Cannot use trunc store to change the number of vector elements!");
6071 SDVTList VTs = getVTList(MVT::Other);
6072 SDValue Undef = getUNDEF(Ptr.getValueType());
6073 SDValue Ops[] = { Chain, Val, Ptr, Undef };
6074 FoldingSetNodeID ID;
6075 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6076 ID.AddInteger(SVT.getRawBits());
6077 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6078 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
6079 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6081 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6082 cast<StoreSDNode>(E)->refineAlignment(MMO);
6083 return SDValue(E, 0);
6085 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6086 ISD::UNINDEXED, true, SVT, MMO);
6087 createOperands(N, Ops);
6089 CSEMap.InsertNode(N, IP);
6091 return SDValue(N, 0);
6094 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
6095 SDValue Base, SDValue Offset,
6096 ISD::MemIndexedMode AM) {
6097 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
6098 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
6099 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
6100 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
6101 FoldingSetNodeID ID;
6102 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6103 ID.AddInteger(ST->getMemoryVT().getRawBits());
6104 ID.AddInteger(ST->getRawSubclassData());
6105 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
6107 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6108 return SDValue(E, 0);
6110 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6111 ST->isTruncatingStore(), ST->getMemoryVT(),
6112 ST->getMemOperand());
6113 createOperands(N, Ops);
6115 CSEMap.InsertNode(N, IP);
6117 return SDValue(N, 0);
6120 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6121 SDValue Ptr, SDValue Mask, SDValue Src0,
6122 EVT MemVT, MachineMemOperand *MMO,
6123 ISD::LoadExtType ExtTy, bool isExpanding) {
6124 SDVTList VTs = getVTList(VT, MVT::Other);
6125 SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
6126 FoldingSetNodeID ID;
6127 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
6128 ID.AddInteger(VT.getRawBits());
6129 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
6130 dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
6131 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6133 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6134 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
6135 return SDValue(E, 0);
6137 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6138 ExtTy, isExpanding, MemVT, MMO);
6139 createOperands(N, Ops);
6141 CSEMap.InsertNode(N, IP);
6143 return SDValue(N, 0);
6146 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
6147 SDValue Val, SDValue Ptr, SDValue Mask,
6148 EVT MemVT, MachineMemOperand *MMO,
6149 bool IsTruncating, bool IsCompressing) {
6150 assert(Chain.getValueType() == MVT::Other &&
6151 "Invalid chain type");
6152 EVT VT = Val.getValueType();
6153 SDVTList VTs = getVTList(MVT::Other);
6154 SDValue Ops[] = { Chain, Ptr, Mask, Val };
6155 FoldingSetNodeID ID;
6156 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
6157 ID.AddInteger(VT.getRawBits());
6158 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
6159 dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
6160 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6162 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6163 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
6164 return SDValue(E, 0);
6166 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6167 IsTruncating, IsCompressing, MemVT, MMO);
6168 createOperands(N, Ops);
6170 CSEMap.InsertNode(N, IP);
6172 return SDValue(N, 0);
6175 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
6176 ArrayRef<SDValue> Ops,
6177 MachineMemOperand *MMO) {
6178 assert(Ops.size() == 5 && "Incompatible number of operands");
6180 FoldingSetNodeID ID;
6181 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
6182 ID.AddInteger(VT.getRawBits());
6183 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
6184 dl.getIROrder(), VTs, VT, MMO));
6185 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6187 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6188 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
6189 return SDValue(E, 0);
6192 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6194 createOperands(N, Ops);
6196 assert(N->getValue().getValueType() == N->getValueType(0) &&
6197 "Incompatible type of the PassThru value in MaskedGatherSDNode");
6198 assert(N->getMask().getValueType().getVectorNumElements() ==
6199 N->getValueType(0).getVectorNumElements() &&
6200 "Vector width mismatch between mask and data");
6201 assert(N->getIndex().getValueType().getVectorNumElements() ==
6202 N->getValueType(0).getVectorNumElements() &&
6203 "Vector width mismatch between index and data");
6205 CSEMap.InsertNode(N, IP);
6207 return SDValue(N, 0);
6210 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
6211 ArrayRef<SDValue> Ops,
6212 MachineMemOperand *MMO) {
6213 assert(Ops.size() == 5 && "Incompatible number of operands");
6215 FoldingSetNodeID ID;
6216 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
6217 ID.AddInteger(VT.getRawBits());
6218 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
6219 dl.getIROrder(), VTs, VT, MMO));
6220 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6222 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6223 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
6224 return SDValue(E, 0);
6226 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6228 createOperands(N, Ops);
6230 assert(N->getMask().getValueType().getVectorNumElements() ==
6231 N->getValue().getValueType().getVectorNumElements() &&
6232 "Vector width mismatch between mask and data");
6233 assert(N->getIndex().getValueType().getVectorNumElements() ==
6234 N->getValue().getValueType().getVectorNumElements() &&
6235 "Vector width mismatch between index and data");
6237 CSEMap.InsertNode(N, IP);
6239 return SDValue(N, 0);
6242 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
6243 SDValue Ptr, SDValue SV, unsigned Align) {
6244 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
6245 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
6248 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6249 ArrayRef<SDUse> Ops) {
6250 switch (Ops.size()) {
6251 case 0: return getNode(Opcode, DL, VT);
6252 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
6253 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
6254 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6258 // Copy from an SDUse array into an SDValue array for use with
6259 // the regular getNode logic.
6260 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
6261 return getNode(Opcode, DL, VT, NewOps);
6264 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6265 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
6266 unsigned NumOps = Ops.size();
6268 case 0: return getNode(Opcode, DL, VT);
6269 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
6270 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
6271 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
6277 case ISD::CONCAT_VECTORS:
6278 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
6279 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
6282 case ISD::SELECT_CC:
6283 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
6284 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
6285 "LHS and RHS of condition must have same type!");
6286 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6287 "True and False arms of SelectCC must have same type!");
6288 assert(Ops[2].getValueType() == VT &&
6289 "select_cc node must be of same type as true and false value!");
6292 assert(NumOps == 5 && "BR_CC takes 5 operands!");
6293 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
6294 "LHS/RHS of comparison should match types!");
6300 SDVTList VTs = getVTList(VT);
6302 if (VT != MVT::Glue) {
6303 FoldingSetNodeID ID;
6304 AddNodeIDNode(ID, Opcode, VTs, Ops);
6307 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6308 return SDValue(E, 0);
6310 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6311 createOperands(N, Ops);
6313 CSEMap.InsertNode(N, IP);
6315 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6316 createOperands(N, Ops);
6320 return SDValue(N, 0);
6323 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6324 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
6325 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
6328 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6329 ArrayRef<SDValue> Ops) {
6330 if (VTList.NumVTs == 1)
6331 return getNode(Opcode, DL, VTList.VTs[0], Ops);
6335 // FIXME: figure out how to safely handle things like
6336 // int foo(int x) { return 1 << (x & 255); }
6337 // int bar() { return foo(256); }
6338 case ISD::SRA_PARTS:
6339 case ISD::SRL_PARTS:
6340 case ISD::SHL_PARTS:
6341 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6342 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
6343 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6344 else if (N3.getOpcode() == ISD::AND)
6345 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
6346 // If the and is only masking out bits that cannot effect the shift,
6347 // eliminate the and.
6348 unsigned NumBits = VT.getScalarSizeInBits()*2;
6349 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
6350 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
6356 // Memoize the node unless it returns a flag.
6358 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6359 FoldingSetNodeID ID;
6360 AddNodeIDNode(ID, Opcode, VTList, Ops);
6362 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
6363 return SDValue(E, 0);
6365 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6366 createOperands(N, Ops);
6367 CSEMap.InsertNode(N, IP);
6369 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
6370 createOperands(N, Ops);
6373 return SDValue(N, 0);
6376 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
6378 return getNode(Opcode, DL, VTList, None);
6381 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6383 SDValue Ops[] = { N1 };
6384 return getNode(Opcode, DL, VTList, Ops);
6387 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6388 SDValue N1, SDValue N2) {
6389 SDValue Ops[] = { N1, N2 };
6390 return getNode(Opcode, DL, VTList, Ops);
6393 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6394 SDValue N1, SDValue N2, SDValue N3) {
6395 SDValue Ops[] = { N1, N2, N3 };
6396 return getNode(Opcode, DL, VTList, Ops);
6399 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6400 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6401 SDValue Ops[] = { N1, N2, N3, N4 };
6402 return getNode(Opcode, DL, VTList, Ops);
6405 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
6406 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6408 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6409 return getNode(Opcode, DL, VTList, Ops);
6412 SDVTList SelectionDAG::getVTList(EVT VT) {
6413 return makeVTList(SDNode::getValueTypeList(VT), 1);
6416 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
6417 FoldingSetNodeID ID;
6419 ID.AddInteger(VT1.getRawBits());
6420 ID.AddInteger(VT2.getRawBits());
6423 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6425 EVT *Array = Allocator.Allocate<EVT>(2);
6428 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
6429 VTListMap.InsertNode(Result, IP);
6431 return Result->getSDVTList();
6434 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
6435 FoldingSetNodeID ID;
6437 ID.AddInteger(VT1.getRawBits());
6438 ID.AddInteger(VT2.getRawBits());
6439 ID.AddInteger(VT3.getRawBits());
6442 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6444 EVT *Array = Allocator.Allocate<EVT>(3);
6448 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
6449 VTListMap.InsertNode(Result, IP);
6451 return Result->getSDVTList();
6454 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
6455 FoldingSetNodeID ID;
6457 ID.AddInteger(VT1.getRawBits());
6458 ID.AddInteger(VT2.getRawBits());
6459 ID.AddInteger(VT3.getRawBits());
6460 ID.AddInteger(VT4.getRawBits());
6463 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6465 EVT *Array = Allocator.Allocate<EVT>(4);
6470 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
6471 VTListMap.InsertNode(Result, IP);
6473 return Result->getSDVTList();
6476 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
6477 unsigned NumVTs = VTs.size();
6478 FoldingSetNodeID ID;
6479 ID.AddInteger(NumVTs);
6480 for (unsigned index = 0; index < NumVTs; index++) {
6481 ID.AddInteger(VTs[index].getRawBits());
6485 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
6487 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
6488 std::copy(VTs.begin(), VTs.end(), Array);
6489 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
6490 VTListMap.InsertNode(Result, IP);
6492 return Result->getSDVTList();
6496 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
6497 /// specified operands. If the resultant node already exists in the DAG,
6498 /// this does not modify the specified node, instead it returns the node that
6499 /// already exists. If the resultant node does not exist in the DAG, the
6500 /// input node is returned. As a degenerate case, if you specify the same
6501 /// input operands as the node already has, the input node is returned.
6502 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
6503 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
6505 // Check to see if there is no change.
6506 if (Op == N->getOperand(0)) return N;
6508 // See if the modified node already exists.
6509 void *InsertPos = nullptr;
6510 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
6513 // Nope it doesn't. Remove the node from its current place in the maps.
6515 if (!RemoveNodeFromCSEMaps(N))
6516 InsertPos = nullptr;
6518 // Now we update the operands.
6519 N->OperandList[0].set(Op);
6521 // If this gets put into a CSE map, add it.
6522 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6526 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
6527 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
6529 // Check to see if there is no change.
6530 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
6531 return N; // No operands changed, just return the input node.
6533 // See if the modified node already exists.
6534 void *InsertPos = nullptr;
6535 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
6538 // Nope it doesn't. Remove the node from its current place in the maps.
6540 if (!RemoveNodeFromCSEMaps(N))
6541 InsertPos = nullptr;
6543 // Now we update the operands.
6544 if (N->OperandList[0] != Op1)
6545 N->OperandList[0].set(Op1);
6546 if (N->OperandList[1] != Op2)
6547 N->OperandList[1].set(Op2);
6549 // If this gets put into a CSE map, add it.
6550 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6554 SDNode *SelectionDAG::
6555 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
6556 SDValue Ops[] = { Op1, Op2, Op3 };
6557 return UpdateNodeOperands(N, Ops);
6560 SDNode *SelectionDAG::
6561 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6562 SDValue Op3, SDValue Op4) {
6563 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
6564 return UpdateNodeOperands(N, Ops);
6567 SDNode *SelectionDAG::
6568 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
6569 SDValue Op3, SDValue Op4, SDValue Op5) {
6570 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
6571 return UpdateNodeOperands(N, Ops);
6574 SDNode *SelectionDAG::
6575 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
6576 unsigned NumOps = Ops.size();
6577 assert(N->getNumOperands() == NumOps &&
6578 "Update with wrong number of operands");
6580 // If no operands changed just return the input node.
6581 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
6584 // See if the modified node already exists.
6585 void *InsertPos = nullptr;
6586 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
6589 // Nope it doesn't. Remove the node from its current place in the maps.
6591 if (!RemoveNodeFromCSEMaps(N))
6592 InsertPos = nullptr;
6594 // Now we update the operands.
6595 for (unsigned i = 0; i != NumOps; ++i)
6596 if (N->OperandList[i] != Ops[i])
6597 N->OperandList[i].set(Ops[i]);
6599 // If this gets put into a CSE map, add it.
6600 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
6604 /// DropOperands - Release the operands and set this node to have
6606 void SDNode::DropOperands() {
6607 // Unlike the code in MorphNodeTo that does this, we don't need to
6608 // watch for dead nodes here.
6609 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
6615 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
6618 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6620 SDVTList VTs = getVTList(VT);
6621 return SelectNodeTo(N, MachineOpc, VTs, None);
6624 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6625 EVT VT, SDValue Op1) {
6626 SDVTList VTs = getVTList(VT);
6627 SDValue Ops[] = { Op1 };
6628 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6631 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6632 EVT VT, SDValue Op1,
6634 SDVTList VTs = getVTList(VT);
6635 SDValue Ops[] = { Op1, Op2 };
6636 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6639 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6640 EVT VT, SDValue Op1,
6641 SDValue Op2, SDValue Op3) {
6642 SDVTList VTs = getVTList(VT);
6643 SDValue Ops[] = { Op1, Op2, Op3 };
6644 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6647 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6648 EVT VT, ArrayRef<SDValue> Ops) {
6649 SDVTList VTs = getVTList(VT);
6650 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6653 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6654 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
6655 SDVTList VTs = getVTList(VT1, VT2);
6656 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6659 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6661 SDVTList VTs = getVTList(VT1, VT2);
6662 return SelectNodeTo(N, MachineOpc, VTs, None);
6665 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6666 EVT VT1, EVT VT2, EVT VT3,
6667 ArrayRef<SDValue> Ops) {
6668 SDVTList VTs = getVTList(VT1, VT2, VT3);
6669 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6672 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6674 SDValue Op1, SDValue Op2) {
6675 SDVTList VTs = getVTList(VT1, VT2);
6676 SDValue Ops[] = { Op1, Op2 };
6677 return SelectNodeTo(N, MachineOpc, VTs, Ops);
6680 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
6681 SDVTList VTs,ArrayRef<SDValue> Ops) {
6682 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
6683 // Reset the NodeID to -1.
6686 ReplaceAllUsesWith(N, New);
6692 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
6693 /// the line number information on the merged node since it is not possible to
6694 /// preserve the information that operation is associated with multiple lines.
6695 /// This will make the debugger working better at -O0, were there is a higher
6696 /// probability having other instructions associated with that line.
6698 /// For IROrder, we keep the smaller of the two
6699 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
6700 DebugLoc NLoc = N->getDebugLoc();
6701 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
6702 N->setDebugLoc(DebugLoc());
6704 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
6705 N->setIROrder(Order);
6709 /// MorphNodeTo - This *mutates* the specified node to have the specified
6710 /// return type, opcode, and operands.
6712 /// Note that MorphNodeTo returns the resultant node. If there is already a
6713 /// node of the specified opcode and operands, it returns that node instead of
6714 /// the current one. Note that the SDLoc need not be the same.
6716 /// Using MorphNodeTo is faster than creating a new node and swapping it in
6717 /// with ReplaceAllUsesWith both because it often avoids allocating a new
6718 /// node, and because it doesn't require CSE recalculation for any of
6719 /// the node's users.
6721 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
6722 /// As a consequence it isn't appropriate to use from within the DAG combiner or
6723 /// the legalizer which maintain worklists that would need to be updated when
6724 /// deleting things.
6725 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
6726 SDVTList VTs, ArrayRef<SDValue> Ops) {
6727 // If an identical node already exists, use it.
6729 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
6730 FoldingSetNodeID ID;
6731 AddNodeIDNode(ID, Opc, VTs, Ops);
6732 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
6733 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
6736 if (!RemoveNodeFromCSEMaps(N))
6739 // Start the morphing.
6741 N->ValueList = VTs.VTs;
6742 N->NumValues = VTs.NumVTs;
6744 // Clear the operands list, updating used nodes to remove this from their
6745 // use list. Keep track of any operands that become dead as a result.
6746 SmallPtrSet<SDNode*, 16> DeadNodeSet;
6747 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
6749 SDNode *Used = Use.getNode();
6751 if (Used->use_empty())
6752 DeadNodeSet.insert(Used);
6755 // For MachineNode, initialize the memory references information.
6756 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
6757 MN->setMemRefs(nullptr, nullptr);
6759 // Swap for an appropriately sized array from the recycler.
6761 createOperands(N, Ops);
6763 // Delete any nodes that are still dead after adding the uses for the
6765 if (!DeadNodeSet.empty()) {
6766 SmallVector<SDNode *, 16> DeadNodes;
6767 for (SDNode *N : DeadNodeSet)
6769 DeadNodes.push_back(N);
6770 RemoveDeadNodes(DeadNodes);
6774 CSEMap.InsertNode(N, IP); // Memoize the new node.
6778 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
6779 unsigned OrigOpc = Node->getOpcode();
6781 bool IsUnary = false;
6782 bool IsTernary = false;
6785 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
6786 case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
6787 case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
6788 case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
6789 case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
6790 case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
6791 case ISD::STRICT_FMA: NewOpc = ISD::FMA; IsTernary = true; break;
6792 case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break;
6793 case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
6794 case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
6795 case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break;
6796 case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break;
6797 case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break;
6798 case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break;
6799 case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break;
6800 case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break;
6801 case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break;
6802 case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break;
6803 case ISD::STRICT_FNEARBYINT:
6804 NewOpc = ISD::FNEARBYINT;
6809 // We're taking this node out of the chain, so we need to re-link things.
6810 SDValue InputChain = Node->getOperand(0);
6811 SDValue OutputChain = SDValue(Node, 1);
6812 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
6814 SDVTList VTs = getVTList(Node->getOperand(1).getValueType());
6815 SDNode *Res = nullptr;
6817 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) });
6819 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
6820 Node->getOperand(2),
6821 Node->getOperand(3)});
6823 Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
6824 Node->getOperand(2) });
6826 // MorphNodeTo can operate in two ways: if an existing node with the
6827 // specified operands exists, it can just return it. Otherwise, it
6828 // updates the node in place to have the requested operands.
6830 // If we updated the node in place, reset the node ID. To the isel,
6831 // this should be just like a newly allocated machine node.
6834 ReplaceAllUsesWith(Node, Res);
6835 RemoveDeadNode(Node);
6841 /// getMachineNode - These are used for target selectors to create a new node
6842 /// with specified return type(s), MachineInstr opcode, and operands.
6844 /// Note that getMachineNode returns the resultant node. If there is already a
6845 /// node of the specified opcode and operands, it returns that node instead of
6846 /// the current one.
6847 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6849 SDVTList VTs = getVTList(VT);
6850 return getMachineNode(Opcode, dl, VTs, None);
6853 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6854 EVT VT, SDValue Op1) {
6855 SDVTList VTs = getVTList(VT);
6856 SDValue Ops[] = { Op1 };
6857 return getMachineNode(Opcode, dl, VTs, Ops);
6860 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6861 EVT VT, SDValue Op1, SDValue Op2) {
6862 SDVTList VTs = getVTList(VT);
6863 SDValue Ops[] = { Op1, Op2 };
6864 return getMachineNode(Opcode, dl, VTs, Ops);
6867 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6868 EVT VT, SDValue Op1, SDValue Op2,
6870 SDVTList VTs = getVTList(VT);
6871 SDValue Ops[] = { Op1, Op2, Op3 };
6872 return getMachineNode(Opcode, dl, VTs, Ops);
6875 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6876 EVT VT, ArrayRef<SDValue> Ops) {
6877 SDVTList VTs = getVTList(VT);
6878 return getMachineNode(Opcode, dl, VTs, Ops);
6881 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6882 EVT VT1, EVT VT2, SDValue Op1,
6884 SDVTList VTs = getVTList(VT1, VT2);
6885 SDValue Ops[] = { Op1, Op2 };
6886 return getMachineNode(Opcode, dl, VTs, Ops);
6889 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6890 EVT VT1, EVT VT2, SDValue Op1,
6891 SDValue Op2, SDValue Op3) {
6892 SDVTList VTs = getVTList(VT1, VT2);
6893 SDValue Ops[] = { Op1, Op2, Op3 };
6894 return getMachineNode(Opcode, dl, VTs, Ops);
6897 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6899 ArrayRef<SDValue> Ops) {
6900 SDVTList VTs = getVTList(VT1, VT2);
6901 return getMachineNode(Opcode, dl, VTs, Ops);
6904 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6905 EVT VT1, EVT VT2, EVT VT3,
6906 SDValue Op1, SDValue Op2) {
6907 SDVTList VTs = getVTList(VT1, VT2, VT3);
6908 SDValue Ops[] = { Op1, Op2 };
6909 return getMachineNode(Opcode, dl, VTs, Ops);
6912 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6913 EVT VT1, EVT VT2, EVT VT3,
6914 SDValue Op1, SDValue Op2,
6916 SDVTList VTs = getVTList(VT1, VT2, VT3);
6917 SDValue Ops[] = { Op1, Op2, Op3 };
6918 return getMachineNode(Opcode, dl, VTs, Ops);
6921 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6922 EVT VT1, EVT VT2, EVT VT3,
6923 ArrayRef<SDValue> Ops) {
6924 SDVTList VTs = getVTList(VT1, VT2, VT3);
6925 return getMachineNode(Opcode, dl, VTs, Ops);
6928 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6929 ArrayRef<EVT> ResultTys,
6930 ArrayRef<SDValue> Ops) {
6931 SDVTList VTs = getVTList(ResultTys);
6932 return getMachineNode(Opcode, dl, VTs, Ops);
6935 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6937 ArrayRef<SDValue> Ops) {
6938 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6943 FoldingSetNodeID ID;
6944 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6946 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6947 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
6951 // Allocate a new MachineSDNode.
6952 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6953 createOperands(N, Ops);
6956 CSEMap.InsertNode(N, IP);
6962 /// getTargetExtractSubreg - A convenience function for creating
6963 /// TargetOpcode::EXTRACT_SUBREG nodes.
6964 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6966 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6967 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6968 VT, Operand, SRIdxVal);
6969 return SDValue(Subreg, 0);
6972 /// getTargetInsertSubreg - A convenience function for creating
6973 /// TargetOpcode::INSERT_SUBREG nodes.
6974 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6975 SDValue Operand, SDValue Subreg) {
6976 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6977 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6978 VT, Operand, Subreg, SRIdxVal);
6979 return SDValue(Result, 0);
6982 /// getNodeIfExists - Get the specified node if it's already available, or
6983 /// else return NULL.
6984 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6985 ArrayRef<SDValue> Ops,
6986 const SDNodeFlags Flags) {
6987 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6988 FoldingSetNodeID ID;
6989 AddNodeIDNode(ID, Opcode, VTList, Ops);
6991 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6992 E->intersectFlagsWith(Flags);
6999 /// getDbgValue - Creates a SDDbgValue node.
7002 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
7003 SDNode *N, unsigned R, bool IsIndirect,
7004 const DebugLoc &DL, unsigned O) {
7005 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7006 "Expected inlined-at fields to agree");
7007 return new (DbgInfo->getAlloc())
7008 SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
7012 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
7015 const DebugLoc &DL, unsigned O) {
7016 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7017 "Expected inlined-at fields to agree");
7018 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
7022 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
7023 DIExpression *Expr, unsigned FI,
7026 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7027 "Expected inlined-at fields to agree");
7028 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, DL, O);
7031 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
7032 unsigned OffsetInBits, unsigned SizeInBits,
7033 bool InvalidateDbg) {
7034 SDNode *FromNode = From.getNode();
7035 SDNode *ToNode = To.getNode();
7036 assert(FromNode && ToNode && "Can't modify dbg values");
7039 // TODO: assert(From != To && "Redundant dbg value transfer");
7040 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
7041 if (From == To || FromNode == ToNode)
7044 if (!FromNode->getHasDebugValue())
7047 SmallVector<SDDbgValue *, 2> ClonedDVs;
7048 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
7049 if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
7052 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
7054 // Just transfer the dbg value attached to From.
7055 if (Dbg->getResNo() != From.getResNo())
7058 DIVariable *Var = Dbg->getVariable();
7059 auto *Expr = Dbg->getExpression();
7060 // If a fragment is requested, update the expression.
7062 // When splitting a larger (e.g., sign-extended) value whose
7063 // lower bits are described with an SDDbgValue, do not attempt
7064 // to transfer the SDDbgValue to the upper bits.
7065 if (auto FI = Expr->getFragmentInfo())
7066 if (OffsetInBits + SizeInBits > FI->SizeInBits)
7068 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
7074 // Clone the SDDbgValue and move it to To.
7076 getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(),
7077 Dbg->getDebugLoc(), Dbg->getOrder());
7078 ClonedDVs.push_back(Clone);
7081 Dbg->setIsInvalidated();
7084 for (SDDbgValue *Dbg : ClonedDVs)
7085 AddDbgValue(Dbg, ToNode, false);
7088 void SelectionDAG::salvageDebugInfo(SDNode &N) {
7089 if (!N.getHasDebugValue())
7091 for (auto DV : GetDbgValues(&N)) {
7092 if (DV->isInvalidated())
7094 switch (N.getOpcode()) {
7098 SDValue N0 = N.getOperand(0);
7099 SDValue N1 = N.getOperand(1);
7100 if (!isConstantIntBuildVectorOrConstantInt(N0) &&
7101 isConstantIntBuildVectorOrConstantInt(N1)) {
7102 uint64_t Offset = N.getConstantOperandVal(1);
7103 // Rewrite an ADD constant node into a DIExpression. Since we are
7104 // performing arithmetic to compute the variable's *value* in the
7105 // DIExpression, we need to mark the expression with a
7106 // DW_OP_stack_value.
7107 auto *DIExpr = DV->getExpression();
7108 DIExpr = DIExpression::prepend(DIExpr, DIExpression::NoDeref, Offset,
7109 DIExpression::WithStackValue);
7111 getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
7112 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
7113 DV->setIsInvalidated();
7114 AddDbgValue(Clone, N0.getNode(), false);
7115 DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
7116 dbgs() << " into " << *DIExpr << '\n');
7124 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
7125 /// pointed to by a use iterator is deleted, increment the use iterator
7126 /// so that it doesn't dangle.
7128 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
7129 SDNode::use_iterator &UI;
7130 SDNode::use_iterator &UE;
7132 void NodeDeleted(SDNode *N, SDNode *E) override {
7133 // Increment the iterator as needed.
7134 while (UI != UE && N == *UI)
7139 RAUWUpdateListener(SelectionDAG &d,
7140 SDNode::use_iterator &ui,
7141 SDNode::use_iterator &ue)
7142 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
7145 } // end anonymous namespace
7147 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
7148 /// This can cause recursive merging of nodes in the DAG.
7150 /// This version assumes From has a single result value.
7152 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
7153 SDNode *From = FromN.getNode();
7154 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
7155 "Cannot replace with this method!");
7156 assert(From != To.getNode() && "Cannot replace uses of with self");
7158 // Preserve Debug Values
7159 transferDbgValues(FromN, To);
7161 // Iterate over all the existing uses of From. New uses will be added
7162 // to the beginning of the use list, which we avoid visiting.
7163 // This specifically avoids visiting uses of From that arise while the
7164 // replacement is happening, because any such uses would be the result
7165 // of CSE: If an existing node looks like From after one of its operands
7166 // is replaced by To, we don't want to replace of all its users with To
7167 // too. See PR3018 for more info.
7168 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
7169 RAUWUpdateListener Listener(*this, UI, UE);
7173 // This node is about to morph, remove its old self from the CSE maps.
7174 RemoveNodeFromCSEMaps(User);
7176 // A user can appear in a use list multiple times, and when this
7177 // happens the uses are usually next to each other in the list.
7178 // To help reduce the number of CSE recomputations, process all
7179 // the uses of this user that we can find this way.
7181 SDUse &Use = UI.getUse();
7184 } while (UI != UE && *UI == User);
7186 // Now that we have modified User, add it back to the CSE maps. If it
7187 // already exists there, recursively merge the results together.
7188 AddModifiedNodeToCSEMaps(User);
7191 // If we just RAUW'd the root, take note.
7192 if (FromN == getRoot())
7196 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
7197 /// This can cause recursive merging of nodes in the DAG.
7199 /// This version assumes that for each value of From, there is a
7200 /// corresponding value in To in the same position with the same type.
7202 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
7204 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
7205 assert((!From->hasAnyUseOfValue(i) ||
7206 From->getValueType(i) == To->getValueType(i)) &&
7207 "Cannot use this version of ReplaceAllUsesWith!");
7210 // Handle the trivial case.
7214 // Preserve Debug Info. Only do this if there's a use.
7215 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
7216 if (From->hasAnyUseOfValue(i)) {
7217 assert((i < To->getNumValues()) && "Invalid To location");
7218 transferDbgValues(SDValue(From, i), SDValue(To, i));
7221 // Iterate over just the existing users of From. See the comments in
7222 // the ReplaceAllUsesWith above.
7223 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
7224 RAUWUpdateListener Listener(*this, UI, UE);
7228 // This node is about to morph, remove its old self from the CSE maps.
7229 RemoveNodeFromCSEMaps(User);
7231 // A user can appear in a use list multiple times, and when this
7232 // happens the uses are usually next to each other in the list.
7233 // To help reduce the number of CSE recomputations, process all
7234 // the uses of this user that we can find this way.
7236 SDUse &Use = UI.getUse();
7239 } while (UI != UE && *UI == User);
7241 // Now that we have modified User, add it back to the CSE maps. If it
7242 // already exists there, recursively merge the results together.
7243 AddModifiedNodeToCSEMaps(User);
7246 // If we just RAUW'd the root, take note.
7247 if (From == getRoot().getNode())
7248 setRoot(SDValue(To, getRoot().getResNo()));
7251 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
7252 /// This can cause recursive merging of nodes in the DAG.
7254 /// This version can replace From with any result values. To must match the
7255 /// number and types of values returned by From.
7256 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
7257 if (From->getNumValues() == 1) // Handle the simple case efficiently.
7258 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
7260 // Preserve Debug Info.
7261 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
7262 transferDbgValues(SDValue(From, i), *To);
7264 // Iterate over just the existing users of From. See the comments in
7265 // the ReplaceAllUsesWith above.
7266 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
7267 RAUWUpdateListener Listener(*this, UI, UE);
7271 // This node is about to morph, remove its old self from the CSE maps.
7272 RemoveNodeFromCSEMaps(User);
7274 // A user can appear in a use list multiple times, and when this
7275 // happens the uses are usually next to each other in the list.
7276 // To help reduce the number of CSE recomputations, process all
7277 // the uses of this user that we can find this way.
7279 SDUse &Use = UI.getUse();
7280 const SDValue &ToOp = To[Use.getResNo()];
7283 } while (UI != UE && *UI == User);
7285 // Now that we have modified User, add it back to the CSE maps. If it
7286 // already exists there, recursively merge the results together.
7287 AddModifiedNodeToCSEMaps(User);
7290 // If we just RAUW'd the root, take note.
7291 if (From == getRoot().getNode())
7292 setRoot(SDValue(To[getRoot().getResNo()]));
7295 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
7296 /// uses of other values produced by From.getNode() alone. The Deleted
7297 /// vector is handled the same way as for ReplaceAllUsesWith.
7298 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
7299 // Handle the really simple, really trivial case efficiently.
7300 if (From == To) return;
7302 // Handle the simple, trivial, case efficiently.
7303 if (From.getNode()->getNumValues() == 1) {
7304 ReplaceAllUsesWith(From, To);
7308 // Preserve Debug Info.
7309 transferDbgValues(From, To);
7311 // Iterate over just the existing users of From. See the comments in
7312 // the ReplaceAllUsesWith above.
7313 SDNode::use_iterator UI = From.getNode()->use_begin(),
7314 UE = From.getNode()->use_end();
7315 RAUWUpdateListener Listener(*this, UI, UE);
7318 bool UserRemovedFromCSEMaps = false;
7320 // A user can appear in a use list multiple times, and when this
7321 // happens the uses are usually next to each other in the list.
7322 // To help reduce the number of CSE recomputations, process all
7323 // the uses of this user that we can find this way.
7325 SDUse &Use = UI.getUse();
7327 // Skip uses of different values from the same node.
7328 if (Use.getResNo() != From.getResNo()) {
7333 // If this node hasn't been modified yet, it's still in the CSE maps,
7334 // so remove its old self from the CSE maps.
7335 if (!UserRemovedFromCSEMaps) {
7336 RemoveNodeFromCSEMaps(User);
7337 UserRemovedFromCSEMaps = true;
7342 } while (UI != UE && *UI == User);
7344 // We are iterating over all uses of the From node, so if a use
7345 // doesn't use the specific value, no changes are made.
7346 if (!UserRemovedFromCSEMaps)
7349 // Now that we have modified User, add it back to the CSE maps. If it
7350 // already exists there, recursively merge the results together.
7351 AddModifiedNodeToCSEMaps(User);
7354 // If we just RAUW'd the root, take note.
7355 if (From == getRoot())
7361 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
7362 /// to record information about a use.
7369 /// operator< - Sort Memos by User.
7370 bool operator<(const UseMemo &L, const UseMemo &R) {
7371 return (intptr_t)L.User < (intptr_t)R.User;
7374 } // end anonymous namespace
7376 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
7377 /// uses of other values produced by From.getNode() alone. The same value
7378 /// may appear in both the From and To list. The Deleted vector is
7379 /// handled the same way as for ReplaceAllUsesWith.
7380 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
7383 // Handle the simple, trivial case efficiently.
7385 return ReplaceAllUsesOfValueWith(*From, *To);
7387 transferDbgValues(*From, *To);
7389 // Read up all the uses and make records of them. This helps
7390 // processing new uses that are introduced during the
7391 // replacement process.
7392 SmallVector<UseMemo, 4> Uses;
7393 for (unsigned i = 0; i != Num; ++i) {
7394 unsigned FromResNo = From[i].getResNo();
7395 SDNode *FromNode = From[i].getNode();
7396 for (SDNode::use_iterator UI = FromNode->use_begin(),
7397 E = FromNode->use_end(); UI != E; ++UI) {
7398 SDUse &Use = UI.getUse();
7399 if (Use.getResNo() == FromResNo) {
7400 UseMemo Memo = { *UI, i, &Use };
7401 Uses.push_back(Memo);
7406 // Sort the uses, so that all the uses from a given User are together.
7407 std::sort(Uses.begin(), Uses.end());
7409 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
7410 UseIndex != UseIndexEnd; ) {
7411 // We know that this user uses some value of From. If it is the right
7412 // value, update it.
7413 SDNode *User = Uses[UseIndex].User;
7415 // This node is about to morph, remove its old self from the CSE maps.
7416 RemoveNodeFromCSEMaps(User);
7418 // The Uses array is sorted, so all the uses for a given User
7419 // are next to each other in the list.
7420 // To help reduce the number of CSE recomputations, process all
7421 // the uses of this user that we can find this way.
7423 unsigned i = Uses[UseIndex].Index;
7424 SDUse &Use = *Uses[UseIndex].Use;
7428 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
7430 // Now that we have modified User, add it back to the CSE maps. If it
7431 // already exists there, recursively merge the results together.
7432 AddModifiedNodeToCSEMaps(User);
7436 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
7437 /// based on their topological order. It returns the maximum id and a vector
7438 /// of the SDNodes* in assigned order by reference.
7439 unsigned SelectionDAG::AssignTopologicalOrder() {
7440 unsigned DAGSize = 0;
7442 // SortedPos tracks the progress of the algorithm. Nodes before it are
7443 // sorted, nodes after it are unsorted. When the algorithm completes
7444 // it is at the end of the list.
7445 allnodes_iterator SortedPos = allnodes_begin();
7447 // Visit all the nodes. Move nodes with no operands to the front of
7448 // the list immediately. Annotate nodes that do have operands with their
7449 // operand count. Before we do this, the Node Id fields of the nodes
7450 // may contain arbitrary values. After, the Node Id fields for nodes
7451 // before SortedPos will contain the topological sort index, and the
7452 // Node Id fields for nodes At SortedPos and after will contain the
7453 // count of outstanding operands.
7454 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
7456 checkForCycles(N, this);
7457 unsigned Degree = N->getNumOperands();
7459 // A node with no uses, add it to the result array immediately.
7460 N->setNodeId(DAGSize++);
7461 allnodes_iterator Q(N);
7463 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
7464 assert(SortedPos != AllNodes.end() && "Overran node list");
7467 // Temporarily use the Node Id as scratch space for the degree count.
7468 N->setNodeId(Degree);
7472 // Visit all the nodes. As we iterate, move nodes into sorted order,
7473 // such that by the time the end is reached all nodes will be sorted.
7474 for (SDNode &Node : allnodes()) {
7476 checkForCycles(N, this);
7477 // N is in sorted position, so all its uses have one less operand
7478 // that needs to be sorted.
7479 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7482 unsigned Degree = P->getNodeId();
7483 assert(Degree != 0 && "Invalid node degree");
7486 // All of P's operands are sorted, so P may sorted now.
7487 P->setNodeId(DAGSize++);
7488 if (P->getIterator() != SortedPos)
7489 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
7490 assert(SortedPos != AllNodes.end() && "Overran node list");
7493 // Update P's outstanding operand count.
7494 P->setNodeId(Degree);
7497 if (Node.getIterator() == SortedPos) {
7499 allnodes_iterator I(N);
7501 dbgs() << "Overran sorted position:\n";
7502 S->dumprFull(this); dbgs() << "\n";
7503 dbgs() << "Checking if this is due to cycles\n";
7504 checkForCycles(this, true);
7506 llvm_unreachable(nullptr);
7510 assert(SortedPos == AllNodes.end() &&
7511 "Topological sort incomplete!");
7512 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
7513 "First node in topological sort is not the entry token!");
7514 assert(AllNodes.front().getNodeId() == 0 &&
7515 "First node in topological sort has non-zero id!");
7516 assert(AllNodes.front().getNumOperands() == 0 &&
7517 "First node in topological sort has operands!");
7518 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
7519 "Last node in topologic sort has unexpected id!");
7520 assert(AllNodes.back().use_empty() &&
7521 "Last node in topologic sort has users!");
7522 assert(DAGSize == allnodes_size() && "Node count mismatch!");
7526 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
7527 /// value is produced by SD.
7528 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
7530 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
7531 SD->setHasDebugValue(true);
7533 DbgInfo->add(DB, SD, isParameter);
7536 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
7538 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
7539 // The new memory operation must have the same position as the old load in
7540 // terms of memory dependency. Create a TokenFactor for the old load and new
7541 // memory operation and update uses of the old load's output chain to use that
7543 SDValue OldChain = SDValue(OldLoad, 1);
7544 SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
7545 if (!OldLoad->hasAnyUseOfValue(1))
7548 SDValue TokenFactor =
7549 getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
7550 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
7551 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
7555 //===----------------------------------------------------------------------===//
7557 //===----------------------------------------------------------------------===//
7559 bool llvm::isNullConstant(SDValue V) {
7560 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7561 return Const != nullptr && Const->isNullValue();
7564 bool llvm::isNullFPConstant(SDValue V) {
7565 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
7566 return Const != nullptr && Const->isZero() && !Const->isNegative();
7569 bool llvm::isAllOnesConstant(SDValue V) {
7570 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7571 return Const != nullptr && Const->isAllOnesValue();
7574 bool llvm::isOneConstant(SDValue V) {
7575 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
7576 return Const != nullptr && Const->isOne();
7579 bool llvm::isBitwiseNot(SDValue V) {
7580 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
7583 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N) {
7584 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
7587 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7588 BitVector UndefElements;
7589 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
7591 // BuildVectors can truncate their operands. Ignore that case here.
7592 // FIXME: We blindly ignore splats which include undef which is overly
7594 if (CN && UndefElements.none() &&
7595 CN->getValueType(0) == N.getValueType().getScalarType())
7602 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N) {
7603 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
7606 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
7607 BitVector UndefElements;
7608 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
7610 if (CN && UndefElements.none())
7617 HandleSDNode::~HandleSDNode() {
7621 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
7623 const GlobalValue *GA, EVT VT,
7624 int64_t o, unsigned char TF)
7625 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
7629 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
7630 EVT VT, unsigned SrcAS,
7632 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
7633 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
7635 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
7636 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
7637 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
7638 MemSDNodeBits.IsVolatile = MMO->isVolatile();
7639 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
7640 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
7641 MemSDNodeBits.IsInvariant = MMO->isInvariant();
7643 // We check here that the size of the memory operand fits within the size of
7644 // the MMO. This is because the MMO might indicate only a possible address
7645 // range instead of specifying the affected memory addresses precisely.
7646 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
7649 /// Profile - Gather unique data for the node.
7651 void SDNode::Profile(FoldingSetNodeID &ID) const {
7652 AddNodeIDNode(ID, this);
7658 std::vector<EVT> VTs;
7661 VTs.reserve(MVT::LAST_VALUETYPE);
7662 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
7663 VTs.push_back(MVT((MVT::SimpleValueType)i));
7667 } // end anonymous namespace
7669 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
7670 static ManagedStatic<EVTArray> SimpleVTArray;
7671 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
7673 /// getValueTypeList - Return a pointer to the specified value type.
7675 const EVT *SDNode::getValueTypeList(EVT VT) {
7676 if (VT.isExtended()) {
7677 sys::SmartScopedLock<true> Lock(*VTMutex);
7678 return &(*EVTs->insert(VT).first);
7680 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
7681 "Value type out of range!");
7682 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
7686 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
7687 /// indicated value. This method ignores uses of other values defined by this
7689 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
7690 assert(Value < getNumValues() && "Bad value!");
7692 // TODO: Only iterate over uses of a given value of the node
7693 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
7694 if (UI.getUse().getResNo() == Value) {
7701 // Found exactly the right number of uses?
7705 /// hasAnyUseOfValue - Return true if there are any use of the indicated
7706 /// value. This method ignores uses of other values defined by this operation.
7707 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
7708 assert(Value < getNumValues() && "Bad value!");
7710 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
7711 if (UI.getUse().getResNo() == Value)
7717 /// isOnlyUserOf - Return true if this node is the only use of N.
7718 bool SDNode::isOnlyUserOf(const SDNode *N) const {
7720 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7731 /// Return true if the only users of N are contained in Nodes.
7732 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
7734 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
7736 if (llvm::any_of(Nodes,
7737 [&User](const SDNode *Node) { return User == Node; }))
7746 /// isOperand - Return true if this node is an operand of N.
7747 bool SDValue::isOperandOf(const SDNode *N) const {
7748 for (const SDValue &Op : N->op_values())
7754 bool SDNode::isOperandOf(const SDNode *N) const {
7755 for (const SDValue &Op : N->op_values())
7756 if (this == Op.getNode())
7761 /// reachesChainWithoutSideEffects - Return true if this operand (which must
7762 /// be a chain) reaches the specified operand without crossing any
7763 /// side-effecting instructions on any chain path. In practice, this looks
7764 /// through token factors and non-volatile loads. In order to remain efficient,
7765 /// this only looks a couple of nodes in, it does not do an exhaustive search.
7767 /// Note that we only need to examine chains when we're searching for
7768 /// side-effects; SelectionDAG requires that all side-effects are represented
7769 /// by chains, even if another operand would force a specific ordering. This
7770 /// constraint is necessary to allow transformations like splitting loads.
7771 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
7772 unsigned Depth) const {
7773 if (*this == Dest) return true;
7775 // Don't search too deeply, we just want to be able to see through
7776 // TokenFactor's etc.
7777 if (Depth == 0) return false;
7779 // If this is a token factor, all inputs to the TF happen in parallel.
7780 if (getOpcode() == ISD::TokenFactor) {
7781 // First, try a shallow search.
7782 if (is_contained((*this)->ops(), Dest)) {
7783 // We found the chain we want as an operand of this TokenFactor.
7784 // Essentially, we reach the chain without side-effects if we could
7785 // serialize the TokenFactor into a simple chain of operations with
7786 // Dest as the last operation. This is automatically true if the
7787 // chain has one use: there are no other ordering constraints.
7788 // If the chain has more than one use, we give up: some other
7789 // use of Dest might force a side-effect between Dest and the current
7791 if (Dest.hasOneUse())
7794 // Next, try a deep search: check whether every operand of the TokenFactor
7796 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
7797 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
7801 // Loads don't have side effects, look through them.
7802 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
7803 if (!Ld->isVolatile())
7804 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
7809 bool SDNode::hasPredecessor(const SDNode *N) const {
7810 SmallPtrSet<const SDNode *, 32> Visited;
7811 SmallVector<const SDNode *, 16> Worklist;
7812 Worklist.push_back(this);
7813 return hasPredecessorHelper(N, Visited, Worklist);
7816 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
7817 this->Flags.intersectWith(Flags);
7820 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
7821 assert(N->getNumValues() == 1 &&
7822 "Can't unroll a vector with multiple results!");
7824 EVT VT = N->getValueType(0);
7825 unsigned NE = VT.getVectorNumElements();
7826 EVT EltVT = VT.getVectorElementType();
7829 SmallVector<SDValue, 8> Scalars;
7830 SmallVector<SDValue, 4> Operands(N->getNumOperands());
7832 // If ResNE is 0, fully unroll the vector op.
7835 else if (NE > ResNE)
7839 for (i= 0; i != NE; ++i) {
7840 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
7841 SDValue Operand = N->getOperand(j);
7842 EVT OperandVT = Operand.getValueType();
7843 if (OperandVT.isVector()) {
7844 // A vector operand; extract a single element.
7845 EVT OperandEltVT = OperandVT.getVectorElementType();
7847 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
7848 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
7850 // A scalar operand; just use it as is.
7851 Operands[j] = Operand;
7855 switch (N->getOpcode()) {
7857 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
7862 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
7869 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
7870 getShiftAmountOperand(Operands[0].getValueType(),
7873 case ISD::SIGN_EXTEND_INREG:
7874 case ISD::FP_ROUND_INREG: {
7875 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
7876 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
7878 getValueType(ExtVT)));
7883 for (; i < ResNE; ++i)
7884 Scalars.push_back(getUNDEF(EltVT));
7886 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
7887 return getBuildVector(VecVT, dl, Scalars);
7890 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
7894 if (LD->isVolatile() || Base->isVolatile())
7896 if (LD->isIndexed() || Base->isIndexed())
7898 if (LD->getChain() != Base->getChain())
7900 EVT VT = LD->getValueType(0);
7901 if (VT.getSizeInBits() / 8 != Bytes)
7904 SDValue Loc = LD->getOperand(1);
7905 SDValue BaseLoc = Base->getOperand(1);
7907 auto BaseLocDecomp = BaseIndexOffset::match(BaseLoc, *this);
7908 auto LocDecomp = BaseIndexOffset::match(Loc, *this);
7911 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
7912 return (Dist * Bytes == Offset);
7916 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
7917 /// it cannot be inferred.
7918 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
7919 // If this is a GlobalAddress + cst, return the alignment.
7920 const GlobalValue *GV;
7921 int64_t GVOffset = 0;
7922 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
7923 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
7924 KnownBits Known(PtrWidth);
7925 llvm::computeKnownBits(GV, Known, getDataLayout());
7926 unsigned AlignBits = Known.countMinTrailingZeros();
7927 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7929 return MinAlign(Align, GVOffset);
7932 // If this is a direct reference to a stack slot, use information about the
7933 // stack slot's alignment.
7934 int FrameIdx = 1 << 31;
7935 int64_t FrameOffset = 0;
7936 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7937 FrameIdx = FI->getIndex();
7938 } else if (isBaseWithConstantOffset(Ptr) &&
7939 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7941 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7942 FrameOffset = Ptr.getConstantOperandVal(1);
7945 if (FrameIdx != (1 << 31)) {
7946 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
7947 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7955 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7956 /// which is split (or expanded) into two not necessarily identical pieces.
7957 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7958 // Currently all types are split in half.
7961 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7963 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
7965 return std::make_pair(LoVT, HiVT);
7968 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7970 std::pair<SDValue, SDValue>
7971 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7973 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7974 N.getValueType().getVectorNumElements() &&
7975 "More vector elements requested than available!");
7977 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7978 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7979 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7980 getConstant(LoVT.getVectorNumElements(), DL,
7981 TLI->getVectorIdxTy(getDataLayout())));
7982 return std::make_pair(Lo, Hi);
7985 void SelectionDAG::ExtractVectorElements(SDValue Op,
7986 SmallVectorImpl<SDValue> &Args,
7987 unsigned Start, unsigned Count) {
7988 EVT VT = Op.getValueType();
7990 Count = VT.getVectorNumElements();
7992 EVT EltVT = VT.getVectorElementType();
7993 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7995 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7996 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7997 Op, getConstant(i, SL, IdxTy)));
8001 // getAddressSpace - Return the address space this GlobalAddress belongs to.
8002 unsigned GlobalAddressSDNode::getAddressSpace() const {
8003 return getGlobal()->getType()->getAddressSpace();
8006 Type *ConstantPoolSDNode::getType() const {
8007 if (isMachineConstantPoolEntry())
8008 return Val.MachineCPVal->getType();
8009 return Val.ConstVal->getType();
8012 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
8013 unsigned &SplatBitSize,
8015 unsigned MinSplatBits,
8016 bool IsBigEndian) const {
8017 EVT VT = getValueType(0);
8018 assert(VT.isVector() && "Expected a vector type");
8019 unsigned VecWidth = VT.getSizeInBits();
8020 if (MinSplatBits > VecWidth)
8023 // FIXME: The widths are based on this node's type, but build vectors can
8024 // truncate their operands.
8025 SplatValue = APInt(VecWidth, 0);
8026 SplatUndef = APInt(VecWidth, 0);
8028 // Get the bits. Bits with undefined values (when the corresponding element
8029 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
8030 // in SplatValue. If any of the values are not constant, give up and return
8032 unsigned int NumOps = getNumOperands();
8033 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
8034 unsigned EltWidth = VT.getScalarSizeInBits();
8036 for (unsigned j = 0; j < NumOps; ++j) {
8037 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
8038 SDValue OpVal = getOperand(i);
8039 unsigned BitPos = j * EltWidth;
8041 if (OpVal.isUndef())
8042 SplatUndef.setBits(BitPos, BitPos + EltWidth);
8043 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
8044 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
8045 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
8046 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
8051 // The build_vector is all constants or undefs. Find the smallest element
8052 // size that splats the vector.
8053 HasAnyUndefs = (SplatUndef != 0);
8055 // FIXME: This does not work for vectors with elements less than 8 bits.
8056 while (VecWidth > 8) {
8057 unsigned HalfSize = VecWidth / 2;
8058 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
8059 APInt LowValue = SplatValue.trunc(HalfSize);
8060 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
8061 APInt LowUndef = SplatUndef.trunc(HalfSize);
8063 // If the two halves do not match (ignoring undef bits), stop here.
8064 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
8065 MinSplatBits > HalfSize)
8068 SplatValue = HighValue | LowValue;
8069 SplatUndef = HighUndef & LowUndef;
8071 VecWidth = HalfSize;
8074 SplatBitSize = VecWidth;
8078 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
8079 if (UndefElements) {
8080 UndefElements->clear();
8081 UndefElements->resize(getNumOperands());
8084 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
8085 SDValue Op = getOperand(i);
8088 (*UndefElements)[i] = true;
8089 } else if (!Splatted) {
8091 } else if (Splatted != Op) {
8097 assert(getOperand(0).isUndef() &&
8098 "Can only have a splat without a constant for all undefs.");
8099 return getOperand(0);
8106 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
8107 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
8111 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
8112 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
8116 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
8117 uint32_t BitWidth) const {
8118 if (ConstantFPSDNode *CN =
8119 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
8121 APSInt IntVal(BitWidth);
8122 const APFloat &APF = CN->getValueAPF();
8123 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
8128 return IntVal.exactLogBase2();
8133 bool BuildVectorSDNode::isConstant() const {
8134 for (const SDValue &Op : op_values()) {
8135 unsigned Opc = Op.getOpcode();
8136 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
8142 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
8143 // Find the first non-undef value in the shuffle mask.
8145 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
8148 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
8150 // Make sure all remaining elements are either undef or the same as the first
8152 for (int Idx = Mask[i]; i != e; ++i)
8153 if (Mask[i] >= 0 && Mask[i] != Idx)
8158 // \brief Returns the SDNode if it is a constant integer BuildVector
8159 // or constant integer.
8160 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
8161 if (isa<ConstantSDNode>(N))
8163 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
8165 // Treat a GlobalAddress supporting constant offset folding as a
8166 // constant integer.
8167 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
8168 if (GA->getOpcode() == ISD::GlobalAddress &&
8169 TLI->isOffsetFoldingLegal(GA))
8174 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
8175 if (isa<ConstantFPSDNode>(N))
8178 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
8185 static void checkForCyclesHelper(const SDNode *N,
8186 SmallPtrSetImpl<const SDNode*> &Visited,
8187 SmallPtrSetImpl<const SDNode*> &Checked,
8188 const llvm::SelectionDAG *DAG) {
8189 // If this node has already been checked, don't check it again.
8190 if (Checked.count(N))
8193 // If a node has already been visited on this depth-first walk, reject it as
8195 if (!Visited.insert(N).second) {
8196 errs() << "Detected cycle in SelectionDAG\n";
8197 dbgs() << "Offending node:\n";
8198 N->dumprFull(DAG); dbgs() << "\n";
8202 for (const SDValue &Op : N->op_values())
8203 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
8210 void llvm::checkForCycles(const llvm::SDNode *N,
8211 const llvm::SelectionDAG *DAG,
8215 #ifdef EXPENSIVE_CHECKS
8217 #endif // EXPENSIVE_CHECKS
8219 assert(N && "Checking nonexistent SDNode");
8220 SmallPtrSet<const SDNode*, 32> visited;
8221 SmallPtrSet<const SDNode*, 32> checked;
8222 checkForCyclesHelper(N, visited, checked, DAG);
8227 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
8228 checkForCycles(DAG->getRoot().getNode(), DAG, force);