1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/ManagedStatic.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/Mutex.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetIntrinsicInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Target/TargetRegisterInfo.h"
49 #include "llvm/Target/TargetSubtargetInfo.h"
56 /// makeVTList - Return an instance of the SDVTList struct initialized with the
57 /// specified members.
58 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
59 SDVTList Res = {VTs, NumVTs};
63 // Default null implementations of the callbacks.
64 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
65 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
67 //===----------------------------------------------------------------------===//
68 // ConstantFPSDNode Class
69 //===----------------------------------------------------------------------===//
71 /// isExactlyValue - We don't rely on operator== working on double values, as
72 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
73 /// As such, this method can be used to do an exact bit-for-bit comparison of
74 /// two floating point values.
75 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
76 return getValueAPF().bitwiseIsEqual(V);
79 bool ConstantFPSDNode::isValueValidForType(EVT VT,
81 assert(VT.isFloatingPoint() && "Can only convert between FP types");
83 // convert modifies in place, so make a copy.
84 APFloat Val2 = APFloat(Val);
86 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
87 APFloat::rmNearestTiesToEven,
92 //===----------------------------------------------------------------------===//
94 //===----------------------------------------------------------------------===//
96 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
97 auto *BV = dyn_cast<BuildVectorSDNode>(N);
102 unsigned SplatBitSize;
104 EVT EltVT = N->getValueType(0).getVectorElementType();
105 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs) &&
106 EltVT.getSizeInBits() >= SplatBitSize;
109 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
110 // specializations of the more general isConstantSplatVector()?
112 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
113 // Look through a bit convert.
114 while (N->getOpcode() == ISD::BITCAST)
115 N = N->getOperand(0).getNode();
117 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
119 unsigned i = 0, e = N->getNumOperands();
121 // Skip over all of the undef values.
122 while (i != e && N->getOperand(i).isUndef())
125 // Do not accept an all-undef vector.
126 if (i == e) return false;
128 // Do not accept build_vectors that aren't all constants or which have non-~0
129 // elements. We have to be a bit careful here, as the type of the constant
130 // may not be the same as the type of the vector elements due to type
131 // legalization (the elements are promoted to a legal type for the target and
132 // a vector of a type may be legal when the base element type is not).
133 // We only want to check enough bits to cover the vector elements, because
134 // we care if the resultant vector is all ones, not whether the individual
136 SDValue NotZero = N->getOperand(i);
137 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
138 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
139 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
141 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
142 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
147 // Okay, we have at least one ~0 value, check to see if the rest match or are
148 // undefs. Even with the above element type twiddling, this should be OK, as
149 // the same type legalization should have applied to all the elements.
150 for (++i; i != e; ++i)
151 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
156 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
157 // Look through a bit convert.
158 while (N->getOpcode() == ISD::BITCAST)
159 N = N->getOperand(0).getNode();
161 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
163 bool IsAllUndef = true;
164 for (const SDValue &Op : N->op_values()) {
168 // Do not accept build_vectors that aren't all constants or which have non-0
169 // elements. We have to be a bit careful here, as the type of the constant
170 // may not be the same as the type of the vector elements due to type
171 // legalization (the elements are promoted to a legal type for the target
172 // and a vector of a type may be legal when the base element type is not).
173 // We only want to check enough bits to cover the vector elements, because
174 // we care if the resultant vector is all zeros, not whether the individual
176 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
177 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
178 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
180 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
181 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
187 // Do not accept an all-undef vector.
193 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
194 if (N->getOpcode() != ISD::BUILD_VECTOR)
197 for (const SDValue &Op : N->op_values()) {
200 if (!isa<ConstantSDNode>(Op))
206 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
207 if (N->getOpcode() != ISD::BUILD_VECTOR)
210 for (const SDValue &Op : N->op_values()) {
213 if (!isa<ConstantFPSDNode>(Op))
219 bool ISD::allOperandsUndef(const SDNode *N) {
220 // Return false if the node has no operands.
221 // This is "logically inconsistent" with the definition of "all" but
222 // is probably the desired behavior.
223 if (N->getNumOperands() == 0)
226 for (const SDValue &Op : N->op_values())
233 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
236 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
238 return ISD::SIGN_EXTEND;
240 return ISD::ZERO_EXTEND;
245 llvm_unreachable("Invalid LoadExtType");
248 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
249 // To perform this operation, we just need to swap the L and G bits of the
251 unsigned OldL = (Operation >> 2) & 1;
252 unsigned OldG = (Operation >> 1) & 1;
253 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
254 (OldL << 1) | // New G bit
255 (OldG << 2)); // New L bit.
258 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
259 unsigned Operation = Op;
261 Operation ^= 7; // Flip L, G, E bits, but not U.
263 Operation ^= 15; // Flip all of the condition bits.
265 if (Operation > ISD::SETTRUE2)
266 Operation &= ~8; // Don't let N and U bits get set.
268 return ISD::CondCode(Operation);
272 /// For an integer comparison, return 1 if the comparison is a signed operation
273 /// and 2 if the result is an unsigned comparison. Return zero if the operation
274 /// does not depend on the sign of the input (setne and seteq).
275 static int isSignedOp(ISD::CondCode Opcode) {
277 default: llvm_unreachable("Illegal integer setcc operation!");
279 case ISD::SETNE: return 0;
283 case ISD::SETGE: return 1;
287 case ISD::SETUGE: return 2;
291 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
293 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
294 // Cannot fold a signed integer setcc with an unsigned integer setcc.
295 return ISD::SETCC_INVALID;
297 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
299 // If the N and U bits get set then the resultant comparison DOES suddenly
300 // care about orderedness, and is true when ordered.
301 if (Op > ISD::SETTRUE2)
302 Op &= ~16; // Clear the U bit if the N bit is set.
304 // Canonicalize illegal integer setcc's.
305 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
308 return ISD::CondCode(Op);
311 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
313 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
314 // Cannot fold a signed setcc with an unsigned setcc.
315 return ISD::SETCC_INVALID;
317 // Combine all of the condition bits.
318 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
320 // Canonicalize illegal integer setcc's.
324 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
325 case ISD::SETOEQ: // SETEQ & SETU[LG]E
326 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
327 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
328 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
335 //===----------------------------------------------------------------------===//
336 // SDNode Profile Support
337 //===----------------------------------------------------------------------===//
339 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
341 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
345 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
346 /// solely with their pointer.
347 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
348 ID.AddPointer(VTList.VTs);
351 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
353 static void AddNodeIDOperands(FoldingSetNodeID &ID,
354 ArrayRef<SDValue> Ops) {
355 for (auto& Op : Ops) {
356 ID.AddPointer(Op.getNode());
357 ID.AddInteger(Op.getResNo());
361 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
363 static void AddNodeIDOperands(FoldingSetNodeID &ID,
364 ArrayRef<SDUse> Ops) {
365 for (auto& Op : Ops) {
366 ID.AddPointer(Op.getNode());
367 ID.AddInteger(Op.getResNo());
371 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
372 SDVTList VTList, ArrayRef<SDValue> OpList) {
373 AddNodeIDOpcode(ID, OpC);
374 AddNodeIDValueTypes(ID, VTList);
375 AddNodeIDOperands(ID, OpList);
378 /// If this is an SDNode with special info, add this info to the NodeID data.
379 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
380 switch (N->getOpcode()) {
381 case ISD::TargetExternalSymbol:
382 case ISD::ExternalSymbol:
384 llvm_unreachable("Should only be used on nodes with operands");
385 default: break; // Normal nodes don't need extra info.
386 case ISD::TargetConstant:
387 case ISD::Constant: {
388 const ConstantSDNode *C = cast<ConstantSDNode>(N);
389 ID.AddPointer(C->getConstantIntValue());
390 ID.AddBoolean(C->isOpaque());
393 case ISD::TargetConstantFP:
394 case ISD::ConstantFP: {
395 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
398 case ISD::TargetGlobalAddress:
399 case ISD::GlobalAddress:
400 case ISD::TargetGlobalTLSAddress:
401 case ISD::GlobalTLSAddress: {
402 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
403 ID.AddPointer(GA->getGlobal());
404 ID.AddInteger(GA->getOffset());
405 ID.AddInteger(GA->getTargetFlags());
406 ID.AddInteger(GA->getAddressSpace());
409 case ISD::BasicBlock:
410 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
413 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
415 case ISD::RegisterMask:
416 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
419 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
421 case ISD::FrameIndex:
422 case ISD::TargetFrameIndex:
423 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
426 case ISD::TargetJumpTable:
427 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
428 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
430 case ISD::ConstantPool:
431 case ISD::TargetConstantPool: {
432 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
433 ID.AddInteger(CP->getAlignment());
434 ID.AddInteger(CP->getOffset());
435 if (CP->isMachineConstantPoolEntry())
436 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
438 ID.AddPointer(CP->getConstVal());
439 ID.AddInteger(CP->getTargetFlags());
442 case ISD::TargetIndex: {
443 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
444 ID.AddInteger(TI->getIndex());
445 ID.AddInteger(TI->getOffset());
446 ID.AddInteger(TI->getTargetFlags());
450 const LoadSDNode *LD = cast<LoadSDNode>(N);
451 ID.AddInteger(LD->getMemoryVT().getRawBits());
452 ID.AddInteger(LD->getRawSubclassData());
453 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
457 const StoreSDNode *ST = cast<StoreSDNode>(N);
458 ID.AddInteger(ST->getMemoryVT().getRawBits());
459 ID.AddInteger(ST->getRawSubclassData());
460 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
463 case ISD::ATOMIC_CMP_SWAP:
464 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
465 case ISD::ATOMIC_SWAP:
466 case ISD::ATOMIC_LOAD_ADD:
467 case ISD::ATOMIC_LOAD_SUB:
468 case ISD::ATOMIC_LOAD_AND:
469 case ISD::ATOMIC_LOAD_OR:
470 case ISD::ATOMIC_LOAD_XOR:
471 case ISD::ATOMIC_LOAD_NAND:
472 case ISD::ATOMIC_LOAD_MIN:
473 case ISD::ATOMIC_LOAD_MAX:
474 case ISD::ATOMIC_LOAD_UMIN:
475 case ISD::ATOMIC_LOAD_UMAX:
476 case ISD::ATOMIC_LOAD:
477 case ISD::ATOMIC_STORE: {
478 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
479 ID.AddInteger(AT->getMemoryVT().getRawBits());
480 ID.AddInteger(AT->getRawSubclassData());
481 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
484 case ISD::PREFETCH: {
485 const MemSDNode *PF = cast<MemSDNode>(N);
486 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
489 case ISD::VECTOR_SHUFFLE: {
490 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
491 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
493 ID.AddInteger(SVN->getMaskElt(i));
496 case ISD::TargetBlockAddress:
497 case ISD::BlockAddress: {
498 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
499 ID.AddPointer(BA->getBlockAddress());
500 ID.AddInteger(BA->getOffset());
501 ID.AddInteger(BA->getTargetFlags());
504 } // end switch (N->getOpcode())
506 // Target specific memory nodes could also have address spaces to check.
507 if (N->isTargetMemoryOpcode())
508 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
511 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
513 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
514 AddNodeIDOpcode(ID, N->getOpcode());
515 // Add the return value info.
516 AddNodeIDValueTypes(ID, N->getVTList());
517 // Add the operand info.
518 AddNodeIDOperands(ID, N->ops());
520 // Handle SDNode leafs with special info.
521 AddNodeIDCustom(ID, N);
524 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
525 /// the CSE map that carries volatility, temporalness, indexing mode, and
526 /// extension/truncation information.
528 static inline unsigned
529 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile,
530 bool isNonTemporal, bool isInvariant) {
531 assert((ConvType & 3) == ConvType &&
532 "ConvType may not require more than 2 bits!");
533 assert((AM & 7) == AM &&
534 "AM may not require more than 3 bits!");
538 (isNonTemporal << 6) |
542 //===----------------------------------------------------------------------===//
543 // SelectionDAG Class
544 //===----------------------------------------------------------------------===//
546 /// doNotCSE - Return true if CSE should not be performed for this node.
547 static bool doNotCSE(SDNode *N) {
548 if (N->getValueType(0) == MVT::Glue)
549 return true; // Never CSE anything that produces a flag.
551 switch (N->getOpcode()) {
553 case ISD::HANDLENODE:
555 return true; // Never CSE these nodes.
558 // Check that remaining values produced are not flags.
559 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
560 if (N->getValueType(i) == MVT::Glue)
561 return true; // Never CSE anything that produces a flag.
566 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
568 void SelectionDAG::RemoveDeadNodes() {
569 // Create a dummy node (which is not added to allnodes), that adds a reference
570 // to the root node, preventing it from being deleted.
571 HandleSDNode Dummy(getRoot());
573 SmallVector<SDNode*, 128> DeadNodes;
575 // Add all obviously-dead nodes to the DeadNodes worklist.
576 for (SDNode &Node : allnodes())
577 if (Node.use_empty())
578 DeadNodes.push_back(&Node);
580 RemoveDeadNodes(DeadNodes);
582 // If the root changed (e.g. it was a dead load, update the root).
583 setRoot(Dummy.getValue());
586 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
587 /// given list, and any nodes that become unreachable as a result.
588 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
590 // Process the worklist, deleting the nodes and adding their uses to the
592 while (!DeadNodes.empty()) {
593 SDNode *N = DeadNodes.pop_back_val();
595 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
596 DUL->NodeDeleted(N, nullptr);
598 // Take the node out of the appropriate CSE map.
599 RemoveNodeFromCSEMaps(N);
601 // Next, brutally remove the operand list. This is safe to do, as there are
602 // no cycles in the graph.
603 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
605 SDNode *Operand = Use.getNode();
608 // Now that we removed this operand, see if there are no uses of it left.
609 if (Operand->use_empty())
610 DeadNodes.push_back(Operand);
617 void SelectionDAG::RemoveDeadNode(SDNode *N){
618 SmallVector<SDNode*, 16> DeadNodes(1, N);
620 // Create a dummy node that adds a reference to the root node, preventing
621 // it from being deleted. (This matters if the root is an operand of the
623 HandleSDNode Dummy(getRoot());
625 RemoveDeadNodes(DeadNodes);
628 void SelectionDAG::DeleteNode(SDNode *N) {
629 // First take this out of the appropriate CSE map.
630 RemoveNodeFromCSEMaps(N);
632 // Finally, remove uses due to operands of this node, remove from the
633 // AllNodes list, and delete the node.
634 DeleteNodeNotInCSEMaps(N);
637 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
638 assert(N->getIterator() != AllNodes.begin() &&
639 "Cannot delete the entry node!");
640 assert(N->use_empty() && "Cannot delete a node that is not dead!");
642 // Drop all of the operands and decrement used node's use counts.
648 void SDDbgInfo::erase(const SDNode *Node) {
649 DbgValMapType::iterator I = DbgValMap.find(Node);
650 if (I == DbgValMap.end())
652 for (auto &Val: I->second)
653 Val->setIsInvalidated();
657 void SelectionDAG::DeallocateNode(SDNode *N) {
658 // If we have operands, deallocate them.
661 // Set the opcode to DELETED_NODE to help catch bugs when node
662 // memory is reallocated.
663 N->NodeType = ISD::DELETED_NODE;
665 NodeAllocator.Deallocate(AllNodes.remove(N));
667 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
668 // them and forget about that node.
673 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
674 static void VerifySDNode(SDNode *N) {
675 switch (N->getOpcode()) {
678 case ISD::BUILD_PAIR: {
679 EVT VT = N->getValueType(0);
680 assert(N->getNumValues() == 1 && "Too many results!");
681 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
682 "Wrong return type!");
683 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
684 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
685 "Mismatched operand types!");
686 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
687 "Wrong operand type!");
688 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
689 "Wrong return type size");
692 case ISD::BUILD_VECTOR: {
693 assert(N->getNumValues() == 1 && "Too many results!");
694 assert(N->getValueType(0).isVector() && "Wrong return type!");
695 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
696 "Wrong number of operands!");
697 EVT EltVT = N->getValueType(0).getVectorElementType();
698 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
699 assert((I->getValueType() == EltVT ||
700 (EltVT.isInteger() && I->getValueType().isInteger() &&
701 EltVT.bitsLE(I->getValueType()))) &&
702 "Wrong operand type!");
703 assert(I->getValueType() == N->getOperand(0).getValueType() &&
704 "Operands must all have the same type");
712 /// \brief Insert a newly allocated node into the DAG.
714 /// Handles insertion into the all nodes list and CSE map, as well as
715 /// verification and other common operations when a new node is allocated.
716 void SelectionDAG::InsertNode(SDNode *N) {
717 AllNodes.push_back(N);
719 N->PersistentId = NextPersistentId++;
724 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
725 /// correspond to it. This is useful when we're about to delete or repurpose
726 /// the node. We don't want future request for structurally identical nodes
727 /// to return N anymore.
728 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
730 switch (N->getOpcode()) {
731 case ISD::HANDLENODE: return false; // noop.
733 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
734 "Cond code doesn't exist!");
735 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
736 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
738 case ISD::ExternalSymbol:
739 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
741 case ISD::TargetExternalSymbol: {
742 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
743 Erased = TargetExternalSymbols.erase(
744 std::pair<std::string,unsigned char>(ESN->getSymbol(),
745 ESN->getTargetFlags()));
748 case ISD::MCSymbol: {
749 auto *MCSN = cast<MCSymbolSDNode>(N);
750 Erased = MCSymbols.erase(MCSN->getMCSymbol());
753 case ISD::VALUETYPE: {
754 EVT VT = cast<VTSDNode>(N)->getVT();
755 if (VT.isExtended()) {
756 Erased = ExtendedValueTypeNodes.erase(VT);
758 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
759 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
764 // Remove it from the CSE Map.
765 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
766 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
767 Erased = CSEMap.RemoveNode(N);
771 // Verify that the node was actually in one of the CSE maps, unless it has a
772 // flag result (which cannot be CSE'd) or is one of the special cases that are
773 // not subject to CSE.
774 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
775 !N->isMachineOpcode() && !doNotCSE(N)) {
778 llvm_unreachable("Node is not in map!");
784 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
785 /// maps and modified in place. Add it back to the CSE maps, unless an identical
786 /// node already exists, in which case transfer all its users to the existing
787 /// node. This transfer can potentially trigger recursive merging.
790 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
791 // For node types that aren't CSE'd, just act as if no identical node
794 SDNode *Existing = CSEMap.GetOrInsertNode(N);
796 // If there was already an existing matching node, use ReplaceAllUsesWith
797 // to replace the dead one with the existing one. This can cause
798 // recursive merging of other unrelated nodes down the line.
799 ReplaceAllUsesWith(N, Existing);
801 // N is now dead. Inform the listeners and delete it.
802 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
803 DUL->NodeDeleted(N, Existing);
804 DeleteNodeNotInCSEMaps(N);
809 // If the node doesn't already exist, we updated it. Inform listeners.
810 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
814 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
815 /// were replaced with those specified. If this node is never memoized,
816 /// return null, otherwise return a pointer to the slot it would take. If a
817 /// node already exists with these operands, the slot will be non-null.
818 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
823 SDValue Ops[] = { Op };
825 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
826 AddNodeIDCustom(ID, N);
827 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
829 if (const SDNodeFlags *Flags = N->getFlags())
830 Node->intersectFlagsWith(Flags);
834 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
835 /// were replaced with those specified. If this node is never memoized,
836 /// return null, otherwise return a pointer to the slot it would take. If a
837 /// node already exists with these operands, the slot will be non-null.
838 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
839 SDValue Op1, SDValue Op2,
844 SDValue Ops[] = { Op1, Op2 };
846 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
847 AddNodeIDCustom(ID, N);
848 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
850 if (const SDNodeFlags *Flags = N->getFlags())
851 Node->intersectFlagsWith(Flags);
856 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
857 /// were replaced with those specified. If this node is never memoized,
858 /// return null, otherwise return a pointer to the slot it would take. If a
859 /// node already exists with these operands, the slot will be non-null.
860 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
866 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
867 AddNodeIDCustom(ID, N);
868 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
870 if (const SDNodeFlags *Flags = N->getFlags())
871 Node->intersectFlagsWith(Flags);
875 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
876 Type *Ty = VT == MVT::iPTR ?
877 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
878 VT.getTypeForEVT(*getContext());
880 return getDataLayout().getABITypeAlignment(Ty);
883 // EntryNode could meaningfully have debug info if we can find it...
884 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
885 : TM(tm), TSI(nullptr), TLI(nullptr), OptLevel(OL),
886 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
887 Root(getEntryNode()), NewNodesMustHaveLegalTypes(false),
888 UpdateListeners(nullptr) {
889 InsertNode(&EntryNode);
890 DbgInfo = new SDDbgInfo();
893 void SelectionDAG::init(MachineFunction &mf) {
895 TLI = getSubtarget().getTargetLowering();
896 TSI = getSubtarget().getSelectionDAGInfo();
897 Context = &mf.getFunction()->getContext();
900 SelectionDAG::~SelectionDAG() {
901 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
903 OperandRecycler.clear(OperandAllocator);
907 void SelectionDAG::allnodes_clear() {
908 assert(&*AllNodes.begin() == &EntryNode);
909 AllNodes.remove(AllNodes.begin());
910 while (!AllNodes.empty())
911 DeallocateNode(&AllNodes.front());
913 NextPersistentId = 0;
917 SDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, const SDLoc &DL,
918 SDVTList VTs, SDValue N1, SDValue N2,
919 const SDNodeFlags *Flags) {
920 SDValue Ops[] = {N1, N2};
922 if (isBinOpWithFlags(Opcode)) {
923 // If no flags were passed in, use a default flags object.
925 if (Flags == nullptr)
928 auto *FN = newSDNode<BinaryWithFlagsSDNode>(Opcode, DL.getIROrder(),
929 DL.getDebugLoc(), VTs, *Flags);
930 createOperands(FN, Ops);
935 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
936 createOperands(N, Ops);
940 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
942 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
944 switch (N->getOpcode()) {
947 case ISD::ConstantFP:
948 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
949 "debug location. Use another overload.");
955 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
956 const SDLoc &DL, void *&InsertPos) {
957 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
959 switch (N->getOpcode()) {
961 case ISD::ConstantFP:
962 // Erase debug location from the node if the node is used at several
963 // different places. Do not propagate one location to all uses as it
964 // will cause a worse single stepping debugging experience.
965 if (N->getDebugLoc() != DL.getDebugLoc())
966 N->setDebugLoc(DebugLoc());
969 // When the node's point of use is located earlier in the instruction
970 // sequence than its prior point of use, update its debug info to the
972 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
973 N->setDebugLoc(DL.getDebugLoc());
980 void SelectionDAG::clear() {
982 OperandRecycler.clear(OperandAllocator);
983 OperandAllocator.Reset();
986 ExtendedValueTypeNodes.clear();
987 ExternalSymbols.clear();
988 TargetExternalSymbols.clear();
990 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
991 static_cast<CondCodeSDNode*>(nullptr));
992 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
993 static_cast<SDNode*>(nullptr));
995 EntryNode.UseList = nullptr;
996 InsertNode(&EntryNode);
997 Root = getEntryNode();
1001 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1002 return VT.bitsGT(Op.getValueType()) ?
1003 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1004 getNode(ISD::TRUNCATE, DL, VT, Op);
1007 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1008 return VT.bitsGT(Op.getValueType()) ?
1009 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1010 getNode(ISD::TRUNCATE, DL, VT, Op);
1013 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1014 return VT.bitsGT(Op.getValueType()) ?
1015 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1016 getNode(ISD::TRUNCATE, DL, VT, Op);
1019 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1021 if (VT.bitsLE(Op.getValueType()))
1022 return getNode(ISD::TRUNCATE, SL, VT, Op);
1024 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1025 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1028 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1029 assert(!VT.isVector() &&
1030 "getZeroExtendInReg should use the vector element type instead of "
1031 "the vector type!");
1032 if (Op.getValueType() == VT) return Op;
1033 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1034 APInt Imm = APInt::getLowBitsSet(BitWidth,
1035 VT.getSizeInBits());
1036 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1037 getConstant(Imm, DL, Op.getValueType()));
1040 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL,
1042 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1043 assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() &&
1044 "The sizes of the input and result must match in order to perform the "
1045 "extend in-register.");
1046 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1047 "The destination vector type must have fewer lanes than the input.");
1048 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op);
1051 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL,
1053 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1054 assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() &&
1055 "The sizes of the input and result must match in order to perform the "
1056 "extend in-register.");
1057 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1058 "The destination vector type must have fewer lanes than the input.");
1059 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op);
1062 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL,
1064 assert(VT.isVector() && "This DAG node is restricted to vector types.");
1065 assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() &&
1066 "The sizes of the input and result must match in order to perform the "
1067 "extend in-register.");
1068 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() &&
1069 "The destination vector type must have fewer lanes than the input.");
1070 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op);
1073 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1075 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1076 EVT EltVT = VT.getScalarType();
1078 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1079 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1082 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1083 EVT EltVT = VT.getScalarType();
1085 switch (TLI->getBooleanContents(VT)) {
1086 case TargetLowering::ZeroOrOneBooleanContent:
1087 case TargetLowering::UndefinedBooleanContent:
1088 TrueValue = getConstant(1, DL, VT);
1090 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1091 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL,
1095 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1098 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1099 bool isT, bool isO) {
1100 EVT EltVT = VT.getScalarType();
1101 assert((EltVT.getSizeInBits() >= 64 ||
1102 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1103 "getConstant with a uint64_t value that doesn't fit in the type!");
1104 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1107 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1108 bool isT, bool isO) {
1109 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1112 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1113 EVT VT, bool isT, bool isO) {
1114 assert(VT.isInteger() && "Cannot create FP integer constant!");
1116 EVT EltVT = VT.getScalarType();
1117 const ConstantInt *Elt = &Val;
1119 // In some cases the vector type is legal but the element type is illegal and
1120 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1121 // inserted value (the type does not need to match the vector element type).
1122 // Any extra bits introduced will be truncated away.
1123 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1124 TargetLowering::TypePromoteInteger) {
1125 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1126 APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits());
1127 Elt = ConstantInt::get(*getContext(), NewVal);
1129 // In other cases the element type is illegal and needs to be expanded, for
1130 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1131 // the value into n parts and use a vector type with n-times the elements.
1132 // Then bitcast to the type requested.
1133 // Legalizing constants too early makes the DAGCombiner's job harder so we
1134 // only legalize if the DAG tells us we must produce legal types.
1135 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1136 TLI->getTypeAction(*getContext(), EltVT) ==
1137 TargetLowering::TypeExpandInteger) {
1138 const APInt &NewVal = Elt->getValue();
1139 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1140 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1141 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1142 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1144 // Check the temporary vector is the correct size. If this fails then
1145 // getTypeToTransformTo() probably returned a type whose size (in bits)
1146 // isn't a power-of-2 factor of the requested type size.
1147 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1149 SmallVector<SDValue, 2> EltParts;
1150 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1151 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1152 .trunc(ViaEltSizeInBits), DL,
1153 ViaEltVT, isT, isO));
1156 // EltParts is currently in little endian order. If we actually want
1157 // big-endian order then reverse it now.
1158 if (getDataLayout().isBigEndian())
1159 std::reverse(EltParts.begin(), EltParts.end());
1161 // The elements must be reversed when the element order is different
1162 // to the endianness of the elements (because the BITCAST is itself a
1163 // vector shuffle in this situation). However, we do not need any code to
1164 // perform this reversal because getConstant() is producing a vector
1166 // This situation occurs in MIPS MSA.
1168 SmallVector<SDValue, 8> Ops;
1169 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
1170 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1172 SDValue Result = getNode(ISD::BITCAST, DL, VT,
1173 getNode(ISD::BUILD_VECTOR, DL, ViaVecVT, Ops));
1177 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1178 "APInt size does not match type size!");
1179 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1180 FoldingSetNodeID ID;
1181 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1185 SDNode *N = nullptr;
1186 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1188 return SDValue(N, 0);
1191 N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT);
1192 CSEMap.InsertNode(N, IP);
1196 SDValue Result(N, 0);
1198 Result = getSplatBuildVector(VT, DL, Result);
1202 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1204 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1207 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1209 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1212 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1213 EVT VT, bool isTarget) {
1214 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1216 EVT EltVT = VT.getScalarType();
1218 // Do the map lookup using the actual bit pattern for the floating point
1219 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1220 // we don't have issues with SNANs.
1221 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1222 FoldingSetNodeID ID;
1223 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1226 SDNode *N = nullptr;
1227 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1229 return SDValue(N, 0);
1232 N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT);
1233 CSEMap.InsertNode(N, IP);
1237 SDValue Result(N, 0);
1239 Result = getSplatBuildVector(VT, DL, Result);
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);
1283 ID.AddInteger(GV->getType()->getAddressSpace());
1285 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1286 return SDValue(E, 0);
1288 auto *N = newSDNode<GlobalAddressSDNode>(
1289 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1290 CSEMap.InsertNode(N, IP);
1292 return SDValue(N, 0);
1295 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1296 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1297 FoldingSetNodeID ID;
1298 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1301 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1302 return SDValue(E, 0);
1304 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1305 CSEMap.InsertNode(N, IP);
1307 return SDValue(N, 0);
1310 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1311 unsigned char TargetFlags) {
1312 assert((TargetFlags == 0 || isTarget) &&
1313 "Cannot set target flags on target-independent jump tables");
1314 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1315 FoldingSetNodeID ID;
1316 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1318 ID.AddInteger(TargetFlags);
1320 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1321 return SDValue(E, 0);
1323 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1324 CSEMap.InsertNode(N, IP);
1326 return SDValue(N, 0);
1329 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1330 unsigned Alignment, int Offset,
1332 unsigned char TargetFlags) {
1333 assert((TargetFlags == 0 || isTarget) &&
1334 "Cannot set target flags on target-independent globals");
1336 Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1337 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1338 FoldingSetNodeID ID;
1339 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1340 ID.AddInteger(Alignment);
1341 ID.AddInteger(Offset);
1343 ID.AddInteger(TargetFlags);
1345 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1346 return SDValue(E, 0);
1348 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1350 CSEMap.InsertNode(N, IP);
1352 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(all_of(Mask, [&](int M) { return M < (NElts * 2); }) &&
1490 "Index out of range");
1492 // Copy the mask so we can do any needed cleanup.
1493 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1495 // Canonicalize shuffle v, v -> v, undef
1498 for (int i = 0; i != NElts; ++i)
1499 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1502 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1504 commuteShuffle(N1, N2, MaskVec);
1506 // If shuffling a splat, try to blend the splat instead. We do this here so
1507 // that even when this arises during lowering we don't have to re-handle it.
1508 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1509 BitVector UndefElements;
1510 SDValue Splat = BV->getSplatValue(&UndefElements);
1514 for (int i = 0; i < NElts; ++i) {
1515 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1518 // If this input comes from undef, mark it as such.
1519 if (UndefElements[MaskVec[i] - Offset]) {
1524 // If we can blend a non-undef lane, use that instead.
1525 if (!UndefElements[i])
1526 MaskVec[i] = i + Offset;
1529 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1530 BlendSplat(N1BV, 0);
1531 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1532 BlendSplat(N2BV, NElts);
1534 // Canonicalize all index into lhs, -> shuffle lhs, undef
1535 // Canonicalize all index into rhs, -> shuffle rhs, undef
1536 bool AllLHS = true, AllRHS = true;
1537 bool N2Undef = N2.isUndef();
1538 for (int i = 0; i != NElts; ++i) {
1539 if (MaskVec[i] >= NElts) {
1544 } else if (MaskVec[i] >= 0) {
1548 if (AllLHS && AllRHS)
1549 return getUNDEF(VT);
1550 if (AllLHS && !N2Undef)
1554 commuteShuffle(N1, N2, MaskVec);
1556 // Reset our undef status after accounting for the mask.
1557 N2Undef = N2.isUndef();
1558 // Re-check whether both sides ended up undef.
1559 if (N1.isUndef() && N2Undef)
1560 return getUNDEF(VT);
1562 // If Identity shuffle return that node.
1563 bool Identity = true, AllSame = true;
1564 for (int i = 0; i != NElts; ++i) {
1565 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1566 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1568 if (Identity && NElts)
1571 // Shuffling a constant splat doesn't change the result.
1575 // Look through any bitcasts. We check that these don't change the number
1576 // (and size) of elements and just changes their types.
1577 while (V.getOpcode() == ISD::BITCAST)
1578 V = V->getOperand(0);
1580 // A splat should always show up as a build vector node.
1581 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1582 BitVector UndefElements;
1583 SDValue Splat = BV->getSplatValue(&UndefElements);
1584 // If this is a splat of an undef, shuffling it is also undef.
1585 if (Splat && Splat.isUndef())
1586 return getUNDEF(VT);
1589 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1591 // We only have a splat which can skip shuffles if there is a splatted
1592 // value and no undef lanes rearranged by the shuffle.
1593 if (Splat && UndefElements.none()) {
1594 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1595 // number of elements match or the value splatted is a zero constant.
1598 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1599 if (C->isNullValue())
1603 // If the shuffle itself creates a splat, build the vector directly.
1604 if (AllSame && SameNumElts) {
1605 EVT BuildVT = BV->getValueType(0);
1606 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1607 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1609 // We may have jumped through bitcasts, so the type of the
1610 // BUILD_VECTOR may not match the type of the shuffle.
1612 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1618 FoldingSetNodeID ID;
1619 SDValue Ops[2] = { N1, N2 };
1620 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1621 for (int i = 0; i != NElts; ++i)
1622 ID.AddInteger(MaskVec[i]);
1625 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1626 return SDValue(E, 0);
1628 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1629 // SDNode doesn't have access to it. This memory will be "leaked" when
1630 // the node is deallocated, but recovered when the NodeAllocator is released.
1631 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1632 std::copy(MaskVec.begin(), MaskVec.end(), MaskAlloc);
1634 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1635 dl.getDebugLoc(), MaskAlloc);
1636 createOperands(N, Ops);
1638 CSEMap.InsertNode(N, IP);
1640 return SDValue(N, 0);
1643 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1644 MVT VT = SV.getSimpleValueType(0);
1645 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1646 ShuffleVectorSDNode::commuteMask(MaskVec);
1648 SDValue Op0 = SV.getOperand(0);
1649 SDValue Op1 = SV.getOperand(1);
1650 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1653 SDValue SelectionDAG::getConvertRndSat(EVT VT, const SDLoc &dl, SDValue Val,
1654 SDValue DTy, SDValue STy, SDValue Rnd,
1655 SDValue Sat, ISD::CvtCode Code) {
1656 // If the src and dest types are the same and the conversion is between
1657 // integer types of the same sign or two floats, no conversion is necessary.
1659 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1662 FoldingSetNodeID ID;
1663 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1664 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), Ops);
1666 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1667 return SDValue(E, 0);
1670 newSDNode<CvtRndSatSDNode>(VT, dl.getIROrder(), dl.getDebugLoc(), Code);
1671 createOperands(N, Ops);
1673 CSEMap.InsertNode(N, IP);
1675 return SDValue(N, 0);
1678 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1679 FoldingSetNodeID ID;
1680 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1681 ID.AddInteger(RegNo);
1683 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1684 return SDValue(E, 0);
1686 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1687 CSEMap.InsertNode(N, IP);
1689 return SDValue(N, 0);
1692 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1693 FoldingSetNodeID ID;
1694 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1695 ID.AddPointer(RegMask);
1697 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1698 return SDValue(E, 0);
1700 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1701 CSEMap.InsertNode(N, IP);
1703 return SDValue(N, 0);
1706 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1708 FoldingSetNodeID ID;
1709 SDValue Ops[] = { Root };
1710 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops);
1711 ID.AddPointer(Label);
1713 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1714 return SDValue(E, 0);
1716 auto *N = newSDNode<EHLabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1717 createOperands(N, Ops);
1719 CSEMap.InsertNode(N, IP);
1721 return SDValue(N, 0);
1724 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1727 unsigned char TargetFlags) {
1728 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1730 FoldingSetNodeID ID;
1731 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1733 ID.AddInteger(Offset);
1734 ID.AddInteger(TargetFlags);
1736 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1737 return SDValue(E, 0);
1739 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1740 CSEMap.InsertNode(N, IP);
1742 return SDValue(N, 0);
1745 SDValue SelectionDAG::getSrcValue(const Value *V) {
1746 assert((!V || V->getType()->isPointerTy()) &&
1747 "SrcValue is not a pointer?");
1749 FoldingSetNodeID ID;
1750 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1754 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1755 return SDValue(E, 0);
1757 auto *N = newSDNode<SrcValueSDNode>(V);
1758 CSEMap.InsertNode(N, IP);
1760 return SDValue(N, 0);
1763 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1764 FoldingSetNodeID ID;
1765 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1769 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1770 return SDValue(E, 0);
1772 auto *N = newSDNode<MDNodeSDNode>(MD);
1773 CSEMap.InsertNode(N, IP);
1775 return SDValue(N, 0);
1778 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1779 if (VT == V.getValueType())
1782 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1785 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1786 unsigned SrcAS, unsigned DestAS) {
1787 SDValue Ops[] = {Ptr};
1788 FoldingSetNodeID ID;
1789 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1790 ID.AddInteger(SrcAS);
1791 ID.AddInteger(DestAS);
1794 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1795 return SDValue(E, 0);
1797 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1799 createOperands(N, Ops);
1801 CSEMap.InsertNode(N, IP);
1803 return SDValue(N, 0);
1806 /// getShiftAmountOperand - Return the specified value casted to
1807 /// the target's desired shift amount type.
1808 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1809 EVT OpTy = Op.getValueType();
1810 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1811 if (OpTy == ShTy || OpTy.isVector()) return Op;
1813 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1816 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1818 const TargetLowering &TLI = getTargetLoweringInfo();
1819 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1820 EVT VT = Node->getValueType(0);
1821 SDValue Tmp1 = Node->getOperand(0);
1822 SDValue Tmp2 = Node->getOperand(1);
1823 unsigned Align = Node->getConstantOperandVal(3);
1825 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1826 Tmp2, MachinePointerInfo(V));
1827 SDValue VAList = VAListLoad;
1829 if (Align > TLI.getMinStackArgumentAlignment()) {
1830 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1832 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1833 getConstant(Align - 1, dl, VAList.getValueType()));
1835 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1836 getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1839 // Increment the pointer, VAList, to the next vaarg
1840 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1841 getConstant(getDataLayout().getTypeAllocSize(
1842 VT.getTypeForEVT(*getContext())),
1843 dl, VAList.getValueType()));
1844 // Store the incremented VAList to the legalized pointer
1846 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1847 // Load the actual argument out of the pointer VAList
1848 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1851 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1853 const TargetLowering &TLI = getTargetLoweringInfo();
1854 // This defaults to loading a pointer from the input and storing it to the
1855 // output, returning the chain.
1856 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1857 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1859 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1860 Node->getOperand(2), MachinePointerInfo(VS));
1861 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1862 MachinePointerInfo(VD));
1865 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1866 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1867 unsigned ByteSize = VT.getStoreSize();
1868 Type *Ty = VT.getTypeForEVT(*getContext());
1869 unsigned StackAlign =
1870 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1872 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1873 return getFrameIndex(FrameIdx, TLI->getPointerTy(getDataLayout()));
1876 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1877 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1878 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1879 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1880 const DataLayout &DL = getDataLayout();
1882 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1884 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1885 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1886 return getFrameIndex(FrameIdx, TLI->getPointerTy(getDataLayout()));
1889 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1890 ISD::CondCode Cond, const SDLoc &dl) {
1891 // These setcc operations always fold.
1895 case ISD::SETFALSE2: return getConstant(0, dl, VT);
1897 case ISD::SETTRUE2: {
1898 TargetLowering::BooleanContent Cnt =
1899 TLI->getBooleanContents(N1->getValueType(0));
1901 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1915 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1919 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1920 const APInt &C2 = N2C->getAPIntValue();
1921 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1922 const APInt &C1 = N1C->getAPIntValue();
1925 default: llvm_unreachable("Unknown integer setcc!");
1926 case ISD::SETEQ: return getConstant(C1 == C2, dl, VT);
1927 case ISD::SETNE: return getConstant(C1 != C2, dl, VT);
1928 case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT);
1929 case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT);
1930 case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT);
1931 case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT);
1932 case ISD::SETLT: return getConstant(C1.slt(C2), dl, VT);
1933 case ISD::SETGT: return getConstant(C1.sgt(C2), dl, VT);
1934 case ISD::SETLE: return getConstant(C1.sle(C2), dl, VT);
1935 case ISD::SETGE: return getConstant(C1.sge(C2), dl, VT);
1939 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1940 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1941 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1944 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1945 return getUNDEF(VT);
1947 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT);
1948 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1949 return getUNDEF(VT);
1951 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1952 R==APFloat::cmpLessThan, dl, VT);
1953 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1954 return getUNDEF(VT);
1956 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT);
1957 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1958 return getUNDEF(VT);
1960 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT);
1961 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1962 return getUNDEF(VT);
1964 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1965 R==APFloat::cmpEqual, dl, VT);
1966 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1967 return getUNDEF(VT);
1969 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1970 R==APFloat::cmpEqual, dl, VT);
1971 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, dl, VT);
1972 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, dl, VT);
1973 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1974 R==APFloat::cmpEqual, dl, VT);
1975 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT);
1976 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1977 R==APFloat::cmpLessThan, dl, VT);
1978 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1979 R==APFloat::cmpUnordered, dl, VT);
1980 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT);
1981 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT);
1984 // Ensure that the constant occurs on the RHS.
1985 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1986 MVT CompVT = N1.getValueType().getSimpleVT();
1987 if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
1990 return getSetCC(dl, VT, N2, N1, SwappedCond);
1994 // Could not fold it.
1998 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1999 /// use this predicate to simplify operations downstream.
2000 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2001 // This predicate is not safe for vector operations.
2002 if (Op.getValueType().isVector())
2005 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
2006 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
2009 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2010 /// this predicate to simplify operations downstream. Mask is known to be zero
2011 /// for bits that V cannot have.
2012 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
2013 unsigned Depth) const {
2014 APInt KnownZero, KnownOne;
2015 computeKnownBits(Op, KnownZero, KnownOne, Depth);
2016 return (KnownZero & Mask) == Mask;
2019 /// Determine which bits of Op are known to be either zero or one and return
2020 /// them in the KnownZero/KnownOne bitsets.
2021 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero,
2022 APInt &KnownOne, unsigned Depth) const {
2023 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
2025 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
2027 return; // Limit search depth.
2029 APInt KnownZero2, KnownOne2;
2031 switch (Op.getOpcode()) {
2033 // We know all of the bits for a constant!
2034 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
2035 KnownZero = ~KnownOne;
2038 // If either the LHS or the RHS are Zero, the result is zero.
2039 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2040 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2042 // Output known-1 bits are only known if set in both the LHS & RHS.
2043 KnownOne &= KnownOne2;
2044 // Output known-0 are known to be clear if zero in either the LHS | RHS.
2045 KnownZero |= KnownZero2;
2048 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2049 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2051 // Output known-0 bits are only known if clear in both the LHS & RHS.
2052 KnownZero &= KnownZero2;
2053 // Output known-1 are known to be set if set in either the LHS | RHS.
2054 KnownOne |= KnownOne2;
2057 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2058 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2060 // Output known-0 bits are known if clear or set in both the LHS & RHS.
2061 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
2062 // Output known-1 are known to be set if set in only one of the LHS, RHS.
2063 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
2064 KnownZero = KnownZeroOut;
2068 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2069 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2071 // If low bits are zero in either operand, output low known-0 bits.
2072 // Also compute a conserative estimate for high known-0 bits.
2073 // More trickiness is possible, but this is sufficient for the
2074 // interesting case of alignment computation.
2075 KnownOne.clearAllBits();
2076 unsigned TrailZ = KnownZero.countTrailingOnes() +
2077 KnownZero2.countTrailingOnes();
2078 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
2079 KnownZero2.countLeadingOnes(),
2080 BitWidth) - BitWidth;
2082 TrailZ = std::min(TrailZ, BitWidth);
2083 LeadZ = std::min(LeadZ, BitWidth);
2084 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
2085 APInt::getHighBitsSet(BitWidth, LeadZ);
2089 // For the purposes of computing leading zeros we can conservatively
2090 // treat a udiv as a logical right shift by the power of 2 known to
2091 // be less than the denominator.
2092 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2093 unsigned LeadZ = KnownZero2.countLeadingOnes();
2095 KnownOne2.clearAllBits();
2096 KnownZero2.clearAllBits();
2097 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2098 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
2099 if (RHSUnknownLeadingOnes != BitWidth)
2100 LeadZ = std::min(BitWidth,
2101 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
2103 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
2107 computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1);
2108 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2110 // Only known if known in both the LHS and RHS.
2111 KnownOne &= KnownOne2;
2112 KnownZero &= KnownZero2;
2114 case ISD::SELECT_CC:
2115 computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1);
2116 computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1);
2118 // Only known if known in both the LHS and RHS.
2119 KnownOne &= KnownOne2;
2120 KnownZero &= KnownZero2;
2128 if (Op.getResNo() != 1)
2130 // The boolean result conforms to getBooleanContents.
2131 // If we know the result of a setcc has the top bits zero, use this info.
2132 // We know that we have an integer-based boolean since these operations
2133 // are only available for integer.
2134 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2135 TargetLowering::ZeroOrOneBooleanContent &&
2137 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
2140 // If we know the result of a setcc has the top bits zero, use this info.
2141 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2142 TargetLowering::ZeroOrOneBooleanContent &&
2144 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
2147 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
2148 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2149 unsigned ShAmt = SA->getZExtValue();
2151 // If the shift count is an invalid immediate, don't do anything.
2152 if (ShAmt >= BitWidth)
2155 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2156 KnownZero <<= ShAmt;
2158 // low bits known zero.
2159 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
2163 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
2164 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2165 unsigned ShAmt = SA->getZExtValue();
2167 // If the shift count is an invalid immediate, don't do anything.
2168 if (ShAmt >= BitWidth)
2171 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2172 KnownZero = KnownZero.lshr(ShAmt);
2173 KnownOne = KnownOne.lshr(ShAmt);
2175 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
2176 KnownZero |= HighBits; // High bits known zero.
2180 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2181 unsigned ShAmt = SA->getZExtValue();
2183 // If the shift count is an invalid immediate, don't do anything.
2184 if (ShAmt >= BitWidth)
2187 // If any of the demanded bits are produced by the sign extension, we also
2188 // demand the input sign bit.
2189 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
2191 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2192 KnownZero = KnownZero.lshr(ShAmt);
2193 KnownOne = KnownOne.lshr(ShAmt);
2195 // Handle the sign bits.
2196 APInt SignBit = APInt::getSignBit(BitWidth);
2197 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
2199 if (KnownZero.intersects(SignBit)) {
2200 KnownZero |= HighBits; // New bits are known zero.
2201 } else if (KnownOne.intersects(SignBit)) {
2202 KnownOne |= HighBits; // New bits are known one.
2206 case ISD::SIGN_EXTEND_INREG: {
2207 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2208 unsigned EBits = EVT.getScalarType().getSizeInBits();
2210 // Sign extension. Compute the demanded bits in the result that are not
2211 // present in the input.
2212 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2214 APInt InSignBit = APInt::getSignBit(EBits);
2215 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2217 // If the sign extended bits are demanded, we know that the sign
2219 InSignBit = InSignBit.zext(BitWidth);
2220 if (NewBits.getBoolValue())
2221 InputDemandedBits |= InSignBit;
2223 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2224 KnownOne &= InputDemandedBits;
2225 KnownZero &= InputDemandedBits;
2227 // If the sign bit of the input is known set or clear, then we know the
2228 // top bits of the result.
2229 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
2230 KnownZero |= NewBits;
2231 KnownOne &= ~NewBits;
2232 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
2233 KnownOne |= NewBits;
2234 KnownZero &= ~NewBits;
2235 } else { // Input sign bit unknown
2236 KnownZero &= ~NewBits;
2237 KnownOne &= ~NewBits;
2242 case ISD::CTTZ_ZERO_UNDEF:
2244 case ISD::CTLZ_ZERO_UNDEF:
2246 unsigned LowBits = Log2_32(BitWidth)+1;
2247 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
2248 KnownOne.clearAllBits();
2252 LoadSDNode *LD = cast<LoadSDNode>(Op);
2253 // If this is a ZEXTLoad and we are looking at the loaded value.
2254 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2255 EVT VT = LD->getMemoryVT();
2256 unsigned MemBits = VT.getScalarType().getSizeInBits();
2257 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
2258 } else if (const MDNode *Ranges = LD->getRanges()) {
2259 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2260 computeKnownBitsFromRangeMetadata(*Ranges, KnownZero, KnownOne);
2264 case ISD::ZERO_EXTEND: {
2265 EVT InVT = Op.getOperand(0).getValueType();
2266 unsigned InBits = InVT.getScalarType().getSizeInBits();
2267 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
2268 KnownZero = KnownZero.trunc(InBits);
2269 KnownOne = KnownOne.trunc(InBits);
2270 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2271 KnownZero = KnownZero.zext(BitWidth);
2272 KnownOne = KnownOne.zext(BitWidth);
2273 KnownZero |= NewBits;
2276 case ISD::SIGN_EXTEND: {
2277 EVT InVT = Op.getOperand(0).getValueType();
2278 unsigned InBits = InVT.getScalarType().getSizeInBits();
2279 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
2281 KnownZero = KnownZero.trunc(InBits);
2282 KnownOne = KnownOne.trunc(InBits);
2283 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2285 // Note if the sign bit is known to be zero or one.
2286 bool SignBitKnownZero = KnownZero.isNegative();
2287 bool SignBitKnownOne = KnownOne.isNegative();
2289 KnownZero = KnownZero.zext(BitWidth);
2290 KnownOne = KnownOne.zext(BitWidth);
2292 // If the sign bit is known zero or one, the top bits match.
2293 if (SignBitKnownZero)
2294 KnownZero |= NewBits;
2295 else if (SignBitKnownOne)
2296 KnownOne |= NewBits;
2299 case ISD::ANY_EXTEND: {
2300 EVT InVT = Op.getOperand(0).getValueType();
2301 unsigned InBits = InVT.getScalarType().getSizeInBits();
2302 KnownZero = KnownZero.trunc(InBits);
2303 KnownOne = KnownOne.trunc(InBits);
2304 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2305 KnownZero = KnownZero.zext(BitWidth);
2306 KnownOne = KnownOne.zext(BitWidth);
2309 case ISD::TRUNCATE: {
2310 EVT InVT = Op.getOperand(0).getValueType();
2311 unsigned InBits = InVT.getScalarType().getSizeInBits();
2312 KnownZero = KnownZero.zext(InBits);
2313 KnownOne = KnownOne.zext(InBits);
2314 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2315 KnownZero = KnownZero.trunc(BitWidth);
2316 KnownOne = KnownOne.trunc(BitWidth);
2319 case ISD::AssertZext: {
2320 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2321 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2322 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2323 KnownZero |= (~InMask);
2324 KnownOne &= (~KnownZero);
2328 // All bits are zero except the low bit.
2329 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
2333 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
2334 // We know that the top bits of C-X are clear if X contains less bits
2335 // than C (i.e. no wrap-around can happen). For example, 20-X is
2336 // positive if we can prove that X is >= 0 and < 16.
2337 if (CLHS->getAPIntValue().isNonNegative()) {
2338 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2339 // NLZ can't be BitWidth with no sign bit
2340 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2341 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2343 // If all of the MaskV bits are known to be zero, then we know the
2344 // output top bits are zero, because we now know that the output is
2346 if ((KnownZero2 & MaskV) == MaskV) {
2347 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2348 // Top bits known zero.
2349 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
2357 // Output known-0 bits are known if clear or set in both the low clear bits
2358 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2359 // low 3 bits clear.
2360 // Output known-0 bits are also known if the top bits of each input are
2361 // known to be clear. For example, if one input has the top 10 bits clear
2362 // and the other has the top 8 bits clear, we know the top 7 bits of the
2363 // output must be clear.
2364 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2365 unsigned KnownZeroHigh = KnownZero2.countLeadingOnes();
2366 unsigned KnownZeroLow = KnownZero2.countTrailingOnes();
2368 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2369 KnownZeroHigh = std::min(KnownZeroHigh,
2370 KnownZero2.countLeadingOnes());
2371 KnownZeroLow = std::min(KnownZeroLow,
2372 KnownZero2.countTrailingOnes());
2374 if (Op.getOpcode() == ISD::ADD) {
2375 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroLow);
2376 if (KnownZeroHigh > 1)
2377 KnownZero |= APInt::getHighBitsSet(BitWidth, KnownZeroHigh - 1);
2381 // With ADDE, a carry bit may be added in, so we can only use this
2382 // information if we know (at least) that the low two bits are clear. We
2383 // then return to the caller that the low bit is unknown but that other bits
2385 if (KnownZeroLow >= 2) // ADDE
2386 KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroLow);
2390 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2391 const APInt &RA = Rem->getAPIntValue().abs();
2392 if (RA.isPowerOf2()) {
2393 APInt LowBits = RA - 1;
2394 computeKnownBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1);
2396 // The low bits of the first operand are unchanged by the srem.
2397 KnownZero = KnownZero2 & LowBits;
2398 KnownOne = KnownOne2 & LowBits;
2400 // If the first operand is non-negative or has all low bits zero, then
2401 // the upper bits are all zero.
2402 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2403 KnownZero |= ~LowBits;
2405 // If the first operand is negative and not all low bits are zero, then
2406 // the upper bits are all one.
2407 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2408 KnownOne |= ~LowBits;
2409 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2414 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2415 const APInt &RA = Rem->getAPIntValue();
2416 if (RA.isPowerOf2()) {
2417 APInt LowBits = (RA - 1);
2418 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth + 1);
2420 // The upper bits are all zero, the lower ones are unchanged.
2421 KnownZero = KnownZero2 | ~LowBits;
2422 KnownOne = KnownOne2 & LowBits;
2427 // Since the result is less than or equal to either operand, any leading
2428 // zero bits in either operand must also exist in the result.
2429 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2430 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2432 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2433 KnownZero2.countLeadingOnes());
2434 KnownOne.clearAllBits();
2435 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
2438 case ISD::EXTRACT_ELEMENT: {
2439 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2440 const unsigned Index =
2441 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2442 const unsigned BitWidth = Op.getValueType().getSizeInBits();
2444 // Remove low part of known bits mask
2445 KnownZero = KnownZero.getHiBits(KnownZero.getBitWidth() - Index * BitWidth);
2446 KnownOne = KnownOne.getHiBits(KnownOne.getBitWidth() - Index * BitWidth);
2448 // Remove high part of known bit mask
2449 KnownZero = KnownZero.trunc(BitWidth);
2450 KnownOne = KnownOne.trunc(BitWidth);
2454 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2455 KnownZero = KnownZero2.byteSwap();
2456 KnownOne = KnownOne2.byteSwap();
2463 APInt Op0Zero, Op0One;
2464 APInt Op1Zero, Op1One;
2465 computeKnownBits(Op.getOperand(0), Op0Zero, Op0One, Depth);
2466 computeKnownBits(Op.getOperand(1), Op1Zero, Op1One, Depth);
2468 KnownZero = Op0Zero & Op1Zero;
2469 KnownOne = Op0One & Op1One;
2472 case ISD::FrameIndex:
2473 case ISD::TargetFrameIndex:
2474 if (unsigned Align = InferPtrAlignment(Op)) {
2475 // The low bits are known zero if the pointer is aligned.
2476 KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align));
2482 if (Op.getOpcode() < ISD::BUILTIN_OP_END)
2485 case ISD::INTRINSIC_WO_CHAIN:
2486 case ISD::INTRINSIC_W_CHAIN:
2487 case ISD::INTRINSIC_VOID:
2488 // Allow the target to implement this method for its nodes.
2489 TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth);
2493 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2496 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
2497 // A left-shift of a constant one will have exactly one bit set because
2498 // shifting the bit off the end is undefined.
2499 if (Val.getOpcode() == ISD::SHL) {
2500 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0));
2501 if (C && C->getAPIntValue() == 1)
2505 // Similarly, a logical right-shift of a constant sign-bit will have exactly
2507 if (Val.getOpcode() == ISD::SRL) {
2508 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0));
2509 if (C && C->getAPIntValue().isSignBit())
2513 // More could be done here, though the above checks are enough
2514 // to handle some common cases.
2516 // Fall back to computeKnownBits to catch other known cases.
2517 EVT OpVT = Val.getValueType();
2518 unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
2519 APInt KnownZero, KnownOne;
2520 computeKnownBits(Val, KnownZero, KnownOne);
2521 return (KnownZero.countPopulation() == BitWidth - 1) &&
2522 (KnownOne.countPopulation() == 1);
2525 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
2526 EVT VT = Op.getValueType();
2527 assert(VT.isInteger() && "Invalid VT!");
2528 unsigned VTBits = VT.getScalarType().getSizeInBits();
2530 unsigned FirstAnswer = 1;
2533 return 1; // Limit search depth.
2535 switch (Op.getOpcode()) {
2537 case ISD::AssertSext:
2538 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2539 return VTBits-Tmp+1;
2540 case ISD::AssertZext:
2541 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2544 case ISD::Constant: {
2545 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2546 return Val.getNumSignBits();
2549 case ISD::SIGN_EXTEND:
2551 VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2552 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2554 case ISD::SIGN_EXTEND_INREG:
2555 // Max of the input and what this extends.
2557 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
2560 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2561 return std::max(Tmp, Tmp2);
2564 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2565 // SRA X, C -> adds C sign bits.
2566 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2567 Tmp += C->getZExtValue();
2568 if (Tmp > VTBits) Tmp = VTBits;
2572 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2573 // shl destroys sign bits.
2574 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2575 if (C->getZExtValue() >= VTBits || // Bad shift.
2576 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2577 return Tmp - C->getZExtValue();
2582 case ISD::XOR: // NOT is handled here.
2583 // Logical binary ops preserve the number of sign bits at the worst.
2584 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2586 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2587 FirstAnswer = std::min(Tmp, Tmp2);
2588 // We computed what we know about the sign bits as our first
2589 // answer. Now proceed to the generic code that uses
2590 // computeKnownBits, and pick whichever answer is better.
2595 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2596 if (Tmp == 1) return 1; // Early out.
2597 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2598 return std::min(Tmp, Tmp2);
2599 case ISD::SELECT_CC:
2600 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2601 if (Tmp == 1) return 1; // Early out.
2602 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1);
2603 return std::min(Tmp, Tmp2);
2608 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
2610 return 1; // Early out.
2611 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
2612 return std::min(Tmp, Tmp2);
2619 if (Op.getResNo() != 1)
2621 // The boolean result conforms to getBooleanContents. Fall through.
2622 // If setcc returns 0/-1, all bits are sign bits.
2623 // We know that we have an integer-based boolean since these operations
2624 // are only available for integer.
2625 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2626 TargetLowering::ZeroOrNegativeOneBooleanContent)
2630 // If setcc returns 0/-1, all bits are sign bits.
2631 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2632 TargetLowering::ZeroOrNegativeOneBooleanContent)
2637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2638 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2640 // Handle rotate right by N like a rotate left by 32-N.
2641 if (Op.getOpcode() == ISD::ROTR)
2642 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2644 // If we aren't rotating out all of the known-in sign bits, return the
2645 // number that are left. This handles rotl(sext(x), 1) for example.
2646 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2647 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2651 // Add can have at most one carry bit. Thus we know that the output
2652 // is, at worst, one more bit than the inputs.
2653 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2654 if (Tmp == 1) return 1; // Early out.
2656 // Special case decrementing a value (ADD X, -1):
2657 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2658 if (CRHS->isAllOnesValue()) {
2659 APInt KnownZero, KnownOne;
2660 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2662 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2664 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2667 // If we are subtracting one from a positive number, there is no carry
2668 // out of the result.
2669 if (KnownZero.isNegative())
2673 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2674 if (Tmp2 == 1) return 1;
2675 return std::min(Tmp, Tmp2)-1;
2678 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2679 if (Tmp2 == 1) return 1;
2682 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2683 if (CLHS->isNullValue()) {
2684 APInt KnownZero, KnownOne;
2685 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2686 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2688 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2691 // If the input is known to be positive (the sign bit is known clear),
2692 // the output of the NEG has the same number of sign bits as the input.
2693 if (KnownZero.isNegative())
2696 // Otherwise, we treat this like a SUB.
2699 // Sub can have at most one carry bit. Thus we know that the output
2700 // is, at worst, one more bit than the inputs.
2701 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2702 if (Tmp == 1) return 1; // Early out.
2703 return std::min(Tmp, Tmp2)-1;
2705 // FIXME: it's tricky to do anything useful for this, but it is an important
2706 // case for targets like X86.
2708 case ISD::EXTRACT_ELEMENT: {
2709 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2710 const int BitWidth = Op.getValueType().getSizeInBits();
2712 Op.getOperand(0).getValueType().getSizeInBits() / BitWidth;
2714 // Get reverse index (starting from 1), Op1 value indexes elements from
2715 // little end. Sign starts at big end.
2716 const int rIndex = Items - 1 -
2717 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2719 // If the sign portion ends in our element the subtraction gives correct
2720 // result. Otherwise it gives either negative or > bitwidth result
2721 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
2725 // If we are looking at the loaded value of the SDNode.
2726 if (Op.getResNo() == 0) {
2727 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2728 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
2729 unsigned ExtType = LD->getExtensionType();
2732 case ISD::SEXTLOAD: // '17' bits known
2733 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2734 return VTBits-Tmp+1;
2735 case ISD::ZEXTLOAD: // '16' bits known
2736 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2742 // Allow the target to implement this method for its nodes.
2743 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2744 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2745 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2746 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2747 unsigned NumBits = TLI->ComputeNumSignBitsForTargetNode(Op, *this, Depth);
2748 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2751 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2752 // use this information.
2753 APInt KnownZero, KnownOne;
2754 computeKnownBits(Op, KnownZero, KnownOne, Depth);
2757 if (KnownZero.isNegative()) { // sign bit is 0
2759 } else if (KnownOne.isNegative()) { // sign bit is 1;
2766 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2767 // the number of identical bits in the top of the input value.
2769 Mask <<= Mask.getBitWidth()-VTBits;
2770 // Return # leading zeros. We use 'min' here in case Val was zero before
2771 // shifting. We don't want to return '64' as for an i32 "0".
2772 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2775 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
2776 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
2777 !isa<ConstantSDNode>(Op.getOperand(1)))
2780 if (Op.getOpcode() == ISD::OR &&
2781 !MaskedValueIsZero(Op.getOperand(0),
2782 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
2788 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2789 // If we're told that NaNs won't happen, assume they won't.
2790 if (getTarget().Options.NoNaNsFPMath)
2793 // If the value is a constant, we can obviously see if it is a NaN or not.
2794 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2795 return !C->getValueAPF().isNaN();
2797 // TODO: Recognize more cases here.
2802 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2803 // If the value is a constant, we can obviously see if it is a zero or not.
2804 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2805 return !C->isZero();
2807 // TODO: Recognize more cases here.
2808 switch (Op.getOpcode()) {
2811 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2812 return !C->isNullValue();
2819 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2820 // Check the obvious case.
2821 if (A == B) return true;
2823 // For for negative and positive zero.
2824 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2825 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2826 if (CA->isZero() && CB->isZero()) return true;
2828 // Otherwise they may not be equal.
2832 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
2833 assert(A.getValueType() == B.getValueType() &&
2834 "Values must have the same type");
2837 computeKnownBits(A, AZero, AOne);
2838 computeKnownBits(B, BZero, BOne);
2839 return (AZero | BZero).isAllOnesValue();
2842 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
2843 ArrayRef<SDValue> Ops,
2844 llvm::SelectionDAG &DAG) {
2845 if (Ops.size() == 1)
2848 // Concat of UNDEFs is UNDEF.
2849 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
2850 return DAG.getUNDEF(VT);
2852 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
2853 // simplified to one big BUILD_VECTOR.
2854 // FIXME: Add support for SCALAR_TO_VECTOR as well.
2855 EVT SVT = VT.getScalarType();
2856 SmallVector<SDValue, 16> Elts;
2857 for (SDValue Op : Ops) {
2858 EVT OpVT = Op.getValueType();
2860 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
2861 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
2862 Elts.append(Op->op_begin(), Op->op_end());
2867 // BUILD_VECTOR requires all inputs to be of the same type, find the
2868 // maximum type and extend them all.
2869 for (SDValue Op : Elts)
2870 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
2872 if (SVT.bitsGT(VT.getScalarType()))
2873 for (SDValue &Op : Elts)
2874 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
2875 ? DAG.getZExtOrTrunc(Op, DL, SVT)
2876 : DAG.getSExtOrTrunc(Op, DL, SVT);
2878 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts);
2881 /// Gets or creates the specified node.
2882 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
2883 FoldingSetNodeID ID;
2884 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
2886 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
2887 return SDValue(E, 0);
2889 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
2891 CSEMap.InsertNode(N, IP);
2894 return SDValue(N, 0);
2897 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
2899 // Constant fold unary operations with an integer constant operand. Even
2900 // opaque constant will be folded, because the folding of unary operations
2901 // doesn't create new constants with different values. Nevertheless, the
2902 // opaque flag is preserved during folding to prevent future folding with
2904 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
2905 const APInt &Val = C->getAPIntValue();
2908 case ISD::SIGN_EXTEND:
2909 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
2910 C->isTargetOpcode(), C->isOpaque());
2911 case ISD::ANY_EXTEND:
2912 case ISD::ZERO_EXTEND:
2914 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
2915 C->isTargetOpcode(), C->isOpaque());
2916 case ISD::UINT_TO_FP:
2917 case ISD::SINT_TO_FP: {
2918 APFloat apf(EVTToAPFloatSemantics(VT),
2919 APInt::getNullValue(VT.getSizeInBits()));
2920 (void)apf.convertFromAPInt(Val,
2921 Opcode==ISD::SINT_TO_FP,
2922 APFloat::rmNearestTiesToEven);
2923 return getConstantFP(apf, DL, VT);
2926 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
2927 return getConstantFP(APFloat(APFloat::IEEEhalf, Val), DL, VT);
2928 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2929 return getConstantFP(APFloat(APFloat::IEEEsingle, Val), DL, VT);
2930 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2931 return getConstantFP(APFloat(APFloat::IEEEdouble, Val), DL, VT);
2932 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
2933 return getConstantFP(APFloat(APFloat::IEEEquad, Val), DL, VT);
2936 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
2939 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
2942 case ISD::CTLZ_ZERO_UNDEF:
2943 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
2946 case ISD::CTTZ_ZERO_UNDEF:
2947 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
2952 // Constant fold unary operations with a floating point constant operand.
2953 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
2954 APFloat V = C->getValueAPF(); // make copy
2958 return getConstantFP(V, DL, VT);
2961 return getConstantFP(V, DL, VT);
2963 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
2964 if (fs == APFloat::opOK || fs == APFloat::opInexact)
2965 return getConstantFP(V, DL, VT);
2969 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
2970 if (fs == APFloat::opOK || fs == APFloat::opInexact)
2971 return getConstantFP(V, DL, VT);
2975 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
2976 if (fs == APFloat::opOK || fs == APFloat::opInexact)
2977 return getConstantFP(V, DL, VT);
2980 case ISD::FP_EXTEND: {
2982 // This can return overflow, underflow, or inexact; we don't care.
2983 // FIXME need to be more flexible about rounding mode.
2984 (void)V.convert(EVTToAPFloatSemantics(VT),
2985 APFloat::rmNearestTiesToEven, &ignored);
2986 return getConstantFP(V, DL, VT);
2988 case ISD::FP_TO_SINT:
2989 case ISD::FP_TO_UINT: {
2992 static_assert(integerPartWidth >= 64, "APFloat parts too small!");
2993 // FIXME need to be more flexible about rounding mode.
2994 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2995 Opcode==ISD::FP_TO_SINT,
2996 APFloat::rmTowardZero, &ignored);
2997 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2999 APInt api(VT.getSizeInBits(), x);
3000 return getConstant(api, DL, VT);
3003 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
3004 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3005 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
3006 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
3007 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
3008 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
3013 // Constant fold unary operations with a vector integer or float operand.
3014 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
3015 if (BV->isConstant()) {
3018 // FIXME: Entirely reasonable to perform folding of other unary
3019 // operations here as the need arises.
3026 case ISD::FP_EXTEND:
3027 case ISD::FP_TO_SINT:
3028 case ISD::FP_TO_UINT:
3030 case ISD::UINT_TO_FP:
3031 case ISD::SINT_TO_FP:
3034 case ISD::CTLZ_ZERO_UNDEF:
3036 case ISD::CTTZ_ZERO_UNDEF:
3038 SDValue Ops = { Operand };
3039 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3046 unsigned OpOpcode = Operand.getNode()->getOpcode();
3048 case ISD::TokenFactor:
3049 case ISD::MERGE_VALUES:
3050 case ISD::CONCAT_VECTORS:
3051 return Operand; // Factor, merge or concat of one node? No need.
3052 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
3053 case ISD::FP_EXTEND:
3054 assert(VT.isFloatingPoint() &&
3055 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
3056 if (Operand.getValueType() == VT) return Operand; // noop conversion.
3057 assert((!VT.isVector() ||
3058 VT.getVectorNumElements() ==
3059 Operand.getValueType().getVectorNumElements()) &&
3060 "Vector element count mismatch!");
3061 assert(Operand.getValueType().bitsLT(VT) &&
3062 "Invalid fpext node, dst < src!");
3063 if (Operand.isUndef())
3064 return getUNDEF(VT);
3066 case ISD::SIGN_EXTEND:
3067 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3068 "Invalid SIGN_EXTEND!");
3069 if (Operand.getValueType() == VT) return Operand; // noop extension
3070 assert((!VT.isVector() ||
3071 VT.getVectorNumElements() ==
3072 Operand.getValueType().getVectorNumElements()) &&
3073 "Vector element count mismatch!");
3074 assert(Operand.getValueType().bitsLT(VT) &&
3075 "Invalid sext node, dst < src!");
3076 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
3077 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3078 else if (OpOpcode == ISD::UNDEF)
3079 // sext(undef) = 0, because the top bits will all be the same.
3080 return getConstant(0, DL, VT);
3082 case ISD::ZERO_EXTEND:
3083 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3084 "Invalid ZERO_EXTEND!");
3085 if (Operand.getValueType() == VT) return Operand; // noop extension
3086 assert((!VT.isVector() ||
3087 VT.getVectorNumElements() ==
3088 Operand.getValueType().getVectorNumElements()) &&
3089 "Vector element count mismatch!");
3090 assert(Operand.getValueType().bitsLT(VT) &&
3091 "Invalid zext node, dst < src!");
3092 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
3093 return getNode(ISD::ZERO_EXTEND, DL, VT,
3094 Operand.getNode()->getOperand(0));
3095 else if (OpOpcode == ISD::UNDEF)
3096 // zext(undef) = 0, because the top bits will be zero.
3097 return getConstant(0, DL, VT);
3099 case ISD::ANY_EXTEND:
3100 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3101 "Invalid ANY_EXTEND!");
3102 if (Operand.getValueType() == VT) return Operand; // noop extension
3103 assert((!VT.isVector() ||
3104 VT.getVectorNumElements() ==
3105 Operand.getValueType().getVectorNumElements()) &&
3106 "Vector element count mismatch!");
3107 assert(Operand.getValueType().bitsLT(VT) &&
3108 "Invalid anyext node, dst < src!");
3110 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3111 OpOpcode == ISD::ANY_EXTEND)
3112 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
3113 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3114 else if (OpOpcode == ISD::UNDEF)
3115 return getUNDEF(VT);
3117 // (ext (trunx x)) -> x
3118 if (OpOpcode == ISD::TRUNCATE) {
3119 SDValue OpOp = Operand.getNode()->getOperand(0);
3120 if (OpOp.getValueType() == VT)
3125 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
3126 "Invalid TRUNCATE!");
3127 if (Operand.getValueType() == VT) return Operand; // noop truncate
3128 assert((!VT.isVector() ||
3129 VT.getVectorNumElements() ==
3130 Operand.getValueType().getVectorNumElements()) &&
3131 "Vector element count mismatch!");
3132 assert(Operand.getValueType().bitsGT(VT) &&
3133 "Invalid truncate node, src < dst!");
3134 if (OpOpcode == ISD::TRUNCATE)
3135 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3136 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
3137 OpOpcode == ISD::ANY_EXTEND) {
3138 // If the source is smaller than the dest, we still need an extend.
3139 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
3140 .bitsLT(VT.getScalarType()))
3141 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
3142 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
3143 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
3144 return Operand.getNode()->getOperand(0);
3146 if (OpOpcode == ISD::UNDEF)
3147 return getUNDEF(VT);
3150 assert(VT.isInteger() && VT == Operand.getValueType() &&
3152 assert((VT.getScalarSizeInBits() % 16 == 0) &&
3153 "BSWAP types must be a multiple of 16 bits!");
3154 if (OpOpcode == ISD::UNDEF)
3155 return getUNDEF(VT);
3157 case ISD::BITREVERSE:
3158 assert(VT.isInteger() && VT == Operand.getValueType() &&
3159 "Invalid BITREVERSE!");
3160 if (OpOpcode == ISD::UNDEF)
3161 return getUNDEF(VT);
3164 // Basic sanity checking.
3165 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
3166 && "Cannot BITCAST between types of different sizes!");
3167 if (VT == Operand.getValueType()) return Operand; // noop conversion.
3168 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
3169 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
3170 if (OpOpcode == ISD::UNDEF)
3171 return getUNDEF(VT);
3173 case ISD::SCALAR_TO_VECTOR:
3174 assert(VT.isVector() && !Operand.getValueType().isVector() &&
3175 (VT.getVectorElementType() == Operand.getValueType() ||
3176 (VT.getVectorElementType().isInteger() &&
3177 Operand.getValueType().isInteger() &&
3178 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
3179 "Illegal SCALAR_TO_VECTOR node!");
3180 if (OpOpcode == ISD::UNDEF)
3181 return getUNDEF(VT);
3182 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
3183 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
3184 isa<ConstantSDNode>(Operand.getOperand(1)) &&
3185 Operand.getConstantOperandVal(1) == 0 &&
3186 Operand.getOperand(0).getValueType() == VT)
3187 return Operand.getOperand(0);
3190 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
3191 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
3192 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags?
3193 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
3194 Operand.getNode()->getOperand(0),
3195 &cast<BinaryWithFlagsSDNode>(Operand.getNode())->Flags);
3196 if (OpOpcode == ISD::FNEG) // --X -> X
3197 return Operand.getNode()->getOperand(0);
3200 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
3201 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
3206 SDVTList VTs = getVTList(VT);
3207 SDValue Ops[] = {Operand};
3208 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
3209 FoldingSetNodeID ID;
3210 AddNodeIDNode(ID, Opcode, VTs, Ops);
3212 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
3213 return SDValue(E, 0);
3215 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3216 createOperands(N, Ops);
3217 CSEMap.InsertNode(N, IP);
3219 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
3220 createOperands(N, Ops);
3224 return SDValue(N, 0);
3227 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
3230 case ISD::ADD: return std::make_pair(C1 + C2, true);
3231 case ISD::SUB: return std::make_pair(C1 - C2, true);
3232 case ISD::MUL: return std::make_pair(C1 * C2, true);
3233 case ISD::AND: return std::make_pair(C1 & C2, true);
3234 case ISD::OR: return std::make_pair(C1 | C2, true);
3235 case ISD::XOR: return std::make_pair(C1 ^ C2, true);
3236 case ISD::SHL: return std::make_pair(C1 << C2, true);
3237 case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
3238 case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
3239 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
3240 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
3241 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
3242 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
3243 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
3244 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
3246 if (!C2.getBoolValue())
3248 return std::make_pair(C1.udiv(C2), true);
3250 if (!C2.getBoolValue())
3252 return std::make_pair(C1.urem(C2), true);
3254 if (!C2.getBoolValue())
3256 return std::make_pair(C1.sdiv(C2), true);
3258 if (!C2.getBoolValue())
3260 return std::make_pair(C1.srem(C2), true);
3262 return std::make_pair(APInt(1, 0), false);
3265 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3266 EVT VT, const ConstantSDNode *Cst1,
3267 const ConstantSDNode *Cst2) {
3268 if (Cst1->isOpaque() || Cst2->isOpaque())
3271 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
3272 Cst2->getAPIntValue());
3275 return getConstant(Folded.first, DL, VT);
3278 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
3279 const GlobalAddressSDNode *GA,
3281 if (GA->getOpcode() != ISD::GlobalAddress)
3283 if (!TLI->isOffsetFoldingLegal(GA))
3285 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
3288 int64_t Offset = Cst2->getSExtValue();
3290 case ISD::ADD: break;
3291 case ISD::SUB: Offset = -uint64_t(Offset); break;
3292 default: return SDValue();
3294 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
3295 GA->getOffset() + uint64_t(Offset));
3298 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
3299 EVT VT, SDNode *Cst1,
3301 // If the opcode is a target-specific ISD node, there's nothing we can
3302 // do here and the operand rules may not line up with the below, so
3304 if (Opcode >= ISD::BUILTIN_OP_END)
3307 // Handle the case of two scalars.
3308 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
3309 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
3310 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
3311 assert((!Folded || !VT.isVector()) &&
3312 "Can't fold vectors ops with scalar operands");
3317 // fold (add Sym, c) -> Sym+c
3318 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
3319 return FoldSymbolOffset(Opcode, VT, GA, Cst2);
3320 if (isCommutativeBinOp(Opcode))
3321 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
3322 return FoldSymbolOffset(Opcode, VT, GA, Cst1);
3324 // For vectors extract each constant element into Inputs so we can constant
3325 // fold them individually.
3326 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
3327 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
3331 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
3333 EVT SVT = VT.getScalarType();
3334 SmallVector<SDValue, 4> Outputs;
3335 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
3336 ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
3337 ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I));
3338 if (!V1 || !V2) // Not a constant, bail.
3341 if (V1->isOpaque() || V2->isOpaque())
3344 // Avoid BUILD_VECTOR nodes that perform implicit truncation.
3345 // FIXME: This is valid and could be handled by truncating the APInts.
3346 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
3349 // Fold one vector element.
3350 std::pair<APInt, bool> Folded = FoldValue(Opcode, V1->getAPIntValue(),
3351 V2->getAPIntValue());
3354 Outputs.push_back(getConstant(Folded.first, DL, SVT));
3357 assert(VT.getVectorNumElements() == Outputs.size() &&
3358 "Vector size mismatch!");
3360 // We may have a vector type but a scalar result. Create a splat.
3361 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
3363 // Build a big vector out of the scalar elements we generated.
3364 return getBuildVector(VT, SDLoc(), Outputs);
3367 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
3368 const SDLoc &DL, EVT VT,
3369 ArrayRef<SDValue> Ops,
3370 const SDNodeFlags *Flags) {
3371 // If the opcode is a target-specific ISD node, there's nothing we can
3372 // do here and the operand rules may not line up with the below, so
3374 if (Opcode >= ISD::BUILTIN_OP_END)
3377 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
3381 unsigned NumElts = VT.getVectorNumElements();
3383 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
3384 return !Op.getValueType().isVector() ||
3385 Op.getValueType().getVectorNumElements() == NumElts;
3388 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
3389 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
3390 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
3391 (BV && BV->isConstant());
3394 // All operands must be vector types with the same number of elements as
3395 // the result type and must be either UNDEF or a build vector of constant
3396 // or UNDEF scalars.
3397 if (!std::all_of(Ops.begin(), Ops.end(), IsConstantBuildVectorOrUndef) ||
3398 !std::all_of(Ops.begin(), Ops.end(), IsScalarOrSameVectorSize))
3401 // If we are comparing vectors, then the result needs to be a i1 boolean
3402 // that is then sign-extended back to the legal result type.
3403 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
3405 // Find legal integer scalar type for constant promotion and
3406 // ensure that its scalar size is at least as large as source.
3407 EVT LegalSVT = VT.getScalarType();
3408 if (LegalSVT.isInteger()) {
3409 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3410 if (LegalSVT.bitsLT(VT.getScalarType()))
3414 // Constant fold each scalar lane separately.
3415 SmallVector<SDValue, 4> ScalarResults;
3416 for (unsigned i = 0; i != NumElts; i++) {
3417 SmallVector<SDValue, 4> ScalarOps;
3418 for (SDValue Op : Ops) {
3419 EVT InSVT = Op.getValueType().getScalarType();
3420 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
3422 // We've checked that this is UNDEF or a constant of some kind.
3424 ScalarOps.push_back(getUNDEF(InSVT));
3426 ScalarOps.push_back(Op);
3430 SDValue ScalarOp = InBV->getOperand(i);
3431 EVT ScalarVT = ScalarOp.getValueType();
3433 // Build vector (integer) scalar operands may need implicit
3434 // truncation - do this before constant folding.
3435 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
3436 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
3438 ScalarOps.push_back(ScalarOp);
3441 // Constant fold the scalar operands.
3442 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
3444 // Legalize the (integer) scalar constant if necessary.
3445 if (LegalSVT != SVT)
3446 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
3448 // Scalar folding only succeeded if the result is a constant or UNDEF.
3449 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
3450 ScalarResult.getOpcode() != ISD::ConstantFP)
3452 ScalarResults.push_back(ScalarResult);
3455 return getBuildVector(VT, DL, ScalarResults);
3458 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3459 SDValue N1, SDValue N2,
3460 const SDNodeFlags *Flags) {
3461 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3462 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3463 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3464 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3466 // Canonicalize constant to RHS if commutative.
3467 if (isCommutativeBinOp(Opcode)) {
3469 std::swap(N1C, N2C);
3471 } else if (N1CFP && !N2CFP) {
3472 std::swap(N1CFP, N2CFP);
3479 case ISD::TokenFactor:
3480 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
3481 N2.getValueType() == MVT::Other && "Invalid token factor!");
3482 // Fold trivial token factors.
3483 if (N1.getOpcode() == ISD::EntryToken) return N2;
3484 if (N2.getOpcode() == ISD::EntryToken) return N1;
3485 if (N1 == N2) return N1;
3487 case ISD::CONCAT_VECTORS: {
3488 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
3489 SDValue Ops[] = {N1, N2};
3490 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
3495 assert(VT.isInteger() && "This operator does not apply to FP types!");
3496 assert(N1.getValueType() == N2.getValueType() &&
3497 N1.getValueType() == VT && "Binary operator types must match!");
3498 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
3499 // worth handling here.
3500 if (N2C && N2C->isNullValue())
3502 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
3509 assert(VT.isInteger() && "This operator does not apply to FP types!");
3510 assert(N1.getValueType() == N2.getValueType() &&
3511 N1.getValueType() == VT && "Binary operator types must match!");
3512 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
3513 // it's worth handling here.
3514 if (N2C && N2C->isNullValue())
3528 assert(VT.isInteger() && "This operator does not apply to FP types!");
3529 assert(N1.getValueType() == N2.getValueType() &&
3530 N1.getValueType() == VT && "Binary operator types must match!");
3537 if (getTarget().Options.UnsafeFPMath) {
3538 if (Opcode == ISD::FADD) {
3540 if (N2CFP && N2CFP->getValueAPF().isZero())
3542 } else if (Opcode == ISD::FSUB) {
3544 if (N2CFP && N2CFP->getValueAPF().isZero())
3546 } else if (Opcode == ISD::FMUL) {
3548 if (N2CFP && N2CFP->isZero())
3551 if (N2CFP && N2CFP->isExactlyValue(1.0))
3555 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
3556 assert(N1.getValueType() == N2.getValueType() &&
3557 N1.getValueType() == VT && "Binary operator types must match!");
3559 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
3560 assert(N1.getValueType() == VT &&
3561 N1.getValueType().isFloatingPoint() &&
3562 N2.getValueType().isFloatingPoint() &&
3563 "Invalid FCOPYSIGN!");
3570 assert(VT == N1.getValueType() &&
3571 "Shift operators return type must be the same as their first arg");
3572 assert(VT.isInteger() && N2.getValueType().isInteger() &&
3573 "Shifts only work on integers");
3574 assert((!VT.isVector() || VT == N2.getValueType()) &&
3575 "Vector shift amounts must be in the same as their first arg");
3576 // Verify that the shift amount VT is bit enough to hold valid shift
3577 // amounts. This catches things like trying to shift an i1024 value by an
3578 // i8, which is easy to fall into in generic code that uses
3579 // TLI.getShiftAmount().
3580 assert(N2.getValueType().getSizeInBits() >=
3581 Log2_32_Ceil(N1.getValueType().getSizeInBits()) &&
3582 "Invalid use of small shift amount with oversized value!");
3584 // Always fold shifts of i1 values so the code generator doesn't need to
3585 // handle them. Since we know the size of the shift has to be less than the
3586 // size of the value, the shift/rotate count is guaranteed to be zero.
3589 if (N2C && N2C->isNullValue())
3592 case ISD::FP_ROUND_INREG: {
3593 EVT EVT = cast<VTSDNode>(N2)->getVT();
3594 assert(VT == N1.getValueType() && "Not an inreg round!");
3595 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
3596 "Cannot FP_ROUND_INREG integer types");
3597 assert(EVT.isVector() == VT.isVector() &&
3598 "FP_ROUND_INREG type should be vector iff the operand "
3600 assert((!EVT.isVector() ||
3601 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
3602 "Vector element counts must match in FP_ROUND_INREG");
3603 assert(EVT.bitsLE(VT) && "Not rounding down!");
3605 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
3609 assert(VT.isFloatingPoint() &&
3610 N1.getValueType().isFloatingPoint() &&
3611 VT.bitsLE(N1.getValueType()) &&
3612 N2C && "Invalid FP_ROUND!");
3613 if (N1.getValueType() == VT) return N1; // noop conversion.
3615 case ISD::AssertSext:
3616 case ISD::AssertZext: {
3617 EVT EVT = cast<VTSDNode>(N2)->getVT();
3618 assert(VT == N1.getValueType() && "Not an inreg extend!");
3619 assert(VT.isInteger() && EVT.isInteger() &&
3620 "Cannot *_EXTEND_INREG FP types");
3621 assert(!EVT.isVector() &&
3622 "AssertSExt/AssertZExt type should be the vector element type "
3623 "rather than the vector type!");
3624 assert(EVT.bitsLE(VT) && "Not extending!");
3625 if (VT == EVT) return N1; // noop assertion.
3628 case ISD::SIGN_EXTEND_INREG: {
3629 EVT EVT = cast<VTSDNode>(N2)->getVT();
3630 assert(VT == N1.getValueType() && "Not an inreg extend!");
3631 assert(VT.isInteger() && EVT.isInteger() &&
3632 "Cannot *_EXTEND_INREG FP types");
3633 assert(EVT.isVector() == VT.isVector() &&
3634 "SIGN_EXTEND_INREG type should be vector iff the operand "
3636 assert((!EVT.isVector() ||
3637 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
3638 "Vector element counts must match in SIGN_EXTEND_INREG");
3639 assert(EVT.bitsLE(VT) && "Not extending!");
3640 if (EVT == VT) return N1; // Not actually extending
3642 auto SignExtendInReg = [&](APInt Val) {
3643 unsigned FromBits = EVT.getScalarType().getSizeInBits();
3644 Val <<= Val.getBitWidth() - FromBits;
3645 Val = Val.ashr(Val.getBitWidth() - FromBits);
3646 return getConstant(Val, DL, VT.getScalarType());
3650 const APInt &Val = N1C->getAPIntValue();
3651 return SignExtendInReg(Val);
3653 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
3654 SmallVector<SDValue, 8> Ops;
3655 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
3656 SDValue Op = N1.getOperand(i);
3658 Ops.push_back(getUNDEF(VT.getScalarType()));
3661 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3662 APInt Val = C->getAPIntValue();
3663 Val = Val.zextOrTrunc(VT.getScalarSizeInBits());
3664 Ops.push_back(SignExtendInReg(Val));
3669 if (Ops.size() == VT.getVectorNumElements())
3670 return getBuildVector(VT, DL, Ops);
3674 case ISD::EXTRACT_VECTOR_ELT:
3675 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
3677 return getUNDEF(VT);
3679 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
3680 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements())
3681 return getUNDEF(VT);
3683 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
3684 // expanding copies of large vectors from registers.
3686 N1.getOpcode() == ISD::CONCAT_VECTORS &&
3687 N1.getNumOperands() > 0) {
3689 N1.getOperand(0).getValueType().getVectorNumElements();
3690 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
3691 N1.getOperand(N2C->getZExtValue() / Factor),
3692 getConstant(N2C->getZExtValue() % Factor, DL,
3693 N2.getValueType()));
3696 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
3697 // expanding large vector constants.
3698 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
3699 SDValue Elt = N1.getOperand(N2C->getZExtValue());
3701 if (VT != Elt.getValueType())
3702 // If the vector element type is not legal, the BUILD_VECTOR operands
3703 // are promoted and implicitly truncated, and the result implicitly
3704 // extended. Make that explicit here.
3705 Elt = getAnyExtOrTrunc(Elt, DL, VT);
3710 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
3711 // operations are lowered to scalars.
3712 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
3713 // If the indices are the same, return the inserted element else
3714 // if the indices are known different, extract the element from
3715 // the original vector.
3716 SDValue N1Op2 = N1.getOperand(2);
3717 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
3719 if (N1Op2C && N2C) {
3720 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
3721 if (VT == N1.getOperand(1).getValueType())
3722 return N1.getOperand(1);
3724 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
3727 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
3731 case ISD::EXTRACT_ELEMENT:
3732 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
3733 assert(!N1.getValueType().isVector() && !VT.isVector() &&
3734 (N1.getValueType().isInteger() == VT.isInteger()) &&
3735 N1.getValueType() != VT &&
3736 "Wrong types for EXTRACT_ELEMENT!");
3738 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
3739 // 64-bit integers into 32-bit parts. Instead of building the extract of
3740 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
3741 if (N1.getOpcode() == ISD::BUILD_PAIR)
3742 return N1.getOperand(N2C->getZExtValue());
3744 // EXTRACT_ELEMENT of a constant int is also very common.
3746 unsigned ElementSize = VT.getSizeInBits();
3747 unsigned Shift = ElementSize * N2C->getZExtValue();
3748 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
3749 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
3752 case ISD::EXTRACT_SUBVECTOR:
3753 if (VT.isSimple() && N1.getValueType().isSimple()) {
3754 assert(VT.isVector() && N1.getValueType().isVector() &&
3755 "Extract subvector VTs must be a vectors!");
3756 assert(VT.getVectorElementType() ==
3757 N1.getValueType().getVectorElementType() &&
3758 "Extract subvector VTs must have the same element type!");
3759 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
3760 "Extract subvector must be from larger vector to smaller vector!");
3763 assert((VT.getVectorNumElements() + N2C->getZExtValue()
3764 <= N1.getValueType().getVectorNumElements())
3765 && "Extract subvector overflow!");
3768 // Trivial extraction.
3769 if (VT.getSimpleVT() == N1.getSimpleValueType())
3775 // Perform trivial constant folding.
3777 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
3780 // Constant fold FP operations.
3781 bool HasFPExceptions = TLI->hasFloatingPointExceptions();
3784 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
3785 APFloat::opStatus s;
3788 s = V1.add(V2, APFloat::rmNearestTiesToEven);
3789 if (!HasFPExceptions || s != APFloat::opInvalidOp)
3790 return getConstantFP(V1, DL, VT);
3793 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
3794 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
3795 return getConstantFP(V1, DL, VT);
3798 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
3799 if (!HasFPExceptions || s!=APFloat::opInvalidOp)
3800 return getConstantFP(V1, DL, VT);
3803 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
3804 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
3805 s!=APFloat::opDivByZero)) {
3806 return getConstantFP(V1, DL, VT);
3811 if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
3812 s!=APFloat::opDivByZero)) {
3813 return getConstantFP(V1, DL, VT);
3816 case ISD::FCOPYSIGN:
3818 return getConstantFP(V1, DL, VT);
3823 if (Opcode == ISD::FP_ROUND) {
3824 APFloat V = N1CFP->getValueAPF(); // make copy
3826 // This can return overflow, underflow, or inexact; we don't care.
3827 // FIXME need to be more flexible about rounding mode.
3828 (void)V.convert(EVTToAPFloatSemantics(VT),
3829 APFloat::rmNearestTiesToEven, &ignored);
3830 return getConstantFP(V, DL, VT);
3834 // Canonicalize an UNDEF to the RHS, even over a constant.
3836 if (isCommutativeBinOp(Opcode)) {
3840 case ISD::FP_ROUND_INREG:
3841 case ISD::SIGN_EXTEND_INREG:
3847 return N1; // fold op(undef, arg2) -> undef
3855 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
3856 // For vectors, we can't easily build an all zero vector, just return
3863 // Fold a bunch of operators when the RHS is undef.
3868 // Handle undef ^ undef -> 0 special case. This is a common
3870 return getConstant(0, DL, VT);
3880 return N2; // fold op(arg1, undef) -> undef
3886 if (getTarget().Options.UnsafeFPMath)
3894 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
3895 // For vectors, we can't easily build an all zero vector, just return
3900 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
3901 // For vectors, we can't easily build an all one vector, just return
3909 // Memoize this node if possible.
3911 SDVTList VTs = getVTList(VT);
3912 if (VT != MVT::Glue) {
3913 SDValue Ops[] = {N1, N2};
3914 FoldingSetNodeID ID;
3915 AddNodeIDNode(ID, Opcode, VTs, Ops);
3917 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
3919 E->intersectFlagsWith(Flags);
3920 return SDValue(E, 0);
3923 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags);
3924 CSEMap.InsertNode(N, IP);
3926 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags);
3930 return SDValue(N, 0);
3933 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
3934 SDValue N1, SDValue N2, SDValue N3) {
3935 // Perform various simplifications.
3938 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3939 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3940 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
3941 if (N1CFP && N2CFP && N3CFP) {
3942 APFloat V1 = N1CFP->getValueAPF();
3943 const APFloat &V2 = N2CFP->getValueAPF();
3944 const APFloat &V3 = N3CFP->getValueAPF();
3945 APFloat::opStatus s =
3946 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
3947 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
3948 return getConstantFP(V1, DL, VT);
3952 case ISD::CONCAT_VECTORS: {
3953 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
3954 SDValue Ops[] = {N1, N2, N3};
3955 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
3960 // Use FoldSetCC to simplify SETCC's.
3961 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
3963 // Vector constant folding.
3964 SDValue Ops[] = {N1, N2, N3};
3965 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
3970 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
3971 if (N1C->getZExtValue())
3972 return N2; // select true, X, Y -> X
3973 return N3; // select false, X, Y -> Y
3976 if (N2 == N3) return N2; // select C, X, X -> X
3978 case ISD::VECTOR_SHUFFLE:
3979 llvm_unreachable("should use getVectorShuffle constructor!");
3980 case ISD::INSERT_SUBVECTOR: {
3982 if (VT.isSimple() && N1.getValueType().isSimple()
3983 && N2.getValueType().isSimple()) {
3984 assert(VT.isVector() && N1.getValueType().isVector() &&
3985 N2.getValueType().isVector() &&
3986 "Insert subvector VTs must be a vectors");
3987 assert(VT == N1.getValueType() &&
3988 "Dest and insert subvector source types must match!");
3989 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
3990 "Insert subvector must be from smaller vector to larger vector!");
3991 if (isa<ConstantSDNode>(Index)) {
3992 assert((N2.getValueType().getVectorNumElements() +
3993 cast<ConstantSDNode>(Index)->getZExtValue()
3994 <= VT.getVectorNumElements())
3995 && "Insert subvector overflow!");
3998 // Trivial insertion.
3999 if (VT.getSimpleVT() == N2.getSimpleValueType())
4005 // Fold bit_convert nodes from a type to themselves.
4006 if (N1.getValueType() == VT)
4011 // Memoize node if it doesn't produce a flag.
4013 SDVTList VTs = getVTList(VT);
4014 SDValue Ops[] = {N1, N2, N3};
4015 if (VT != MVT::Glue) {
4016 FoldingSetNodeID ID;
4017 AddNodeIDNode(ID, Opcode, VTs, Ops);
4019 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4020 return SDValue(E, 0);
4022 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4023 createOperands(N, Ops);
4024 CSEMap.InsertNode(N, IP);
4026 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4027 createOperands(N, Ops);
4031 return SDValue(N, 0);
4034 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4035 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
4036 SDValue Ops[] = { N1, N2, N3, N4 };
4037 return getNode(Opcode, DL, VT, Ops);
4040 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4041 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
4043 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4044 return getNode(Opcode, DL, VT, Ops);
4047 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
4048 /// the incoming stack arguments to be loaded from the stack.
4049 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
4050 SmallVector<SDValue, 8> ArgChains;
4052 // Include the original chain at the beginning of the list. When this is
4053 // used by target LowerCall hooks, this helps legalize find the
4054 // CALLSEQ_BEGIN node.
4055 ArgChains.push_back(Chain);
4057 // Add a chain value for each stack argument.
4058 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
4059 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
4060 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
4061 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
4062 if (FI->getIndex() < 0)
4063 ArgChains.push_back(SDValue(L, 1));
4065 // Build a tokenfactor for all the chains.
4066 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
4069 /// getMemsetValue - Vectorized representation of the memset value
4071 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
4073 assert(!Value.isUndef());
4075 unsigned NumBits = VT.getScalarType().getSizeInBits();
4076 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
4077 assert(C->getAPIntValue().getBitWidth() == 8);
4078 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
4080 return DAG.getConstant(Val, dl, VT);
4081 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
4085 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
4086 EVT IntVT = VT.getScalarType();
4087 if (!IntVT.isInteger())
4088 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
4090 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
4092 // Use a multiplication with 0x010101... to extend the input to the
4094 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
4095 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
4096 DAG.getConstant(Magic, dl, IntVT));
4099 if (VT != Value.getValueType() && !VT.isInteger())
4100 Value = DAG.getBitcast(VT.getScalarType(), Value);
4101 if (VT != Value.getValueType())
4102 Value = DAG.getSplatBuildVector(VT, dl, Value);
4107 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
4108 /// used when a memcpy is turned into a memset when the source is a constant
4110 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
4111 const TargetLowering &TLI, StringRef Str) {
4112 // Handle vector with all elements zero.
4115 return DAG.getConstant(0, dl, VT);
4116 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
4117 return DAG.getConstantFP(0.0, dl, VT);
4118 else if (VT.isVector()) {
4119 unsigned NumElts = VT.getVectorNumElements();
4120 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
4121 return DAG.getNode(ISD::BITCAST, dl, VT,
4122 DAG.getConstant(0, dl,
4123 EVT::getVectorVT(*DAG.getContext(),
4126 llvm_unreachable("Expected type!");
4129 assert(!VT.isVector() && "Can't handle vector type here!");
4130 unsigned NumVTBits = VT.getSizeInBits();
4131 unsigned NumVTBytes = NumVTBits / 8;
4132 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
4134 APInt Val(NumVTBits, 0);
4135 if (DAG.getDataLayout().isLittleEndian()) {
4136 for (unsigned i = 0; i != NumBytes; ++i)
4137 Val |= (uint64_t)(unsigned char)Str[i] << i*8;
4139 for (unsigned i = 0; i != NumBytes; ++i)
4140 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
4143 // If the "cost" of materializing the integer immediate is less than the cost
4144 // of a load, then it is cost effective to turn the load into the immediate.
4145 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
4146 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
4147 return DAG.getConstant(Val, dl, VT);
4148 return SDValue(nullptr, 0);
4151 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
4153 EVT VT = Base.getValueType();
4154 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
4157 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
4159 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
4160 uint64_t SrcDelta = 0;
4161 GlobalAddressSDNode *G = nullptr;
4162 if (Src.getOpcode() == ISD::GlobalAddress)
4163 G = cast<GlobalAddressSDNode>(Src);
4164 else if (Src.getOpcode() == ISD::ADD &&
4165 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
4166 Src.getOperand(1).getOpcode() == ISD::Constant) {
4167 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
4168 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
4173 return getConstantStringInfo(G->getGlobal(), Str,
4174 SrcDelta + G->getOffset(), false);
4177 /// Determines the optimal series of memory ops to replace the memset / memcpy.
4178 /// Return true if the number of memory ops is below the threshold (Limit).
4179 /// It returns the types of the sequence of memory ops to perform
4180 /// memset / memcpy by reference.
4181 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
4182 unsigned Limit, uint64_t Size,
4183 unsigned DstAlign, unsigned SrcAlign,
4188 unsigned DstAS, unsigned SrcAS,
4190 const TargetLowering &TLI) {
4191 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
4192 "Expecting memcpy / memset source to meet alignment requirement!");
4193 // If 'SrcAlign' is zero, that means the memory operation does not need to
4194 // load the value, i.e. memset or memcpy from constant string. Otherwise,
4195 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
4196 // is the specified alignment of the memory operation. If it is zero, that
4197 // means it's possible to change the alignment of the destination.
4198 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
4199 // not need to be loaded.
4200 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
4201 IsMemset, ZeroMemset, MemcpyStrSrc,
4202 DAG.getMachineFunction());
4204 if (VT == MVT::Other) {
4205 if (DstAlign >= DAG.getDataLayout().getPointerPrefAlignment(DstAS) ||
4206 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign)) {
4207 VT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
4209 switch (DstAlign & 7) {
4210 case 0: VT = MVT::i64; break;
4211 case 4: VT = MVT::i32; break;
4212 case 2: VT = MVT::i16; break;
4213 default: VT = MVT::i8; break;
4218 while (!TLI.isTypeLegal(LVT))
4219 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
4220 assert(LVT.isInteger());
4226 unsigned NumMemOps = 0;
4228 unsigned VTSize = VT.getSizeInBits() / 8;
4229 while (VTSize > Size) {
4230 // For now, only use non-vector load / store's for the left-over pieces.
4235 if (VT.isVector() || VT.isFloatingPoint()) {
4236 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
4237 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
4238 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
4240 else if (NewVT == MVT::i64 &&
4241 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
4242 TLI.isSafeMemOpType(MVT::f64)) {
4243 // i64 is usually not legal on 32-bit targets, but f64 may be.
4251 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
4252 if (NewVT == MVT::i8)
4254 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
4256 NewVTSize = NewVT.getSizeInBits() / 8;
4258 // If the new VT cannot cover all of the remaining bits, then consider
4259 // issuing a (or a pair of) unaligned and overlapping load / store.
4260 // FIXME: Only does this for 64-bit or more since we don't have proper
4261 // cost model for unaligned load / store.
4263 if (NumMemOps && AllowOverlap &&
4264 VTSize >= 8 && NewVTSize < Size &&
4265 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast)
4273 if (++NumMemOps > Limit)
4276 MemOps.push_back(VT);
4283 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
4284 // On Darwin, -Os means optimize for size without hurting performance, so
4285 // only really optimize for size when -Oz (MinSize) is used.
4286 if (MF.getTarget().getTargetTriple().isOSDarwin())
4287 return MF.getFunction()->optForMinSize();
4288 return MF.getFunction()->optForSize();
4291 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4292 SDValue Chain, SDValue Dst, SDValue Src,
4293 uint64_t Size, unsigned Align,
4294 bool isVol, bool AlwaysInline,
4295 MachinePointerInfo DstPtrInfo,
4296 MachinePointerInfo SrcPtrInfo) {
4297 // Turn a memcpy of undef to nop.
4301 // Expand memcpy to a series of load and store ops if the size operand falls
4302 // below a certain threshold.
4303 // TODO: In the AlwaysInline case, if the size is big then generate a loop
4304 // rather than maybe a humongous number of loads and stores.
4305 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4306 std::vector<EVT> MemOps;
4307 bool DstAlignCanChange = false;
4308 MachineFunction &MF = DAG.getMachineFunction();
4309 MachineFrameInfo *MFI = MF.getFrameInfo();
4310 bool OptSize = shouldLowerMemFuncForSize(MF);
4311 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4312 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
4313 DstAlignCanChange = true;
4314 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4315 if (Align > SrcAlign)
4318 bool CopyFromStr = isMemSrcFromString(Src, Str);
4319 bool isZeroStr = CopyFromStr && Str.empty();
4320 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
4322 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4323 (DstAlignCanChange ? 0 : Align),
4324 (isZeroStr ? 0 : SrcAlign),
4325 false, false, CopyFromStr, true,
4326 DstPtrInfo.getAddrSpace(),
4327 SrcPtrInfo.getAddrSpace(),
4331 if (DstAlignCanChange) {
4332 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4333 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4335 // Don't promote to an alignment that would require dynamic stack
4337 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4338 if (!TRI->needsStackRealignment(MF))
4339 while (NewAlign > Align &&
4340 DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign))
4343 if (NewAlign > Align) {
4344 // Give the stack frame object a larger alignment if needed.
4345 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
4346 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
4351 MachineMemOperand::Flags MMOFlags =
4352 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4353 SmallVector<SDValue, 8> OutChains;
4354 unsigned NumMemOps = MemOps.size();
4355 uint64_t SrcOff = 0, DstOff = 0;
4356 for (unsigned i = 0; i != NumMemOps; ++i) {
4358 unsigned VTSize = VT.getSizeInBits() / 8;
4359 SDValue Value, Store;
4361 if (VTSize > Size) {
4362 // Issuing an unaligned load / store pair that overlaps with the previous
4363 // pair. Adjust the offset accordingly.
4364 assert(i == NumMemOps-1 && i != 0);
4365 SrcOff -= VTSize - Size;
4366 DstOff -= VTSize - Size;
4370 (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
4371 // It's unlikely a store of a vector immediate can be done in a single
4372 // instruction. It would require a load from a constantpool first.
4373 // We only handle zero vectors here.
4374 // FIXME: Handle other cases where store of vector immediate is done in
4375 // a single instruction.
4376 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
4377 if (Value.getNode())
4378 Store = DAG.getStore(Chain, dl, Value,
4379 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4380 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
4383 if (!Store.getNode()) {
4384 // The type might not be legal for the target. This should only happen
4385 // if the type is smaller than a legal type, as on PPC, so the right
4386 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
4387 // to Load/Store if NVT==VT.
4388 // FIXME does the case above also need this?
4389 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4390 assert(NVT.bitsGE(VT));
4391 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
4392 DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4393 SrcPtrInfo.getWithOffset(SrcOff), VT,
4394 MinAlign(SrcAlign, SrcOff), MMOFlags);
4395 OutChains.push_back(Value.getValue(1));
4396 Store = DAG.getTruncStore(
4397 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4398 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
4400 OutChains.push_back(Store);
4406 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4409 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
4410 SDValue Chain, SDValue Dst, SDValue Src,
4411 uint64_t Size, unsigned Align,
4412 bool isVol, bool AlwaysInline,
4413 MachinePointerInfo DstPtrInfo,
4414 MachinePointerInfo SrcPtrInfo) {
4415 // Turn a memmove of undef to nop.
4419 // Expand memmove to a series of load and store ops if the size operand falls
4420 // below a certain threshold.
4421 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4422 std::vector<EVT> MemOps;
4423 bool DstAlignCanChange = false;
4424 MachineFunction &MF = DAG.getMachineFunction();
4425 MachineFrameInfo *MFI = MF.getFrameInfo();
4426 bool OptSize = shouldLowerMemFuncForSize(MF);
4427 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4428 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
4429 DstAlignCanChange = true;
4430 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
4431 if (Align > SrcAlign)
4433 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
4435 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
4436 (DstAlignCanChange ? 0 : Align), SrcAlign,
4437 false, false, false, false,
4438 DstPtrInfo.getAddrSpace(),
4439 SrcPtrInfo.getAddrSpace(),
4443 if (DstAlignCanChange) {
4444 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4445 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4446 if (NewAlign > Align) {
4447 // Give the stack frame object a larger alignment if needed.
4448 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
4449 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
4454 MachineMemOperand::Flags MMOFlags =
4455 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
4456 uint64_t SrcOff = 0, DstOff = 0;
4457 SmallVector<SDValue, 8> LoadValues;
4458 SmallVector<SDValue, 8> LoadChains;
4459 SmallVector<SDValue, 8> OutChains;
4460 unsigned NumMemOps = MemOps.size();
4461 for (unsigned i = 0; i < NumMemOps; i++) {
4463 unsigned VTSize = VT.getSizeInBits() / 8;
4467 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
4468 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, MMOFlags);
4469 LoadValues.push_back(Value);
4470 LoadChains.push_back(Value.getValue(1));
4473 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
4475 for (unsigned i = 0; i < NumMemOps; i++) {
4477 unsigned VTSize = VT.getSizeInBits() / 8;
4480 Store = DAG.getStore(Chain, dl, LoadValues[i],
4481 DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4482 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
4483 OutChains.push_back(Store);
4487 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4490 /// \brief Lower the call to 'memset' intrinsic function into a series of store
4493 /// \param DAG Selection DAG where lowered code is placed.
4494 /// \param dl Link to corresponding IR location.
4495 /// \param Chain Control flow dependency.
4496 /// \param Dst Pointer to destination memory location.
4497 /// \param Src Value of byte to write into the memory.
4498 /// \param Size Number of bytes to write.
4499 /// \param Align Alignment of the destination in bytes.
4500 /// \param isVol True if destination is volatile.
4501 /// \param DstPtrInfo IR information on the memory pointer.
4502 /// \returns New head in the control flow, if lowering was successful, empty
4503 /// SDValue otherwise.
4505 /// The function tries to replace 'llvm.memset' intrinsic with several store
4506 /// operations and value calculation code. This is usually profitable for small
4508 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
4509 SDValue Chain, SDValue Dst, SDValue Src,
4510 uint64_t Size, unsigned Align, bool isVol,
4511 MachinePointerInfo DstPtrInfo) {
4512 // Turn a memset of undef to nop.
4516 // Expand memset to a series of load/store ops if the size operand
4517 // falls below a certain threshold.
4518 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4519 std::vector<EVT> MemOps;
4520 bool DstAlignCanChange = false;
4521 MachineFunction &MF = DAG.getMachineFunction();
4522 MachineFrameInfo *MFI = MF.getFrameInfo();
4523 bool OptSize = shouldLowerMemFuncForSize(MF);
4524 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4525 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
4526 DstAlignCanChange = true;
4528 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
4529 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
4530 Size, (DstAlignCanChange ? 0 : Align), 0,
4531 true, IsZeroVal, false, true,
4532 DstPtrInfo.getAddrSpace(), ~0u,
4536 if (DstAlignCanChange) {
4537 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4538 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
4539 if (NewAlign > Align) {
4540 // Give the stack frame object a larger alignment if needed.
4541 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
4542 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
4547 SmallVector<SDValue, 8> OutChains;
4548 uint64_t DstOff = 0;
4549 unsigned NumMemOps = MemOps.size();
4551 // Find the largest store and generate the bit pattern for it.
4552 EVT LargestVT = MemOps[0];
4553 for (unsigned i = 1; i < NumMemOps; i++)
4554 if (MemOps[i].bitsGT(LargestVT))
4555 LargestVT = MemOps[i];
4556 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
4558 for (unsigned i = 0; i < NumMemOps; i++) {
4560 unsigned VTSize = VT.getSizeInBits() / 8;
4561 if (VTSize > Size) {
4562 // Issuing an unaligned load / store pair that overlaps with the previous
4563 // pair. Adjust the offset accordingly.
4564 assert(i == NumMemOps-1 && i != 0);
4565 DstOff -= VTSize - Size;
4568 // If this store is smaller than the largest store see whether we can get
4569 // the smaller value for free with a truncate.
4570 SDValue Value = MemSetValue;
4571 if (VT.bitsLT(LargestVT)) {
4572 if (!LargestVT.isVector() && !VT.isVector() &&
4573 TLI.isTruncateFree(LargestVT, VT))
4574 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
4576 Value = getMemsetValue(Src, VT, DAG, dl);
4578 assert(Value.getValueType() == VT && "Value with wrong type.");
4579 SDValue Store = DAG.getStore(
4580 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
4581 DstPtrInfo.getWithOffset(DstOff), Align,
4582 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
4583 OutChains.push_back(Store);
4584 DstOff += VT.getSizeInBits() / 8;
4588 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4591 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
4593 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
4594 // pointer operands can be losslessly bitcasted to pointers of address space 0
4595 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
4596 report_fatal_error("cannot lower memory intrinsic in address space " +
4601 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
4602 SDValue Src, SDValue Size, unsigned Align,
4603 bool isVol, bool AlwaysInline, bool isTailCall,
4604 MachinePointerInfo DstPtrInfo,
4605 MachinePointerInfo SrcPtrInfo) {
4606 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4608 // Check to see if we should lower the memcpy to loads and stores first.
4609 // For cases within the target-specified limits, this is the best choice.
4610 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4612 // Memcpy with size zero? Just return the original chain.
4613 if (ConstantSize->isNullValue())
4616 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
4617 ConstantSize->getZExtValue(),Align,
4618 isVol, false, DstPtrInfo, SrcPtrInfo);
4619 if (Result.getNode())
4623 // Then check to see if we should lower the memcpy with target-specific
4624 // code. If the target chooses to do this, this is the next best.
4626 SDValue Result = TSI->EmitTargetCodeForMemcpy(
4627 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
4628 DstPtrInfo, SrcPtrInfo);
4629 if (Result.getNode())
4633 // If we really need inline code and the target declined to provide it,
4634 // use a (potentially long) sequence of loads and stores.
4636 assert(ConstantSize && "AlwaysInline requires a constant size!");
4637 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
4638 ConstantSize->getZExtValue(), Align, isVol,
4639 true, DstPtrInfo, SrcPtrInfo);
4642 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
4643 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
4645 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
4646 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
4647 // respect volatile, so they may do things like read or write memory
4648 // beyond the given memory regions. But fixing this isn't easy, and most
4649 // people don't care.
4651 // Emit a library call.
4652 TargetLowering::ArgListTy Args;
4653 TargetLowering::ArgListEntry Entry;
4654 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
4655 Entry.Node = Dst; Args.push_back(Entry);
4656 Entry.Node = Src; Args.push_back(Entry);
4657 Entry.Node = Size; Args.push_back(Entry);
4658 // FIXME: pass in SDLoc
4659 TargetLowering::CallLoweringInfo CLI(*this);
4662 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
4663 Dst.getValueType().getTypeForEVT(*getContext()),
4664 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
4665 TLI->getPointerTy(getDataLayout())),
4668 .setTailCall(isTailCall);
4670 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4671 return CallResult.second;
4674 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
4675 SDValue Src, SDValue Size, unsigned Align,
4676 bool isVol, bool isTailCall,
4677 MachinePointerInfo DstPtrInfo,
4678 MachinePointerInfo SrcPtrInfo) {
4679 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4681 // Check to see if we should lower the memmove to loads and stores first.
4682 // For cases within the target-specified limits, this is the best choice.
4683 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4685 // Memmove with size zero? Just return the original chain.
4686 if (ConstantSize->isNullValue())
4690 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
4691 ConstantSize->getZExtValue(), Align, isVol,
4692 false, DstPtrInfo, SrcPtrInfo);
4693 if (Result.getNode())
4697 // Then check to see if we should lower the memmove with target-specific
4698 // code. If the target chooses to do this, this is the next best.
4700 SDValue Result = TSI->EmitTargetCodeForMemmove(
4701 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
4702 if (Result.getNode())
4706 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
4707 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
4709 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
4710 // not be safe. See memcpy above for more details.
4712 // Emit a library call.
4713 TargetLowering::ArgListTy Args;
4714 TargetLowering::ArgListEntry Entry;
4715 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
4716 Entry.Node = Dst; Args.push_back(Entry);
4717 Entry.Node = Src; Args.push_back(Entry);
4718 Entry.Node = Size; Args.push_back(Entry);
4719 // FIXME: pass in SDLoc
4720 TargetLowering::CallLoweringInfo CLI(*this);
4723 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
4724 Dst.getValueType().getTypeForEVT(*getContext()),
4725 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
4726 TLI->getPointerTy(getDataLayout())),
4729 .setTailCall(isTailCall);
4731 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4732 return CallResult.second;
4735 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
4736 SDValue Src, SDValue Size, unsigned Align,
4737 bool isVol, bool isTailCall,
4738 MachinePointerInfo DstPtrInfo) {
4739 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4741 // Check to see if we should lower the memset to stores first.
4742 // For cases within the target-specified limits, this is the best choice.
4743 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4745 // Memset with size zero? Just return the original chain.
4746 if (ConstantSize->isNullValue())
4750 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
4751 Align, isVol, DstPtrInfo);
4753 if (Result.getNode())
4757 // Then check to see if we should lower the memset with target-specific
4758 // code. If the target chooses to do this, this is the next best.
4760 SDValue Result = TSI->EmitTargetCodeForMemset(
4761 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
4762 if (Result.getNode())
4766 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
4768 // Emit a library call.
4769 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
4770 TargetLowering::ArgListTy Args;
4771 TargetLowering::ArgListEntry Entry;
4772 Entry.Node = Dst; Entry.Ty = IntPtrTy;
4773 Args.push_back(Entry);
4775 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
4776 Args.push_back(Entry);
4778 Entry.Ty = IntPtrTy;
4779 Args.push_back(Entry);
4781 // FIXME: pass in SDLoc
4782 TargetLowering::CallLoweringInfo CLI(*this);
4785 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
4786 Dst.getValueType().getTypeForEVT(*getContext()),
4787 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
4788 TLI->getPointerTy(getDataLayout())),
4791 .setTailCall(isTailCall);
4793 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4794 return CallResult.second;
4797 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
4798 SDVTList VTList, ArrayRef<SDValue> Ops,
4799 MachineMemOperand *MMO,
4800 AtomicOrdering SuccessOrdering,
4801 AtomicOrdering FailureOrdering,
4802 SynchronizationScope SynchScope) {
4803 FoldingSetNodeID ID;
4804 ID.AddInteger(MemVT.getRawBits());
4805 AddNodeIDNode(ID, Opcode, VTList, Ops);
4806 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4808 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
4809 cast<AtomicSDNode>(E)->refineAlignment(MMO);
4810 return SDValue(E, 0);
4813 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
4814 VTList, MemVT, MMO, SuccessOrdering,
4815 FailureOrdering, SynchScope);
4816 createOperands(N, Ops);
4818 CSEMap.InsertNode(N, IP);
4820 return SDValue(N, 0);
4823 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
4824 SDVTList VTList, ArrayRef<SDValue> Ops,
4825 MachineMemOperand *MMO, AtomicOrdering Ordering,
4826 SynchronizationScope SynchScope) {
4827 return getAtomic(Opcode, dl, MemVT, VTList, Ops, MMO, Ordering,
4828 Ordering, SynchScope);
4831 SDValue SelectionDAG::getAtomicCmpSwap(
4832 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
4833 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
4834 unsigned Alignment, AtomicOrdering SuccessOrdering,
4835 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
4836 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
4837 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
4838 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4840 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4841 Alignment = getEVTAlignment(MemVT);
4843 MachineFunction &MF = getMachineFunction();
4845 // FIXME: Volatile isn't really correct; we should keep track of atomic
4846 // orderings in the memoperand.
4847 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
4848 MachineMemOperand::MOStore;
4849 MachineMemOperand *MMO =
4850 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment);
4852 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO,
4853 SuccessOrdering, FailureOrdering, SynchScope);
4856 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
4857 EVT MemVT, SDVTList VTs, SDValue Chain,
4858 SDValue Ptr, SDValue Cmp, SDValue Swp,
4859 MachineMemOperand *MMO,
4860 AtomicOrdering SuccessOrdering,
4861 AtomicOrdering FailureOrdering,
4862 SynchronizationScope SynchScope) {
4863 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
4864 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
4865 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4867 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
4868 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO,
4869 SuccessOrdering, FailureOrdering, SynchScope);
4872 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
4873 SDValue Chain, SDValue Ptr, SDValue Val,
4874 const Value *PtrVal, unsigned Alignment,
4875 AtomicOrdering Ordering,
4876 SynchronizationScope SynchScope) {
4877 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4878 Alignment = getEVTAlignment(MemVT);
4880 MachineFunction &MF = getMachineFunction();
4881 // An atomic store does not load. An atomic load does not store.
4882 // (An atomicrmw obviously both loads and stores.)
4883 // For now, atomics are considered to be volatile always, and they are
4885 // FIXME: Volatile isn't really correct; we should keep track of atomic
4886 // orderings in the memoperand.
4887 auto Flags = MachineMemOperand::MOVolatile;
4888 if (Opcode != ISD::ATOMIC_STORE)
4889 Flags |= MachineMemOperand::MOLoad;
4890 if (Opcode != ISD::ATOMIC_LOAD)
4891 Flags |= MachineMemOperand::MOStore;
4893 MachineMemOperand *MMO =
4894 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
4895 MemVT.getStoreSize(), Alignment);
4897 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO,
4898 Ordering, SynchScope);
4901 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
4902 SDValue Chain, SDValue Ptr, SDValue Val,
4903 MachineMemOperand *MMO, AtomicOrdering Ordering,
4904 SynchronizationScope SynchScope) {
4905 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
4906 Opcode == ISD::ATOMIC_LOAD_SUB ||
4907 Opcode == ISD::ATOMIC_LOAD_AND ||
4908 Opcode == ISD::ATOMIC_LOAD_OR ||
4909 Opcode == ISD::ATOMIC_LOAD_XOR ||
4910 Opcode == ISD::ATOMIC_LOAD_NAND ||
4911 Opcode == ISD::ATOMIC_LOAD_MIN ||
4912 Opcode == ISD::ATOMIC_LOAD_MAX ||
4913 Opcode == ISD::ATOMIC_LOAD_UMIN ||
4914 Opcode == ISD::ATOMIC_LOAD_UMAX ||
4915 Opcode == ISD::ATOMIC_SWAP ||
4916 Opcode == ISD::ATOMIC_STORE) &&
4917 "Invalid Atomic Op");
4919 EVT VT = Val.getValueType();
4921 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
4922 getVTList(VT, MVT::Other);
4923 SDValue Ops[] = {Chain, Ptr, Val};
4924 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope);
4927 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
4928 EVT VT, SDValue Chain, SDValue Ptr,
4929 MachineMemOperand *MMO, AtomicOrdering Ordering,
4930 SynchronizationScope SynchScope) {
4931 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
4933 SDVTList VTs = getVTList(VT, MVT::Other);
4934 SDValue Ops[] = {Chain, Ptr};
4935 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope);
4938 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
4939 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
4940 if (Ops.size() == 1)
4943 SmallVector<EVT, 4> VTs;
4944 VTs.reserve(Ops.size());
4945 for (unsigned i = 0; i < Ops.size(); ++i)
4946 VTs.push_back(Ops[i].getValueType());
4947 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
4950 SDValue SelectionDAG::getMemIntrinsicNode(
4951 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
4952 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol,
4953 bool ReadMem, bool WriteMem, unsigned Size) {
4954 if (Align == 0) // Ensure that codegen never sees alignment 0
4955 Align = getEVTAlignment(MemVT);
4957 MachineFunction &MF = getMachineFunction();
4958 auto Flags = MachineMemOperand::MONone;
4960 Flags |= MachineMemOperand::MOStore;
4962 Flags |= MachineMemOperand::MOLoad;
4964 Flags |= MachineMemOperand::MOVolatile;
4966 Size = MemVT.getStoreSize();
4967 MachineMemOperand *MMO =
4968 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
4970 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
4973 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
4975 ArrayRef<SDValue> Ops, EVT MemVT,
4976 MachineMemOperand *MMO) {
4977 assert((Opcode == ISD::INTRINSIC_VOID ||
4978 Opcode == ISD::INTRINSIC_W_CHAIN ||
4979 Opcode == ISD::PREFETCH ||
4980 Opcode == ISD::LIFETIME_START ||
4981 Opcode == ISD::LIFETIME_END ||
4982 (Opcode <= INT_MAX &&
4983 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
4984 "Opcode is not a memory-accessing opcode!");
4986 // Memoize the node unless it returns a flag.
4987 MemIntrinsicSDNode *N;
4988 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4989 FoldingSetNodeID ID;
4990 AddNodeIDNode(ID, Opcode, VTList, Ops);
4991 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4993 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
4994 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
4995 return SDValue(E, 0);
4998 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
4999 VTList, MemVT, MMO);
5000 createOperands(N, Ops);
5002 CSEMap.InsertNode(N, IP);
5004 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
5005 VTList, MemVT, MMO);
5006 createOperands(N, Ops);
5009 return SDValue(N, 0);
5012 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5013 /// MachinePointerInfo record from it. This is particularly useful because the
5014 /// code generator has many cases where it doesn't bother passing in a
5015 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5016 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5017 int64_t Offset = 0) {
5018 // If this is FI+Offset, we can model it.
5019 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
5020 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
5021 FI->getIndex(), Offset);
5023 // If this is (FI+Offset1)+Offset2, we can model it.
5024 if (Ptr.getOpcode() != ISD::ADD ||
5025 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
5026 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
5027 return MachinePointerInfo();
5029 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5030 return MachinePointerInfo::getFixedStack(
5031 DAG.getMachineFunction(), FI,
5032 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
5035 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
5036 /// MachinePointerInfo record from it. This is particularly useful because the
5037 /// code generator has many cases where it doesn't bother passing in a
5038 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
5039 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr,
5041 // If the 'Offset' value isn't a constant, we can't handle this.
5042 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
5043 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue());
5044 if (OffsetOp.isUndef())
5045 return InferPointerInfo(DAG, Ptr);
5046 return MachinePointerInfo();
5049 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5050 EVT VT, const SDLoc &dl, SDValue Chain,
5051 SDValue Ptr, SDValue Offset,
5052 MachinePointerInfo PtrInfo, EVT MemVT,
5054 MachineMemOperand::Flags MMOFlags,
5055 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5056 assert(Chain.getValueType() == MVT::Other &&
5057 "Invalid chain type");
5058 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5059 Alignment = getEVTAlignment(VT);
5061 MMOFlags |= MachineMemOperand::MOLoad;
5062 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
5063 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
5065 if (PtrInfo.V.isNull())
5066 PtrInfo = InferPointerInfo(*this, Ptr, Offset);
5068 MachineFunction &MF = getMachineFunction();
5069 MachineMemOperand *MMO = MF.getMachineMemOperand(
5070 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
5071 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
5074 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
5075 EVT VT, const SDLoc &dl, SDValue Chain,
5076 SDValue Ptr, SDValue Offset, EVT MemVT,
5077 MachineMemOperand *MMO) {
5079 ExtType = ISD::NON_EXTLOAD;
5080 } else if (ExtType == ISD::NON_EXTLOAD) {
5081 assert(VT == MemVT && "Non-extending load from different memory type!");
5084 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
5085 "Should only be an extending load, not truncating!");
5086 assert(VT.isInteger() == MemVT.isInteger() &&
5087 "Cannot convert from FP to Int or Int -> FP!");
5088 assert(VT.isVector() == MemVT.isVector() &&
5089 "Cannot use an ext load to convert to or from a vector!");
5090 assert((!VT.isVector() ||
5091 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
5092 "Cannot use an ext load to change the number of vector elements!");
5095 bool Indexed = AM != ISD::UNINDEXED;
5096 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
5098 SDVTList VTs = Indexed ?
5099 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
5100 SDValue Ops[] = { Chain, Ptr, Offset };
5101 FoldingSetNodeID ID;
5102 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
5103 ID.AddInteger(MemVT.getRawBits());
5104 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
5105 MMO->isNonTemporal(),
5106 MMO->isInvariant()));
5107 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5109 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5110 cast<LoadSDNode>(E)->refineAlignment(MMO);
5111 return SDValue(E, 0);
5113 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5114 ExtType, MemVT, MMO);
5115 createOperands(N, Ops);
5117 CSEMap.InsertNode(N, IP);
5119 return SDValue(N, 0);
5122 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5123 SDValue Ptr, MachinePointerInfo PtrInfo,
5125 MachineMemOperand::Flags MMOFlags,
5126 const AAMDNodes &AAInfo, const MDNode *Ranges) {
5127 SDValue Undef = getUNDEF(Ptr.getValueType());
5128 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5129 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
5132 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5133 SDValue Ptr, MachineMemOperand *MMO) {
5134 SDValue Undef = getUNDEF(Ptr.getValueType());
5135 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
5139 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5140 EVT VT, SDValue Chain, SDValue Ptr,
5141 MachinePointerInfo PtrInfo, EVT MemVT,
5143 MachineMemOperand::Flags MMOFlags,
5144 const AAMDNodes &AAInfo) {
5145 SDValue Undef = getUNDEF(Ptr.getValueType());
5146 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
5147 MemVT, Alignment, MMOFlags, AAInfo);
5150 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
5151 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
5152 MachineMemOperand *MMO) {
5153 SDValue Undef = getUNDEF(Ptr.getValueType());
5154 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
5158 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
5159 SDValue Base, SDValue Offset,
5160 ISD::MemIndexedMode AM) {
5161 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
5162 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
5163 // Don't propagate the invariant flag.
5165 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOInvariant;
5166 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
5167 LD->getChain(), Base, Offset, LD->getPointerInfo(),
5168 LD->getMemoryVT(), LD->getAlignment(), MMOFlags);
5171 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5172 SDValue Ptr, MachinePointerInfo PtrInfo,
5174 MachineMemOperand::Flags MMOFlags,
5175 const AAMDNodes &AAInfo) {
5176 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
5177 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5178 Alignment = getEVTAlignment(Val.getValueType());
5180 MMOFlags |= MachineMemOperand::MOStore;
5181 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5183 if (PtrInfo.V.isNull())
5184 PtrInfo = InferPointerInfo(*this, Ptr);
5186 MachineFunction &MF = getMachineFunction();
5187 MachineMemOperand *MMO = MF.getMachineMemOperand(
5188 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
5189 return getStore(Chain, dl, Val, Ptr, MMO);
5192 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5193 SDValue Ptr, MachineMemOperand *MMO) {
5194 assert(Chain.getValueType() == MVT::Other &&
5195 "Invalid chain type");
5196 EVT VT = Val.getValueType();
5197 SDVTList VTs = getVTList(MVT::Other);
5198 SDValue Undef = getUNDEF(Ptr.getValueType());
5199 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5200 FoldingSetNodeID ID;
5201 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5202 ID.AddInteger(VT.getRawBits());
5203 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
5204 MMO->isNonTemporal(), MMO->isInvariant()));
5205 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5207 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5208 cast<StoreSDNode>(E)->refineAlignment(MMO);
5209 return SDValue(E, 0);
5211 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5212 ISD::UNINDEXED, false, VT, MMO);
5213 createOperands(N, Ops);
5215 CSEMap.InsertNode(N, IP);
5217 return SDValue(N, 0);
5220 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5221 SDValue Ptr, MachinePointerInfo PtrInfo,
5222 EVT SVT, unsigned Alignment,
5223 MachineMemOperand::Flags MMOFlags,
5224 const AAMDNodes &AAInfo) {
5225 assert(Chain.getValueType() == MVT::Other &&
5226 "Invalid chain type");
5227 if (Alignment == 0) // Ensure that codegen never sees alignment 0
5228 Alignment = getEVTAlignment(SVT);
5230 MMOFlags |= MachineMemOperand::MOStore;
5231 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
5233 if (PtrInfo.V.isNull())
5234 PtrInfo = InferPointerInfo(*this, Ptr);
5236 MachineFunction &MF = getMachineFunction();
5237 MachineMemOperand *MMO = MF.getMachineMemOperand(
5238 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
5239 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
5242 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
5243 SDValue Ptr, EVT SVT,
5244 MachineMemOperand *MMO) {
5245 EVT VT = Val.getValueType();
5247 assert(Chain.getValueType() == MVT::Other &&
5248 "Invalid chain type");
5250 return getStore(Chain, dl, Val, Ptr, MMO);
5252 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
5253 "Should only be a truncating store, not extending!");
5254 assert(VT.isInteger() == SVT.isInteger() &&
5255 "Can't do FP-INT conversion!");
5256 assert(VT.isVector() == SVT.isVector() &&
5257 "Cannot use trunc store to convert to or from a vector!");
5258 assert((!VT.isVector() ||
5259 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
5260 "Cannot use trunc store to change the number of vector elements!");
5262 SDVTList VTs = getVTList(MVT::Other);
5263 SDValue Undef = getUNDEF(Ptr.getValueType());
5264 SDValue Ops[] = { Chain, Val, Ptr, Undef };
5265 FoldingSetNodeID ID;
5266 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5267 ID.AddInteger(SVT.getRawBits());
5268 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
5269 MMO->isNonTemporal(), MMO->isInvariant()));
5270 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5272 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5273 cast<StoreSDNode>(E)->refineAlignment(MMO);
5274 return SDValue(E, 0);
5276 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5277 ISD::UNINDEXED, true, SVT, MMO);
5278 createOperands(N, Ops);
5280 CSEMap.InsertNode(N, IP);
5282 return SDValue(N, 0);
5285 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
5286 SDValue Base, SDValue Offset,
5287 ISD::MemIndexedMode AM) {
5288 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
5289 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
5290 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
5291 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
5292 FoldingSetNodeID ID;
5293 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
5294 ID.AddInteger(ST->getMemoryVT().getRawBits());
5295 ID.AddInteger(ST->getRawSubclassData());
5296 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
5298 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
5299 return SDValue(E, 0);
5301 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
5302 ST->isTruncatingStore(), ST->getMemoryVT(),
5303 ST->getMemOperand());
5304 createOperands(N, Ops);
5306 CSEMap.InsertNode(N, IP);
5308 return SDValue(N, 0);
5311 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
5312 SDValue Ptr, SDValue Mask, SDValue Src0,
5313 EVT MemVT, MachineMemOperand *MMO,
5314 ISD::LoadExtType ExtTy) {
5316 SDVTList VTs = getVTList(VT, MVT::Other);
5317 SDValue Ops[] = { Chain, Ptr, Mask, Src0 };
5318 FoldingSetNodeID ID;
5319 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
5320 ID.AddInteger(VT.getRawBits());
5321 ID.AddInteger(encodeMemSDNodeFlags(ExtTy, ISD::UNINDEXED,
5323 MMO->isNonTemporal(),
5324 MMO->isInvariant()));
5325 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5327 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5328 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
5329 return SDValue(E, 0);
5331 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5333 createOperands(N, Ops);
5335 CSEMap.InsertNode(N, IP);
5337 return SDValue(N, 0);
5340 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
5341 SDValue Val, SDValue Ptr, SDValue Mask,
5342 EVT MemVT, MachineMemOperand *MMO,
5344 assert(Chain.getValueType() == MVT::Other &&
5345 "Invalid chain type");
5346 EVT VT = Val.getValueType();
5347 SDVTList VTs = getVTList(MVT::Other);
5348 SDValue Ops[] = { Chain, Ptr, Mask, Val };
5349 FoldingSetNodeID ID;
5350 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
5351 ID.AddInteger(VT.getRawBits());
5352 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
5353 MMO->isNonTemporal(), MMO->isInvariant()));
5354 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5356 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5357 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
5358 return SDValue(E, 0);
5360 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
5361 isTrunc, MemVT, MMO);
5362 createOperands(N, Ops);
5364 CSEMap.InsertNode(N, IP);
5366 return SDValue(N, 0);
5369 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
5370 ArrayRef<SDValue> Ops,
5371 MachineMemOperand *MMO) {
5372 assert(Ops.size() == 5 && "Incompatible number of operands");
5374 FoldingSetNodeID ID;
5375 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
5376 ID.AddInteger(VT.getRawBits());
5377 ID.AddInteger(encodeMemSDNodeFlags(ISD::NON_EXTLOAD, ISD::UNINDEXED,
5379 MMO->isNonTemporal(),
5380 MMO->isInvariant()));
5381 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5383 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5384 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
5385 return SDValue(E, 0);
5388 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5390 createOperands(N, Ops);
5392 assert(N->getValue().getValueType() == N->getValueType(0) &&
5393 "Incompatible type of the PassThru value in MaskedGatherSDNode");
5394 assert(N->getMask().getValueType().getVectorNumElements() ==
5395 N->getValueType(0).getVectorNumElements() &&
5396 "Vector width mismatch between mask and data");
5397 assert(N->getIndex().getValueType().getVectorNumElements() ==
5398 N->getValueType(0).getVectorNumElements() &&
5399 "Vector width mismatch between index and data");
5401 CSEMap.InsertNode(N, IP);
5403 return SDValue(N, 0);
5406 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
5407 ArrayRef<SDValue> Ops,
5408 MachineMemOperand *MMO) {
5409 assert(Ops.size() == 5 && "Incompatible number of operands");
5411 FoldingSetNodeID ID;
5412 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
5413 ID.AddInteger(VT.getRawBits());
5414 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
5415 MMO->isNonTemporal(),
5416 MMO->isInvariant()));
5417 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
5419 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
5420 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
5421 return SDValue(E, 0);
5423 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
5425 createOperands(N, Ops);
5427 assert(N->getMask().getValueType().getVectorNumElements() ==
5428 N->getValue().getValueType().getVectorNumElements() &&
5429 "Vector width mismatch between mask and data");
5430 assert(N->getIndex().getValueType().getVectorNumElements() ==
5431 N->getValue().getValueType().getVectorNumElements() &&
5432 "Vector width mismatch between index and data");
5434 CSEMap.InsertNode(N, IP);
5436 return SDValue(N, 0);
5439 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
5440 SDValue Ptr, SDValue SV, unsigned Align) {
5441 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
5442 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
5445 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5446 ArrayRef<SDUse> Ops) {
5447 switch (Ops.size()) {
5448 case 0: return getNode(Opcode, DL, VT);
5449 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
5450 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
5451 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5455 // Copy from an SDUse array into an SDValue array for use with
5456 // the regular getNode logic.
5457 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
5458 return getNode(Opcode, DL, VT, NewOps);
5461 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5462 ArrayRef<SDValue> Ops, const SDNodeFlags *Flags) {
5463 unsigned NumOps = Ops.size();
5465 case 0: return getNode(Opcode, DL, VT);
5466 case 1: return getNode(Opcode, DL, VT, Ops[0]);
5467 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
5468 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
5474 case ISD::CONCAT_VECTORS: {
5475 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
5476 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
5480 case ISD::SELECT_CC: {
5481 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
5482 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
5483 "LHS and RHS of condition must have same type!");
5484 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
5485 "True and False arms of SelectCC must have same type!");
5486 assert(Ops[2].getValueType() == VT &&
5487 "select_cc node must be of same type as true and false value!");
5491 assert(NumOps == 5 && "BR_CC takes 5 operands!");
5492 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
5493 "LHS/RHS of comparison should match types!");
5500 SDVTList VTs = getVTList(VT);
5502 if (VT != MVT::Glue) {
5503 FoldingSetNodeID ID;
5504 AddNodeIDNode(ID, Opcode, VTs, Ops);
5507 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5508 return SDValue(E, 0);
5510 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5511 createOperands(N, Ops);
5513 CSEMap.InsertNode(N, IP);
5515 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5516 createOperands(N, Ops);
5520 return SDValue(N, 0);
5523 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
5524 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
5525 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
5528 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5529 ArrayRef<SDValue> Ops) {
5530 if (VTList.NumVTs == 1)
5531 return getNode(Opcode, DL, VTList.VTs[0], Ops);
5535 // FIXME: figure out how to safely handle things like
5536 // int foo(int x) { return 1 << (x & 255); }
5537 // int bar() { return foo(256); }
5538 case ISD::SRA_PARTS:
5539 case ISD::SRL_PARTS:
5540 case ISD::SHL_PARTS:
5541 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5542 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
5543 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
5544 else if (N3.getOpcode() == ISD::AND)
5545 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
5546 // If the and is only masking out bits that cannot effect the shift,
5547 // eliminate the and.
5548 unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
5549 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
5550 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
5556 // Memoize the node unless it returns a flag.
5558 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5559 FoldingSetNodeID ID;
5560 AddNodeIDNode(ID, Opcode, VTList, Ops);
5562 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5563 return SDValue(E, 0);
5565 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
5566 createOperands(N, Ops);
5567 CSEMap.InsertNode(N, IP);
5569 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
5570 createOperands(N, Ops);
5573 return SDValue(N, 0);
5576 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
5578 return getNode(Opcode, DL, VTList, None);
5581 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5583 SDValue Ops[] = { N1 };
5584 return getNode(Opcode, DL, VTList, Ops);
5587 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5588 SDValue N1, SDValue N2) {
5589 SDValue Ops[] = { N1, N2 };
5590 return getNode(Opcode, DL, VTList, Ops);
5593 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5594 SDValue N1, SDValue N2, SDValue N3) {
5595 SDValue Ops[] = { N1, N2, N3 };
5596 return getNode(Opcode, DL, VTList, Ops);
5599 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5600 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5601 SDValue Ops[] = { N1, N2, N3, N4 };
5602 return getNode(Opcode, DL, VTList, Ops);
5605 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
5606 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5608 SDValue Ops[] = { N1, N2, N3, N4, N5 };
5609 return getNode(Opcode, DL, VTList, Ops);
5612 SDVTList SelectionDAG::getVTList(EVT VT) {
5613 return makeVTList(SDNode::getValueTypeList(VT), 1);
5616 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
5617 FoldingSetNodeID ID;
5619 ID.AddInteger(VT1.getRawBits());
5620 ID.AddInteger(VT2.getRawBits());
5623 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5625 EVT *Array = Allocator.Allocate<EVT>(2);
5628 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
5629 VTListMap.InsertNode(Result, IP);
5631 return Result->getSDVTList();
5634 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
5635 FoldingSetNodeID ID;
5637 ID.AddInteger(VT1.getRawBits());
5638 ID.AddInteger(VT2.getRawBits());
5639 ID.AddInteger(VT3.getRawBits());
5642 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5644 EVT *Array = Allocator.Allocate<EVT>(3);
5648 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
5649 VTListMap.InsertNode(Result, IP);
5651 return Result->getSDVTList();
5654 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
5655 FoldingSetNodeID ID;
5657 ID.AddInteger(VT1.getRawBits());
5658 ID.AddInteger(VT2.getRawBits());
5659 ID.AddInteger(VT3.getRawBits());
5660 ID.AddInteger(VT4.getRawBits());
5663 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5665 EVT *Array = Allocator.Allocate<EVT>(4);
5670 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
5671 VTListMap.InsertNode(Result, IP);
5673 return Result->getSDVTList();
5676 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
5677 unsigned NumVTs = VTs.size();
5678 FoldingSetNodeID ID;
5679 ID.AddInteger(NumVTs);
5680 for (unsigned index = 0; index < NumVTs; index++) {
5681 ID.AddInteger(VTs[index].getRawBits());
5685 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5687 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
5688 std::copy(VTs.begin(), VTs.end(), Array);
5689 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
5690 VTListMap.InsertNode(Result, IP);
5692 return Result->getSDVTList();
5696 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
5697 /// specified operands. If the resultant node already exists in the DAG,
5698 /// this does not modify the specified node, instead it returns the node that
5699 /// already exists. If the resultant node does not exist in the DAG, the
5700 /// input node is returned. As a degenerate case, if you specify the same
5701 /// input operands as the node already has, the input node is returned.
5702 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
5703 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
5705 // Check to see if there is no change.
5706 if (Op == N->getOperand(0)) return N;
5708 // See if the modified node already exists.
5709 void *InsertPos = nullptr;
5710 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
5713 // Nope it doesn't. Remove the node from its current place in the maps.
5715 if (!RemoveNodeFromCSEMaps(N))
5716 InsertPos = nullptr;
5718 // Now we update the operands.
5719 N->OperandList[0].set(Op);
5721 // If this gets put into a CSE map, add it.
5722 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5726 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
5727 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
5729 // Check to see if there is no change.
5730 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
5731 return N; // No operands changed, just return the input node.
5733 // See if the modified node already exists.
5734 void *InsertPos = nullptr;
5735 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
5738 // Nope it doesn't. Remove the node from its current place in the maps.
5740 if (!RemoveNodeFromCSEMaps(N))
5741 InsertPos = nullptr;
5743 // Now we update the operands.
5744 if (N->OperandList[0] != Op1)
5745 N->OperandList[0].set(Op1);
5746 if (N->OperandList[1] != Op2)
5747 N->OperandList[1].set(Op2);
5749 // If this gets put into a CSE map, add it.
5750 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5754 SDNode *SelectionDAG::
5755 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
5756 SDValue Ops[] = { Op1, Op2, Op3 };
5757 return UpdateNodeOperands(N, Ops);
5760 SDNode *SelectionDAG::
5761 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
5762 SDValue Op3, SDValue Op4) {
5763 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
5764 return UpdateNodeOperands(N, Ops);
5767 SDNode *SelectionDAG::
5768 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
5769 SDValue Op3, SDValue Op4, SDValue Op5) {
5770 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
5771 return UpdateNodeOperands(N, Ops);
5774 SDNode *SelectionDAG::
5775 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
5776 unsigned NumOps = Ops.size();
5777 assert(N->getNumOperands() == NumOps &&
5778 "Update with wrong number of operands");
5780 // If no operands changed just return the input node.
5781 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
5784 // See if the modified node already exists.
5785 void *InsertPos = nullptr;
5786 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
5789 // Nope it doesn't. Remove the node from its current place in the maps.
5791 if (!RemoveNodeFromCSEMaps(N))
5792 InsertPos = nullptr;
5794 // Now we update the operands.
5795 for (unsigned i = 0; i != NumOps; ++i)
5796 if (N->OperandList[i] != Ops[i])
5797 N->OperandList[i].set(Ops[i]);
5799 // If this gets put into a CSE map, add it.
5800 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5804 /// DropOperands - Release the operands and set this node to have
5806 void SDNode::DropOperands() {
5807 // Unlike the code in MorphNodeTo that does this, we don't need to
5808 // watch for dead nodes here.
5809 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
5815 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
5818 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5820 SDVTList VTs = getVTList(VT);
5821 return SelectNodeTo(N, MachineOpc, VTs, None);
5824 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5825 EVT VT, SDValue Op1) {
5826 SDVTList VTs = getVTList(VT);
5827 SDValue Ops[] = { Op1 };
5828 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5831 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5832 EVT VT, SDValue Op1,
5834 SDVTList VTs = getVTList(VT);
5835 SDValue Ops[] = { Op1, Op2 };
5836 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5839 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5840 EVT VT, SDValue Op1,
5841 SDValue Op2, SDValue Op3) {
5842 SDVTList VTs = getVTList(VT);
5843 SDValue Ops[] = { Op1, Op2, Op3 };
5844 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5847 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5848 EVT VT, ArrayRef<SDValue> Ops) {
5849 SDVTList VTs = getVTList(VT);
5850 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5853 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5854 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
5855 SDVTList VTs = getVTList(VT1, VT2);
5856 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5859 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5861 SDVTList VTs = getVTList(VT1, VT2);
5862 return SelectNodeTo(N, MachineOpc, VTs, None);
5865 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5866 EVT VT1, EVT VT2, EVT VT3,
5867 ArrayRef<SDValue> Ops) {
5868 SDVTList VTs = getVTList(VT1, VT2, VT3);
5869 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5872 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5873 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
5874 ArrayRef<SDValue> Ops) {
5875 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5876 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5879 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5882 SDVTList VTs = getVTList(VT1, VT2);
5883 SDValue Ops[] = { Op1 };
5884 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5887 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5889 SDValue Op1, SDValue Op2) {
5890 SDVTList VTs = getVTList(VT1, VT2);
5891 SDValue Ops[] = { Op1, Op2 };
5892 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5895 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5897 SDValue Op1, SDValue Op2,
5899 SDVTList VTs = getVTList(VT1, VT2);
5900 SDValue Ops[] = { Op1, Op2, Op3 };
5901 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5904 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5905 EVT VT1, EVT VT2, EVT VT3,
5906 SDValue Op1, SDValue Op2,
5908 SDVTList VTs = getVTList(VT1, VT2, VT3);
5909 SDValue Ops[] = { Op1, Op2, Op3 };
5910 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5913 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5914 SDVTList VTs,ArrayRef<SDValue> Ops) {
5915 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
5916 // Reset the NodeID to -1.
5919 ReplaceAllUsesWith(N, New);
5925 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away
5926 /// the line number information on the merged node since it is not possible to
5927 /// preserve the information that operation is associated with multiple lines.
5928 /// This will make the debugger working better at -O0, were there is a higher
5929 /// probability having other instructions associated with that line.
5931 /// For IROrder, we keep the smaller of the two
5932 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, const SDLoc &OLoc) {
5933 DebugLoc NLoc = N->getDebugLoc();
5934 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
5935 N->setDebugLoc(DebugLoc());
5937 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
5938 N->setIROrder(Order);
5942 /// MorphNodeTo - This *mutates* the specified node to have the specified
5943 /// return type, opcode, and operands.
5945 /// Note that MorphNodeTo returns the resultant node. If there is already a
5946 /// node of the specified opcode and operands, it returns that node instead of
5947 /// the current one. Note that the SDLoc need not be the same.
5949 /// Using MorphNodeTo is faster than creating a new node and swapping it in
5950 /// with ReplaceAllUsesWith both because it often avoids allocating a new
5951 /// node, and because it doesn't require CSE recalculation for any of
5952 /// the node's users.
5954 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
5955 /// As a consequence it isn't appropriate to use from within the DAG combiner or
5956 /// the legalizer which maintain worklists that would need to be updated when
5957 /// deleting things.
5958 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
5959 SDVTList VTs, ArrayRef<SDValue> Ops) {
5960 // If an identical node already exists, use it.
5962 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
5963 FoldingSetNodeID ID;
5964 AddNodeIDNode(ID, Opc, VTs, Ops);
5965 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
5966 return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N));
5969 if (!RemoveNodeFromCSEMaps(N))
5972 // Start the morphing.
5974 N->ValueList = VTs.VTs;
5975 N->NumValues = VTs.NumVTs;
5977 // Clear the operands list, updating used nodes to remove this from their
5978 // use list. Keep track of any operands that become dead as a result.
5979 SmallPtrSet<SDNode*, 16> DeadNodeSet;
5980 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
5982 SDNode *Used = Use.getNode();
5984 if (Used->use_empty())
5985 DeadNodeSet.insert(Used);
5988 // For MachineNode, initialize the memory references information.
5989 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
5990 MN->setMemRefs(nullptr, nullptr);
5992 // Swap for an appropriately sized array from the recycler.
5994 createOperands(N, Ops);
5996 // Delete any nodes that are still dead after adding the uses for the
5998 if (!DeadNodeSet.empty()) {
5999 SmallVector<SDNode *, 16> DeadNodes;
6000 for (SDNode *N : DeadNodeSet)
6002 DeadNodes.push_back(N);
6003 RemoveDeadNodes(DeadNodes);
6007 CSEMap.InsertNode(N, IP); // Memoize the new node.
6012 /// getMachineNode - These are used for target selectors to create a new node
6013 /// with specified return type(s), MachineInstr opcode, and operands.
6015 /// Note that getMachineNode returns the resultant node. If there is already a
6016 /// node of the specified opcode and operands, it returns that node instead of
6017 /// the current one.
6018 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6020 SDVTList VTs = getVTList(VT);
6021 return getMachineNode(Opcode, dl, VTs, None);
6024 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6025 EVT VT, SDValue Op1) {
6026 SDVTList VTs = getVTList(VT);
6027 SDValue Ops[] = { Op1 };
6028 return getMachineNode(Opcode, dl, VTs, Ops);
6031 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6032 EVT VT, SDValue Op1, SDValue Op2) {
6033 SDVTList VTs = getVTList(VT);
6034 SDValue Ops[] = { Op1, Op2 };
6035 return getMachineNode(Opcode, dl, VTs, Ops);
6038 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6039 EVT VT, SDValue Op1, SDValue Op2,
6041 SDVTList VTs = getVTList(VT);
6042 SDValue Ops[] = { Op1, Op2, Op3 };
6043 return getMachineNode(Opcode, dl, VTs, Ops);
6046 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6047 EVT VT, ArrayRef<SDValue> Ops) {
6048 SDVTList VTs = getVTList(VT);
6049 return getMachineNode(Opcode, dl, VTs, Ops);
6052 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6054 SDVTList VTs = getVTList(VT1, VT2);
6055 return getMachineNode(Opcode, dl, VTs, None);
6058 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6059 EVT VT1, EVT VT2, SDValue Op1) {
6060 SDVTList VTs = getVTList(VT1, VT2);
6061 SDValue Ops[] = { Op1 };
6062 return getMachineNode(Opcode, dl, VTs, Ops);
6065 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6066 EVT VT1, EVT VT2, SDValue Op1,
6068 SDVTList VTs = getVTList(VT1, VT2);
6069 SDValue Ops[] = { Op1, Op2 };
6070 return getMachineNode(Opcode, dl, VTs, Ops);
6073 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6074 EVT VT1, EVT VT2, SDValue Op1,
6075 SDValue Op2, SDValue Op3) {
6076 SDVTList VTs = getVTList(VT1, VT2);
6077 SDValue Ops[] = { Op1, Op2, Op3 };
6078 return getMachineNode(Opcode, dl, VTs, Ops);
6081 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6083 ArrayRef<SDValue> Ops) {
6084 SDVTList VTs = getVTList(VT1, VT2);
6085 return getMachineNode(Opcode, dl, VTs, Ops);
6088 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6089 EVT VT1, EVT VT2, EVT VT3,
6090 SDValue Op1, SDValue Op2) {
6091 SDVTList VTs = getVTList(VT1, VT2, VT3);
6092 SDValue Ops[] = { Op1, Op2 };
6093 return getMachineNode(Opcode, dl, VTs, Ops);
6096 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6097 EVT VT1, EVT VT2, EVT VT3,
6098 SDValue Op1, SDValue Op2,
6100 SDVTList VTs = getVTList(VT1, VT2, VT3);
6101 SDValue Ops[] = { Op1, Op2, Op3 };
6102 return getMachineNode(Opcode, dl, VTs, Ops);
6105 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6106 EVT VT1, EVT VT2, EVT VT3,
6107 ArrayRef<SDValue> Ops) {
6108 SDVTList VTs = getVTList(VT1, VT2, VT3);
6109 return getMachineNode(Opcode, dl, VTs, Ops);
6112 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6113 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
6114 ArrayRef<SDValue> Ops) {
6115 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
6116 return getMachineNode(Opcode, dl, VTs, Ops);
6119 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
6120 ArrayRef<EVT> ResultTys,
6121 ArrayRef<SDValue> Ops) {
6122 SDVTList VTs = getVTList(ResultTys);
6123 return getMachineNode(Opcode, dl, VTs, Ops);
6126 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
6128 ArrayRef<SDValue> Ops) {
6129 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
6134 FoldingSetNodeID ID;
6135 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
6137 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6138 return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL));
6142 // Allocate a new MachineSDNode.
6143 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6144 createOperands(N, Ops);
6147 CSEMap.InsertNode(N, IP);
6153 /// getTargetExtractSubreg - A convenience function for creating
6154 /// TargetOpcode::EXTRACT_SUBREG nodes.
6155 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6157 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6158 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
6159 VT, Operand, SRIdxVal);
6160 return SDValue(Subreg, 0);
6163 /// getTargetInsertSubreg - A convenience function for creating
6164 /// TargetOpcode::INSERT_SUBREG nodes.
6165 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
6166 SDValue Operand, SDValue Subreg) {
6167 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
6168 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
6169 VT, Operand, Subreg, SRIdxVal);
6170 return SDValue(Result, 0);
6173 /// getNodeIfExists - Get the specified node if it's already available, or
6174 /// else return NULL.
6175 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
6176 ArrayRef<SDValue> Ops,
6177 const SDNodeFlags *Flags) {
6178 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
6179 FoldingSetNodeID ID;
6180 AddNodeIDNode(ID, Opcode, VTList, Ops);
6182 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
6184 E->intersectFlagsWith(Flags);
6191 /// getDbgValue - Creates a SDDbgValue node.
6194 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N,
6195 unsigned R, bool IsIndirect, uint64_t Off,
6196 const DebugLoc &DL, unsigned O) {
6197 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6198 "Expected inlined-at fields to agree");
6199 return new (DbgInfo->getAlloc())
6200 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O);
6204 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr,
6205 const Value *C, uint64_t Off,
6206 const DebugLoc &DL, unsigned O) {
6207 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6208 "Expected inlined-at fields to agree");
6209 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O);
6213 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr,
6214 unsigned FI, uint64_t Off,
6217 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
6218 "Expected inlined-at fields to agree");
6219 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O);
6224 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
6225 /// pointed to by a use iterator is deleted, increment the use iterator
6226 /// so that it doesn't dangle.
6228 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
6229 SDNode::use_iterator &UI;
6230 SDNode::use_iterator &UE;
6232 void NodeDeleted(SDNode *N, SDNode *E) override {
6233 // Increment the iterator as needed.
6234 while (UI != UE && N == *UI)
6239 RAUWUpdateListener(SelectionDAG &d,
6240 SDNode::use_iterator &ui,
6241 SDNode::use_iterator &ue)
6242 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
6247 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6248 /// This can cause recursive merging of nodes in the DAG.
6250 /// This version assumes From has a single result value.
6252 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
6253 SDNode *From = FromN.getNode();
6254 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
6255 "Cannot replace with this method!");
6256 assert(From != To.getNode() && "Cannot replace uses of with self");
6258 // Iterate over all the existing uses of From. New uses will be added
6259 // to the beginning of the use list, which we avoid visiting.
6260 // This specifically avoids visiting uses of From that arise while the
6261 // replacement is happening, because any such uses would be the result
6262 // of CSE: If an existing node looks like From after one of its operands
6263 // is replaced by To, we don't want to replace of all its users with To
6264 // too. See PR3018 for more info.
6265 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6266 RAUWUpdateListener Listener(*this, UI, UE);
6270 // This node is about to morph, remove its old self from the CSE maps.
6271 RemoveNodeFromCSEMaps(User);
6273 // A user can appear in a use list multiple times, and when this
6274 // happens the uses are usually next to each other in the list.
6275 // To help reduce the number of CSE recomputations, process all
6276 // the uses of this user that we can find this way.
6278 SDUse &Use = UI.getUse();
6281 } while (UI != UE && *UI == User);
6283 // Now that we have modified User, add it back to the CSE maps. If it
6284 // already exists there, recursively merge the results together.
6285 AddModifiedNodeToCSEMaps(User);
6288 // Preserve Debug Values
6289 TransferDbgValues(FromN, To);
6291 // If we just RAUW'd the root, take note.
6292 if (FromN == getRoot())
6296 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6297 /// This can cause recursive merging of nodes in the DAG.
6299 /// This version assumes that for each value of From, there is a
6300 /// corresponding value in To in the same position with the same type.
6302 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
6304 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6305 assert((!From->hasAnyUseOfValue(i) ||
6306 From->getValueType(i) == To->getValueType(i)) &&
6307 "Cannot use this version of ReplaceAllUsesWith!");
6310 // Handle the trivial case.
6314 // Preserve Debug Info. Only do this if there's a use.
6315 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6316 if (From->hasAnyUseOfValue(i)) {
6317 assert((i < To->getNumValues()) && "Invalid To location");
6318 TransferDbgValues(SDValue(From, i), SDValue(To, i));
6321 // Iterate over just the existing users of From. See the comments in
6322 // the ReplaceAllUsesWith above.
6323 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6324 RAUWUpdateListener Listener(*this, UI, UE);
6328 // This node is about to morph, remove its old self from the CSE maps.
6329 RemoveNodeFromCSEMaps(User);
6331 // A user can appear in a use list multiple times, and when this
6332 // happens the uses are usually next to each other in the list.
6333 // To help reduce the number of CSE recomputations, process all
6334 // the uses of this user that we can find this way.
6336 SDUse &Use = UI.getUse();
6339 } while (UI != UE && *UI == User);
6341 // Now that we have modified User, add it back to the CSE maps. If it
6342 // already exists there, recursively merge the results together.
6343 AddModifiedNodeToCSEMaps(User);
6346 // If we just RAUW'd the root, take note.
6347 if (From == getRoot().getNode())
6348 setRoot(SDValue(To, getRoot().getResNo()));
6351 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
6352 /// This can cause recursive merging of nodes in the DAG.
6354 /// This version can replace From with any result values. To must match the
6355 /// number and types of values returned by From.
6356 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
6357 if (From->getNumValues() == 1) // Handle the simple case efficiently.
6358 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
6360 // Preserve Debug Info.
6361 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
6362 TransferDbgValues(SDValue(From, i), *To);
6364 // Iterate over just the existing users of From. See the comments in
6365 // the ReplaceAllUsesWith above.
6366 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
6367 RAUWUpdateListener Listener(*this, UI, UE);
6371 // This node is about to morph, remove its old self from the CSE maps.
6372 RemoveNodeFromCSEMaps(User);
6374 // A user can appear in a use list multiple times, and when this
6375 // happens the uses are usually next to each other in the list.
6376 // To help reduce the number of CSE recomputations, process all
6377 // the uses of this user that we can find this way.
6379 SDUse &Use = UI.getUse();
6380 const SDValue &ToOp = To[Use.getResNo()];
6383 } while (UI != UE && *UI == User);
6385 // Now that we have modified User, add it back to the CSE maps. If it
6386 // already exists there, recursively merge the results together.
6387 AddModifiedNodeToCSEMaps(User);
6390 // If we just RAUW'd the root, take note.
6391 if (From == getRoot().getNode())
6392 setRoot(SDValue(To[getRoot().getResNo()]));
6395 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
6396 /// uses of other values produced by From.getNode() alone. The Deleted
6397 /// vector is handled the same way as for ReplaceAllUsesWith.
6398 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
6399 // Handle the really simple, really trivial case efficiently.
6400 if (From == To) return;
6402 // Handle the simple, trivial, case efficiently.
6403 if (From.getNode()->getNumValues() == 1) {
6404 ReplaceAllUsesWith(From, To);
6408 // Preserve Debug Info.
6409 TransferDbgValues(From, To);
6411 // Iterate over just the existing users of From. See the comments in
6412 // the ReplaceAllUsesWith above.
6413 SDNode::use_iterator UI = From.getNode()->use_begin(),
6414 UE = From.getNode()->use_end();
6415 RAUWUpdateListener Listener(*this, UI, UE);
6418 bool UserRemovedFromCSEMaps = false;
6420 // A user can appear in a use list multiple times, and when this
6421 // happens the uses are usually next to each other in the list.
6422 // To help reduce the number of CSE recomputations, process all
6423 // the uses of this user that we can find this way.
6425 SDUse &Use = UI.getUse();
6427 // Skip uses of different values from the same node.
6428 if (Use.getResNo() != From.getResNo()) {
6433 // If this node hasn't been modified yet, it's still in the CSE maps,
6434 // so remove its old self from the CSE maps.
6435 if (!UserRemovedFromCSEMaps) {
6436 RemoveNodeFromCSEMaps(User);
6437 UserRemovedFromCSEMaps = true;
6442 } while (UI != UE && *UI == User);
6444 // We are iterating over all uses of the From node, so if a use
6445 // doesn't use the specific value, no changes are made.
6446 if (!UserRemovedFromCSEMaps)
6449 // Now that we have modified User, add it back to the CSE maps. If it
6450 // already exists there, recursively merge the results together.
6451 AddModifiedNodeToCSEMaps(User);
6454 // If we just RAUW'd the root, take note.
6455 if (From == getRoot())
6460 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
6461 /// to record information about a use.
6468 /// operator< - Sort Memos by User.
6469 bool operator<(const UseMemo &L, const UseMemo &R) {
6470 return (intptr_t)L.User < (intptr_t)R.User;
6474 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
6475 /// uses of other values produced by From.getNode() alone. The same value
6476 /// may appear in both the From and To list. The Deleted vector is
6477 /// handled the same way as for ReplaceAllUsesWith.
6478 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
6481 // Handle the simple, trivial case efficiently.
6483 return ReplaceAllUsesOfValueWith(*From, *To);
6485 TransferDbgValues(*From, *To);
6487 // Read up all the uses and make records of them. This helps
6488 // processing new uses that are introduced during the
6489 // replacement process.
6490 SmallVector<UseMemo, 4> Uses;
6491 for (unsigned i = 0; i != Num; ++i) {
6492 unsigned FromResNo = From[i].getResNo();
6493 SDNode *FromNode = From[i].getNode();
6494 for (SDNode::use_iterator UI = FromNode->use_begin(),
6495 E = FromNode->use_end(); UI != E; ++UI) {
6496 SDUse &Use = UI.getUse();
6497 if (Use.getResNo() == FromResNo) {
6498 UseMemo Memo = { *UI, i, &Use };
6499 Uses.push_back(Memo);
6504 // Sort the uses, so that all the uses from a given User are together.
6505 std::sort(Uses.begin(), Uses.end());
6507 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
6508 UseIndex != UseIndexEnd; ) {
6509 // We know that this user uses some value of From. If it is the right
6510 // value, update it.
6511 SDNode *User = Uses[UseIndex].User;
6513 // This node is about to morph, remove its old self from the CSE maps.
6514 RemoveNodeFromCSEMaps(User);
6516 // The Uses array is sorted, so all the uses for a given User
6517 // are next to each other in the list.
6518 // To help reduce the number of CSE recomputations, process all
6519 // the uses of this user that we can find this way.
6521 unsigned i = Uses[UseIndex].Index;
6522 SDUse &Use = *Uses[UseIndex].Use;
6526 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
6528 // Now that we have modified User, add it back to the CSE maps. If it
6529 // already exists there, recursively merge the results together.
6530 AddModifiedNodeToCSEMaps(User);
6534 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
6535 /// based on their topological order. It returns the maximum id and a vector
6536 /// of the SDNodes* in assigned order by reference.
6537 unsigned SelectionDAG::AssignTopologicalOrder() {
6539 unsigned DAGSize = 0;
6541 // SortedPos tracks the progress of the algorithm. Nodes before it are
6542 // sorted, nodes after it are unsorted. When the algorithm completes
6543 // it is at the end of the list.
6544 allnodes_iterator SortedPos = allnodes_begin();
6546 // Visit all the nodes. Move nodes with no operands to the front of
6547 // the list immediately. Annotate nodes that do have operands with their
6548 // operand count. Before we do this, the Node Id fields of the nodes
6549 // may contain arbitrary values. After, the Node Id fields for nodes
6550 // before SortedPos will contain the topological sort index, and the
6551 // Node Id fields for nodes At SortedPos and after will contain the
6552 // count of outstanding operands.
6553 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
6555 checkForCycles(N, this);
6556 unsigned Degree = N->getNumOperands();
6558 // A node with no uses, add it to the result array immediately.
6559 N->setNodeId(DAGSize++);
6560 allnodes_iterator Q(N);
6562 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
6563 assert(SortedPos != AllNodes.end() && "Overran node list");
6566 // Temporarily use the Node Id as scratch space for the degree count.
6567 N->setNodeId(Degree);
6571 // Visit all the nodes. As we iterate, move nodes into sorted order,
6572 // such that by the time the end is reached all nodes will be sorted.
6573 for (SDNode &Node : allnodes()) {
6575 checkForCycles(N, this);
6576 // N is in sorted position, so all its uses have one less operand
6577 // that needs to be sorted.
6578 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6581 unsigned Degree = P->getNodeId();
6582 assert(Degree != 0 && "Invalid node degree");
6585 // All of P's operands are sorted, so P may sorted now.
6586 P->setNodeId(DAGSize++);
6587 if (P->getIterator() != SortedPos)
6588 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
6589 assert(SortedPos != AllNodes.end() && "Overran node list");
6592 // Update P's outstanding operand count.
6593 P->setNodeId(Degree);
6596 if (Node.getIterator() == SortedPos) {
6598 allnodes_iterator I(N);
6600 dbgs() << "Overran sorted position:\n";
6601 S->dumprFull(this); dbgs() << "\n";
6602 dbgs() << "Checking if this is due to cycles\n";
6603 checkForCycles(this, true);
6605 llvm_unreachable(nullptr);
6609 assert(SortedPos == AllNodes.end() &&
6610 "Topological sort incomplete!");
6611 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
6612 "First node in topological sort is not the entry token!");
6613 assert(AllNodes.front().getNodeId() == 0 &&
6614 "First node in topological sort has non-zero id!");
6615 assert(AllNodes.front().getNumOperands() == 0 &&
6616 "First node in topological sort has operands!");
6617 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
6618 "Last node in topologic sort has unexpected id!");
6619 assert(AllNodes.back().use_empty() &&
6620 "Last node in topologic sort has users!");
6621 assert(DAGSize == allnodes_size() && "Node count mismatch!");
6625 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
6626 /// value is produced by SD.
6627 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
6629 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
6630 SD->setHasDebugValue(true);
6632 DbgInfo->add(DB, SD, isParameter);
6635 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes.
6636 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
6637 if (From == To || !From.getNode()->getHasDebugValue())
6639 SDNode *FromNode = From.getNode();
6640 SDNode *ToNode = To.getNode();
6641 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
6642 SmallVector<SDDbgValue *, 2> ClonedDVs;
6643 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
6645 SDDbgValue *Dbg = *I;
6646 // Only add Dbgvalues attached to same ResNo.
6647 if (Dbg->getKind() == SDDbgValue::SDNODE &&
6648 Dbg->getSDNode() == From.getNode() &&
6649 Dbg->getResNo() == From.getResNo() && !Dbg->isInvalidated()) {
6650 assert(FromNode != ToNode &&
6651 "Should not transfer Debug Values intranode");
6653 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode,
6654 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(),
6655 Dbg->getDebugLoc(), Dbg->getOrder());
6656 ClonedDVs.push_back(Clone);
6657 Dbg->setIsInvalidated();
6660 for (SDDbgValue *I : ClonedDVs)
6661 AddDbgValue(I, ToNode, false);
6664 //===----------------------------------------------------------------------===//
6666 //===----------------------------------------------------------------------===//
6668 bool llvm::isNullConstant(SDValue V) {
6669 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
6670 return Const != nullptr && Const->isNullValue();
6673 bool llvm::isNullFPConstant(SDValue V) {
6674 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
6675 return Const != nullptr && Const->isZero() && !Const->isNegative();
6678 bool llvm::isAllOnesConstant(SDValue V) {
6679 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
6680 return Const != nullptr && Const->isAllOnesValue();
6683 bool llvm::isOneConstant(SDValue V) {
6684 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
6685 return Const != nullptr && Const->isOne();
6688 bool llvm::isBitwiseNot(SDValue V) {
6689 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1));
6692 HandleSDNode::~HandleSDNode() {
6696 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
6698 const GlobalValue *GA, EVT VT,
6699 int64_t o, unsigned char TF)
6700 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
6704 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
6705 EVT VT, unsigned SrcAS,
6707 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
6708 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
6710 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
6711 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
6712 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
6713 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
6714 MMO->isNonTemporal(), MMO->isInvariant());
6715 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
6716 assert(isNonTemporal() == MMO->isNonTemporal() &&
6717 "Non-temporal encoding error!");
6718 // We check here that the size of the memory operand fits within the size of
6719 // the MMO. This is because the MMO might indicate only a possible address
6720 // range instead of specifying the affected memory addresses precisely.
6721 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
6724 /// Profile - Gather unique data for the node.
6726 void SDNode::Profile(FoldingSetNodeID &ID) const {
6727 AddNodeIDNode(ID, this);
6732 std::vector<EVT> VTs;
6735 VTs.reserve(MVT::LAST_VALUETYPE);
6736 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
6737 VTs.push_back(MVT((MVT::SimpleValueType)i));
6742 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
6743 static ManagedStatic<EVTArray> SimpleVTArray;
6744 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
6746 /// getValueTypeList - Return a pointer to the specified value type.
6748 const EVT *SDNode::getValueTypeList(EVT VT) {
6749 if (VT.isExtended()) {
6750 sys::SmartScopedLock<true> Lock(*VTMutex);
6751 return &(*EVTs->insert(VT).first);
6753 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
6754 "Value type out of range!");
6755 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
6759 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
6760 /// indicated value. This method ignores uses of other values defined by this
6762 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
6763 assert(Value < getNumValues() && "Bad value!");
6765 // TODO: Only iterate over uses of a given value of the node
6766 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
6767 if (UI.getUse().getResNo() == Value) {
6774 // Found exactly the right number of uses?
6779 /// hasAnyUseOfValue - Return true if there are any use of the indicated
6780 /// value. This method ignores uses of other values defined by this operation.
6781 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
6782 assert(Value < getNumValues() && "Bad value!");
6784 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
6785 if (UI.getUse().getResNo() == Value)
6792 /// isOnlyUserOf - Return true if this node is the only use of N.
6794 bool SDNode::isOnlyUserOf(const SDNode *N) const {
6796 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
6807 /// isOperand - Return true if this node is an operand of N.
6809 bool SDValue::isOperandOf(const SDNode *N) const {
6810 for (const SDValue &Op : N->op_values())
6816 bool SDNode::isOperandOf(const SDNode *N) const {
6817 for (const SDValue &Op : N->op_values())
6818 if (this == Op.getNode())
6823 /// reachesChainWithoutSideEffects - Return true if this operand (which must
6824 /// be a chain) reaches the specified operand without crossing any
6825 /// side-effecting instructions on any chain path. In practice, this looks
6826 /// through token factors and non-volatile loads. In order to remain efficient,
6827 /// this only looks a couple of nodes in, it does not do an exhaustive search.
6828 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
6829 unsigned Depth) const {
6830 if (*this == Dest) return true;
6832 // Don't search too deeply, we just want to be able to see through
6833 // TokenFactor's etc.
6834 if (Depth == 0) return false;
6836 // If this is a token factor, all inputs to the TF happen in parallel. If any
6837 // of the operands of the TF does not reach dest, then we cannot do the xform.
6838 if (getOpcode() == ISD::TokenFactor) {
6839 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6840 if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
6845 // Loads don't have side effects, look through them.
6846 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
6847 if (!Ld->isVolatile())
6848 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
6853 bool SDNode::hasPredecessor(const SDNode *N) const {
6854 SmallPtrSet<const SDNode *, 32> Visited;
6855 SmallVector<const SDNode *, 16> Worklist;
6856 Worklist.push_back(this);
6857 return hasPredecessorHelper(N, Visited, Worklist);
6860 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
6861 assert(Num < NumOperands && "Invalid child # of SDNode!");
6862 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
6865 const SDNodeFlags *SDNode::getFlags() const {
6866 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this))
6867 return &FlagsNode->Flags;
6871 void SDNode::intersectFlagsWith(const SDNodeFlags *Flags) {
6872 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this))
6873 FlagsNode->Flags.intersectWith(Flags);
6876 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6877 assert(N->getNumValues() == 1 &&
6878 "Can't unroll a vector with multiple results!");
6880 EVT VT = N->getValueType(0);
6881 unsigned NE = VT.getVectorNumElements();
6882 EVT EltVT = VT.getVectorElementType();
6885 SmallVector<SDValue, 8> Scalars;
6886 SmallVector<SDValue, 4> Operands(N->getNumOperands());
6888 // If ResNE is 0, fully unroll the vector op.
6891 else if (NE > ResNE)
6895 for (i= 0; i != NE; ++i) {
6896 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
6897 SDValue Operand = N->getOperand(j);
6898 EVT OperandVT = Operand.getValueType();
6899 if (OperandVT.isVector()) {
6900 // A vector operand; extract a single element.
6901 EVT OperandEltVT = OperandVT.getVectorElementType();
6903 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
6904 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
6906 // A scalar operand; just use it as is.
6907 Operands[j] = Operand;
6911 switch (N->getOpcode()) {
6913 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
6918 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
6925 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6926 getShiftAmountOperand(Operands[0].getValueType(),
6929 case ISD::SIGN_EXTEND_INREG:
6930 case ISD::FP_ROUND_INREG: {
6931 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6932 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6934 getValueType(ExtVT)));
6939 for (; i < ResNE; ++i)
6940 Scalars.push_back(getUNDEF(EltVT));
6942 return getNode(ISD::BUILD_VECTOR, dl,
6943 EVT::getVectorVT(*getContext(), EltVT, ResNE), Scalars);
6946 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
6950 if (LD->isVolatile() || Base->isVolatile())
6952 if (LD->isIndexed() || Base->isIndexed())
6954 if (LD->getChain() != Base->getChain())
6956 EVT VT = LD->getValueType(0);
6957 if (VT.getSizeInBits() / 8 != Bytes)
6960 SDValue Loc = LD->getOperand(1);
6961 SDValue BaseLoc = Base->getOperand(1);
6962 if (Loc.getOpcode() == ISD::FrameIndex) {
6963 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6965 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6966 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6967 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6968 int FS = MFI->getObjectSize(FI);
6969 int BFS = MFI->getObjectSize(BFI);
6970 if (FS != BFS || FS != (int)Bytes) return false;
6971 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6975 if (isBaseWithConstantOffset(Loc)) {
6976 int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
6977 if (Loc.getOperand(0) == BaseLoc) {
6978 // If the base location is a simple address with no offset itself, then
6979 // the second load's first add operand should be the base address.
6980 if (LocOffset == Dist * (int)Bytes)
6982 } else if (isBaseWithConstantOffset(BaseLoc)) {
6983 // The base location itself has an offset, so subtract that value from the
6984 // second load's offset before comparing to distance * size.
6986 cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue();
6987 if (Loc.getOperand(0) == BaseLoc.getOperand(0)) {
6988 if ((LocOffset - BOffset) == Dist * (int)Bytes)
6993 const GlobalValue *GV1 = nullptr;
6994 const GlobalValue *GV2 = nullptr;
6995 int64_t Offset1 = 0;
6996 int64_t Offset2 = 0;
6997 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6998 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6999 if (isGA1 && isGA2 && GV1 == GV2)
7000 return Offset1 == (Offset2 + Dist*Bytes);
7005 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
7006 /// it cannot be inferred.
7007 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
7008 // If this is a GlobalAddress + cst, return the alignment.
7009 const GlobalValue *GV;
7010 int64_t GVOffset = 0;
7011 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
7012 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
7013 APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
7014 llvm::computeKnownBits(const_cast<GlobalValue *>(GV), KnownZero, KnownOne,
7016 unsigned AlignBits = KnownZero.countTrailingOnes();
7017 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
7019 return MinAlign(Align, GVOffset);
7022 // If this is a direct reference to a stack slot, use information about the
7023 // stack slot's alignment.
7024 int FrameIdx = 1 << 31;
7025 int64_t FrameOffset = 0;
7026 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
7027 FrameIdx = FI->getIndex();
7028 } else if (isBaseWithConstantOffset(Ptr) &&
7029 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7031 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7032 FrameOffset = Ptr.getConstantOperandVal(1);
7035 if (FrameIdx != (1 << 31)) {
7036 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
7037 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
7045 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
7046 /// which is split (or expanded) into two not necessarily identical pieces.
7047 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
7048 // Currently all types are split in half.
7050 if (!VT.isVector()) {
7051 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
7053 unsigned NumElements = VT.getVectorNumElements();
7054 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7055 LoVT = HiVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
7058 return std::make_pair(LoVT, HiVT);
7061 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
7063 std::pair<SDValue, SDValue>
7064 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
7066 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
7067 N.getValueType().getVectorNumElements() &&
7068 "More vector elements requested than available!");
7070 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
7071 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
7072 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
7073 getConstant(LoVT.getVectorNumElements(), DL,
7074 TLI->getVectorIdxTy(getDataLayout())));
7075 return std::make_pair(Lo, Hi);
7078 void SelectionDAG::ExtractVectorElements(SDValue Op,
7079 SmallVectorImpl<SDValue> &Args,
7080 unsigned Start, unsigned Count) {
7081 EVT VT = Op.getValueType();
7083 Count = VT.getVectorNumElements();
7085 EVT EltVT = VT.getVectorElementType();
7086 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
7088 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
7089 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7090 Op, getConstant(i, SL, IdxTy)));
7094 // getAddressSpace - Return the address space this GlobalAddress belongs to.
7095 unsigned GlobalAddressSDNode::getAddressSpace() const {
7096 return getGlobal()->getType()->getAddressSpace();
7100 Type *ConstantPoolSDNode::getType() const {
7101 if (isMachineConstantPoolEntry())
7102 return Val.MachineCPVal->getType();
7103 return Val.ConstVal->getType();
7106 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
7108 unsigned &SplatBitSize,
7110 unsigned MinSplatBits,
7111 bool isBigEndian) const {
7112 EVT VT = getValueType(0);
7113 assert(VT.isVector() && "Expected a vector type");
7114 unsigned sz = VT.getSizeInBits();
7115 if (MinSplatBits > sz)
7118 SplatValue = APInt(sz, 0);
7119 SplatUndef = APInt(sz, 0);
7121 // Get the bits. Bits with undefined values (when the corresponding element
7122 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
7123 // in SplatValue. If any of the values are not constant, give up and return
7125 unsigned int nOps = getNumOperands();
7126 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
7127 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
7129 for (unsigned j = 0; j < nOps; ++j) {
7130 unsigned i = isBigEndian ? nOps-1-j : j;
7131 SDValue OpVal = getOperand(i);
7132 unsigned BitPos = j * EltBitSize;
7134 if (OpVal.isUndef())
7135 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
7136 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
7137 SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize).
7138 zextOrTrunc(sz) << BitPos;
7139 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
7140 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
7145 // The build_vector is all constants or undefs. Find the smallest element
7146 // size that splats the vector.
7148 HasAnyUndefs = (SplatUndef != 0);
7151 unsigned HalfSize = sz / 2;
7152 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
7153 APInt LowValue = SplatValue.trunc(HalfSize);
7154 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
7155 APInt LowUndef = SplatUndef.trunc(HalfSize);
7157 // If the two halves do not match (ignoring undef bits), stop here.
7158 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
7159 MinSplatBits > HalfSize)
7162 SplatValue = HighValue | LowValue;
7163 SplatUndef = HighUndef & LowUndef;
7172 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
7173 if (UndefElements) {
7174 UndefElements->clear();
7175 UndefElements->resize(getNumOperands());
7178 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
7179 SDValue Op = getOperand(i);
7182 (*UndefElements)[i] = true;
7183 } else if (!Splatted) {
7185 } else if (Splatted != Op) {
7191 assert(getOperand(0).isUndef() &&
7192 "Can only have a splat without a constant for all undefs.");
7193 return getOperand(0);
7200 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
7201 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
7205 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
7206 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
7210 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
7211 uint32_t BitWidth) const {
7212 if (ConstantFPSDNode *CN =
7213 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
7215 APSInt IntVal(BitWidth);
7216 const APFloat &APF = CN->getValueAPF();
7217 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
7222 return IntVal.exactLogBase2();
7227 bool BuildVectorSDNode::isConstant() const {
7228 for (const SDValue &Op : op_values()) {
7229 unsigned Opc = Op.getOpcode();
7230 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
7236 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
7237 // Find the first non-undef value in the shuffle mask.
7239 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
7242 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
7244 // Make sure all remaining elements are either undef or the same as the first
7246 for (int Idx = Mask[i]; i != e; ++i)
7247 if (Mask[i] >= 0 && Mask[i] != Idx)
7252 // \brief Returns the SDNode if it is a constant integer BuildVector
7253 // or constant integer.
7254 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
7255 if (isa<ConstantSDNode>(N))
7257 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
7259 // Treat a GlobalAddress supporting constant offset folding as a
7260 // constant integer.
7261 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
7262 if (GA->getOpcode() == ISD::GlobalAddress &&
7263 TLI->isOffsetFoldingLegal(GA))
7269 static void checkForCyclesHelper(const SDNode *N,
7270 SmallPtrSetImpl<const SDNode*> &Visited,
7271 SmallPtrSetImpl<const SDNode*> &Checked,
7272 const llvm::SelectionDAG *DAG) {
7273 // If this node has already been checked, don't check it again.
7274 if (Checked.count(N))
7277 // If a node has already been visited on this depth-first walk, reject it as
7279 if (!Visited.insert(N).second) {
7280 errs() << "Detected cycle in SelectionDAG\n";
7281 dbgs() << "Offending node:\n";
7282 N->dumprFull(DAG); dbgs() << "\n";
7286 for (const SDValue &Op : N->op_values())
7287 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
7294 void llvm::checkForCycles(const llvm::SDNode *N,
7295 const llvm::SelectionDAG *DAG,
7299 #ifdef EXPENSIVE_CHECKS
7301 #endif // EXPENSIVE_CHECKS
7303 assert(N && "Checking nonexistent SDNode");
7304 SmallPtrSet<const SDNode*, 32> visited;
7305 SmallPtrSet<const SDNode*, 32> checked;
7306 checkForCyclesHelper(N, visited, checked, DAG);
7311 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
7312 checkForCycles(DAG->getRoot().getNode(), DAG, force);