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/SetVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/CallingConv.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/Mutex.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetIntrinsicInfo.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetRegisterInfo.h"
48 #include "llvm/Target/TargetSelectionDAGInfo.h"
54 /// makeVTList - Return an instance of the SDVTList struct initialized with the
55 /// specified members.
56 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
57 SDVTList Res = {VTs, NumVTs};
61 // Default null implementations of the callbacks.
62 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
63 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
65 //===----------------------------------------------------------------------===//
66 // ConstantFPSDNode Class
67 //===----------------------------------------------------------------------===//
69 /// isExactlyValue - We don't rely on operator== working on double values, as
70 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
71 /// As such, this method can be used to do an exact bit-for-bit comparison of
72 /// two floating point values.
73 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
74 return getValueAPF().bitwiseIsEqual(V);
77 bool ConstantFPSDNode::isValueValidForType(EVT VT,
79 assert(VT.isFloatingPoint() && "Can only convert between FP types");
81 // convert modifies in place, so make a copy.
82 APFloat Val2 = APFloat(Val);
84 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
85 APFloat::rmNearestTiesToEven,
90 //===----------------------------------------------------------------------===//
92 //===----------------------------------------------------------------------===//
94 /// isBuildVectorAllOnes - Return true if the specified node is a
95 /// BUILD_VECTOR where all of the elements are ~0 or undef.
96 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
97 // Look through a bit convert.
98 if (N->getOpcode() == ISD::BITCAST)
99 N = N->getOperand(0).getNode();
101 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
103 unsigned i = 0, e = N->getNumOperands();
105 // Skip over all of the undef values.
106 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
109 // Do not accept an all-undef vector.
110 if (i == e) return false;
112 // Do not accept build_vectors that aren't all constants or which have non-~0
113 // elements. We have to be a bit careful here, as the type of the constant
114 // may not be the same as the type of the vector elements due to type
115 // legalization (the elements are promoted to a legal type for the target and
116 // a vector of a type may be legal when the base element type is not).
117 // We only want to check enough bits to cover the vector elements, because
118 // we care if the resultant vector is all ones, not whether the individual
120 SDValue NotZero = N->getOperand(i);
121 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
122 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
123 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
125 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
126 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
131 // Okay, we have at least one ~0 value, check to see if the rest match or are
132 // undefs. Even with the above element type twiddling, this should be OK, as
133 // the same type legalization should have applied to all the elements.
134 for (++i; i != e; ++i)
135 if (N->getOperand(i) != NotZero &&
136 N->getOperand(i).getOpcode() != ISD::UNDEF)
142 /// isBuildVectorAllZeros - Return true if the specified node is a
143 /// BUILD_VECTOR where all of the elements are 0 or undef.
144 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
145 // Look through a bit convert.
146 if (N->getOpcode() == ISD::BITCAST)
147 N = N->getOperand(0).getNode();
149 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
151 unsigned i = 0, e = N->getNumOperands();
153 // Skip over all of the undef values.
154 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
157 // Do not accept an all-undef vector.
158 if (i == e) return false;
160 // Do not accept build_vectors that aren't all constants or which have non-0
162 SDValue Zero = N->getOperand(i);
163 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Zero)) {
164 if (!CN->isNullValue())
166 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Zero)) {
167 if (!CFPN->getValueAPF().isPosZero())
172 // Okay, we have at least one 0 value, check to see if the rest match or are
174 for (++i; i != e; ++i)
175 if (N->getOperand(i) != Zero &&
176 N->getOperand(i).getOpcode() != ISD::UNDEF)
181 /// \brief Return true if the specified node is a BUILD_VECTOR node of
182 /// all ConstantSDNode or undef.
183 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
184 if (N->getOpcode() != ISD::BUILD_VECTOR)
187 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
188 SDValue Op = N->getOperand(i);
189 if (Op.getOpcode() == ISD::UNDEF)
191 if (!isa<ConstantSDNode>(Op))
197 /// isScalarToVector - Return true if the specified node is a
198 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
199 /// element is not an undef.
200 bool ISD::isScalarToVector(const SDNode *N) {
201 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
204 if (N->getOpcode() != ISD::BUILD_VECTOR)
206 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
208 unsigned NumElems = N->getNumOperands();
211 for (unsigned i = 1; i < NumElems; ++i) {
212 SDValue V = N->getOperand(i);
213 if (V.getOpcode() != ISD::UNDEF)
219 /// allOperandsUndef - Return true if the node has at least one operand
220 /// and all operands of the specified node are ISD::UNDEF.
221 bool ISD::allOperandsUndef(const SDNode *N) {
222 // Return false if the node has no operands.
223 // This is "logically inconsistent" with the definition of "all" but
224 // is probably the desired behavior.
225 if (N->getNumOperands() == 0)
228 for (unsigned i = 0, e = N->getNumOperands(); i != e ; ++i)
229 if (N->getOperand(i).getOpcode() != ISD::UNDEF)
235 ISD::NodeType ISD::getExtForLoadExtType(ISD::LoadExtType ExtType) {
238 return ISD::ANY_EXTEND;
240 return ISD::SIGN_EXTEND;
242 return ISD::ZERO_EXTEND;
247 llvm_unreachable("Invalid LoadExtType");
250 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
251 /// when given the operation for (X op Y).
252 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
253 // To perform this operation, we just need to swap the L and G bits of the
255 unsigned OldL = (Operation >> 2) & 1;
256 unsigned OldG = (Operation >> 1) & 1;
257 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
258 (OldL << 1) | // New G bit
259 (OldG << 2)); // New L bit.
262 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
263 /// 'op' is a valid SetCC operation.
264 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
265 unsigned Operation = Op;
267 Operation ^= 7; // Flip L, G, E bits, but not U.
269 Operation ^= 15; // Flip all of the condition bits.
271 if (Operation > ISD::SETTRUE2)
272 Operation &= ~8; // Don't let N and U bits get set.
274 return ISD::CondCode(Operation);
278 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
279 /// signed operation and 2 if the result is an unsigned comparison. Return zero
280 /// if the operation does not depend on the sign of the input (setne and seteq).
281 static int isSignedOp(ISD::CondCode Opcode) {
283 default: llvm_unreachable("Illegal integer setcc operation!");
285 case ISD::SETNE: return 0;
289 case ISD::SETGE: return 1;
293 case ISD::SETUGE: return 2;
297 /// getSetCCOrOperation - Return the result of a logical OR between different
298 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
299 /// returns SETCC_INVALID if it is not possible to represent the resultant
301 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
303 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
304 // Cannot fold a signed integer setcc with an unsigned integer setcc.
305 return ISD::SETCC_INVALID;
307 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
309 // If the N and U bits get set then the resultant comparison DOES suddenly
310 // care about orderedness, and is true when ordered.
311 if (Op > ISD::SETTRUE2)
312 Op &= ~16; // Clear the U bit if the N bit is set.
314 // Canonicalize illegal integer setcc's.
315 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
318 return ISD::CondCode(Op);
321 /// getSetCCAndOperation - Return the result of a logical AND between different
322 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
323 /// function returns zero if it is not possible to represent the resultant
325 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
327 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
328 // Cannot fold a signed setcc with an unsigned setcc.
329 return ISD::SETCC_INVALID;
331 // Combine all of the condition bits.
332 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
334 // Canonicalize illegal integer setcc's.
338 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
339 case ISD::SETOEQ: // SETEQ & SETU[LG]E
340 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
341 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
342 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
349 //===----------------------------------------------------------------------===//
350 // SDNode Profile Support
351 //===----------------------------------------------------------------------===//
353 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
355 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
359 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
360 /// solely with their pointer.
361 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
362 ID.AddPointer(VTList.VTs);
365 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
367 static void AddNodeIDOperands(FoldingSetNodeID &ID,
368 ArrayRef<SDValue> Ops) {
369 for (auto& Op : Ops) {
370 ID.AddPointer(Op.getNode());
371 ID.AddInteger(Op.getResNo());
375 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
377 static void AddNodeIDOperands(FoldingSetNodeID &ID,
378 ArrayRef<SDUse> Ops) {
379 for (auto& Op : Ops) {
380 ID.AddPointer(Op.getNode());
381 ID.AddInteger(Op.getResNo());
385 static void AddBinaryNodeIDCustom(FoldingSetNodeID &ID, bool nuw, bool nsw,
389 ID.AddBoolean(exact);
392 /// AddBinaryNodeIDCustom - Add BinarySDNodes special infos
393 static void AddBinaryNodeIDCustom(FoldingSetNodeID &ID, unsigned Opcode,
394 bool nuw, bool nsw, bool exact) {
395 if (isBinOpWithFlags(Opcode))
396 AddBinaryNodeIDCustom(ID, nuw, nsw, exact);
399 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
400 SDVTList VTList, ArrayRef<SDValue> OpList) {
401 AddNodeIDOpcode(ID, OpC);
402 AddNodeIDValueTypes(ID, VTList);
403 AddNodeIDOperands(ID, OpList);
406 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
408 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
409 switch (N->getOpcode()) {
410 case ISD::TargetExternalSymbol:
411 case ISD::ExternalSymbol:
412 llvm_unreachable("Should only be used on nodes with operands");
413 default: break; // Normal nodes don't need extra info.
414 case ISD::TargetConstant:
415 case ISD::Constant: {
416 const ConstantSDNode *C = cast<ConstantSDNode>(N);
417 ID.AddPointer(C->getConstantIntValue());
418 ID.AddBoolean(C->isOpaque());
421 case ISD::TargetConstantFP:
422 case ISD::ConstantFP: {
423 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
426 case ISD::TargetGlobalAddress:
427 case ISD::GlobalAddress:
428 case ISD::TargetGlobalTLSAddress:
429 case ISD::GlobalTLSAddress: {
430 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
431 ID.AddPointer(GA->getGlobal());
432 ID.AddInteger(GA->getOffset());
433 ID.AddInteger(GA->getTargetFlags());
434 ID.AddInteger(GA->getAddressSpace());
437 case ISD::BasicBlock:
438 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
441 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
443 case ISD::RegisterMask:
444 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
447 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
449 case ISD::FrameIndex:
450 case ISD::TargetFrameIndex:
451 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
454 case ISD::TargetJumpTable:
455 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
456 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
458 case ISD::ConstantPool:
459 case ISD::TargetConstantPool: {
460 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
461 ID.AddInteger(CP->getAlignment());
462 ID.AddInteger(CP->getOffset());
463 if (CP->isMachineConstantPoolEntry())
464 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
466 ID.AddPointer(CP->getConstVal());
467 ID.AddInteger(CP->getTargetFlags());
470 case ISD::TargetIndex: {
471 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
472 ID.AddInteger(TI->getIndex());
473 ID.AddInteger(TI->getOffset());
474 ID.AddInteger(TI->getTargetFlags());
478 const LoadSDNode *LD = cast<LoadSDNode>(N);
479 ID.AddInteger(LD->getMemoryVT().getRawBits());
480 ID.AddInteger(LD->getRawSubclassData());
481 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
485 const StoreSDNode *ST = cast<StoreSDNode>(N);
486 ID.AddInteger(ST->getMemoryVT().getRawBits());
487 ID.AddInteger(ST->getRawSubclassData());
488 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
499 const BinaryWithFlagsSDNode *BinNode = cast<BinaryWithFlagsSDNode>(N);
500 AddBinaryNodeIDCustom(ID, N->getOpcode(), BinNode->hasNoUnsignedWrap(),
501 BinNode->hasNoSignedWrap(), BinNode->isExact());
504 case ISD::ATOMIC_CMP_SWAP:
505 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
506 case ISD::ATOMIC_SWAP:
507 case ISD::ATOMIC_LOAD_ADD:
508 case ISD::ATOMIC_LOAD_SUB:
509 case ISD::ATOMIC_LOAD_AND:
510 case ISD::ATOMIC_LOAD_OR:
511 case ISD::ATOMIC_LOAD_XOR:
512 case ISD::ATOMIC_LOAD_NAND:
513 case ISD::ATOMIC_LOAD_MIN:
514 case ISD::ATOMIC_LOAD_MAX:
515 case ISD::ATOMIC_LOAD_UMIN:
516 case ISD::ATOMIC_LOAD_UMAX:
517 case ISD::ATOMIC_LOAD:
518 case ISD::ATOMIC_STORE: {
519 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
520 ID.AddInteger(AT->getMemoryVT().getRawBits());
521 ID.AddInteger(AT->getRawSubclassData());
522 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
525 case ISD::PREFETCH: {
526 const MemSDNode *PF = cast<MemSDNode>(N);
527 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
530 case ISD::VECTOR_SHUFFLE: {
531 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
532 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
534 ID.AddInteger(SVN->getMaskElt(i));
537 case ISD::TargetBlockAddress:
538 case ISD::BlockAddress: {
539 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
540 ID.AddPointer(BA->getBlockAddress());
541 ID.AddInteger(BA->getOffset());
542 ID.AddInteger(BA->getTargetFlags());
545 } // end switch (N->getOpcode())
547 // Target specific memory nodes could also have address spaces to check.
548 if (N->isTargetMemoryOpcode())
549 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
552 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
554 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
555 AddNodeIDOpcode(ID, N->getOpcode());
556 // Add the return value info.
557 AddNodeIDValueTypes(ID, N->getVTList());
558 // Add the operand info.
559 AddNodeIDOperands(ID, makeArrayRef(N->op_begin(), N->op_end()));
561 // Handle SDNode leafs with special info.
562 AddNodeIDCustom(ID, N);
565 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
566 /// the CSE map that carries volatility, temporalness, indexing mode, and
567 /// extension/truncation information.
569 static inline unsigned
570 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile,
571 bool isNonTemporal, bool isInvariant) {
572 assert((ConvType & 3) == ConvType &&
573 "ConvType may not require more than 2 bits!");
574 assert((AM & 7) == AM &&
575 "AM may not require more than 3 bits!");
579 (isNonTemporal << 6) |
583 //===----------------------------------------------------------------------===//
584 // SelectionDAG Class
585 //===----------------------------------------------------------------------===//
587 /// doNotCSE - Return true if CSE should not be performed for this node.
588 static bool doNotCSE(SDNode *N) {
589 if (N->getValueType(0) == MVT::Glue)
590 return true; // Never CSE anything that produces a flag.
592 switch (N->getOpcode()) {
594 case ISD::HANDLENODE:
596 return true; // Never CSE these nodes.
599 // Check that remaining values produced are not flags.
600 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
601 if (N->getValueType(i) == MVT::Glue)
602 return true; // Never CSE anything that produces a flag.
607 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
609 void SelectionDAG::RemoveDeadNodes() {
610 // Create a dummy node (which is not added to allnodes), that adds a reference
611 // to the root node, preventing it from being deleted.
612 HandleSDNode Dummy(getRoot());
614 SmallVector<SDNode*, 128> DeadNodes;
616 // Add all obviously-dead nodes to the DeadNodes worklist.
617 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
619 DeadNodes.push_back(I);
621 RemoveDeadNodes(DeadNodes);
623 // If the root changed (e.g. it was a dead load, update the root).
624 setRoot(Dummy.getValue());
627 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
628 /// given list, and any nodes that become unreachable as a result.
629 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
631 // Process the worklist, deleting the nodes and adding their uses to the
633 while (!DeadNodes.empty()) {
634 SDNode *N = DeadNodes.pop_back_val();
636 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
637 DUL->NodeDeleted(N, nullptr);
639 // Take the node out of the appropriate CSE map.
640 RemoveNodeFromCSEMaps(N);
642 // Next, brutally remove the operand list. This is safe to do, as there are
643 // no cycles in the graph.
644 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
646 SDNode *Operand = Use.getNode();
649 // Now that we removed this operand, see if there are no uses of it left.
650 if (Operand->use_empty())
651 DeadNodes.push_back(Operand);
658 void SelectionDAG::RemoveDeadNode(SDNode *N){
659 SmallVector<SDNode*, 16> DeadNodes(1, N);
661 // Create a dummy node that adds a reference to the root node, preventing
662 // it from being deleted. (This matters if the root is an operand of the
664 HandleSDNode Dummy(getRoot());
666 RemoveDeadNodes(DeadNodes);
669 void SelectionDAG::DeleteNode(SDNode *N) {
670 // First take this out of the appropriate CSE map.
671 RemoveNodeFromCSEMaps(N);
673 // Finally, remove uses due to operands of this node, remove from the
674 // AllNodes list, and delete the node.
675 DeleteNodeNotInCSEMaps(N);
678 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
679 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
680 assert(N->use_empty() && "Cannot delete a node that is not dead!");
682 // Drop all of the operands and decrement used node's use counts.
688 void SelectionDAG::DeallocateNode(SDNode *N) {
689 if (N->OperandsNeedDelete)
690 delete[] N->OperandList;
692 // Set the opcode to DELETED_NODE to help catch bugs when node
693 // memory is reallocated.
694 N->NodeType = ISD::DELETED_NODE;
696 NodeAllocator.Deallocate(AllNodes.remove(N));
698 // If any of the SDDbgValue nodes refer to this SDNode, invalidate them.
699 ArrayRef<SDDbgValue*> DbgVals = DbgInfo->getSDDbgValues(N);
700 for (unsigned i = 0, e = DbgVals.size(); i != e; ++i)
701 DbgVals[i]->setIsInvalidated();
704 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
705 /// correspond to it. This is useful when we're about to delete or repurpose
706 /// the node. We don't want future request for structurally identical nodes
707 /// to return N anymore.
708 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
710 switch (N->getOpcode()) {
711 case ISD::HANDLENODE: return false; // noop.
713 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
714 "Cond code doesn't exist!");
715 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
716 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
718 case ISD::ExternalSymbol:
719 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
721 case ISD::TargetExternalSymbol: {
722 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
723 Erased = TargetExternalSymbols.erase(
724 std::pair<std::string,unsigned char>(ESN->getSymbol(),
725 ESN->getTargetFlags()));
728 case ISD::VALUETYPE: {
729 EVT VT = cast<VTSDNode>(N)->getVT();
730 if (VT.isExtended()) {
731 Erased = ExtendedValueTypeNodes.erase(VT);
733 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
734 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
739 // Remove it from the CSE Map.
740 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
741 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
742 Erased = CSEMap.RemoveNode(N);
746 // Verify that the node was actually in one of the CSE maps, unless it has a
747 // flag result (which cannot be CSE'd) or is one of the special cases that are
748 // not subject to CSE.
749 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
750 !N->isMachineOpcode() && !doNotCSE(N)) {
753 llvm_unreachable("Node is not in map!");
759 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
760 /// maps and modified in place. Add it back to the CSE maps, unless an identical
761 /// node already exists, in which case transfer all its users to the existing
762 /// node. This transfer can potentially trigger recursive merging.
765 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
766 // For node types that aren't CSE'd, just act as if no identical node
769 SDNode *Existing = CSEMap.GetOrInsertNode(N);
771 // If there was already an existing matching node, use ReplaceAllUsesWith
772 // to replace the dead one with the existing one. This can cause
773 // recursive merging of other unrelated nodes down the line.
774 ReplaceAllUsesWith(N, Existing);
776 // N is now dead. Inform the listeners and delete it.
777 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
778 DUL->NodeDeleted(N, Existing);
779 DeleteNodeNotInCSEMaps(N);
784 // If the node doesn't already exist, we updated it. Inform listeners.
785 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
789 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
790 /// were replaced with those specified. If this node is never memoized,
791 /// return null, otherwise return a pointer to the slot it would take. If a
792 /// node already exists with these operands, the slot will be non-null.
793 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
798 SDValue Ops[] = { Op };
800 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
801 AddNodeIDCustom(ID, N);
802 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
806 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
807 /// were replaced with those specified. If this node is never memoized,
808 /// return null, otherwise return a pointer to the slot it would take. If a
809 /// node already exists with these operands, the slot will be non-null.
810 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
811 SDValue Op1, SDValue Op2,
816 SDValue Ops[] = { Op1, Op2 };
818 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
819 AddNodeIDCustom(ID, N);
820 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
825 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
826 /// were replaced with those specified. If this node is never memoized,
827 /// return null, otherwise return a pointer to the slot it would take. If a
828 /// node already exists with these operands, the slot will be non-null.
829 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
835 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
836 AddNodeIDCustom(ID, N);
837 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
842 /// VerifyNodeCommon - Sanity check the given node. Aborts if it is invalid.
843 static void VerifyNodeCommon(SDNode *N) {
844 switch (N->getOpcode()) {
847 case ISD::BUILD_PAIR: {
848 EVT VT = N->getValueType(0);
849 assert(N->getNumValues() == 1 && "Too many results!");
850 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
851 "Wrong return type!");
852 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
853 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
854 "Mismatched operand types!");
855 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
856 "Wrong operand type!");
857 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
858 "Wrong return type size");
861 case ISD::BUILD_VECTOR: {
862 assert(N->getNumValues() == 1 && "Too many results!");
863 assert(N->getValueType(0).isVector() && "Wrong return type!");
864 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
865 "Wrong number of operands!");
866 EVT EltVT = N->getValueType(0).getVectorElementType();
867 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
868 assert((I->getValueType() == EltVT ||
869 (EltVT.isInteger() && I->getValueType().isInteger() &&
870 EltVT.bitsLE(I->getValueType()))) &&
871 "Wrong operand type!");
872 assert(I->getValueType() == N->getOperand(0).getValueType() &&
873 "Operands must all have the same type");
880 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
881 static void VerifySDNode(SDNode *N) {
882 // The SDNode allocators cannot be used to allocate nodes with fields that are
883 // not present in an SDNode!
884 assert(!isa<MemSDNode>(N) && "Bad MemSDNode!");
885 assert(!isa<ShuffleVectorSDNode>(N) && "Bad ShuffleVectorSDNode!");
886 assert(!isa<ConstantSDNode>(N) && "Bad ConstantSDNode!");
887 assert(!isa<ConstantFPSDNode>(N) && "Bad ConstantFPSDNode!");
888 assert(!isa<GlobalAddressSDNode>(N) && "Bad GlobalAddressSDNode!");
889 assert(!isa<FrameIndexSDNode>(N) && "Bad FrameIndexSDNode!");
890 assert(!isa<JumpTableSDNode>(N) && "Bad JumpTableSDNode!");
891 assert(!isa<ConstantPoolSDNode>(N) && "Bad ConstantPoolSDNode!");
892 assert(!isa<BasicBlockSDNode>(N) && "Bad BasicBlockSDNode!");
893 assert(!isa<SrcValueSDNode>(N) && "Bad SrcValueSDNode!");
894 assert(!isa<MDNodeSDNode>(N) && "Bad MDNodeSDNode!");
895 assert(!isa<RegisterSDNode>(N) && "Bad RegisterSDNode!");
896 assert(!isa<BlockAddressSDNode>(N) && "Bad BlockAddressSDNode!");
897 assert(!isa<EHLabelSDNode>(N) && "Bad EHLabelSDNode!");
898 assert(!isa<ExternalSymbolSDNode>(N) && "Bad ExternalSymbolSDNode!");
899 assert(!isa<CondCodeSDNode>(N) && "Bad CondCodeSDNode!");
900 assert(!isa<CvtRndSatSDNode>(N) && "Bad CvtRndSatSDNode!");
901 assert(!isa<VTSDNode>(N) && "Bad VTSDNode!");
902 assert(!isa<MachineSDNode>(N) && "Bad MachineSDNode!");
907 /// VerifyMachineNode - Sanity check the given MachineNode. Aborts if it is
909 static void VerifyMachineNode(SDNode *N) {
910 // The MachineNode allocators cannot be used to allocate nodes with fields
911 // that are not present in a MachineNode!
912 // Currently there are no such nodes.
918 /// getEVTAlignment - Compute the default alignment value for the
921 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
922 Type *Ty = VT == MVT::iPTR ?
923 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
924 VT.getTypeForEVT(*getContext());
926 return TM.getTargetLowering()->getDataLayout()->getABITypeAlignment(Ty);
929 // EntryNode could meaningfully have debug info if we can find it...
930 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
931 : TM(tm), TSI(*tm.getSelectionDAGInfo()), TLI(nullptr), OptLevel(OL),
932 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
933 Root(getEntryNode()), NewNodesMustHaveLegalTypes(false),
934 UpdateListeners(nullptr) {
935 AllNodes.push_back(&EntryNode);
936 DbgInfo = new SDDbgInfo();
939 void SelectionDAG::init(MachineFunction &mf, const TargetLowering *tli) {
942 Context = &mf.getFunction()->getContext();
945 SelectionDAG::~SelectionDAG() {
946 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
951 void SelectionDAG::allnodes_clear() {
952 assert(&*AllNodes.begin() == &EntryNode);
953 AllNodes.remove(AllNodes.begin());
954 while (!AllNodes.empty())
955 DeallocateNode(AllNodes.begin());
958 BinarySDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, SDLoc DL,
959 SDVTList VTs, SDValue N1,
960 SDValue N2, bool nuw, bool nsw,
962 if (isBinOpWithFlags(Opcode)) {
963 BinaryWithFlagsSDNode *FN = new (NodeAllocator) BinaryWithFlagsSDNode(
964 Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2);
965 FN->setHasNoUnsignedWrap(nuw);
966 FN->setHasNoSignedWrap(nsw);
967 FN->setIsExact(exact);
972 BinarySDNode *N = new (NodeAllocator)
973 BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2);
977 void SelectionDAG::clear() {
979 OperandAllocator.Reset();
982 ExtendedValueTypeNodes.clear();
983 ExternalSymbols.clear();
984 TargetExternalSymbols.clear();
985 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
986 static_cast<CondCodeSDNode*>(nullptr));
987 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
988 static_cast<SDNode*>(nullptr));
990 EntryNode.UseList = nullptr;
991 AllNodes.push_back(&EntryNode);
992 Root = getEntryNode();
996 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
997 return VT.bitsGT(Op.getValueType()) ?
998 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
999 getNode(ISD::TRUNCATE, DL, VT, Op);
1002 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
1003 return VT.bitsGT(Op.getValueType()) ?
1004 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1005 getNode(ISD::TRUNCATE, DL, VT, Op);
1008 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
1009 return VT.bitsGT(Op.getValueType()) ?
1010 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1011 getNode(ISD::TRUNCATE, DL, VT, Op);
1014 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, SDLoc SL, EVT VT) {
1015 if (VT.bitsLE(Op.getValueType()))
1016 return getNode(ISD::TRUNCATE, SL, VT, Op);
1018 TargetLowering::BooleanContent BType = TLI->getBooleanContents(VT.isVector());
1019 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1022 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, SDLoc DL, EVT VT) {
1023 assert(!VT.isVector() &&
1024 "getZeroExtendInReg should use the vector element type instead of "
1025 "the vector type!");
1026 if (Op.getValueType() == VT) return Op;
1027 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1028 APInt Imm = APInt::getLowBitsSet(BitWidth,
1029 VT.getSizeInBits());
1030 return getNode(ISD::AND, DL, Op.getValueType(), Op,
1031 getConstant(Imm, Op.getValueType()));
1034 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1036 SDValue SelectionDAG::getNOT(SDLoc DL, SDValue Val, EVT VT) {
1037 EVT EltVT = VT.getScalarType();
1039 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
1040 return getNode(ISD::XOR, DL, VT, Val, NegOne);
1043 SDValue SelectionDAG::getLogicalNOT(SDLoc DL, SDValue Val, EVT VT) {
1044 EVT EltVT = VT.getScalarType();
1046 switch (TLI->getBooleanContents(VT.isVector())) {
1047 case TargetLowering::ZeroOrOneBooleanContent:
1048 case TargetLowering::UndefinedBooleanContent:
1049 TrueValue = getConstant(1, VT);
1051 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1052 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
1056 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1059 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT, bool isO) {
1060 EVT EltVT = VT.getScalarType();
1061 assert((EltVT.getSizeInBits() >= 64 ||
1062 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1063 "getConstant with a uint64_t value that doesn't fit in the type!");
1064 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT, isO);
1067 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT, bool isO)
1069 return getConstant(*ConstantInt::get(*Context, Val), VT, isT, isO);
1072 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT,
1074 assert(VT.isInteger() && "Cannot create FP integer constant!");
1076 EVT EltVT = VT.getScalarType();
1077 const ConstantInt *Elt = &Val;
1079 const TargetLowering *TLI = TM.getTargetLowering();
1081 // In some cases the vector type is legal but the element type is illegal and
1082 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1083 // inserted value (the type does not need to match the vector element type).
1084 // Any extra bits introduced will be truncated away.
1085 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1086 TargetLowering::TypePromoteInteger) {
1087 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1088 APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits());
1089 Elt = ConstantInt::get(*getContext(), NewVal);
1091 // In other cases the element type is illegal and needs to be expanded, for
1092 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1093 // the value into n parts and use a vector type with n-times the elements.
1094 // Then bitcast to the type requested.
1095 // Legalizing constants too early makes the DAGCombiner's job harder so we
1096 // only legalize if the DAG tells us we must produce legal types.
1097 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1098 TLI->getTypeAction(*getContext(), EltVT) ==
1099 TargetLowering::TypeExpandInteger) {
1100 APInt NewVal = Elt->getValue();
1101 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1102 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1103 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1104 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1106 // Check the temporary vector is the correct size. If this fails then
1107 // getTypeToTransformTo() probably returned a type whose size (in bits)
1108 // isn't a power-of-2 factor of the requested type size.
1109 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1111 SmallVector<SDValue, 2> EltParts;
1112 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1113 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1114 .trunc(ViaEltSizeInBits),
1115 ViaEltVT, isT, isO));
1118 // EltParts is currently in little endian order. If we actually want
1119 // big-endian order then reverse it now.
1120 if (TLI->isBigEndian())
1121 std::reverse(EltParts.begin(), EltParts.end());
1123 // The elements must be reversed when the element order is different
1124 // to the endianness of the elements (because the BITCAST is itself a
1125 // vector shuffle in this situation). However, we do not need any code to
1126 // perform this reversal because getConstant() is producing a vector
1128 // This situation occurs in MIPS MSA.
1130 SmallVector<SDValue, 8> Ops;
1131 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i)
1132 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1134 SDValue Result = getNode(ISD::BITCAST, SDLoc(), VT,
1135 getNode(ISD::BUILD_VECTOR, SDLoc(), ViaVecVT,
1140 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1141 "APInt size does not match type size!");
1142 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1143 FoldingSetNodeID ID;
1144 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1148 SDNode *N = nullptr;
1149 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
1151 return SDValue(N, 0);
1154 N = new (NodeAllocator) ConstantSDNode(isT, isO, Elt, EltVT);
1155 CSEMap.InsertNode(N, IP);
1156 AllNodes.push_back(N);
1159 SDValue Result(N, 0);
1160 if (VT.isVector()) {
1161 SmallVector<SDValue, 8> Ops;
1162 Ops.assign(VT.getVectorNumElements(), Result);
1163 Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Ops);
1168 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
1169 return getConstant(Val, TM.getTargetLowering()->getPointerTy(), isTarget);
1173 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
1174 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
1177 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
1178 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1180 EVT EltVT = VT.getScalarType();
1182 // Do the map lookup using the actual bit pattern for the floating point
1183 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1184 // we don't have issues with SNANs.
1185 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1186 FoldingSetNodeID ID;
1187 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1190 SDNode *N = nullptr;
1191 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
1193 return SDValue(N, 0);
1196 N = new (NodeAllocator) ConstantFPSDNode(isTarget, &V, EltVT);
1197 CSEMap.InsertNode(N, IP);
1198 AllNodes.push_back(N);
1201 SDValue Result(N, 0);
1202 if (VT.isVector()) {
1203 SmallVector<SDValue, 8> Ops;
1204 Ops.assign(VT.getVectorNumElements(), Result);
1205 // FIXME SDLoc info might be appropriate here
1206 Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Ops);
1211 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
1212 EVT EltVT = VT.getScalarType();
1213 if (EltVT==MVT::f32)
1214 return getConstantFP(APFloat((float)Val), VT, isTarget);
1215 else if (EltVT==MVT::f64)
1216 return getConstantFP(APFloat(Val), VT, isTarget);
1217 else if (EltVT==MVT::f80 || EltVT==MVT::f128 || EltVT==MVT::ppcf128 ||
1220 APFloat apf = APFloat(Val);
1221 apf.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1223 return getConstantFP(apf, VT, isTarget);
1225 llvm_unreachable("Unsupported type in getConstantFP");
1228 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, SDLoc DL,
1229 EVT VT, int64_t Offset,
1231 unsigned char TargetFlags) {
1232 assert((TargetFlags == 0 || isTargetGA) &&
1233 "Cannot set target flags on target-independent globals");
1234 const TargetLowering *TLI = TM.getTargetLowering();
1236 // Truncate (with sign-extension) the offset value to the pointer size.
1237 unsigned BitWidth = TLI->getPointerTypeSizeInBits(GV->getType());
1239 Offset = SignExtend64(Offset, BitWidth);
1242 if (GV->isThreadLocal())
1243 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1245 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1247 FoldingSetNodeID ID;
1248 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1250 ID.AddInteger(Offset);
1251 ID.AddInteger(TargetFlags);
1252 ID.AddInteger(GV->getType()->getAddressSpace());
1254 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1255 return SDValue(E, 0);
1257 SDNode *N = new (NodeAllocator) GlobalAddressSDNode(Opc, DL.getIROrder(),
1258 DL.getDebugLoc(), GV, VT,
1259 Offset, TargetFlags);
1260 CSEMap.InsertNode(N, IP);
1261 AllNodes.push_back(N);
1262 return SDValue(N, 0);
1265 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1266 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1267 FoldingSetNodeID ID;
1268 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1271 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1272 return SDValue(E, 0);
1274 SDNode *N = new (NodeAllocator) FrameIndexSDNode(FI, VT, isTarget);
1275 CSEMap.InsertNode(N, IP);
1276 AllNodes.push_back(N);
1277 return SDValue(N, 0);
1280 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1281 unsigned char TargetFlags) {
1282 assert((TargetFlags == 0 || isTarget) &&
1283 "Cannot set target flags on target-independent jump tables");
1284 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1285 FoldingSetNodeID ID;
1286 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1288 ID.AddInteger(TargetFlags);
1290 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1291 return SDValue(E, 0);
1293 SDNode *N = new (NodeAllocator) JumpTableSDNode(JTI, VT, isTarget,
1295 CSEMap.InsertNode(N, IP);
1296 AllNodes.push_back(N);
1297 return SDValue(N, 0);
1300 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1301 unsigned Alignment, int Offset,
1303 unsigned char TargetFlags) {
1304 assert((TargetFlags == 0 || isTarget) &&
1305 "Cannot set target flags on target-independent globals");
1308 TM.getTargetLowering()->getDataLayout()->getPrefTypeAlignment(C->getType());
1309 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1310 FoldingSetNodeID ID;
1311 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1312 ID.AddInteger(Alignment);
1313 ID.AddInteger(Offset);
1315 ID.AddInteger(TargetFlags);
1317 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1318 return SDValue(E, 0);
1320 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1321 Alignment, TargetFlags);
1322 CSEMap.InsertNode(N, IP);
1323 AllNodes.push_back(N);
1324 return SDValue(N, 0);
1328 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1329 unsigned Alignment, int Offset,
1331 unsigned char TargetFlags) {
1332 assert((TargetFlags == 0 || isTarget) &&
1333 "Cannot set target flags on target-independent globals");
1336 TM.getTargetLowering()->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);
1342 C->addSelectionDAGCSEId(ID);
1343 ID.AddInteger(TargetFlags);
1345 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1346 return SDValue(E, 0);
1348 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1349 Alignment, TargetFlags);
1350 CSEMap.InsertNode(N, IP);
1351 AllNodes.push_back(N);
1352 return SDValue(N, 0);
1355 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1356 unsigned char TargetFlags) {
1357 FoldingSetNodeID ID;
1358 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1359 ID.AddInteger(Index);
1360 ID.AddInteger(Offset);
1361 ID.AddInteger(TargetFlags);
1363 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1364 return SDValue(E, 0);
1366 SDNode *N = new (NodeAllocator) TargetIndexSDNode(Index, VT, Offset,
1368 CSEMap.InsertNode(N, IP);
1369 AllNodes.push_back(N);
1370 return SDValue(N, 0);
1373 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1374 FoldingSetNodeID ID;
1375 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1378 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1379 return SDValue(E, 0);
1381 SDNode *N = new (NodeAllocator) BasicBlockSDNode(MBB);
1382 CSEMap.InsertNode(N, IP);
1383 AllNodes.push_back(N);
1384 return SDValue(N, 0);
1387 SDValue SelectionDAG::getValueType(EVT VT) {
1388 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1389 ValueTypeNodes.size())
1390 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1392 SDNode *&N = VT.isExtended() ?
1393 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1395 if (N) return SDValue(N, 0);
1396 N = new (NodeAllocator) VTSDNode(VT);
1397 AllNodes.push_back(N);
1398 return SDValue(N, 0);
1401 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1402 SDNode *&N = ExternalSymbols[Sym];
1403 if (N) return SDValue(N, 0);
1404 N = new (NodeAllocator) ExternalSymbolSDNode(false, Sym, 0, VT);
1405 AllNodes.push_back(N);
1406 return SDValue(N, 0);
1409 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1410 unsigned char TargetFlags) {
1412 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1414 if (N) return SDValue(N, 0);
1415 N = new (NodeAllocator) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1416 AllNodes.push_back(N);
1417 return SDValue(N, 0);
1420 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1421 if ((unsigned)Cond >= CondCodeNodes.size())
1422 CondCodeNodes.resize(Cond+1);
1424 if (!CondCodeNodes[Cond]) {
1425 CondCodeSDNode *N = new (NodeAllocator) CondCodeSDNode(Cond);
1426 CondCodeNodes[Cond] = N;
1427 AllNodes.push_back(N);
1430 return SDValue(CondCodeNodes[Cond], 0);
1433 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1434 // the shuffle mask M that point at N1 to point at N2, and indices that point
1435 // N2 to point at N1.
1436 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1438 int NElts = M.size();
1439 for (int i = 0; i != NElts; ++i) {
1447 SDValue SelectionDAG::getVectorShuffle(EVT VT, SDLoc dl, SDValue N1,
1448 SDValue N2, const int *Mask) {
1449 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1450 "Invalid VECTOR_SHUFFLE");
1452 // Canonicalize shuffle undef, undef -> undef
1453 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1454 return getUNDEF(VT);
1456 // Validate that all indices in Mask are within the range of the elements
1457 // input to the shuffle.
1458 unsigned NElts = VT.getVectorNumElements();
1459 SmallVector<int, 8> MaskVec;
1460 for (unsigned i = 0; i != NElts; ++i) {
1461 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1462 MaskVec.push_back(Mask[i]);
1465 // Canonicalize shuffle v, v -> v, undef
1468 for (unsigned i = 0; i != NElts; ++i)
1469 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1472 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1473 if (N1.getOpcode() == ISD::UNDEF)
1474 commuteShuffle(N1, N2, MaskVec);
1476 // Canonicalize all index into lhs, -> shuffle lhs, undef
1477 // Canonicalize all index into rhs, -> shuffle rhs, undef
1478 bool AllLHS = true, AllRHS = true;
1479 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1480 for (unsigned i = 0; i != NElts; ++i) {
1481 if (MaskVec[i] >= (int)NElts) {
1486 } else if (MaskVec[i] >= 0) {
1490 if (AllLHS && AllRHS)
1491 return getUNDEF(VT);
1492 if (AllLHS && !N2Undef)
1496 commuteShuffle(N1, N2, MaskVec);
1499 // If Identity shuffle return that node.
1500 bool Identity = true;
1501 for (unsigned i = 0; i != NElts; ++i) {
1502 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1504 if (Identity && NElts)
1507 // Shuffling a constant splat doesn't change the result.
1508 if (N2Undef && N1.getOpcode() == ISD::BUILD_VECTOR)
1509 if (cast<BuildVectorSDNode>(N1)->getConstantSplatValue())
1512 FoldingSetNodeID ID;
1513 SDValue Ops[2] = { N1, N2 };
1514 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1515 for (unsigned i = 0; i != NElts; ++i)
1516 ID.AddInteger(MaskVec[i]);
1519 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1520 return SDValue(E, 0);
1522 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1523 // SDNode doesn't have access to it. This memory will be "leaked" when
1524 // the node is deallocated, but recovered when the NodeAllocator is released.
1525 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1526 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1528 ShuffleVectorSDNode *N =
1529 new (NodeAllocator) ShuffleVectorSDNode(VT, dl.getIROrder(),
1530 dl.getDebugLoc(), N1, N2,
1532 CSEMap.InsertNode(N, IP);
1533 AllNodes.push_back(N);
1534 return SDValue(N, 0);
1537 SDValue SelectionDAG::getConvertRndSat(EVT VT, SDLoc dl,
1538 SDValue Val, SDValue DTy,
1539 SDValue STy, SDValue Rnd, SDValue Sat,
1540 ISD::CvtCode Code) {
1541 // If the src and dest types are the same and the conversion is between
1542 // integer types of the same sign or two floats, no conversion is necessary.
1544 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1547 FoldingSetNodeID ID;
1548 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1549 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), Ops);
1551 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1552 return SDValue(E, 0);
1554 CvtRndSatSDNode *N = new (NodeAllocator) CvtRndSatSDNode(VT, dl.getIROrder(),
1557 CSEMap.InsertNode(N, IP);
1558 AllNodes.push_back(N);
1559 return SDValue(N, 0);
1562 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1563 FoldingSetNodeID ID;
1564 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1565 ID.AddInteger(RegNo);
1567 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1568 return SDValue(E, 0);
1570 SDNode *N = new (NodeAllocator) RegisterSDNode(RegNo, VT);
1571 CSEMap.InsertNode(N, IP);
1572 AllNodes.push_back(N);
1573 return SDValue(N, 0);
1576 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1577 FoldingSetNodeID ID;
1578 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1579 ID.AddPointer(RegMask);
1581 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1582 return SDValue(E, 0);
1584 SDNode *N = new (NodeAllocator) RegisterMaskSDNode(RegMask);
1585 CSEMap.InsertNode(N, IP);
1586 AllNodes.push_back(N);
1587 return SDValue(N, 0);
1590 SDValue SelectionDAG::getEHLabel(SDLoc dl, SDValue Root, MCSymbol *Label) {
1591 FoldingSetNodeID ID;
1592 SDValue Ops[] = { Root };
1593 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops);
1594 ID.AddPointer(Label);
1596 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1597 return SDValue(E, 0);
1599 SDNode *N = new (NodeAllocator) EHLabelSDNode(dl.getIROrder(),
1600 dl.getDebugLoc(), Root, Label);
1601 CSEMap.InsertNode(N, IP);
1602 AllNodes.push_back(N);
1603 return SDValue(N, 0);
1607 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1610 unsigned char TargetFlags) {
1611 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1613 FoldingSetNodeID ID;
1614 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1616 ID.AddInteger(Offset);
1617 ID.AddInteger(TargetFlags);
1619 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1620 return SDValue(E, 0);
1622 SDNode *N = new (NodeAllocator) BlockAddressSDNode(Opc, VT, BA, Offset,
1624 CSEMap.InsertNode(N, IP);
1625 AllNodes.push_back(N);
1626 return SDValue(N, 0);
1629 SDValue SelectionDAG::getSrcValue(const Value *V) {
1630 assert((!V || V->getType()->isPointerTy()) &&
1631 "SrcValue is not a pointer?");
1633 FoldingSetNodeID ID;
1634 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1638 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1639 return SDValue(E, 0);
1641 SDNode *N = new (NodeAllocator) SrcValueSDNode(V);
1642 CSEMap.InsertNode(N, IP);
1643 AllNodes.push_back(N);
1644 return SDValue(N, 0);
1647 /// getMDNode - Return an MDNodeSDNode which holds an MDNode.
1648 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1649 FoldingSetNodeID ID;
1650 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1654 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1655 return SDValue(E, 0);
1657 SDNode *N = new (NodeAllocator) MDNodeSDNode(MD);
1658 CSEMap.InsertNode(N, IP);
1659 AllNodes.push_back(N);
1660 return SDValue(N, 0);
1663 /// getAddrSpaceCast - Return an AddrSpaceCastSDNode.
1664 SDValue SelectionDAG::getAddrSpaceCast(SDLoc dl, EVT VT, SDValue Ptr,
1665 unsigned SrcAS, unsigned DestAS) {
1666 SDValue Ops[] = {Ptr};
1667 FoldingSetNodeID ID;
1668 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1669 ID.AddInteger(SrcAS);
1670 ID.AddInteger(DestAS);
1673 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1674 return SDValue(E, 0);
1676 SDNode *N = new (NodeAllocator) AddrSpaceCastSDNode(dl.getIROrder(),
1678 VT, Ptr, SrcAS, DestAS);
1679 CSEMap.InsertNode(N, IP);
1680 AllNodes.push_back(N);
1681 return SDValue(N, 0);
1684 /// getShiftAmountOperand - Return the specified value casted to
1685 /// the target's desired shift amount type.
1686 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1687 EVT OpTy = Op.getValueType();
1688 EVT ShTy = TM.getTargetLowering()->getShiftAmountTy(LHSTy);
1689 if (OpTy == ShTy || OpTy.isVector()) return Op;
1691 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1692 return getNode(Opcode, SDLoc(Op), ShTy, Op);
1695 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1696 /// specified value type.
1697 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1698 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1699 unsigned ByteSize = VT.getStoreSize();
1700 Type *Ty = VT.getTypeForEVT(*getContext());
1701 const TargetLowering *TLI = TM.getTargetLowering();
1702 unsigned StackAlign =
1703 std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty), minAlign);
1705 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1706 return getFrameIndex(FrameIdx, TLI->getPointerTy());
1709 /// CreateStackTemporary - Create a stack temporary suitable for holding
1710 /// either of the specified value types.
1711 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1712 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1713 VT2.getStoreSizeInBits())/8;
1714 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1715 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1716 const TargetLowering *TLI = TM.getTargetLowering();
1717 const DataLayout *TD = TLI->getDataLayout();
1718 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1719 TD->getPrefTypeAlignment(Ty2));
1721 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1722 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1723 return getFrameIndex(FrameIdx, TLI->getPointerTy());
1726 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1727 SDValue N2, ISD::CondCode Cond, SDLoc dl) {
1728 // These setcc operations always fold.
1732 case ISD::SETFALSE2: return getConstant(0, VT);
1734 case ISD::SETTRUE2: {
1735 const TargetLowering *TLI = TM.getTargetLowering();
1736 TargetLowering::BooleanContent Cnt = TLI->getBooleanContents(VT.isVector());
1738 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, VT);
1751 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1755 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1756 const APInt &C2 = N2C->getAPIntValue();
1757 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1758 const APInt &C1 = N1C->getAPIntValue();
1761 default: llvm_unreachable("Unknown integer setcc!");
1762 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1763 case ISD::SETNE: return getConstant(C1 != C2, VT);
1764 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1765 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1766 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1767 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1768 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1769 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1770 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1771 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1775 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1776 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1777 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1780 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1781 return getUNDEF(VT);
1783 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1784 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1785 return getUNDEF(VT);
1787 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1788 R==APFloat::cmpLessThan, VT);
1789 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1790 return getUNDEF(VT);
1792 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1793 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1794 return getUNDEF(VT);
1796 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1797 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1798 return getUNDEF(VT);
1800 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1801 R==APFloat::cmpEqual, VT);
1802 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1803 return getUNDEF(VT);
1805 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1806 R==APFloat::cmpEqual, VT);
1807 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1808 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1809 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1810 R==APFloat::cmpEqual, VT);
1811 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1812 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1813 R==APFloat::cmpLessThan, VT);
1814 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1815 R==APFloat::cmpUnordered, VT);
1816 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1817 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1820 // Ensure that the constant occurs on the RHS.
1821 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
1822 MVT CompVT = N1.getValueType().getSimpleVT();
1823 if (!TM.getTargetLowering()->isCondCodeLegal(SwappedCond, CompVT))
1826 return getSetCC(dl, VT, N2, N1, SwappedCond);
1830 // Could not fold it.
1834 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1835 /// use this predicate to simplify operations downstream.
1836 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1837 // This predicate is not safe for vector operations.
1838 if (Op.getValueType().isVector())
1841 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1842 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1845 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1846 /// this predicate to simplify operations downstream. Mask is known to be zero
1847 /// for bits that V cannot have.
1848 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1849 unsigned Depth) const {
1850 APInt KnownZero, KnownOne;
1851 computeKnownBits(Op, KnownZero, KnownOne, Depth);
1852 return (KnownZero & Mask) == Mask;
1855 /// Determine which bits of Op are known to be either zero or one and return
1856 /// them in the KnownZero/KnownOne bitsets.
1857 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero,
1858 APInt &KnownOne, unsigned Depth) const {
1859 const TargetLowering *TLI = TM.getTargetLowering();
1860 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1862 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1864 return; // Limit search depth.
1866 APInt KnownZero2, KnownOne2;
1868 switch (Op.getOpcode()) {
1870 // We know all of the bits for a constant!
1871 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
1872 KnownZero = ~KnownOne;
1875 // If either the LHS or the RHS are Zero, the result is zero.
1876 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1877 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1879 // Output known-1 bits are only known if set in both the LHS & RHS.
1880 KnownOne &= KnownOne2;
1881 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1882 KnownZero |= KnownZero2;
1885 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1886 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1888 // Output known-0 bits are only known if clear in both the LHS & RHS.
1889 KnownZero &= KnownZero2;
1890 // Output known-1 are known to be set if set in either the LHS | RHS.
1891 KnownOne |= KnownOne2;
1894 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1895 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1897 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1898 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1899 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1900 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1901 KnownZero = KnownZeroOut;
1905 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1906 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1908 // If low bits are zero in either operand, output low known-0 bits.
1909 // Also compute a conserative estimate for high known-0 bits.
1910 // More trickiness is possible, but this is sufficient for the
1911 // interesting case of alignment computation.
1912 KnownOne.clearAllBits();
1913 unsigned TrailZ = KnownZero.countTrailingOnes() +
1914 KnownZero2.countTrailingOnes();
1915 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1916 KnownZero2.countLeadingOnes(),
1917 BitWidth) - BitWidth;
1919 TrailZ = std::min(TrailZ, BitWidth);
1920 LeadZ = std::min(LeadZ, BitWidth);
1921 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1922 APInt::getHighBitsSet(BitWidth, LeadZ);
1926 // For the purposes of computing leading zeros we can conservatively
1927 // treat a udiv as a logical right shift by the power of 2 known to
1928 // be less than the denominator.
1929 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1930 unsigned LeadZ = KnownZero2.countLeadingOnes();
1932 KnownOne2.clearAllBits();
1933 KnownZero2.clearAllBits();
1934 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
1935 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1936 if (RHSUnknownLeadingOnes != BitWidth)
1937 LeadZ = std::min(BitWidth,
1938 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1940 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
1944 computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1);
1945 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
1947 // Only known if known in both the LHS and RHS.
1948 KnownOne &= KnownOne2;
1949 KnownZero &= KnownZero2;
1951 case ISD::SELECT_CC:
1952 computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1);
1953 computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1);
1955 // Only known if known in both the LHS and RHS.
1956 KnownOne &= KnownOne2;
1957 KnownZero &= KnownZero2;
1965 if (Op.getResNo() != 1)
1967 // The boolean result conforms to getBooleanContents. Fall through.
1969 // If we know the result of a setcc has the top bits zero, use this info.
1970 if (TLI->getBooleanContents(Op.getValueType().isVector()) ==
1971 TargetLowering::ZeroOrOneBooleanContent && BitWidth > 1)
1972 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1975 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1976 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1977 unsigned ShAmt = SA->getZExtValue();
1979 // If the shift count is an invalid immediate, don't do anything.
1980 if (ShAmt >= BitWidth)
1983 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1984 KnownZero <<= ShAmt;
1986 // low bits known zero.
1987 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1991 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1992 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1993 unsigned ShAmt = SA->getZExtValue();
1995 // If the shift count is an invalid immediate, don't do anything.
1996 if (ShAmt >= BitWidth)
1999 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2000 KnownZero = KnownZero.lshr(ShAmt);
2001 KnownOne = KnownOne.lshr(ShAmt);
2003 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
2004 KnownZero |= HighBits; // High bits known zero.
2008 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2009 unsigned ShAmt = SA->getZExtValue();
2011 // If the shift count is an invalid immediate, don't do anything.
2012 if (ShAmt >= BitWidth)
2015 // If any of the demanded bits are produced by the sign extension, we also
2016 // demand the input sign bit.
2017 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
2019 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2020 KnownZero = KnownZero.lshr(ShAmt);
2021 KnownOne = KnownOne.lshr(ShAmt);
2023 // Handle the sign bits.
2024 APInt SignBit = APInt::getSignBit(BitWidth);
2025 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
2027 if (KnownZero.intersects(SignBit)) {
2028 KnownZero |= HighBits; // New bits are known zero.
2029 } else if (KnownOne.intersects(SignBit)) {
2030 KnownOne |= HighBits; // New bits are known one.
2034 case ISD::SIGN_EXTEND_INREG: {
2035 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2036 unsigned EBits = EVT.getScalarType().getSizeInBits();
2038 // Sign extension. Compute the demanded bits in the result that are not
2039 // present in the input.
2040 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2042 APInt InSignBit = APInt::getSignBit(EBits);
2043 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2045 // If the sign extended bits are demanded, we know that the sign
2047 InSignBit = InSignBit.zext(BitWidth);
2048 if (NewBits.getBoolValue())
2049 InputDemandedBits |= InSignBit;
2051 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2052 KnownOne &= InputDemandedBits;
2053 KnownZero &= InputDemandedBits;
2055 // If the sign bit of the input is known set or clear, then we know the
2056 // top bits of the result.
2057 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
2058 KnownZero |= NewBits;
2059 KnownOne &= ~NewBits;
2060 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
2061 KnownOne |= NewBits;
2062 KnownZero &= ~NewBits;
2063 } else { // Input sign bit unknown
2064 KnownZero &= ~NewBits;
2065 KnownOne &= ~NewBits;
2070 case ISD::CTTZ_ZERO_UNDEF:
2072 case ISD::CTLZ_ZERO_UNDEF:
2074 unsigned LowBits = Log2_32(BitWidth)+1;
2075 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
2076 KnownOne.clearAllBits();
2080 LoadSDNode *LD = cast<LoadSDNode>(Op);
2081 // If this is a ZEXTLoad and we are looking at the loaded value.
2082 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2083 EVT VT = LD->getMemoryVT();
2084 unsigned MemBits = VT.getScalarType().getSizeInBits();
2085 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
2086 } else if (const MDNode *Ranges = LD->getRanges()) {
2087 computeKnownBitsLoad(*Ranges, KnownZero);
2091 case ISD::ZERO_EXTEND: {
2092 EVT InVT = Op.getOperand(0).getValueType();
2093 unsigned InBits = InVT.getScalarType().getSizeInBits();
2094 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
2095 KnownZero = KnownZero.trunc(InBits);
2096 KnownOne = KnownOne.trunc(InBits);
2097 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2098 KnownZero = KnownZero.zext(BitWidth);
2099 KnownOne = KnownOne.zext(BitWidth);
2100 KnownZero |= NewBits;
2103 case ISD::SIGN_EXTEND: {
2104 EVT InVT = Op.getOperand(0).getValueType();
2105 unsigned InBits = InVT.getScalarType().getSizeInBits();
2106 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
2108 KnownZero = KnownZero.trunc(InBits);
2109 KnownOne = KnownOne.trunc(InBits);
2110 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2112 // Note if the sign bit is known to be zero or one.
2113 bool SignBitKnownZero = KnownZero.isNegative();
2114 bool SignBitKnownOne = KnownOne.isNegative();
2116 KnownZero = KnownZero.zext(BitWidth);
2117 KnownOne = KnownOne.zext(BitWidth);
2119 // If the sign bit is known zero or one, the top bits match.
2120 if (SignBitKnownZero)
2121 KnownZero |= NewBits;
2122 else if (SignBitKnownOne)
2123 KnownOne |= NewBits;
2126 case ISD::ANY_EXTEND: {
2127 EVT InVT = Op.getOperand(0).getValueType();
2128 unsigned InBits = InVT.getScalarType().getSizeInBits();
2129 KnownZero = KnownZero.trunc(InBits);
2130 KnownOne = KnownOne.trunc(InBits);
2131 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2132 KnownZero = KnownZero.zext(BitWidth);
2133 KnownOne = KnownOne.zext(BitWidth);
2136 case ISD::TRUNCATE: {
2137 EVT InVT = Op.getOperand(0).getValueType();
2138 unsigned InBits = InVT.getScalarType().getSizeInBits();
2139 KnownZero = KnownZero.zext(InBits);
2140 KnownOne = KnownOne.zext(InBits);
2141 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2142 KnownZero = KnownZero.trunc(BitWidth);
2143 KnownOne = KnownOne.trunc(BitWidth);
2146 case ISD::AssertZext: {
2147 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2148 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2149 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2150 KnownZero |= (~InMask);
2151 KnownOne &= (~KnownZero);
2155 // All bits are zero except the low bit.
2156 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
2160 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
2161 // We know that the top bits of C-X are clear if X contains less bits
2162 // than C (i.e. no wrap-around can happen). For example, 20-X is
2163 // positive if we can prove that X is >= 0 and < 16.
2164 if (CLHS->getAPIntValue().isNonNegative()) {
2165 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2166 // NLZ can't be BitWidth with no sign bit
2167 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2168 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2170 // If all of the MaskV bits are known to be zero, then we know the
2171 // output top bits are zero, because we now know that the output is
2173 if ((KnownZero2 & MaskV) == MaskV) {
2174 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2175 // Top bits known zero.
2176 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
2184 // Output known-0 bits are known if clear or set in both the low clear bits
2185 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2186 // low 3 bits clear.
2187 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2188 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
2190 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2191 KnownZeroOut = std::min(KnownZeroOut,
2192 KnownZero2.countTrailingOnes());
2194 if (Op.getOpcode() == ISD::ADD) {
2195 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
2199 // With ADDE, a carry bit may be added in, so we can only use this
2200 // information if we know (at least) that the low two bits are clear. We
2201 // then return to the caller that the low bit is unknown but that other bits
2203 if (KnownZeroOut >= 2) // ADDE
2204 KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroOut);
2208 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2209 const APInt &RA = Rem->getAPIntValue().abs();
2210 if (RA.isPowerOf2()) {
2211 APInt LowBits = RA - 1;
2212 computeKnownBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1);
2214 // The low bits of the first operand are unchanged by the srem.
2215 KnownZero = KnownZero2 & LowBits;
2216 KnownOne = KnownOne2 & LowBits;
2218 // If the first operand is non-negative or has all low bits zero, then
2219 // the upper bits are all zero.
2220 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2221 KnownZero |= ~LowBits;
2223 // If the first operand is negative and not all low bits are zero, then
2224 // the upper bits are all one.
2225 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2226 KnownOne |= ~LowBits;
2227 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2232 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2233 const APInt &RA = Rem->getAPIntValue();
2234 if (RA.isPowerOf2()) {
2235 APInt LowBits = (RA - 1);
2236 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth + 1);
2238 // The upper bits are all zero, the lower ones are unchanged.
2239 KnownZero = KnownZero2 | ~LowBits;
2240 KnownOne = KnownOne2 & LowBits;
2245 // Since the result is less than or equal to either operand, any leading
2246 // zero bits in either operand must also exist in the result.
2247 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2248 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2250 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2251 KnownZero2.countLeadingOnes());
2252 KnownOne.clearAllBits();
2253 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
2256 case ISD::FrameIndex:
2257 case ISD::TargetFrameIndex:
2258 if (unsigned Align = InferPtrAlignment(Op)) {
2259 // The low bits are known zero if the pointer is aligned.
2260 KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align));
2266 if (Op.getOpcode() < ISD::BUILTIN_OP_END)
2269 case ISD::INTRINSIC_WO_CHAIN:
2270 case ISD::INTRINSIC_W_CHAIN:
2271 case ISD::INTRINSIC_VOID:
2272 // Allow the target to implement this method for its nodes.
2273 TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth);
2277 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
2280 /// ComputeNumSignBits - Return the number of times the sign bit of the
2281 /// register is replicated into the other bits. We know that at least 1 bit
2282 /// is always equal to the sign bit (itself), but other cases can give us
2283 /// information. For example, immediately after an "SRA X, 2", we know that
2284 /// the top 3 bits are all equal to each other, so we return 3.
2285 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
2286 const TargetLowering *TLI = TM.getTargetLowering();
2287 EVT VT = Op.getValueType();
2288 assert(VT.isInteger() && "Invalid VT!");
2289 unsigned VTBits = VT.getScalarType().getSizeInBits();
2291 unsigned FirstAnswer = 1;
2294 return 1; // Limit search depth.
2296 switch (Op.getOpcode()) {
2298 case ISD::AssertSext:
2299 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2300 return VTBits-Tmp+1;
2301 case ISD::AssertZext:
2302 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2305 case ISD::Constant: {
2306 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2307 return Val.getNumSignBits();
2310 case ISD::SIGN_EXTEND:
2312 VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2313 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2315 case ISD::SIGN_EXTEND_INREG:
2316 // Max of the input and what this extends.
2318 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
2321 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2322 return std::max(Tmp, Tmp2);
2325 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2326 // SRA X, C -> adds C sign bits.
2327 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2328 Tmp += C->getZExtValue();
2329 if (Tmp > VTBits) Tmp = VTBits;
2333 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2334 // shl destroys sign bits.
2335 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2336 if (C->getZExtValue() >= VTBits || // Bad shift.
2337 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2338 return Tmp - C->getZExtValue();
2343 case ISD::XOR: // NOT is handled here.
2344 // Logical binary ops preserve the number of sign bits at the worst.
2345 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2347 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2348 FirstAnswer = std::min(Tmp, Tmp2);
2349 // We computed what we know about the sign bits as our first
2350 // answer. Now proceed to the generic code that uses
2351 // computeKnownBits, and pick whichever answer is better.
2356 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2357 if (Tmp == 1) return 1; // Early out.
2358 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2359 return std::min(Tmp, Tmp2);
2367 if (Op.getResNo() != 1)
2369 // The boolean result conforms to getBooleanContents. Fall through.
2371 // If setcc returns 0/-1, all bits are sign bits.
2372 if (TLI->getBooleanContents(Op.getValueType().isVector()) ==
2373 TargetLowering::ZeroOrNegativeOneBooleanContent)
2378 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2379 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2381 // Handle rotate right by N like a rotate left by 32-N.
2382 if (Op.getOpcode() == ISD::ROTR)
2383 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2385 // If we aren't rotating out all of the known-in sign bits, return the
2386 // number that are left. This handles rotl(sext(x), 1) for example.
2387 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2388 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2392 // Add can have at most one carry bit. Thus we know that the output
2393 // is, at worst, one more bit than the inputs.
2394 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2395 if (Tmp == 1) return 1; // Early out.
2397 // Special case decrementing a value (ADD X, -1):
2398 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2399 if (CRHS->isAllOnesValue()) {
2400 APInt KnownZero, KnownOne;
2401 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2403 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2405 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2408 // If we are subtracting one from a positive number, there is no carry
2409 // out of the result.
2410 if (KnownZero.isNegative())
2414 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2415 if (Tmp2 == 1) return 1;
2416 return std::min(Tmp, Tmp2)-1;
2419 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2420 if (Tmp2 == 1) return 1;
2423 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2424 if (CLHS->isNullValue()) {
2425 APInt KnownZero, KnownOne;
2426 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2427 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2429 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2432 // If the input is known to be positive (the sign bit is known clear),
2433 // the output of the NEG has the same number of sign bits as the input.
2434 if (KnownZero.isNegative())
2437 // Otherwise, we treat this like a SUB.
2440 // Sub can have at most one carry bit. Thus we know that the output
2441 // is, at worst, one more bit than the inputs.
2442 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2443 if (Tmp == 1) return 1; // Early out.
2444 return std::min(Tmp, Tmp2)-1;
2446 // FIXME: it's tricky to do anything useful for this, but it is an important
2447 // case for targets like X86.
2451 // If we are looking at the loaded value of the SDNode.
2452 if (Op.getResNo() == 0) {
2453 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2454 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
2455 unsigned ExtType = LD->getExtensionType();
2458 case ISD::SEXTLOAD: // '17' bits known
2459 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2460 return VTBits-Tmp+1;
2461 case ISD::ZEXTLOAD: // '16' bits known
2462 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2468 // Allow the target to implement this method for its nodes.
2469 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2470 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2471 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2472 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2473 unsigned NumBits = TLI->ComputeNumSignBitsForTargetNode(Op, *this, Depth);
2474 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2477 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2478 // use this information.
2479 APInt KnownZero, KnownOne;
2480 computeKnownBits(Op, KnownZero, KnownOne, Depth);
2483 if (KnownZero.isNegative()) { // sign bit is 0
2485 } else if (KnownOne.isNegative()) { // sign bit is 1;
2492 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2493 // the number of identical bits in the top of the input value.
2495 Mask <<= Mask.getBitWidth()-VTBits;
2496 // Return # leading zeros. We use 'min' here in case Val was zero before
2497 // shifting. We don't want to return '64' as for an i32 "0".
2498 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2501 /// isBaseWithConstantOffset - Return true if the specified operand is an
2502 /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an
2503 /// ISD::OR with a ConstantSDNode that is guaranteed to have the same
2504 /// semantics as an ADD. This handles the equivalence:
2505 /// X|Cst == X+Cst iff X&Cst = 0.
2506 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
2507 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
2508 !isa<ConstantSDNode>(Op.getOperand(1)))
2511 if (Op.getOpcode() == ISD::OR &&
2512 !MaskedValueIsZero(Op.getOperand(0),
2513 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
2520 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2521 // If we're told that NaNs won't happen, assume they won't.
2522 if (getTarget().Options.NoNaNsFPMath)
2525 // If the value is a constant, we can obviously see if it is a NaN or not.
2526 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2527 return !C->getValueAPF().isNaN();
2529 // TODO: Recognize more cases here.
2534 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2535 // If the value is a constant, we can obviously see if it is a zero or not.
2536 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2537 return !C->isZero();
2539 // TODO: Recognize more cases here.
2540 switch (Op.getOpcode()) {
2543 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2544 return !C->isNullValue();
2551 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2552 // Check the obvious case.
2553 if (A == B) return true;
2555 // For for negative and positive zero.
2556 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2557 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2558 if (CA->isZero() && CB->isZero()) return true;
2560 // Otherwise they may not be equal.
2564 /// getNode - Gets or creates the specified node.
2566 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT) {
2567 FoldingSetNodeID ID;
2568 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
2570 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2571 return SDValue(E, 0);
2573 SDNode *N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(),
2574 DL.getDebugLoc(), getVTList(VT));
2575 CSEMap.InsertNode(N, IP);
2577 AllNodes.push_back(N);
2581 return SDValue(N, 0);
2584 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
2585 EVT VT, SDValue Operand) {
2586 // Constant fold unary operations with an integer constant operand. Even
2587 // opaque constant will be folded, because the folding of unary operations
2588 // doesn't create new constants with different values. Nevertheless, the
2589 // opaque flag is preserved during folding to prevent future folding with
2591 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2592 const APInt &Val = C->getAPIntValue();
2595 case ISD::SIGN_EXTEND:
2596 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), VT,
2597 C->isTargetOpcode(), C->isOpaque());
2598 case ISD::ANY_EXTEND:
2599 case ISD::ZERO_EXTEND:
2601 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), VT,
2602 C->isTargetOpcode(), C->isOpaque());
2603 case ISD::UINT_TO_FP:
2604 case ISD::SINT_TO_FP: {
2605 APFloat apf(EVTToAPFloatSemantics(VT),
2606 APInt::getNullValue(VT.getSizeInBits()));
2607 (void)apf.convertFromAPInt(Val,
2608 Opcode==ISD::SINT_TO_FP,
2609 APFloat::rmNearestTiesToEven);
2610 return getConstantFP(apf, VT);
2613 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2614 return getConstantFP(APFloat(APFloat::IEEEsingle, Val), VT);
2615 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2616 return getConstantFP(APFloat(APFloat::IEEEdouble, Val), VT);
2619 return getConstant(Val.byteSwap(), VT, C->isTargetOpcode(),
2622 return getConstant(Val.countPopulation(), VT, C->isTargetOpcode(),
2625 case ISD::CTLZ_ZERO_UNDEF:
2626 return getConstant(Val.countLeadingZeros(), VT, C->isTargetOpcode(),
2629 case ISD::CTTZ_ZERO_UNDEF:
2630 return getConstant(Val.countTrailingZeros(), VT, C->isTargetOpcode(),
2635 // Constant fold unary operations with a floating point constant operand.
2636 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2637 APFloat V = C->getValueAPF(); // make copy
2641 return getConstantFP(V, VT);
2644 return getConstantFP(V, VT);
2646 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
2647 if (fs == APFloat::opOK || fs == APFloat::opInexact)
2648 return getConstantFP(V, VT);
2652 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
2653 if (fs == APFloat::opOK || fs == APFloat::opInexact)
2654 return getConstantFP(V, VT);
2658 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
2659 if (fs == APFloat::opOK || fs == APFloat::opInexact)
2660 return getConstantFP(V, VT);
2663 case ISD::FP_EXTEND: {
2665 // This can return overflow, underflow, or inexact; we don't care.
2666 // FIXME need to be more flexible about rounding mode.
2667 (void)V.convert(EVTToAPFloatSemantics(VT),
2668 APFloat::rmNearestTiesToEven, &ignored);
2669 return getConstantFP(V, VT);
2671 case ISD::FP_TO_SINT:
2672 case ISD::FP_TO_UINT: {
2675 assert(integerPartWidth >= 64);
2676 // FIXME need to be more flexible about rounding mode.
2677 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2678 Opcode==ISD::FP_TO_SINT,
2679 APFloat::rmTowardZero, &ignored);
2680 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2682 APInt api(VT.getSizeInBits(), x);
2683 return getConstant(api, VT);
2686 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2687 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2688 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2689 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2694 unsigned OpOpcode = Operand.getNode()->getOpcode();
2696 case ISD::TokenFactor:
2697 case ISD::MERGE_VALUES:
2698 case ISD::CONCAT_VECTORS:
2699 return Operand; // Factor, merge or concat of one node? No need.
2700 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2701 case ISD::FP_EXTEND:
2702 assert(VT.isFloatingPoint() &&
2703 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2704 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2705 assert((!VT.isVector() ||
2706 VT.getVectorNumElements() ==
2707 Operand.getValueType().getVectorNumElements()) &&
2708 "Vector element count mismatch!");
2709 if (Operand.getOpcode() == ISD::UNDEF)
2710 return getUNDEF(VT);
2712 case ISD::SIGN_EXTEND:
2713 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2714 "Invalid SIGN_EXTEND!");
2715 if (Operand.getValueType() == VT) return Operand; // noop extension
2716 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2717 "Invalid sext node, dst < src!");
2718 assert((!VT.isVector() ||
2719 VT.getVectorNumElements() ==
2720 Operand.getValueType().getVectorNumElements()) &&
2721 "Vector element count mismatch!");
2722 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2723 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2724 else if (OpOpcode == ISD::UNDEF)
2725 // sext(undef) = 0, because the top bits will all be the same.
2726 return getConstant(0, VT);
2728 case ISD::ZERO_EXTEND:
2729 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2730 "Invalid ZERO_EXTEND!");
2731 if (Operand.getValueType() == VT) return Operand; // noop extension
2732 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2733 "Invalid zext node, dst < src!");
2734 assert((!VT.isVector() ||
2735 VT.getVectorNumElements() ==
2736 Operand.getValueType().getVectorNumElements()) &&
2737 "Vector element count mismatch!");
2738 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2739 return getNode(ISD::ZERO_EXTEND, DL, VT,
2740 Operand.getNode()->getOperand(0));
2741 else if (OpOpcode == ISD::UNDEF)
2742 // zext(undef) = 0, because the top bits will be zero.
2743 return getConstant(0, VT);
2745 case ISD::ANY_EXTEND:
2746 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2747 "Invalid ANY_EXTEND!");
2748 if (Operand.getValueType() == VT) return Operand; // noop extension
2749 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2750 "Invalid anyext node, dst < src!");
2751 assert((!VT.isVector() ||
2752 VT.getVectorNumElements() ==
2753 Operand.getValueType().getVectorNumElements()) &&
2754 "Vector element count mismatch!");
2756 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2757 OpOpcode == ISD::ANY_EXTEND)
2758 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2759 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2760 else if (OpOpcode == ISD::UNDEF)
2761 return getUNDEF(VT);
2763 // (ext (trunx x)) -> x
2764 if (OpOpcode == ISD::TRUNCATE) {
2765 SDValue OpOp = Operand.getNode()->getOperand(0);
2766 if (OpOp.getValueType() == VT)
2771 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2772 "Invalid TRUNCATE!");
2773 if (Operand.getValueType() == VT) return Operand; // noop truncate
2774 assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2775 "Invalid truncate node, src < dst!");
2776 assert((!VT.isVector() ||
2777 VT.getVectorNumElements() ==
2778 Operand.getValueType().getVectorNumElements()) &&
2779 "Vector element count mismatch!");
2780 if (OpOpcode == ISD::TRUNCATE)
2781 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2782 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2783 OpOpcode == ISD::ANY_EXTEND) {
2784 // If the source is smaller than the dest, we still need an extend.
2785 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2786 .bitsLT(VT.getScalarType()))
2787 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2788 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2789 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2790 return Operand.getNode()->getOperand(0);
2792 if (OpOpcode == ISD::UNDEF)
2793 return getUNDEF(VT);
2796 // Basic sanity checking.
2797 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2798 && "Cannot BITCAST between types of different sizes!");
2799 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2800 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
2801 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
2802 if (OpOpcode == ISD::UNDEF)
2803 return getUNDEF(VT);
2805 case ISD::SCALAR_TO_VECTOR:
2806 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2807 (VT.getVectorElementType() == Operand.getValueType() ||
2808 (VT.getVectorElementType().isInteger() &&
2809 Operand.getValueType().isInteger() &&
2810 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2811 "Illegal SCALAR_TO_VECTOR node!");
2812 if (OpOpcode == ISD::UNDEF)
2813 return getUNDEF(VT);
2814 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2815 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2816 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2817 Operand.getConstantOperandVal(1) == 0 &&
2818 Operand.getOperand(0).getValueType() == VT)
2819 return Operand.getOperand(0);
2822 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2823 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
2824 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2825 Operand.getNode()->getOperand(0));
2826 if (OpOpcode == ISD::FNEG) // --X -> X
2827 return Operand.getNode()->getOperand(0);
2830 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2831 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2836 SDVTList VTs = getVTList(VT);
2837 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
2838 FoldingSetNodeID ID;
2839 SDValue Ops[1] = { Operand };
2840 AddNodeIDNode(ID, Opcode, VTs, Ops);
2842 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2843 return SDValue(E, 0);
2845 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(),
2846 DL.getDebugLoc(), VTs, Operand);
2847 CSEMap.InsertNode(N, IP);
2849 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(),
2850 DL.getDebugLoc(), VTs, Operand);
2853 AllNodes.push_back(N);
2857 return SDValue(N, 0);
2860 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, EVT VT,
2861 SDNode *Cst1, SDNode *Cst2) {
2862 // If the opcode is a target-specific ISD node, there's nothing we can
2863 // do here and the operand rules may not line up with the below, so
2865 if (Opcode >= ISD::BUILTIN_OP_END)
2868 SmallVector<std::pair<ConstantSDNode *, ConstantSDNode *>, 4> Inputs;
2869 SmallVector<SDValue, 4> Outputs;
2870 EVT SVT = VT.getScalarType();
2872 ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1);
2873 ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2);
2874 if (Scalar1 && Scalar2 && (Scalar1->isOpaque() || Scalar2->isOpaque()))
2877 if (Scalar1 && Scalar2)
2878 // Scalar instruction.
2879 Inputs.push_back(std::make_pair(Scalar1, Scalar2));
2881 // For vectors extract each constant element into Inputs so we can constant
2882 // fold them individually.
2883 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
2884 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
2888 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
2890 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
2891 ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
2892 ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I));
2893 if (!V1 || !V2) // Not a constant, bail.
2896 if (V1->isOpaque() || V2->isOpaque())
2899 // Avoid BUILD_VECTOR nodes that perform implicit truncation.
2900 // FIXME: This is valid and could be handled by truncating the APInts.
2901 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
2904 Inputs.push_back(std::make_pair(V1, V2));
2908 // We have a number of constant values, constant fold them element by element.
2909 for (unsigned I = 0, E = Inputs.size(); I != E; ++I) {
2910 const APInt &C1 = Inputs[I].first->getAPIntValue();
2911 const APInt &C2 = Inputs[I].second->getAPIntValue();
2915 Outputs.push_back(getConstant(C1 + C2, SVT));
2918 Outputs.push_back(getConstant(C1 - C2, SVT));
2921 Outputs.push_back(getConstant(C1 * C2, SVT));
2924 if (!C2.getBoolValue())
2926 Outputs.push_back(getConstant(C1.udiv(C2), SVT));
2929 if (!C2.getBoolValue())
2931 Outputs.push_back(getConstant(C1.urem(C2), SVT));
2934 if (!C2.getBoolValue())
2936 Outputs.push_back(getConstant(C1.sdiv(C2), SVT));
2939 if (!C2.getBoolValue())
2941 Outputs.push_back(getConstant(C1.srem(C2), SVT));
2944 Outputs.push_back(getConstant(C1 & C2, SVT));
2947 Outputs.push_back(getConstant(C1 | C2, SVT));
2950 Outputs.push_back(getConstant(C1 ^ C2, SVT));
2953 Outputs.push_back(getConstant(C1 << C2, SVT));
2956 Outputs.push_back(getConstant(C1.lshr(C2), SVT));
2959 Outputs.push_back(getConstant(C1.ashr(C2), SVT));
2962 Outputs.push_back(getConstant(C1.rotl(C2), SVT));
2965 Outputs.push_back(getConstant(C1.rotr(C2), SVT));
2972 assert((Scalar1 && Scalar2) || (VT.getVectorNumElements() == Outputs.size() &&
2973 "Expected a scalar or vector!"));
2975 // Handle the scalar case first.
2977 return Outputs.back();
2979 // We may have a vector type but a scalar result. Create a splat.
2980 Outputs.resize(VT.getVectorNumElements(), Outputs.back());
2982 // Build a big vector out of the scalar elements we generated.
2983 return getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Outputs);
2986 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, SDValue N1,
2987 SDValue N2, bool nuw, bool nsw, bool exact) {
2988 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2989 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2992 case ISD::TokenFactor:
2993 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2994 N2.getValueType() == MVT::Other && "Invalid token factor!");
2995 // Fold trivial token factors.
2996 if (N1.getOpcode() == ISD::EntryToken) return N2;
2997 if (N2.getOpcode() == ISD::EntryToken) return N1;
2998 if (N1 == N2) return N1;
3000 case ISD::CONCAT_VECTORS:
3001 // Concat of UNDEFs is UNDEF.
3002 if (N1.getOpcode() == ISD::UNDEF &&
3003 N2.getOpcode() == ISD::UNDEF)
3004 return getUNDEF(VT);
3006 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3007 // one big BUILD_VECTOR.
3008 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3009 N2.getOpcode() == ISD::BUILD_VECTOR) {
3010 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
3011 N1.getNode()->op_end());
3012 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
3013 return getNode(ISD::BUILD_VECTOR, DL, VT, Elts);
3017 assert(VT.isInteger() && "This operator does not apply to FP types!");
3018 assert(N1.getValueType() == N2.getValueType() &&
3019 N1.getValueType() == VT && "Binary operator types must match!");
3020 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
3021 // worth handling here.
3022 if (N2C && N2C->isNullValue())
3024 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
3031 assert(VT.isInteger() && "This operator does not apply to FP types!");
3032 assert(N1.getValueType() == N2.getValueType() &&
3033 N1.getValueType() == VT && "Binary operator types must match!");
3034 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
3035 // it's worth handling here.
3036 if (N2C && N2C->isNullValue())
3046 assert(VT.isInteger() && "This operator does not apply to FP types!");
3047 assert(N1.getValueType() == N2.getValueType() &&
3048 N1.getValueType() == VT && "Binary operator types must match!");
3055 if (getTarget().Options.UnsafeFPMath) {
3056 if (Opcode == ISD::FADD) {
3058 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
3059 if (CFP->getValueAPF().isZero())
3062 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
3063 if (CFP->getValueAPF().isZero())
3065 } else if (Opcode == ISD::FSUB) {
3067 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
3068 if (CFP->getValueAPF().isZero())
3070 } else if (Opcode == ISD::FMUL) {
3071 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1);
3074 // If the first operand isn't the constant, try the second
3076 CFP = dyn_cast<ConstantFPSDNode>(N2);
3083 return SDValue(CFP,0);
3085 if (CFP->isExactlyValue(1.0))
3090 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
3091 assert(N1.getValueType() == N2.getValueType() &&
3092 N1.getValueType() == VT && "Binary operator types must match!");
3094 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
3095 assert(N1.getValueType() == VT &&
3096 N1.getValueType().isFloatingPoint() &&
3097 N2.getValueType().isFloatingPoint() &&
3098 "Invalid FCOPYSIGN!");
3105 assert(VT == N1.getValueType() &&
3106 "Shift operators return type must be the same as their first arg");
3107 assert(VT.isInteger() && N2.getValueType().isInteger() &&
3108 "Shifts only work on integers");
3109 assert((!VT.isVector() || VT == N2.getValueType()) &&
3110 "Vector shift amounts must be in the same as their first arg");
3111 // Verify that the shift amount VT is bit enough to hold valid shift
3112 // amounts. This catches things like trying to shift an i1024 value by an
3113 // i8, which is easy to fall into in generic code that uses
3114 // TLI.getShiftAmount().
3115 assert(N2.getValueType().getSizeInBits() >=
3116 Log2_32_Ceil(N1.getValueType().getSizeInBits()) &&
3117 "Invalid use of small shift amount with oversized value!");
3119 // Always fold shifts of i1 values so the code generator doesn't need to
3120 // handle them. Since we know the size of the shift has to be less than the
3121 // size of the value, the shift/rotate count is guaranteed to be zero.
3124 if (N2C && N2C->isNullValue())
3127 case ISD::FP_ROUND_INREG: {
3128 EVT EVT = cast<VTSDNode>(N2)->getVT();
3129 assert(VT == N1.getValueType() && "Not an inreg round!");
3130 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
3131 "Cannot FP_ROUND_INREG integer types");
3132 assert(EVT.isVector() == VT.isVector() &&
3133 "FP_ROUND_INREG type should be vector iff the operand "
3135 assert((!EVT.isVector() ||
3136 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
3137 "Vector element counts must match in FP_ROUND_INREG");
3138 assert(EVT.bitsLE(VT) && "Not rounding down!");
3140 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
3144 assert(VT.isFloatingPoint() &&
3145 N1.getValueType().isFloatingPoint() &&
3146 VT.bitsLE(N1.getValueType()) &&
3147 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
3148 if (N1.getValueType() == VT) return N1; // noop conversion.
3150 case ISD::AssertSext:
3151 case ISD::AssertZext: {
3152 EVT EVT = cast<VTSDNode>(N2)->getVT();
3153 assert(VT == N1.getValueType() && "Not an inreg extend!");
3154 assert(VT.isInteger() && EVT.isInteger() &&
3155 "Cannot *_EXTEND_INREG FP types");
3156 assert(!EVT.isVector() &&
3157 "AssertSExt/AssertZExt type should be the vector element type "
3158 "rather than the vector type!");
3159 assert(EVT.bitsLE(VT) && "Not extending!");
3160 if (VT == EVT) return N1; // noop assertion.
3163 case ISD::SIGN_EXTEND_INREG: {
3164 EVT EVT = cast<VTSDNode>(N2)->getVT();
3165 assert(VT == N1.getValueType() && "Not an inreg extend!");
3166 assert(VT.isInteger() && EVT.isInteger() &&
3167 "Cannot *_EXTEND_INREG FP types");
3168 assert(EVT.isVector() == VT.isVector() &&
3169 "SIGN_EXTEND_INREG type should be vector iff the operand "
3171 assert((!EVT.isVector() ||
3172 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
3173 "Vector element counts must match in SIGN_EXTEND_INREG");
3174 assert(EVT.bitsLE(VT) && "Not extending!");
3175 if (EVT == VT) return N1; // Not actually extending
3178 APInt Val = N1C->getAPIntValue();
3179 unsigned FromBits = EVT.getScalarType().getSizeInBits();
3180 Val <<= Val.getBitWidth()-FromBits;
3181 Val = Val.ashr(Val.getBitWidth()-FromBits);
3182 return getConstant(Val, VT);
3186 case ISD::EXTRACT_VECTOR_ELT:
3187 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
3188 if (N1.getOpcode() == ISD::UNDEF)
3189 return getUNDEF(VT);
3191 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
3192 // expanding copies of large vectors from registers.
3194 N1.getOpcode() == ISD::CONCAT_VECTORS &&
3195 N1.getNumOperands() > 0) {
3197 N1.getOperand(0).getValueType().getVectorNumElements();
3198 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
3199 N1.getOperand(N2C->getZExtValue() / Factor),
3200 getConstant(N2C->getZExtValue() % Factor,
3201 N2.getValueType()));
3204 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
3205 // expanding large vector constants.
3206 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
3207 SDValue Elt = N1.getOperand(N2C->getZExtValue());
3209 if (VT != Elt.getValueType())
3210 // If the vector element type is not legal, the BUILD_VECTOR operands
3211 // are promoted and implicitly truncated, and the result implicitly
3212 // extended. Make that explicit here.
3213 Elt = getAnyExtOrTrunc(Elt, DL, VT);
3218 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
3219 // operations are lowered to scalars.
3220 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
3221 // If the indices are the same, return the inserted element else
3222 // if the indices are known different, extract the element from
3223 // the original vector.
3224 SDValue N1Op2 = N1.getOperand(2);
3225 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2.getNode());
3227 if (N1Op2C && N2C) {
3228 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
3229 if (VT == N1.getOperand(1).getValueType())
3230 return N1.getOperand(1);
3232 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
3235 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
3239 case ISD::EXTRACT_ELEMENT:
3240 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
3241 assert(!N1.getValueType().isVector() && !VT.isVector() &&
3242 (N1.getValueType().isInteger() == VT.isInteger()) &&
3243 N1.getValueType() != VT &&
3244 "Wrong types for EXTRACT_ELEMENT!");
3246 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
3247 // 64-bit integers into 32-bit parts. Instead of building the extract of
3248 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
3249 if (N1.getOpcode() == ISD::BUILD_PAIR)
3250 return N1.getOperand(N2C->getZExtValue());
3252 // EXTRACT_ELEMENT of a constant int is also very common.
3253 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3254 unsigned ElementSize = VT.getSizeInBits();
3255 unsigned Shift = ElementSize * N2C->getZExtValue();
3256 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
3257 return getConstant(ShiftedVal.trunc(ElementSize), VT);
3260 case ISD::EXTRACT_SUBVECTOR: {
3262 if (VT.isSimple() && N1.getValueType().isSimple()) {
3263 assert(VT.isVector() && N1.getValueType().isVector() &&
3264 "Extract subvector VTs must be a vectors!");
3265 assert(VT.getVectorElementType() ==
3266 N1.getValueType().getVectorElementType() &&
3267 "Extract subvector VTs must have the same element type!");
3268 assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
3269 "Extract subvector must be from larger vector to smaller vector!");
3271 if (isa<ConstantSDNode>(Index.getNode())) {
3272 assert((VT.getVectorNumElements() +
3273 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3274 <= N1.getValueType().getVectorNumElements())
3275 && "Extract subvector overflow!");
3278 // Trivial extraction.
3279 if (VT.getSimpleVT() == N1.getSimpleValueType())
3286 // Perform trivial constant folding.
3287 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1.getNode(), N2.getNode());
3288 if (SV.getNode()) return SV;
3290 // Canonicalize constant to RHS if commutative.
3291 if (N1C && !N2C && isCommutativeBinOp(Opcode)) {
3292 std::swap(N1C, N2C);
3296 // Constant fold FP operations.
3297 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
3298 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
3300 if (!N2CFP && isCommutativeBinOp(Opcode)) {
3301 // Canonicalize constant to RHS if commutative.
3302 std::swap(N1CFP, N2CFP);
3305 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
3306 APFloat::opStatus s;
3309 s = V1.add(V2, APFloat::rmNearestTiesToEven);
3310 if (s != APFloat::opInvalidOp)
3311 return getConstantFP(V1, VT);
3314 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
3315 if (s!=APFloat::opInvalidOp)
3316 return getConstantFP(V1, VT);
3319 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
3320 if (s!=APFloat::opInvalidOp)
3321 return getConstantFP(V1, VT);
3324 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
3325 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
3326 return getConstantFP(V1, VT);
3329 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
3330 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
3331 return getConstantFP(V1, VT);
3333 case ISD::FCOPYSIGN:
3335 return getConstantFP(V1, VT);
3340 if (Opcode == ISD::FP_ROUND) {
3341 APFloat V = N1CFP->getValueAPF(); // make copy
3343 // This can return overflow, underflow, or inexact; we don't care.
3344 // FIXME need to be more flexible about rounding mode.
3345 (void)V.convert(EVTToAPFloatSemantics(VT),
3346 APFloat::rmNearestTiesToEven, &ignored);
3347 return getConstantFP(V, VT);
3351 // Canonicalize an UNDEF to the RHS, even over a constant.
3352 if (N1.getOpcode() == ISD::UNDEF) {
3353 if (isCommutativeBinOp(Opcode)) {
3357 case ISD::FP_ROUND_INREG:
3358 case ISD::SIGN_EXTEND_INREG:
3364 return N1; // fold op(undef, arg2) -> undef
3372 return getConstant(0, VT); // fold op(undef, arg2) -> 0
3373 // For vectors, we can't easily build an all zero vector, just return
3380 // Fold a bunch of operators when the RHS is undef.
3381 if (N2.getOpcode() == ISD::UNDEF) {
3384 if (N1.getOpcode() == ISD::UNDEF)
3385 // Handle undef ^ undef -> 0 special case. This is a common
3387 return getConstant(0, VT);
3397 return N2; // fold op(arg1, undef) -> undef
3403 if (getTarget().Options.UnsafeFPMath)
3411 return getConstant(0, VT); // fold op(arg1, undef) -> 0
3412 // For vectors, we can't easily build an all zero vector, just return
3417 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3418 // For vectors, we can't easily build an all one vector, just return
3426 // Memoize this node if possible.
3428 SDVTList VTs = getVTList(VT);
3429 const bool BinOpHasFlags = isBinOpWithFlags(Opcode);
3430 if (VT != MVT::Glue) {
3431 SDValue Ops[] = {N1, N2};
3432 FoldingSetNodeID ID;
3433 AddNodeIDNode(ID, Opcode, VTs, Ops);
3435 AddBinaryNodeIDCustom(ID, Opcode, nuw, nsw, exact);
3437 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3438 return SDValue(E, 0);
3440 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, nuw, nsw, exact);
3442 CSEMap.InsertNode(N, IP);
3445 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, nuw, nsw, exact);
3448 AllNodes.push_back(N);
3452 return SDValue(N, 0);
3455 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3456 SDValue N1, SDValue N2, SDValue N3) {
3457 // Perform various simplifications.
3458 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
3461 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3462 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3463 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
3464 if (N1CFP && N2CFP && N3CFP) {
3465 APFloat V1 = N1CFP->getValueAPF();
3466 const APFloat &V2 = N2CFP->getValueAPF();
3467 const APFloat &V3 = N3CFP->getValueAPF();
3468 APFloat::opStatus s =
3469 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
3470 if (s != APFloat::opInvalidOp)
3471 return getConstantFP(V1, VT);
3475 case ISD::CONCAT_VECTORS:
3476 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3477 // one big BUILD_VECTOR.
3478 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3479 N2.getOpcode() == ISD::BUILD_VECTOR &&
3480 N3.getOpcode() == ISD::BUILD_VECTOR) {
3481 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
3482 N1.getNode()->op_end());
3483 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
3484 Elts.append(N3.getNode()->op_begin(), N3.getNode()->op_end());
3485 return getNode(ISD::BUILD_VECTOR, DL, VT, Elts);
3489 // Use FoldSetCC to simplify SETCC's.
3490 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3491 if (Simp.getNode()) return Simp;
3496 if (N1C->getZExtValue())
3497 return N2; // select true, X, Y -> X
3498 return N3; // select false, X, Y -> Y
3501 if (N2 == N3) return N2; // select C, X, X -> X
3503 case ISD::VECTOR_SHUFFLE:
3504 llvm_unreachable("should use getVectorShuffle constructor!");
3505 case ISD::INSERT_SUBVECTOR: {
3507 if (VT.isSimple() && N1.getValueType().isSimple()
3508 && N2.getValueType().isSimple()) {
3509 assert(VT.isVector() && N1.getValueType().isVector() &&
3510 N2.getValueType().isVector() &&
3511 "Insert subvector VTs must be a vectors");
3512 assert(VT == N1.getValueType() &&
3513 "Dest and insert subvector source types must match!");
3514 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
3515 "Insert subvector must be from smaller vector to larger vector!");
3516 if (isa<ConstantSDNode>(Index.getNode())) {
3517 assert((N2.getValueType().getVectorNumElements() +
3518 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3519 <= VT.getVectorNumElements())
3520 && "Insert subvector overflow!");
3523 // Trivial insertion.
3524 if (VT.getSimpleVT() == N2.getSimpleValueType())
3530 // Fold bit_convert nodes from a type to themselves.
3531 if (N1.getValueType() == VT)
3536 // Memoize node if it doesn't produce a flag.
3538 SDVTList VTs = getVTList(VT);
3539 if (VT != MVT::Glue) {
3540 SDValue Ops[] = { N1, N2, N3 };
3541 FoldingSetNodeID ID;
3542 AddNodeIDNode(ID, Opcode, VTs, Ops);
3544 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3545 return SDValue(E, 0);
3547 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
3548 DL.getDebugLoc(), VTs, N1, N2, N3);
3549 CSEMap.InsertNode(N, IP);
3551 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
3552 DL.getDebugLoc(), VTs, N1, N2, N3);
3555 AllNodes.push_back(N);
3559 return SDValue(N, 0);
3562 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3563 SDValue N1, SDValue N2, SDValue N3,
3565 SDValue Ops[] = { N1, N2, N3, N4 };
3566 return getNode(Opcode, DL, VT, Ops);
3569 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3570 SDValue N1, SDValue N2, SDValue N3,
3571 SDValue N4, SDValue N5) {
3572 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3573 return getNode(Opcode, DL, VT, Ops);
3576 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3577 /// the incoming stack arguments to be loaded from the stack.
3578 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3579 SmallVector<SDValue, 8> ArgChains;
3581 // Include the original chain at the beginning of the list. When this is
3582 // used by target LowerCall hooks, this helps legalize find the
3583 // CALLSEQ_BEGIN node.
3584 ArgChains.push_back(Chain);
3586 // Add a chain value for each stack argument.
3587 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3588 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3589 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3590 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3591 if (FI->getIndex() < 0)
3592 ArgChains.push_back(SDValue(L, 1));
3594 // Build a tokenfactor for all the chains.
3595 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3598 /// getMemsetValue - Vectorized representation of the memset value
3600 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3602 assert(Value.getOpcode() != ISD::UNDEF);
3604 unsigned NumBits = VT.getScalarType().getSizeInBits();
3605 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3606 assert(C->getAPIntValue().getBitWidth() == 8);
3607 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
3609 return DAG.getConstant(Val, VT);
3610 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), VT);
3613 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3615 // Use a multiplication with 0x010101... to extend the input to the
3617 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
3618 Value = DAG.getNode(ISD::MUL, dl, VT, Value, DAG.getConstant(Magic, VT));
3624 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3625 /// used when a memcpy is turned into a memset when the source is a constant
3627 static SDValue getMemsetStringVal(EVT VT, SDLoc dl, SelectionDAG &DAG,
3628 const TargetLowering &TLI, StringRef Str) {
3629 // Handle vector with all elements zero.
3632 return DAG.getConstant(0, VT);
3633 else if (VT == MVT::f32 || VT == MVT::f64)
3634 return DAG.getConstantFP(0.0, VT);
3635 else if (VT.isVector()) {
3636 unsigned NumElts = VT.getVectorNumElements();
3637 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3638 return DAG.getNode(ISD::BITCAST, dl, VT,
3639 DAG.getConstant(0, EVT::getVectorVT(*DAG.getContext(),
3642 llvm_unreachable("Expected type!");
3645 assert(!VT.isVector() && "Can't handle vector type here!");
3646 unsigned NumVTBits = VT.getSizeInBits();
3647 unsigned NumVTBytes = NumVTBits / 8;
3648 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
3650 APInt Val(NumVTBits, 0);
3651 if (TLI.isLittleEndian()) {
3652 for (unsigned i = 0; i != NumBytes; ++i)
3653 Val |= (uint64_t)(unsigned char)Str[i] << i*8;
3655 for (unsigned i = 0; i != NumBytes; ++i)
3656 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
3659 // If the "cost" of materializing the integer immediate is less than the cost
3660 // of a load, then it is cost effective to turn the load into the immediate.
3661 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3662 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
3663 return DAG.getConstant(Val, VT);
3664 return SDValue(nullptr, 0);
3667 /// getMemBasePlusOffset - Returns base and offset node for the
3669 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset, SDLoc dl,
3670 SelectionDAG &DAG) {
3671 EVT VT = Base.getValueType();
3672 return DAG.getNode(ISD::ADD, dl,
3673 VT, Base, DAG.getConstant(Offset, VT));
3676 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3678 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
3679 unsigned SrcDelta = 0;
3680 GlobalAddressSDNode *G = nullptr;
3681 if (Src.getOpcode() == ISD::GlobalAddress)
3682 G = cast<GlobalAddressSDNode>(Src);
3683 else if (Src.getOpcode() == ISD::ADD &&
3684 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3685 Src.getOperand(1).getOpcode() == ISD::Constant) {
3686 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3687 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3692 return getConstantStringInfo(G->getGlobal(), Str, SrcDelta, false);
3695 /// FindOptimalMemOpLowering - Determines the optimial series memory ops
3696 /// to replace the memset / memcpy. Return true if the number of memory ops
3697 /// is below the threshold. It returns the types of the sequence of
3698 /// memory ops to perform memset / memcpy by reference.
3699 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
3700 unsigned Limit, uint64_t Size,
3701 unsigned DstAlign, unsigned SrcAlign,
3707 const TargetLowering &TLI) {
3708 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
3709 "Expecting memcpy / memset source to meet alignment requirement!");
3710 // If 'SrcAlign' is zero, that means the memory operation does not need to
3711 // load the value, i.e. memset or memcpy from constant string. Otherwise,
3712 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
3713 // is the specified alignment of the memory operation. If it is zero, that
3714 // means it's possible to change the alignment of the destination.
3715 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
3716 // not need to be loaded.
3717 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
3718 IsMemset, ZeroMemset, MemcpyStrSrc,
3719 DAG.getMachineFunction());
3721 if (VT == MVT::Other) {
3723 if (DstAlign >= TLI.getDataLayout()->getPointerPrefAlignment(AS) ||
3724 TLI.allowsUnalignedMemoryAccesses(VT, AS)) {
3725 VT = TLI.getPointerTy();
3727 switch (DstAlign & 7) {
3728 case 0: VT = MVT::i64; break;
3729 case 4: VT = MVT::i32; break;
3730 case 2: VT = MVT::i16; break;
3731 default: VT = MVT::i8; break;
3736 while (!TLI.isTypeLegal(LVT))
3737 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3738 assert(LVT.isInteger());
3744 unsigned NumMemOps = 0;
3746 unsigned VTSize = VT.getSizeInBits() / 8;
3747 while (VTSize > Size) {
3748 // For now, only use non-vector load / store's for the left-over pieces.
3753 if (VT.isVector() || VT.isFloatingPoint()) {
3754 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
3755 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
3756 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
3758 else if (NewVT == MVT::i64 &&
3759 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
3760 TLI.isSafeMemOpType(MVT::f64)) {
3761 // i64 is usually not legal on 32-bit targets, but f64 may be.
3769 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
3770 if (NewVT == MVT::i8)
3772 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
3774 NewVTSize = NewVT.getSizeInBits() / 8;
3776 // If the new VT cannot cover all of the remaining bits, then consider
3777 // issuing a (or a pair of) unaligned and overlapping load / store.
3778 // FIXME: Only does this for 64-bit or more since we don't have proper
3779 // cost model for unaligned load / store.
3782 if (NumMemOps && AllowOverlap &&
3783 VTSize >= 8 && NewVTSize < Size &&
3784 TLI.allowsUnalignedMemoryAccesses(VT, AS, &Fast) && Fast)
3792 if (++NumMemOps > Limit)
3795 MemOps.push_back(VT);
3802 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, SDLoc dl,
3803 SDValue Chain, SDValue Dst,
3804 SDValue Src, uint64_t Size,
3805 unsigned Align, bool isVol,
3807 MachinePointerInfo DstPtrInfo,
3808 MachinePointerInfo SrcPtrInfo) {
3809 // Turn a memcpy of undef to nop.
3810 if (Src.getOpcode() == ISD::UNDEF)
3813 // Expand memcpy to a series of load and store ops if the size operand falls
3814 // below a certain threshold.
3815 // TODO: In the AlwaysInline case, if the size is big then generate a loop
3816 // rather than maybe a humongous number of loads and stores.
3817 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3818 std::vector<EVT> MemOps;
3819 bool DstAlignCanChange = false;
3820 MachineFunction &MF = DAG.getMachineFunction();
3821 MachineFrameInfo *MFI = MF.getFrameInfo();
3823 MF.getFunction()->getAttributes().
3824 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
3825 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3826 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3827 DstAlignCanChange = true;
3828 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3829 if (Align > SrcAlign)
3832 bool CopyFromStr = isMemSrcFromString(Src, Str);
3833 bool isZeroStr = CopyFromStr && Str.empty();
3834 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
3836 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3837 (DstAlignCanChange ? 0 : Align),
3838 (isZeroStr ? 0 : SrcAlign),
3839 false, false, CopyFromStr, true, DAG, TLI))
3842 if (DstAlignCanChange) {
3843 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3844 unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
3846 // Don't promote to an alignment that would require dynamic stack
3848 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
3849 if (!TRI->needsStackRealignment(MF))
3850 while (NewAlign > Align &&
3851 TLI.getDataLayout()->exceedsNaturalStackAlignment(NewAlign))
3854 if (NewAlign > Align) {
3855 // Give the stack frame object a larger alignment if needed.
3856 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3857 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3862 SmallVector<SDValue, 8> OutChains;
3863 unsigned NumMemOps = MemOps.size();
3864 uint64_t SrcOff = 0, DstOff = 0;
3865 for (unsigned i = 0; i != NumMemOps; ++i) {
3867 unsigned VTSize = VT.getSizeInBits() / 8;
3868 SDValue Value, Store;
3870 if (VTSize > Size) {
3871 // Issuing an unaligned load / store pair that overlaps with the previous
3872 // pair. Adjust the offset accordingly.
3873 assert(i == NumMemOps-1 && i != 0);
3874 SrcOff -= VTSize - Size;
3875 DstOff -= VTSize - Size;
3879 (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
3880 // It's unlikely a store of a vector immediate can be done in a single
3881 // instruction. It would require a load from a constantpool first.
3882 // We only handle zero vectors here.
3883 // FIXME: Handle other cases where store of vector immediate is done in
3884 // a single instruction.
3885 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
3886 if (Value.getNode())
3887 Store = DAG.getStore(Chain, dl, Value,
3888 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3889 DstPtrInfo.getWithOffset(DstOff), isVol,
3893 if (!Store.getNode()) {
3894 // The type might not be legal for the target. This should only happen
3895 // if the type is smaller than a legal type, as on PPC, so the right
3896 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3897 // to Load/Store if NVT==VT.
3898 // FIXME does the case above also need this?
3899 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3900 assert(NVT.bitsGE(VT));
3901 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3902 getMemBasePlusOffset(Src, SrcOff, dl, DAG),
3903 SrcPtrInfo.getWithOffset(SrcOff), VT, isVol, false,
3904 MinAlign(SrcAlign, SrcOff));
3905 Store = DAG.getTruncStore(Chain, dl, Value,
3906 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3907 DstPtrInfo.getWithOffset(DstOff), VT, isVol,
3910 OutChains.push_back(Store);
3916 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
3919 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, SDLoc dl,
3920 SDValue Chain, SDValue Dst,
3921 SDValue Src, uint64_t Size,
3922 unsigned Align, bool isVol,
3924 MachinePointerInfo DstPtrInfo,
3925 MachinePointerInfo SrcPtrInfo) {
3926 // Turn a memmove of undef to nop.
3927 if (Src.getOpcode() == ISD::UNDEF)
3930 // Expand memmove to a series of load and store ops if the size operand falls
3931 // below a certain threshold.
3932 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3933 std::vector<EVT> MemOps;
3934 bool DstAlignCanChange = false;
3935 MachineFunction &MF = DAG.getMachineFunction();
3936 MachineFrameInfo *MFI = MF.getFrameInfo();
3937 bool OptSize = MF.getFunction()->getAttributes().
3938 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
3939 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3940 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3941 DstAlignCanChange = true;
3942 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3943 if (Align > SrcAlign)
3945 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
3947 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3948 (DstAlignCanChange ? 0 : Align), SrcAlign,
3949 false, false, false, false, DAG, TLI))
3952 if (DstAlignCanChange) {
3953 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3954 unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
3955 if (NewAlign > Align) {
3956 // Give the stack frame object a larger alignment if needed.
3957 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3958 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3963 uint64_t SrcOff = 0, DstOff = 0;
3964 SmallVector<SDValue, 8> LoadValues;
3965 SmallVector<SDValue, 8> LoadChains;
3966 SmallVector<SDValue, 8> OutChains;
3967 unsigned NumMemOps = MemOps.size();
3968 for (unsigned i = 0; i < NumMemOps; i++) {
3970 unsigned VTSize = VT.getSizeInBits() / 8;
3973 Value = DAG.getLoad(VT, dl, Chain,
3974 getMemBasePlusOffset(Src, SrcOff, dl, DAG),
3975 SrcPtrInfo.getWithOffset(SrcOff), isVol,
3976 false, false, SrcAlign);
3977 LoadValues.push_back(Value);
3978 LoadChains.push_back(Value.getValue(1));
3981 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
3983 for (unsigned i = 0; i < NumMemOps; i++) {
3985 unsigned VTSize = VT.getSizeInBits() / 8;
3988 Store = DAG.getStore(Chain, dl, LoadValues[i],
3989 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3990 DstPtrInfo.getWithOffset(DstOff), isVol, false, Align);
3991 OutChains.push_back(Store);
3995 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
3998 /// \brief Lower the call to 'memset' intrinsic function into a series of store
4001 /// \param DAG Selection DAG where lowered code is placed.
4002 /// \param dl Link to corresponding IR location.
4003 /// \param Chain Control flow dependency.
4004 /// \param Dst Pointer to destination memory location.
4005 /// \param Src Value of byte to write into the memory.
4006 /// \param Size Number of bytes to write.
4007 /// \param Align Alignment of the destination in bytes.
4008 /// \param isVol True if destination is volatile.
4009 /// \param DstPtrInfo IR information on the memory pointer.
4010 /// \returns New head in the control flow, if lowering was successful, empty
4011 /// SDValue otherwise.
4013 /// The function tries to replace 'llvm.memset' intrinsic with several store
4014 /// operations and value calculation code. This is usually profitable for small
4016 static SDValue getMemsetStores(SelectionDAG &DAG, SDLoc dl,
4017 SDValue Chain, SDValue Dst,
4018 SDValue Src, uint64_t Size,
4019 unsigned Align, bool isVol,
4020 MachinePointerInfo DstPtrInfo) {
4021 // Turn a memset of undef to nop.
4022 if (Src.getOpcode() == ISD::UNDEF)
4025 // Expand memset to a series of load/store ops if the size operand
4026 // falls below a certain threshold.
4027 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4028 std::vector<EVT> MemOps;
4029 bool DstAlignCanChange = false;
4030 MachineFunction &MF = DAG.getMachineFunction();
4031 MachineFrameInfo *MFI = MF.getFrameInfo();
4032 bool OptSize = MF.getFunction()->getAttributes().
4033 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
4034 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
4035 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
4036 DstAlignCanChange = true;
4038 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
4039 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
4040 Size, (DstAlignCanChange ? 0 : Align), 0,
4041 true, IsZeroVal, false, true, DAG, TLI))
4044 if (DstAlignCanChange) {
4045 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
4046 unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
4047 if (NewAlign > Align) {
4048 // Give the stack frame object a larger alignment if needed.
4049 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
4050 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
4055 SmallVector<SDValue, 8> OutChains;
4056 uint64_t DstOff = 0;
4057 unsigned NumMemOps = MemOps.size();
4059 // Find the largest store and generate the bit pattern for it.
4060 EVT LargestVT = MemOps[0];
4061 for (unsigned i = 1; i < NumMemOps; i++)
4062 if (MemOps[i].bitsGT(LargestVT))
4063 LargestVT = MemOps[i];
4064 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
4066 for (unsigned i = 0; i < NumMemOps; i++) {
4068 unsigned VTSize = VT.getSizeInBits() / 8;
4069 if (VTSize > Size) {
4070 // Issuing an unaligned load / store pair that overlaps with the previous
4071 // pair. Adjust the offset accordingly.
4072 assert(i == NumMemOps-1 && i != 0);
4073 DstOff -= VTSize - Size;
4076 // If this store is smaller than the largest store see whether we can get
4077 // the smaller value for free with a truncate.
4078 SDValue Value = MemSetValue;
4079 if (VT.bitsLT(LargestVT)) {
4080 if (!LargestVT.isVector() && !VT.isVector() &&
4081 TLI.isTruncateFree(LargestVT, VT))
4082 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
4084 Value = getMemsetValue(Src, VT, DAG, dl);
4086 assert(Value.getValueType() == VT && "Value with wrong type.");
4087 SDValue Store = DAG.getStore(Chain, dl, Value,
4088 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
4089 DstPtrInfo.getWithOffset(DstOff),
4090 isVol, false, Align);
4091 OutChains.push_back(Store);
4092 DstOff += VT.getSizeInBits() / 8;
4096 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
4099 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDLoc dl, SDValue Dst,
4100 SDValue Src, SDValue Size,
4101 unsigned Align, bool isVol, bool AlwaysInline,
4102 MachinePointerInfo DstPtrInfo,
4103 MachinePointerInfo SrcPtrInfo) {
4104 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4106 // Check to see if we should lower the memcpy to loads and stores first.
4107 // For cases within the target-specified limits, this is the best choice.
4108 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4110 // Memcpy with size zero? Just return the original chain.
4111 if (ConstantSize->isNullValue())
4114 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
4115 ConstantSize->getZExtValue(),Align,
4116 isVol, false, DstPtrInfo, SrcPtrInfo);
4117 if (Result.getNode())
4121 // Then check to see if we should lower the memcpy with target-specific
4122 // code. If the target chooses to do this, this is the next best.
4124 TSI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
4125 isVol, AlwaysInline,
4126 DstPtrInfo, SrcPtrInfo);
4127 if (Result.getNode())
4130 // If we really need inline code and the target declined to provide it,
4131 // use a (potentially long) sequence of loads and stores.
4133 assert(ConstantSize && "AlwaysInline requires a constant size!");
4134 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
4135 ConstantSize->getZExtValue(), Align, isVol,
4136 true, DstPtrInfo, SrcPtrInfo);
4139 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
4140 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
4141 // respect volatile, so they may do things like read or write memory
4142 // beyond the given memory regions. But fixing this isn't easy, and most
4143 // people don't care.
4145 const TargetLowering *TLI = TM.getTargetLowering();
4147 // Emit a library call.
4148 TargetLowering::ArgListTy Args;
4149 TargetLowering::ArgListEntry Entry;
4150 Entry.Ty = TLI->getDataLayout()->getIntPtrType(*getContext());
4151 Entry.Node = Dst; Args.push_back(Entry);
4152 Entry.Node = Src; Args.push_back(Entry);
4153 Entry.Node = Size; Args.push_back(Entry);
4154 // FIXME: pass in SDLoc
4155 TargetLowering::CallLoweringInfo CLI(*this);
4156 CLI.setDebugLoc(dl).setChain(Chain)
4157 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
4158 Type::getVoidTy(*getContext()),
4159 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
4160 TLI->getPointerTy()), &Args, 0)
4161 .setDiscardResult();
4162 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4164 return CallResult.second;
4167 SDValue SelectionDAG::getMemmove(SDValue Chain, SDLoc dl, SDValue Dst,
4168 SDValue Src, SDValue Size,
4169 unsigned Align, bool isVol,
4170 MachinePointerInfo DstPtrInfo,
4171 MachinePointerInfo SrcPtrInfo) {
4172 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4174 // Check to see if we should lower the memmove to loads and stores first.
4175 // For cases within the target-specified limits, this is the best choice.
4176 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4178 // Memmove with size zero? Just return the original chain.
4179 if (ConstantSize->isNullValue())
4183 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
4184 ConstantSize->getZExtValue(), Align, isVol,
4185 false, DstPtrInfo, SrcPtrInfo);
4186 if (Result.getNode())
4190 // Then check to see if we should lower the memmove with target-specific
4191 // code. If the target chooses to do this, this is the next best.
4193 TSI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align, isVol,
4194 DstPtrInfo, SrcPtrInfo);
4195 if (Result.getNode())
4198 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
4199 // not be safe. See memcpy above for more details.
4201 const TargetLowering *TLI = TM.getTargetLowering();
4203 // Emit a library call.
4204 TargetLowering::ArgListTy Args;
4205 TargetLowering::ArgListEntry Entry;
4206 Entry.Ty = TLI->getDataLayout()->getIntPtrType(*getContext());
4207 Entry.Node = Dst; Args.push_back(Entry);
4208 Entry.Node = Src; Args.push_back(Entry);
4209 Entry.Node = Size; Args.push_back(Entry);
4210 // FIXME: pass in SDLoc
4211 TargetLowering::CallLoweringInfo CLI(*this);
4212 CLI.setDebugLoc(dl).setChain(Chain)
4213 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
4214 Type::getVoidTy(*getContext()),
4215 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
4216 TLI->getPointerTy()), &Args, 0)
4217 .setDiscardResult();
4218 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4220 return CallResult.second;
4223 SDValue SelectionDAG::getMemset(SDValue Chain, SDLoc dl, SDValue Dst,
4224 SDValue Src, SDValue Size,
4225 unsigned Align, bool isVol,
4226 MachinePointerInfo DstPtrInfo) {
4227 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4229 // Check to see if we should lower the memset to stores first.
4230 // For cases within the target-specified limits, this is the best choice.
4231 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4233 // Memset with size zero? Just return the original chain.
4234 if (ConstantSize->isNullValue())
4238 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
4239 Align, isVol, DstPtrInfo);
4241 if (Result.getNode())
4245 // Then check to see if we should lower the memset with target-specific
4246 // code. If the target chooses to do this, this is the next best.
4248 TSI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align, isVol,
4250 if (Result.getNode())
4253 // Emit a library call.
4254 const TargetLowering *TLI = TM.getTargetLowering();
4255 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(*getContext());
4256 TargetLowering::ArgListTy Args;
4257 TargetLowering::ArgListEntry Entry;
4258 Entry.Node = Dst; Entry.Ty = IntPtrTy;
4259 Args.push_back(Entry);
4260 // Extend or truncate the argument to be an i32 value for the call.
4261 if (Src.getValueType().bitsGT(MVT::i32))
4262 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
4264 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
4266 Entry.Ty = Type::getInt32Ty(*getContext());
4267 Entry.isSExt = true;
4268 Args.push_back(Entry);
4270 Entry.Ty = IntPtrTy;
4271 Entry.isSExt = false;
4272 Args.push_back(Entry);
4274 // FIXME: pass in SDLoc
4275 TargetLowering::CallLoweringInfo CLI(*this);
4276 CLI.setDebugLoc(dl).setChain(Chain)
4277 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
4278 Type::getVoidTy(*getContext()),
4279 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
4280 TLI->getPointerTy()), &Args, 0)
4281 .setDiscardResult();
4283 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
4284 return CallResult.second;
4287 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4288 SDVTList VTList, ArrayRef<SDValue> Ops,
4289 MachineMemOperand *MMO,
4290 AtomicOrdering SuccessOrdering,
4291 AtomicOrdering FailureOrdering,
4292 SynchronizationScope SynchScope) {
4293 FoldingSetNodeID ID;
4294 ID.AddInteger(MemVT.getRawBits());
4295 AddNodeIDNode(ID, Opcode, VTList, Ops);
4296 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4298 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4299 cast<AtomicSDNode>(E)->refineAlignment(MMO);
4300 return SDValue(E, 0);
4303 // Allocate the operands array for the node out of the BumpPtrAllocator, since
4304 // SDNode doesn't have access to it. This memory will be "leaked" when
4305 // the node is deallocated, but recovered when the allocator is released.
4306 // If the number of operands is less than 5 we use AtomicSDNode's internal
4308 unsigned NumOps = Ops.size();
4309 SDUse *DynOps = NumOps > 4 ? OperandAllocator.Allocate<SDUse>(NumOps)
4312 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(),
4313 dl.getDebugLoc(), VTList, MemVT,
4314 Ops.data(), DynOps, NumOps, MMO,
4315 SuccessOrdering, FailureOrdering,
4317 CSEMap.InsertNode(N, IP);
4318 AllNodes.push_back(N);
4319 return SDValue(N, 0);
4322 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4323 SDVTList VTList, ArrayRef<SDValue> Ops,
4324 MachineMemOperand *MMO,
4325 AtomicOrdering Ordering,
4326 SynchronizationScope SynchScope) {
4327 return getAtomic(Opcode, dl, MemVT, VTList, Ops, MMO, Ordering,
4328 Ordering, SynchScope);
4331 SDValue SelectionDAG::getAtomicCmpSwap(
4332 unsigned Opcode, SDLoc dl, EVT MemVT, SDVTList VTs, SDValue Chain,
4333 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
4334 unsigned Alignment, AtomicOrdering SuccessOrdering,
4335 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) {
4336 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
4337 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
4338 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4340 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4341 Alignment = getEVTAlignment(MemVT);
4343 MachineFunction &MF = getMachineFunction();
4345 // FIXME: Volatile isn't really correct; we should keep track of atomic
4346 // orderings in the memoperand.
4347 unsigned Flags = MachineMemOperand::MOVolatile;
4348 Flags |= MachineMemOperand::MOLoad;
4349 Flags |= MachineMemOperand::MOStore;
4351 MachineMemOperand *MMO =
4352 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment);
4354 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO,
4355 SuccessOrdering, FailureOrdering, SynchScope);
4358 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, SDLoc dl, EVT MemVT,
4359 SDVTList VTs, SDValue Chain, SDValue Ptr,
4360 SDValue Cmp, SDValue Swp,
4361 MachineMemOperand *MMO,
4362 AtomicOrdering SuccessOrdering,
4363 AtomicOrdering FailureOrdering,
4364 SynchronizationScope SynchScope) {
4365 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
4366 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
4367 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4369 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
4370 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO,
4371 SuccessOrdering, FailureOrdering, SynchScope);
4374 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4376 SDValue Ptr, SDValue Val,
4377 const Value* PtrVal,
4379 AtomicOrdering Ordering,
4380 SynchronizationScope SynchScope) {
4381 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4382 Alignment = getEVTAlignment(MemVT);
4384 MachineFunction &MF = getMachineFunction();
4385 // An atomic store does not load. An atomic load does not store.
4386 // (An atomicrmw obviously both loads and stores.)
4387 // For now, atomics are considered to be volatile always, and they are
4389 // FIXME: Volatile isn't really correct; we should keep track of atomic
4390 // orderings in the memoperand.
4391 unsigned Flags = MachineMemOperand::MOVolatile;
4392 if (Opcode != ISD::ATOMIC_STORE)
4393 Flags |= MachineMemOperand::MOLoad;
4394 if (Opcode != ISD::ATOMIC_LOAD)
4395 Flags |= MachineMemOperand::MOStore;
4397 MachineMemOperand *MMO =
4398 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
4399 MemVT.getStoreSize(), Alignment);
4401 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO,
4402 Ordering, SynchScope);
4405 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4407 SDValue Ptr, SDValue Val,
4408 MachineMemOperand *MMO,
4409 AtomicOrdering Ordering,
4410 SynchronizationScope SynchScope) {
4411 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
4412 Opcode == ISD::ATOMIC_LOAD_SUB ||
4413 Opcode == ISD::ATOMIC_LOAD_AND ||
4414 Opcode == ISD::ATOMIC_LOAD_OR ||
4415 Opcode == ISD::ATOMIC_LOAD_XOR ||
4416 Opcode == ISD::ATOMIC_LOAD_NAND ||
4417 Opcode == ISD::ATOMIC_LOAD_MIN ||
4418 Opcode == ISD::ATOMIC_LOAD_MAX ||
4419 Opcode == ISD::ATOMIC_LOAD_UMIN ||
4420 Opcode == ISD::ATOMIC_LOAD_UMAX ||
4421 Opcode == ISD::ATOMIC_SWAP ||
4422 Opcode == ISD::ATOMIC_STORE) &&
4423 "Invalid Atomic Op");
4425 EVT VT = Val.getValueType();
4427 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
4428 getVTList(VT, MVT::Other);
4429 SDValue Ops[] = {Chain, Ptr, Val};
4430 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope);
4433 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4434 EVT VT, SDValue Chain,
4436 MachineMemOperand *MMO,
4437 AtomicOrdering Ordering,
4438 SynchronizationScope SynchScope) {
4439 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
4441 SDVTList VTs = getVTList(VT, MVT::Other);
4442 SDValue Ops[] = {Chain, Ptr};
4443 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope);
4446 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
4447 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, SDLoc dl) {
4448 if (Ops.size() == 1)
4451 SmallVector<EVT, 4> VTs;
4452 VTs.reserve(Ops.size());
4453 for (unsigned i = 0; i < Ops.size(); ++i)
4454 VTs.push_back(Ops[i].getValueType());
4455 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
4459 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
4460 ArrayRef<SDValue> Ops,
4461 EVT MemVT, MachinePointerInfo PtrInfo,
4462 unsigned Align, bool Vol,
4463 bool ReadMem, bool WriteMem) {
4464 if (Align == 0) // Ensure that codegen never sees alignment 0
4465 Align = getEVTAlignment(MemVT);
4467 MachineFunction &MF = getMachineFunction();
4470 Flags |= MachineMemOperand::MOStore;
4472 Flags |= MachineMemOperand::MOLoad;
4474 Flags |= MachineMemOperand::MOVolatile;
4475 MachineMemOperand *MMO =
4476 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Align);
4478 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
4482 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
4483 ArrayRef<SDValue> Ops, EVT MemVT,
4484 MachineMemOperand *MMO) {
4485 assert((Opcode == ISD::INTRINSIC_VOID ||
4486 Opcode == ISD::INTRINSIC_W_CHAIN ||
4487 Opcode == ISD::PREFETCH ||
4488 Opcode == ISD::LIFETIME_START ||
4489 Opcode == ISD::LIFETIME_END ||
4490 (Opcode <= INT_MAX &&
4491 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
4492 "Opcode is not a memory-accessing opcode!");
4494 // Memoize the node unless it returns a flag.
4495 MemIntrinsicSDNode *N;
4496 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4497 FoldingSetNodeID ID;
4498 AddNodeIDNode(ID, Opcode, VTList, Ops);
4499 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4501 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4502 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
4503 return SDValue(E, 0);
4506 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(),
4507 dl.getDebugLoc(), VTList, Ops,
4509 CSEMap.InsertNode(N, IP);
4511 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(),
4512 dl.getDebugLoc(), VTList, Ops,
4515 AllNodes.push_back(N);
4516 return SDValue(N, 0);
4519 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4520 /// MachinePointerInfo record from it. This is particularly useful because the
4521 /// code generator has many cases where it doesn't bother passing in a
4522 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4523 static MachinePointerInfo InferPointerInfo(SDValue Ptr, int64_t Offset = 0) {
4524 // If this is FI+Offset, we can model it.
4525 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
4526 return MachinePointerInfo::getFixedStack(FI->getIndex(), Offset);
4528 // If this is (FI+Offset1)+Offset2, we can model it.
4529 if (Ptr.getOpcode() != ISD::ADD ||
4530 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
4531 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
4532 return MachinePointerInfo();
4534 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4535 return MachinePointerInfo::getFixedStack(FI, Offset+
4536 cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
4539 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4540 /// MachinePointerInfo record from it. This is particularly useful because the
4541 /// code generator has many cases where it doesn't bother passing in a
4542 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4543 static MachinePointerInfo InferPointerInfo(SDValue Ptr, SDValue OffsetOp) {
4544 // If the 'Offset' value isn't a constant, we can't handle this.
4545 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
4546 return InferPointerInfo(Ptr, OffsetNode->getSExtValue());
4547 if (OffsetOp.getOpcode() == ISD::UNDEF)
4548 return InferPointerInfo(Ptr);
4549 return MachinePointerInfo();
4554 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4555 EVT VT, SDLoc dl, SDValue Chain,
4556 SDValue Ptr, SDValue Offset,
4557 MachinePointerInfo PtrInfo, EVT MemVT,
4558 bool isVolatile, bool isNonTemporal, bool isInvariant,
4559 unsigned Alignment, const MDNode *TBAAInfo,
4560 const MDNode *Ranges) {
4561 assert(Chain.getValueType() == MVT::Other &&
4562 "Invalid chain type");
4563 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4564 Alignment = getEVTAlignment(VT);
4566 unsigned Flags = MachineMemOperand::MOLoad;
4568 Flags |= MachineMemOperand::MOVolatile;
4570 Flags |= MachineMemOperand::MONonTemporal;
4572 Flags |= MachineMemOperand::MOInvariant;
4574 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
4576 if (PtrInfo.V.isNull())
4577 PtrInfo = InferPointerInfo(Ptr, Offset);
4579 MachineFunction &MF = getMachineFunction();
4580 MachineMemOperand *MMO =
4581 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
4583 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
4587 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4588 EVT VT, SDLoc dl, SDValue Chain,
4589 SDValue Ptr, SDValue Offset, EVT MemVT,
4590 MachineMemOperand *MMO) {
4592 ExtType = ISD::NON_EXTLOAD;
4593 } else if (ExtType == ISD::NON_EXTLOAD) {
4594 assert(VT == MemVT && "Non-extending load from different memory type!");
4597 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
4598 "Should only be an extending load, not truncating!");
4599 assert(VT.isInteger() == MemVT.isInteger() &&
4600 "Cannot convert from FP to Int or Int -> FP!");
4601 assert(VT.isVector() == MemVT.isVector() &&
4602 "Cannot use trunc store to convert to or from a vector!");
4603 assert((!VT.isVector() ||
4604 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
4605 "Cannot use trunc store to change the number of vector elements!");
4608 bool Indexed = AM != ISD::UNINDEXED;
4609 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
4610 "Unindexed load with an offset!");
4612 SDVTList VTs = Indexed ?
4613 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
4614 SDValue Ops[] = { Chain, Ptr, Offset };
4615 FoldingSetNodeID ID;
4616 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
4617 ID.AddInteger(MemVT.getRawBits());
4618 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
4619 MMO->isNonTemporal(),
4620 MMO->isInvariant()));
4621 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4623 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4624 cast<LoadSDNode>(E)->refineAlignment(MMO);
4625 return SDValue(E, 0);
4627 SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl.getIROrder(),
4628 dl.getDebugLoc(), VTs, AM, ExtType,
4630 CSEMap.InsertNode(N, IP);
4631 AllNodes.push_back(N);
4632 return SDValue(N, 0);
4635 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl,
4636 SDValue Chain, SDValue Ptr,
4637 MachinePointerInfo PtrInfo,
4638 bool isVolatile, bool isNonTemporal,
4639 bool isInvariant, unsigned Alignment,
4640 const MDNode *TBAAInfo,
4641 const MDNode *Ranges) {
4642 SDValue Undef = getUNDEF(Ptr.getValueType());
4643 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4644 PtrInfo, VT, isVolatile, isNonTemporal, isInvariant, Alignment,
4648 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl,
4649 SDValue Chain, SDValue Ptr,
4650 MachineMemOperand *MMO) {
4651 SDValue Undef = getUNDEF(Ptr.getValueType());
4652 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4656 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT,
4657 SDValue Chain, SDValue Ptr,
4658 MachinePointerInfo PtrInfo, EVT MemVT,
4659 bool isVolatile, bool isNonTemporal,
4660 unsigned Alignment, const MDNode *TBAAInfo) {
4661 SDValue Undef = getUNDEF(Ptr.getValueType());
4662 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4663 PtrInfo, MemVT, isVolatile, isNonTemporal, false, Alignment,
4668 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT,
4669 SDValue Chain, SDValue Ptr, EVT MemVT,
4670 MachineMemOperand *MMO) {
4671 SDValue Undef = getUNDEF(Ptr.getValueType());
4672 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4677 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDLoc dl, SDValue Base,
4678 SDValue Offset, ISD::MemIndexedMode AM) {
4679 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
4680 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
4681 "Load is already a indexed load!");
4682 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
4683 LD->getChain(), Base, Offset, LD->getPointerInfo(),
4684 LD->getMemoryVT(), LD->isVolatile(), LD->isNonTemporal(),
4685 false, LD->getAlignment());
4688 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val,
4689 SDValue Ptr, MachinePointerInfo PtrInfo,
4690 bool isVolatile, bool isNonTemporal,
4691 unsigned Alignment, const MDNode *TBAAInfo) {
4692 assert(Chain.getValueType() == MVT::Other &&
4693 "Invalid chain type");
4694 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4695 Alignment = getEVTAlignment(Val.getValueType());
4697 unsigned Flags = MachineMemOperand::MOStore;
4699 Flags |= MachineMemOperand::MOVolatile;
4701 Flags |= MachineMemOperand::MONonTemporal;
4703 if (PtrInfo.V.isNull())
4704 PtrInfo = InferPointerInfo(Ptr);
4706 MachineFunction &MF = getMachineFunction();
4707 MachineMemOperand *MMO =
4708 MF.getMachineMemOperand(PtrInfo, Flags,
4709 Val.getValueType().getStoreSize(), Alignment,
4712 return getStore(Chain, dl, Val, Ptr, MMO);
4715 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val,
4716 SDValue Ptr, MachineMemOperand *MMO) {
4717 assert(Chain.getValueType() == MVT::Other &&
4718 "Invalid chain type");
4719 EVT VT = Val.getValueType();
4720 SDVTList VTs = getVTList(MVT::Other);
4721 SDValue Undef = getUNDEF(Ptr.getValueType());
4722 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4723 FoldingSetNodeID ID;
4724 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
4725 ID.AddInteger(VT.getRawBits());
4726 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
4727 MMO->isNonTemporal(), MMO->isInvariant()));
4728 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4730 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4731 cast<StoreSDNode>(E)->refineAlignment(MMO);
4732 return SDValue(E, 0);
4734 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(),
4735 dl.getDebugLoc(), VTs,
4736 ISD::UNINDEXED, false, VT, MMO);
4737 CSEMap.InsertNode(N, IP);
4738 AllNodes.push_back(N);
4739 return SDValue(N, 0);
4742 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val,
4743 SDValue Ptr, MachinePointerInfo PtrInfo,
4744 EVT SVT,bool isVolatile, bool isNonTemporal,
4746 const MDNode *TBAAInfo) {
4747 assert(Chain.getValueType() == MVT::Other &&
4748 "Invalid chain type");
4749 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4750 Alignment = getEVTAlignment(SVT);
4752 unsigned Flags = MachineMemOperand::MOStore;
4754 Flags |= MachineMemOperand::MOVolatile;
4756 Flags |= MachineMemOperand::MONonTemporal;
4758 if (PtrInfo.V.isNull())
4759 PtrInfo = InferPointerInfo(Ptr);
4761 MachineFunction &MF = getMachineFunction();
4762 MachineMemOperand *MMO =
4763 MF.getMachineMemOperand(PtrInfo, Flags, SVT.getStoreSize(), Alignment,
4766 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
4769 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val,
4770 SDValue Ptr, EVT SVT,
4771 MachineMemOperand *MMO) {
4772 EVT VT = Val.getValueType();
4774 assert(Chain.getValueType() == MVT::Other &&
4775 "Invalid chain type");
4777 return getStore(Chain, dl, Val, Ptr, MMO);
4779 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
4780 "Should only be a truncating store, not extending!");
4781 assert(VT.isInteger() == SVT.isInteger() &&
4782 "Can't do FP-INT conversion!");
4783 assert(VT.isVector() == SVT.isVector() &&
4784 "Cannot use trunc store to convert to or from a vector!");
4785 assert((!VT.isVector() ||
4786 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
4787 "Cannot use trunc store to change the number of vector elements!");
4789 SDVTList VTs = getVTList(MVT::Other);
4790 SDValue Undef = getUNDEF(Ptr.getValueType());
4791 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4792 FoldingSetNodeID ID;
4793 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
4794 ID.AddInteger(SVT.getRawBits());
4795 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
4796 MMO->isNonTemporal(), MMO->isInvariant()));
4797 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4799 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4800 cast<StoreSDNode>(E)->refineAlignment(MMO);
4801 return SDValue(E, 0);
4803 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(),
4804 dl.getDebugLoc(), VTs,
4805 ISD::UNINDEXED, true, SVT, MMO);
4806 CSEMap.InsertNode(N, IP);
4807 AllNodes.push_back(N);
4808 return SDValue(N, 0);
4812 SelectionDAG::getIndexedStore(SDValue OrigStore, SDLoc dl, SDValue Base,
4813 SDValue Offset, ISD::MemIndexedMode AM) {
4814 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4815 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4816 "Store is already a indexed store!");
4817 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4818 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4819 FoldingSetNodeID ID;
4820 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
4821 ID.AddInteger(ST->getMemoryVT().getRawBits());
4822 ID.AddInteger(ST->getRawSubclassData());
4823 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
4825 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4826 return SDValue(E, 0);
4828 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(),
4829 dl.getDebugLoc(), VTs, AM,
4830 ST->isTruncatingStore(),
4832 ST->getMemOperand());
4833 CSEMap.InsertNode(N, IP);
4834 AllNodes.push_back(N);
4835 return SDValue(N, 0);
4838 SDValue SelectionDAG::getVAArg(EVT VT, SDLoc dl,
4839 SDValue Chain, SDValue Ptr,
4842 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, MVT::i32) };
4843 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
4846 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
4847 ArrayRef<SDUse> Ops) {
4848 switch (Ops.size()) {
4849 case 0: return getNode(Opcode, DL, VT);
4850 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
4851 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4852 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4856 // Copy from an SDUse array into an SDValue array for use with
4857 // the regular getNode logic.
4858 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
4859 return getNode(Opcode, DL, VT, NewOps);
4862 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
4863 ArrayRef<SDValue> Ops) {
4864 unsigned NumOps = Ops.size();
4866 case 0: return getNode(Opcode, DL, VT);
4867 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4868 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4869 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4875 case ISD::SELECT_CC: {
4876 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4877 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4878 "LHS and RHS of condition must have same type!");
4879 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4880 "True and False arms of SelectCC must have same type!");
4881 assert(Ops[2].getValueType() == VT &&
4882 "select_cc node must be of same type as true and false value!");
4886 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4887 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4888 "LHS/RHS of comparison should match types!");
4895 SDVTList VTs = getVTList(VT);
4897 if (VT != MVT::Glue) {
4898 FoldingSetNodeID ID;
4899 AddNodeIDNode(ID, Opcode, VTs, Ops);
4902 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4903 return SDValue(E, 0);
4905 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4907 CSEMap.InsertNode(N, IP);
4909 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4913 AllNodes.push_back(N);
4917 return SDValue(N, 0);
4920 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
4921 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
4922 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
4925 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4926 ArrayRef<SDValue> Ops) {
4927 if (VTList.NumVTs == 1)
4928 return getNode(Opcode, DL, VTList.VTs[0], Ops);
4932 // FIXME: figure out how to safely handle things like
4933 // int foo(int x) { return 1 << (x & 255); }
4934 // int bar() { return foo(256); }
4935 case ISD::SRA_PARTS:
4936 case ISD::SRL_PARTS:
4937 case ISD::SHL_PARTS:
4938 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4939 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4940 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4941 else if (N3.getOpcode() == ISD::AND)
4942 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4943 // If the and is only masking out bits that cannot effect the shift,
4944 // eliminate the and.
4945 unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
4946 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4947 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4953 // Memoize the node unless it returns a flag.
4955 unsigned NumOps = Ops.size();
4956 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4957 FoldingSetNodeID ID;
4958 AddNodeIDNode(ID, Opcode, VTList, Ops);
4960 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4961 return SDValue(E, 0);
4964 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(),
4965 DL.getDebugLoc(), VTList, Ops[0]);
4966 } else if (NumOps == 2) {
4967 N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(),
4968 DL.getDebugLoc(), VTList, Ops[0],
4970 } else if (NumOps == 3) {
4971 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
4972 DL.getDebugLoc(), VTList, Ops[0],
4975 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4978 CSEMap.InsertNode(N, IP);
4981 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(),
4982 DL.getDebugLoc(), VTList, Ops[0]);
4983 } else if (NumOps == 2) {
4984 N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(),
4985 DL.getDebugLoc(), VTList, Ops[0],
4987 } else if (NumOps == 3) {
4988 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(),
4989 DL.getDebugLoc(), VTList, Ops[0],
4992 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4996 AllNodes.push_back(N);
5000 return SDValue(N, 0);
5003 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList) {
5004 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
5007 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5009 SDValue Ops[] = { N1 };
5010 return getNode(Opcode, DL, VTList, Ops);
5013 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5014 SDValue N1, SDValue N2) {
5015 SDValue Ops[] = { N1, N2 };
5016 return getNode(Opcode, DL, VTList, Ops);
5019 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5020 SDValue N1, SDValue N2, SDValue N3) {
5021 SDValue Ops[] = { N1, N2, N3 };
5022 return getNode(Opcode, DL, VTList, Ops);
5025 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5026 SDValue N1, SDValue N2, SDValue N3,
5028 SDValue Ops[] = { N1, N2, N3, N4 };
5029 return getNode(Opcode, DL, VTList, Ops);
5032 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
5033 SDValue N1, SDValue N2, SDValue N3,
5034 SDValue N4, SDValue N5) {
5035 SDValue Ops[] = { N1, N2, N3, N4, N5 };
5036 return getNode(Opcode, DL, VTList, Ops);
5039 SDVTList SelectionDAG::getVTList(EVT VT) {
5040 return makeVTList(SDNode::getValueTypeList(VT), 1);
5043 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
5044 FoldingSetNodeID ID;
5046 ID.AddInteger(VT1.getRawBits());
5047 ID.AddInteger(VT2.getRawBits());
5050 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5052 EVT *Array = Allocator.Allocate<EVT>(2);
5055 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
5056 VTListMap.InsertNode(Result, IP);
5058 return Result->getSDVTList();
5061 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
5062 FoldingSetNodeID ID;
5064 ID.AddInteger(VT1.getRawBits());
5065 ID.AddInteger(VT2.getRawBits());
5066 ID.AddInteger(VT3.getRawBits());
5069 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5071 EVT *Array = Allocator.Allocate<EVT>(3);
5075 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
5076 VTListMap.InsertNode(Result, IP);
5078 return Result->getSDVTList();
5081 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
5082 FoldingSetNodeID ID;
5084 ID.AddInteger(VT1.getRawBits());
5085 ID.AddInteger(VT2.getRawBits());
5086 ID.AddInteger(VT3.getRawBits());
5087 ID.AddInteger(VT4.getRawBits());
5090 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5092 EVT *Array = Allocator.Allocate<EVT>(4);
5097 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
5098 VTListMap.InsertNode(Result, IP);
5100 return Result->getSDVTList();
5103 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
5104 unsigned NumVTs = VTs.size();
5105 FoldingSetNodeID ID;
5106 ID.AddInteger(NumVTs);
5107 for (unsigned index = 0; index < NumVTs; index++) {
5108 ID.AddInteger(VTs[index].getRawBits());
5112 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
5114 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
5115 std::copy(VTs.begin(), VTs.end(), Array);
5116 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
5117 VTListMap.InsertNode(Result, IP);
5119 return Result->getSDVTList();
5123 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
5124 /// specified operands. If the resultant node already exists in the DAG,
5125 /// this does not modify the specified node, instead it returns the node that
5126 /// already exists. If the resultant node does not exist in the DAG, the
5127 /// input node is returned. As a degenerate case, if you specify the same
5128 /// input operands as the node already has, the input node is returned.
5129 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
5130 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
5132 // Check to see if there is no change.
5133 if (Op == N->getOperand(0)) return N;
5135 // See if the modified node already exists.
5136 void *InsertPos = nullptr;
5137 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
5140 // Nope it doesn't. Remove the node from its current place in the maps.
5142 if (!RemoveNodeFromCSEMaps(N))
5143 InsertPos = nullptr;
5145 // Now we update the operands.
5146 N->OperandList[0].set(Op);
5148 // If this gets put into a CSE map, add it.
5149 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5153 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
5154 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
5156 // Check to see if there is no change.
5157 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
5158 return N; // No operands changed, just return the input node.
5160 // See if the modified node already exists.
5161 void *InsertPos = nullptr;
5162 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
5165 // Nope it doesn't. Remove the node from its current place in the maps.
5167 if (!RemoveNodeFromCSEMaps(N))
5168 InsertPos = nullptr;
5170 // Now we update the operands.
5171 if (N->OperandList[0] != Op1)
5172 N->OperandList[0].set(Op1);
5173 if (N->OperandList[1] != Op2)
5174 N->OperandList[1].set(Op2);
5176 // If this gets put into a CSE map, add it.
5177 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5181 SDNode *SelectionDAG::
5182 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
5183 SDValue Ops[] = { Op1, Op2, Op3 };
5184 return UpdateNodeOperands(N, Ops);
5187 SDNode *SelectionDAG::
5188 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
5189 SDValue Op3, SDValue Op4) {
5190 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
5191 return UpdateNodeOperands(N, Ops);
5194 SDNode *SelectionDAG::
5195 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
5196 SDValue Op3, SDValue Op4, SDValue Op5) {
5197 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
5198 return UpdateNodeOperands(N, Ops);
5201 SDNode *SelectionDAG::
5202 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
5203 unsigned NumOps = Ops.size();
5204 assert(N->getNumOperands() == NumOps &&
5205 "Update with wrong number of operands");
5207 // Check to see if there is no change.
5208 bool AnyChange = false;
5209 for (unsigned i = 0; i != NumOps; ++i) {
5210 if (Ops[i] != N->getOperand(i)) {
5216 // No operands changed, just return the input node.
5217 if (!AnyChange) return N;
5219 // See if the modified node already exists.
5220 void *InsertPos = nullptr;
5221 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
5224 // Nope it doesn't. Remove the node from its current place in the maps.
5226 if (!RemoveNodeFromCSEMaps(N))
5227 InsertPos = nullptr;
5229 // Now we update the operands.
5230 for (unsigned i = 0; i != NumOps; ++i)
5231 if (N->OperandList[i] != Ops[i])
5232 N->OperandList[i].set(Ops[i]);
5234 // If this gets put into a CSE map, add it.
5235 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5239 /// DropOperands - Release the operands and set this node to have
5241 void SDNode::DropOperands() {
5242 // Unlike the code in MorphNodeTo that does this, we don't need to
5243 // watch for dead nodes here.
5244 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
5250 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
5253 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5255 SDVTList VTs = getVTList(VT);
5256 return SelectNodeTo(N, MachineOpc, VTs, None);
5259 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5260 EVT VT, SDValue Op1) {
5261 SDVTList VTs = getVTList(VT);
5262 SDValue Ops[] = { Op1 };
5263 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5266 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5267 EVT VT, SDValue Op1,
5269 SDVTList VTs = getVTList(VT);
5270 SDValue Ops[] = { Op1, Op2 };
5271 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5274 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5275 EVT VT, SDValue Op1,
5276 SDValue Op2, SDValue Op3) {
5277 SDVTList VTs = getVTList(VT);
5278 SDValue Ops[] = { Op1, Op2, Op3 };
5279 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5282 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5283 EVT VT, ArrayRef<SDValue> Ops) {
5284 SDVTList VTs = getVTList(VT);
5285 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5288 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5289 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
5290 SDVTList VTs = getVTList(VT1, VT2);
5291 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5294 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5296 SDVTList VTs = getVTList(VT1, VT2);
5297 return SelectNodeTo(N, MachineOpc, VTs, None);
5300 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5301 EVT VT1, EVT VT2, EVT VT3,
5302 ArrayRef<SDValue> Ops) {
5303 SDVTList VTs = getVTList(VT1, VT2, VT3);
5304 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5307 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5308 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
5309 ArrayRef<SDValue> Ops) {
5310 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5311 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5314 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5317 SDVTList VTs = getVTList(VT1, VT2);
5318 SDValue Ops[] = { Op1 };
5319 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5322 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5324 SDValue Op1, SDValue Op2) {
5325 SDVTList VTs = getVTList(VT1, VT2);
5326 SDValue Ops[] = { Op1, Op2 };
5327 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5330 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5332 SDValue Op1, SDValue Op2,
5334 SDVTList VTs = getVTList(VT1, VT2);
5335 SDValue Ops[] = { Op1, Op2, Op3 };
5336 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5339 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5340 EVT VT1, EVT VT2, EVT VT3,
5341 SDValue Op1, SDValue Op2,
5343 SDVTList VTs = getVTList(VT1, VT2, VT3);
5344 SDValue Ops[] = { Op1, Op2, Op3 };
5345 return SelectNodeTo(N, MachineOpc, VTs, Ops);
5348 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5349 SDVTList VTs,ArrayRef<SDValue> Ops) {
5350 N = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
5351 // Reset the NodeID to -1.
5356 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away
5357 /// the line number information on the merged node since it is not possible to
5358 /// preserve the information that operation is associated with multiple lines.
5359 /// This will make the debugger working better at -O0, were there is a higher
5360 /// probability having other instructions associated with that line.
5362 /// For IROrder, we keep the smaller of the two
5363 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, SDLoc OLoc) {
5364 DebugLoc NLoc = N->getDebugLoc();
5365 if (!(NLoc.isUnknown()) && (OptLevel == CodeGenOpt::None) &&
5366 (OLoc.getDebugLoc() != NLoc)) {
5367 N->setDebugLoc(DebugLoc());
5369 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
5370 N->setIROrder(Order);
5374 /// MorphNodeTo - This *mutates* the specified node to have the specified
5375 /// return type, opcode, and operands.
5377 /// Note that MorphNodeTo returns the resultant node. If there is already a
5378 /// node of the specified opcode and operands, it returns that node instead of
5379 /// the current one. Note that the SDLoc need not be the same.
5381 /// Using MorphNodeTo is faster than creating a new node and swapping it in
5382 /// with ReplaceAllUsesWith both because it often avoids allocating a new
5383 /// node, and because it doesn't require CSE recalculation for any of
5384 /// the node's users.
5386 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
5387 SDVTList VTs, ArrayRef<SDValue> Ops) {
5388 unsigned NumOps = Ops.size();
5389 // If an identical node already exists, use it.
5391 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
5392 FoldingSetNodeID ID;
5393 AddNodeIDNode(ID, Opc, VTs, Ops);
5394 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
5395 return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N));
5398 if (!RemoveNodeFromCSEMaps(N))
5401 // Start the morphing.
5403 N->ValueList = VTs.VTs;
5404 N->NumValues = VTs.NumVTs;
5406 // Clear the operands list, updating used nodes to remove this from their
5407 // use list. Keep track of any operands that become dead as a result.
5408 SmallPtrSet<SDNode*, 16> DeadNodeSet;
5409 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
5411 SDNode *Used = Use.getNode();
5413 if (Used->use_empty())
5414 DeadNodeSet.insert(Used);
5417 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
5418 // Initialize the memory references information.
5419 MN->setMemRefs(nullptr, nullptr);
5420 // If NumOps is larger than the # of operands we can have in a
5421 // MachineSDNode, reallocate the operand list.
5422 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
5423 if (MN->OperandsNeedDelete)
5424 delete[] MN->OperandList;
5425 if (NumOps > array_lengthof(MN->LocalOperands))
5426 // We're creating a final node that will live unmorphed for the
5427 // remainder of the current SelectionDAG iteration, so we can allocate
5428 // the operands directly out of a pool with no recycling metadata.
5429 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5430 Ops.data(), NumOps);
5432 MN->InitOperands(MN->LocalOperands, Ops.data(), NumOps);
5433 MN->OperandsNeedDelete = false;
5435 MN->InitOperands(MN->OperandList, Ops.data(), NumOps);
5437 // If NumOps is larger than the # of operands we currently have, reallocate
5438 // the operand list.
5439 if (NumOps > N->NumOperands) {
5440 if (N->OperandsNeedDelete)
5441 delete[] N->OperandList;
5442 N->InitOperands(new SDUse[NumOps], Ops.data(), NumOps);
5443 N->OperandsNeedDelete = true;
5445 N->InitOperands(N->OperandList, Ops.data(), NumOps);
5448 // Delete any nodes that are still dead after adding the uses for the
5450 if (!DeadNodeSet.empty()) {
5451 SmallVector<SDNode *, 16> DeadNodes;
5452 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
5453 E = DeadNodeSet.end(); I != E; ++I)
5454 if ((*I)->use_empty())
5455 DeadNodes.push_back(*I);
5456 RemoveDeadNodes(DeadNodes);
5460 CSEMap.InsertNode(N, IP); // Memoize the new node.
5465 /// getMachineNode - These are used for target selectors to create a new node
5466 /// with specified return type(s), MachineInstr opcode, and operands.
5468 /// Note that getMachineNode returns the resultant node. If there is already a
5469 /// node of the specified opcode and operands, it returns that node instead of
5470 /// the current one.
5472 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT) {
5473 SDVTList VTs = getVTList(VT);
5474 return getMachineNode(Opcode, dl, VTs, None);
5478 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, SDValue Op1) {
5479 SDVTList VTs = getVTList(VT);
5480 SDValue Ops[] = { Op1 };
5481 return getMachineNode(Opcode, dl, VTs, Ops);
5485 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5486 SDValue Op1, SDValue Op2) {
5487 SDVTList VTs = getVTList(VT);
5488 SDValue Ops[] = { Op1, Op2 };
5489 return getMachineNode(Opcode, dl, VTs, Ops);
5493 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5494 SDValue Op1, SDValue Op2, SDValue Op3) {
5495 SDVTList VTs = getVTList(VT);
5496 SDValue Ops[] = { Op1, Op2, Op3 };
5497 return getMachineNode(Opcode, dl, VTs, Ops);
5501 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5502 ArrayRef<SDValue> Ops) {
5503 SDVTList VTs = getVTList(VT);
5504 return getMachineNode(Opcode, dl, VTs, Ops);
5508 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2) {
5509 SDVTList VTs = getVTList(VT1, VT2);
5510 return getMachineNode(Opcode, dl, VTs, None);
5514 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5515 EVT VT1, EVT VT2, SDValue Op1) {
5516 SDVTList VTs = getVTList(VT1, VT2);
5517 SDValue Ops[] = { Op1 };
5518 return getMachineNode(Opcode, dl, VTs, Ops);
5522 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5523 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
5524 SDVTList VTs = getVTList(VT1, VT2);
5525 SDValue Ops[] = { Op1, Op2 };
5526 return getMachineNode(Opcode, dl, VTs, Ops);
5530 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5531 EVT VT1, EVT VT2, SDValue Op1,
5532 SDValue Op2, SDValue Op3) {
5533 SDVTList VTs = getVTList(VT1, VT2);
5534 SDValue Ops[] = { Op1, Op2, Op3 };
5535 return getMachineNode(Opcode, dl, VTs, Ops);
5539 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5541 ArrayRef<SDValue> Ops) {
5542 SDVTList VTs = getVTList(VT1, VT2);
5543 return getMachineNode(Opcode, dl, VTs, Ops);
5547 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5548 EVT VT1, EVT VT2, EVT VT3,
5549 SDValue Op1, SDValue Op2) {
5550 SDVTList VTs = getVTList(VT1, VT2, VT3);
5551 SDValue Ops[] = { Op1, Op2 };
5552 return getMachineNode(Opcode, dl, VTs, Ops);
5556 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5557 EVT VT1, EVT VT2, EVT VT3,
5558 SDValue Op1, SDValue Op2, SDValue Op3) {
5559 SDVTList VTs = getVTList(VT1, VT2, VT3);
5560 SDValue Ops[] = { Op1, Op2, Op3 };
5561 return getMachineNode(Opcode, dl, VTs, Ops);
5565 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5566 EVT VT1, EVT VT2, EVT VT3,
5567 ArrayRef<SDValue> Ops) {
5568 SDVTList VTs = getVTList(VT1, VT2, VT3);
5569 return getMachineNode(Opcode, dl, VTs, Ops);
5573 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1,
5574 EVT VT2, EVT VT3, EVT VT4,
5575 ArrayRef<SDValue> Ops) {
5576 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5577 return getMachineNode(Opcode, dl, VTs, Ops);
5581 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5582 ArrayRef<EVT> ResultTys,
5583 ArrayRef<SDValue> Ops) {
5584 SDVTList VTs = getVTList(ResultTys);
5585 return getMachineNode(Opcode, dl, VTs, Ops);
5589 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc DL, SDVTList VTs,
5590 ArrayRef<SDValue> OpsArray) {
5591 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
5594 const SDValue *Ops = OpsArray.data();
5595 unsigned NumOps = OpsArray.size();
5598 FoldingSetNodeID ID;
5599 AddNodeIDNode(ID, ~Opcode, VTs, OpsArray);
5601 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5602 return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL));
5606 // Allocate a new MachineSDNode.
5607 N = new (NodeAllocator) MachineSDNode(~Opcode, DL.getIROrder(),
5608 DL.getDebugLoc(), VTs);
5610 // Initialize the operands list.
5611 if (NumOps > array_lengthof(N->LocalOperands))
5612 // We're creating a final node that will live unmorphed for the
5613 // remainder of the current SelectionDAG iteration, so we can allocate
5614 // the operands directly out of a pool with no recycling metadata.
5615 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5618 N->InitOperands(N->LocalOperands, Ops, NumOps);
5619 N->OperandsNeedDelete = false;
5622 CSEMap.InsertNode(N, IP);
5624 AllNodes.push_back(N);
5626 VerifyMachineNode(N);
5631 /// getTargetExtractSubreg - A convenience function for creating
5632 /// TargetOpcode::EXTRACT_SUBREG nodes.
5634 SelectionDAG::getTargetExtractSubreg(int SRIdx, SDLoc DL, EVT VT,
5636 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5637 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
5638 VT, Operand, SRIdxVal);
5639 return SDValue(Subreg, 0);
5642 /// getTargetInsertSubreg - A convenience function for creating
5643 /// TargetOpcode::INSERT_SUBREG nodes.
5645 SelectionDAG::getTargetInsertSubreg(int SRIdx, SDLoc DL, EVT VT,
5646 SDValue Operand, SDValue Subreg) {
5647 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5648 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
5649 VT, Operand, Subreg, SRIdxVal);
5650 return SDValue(Result, 0);
5653 /// getNodeIfExists - Get the specified node if it's already available, or
5654 /// else return NULL.
5655 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
5656 ArrayRef<SDValue> Ops, bool nuw, bool nsw,
5658 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
5659 FoldingSetNodeID ID;
5660 AddNodeIDNode(ID, Opcode, VTList, Ops);
5661 if (isBinOpWithFlags(Opcode))
5662 AddBinaryNodeIDCustom(ID, nuw, nsw, exact);
5664 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5670 /// getDbgValue - Creates a SDDbgValue node.
5674 SelectionDAG::getDbgValue(MDNode *MDPtr, SDNode *N, unsigned R,
5675 bool IsIndirect, uint64_t Off,
5676 DebugLoc DL, unsigned O) {
5677 return new (Allocator) SDDbgValue(MDPtr, N, R, IsIndirect, Off, DL, O);
5682 SelectionDAG::getConstantDbgValue(MDNode *MDPtr, const Value *C,
5684 DebugLoc DL, unsigned O) {
5685 return new (Allocator) SDDbgValue(MDPtr, C, Off, DL, O);
5690 SelectionDAG::getFrameIndexDbgValue(MDNode *MDPtr, unsigned FI, uint64_t Off,
5691 DebugLoc DL, unsigned O) {
5692 return new (Allocator) SDDbgValue(MDPtr, FI, Off, DL, O);
5697 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
5698 /// pointed to by a use iterator is deleted, increment the use iterator
5699 /// so that it doesn't dangle.
5701 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
5702 SDNode::use_iterator &UI;
5703 SDNode::use_iterator &UE;
5705 void NodeDeleted(SDNode *N, SDNode *E) override {
5706 // Increment the iterator as needed.
5707 while (UI != UE && N == *UI)
5712 RAUWUpdateListener(SelectionDAG &d,
5713 SDNode::use_iterator &ui,
5714 SDNode::use_iterator &ue)
5715 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
5720 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5721 /// This can cause recursive merging of nodes in the DAG.
5723 /// This version assumes From has a single result value.
5725 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
5726 SDNode *From = FromN.getNode();
5727 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
5728 "Cannot replace with this method!");
5729 assert(From != To.getNode() && "Cannot replace uses of with self");
5731 // Iterate over all the existing uses of From. New uses will be added
5732 // to the beginning of the use list, which we avoid visiting.
5733 // This specifically avoids visiting uses of From that arise while the
5734 // replacement is happening, because any such uses would be the result
5735 // of CSE: If an existing node looks like From after one of its operands
5736 // is replaced by To, we don't want to replace of all its users with To
5737 // too. See PR3018 for more info.
5738 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5739 RAUWUpdateListener Listener(*this, UI, UE);
5743 // This node is about to morph, remove its old self from the CSE maps.
5744 RemoveNodeFromCSEMaps(User);
5746 // A user can appear in a use list multiple times, and when this
5747 // happens the uses are usually next to each other in the list.
5748 // To help reduce the number of CSE recomputations, process all
5749 // the uses of this user that we can find this way.
5751 SDUse &Use = UI.getUse();
5754 } while (UI != UE && *UI == User);
5756 // Now that we have modified User, add it back to the CSE maps. If it
5757 // already exists there, recursively merge the results together.
5758 AddModifiedNodeToCSEMaps(User);
5761 // If we just RAUW'd the root, take note.
5762 if (FromN == getRoot())
5766 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5767 /// This can cause recursive merging of nodes in the DAG.
5769 /// This version assumes that for each value of From, there is a
5770 /// corresponding value in To in the same position with the same type.
5772 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
5774 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
5775 assert((!From->hasAnyUseOfValue(i) ||
5776 From->getValueType(i) == To->getValueType(i)) &&
5777 "Cannot use this version of ReplaceAllUsesWith!");
5780 // Handle the trivial case.
5784 // Iterate over just the existing users of From. See the comments in
5785 // the ReplaceAllUsesWith above.
5786 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5787 RAUWUpdateListener Listener(*this, UI, UE);
5791 // This node is about to morph, remove its old self from the CSE maps.
5792 RemoveNodeFromCSEMaps(User);
5794 // A user can appear in a use list multiple times, and when this
5795 // happens the uses are usually next to each other in the list.
5796 // To help reduce the number of CSE recomputations, process all
5797 // the uses of this user that we can find this way.
5799 SDUse &Use = UI.getUse();
5802 } while (UI != UE && *UI == User);
5804 // Now that we have modified User, add it back to the CSE maps. If it
5805 // already exists there, recursively merge the results together.
5806 AddModifiedNodeToCSEMaps(User);
5809 // If we just RAUW'd the root, take note.
5810 if (From == getRoot().getNode())
5811 setRoot(SDValue(To, getRoot().getResNo()));
5814 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5815 /// This can cause recursive merging of nodes in the DAG.
5817 /// This version can replace From with any result values. To must match the
5818 /// number and types of values returned by From.
5819 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
5820 if (From->getNumValues() == 1) // Handle the simple case efficiently.
5821 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
5823 // Iterate over just the existing users of From. See the comments in
5824 // the ReplaceAllUsesWith above.
5825 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5826 RAUWUpdateListener Listener(*this, UI, UE);
5830 // This node is about to morph, remove its old self from the CSE maps.
5831 RemoveNodeFromCSEMaps(User);
5833 // A user can appear in a use list multiple times, and when this
5834 // happens the uses are usually next to each other in the list.
5835 // To help reduce the number of CSE recomputations, process all
5836 // the uses of this user that we can find this way.
5838 SDUse &Use = UI.getUse();
5839 const SDValue &ToOp = To[Use.getResNo()];
5842 } while (UI != UE && *UI == User);
5844 // Now that we have modified User, add it back to the CSE maps. If it
5845 // already exists there, recursively merge the results together.
5846 AddModifiedNodeToCSEMaps(User);
5849 // If we just RAUW'd the root, take note.
5850 if (From == getRoot().getNode())
5851 setRoot(SDValue(To[getRoot().getResNo()]));
5854 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5855 /// uses of other values produced by From.getNode() alone. The Deleted
5856 /// vector is handled the same way as for ReplaceAllUsesWith.
5857 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
5858 // Handle the really simple, really trivial case efficiently.
5859 if (From == To) return;
5861 // Handle the simple, trivial, case efficiently.
5862 if (From.getNode()->getNumValues() == 1) {
5863 ReplaceAllUsesWith(From, To);
5867 // Iterate over just the existing users of From. See the comments in
5868 // the ReplaceAllUsesWith above.
5869 SDNode::use_iterator UI = From.getNode()->use_begin(),
5870 UE = From.getNode()->use_end();
5871 RAUWUpdateListener Listener(*this, UI, UE);
5874 bool UserRemovedFromCSEMaps = false;
5876 // A user can appear in a use list multiple times, and when this
5877 // happens the uses are usually next to each other in the list.
5878 // To help reduce the number of CSE recomputations, process all
5879 // the uses of this user that we can find this way.
5881 SDUse &Use = UI.getUse();
5883 // Skip uses of different values from the same node.
5884 if (Use.getResNo() != From.getResNo()) {
5889 // If this node hasn't been modified yet, it's still in the CSE maps,
5890 // so remove its old self from the CSE maps.
5891 if (!UserRemovedFromCSEMaps) {
5892 RemoveNodeFromCSEMaps(User);
5893 UserRemovedFromCSEMaps = true;
5898 } while (UI != UE && *UI == User);
5900 // We are iterating over all uses of the From node, so if a use
5901 // doesn't use the specific value, no changes are made.
5902 if (!UserRemovedFromCSEMaps)
5905 // Now that we have modified User, add it back to the CSE maps. If it
5906 // already exists there, recursively merge the results together.
5907 AddModifiedNodeToCSEMaps(User);
5910 // If we just RAUW'd the root, take note.
5911 if (From == getRoot())
5916 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5917 /// to record information about a use.
5924 /// operator< - Sort Memos by User.
5925 bool operator<(const UseMemo &L, const UseMemo &R) {
5926 return (intptr_t)L.User < (intptr_t)R.User;
5930 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5931 /// uses of other values produced by From.getNode() alone. The same value
5932 /// may appear in both the From and To list. The Deleted vector is
5933 /// handled the same way as for ReplaceAllUsesWith.
5934 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5937 // Handle the simple, trivial case efficiently.
5939 return ReplaceAllUsesOfValueWith(*From, *To);
5941 // Read up all the uses and make records of them. This helps
5942 // processing new uses that are introduced during the
5943 // replacement process.
5944 SmallVector<UseMemo, 4> Uses;
5945 for (unsigned i = 0; i != Num; ++i) {
5946 unsigned FromResNo = From[i].getResNo();
5947 SDNode *FromNode = From[i].getNode();
5948 for (SDNode::use_iterator UI = FromNode->use_begin(),
5949 E = FromNode->use_end(); UI != E; ++UI) {
5950 SDUse &Use = UI.getUse();
5951 if (Use.getResNo() == FromResNo) {
5952 UseMemo Memo = { *UI, i, &Use };
5953 Uses.push_back(Memo);
5958 // Sort the uses, so that all the uses from a given User are together.
5959 std::sort(Uses.begin(), Uses.end());
5961 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5962 UseIndex != UseIndexEnd; ) {
5963 // We know that this user uses some value of From. If it is the right
5964 // value, update it.
5965 SDNode *User = Uses[UseIndex].User;
5967 // This node is about to morph, remove its old self from the CSE maps.
5968 RemoveNodeFromCSEMaps(User);
5970 // The Uses array is sorted, so all the uses for a given User
5971 // are next to each other in the list.
5972 // To help reduce the number of CSE recomputations, process all
5973 // the uses of this user that we can find this way.
5975 unsigned i = Uses[UseIndex].Index;
5976 SDUse &Use = *Uses[UseIndex].Use;
5980 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5982 // Now that we have modified User, add it back to the CSE maps. If it
5983 // already exists there, recursively merge the results together.
5984 AddModifiedNodeToCSEMaps(User);
5988 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5989 /// based on their topological order. It returns the maximum id and a vector
5990 /// of the SDNodes* in assigned order by reference.
5991 unsigned SelectionDAG::AssignTopologicalOrder() {
5993 unsigned DAGSize = 0;
5995 // SortedPos tracks the progress of the algorithm. Nodes before it are
5996 // sorted, nodes after it are unsorted. When the algorithm completes
5997 // it is at the end of the list.
5998 allnodes_iterator SortedPos = allnodes_begin();
6000 // Visit all the nodes. Move nodes with no operands to the front of
6001 // the list immediately. Annotate nodes that do have operands with their
6002 // operand count. Before we do this, the Node Id fields of the nodes
6003 // may contain arbitrary values. After, the Node Id fields for nodes
6004 // before SortedPos will contain the topological sort index, and the
6005 // Node Id fields for nodes At SortedPos and after will contain the
6006 // count of outstanding operands.
6007 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
6009 checkForCycles(N, this);
6010 unsigned Degree = N->getNumOperands();
6012 // A node with no uses, add it to the result array immediately.
6013 N->setNodeId(DAGSize++);
6014 allnodes_iterator Q = N;
6016 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
6017 assert(SortedPos != AllNodes.end() && "Overran node list");
6020 // Temporarily use the Node Id as scratch space for the degree count.
6021 N->setNodeId(Degree);
6025 // Visit all the nodes. As we iterate, move nodes into sorted order,
6026 // such that by the time the end is reached all nodes will be sorted.
6027 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
6029 checkForCycles(N, this);
6030 // N is in sorted position, so all its uses have one less operand
6031 // that needs to be sorted.
6032 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
6035 unsigned Degree = P->getNodeId();
6036 assert(Degree != 0 && "Invalid node degree");
6039 // All of P's operands are sorted, so P may sorted now.
6040 P->setNodeId(DAGSize++);
6042 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
6043 assert(SortedPos != AllNodes.end() && "Overran node list");
6046 // Update P's outstanding operand count.
6047 P->setNodeId(Degree);
6050 if (I == SortedPos) {
6053 dbgs() << "Overran sorted position:\n";
6054 S->dumprFull(this); dbgs() << "\n";
6055 dbgs() << "Checking if this is due to cycles\n";
6056 checkForCycles(this, true);
6058 llvm_unreachable(nullptr);
6062 assert(SortedPos == AllNodes.end() &&
6063 "Topological sort incomplete!");
6064 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
6065 "First node in topological sort is not the entry token!");
6066 assert(AllNodes.front().getNodeId() == 0 &&
6067 "First node in topological sort has non-zero id!");
6068 assert(AllNodes.front().getNumOperands() == 0 &&
6069 "First node in topological sort has operands!");
6070 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
6071 "Last node in topologic sort has unexpected id!");
6072 assert(AllNodes.back().use_empty() &&
6073 "Last node in topologic sort has users!");
6074 assert(DAGSize == allnodes_size() && "Node count mismatch!");
6078 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
6079 /// value is produced by SD.
6080 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
6081 DbgInfo->add(DB, SD, isParameter);
6083 SD->setHasDebugValue(true);
6086 /// TransferDbgValues - Transfer SDDbgValues.
6087 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
6088 if (From == To || !From.getNode()->getHasDebugValue())
6090 SDNode *FromNode = From.getNode();
6091 SDNode *ToNode = To.getNode();
6092 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
6093 SmallVector<SDDbgValue *, 2> ClonedDVs;
6094 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
6096 SDDbgValue *Dbg = *I;
6097 if (Dbg->getKind() == SDDbgValue::SDNODE) {
6098 SDDbgValue *Clone = getDbgValue(Dbg->getMDPtr(), ToNode, To.getResNo(),
6100 Dbg->getOffset(), Dbg->getDebugLoc(),
6102 ClonedDVs.push_back(Clone);
6105 for (SmallVectorImpl<SDDbgValue *>::iterator I = ClonedDVs.begin(),
6106 E = ClonedDVs.end(); I != E; ++I)
6107 AddDbgValue(*I, ToNode, false);
6110 //===----------------------------------------------------------------------===//
6112 //===----------------------------------------------------------------------===//
6114 HandleSDNode::~HandleSDNode() {
6118 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
6119 DebugLoc DL, const GlobalValue *GA,
6120 EVT VT, int64_t o, unsigned char TF)
6121 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
6125 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, DebugLoc dl, EVT VT,
6126 SDValue X, unsigned SrcAS,
6128 : UnarySDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT), X),
6129 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
6131 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
6132 EVT memvt, MachineMemOperand *mmo)
6133 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
6134 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
6135 MMO->isNonTemporal(), MMO->isInvariant());
6136 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
6137 assert(isNonTemporal() == MMO->isNonTemporal() &&
6138 "Non-temporal encoding error!");
6139 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
6142 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
6143 ArrayRef<SDValue> Ops, EVT memvt, MachineMemOperand *mmo)
6144 : SDNode(Opc, Order, dl, VTs, Ops),
6145 MemoryVT(memvt), MMO(mmo) {
6146 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
6147 MMO->isNonTemporal(), MMO->isInvariant());
6148 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
6149 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
6152 /// Profile - Gather unique data for the node.
6154 void SDNode::Profile(FoldingSetNodeID &ID) const {
6155 AddNodeIDNode(ID, this);
6160 std::vector<EVT> VTs;
6163 VTs.reserve(MVT::LAST_VALUETYPE);
6164 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
6165 VTs.push_back(MVT((MVT::SimpleValueType)i));
6170 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
6171 static ManagedStatic<EVTArray> SimpleVTArray;
6172 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
6174 /// getValueTypeList - Return a pointer to the specified value type.
6176 const EVT *SDNode::getValueTypeList(EVT VT) {
6177 if (VT.isExtended()) {
6178 sys::SmartScopedLock<true> Lock(*VTMutex);
6179 return &(*EVTs->insert(VT).first);
6181 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
6182 "Value type out of range!");
6183 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
6187 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
6188 /// indicated value. This method ignores uses of other values defined by this
6190 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
6191 assert(Value < getNumValues() && "Bad value!");
6193 // TODO: Only iterate over uses of a given value of the node
6194 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
6195 if (UI.getUse().getResNo() == Value) {
6202 // Found exactly the right number of uses?
6207 /// hasAnyUseOfValue - Return true if there are any use of the indicated
6208 /// value. This method ignores uses of other values defined by this operation.
6209 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
6210 assert(Value < getNumValues() && "Bad value!");
6212 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
6213 if (UI.getUse().getResNo() == Value)
6220 /// isOnlyUserOf - Return true if this node is the only use of N.
6222 bool SDNode::isOnlyUserOf(SDNode *N) const {
6224 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
6235 /// isOperand - Return true if this node is an operand of N.
6237 bool SDValue::isOperandOf(SDNode *N) const {
6238 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6239 if (*this == N->getOperand(i))
6244 bool SDNode::isOperandOf(SDNode *N) const {
6245 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
6246 if (this == N->OperandList[i].getNode())
6251 /// reachesChainWithoutSideEffects - Return true if this operand (which must
6252 /// be a chain) reaches the specified operand without crossing any
6253 /// side-effecting instructions on any chain path. In practice, this looks
6254 /// through token factors and non-volatile loads. In order to remain efficient,
6255 /// this only looks a couple of nodes in, it does not do an exhaustive search.
6256 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
6257 unsigned Depth) const {
6258 if (*this == Dest) return true;
6260 // Don't search too deeply, we just want to be able to see through
6261 // TokenFactor's etc.
6262 if (Depth == 0) return false;
6264 // If this is a token factor, all inputs to the TF happen in parallel. If any
6265 // of the operands of the TF does not reach dest, then we cannot do the xform.
6266 if (getOpcode() == ISD::TokenFactor) {
6267 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6268 if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
6273 // Loads don't have side effects, look through them.
6274 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
6275 if (!Ld->isVolatile())
6276 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
6281 /// hasPredecessor - Return true if N is a predecessor of this node.
6282 /// N is either an operand of this node, or can be reached by recursively
6283 /// traversing up the operands.
6284 /// NOTE: This is an expensive method. Use it carefully.
6285 bool SDNode::hasPredecessor(const SDNode *N) const {
6286 SmallPtrSet<const SDNode *, 32> Visited;
6287 SmallVector<const SDNode *, 16> Worklist;
6288 return hasPredecessorHelper(N, Visited, Worklist);
6292 SDNode::hasPredecessorHelper(const SDNode *N,
6293 SmallPtrSet<const SDNode *, 32> &Visited,
6294 SmallVectorImpl<const SDNode *> &Worklist) const {
6295 if (Visited.empty()) {
6296 Worklist.push_back(this);
6298 // Take a look in the visited set. If we've already encountered this node
6299 // we needn't search further.
6300 if (Visited.count(N))
6304 // Haven't visited N yet. Continue the search.
6305 while (!Worklist.empty()) {
6306 const SDNode *M = Worklist.pop_back_val();
6307 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
6308 SDNode *Op = M->getOperand(i).getNode();
6309 if (Visited.insert(Op))
6310 Worklist.push_back(Op);
6319 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
6320 assert(Num < NumOperands && "Invalid child # of SDNode!");
6321 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
6324 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6325 assert(N->getNumValues() == 1 &&
6326 "Can't unroll a vector with multiple results!");
6328 EVT VT = N->getValueType(0);
6329 unsigned NE = VT.getVectorNumElements();
6330 EVT EltVT = VT.getVectorElementType();
6333 SmallVector<SDValue, 8> Scalars;
6334 SmallVector<SDValue, 4> Operands(N->getNumOperands());
6336 // If ResNE is 0, fully unroll the vector op.
6339 else if (NE > ResNE)
6343 for (i= 0; i != NE; ++i) {
6344 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
6345 SDValue Operand = N->getOperand(j);
6346 EVT OperandVT = Operand.getValueType();
6347 if (OperandVT.isVector()) {
6348 // A vector operand; extract a single element.
6349 const TargetLowering *TLI = TM.getTargetLowering();
6350 EVT OperandEltVT = OperandVT.getVectorElementType();
6351 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6354 getConstant(i, TLI->getVectorIdxTy()));
6356 // A scalar operand; just use it as is.
6357 Operands[j] = Operand;
6361 switch (N->getOpcode()) {
6363 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands));
6366 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
6373 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6374 getShiftAmountOperand(Operands[0].getValueType(),
6377 case ISD::SIGN_EXTEND_INREG:
6378 case ISD::FP_ROUND_INREG: {
6379 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6380 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6382 getValueType(ExtVT)));
6387 for (; i < ResNE; ++i)
6388 Scalars.push_back(getUNDEF(EltVT));
6390 return getNode(ISD::BUILD_VECTOR, dl,
6391 EVT::getVectorVT(*getContext(), EltVT, ResNE), Scalars);
6395 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6396 /// location that is 'Dist' units away from the location that the 'Base' load
6397 /// is loading from.
6398 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6399 unsigned Bytes, int Dist) const {
6400 if (LD->getChain() != Base->getChain())
6402 EVT VT = LD->getValueType(0);
6403 if (VT.getSizeInBits() / 8 != Bytes)
6406 SDValue Loc = LD->getOperand(1);
6407 SDValue BaseLoc = Base->getOperand(1);
6408 if (Loc.getOpcode() == ISD::FrameIndex) {
6409 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6411 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6412 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6413 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6414 int FS = MFI->getObjectSize(FI);
6415 int BFS = MFI->getObjectSize(BFI);
6416 if (FS != BFS || FS != (int)Bytes) return false;
6417 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6421 if (isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
6422 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
6425 const GlobalValue *GV1 = nullptr;
6426 const GlobalValue *GV2 = nullptr;
6427 int64_t Offset1 = 0;
6428 int64_t Offset2 = 0;
6429 const TargetLowering *TLI = TM.getTargetLowering();
6430 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6431 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6432 if (isGA1 && isGA2 && GV1 == GV2)
6433 return Offset1 == (Offset2 + Dist*Bytes);
6438 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6439 /// it cannot be inferred.
6440 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6441 // If this is a GlobalAddress + cst, return the alignment.
6442 const GlobalValue *GV;
6443 int64_t GVOffset = 0;
6444 const TargetLowering *TLI = TM.getTargetLowering();
6445 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
6446 unsigned PtrWidth = TLI->getPointerTypeSizeInBits(GV->getType());
6447 APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
6448 llvm::computeKnownBits(const_cast<GlobalValue*>(GV), KnownZero, KnownOne,
6449 TLI->getDataLayout());
6450 unsigned AlignBits = KnownZero.countTrailingOnes();
6451 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
6453 return MinAlign(Align, GVOffset);
6456 // If this is a direct reference to a stack slot, use information about the
6457 // stack slot's alignment.
6458 int FrameIdx = 1 << 31;
6459 int64_t FrameOffset = 0;
6460 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6461 FrameIdx = FI->getIndex();
6462 } else if (isBaseWithConstantOffset(Ptr) &&
6463 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6465 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6466 FrameOffset = Ptr.getConstantOperandVal(1);
6469 if (FrameIdx != (1 << 31)) {
6470 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6471 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6479 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
6480 /// which is split (or expanded) into two not necessarily identical pieces.
6481 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
6482 // Currently all types are split in half.
6484 if (!VT.isVector()) {
6485 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
6487 unsigned NumElements = VT.getVectorNumElements();
6488 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6489 LoVT = HiVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
6492 return std::make_pair(LoVT, HiVT);
6495 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
6497 std::pair<SDValue, SDValue>
6498 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
6500 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
6501 N.getValueType().getVectorNumElements() &&
6502 "More vector elements requested than available!");
6504 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
6505 getConstant(0, TLI->getVectorIdxTy()));
6506 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
6507 getConstant(LoVT.getVectorNumElements(), TLI->getVectorIdxTy()));
6508 return std::make_pair(Lo, Hi);
6511 void SelectionDAG::ExtractVectorElements(SDValue Op,
6512 SmallVectorImpl<SDValue> &Args,
6513 unsigned Start, unsigned Count) {
6514 EVT VT = Op.getValueType();
6516 Count = VT.getVectorNumElements();
6518 EVT EltVT = VT.getVectorElementType();
6519 EVT IdxTy = TLI->getVectorIdxTy();
6521 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
6522 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6523 Op, getConstant(i, IdxTy)));
6527 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6528 unsigned GlobalAddressSDNode::getAddressSpace() const {
6529 return getGlobal()->getType()->getAddressSpace();
6533 Type *ConstantPoolSDNode::getType() const {
6534 if (isMachineConstantPoolEntry())
6535 return Val.MachineCPVal->getType();
6536 return Val.ConstVal->getType();
6539 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6541 unsigned &SplatBitSize,
6543 unsigned MinSplatBits,
6544 bool isBigEndian) const {
6545 EVT VT = getValueType(0);
6546 assert(VT.isVector() && "Expected a vector type");
6547 unsigned sz = VT.getSizeInBits();
6548 if (MinSplatBits > sz)
6551 SplatValue = APInt(sz, 0);
6552 SplatUndef = APInt(sz, 0);
6554 // Get the bits. Bits with undefined values (when the corresponding element
6555 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6556 // in SplatValue. If any of the values are not constant, give up and return
6558 unsigned int nOps = getNumOperands();
6559 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6560 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6562 for (unsigned j = 0; j < nOps; ++j) {
6563 unsigned i = isBigEndian ? nOps-1-j : j;
6564 SDValue OpVal = getOperand(i);
6565 unsigned BitPos = j * EltBitSize;
6567 if (OpVal.getOpcode() == ISD::UNDEF)
6568 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6569 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6570 SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize).
6571 zextOrTrunc(sz) << BitPos;
6572 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6573 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6578 // The build_vector is all constants or undefs. Find the smallest element
6579 // size that splats the vector.
6581 HasAnyUndefs = (SplatUndef != 0);
6584 unsigned HalfSize = sz / 2;
6585 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
6586 APInt LowValue = SplatValue.trunc(HalfSize);
6587 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
6588 APInt LowUndef = SplatUndef.trunc(HalfSize);
6590 // If the two halves do not match (ignoring undef bits), stop here.
6591 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6592 MinSplatBits > HalfSize)
6595 SplatValue = HighValue | LowValue;
6596 SplatUndef = HighUndef & LowUndef;
6605 ConstantSDNode *BuildVectorSDNode::getConstantSplatValue() const {
6606 SDValue Op0 = getOperand(0);
6607 if (Op0.getOpcode() != ISD::Constant)
6610 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
6611 if (getOperand(i) != Op0)
6614 return cast<ConstantSDNode>(Op0);
6617 bool BuildVectorSDNode::isConstant() const {
6618 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
6619 unsigned Opc = getOperand(i).getOpcode();
6620 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
6626 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6627 // Find the first non-undef value in the shuffle mask.
6629 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6632 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6634 // Make sure all remaining elements are either undef or the same as the first
6636 for (int Idx = Mask[i]; i != e; ++i)
6637 if (Mask[i] >= 0 && Mask[i] != Idx)
6643 static void checkForCyclesHelper(const SDNode *N,
6644 SmallPtrSet<const SDNode*, 32> &Visited,
6645 SmallPtrSet<const SDNode*, 32> &Checked,
6646 const llvm::SelectionDAG *DAG) {
6647 // If this node has already been checked, don't check it again.
6648 if (Checked.count(N))
6651 // If a node has already been visited on this depth-first walk, reject it as
6653 if (!Visited.insert(N)) {
6654 errs() << "Detected cycle in SelectionDAG\n";
6655 dbgs() << "Offending node:\n";
6656 N->dumprFull(DAG); dbgs() << "\n";
6660 for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6661 checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked, DAG);
6668 void llvm::checkForCycles(const llvm::SDNode *N,
6669 const llvm::SelectionDAG *DAG,
6677 assert(N && "Checking nonexistent SDNode");
6678 SmallPtrSet<const SDNode*, 32> visited;
6679 SmallPtrSet<const SDNode*, 32> checked;
6680 checkForCyclesHelper(N, visited, checked, DAG);
6685 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
6686 checkForCycles(DAG->getRoot().getNode(), DAG, force);