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/TargetTransformInfo.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/MachineBasicBlock.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/DebugInfo.h"
29 #include "llvm/IR/CallingConv.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalAlias.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Mutex.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetIntrinsicInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
50 #include "llvm/Target/TargetSelectionDAGInfo.h"
55 /// makeVTList - Return an instance of the SDVTList struct initialized with the
56 /// specified members.
57 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
58 SDVTList Res = {VTs, NumVTs};
62 // Default null implementations of the callbacks.
63 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
64 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
66 //===----------------------------------------------------------------------===//
67 // ConstantFPSDNode Class
68 //===----------------------------------------------------------------------===//
70 /// isExactlyValue - We don't rely on operator== working on double values, as
71 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
72 /// As such, this method can be used to do an exact bit-for-bit comparison of
73 /// two floating point values.
74 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
75 return getValueAPF().bitwiseIsEqual(V);
78 bool ConstantFPSDNode::isValueValidForType(EVT VT,
80 assert(VT.isFloatingPoint() && "Can only convert between FP types");
82 // convert modifies in place, so make a copy.
83 APFloat Val2 = APFloat(Val);
85 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
86 APFloat::rmNearestTiesToEven,
91 //===----------------------------------------------------------------------===//
93 //===----------------------------------------------------------------------===//
95 /// isBuildVectorAllOnes - Return true if the specified node is a
96 /// BUILD_VECTOR where all of the elements are ~0 or undef.
97 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
98 // Look through a bit convert.
99 if (N->getOpcode() == ISD::BITCAST)
100 N = N->getOperand(0).getNode();
102 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
104 unsigned i = 0, e = N->getNumOperands();
106 // Skip over all of the undef values.
107 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
110 // Do not accept an all-undef vector.
111 if (i == e) return false;
113 // Do not accept build_vectors that aren't all constants or which have non-~0
114 // elements. We have to be a bit careful here, as the type of the constant
115 // may not be the same as the type of the vector elements due to type
116 // legalization (the elements are promoted to a legal type for the target and
117 // a vector of a type may be legal when the base element type is not).
118 // We only want to check enough bits to cover the vector elements, because
119 // we care if the resultant vector is all ones, not whether the individual
121 SDValue NotZero = N->getOperand(i);
122 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
123 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
124 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
126 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
127 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
132 // Okay, we have at least one ~0 value, check to see if the rest match or are
133 // undefs. Even with the above element type twiddling, this should be OK, as
134 // the same type legalization should have applied to all the elements.
135 for (++i; i != e; ++i)
136 if (N->getOperand(i) != NotZero &&
137 N->getOperand(i).getOpcode() != ISD::UNDEF)
143 /// isBuildVectorAllZeros - Return true if the specified node is a
144 /// BUILD_VECTOR where all of the elements are 0 or undef.
145 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
146 // Look through a bit convert.
147 if (N->getOpcode() == ISD::BITCAST)
148 N = N->getOperand(0).getNode();
150 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
152 unsigned i = 0, e = N->getNumOperands();
154 // Skip over all of the undef values.
155 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
158 // Do not accept an all-undef vector.
159 if (i == e) return false;
161 // Do not accept build_vectors that aren't all constants or which have non-0
163 SDValue Zero = N->getOperand(i);
164 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Zero)) {
165 if (!CN->isNullValue())
167 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Zero)) {
168 if (!CFPN->getValueAPF().isPosZero())
173 // Okay, we have at least one 0 value, check to see if the rest match or are
175 for (++i; i != e; ++i)
176 if (N->getOperand(i) != Zero &&
177 N->getOperand(i).getOpcode() != ISD::UNDEF)
182 /// isScalarToVector - Return true if the specified node is a
183 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
184 /// element is not an undef.
185 bool ISD::isScalarToVector(const SDNode *N) {
186 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
189 if (N->getOpcode() != ISD::BUILD_VECTOR)
191 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
193 unsigned NumElems = N->getNumOperands();
196 for (unsigned i = 1; i < NumElems; ++i) {
197 SDValue V = N->getOperand(i);
198 if (V.getOpcode() != ISD::UNDEF)
204 /// allOperandsUndef - Return true if the node has at least one operand
205 /// and all operands of the specified node are ISD::UNDEF.
206 bool ISD::allOperandsUndef(const SDNode *N) {
207 // Return false if the node has no operands.
208 // This is "logically inconsistent" with the definition of "all" but
209 // is probably the desired behavior.
210 if (N->getNumOperands() == 0)
213 for (unsigned i = 0, e = N->getNumOperands(); i != e ; ++i)
214 if (N->getOperand(i).getOpcode() != ISD::UNDEF)
220 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
221 /// when given the operation for (X op Y).
222 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
223 // To perform this operation, we just need to swap the L and G bits of the
225 unsigned OldL = (Operation >> 2) & 1;
226 unsigned OldG = (Operation >> 1) & 1;
227 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
228 (OldL << 1) | // New G bit
229 (OldG << 2)); // New L bit.
232 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
233 /// 'op' is a valid SetCC operation.
234 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
235 unsigned Operation = Op;
237 Operation ^= 7; // Flip L, G, E bits, but not U.
239 Operation ^= 15; // Flip all of the condition bits.
241 if (Operation > ISD::SETTRUE2)
242 Operation &= ~8; // Don't let N and U bits get set.
244 return ISD::CondCode(Operation);
248 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
249 /// signed operation and 2 if the result is an unsigned comparison. Return zero
250 /// if the operation does not depend on the sign of the input (setne and seteq).
251 static int isSignedOp(ISD::CondCode Opcode) {
253 default: llvm_unreachable("Illegal integer setcc operation!");
255 case ISD::SETNE: return 0;
259 case ISD::SETGE: return 1;
263 case ISD::SETUGE: return 2;
267 /// getSetCCOrOperation - Return the result of a logical OR between different
268 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
269 /// returns SETCC_INVALID if it is not possible to represent the resultant
271 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
273 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
274 // Cannot fold a signed integer setcc with an unsigned integer setcc.
275 return ISD::SETCC_INVALID;
277 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
279 // If the N and U bits get set then the resultant comparison DOES suddenly
280 // care about orderedness, and is true when ordered.
281 if (Op > ISD::SETTRUE2)
282 Op &= ~16; // Clear the U bit if the N bit is set.
284 // Canonicalize illegal integer setcc's.
285 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
288 return ISD::CondCode(Op);
291 /// getSetCCAndOperation - Return the result of a logical AND between different
292 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
293 /// function returns zero if it is not possible to represent the resultant
295 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
297 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
298 // Cannot fold a signed setcc with an unsigned setcc.
299 return ISD::SETCC_INVALID;
301 // Combine all of the condition bits.
302 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
304 // Canonicalize illegal integer setcc's.
308 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
309 case ISD::SETOEQ: // SETEQ & SETU[LG]E
310 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
311 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
312 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
319 //===----------------------------------------------------------------------===//
320 // SDNode Profile Support
321 //===----------------------------------------------------------------------===//
323 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
325 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
329 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
330 /// solely with their pointer.
331 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
332 ID.AddPointer(VTList.VTs);
335 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
337 static void AddNodeIDOperands(FoldingSetNodeID &ID,
338 const SDValue *Ops, unsigned NumOps) {
339 for (; NumOps; --NumOps, ++Ops) {
340 ID.AddPointer(Ops->getNode());
341 ID.AddInteger(Ops->getResNo());
345 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
347 static void AddNodeIDOperands(FoldingSetNodeID &ID,
348 const SDUse *Ops, unsigned NumOps) {
349 for (; NumOps; --NumOps, ++Ops) {
350 ID.AddPointer(Ops->getNode());
351 ID.AddInteger(Ops->getResNo());
355 static void AddNodeIDNode(FoldingSetNodeID &ID,
356 unsigned short OpC, SDVTList VTList,
357 const SDValue *OpList, unsigned N) {
358 AddNodeIDOpcode(ID, OpC);
359 AddNodeIDValueTypes(ID, VTList);
360 AddNodeIDOperands(ID, OpList, N);
363 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
365 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
366 switch (N->getOpcode()) {
367 case ISD::TargetExternalSymbol:
368 case ISD::ExternalSymbol:
369 llvm_unreachable("Should only be used on nodes with operands");
370 default: break; // Normal nodes don't need extra info.
371 case ISD::TargetConstant:
373 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
375 case ISD::TargetConstantFP:
376 case ISD::ConstantFP: {
377 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
380 case ISD::TargetGlobalAddress:
381 case ISD::GlobalAddress:
382 case ISD::TargetGlobalTLSAddress:
383 case ISD::GlobalTLSAddress: {
384 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
385 ID.AddPointer(GA->getGlobal());
386 ID.AddInteger(GA->getOffset());
387 ID.AddInteger(GA->getTargetFlags());
388 ID.AddInteger(GA->getAddressSpace());
391 case ISD::BasicBlock:
392 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
395 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
397 case ISD::RegisterMask:
398 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
401 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
403 case ISD::FrameIndex:
404 case ISD::TargetFrameIndex:
405 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
408 case ISD::TargetJumpTable:
409 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
410 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
412 case ISD::ConstantPool:
413 case ISD::TargetConstantPool: {
414 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
415 ID.AddInteger(CP->getAlignment());
416 ID.AddInteger(CP->getOffset());
417 if (CP->isMachineConstantPoolEntry())
418 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
420 ID.AddPointer(CP->getConstVal());
421 ID.AddInteger(CP->getTargetFlags());
424 case ISD::TargetIndex: {
425 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
426 ID.AddInteger(TI->getIndex());
427 ID.AddInteger(TI->getOffset());
428 ID.AddInteger(TI->getTargetFlags());
432 const LoadSDNode *LD = cast<LoadSDNode>(N);
433 ID.AddInteger(LD->getMemoryVT().getRawBits());
434 ID.AddInteger(LD->getRawSubclassData());
435 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
439 const StoreSDNode *ST = cast<StoreSDNode>(N);
440 ID.AddInteger(ST->getMemoryVT().getRawBits());
441 ID.AddInteger(ST->getRawSubclassData());
442 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
445 case ISD::ATOMIC_CMP_SWAP:
446 case ISD::ATOMIC_SWAP:
447 case ISD::ATOMIC_LOAD_ADD:
448 case ISD::ATOMIC_LOAD_SUB:
449 case ISD::ATOMIC_LOAD_AND:
450 case ISD::ATOMIC_LOAD_OR:
451 case ISD::ATOMIC_LOAD_XOR:
452 case ISD::ATOMIC_LOAD_NAND:
453 case ISD::ATOMIC_LOAD_MIN:
454 case ISD::ATOMIC_LOAD_MAX:
455 case ISD::ATOMIC_LOAD_UMIN:
456 case ISD::ATOMIC_LOAD_UMAX:
457 case ISD::ATOMIC_LOAD:
458 case ISD::ATOMIC_STORE: {
459 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
460 ID.AddInteger(AT->getMemoryVT().getRawBits());
461 ID.AddInteger(AT->getRawSubclassData());
462 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
465 case ISD::PREFETCH: {
466 const MemSDNode *PF = cast<MemSDNode>(N);
467 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
470 case ISD::VECTOR_SHUFFLE: {
471 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
472 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
474 ID.AddInteger(SVN->getMaskElt(i));
477 case ISD::TargetBlockAddress:
478 case ISD::BlockAddress: {
479 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
480 ID.AddPointer(BA->getBlockAddress());
481 ID.AddInteger(BA->getOffset());
482 ID.AddInteger(BA->getTargetFlags());
485 } // end switch (N->getOpcode())
487 // Target specific memory nodes could also have address spaces to check.
488 if (N->isTargetMemoryOpcode())
489 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
492 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
494 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
495 AddNodeIDOpcode(ID, N->getOpcode());
496 // Add the return value info.
497 AddNodeIDValueTypes(ID, N->getVTList());
498 // Add the operand info.
499 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
501 // Handle SDNode leafs with special info.
502 AddNodeIDCustom(ID, N);
505 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
506 /// the CSE map that carries volatility, temporalness, indexing mode, and
507 /// extension/truncation information.
509 static inline unsigned
510 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile,
511 bool isNonTemporal, bool isInvariant) {
512 assert((ConvType & 3) == ConvType &&
513 "ConvType may not require more than 2 bits!");
514 assert((AM & 7) == AM &&
515 "AM may not require more than 3 bits!");
519 (isNonTemporal << 6) |
523 //===----------------------------------------------------------------------===//
524 // SelectionDAG Class
525 //===----------------------------------------------------------------------===//
527 /// doNotCSE - Return true if CSE should not be performed for this node.
528 static bool doNotCSE(SDNode *N) {
529 if (N->getValueType(0) == MVT::Glue)
530 return true; // Never CSE anything that produces a flag.
532 switch (N->getOpcode()) {
534 case ISD::HANDLENODE:
536 return true; // Never CSE these nodes.
539 // Check that remaining values produced are not flags.
540 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
541 if (N->getValueType(i) == MVT::Glue)
542 return true; // Never CSE anything that produces a flag.
547 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
549 void SelectionDAG::RemoveDeadNodes() {
550 // Create a dummy node (which is not added to allnodes), that adds a reference
551 // to the root node, preventing it from being deleted.
552 HandleSDNode Dummy(getRoot());
554 SmallVector<SDNode*, 128> DeadNodes;
556 // Add all obviously-dead nodes to the DeadNodes worklist.
557 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
559 DeadNodes.push_back(I);
561 RemoveDeadNodes(DeadNodes);
563 // If the root changed (e.g. it was a dead load, update the root).
564 setRoot(Dummy.getValue());
567 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
568 /// given list, and any nodes that become unreachable as a result.
569 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
571 // Process the worklist, deleting the nodes and adding their uses to the
573 while (!DeadNodes.empty()) {
574 SDNode *N = DeadNodes.pop_back_val();
576 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
577 DUL->NodeDeleted(N, 0);
579 // Take the node out of the appropriate CSE map.
580 RemoveNodeFromCSEMaps(N);
582 // Next, brutally remove the operand list. This is safe to do, as there are
583 // no cycles in the graph.
584 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
586 SDNode *Operand = Use.getNode();
589 // Now that we removed this operand, see if there are no uses of it left.
590 if (Operand->use_empty())
591 DeadNodes.push_back(Operand);
598 void SelectionDAG::RemoveDeadNode(SDNode *N){
599 SmallVector<SDNode*, 16> DeadNodes(1, N);
601 // Create a dummy node that adds a reference to the root node, preventing
602 // it from being deleted. (This matters if the root is an operand of the
604 HandleSDNode Dummy(getRoot());
606 RemoveDeadNodes(DeadNodes);
609 void SelectionDAG::DeleteNode(SDNode *N) {
610 // First take this out of the appropriate CSE map.
611 RemoveNodeFromCSEMaps(N);
613 // Finally, remove uses due to operands of this node, remove from the
614 // AllNodes list, and delete the node.
615 DeleteNodeNotInCSEMaps(N);
618 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
619 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
620 assert(N->use_empty() && "Cannot delete a node that is not dead!");
622 // Drop all of the operands and decrement used node's use counts.
628 void SelectionDAG::DeallocateNode(SDNode *N) {
629 if (N->OperandsNeedDelete)
630 delete[] N->OperandList;
632 // Set the opcode to DELETED_NODE to help catch bugs when node
633 // memory is reallocated.
634 N->NodeType = ISD::DELETED_NODE;
636 NodeAllocator.Deallocate(AllNodes.remove(N));
638 // If any of the SDDbgValue nodes refer to this SDNode, invalidate them.
639 ArrayRef<SDDbgValue*> DbgVals = DbgInfo->getSDDbgValues(N);
640 for (unsigned i = 0, e = DbgVals.size(); i != e; ++i)
641 DbgVals[i]->setIsInvalidated();
644 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
645 /// correspond to it. This is useful when we're about to delete or repurpose
646 /// the node. We don't want future request for structurally identical nodes
647 /// to return N anymore.
648 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
650 switch (N->getOpcode()) {
651 case ISD::HANDLENODE: return false; // noop.
653 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
654 "Cond code doesn't exist!");
655 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
656 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
658 case ISD::ExternalSymbol:
659 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
661 case ISD::TargetExternalSymbol: {
662 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
663 Erased = TargetExternalSymbols.erase(
664 std::pair<std::string,unsigned char>(ESN->getSymbol(),
665 ESN->getTargetFlags()));
668 case ISD::VALUETYPE: {
669 EVT VT = cast<VTSDNode>(N)->getVT();
670 if (VT.isExtended()) {
671 Erased = ExtendedValueTypeNodes.erase(VT);
673 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
674 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
679 // Remove it from the CSE Map.
680 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
681 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
682 Erased = CSEMap.RemoveNode(N);
686 // Verify that the node was actually in one of the CSE maps, unless it has a
687 // flag result (which cannot be CSE'd) or is one of the special cases that are
688 // not subject to CSE.
689 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
690 !N->isMachineOpcode() && !doNotCSE(N)) {
693 llvm_unreachable("Node is not in map!");
699 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
700 /// maps and modified in place. Add it back to the CSE maps, unless an identical
701 /// node already exists, in which case transfer all its users to the existing
702 /// node. This transfer can potentially trigger recursive merging.
705 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
706 // For node types that aren't CSE'd, just act as if no identical node
709 SDNode *Existing = CSEMap.GetOrInsertNode(N);
711 // If there was already an existing matching node, use ReplaceAllUsesWith
712 // to replace the dead one with the existing one. This can cause
713 // recursive merging of other unrelated nodes down the line.
714 ReplaceAllUsesWith(N, Existing);
716 // N is now dead. Inform the listeners and delete it.
717 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
718 DUL->NodeDeleted(N, Existing);
719 DeleteNodeNotInCSEMaps(N);
724 // If the node doesn't already exist, we updated it. Inform listeners.
725 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
729 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
730 /// were replaced with those specified. If this node is never memoized,
731 /// return null, otherwise return a pointer to the slot it would take. If a
732 /// node already exists with these operands, the slot will be non-null.
733 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
738 SDValue Ops[] = { Op };
740 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
741 AddNodeIDCustom(ID, N);
742 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
746 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
747 /// were replaced with those specified. If this node is never memoized,
748 /// return null, otherwise return a pointer to the slot it would take. If a
749 /// node already exists with these operands, the slot will be non-null.
750 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
751 SDValue Op1, SDValue Op2,
756 SDValue Ops[] = { Op1, Op2 };
758 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
759 AddNodeIDCustom(ID, N);
760 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
765 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
766 /// were replaced with those specified. If this node is never memoized,
767 /// return null, otherwise return a pointer to the slot it would take. If a
768 /// node already exists with these operands, the slot will be non-null.
769 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
770 const SDValue *Ops,unsigned NumOps,
776 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
777 AddNodeIDCustom(ID, N);
778 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
783 /// VerifyNodeCommon - Sanity check the given node. Aborts if it is invalid.
784 static void VerifyNodeCommon(SDNode *N) {
785 switch (N->getOpcode()) {
788 case ISD::BUILD_PAIR: {
789 EVT VT = N->getValueType(0);
790 assert(N->getNumValues() == 1 && "Too many results!");
791 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
792 "Wrong return type!");
793 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
794 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
795 "Mismatched operand types!");
796 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
797 "Wrong operand type!");
798 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
799 "Wrong return type size");
802 case ISD::BUILD_VECTOR: {
803 assert(N->getNumValues() == 1 && "Too many results!");
804 assert(N->getValueType(0).isVector() && "Wrong return type!");
805 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
806 "Wrong number of operands!");
807 EVT EltVT = N->getValueType(0).getVectorElementType();
808 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
809 assert((I->getValueType() == EltVT ||
810 (EltVT.isInteger() && I->getValueType().isInteger() &&
811 EltVT.bitsLE(I->getValueType()))) &&
812 "Wrong operand type!");
813 assert(I->getValueType() == N->getOperand(0).getValueType() &&
814 "Operands must all have the same type");
821 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
822 static void VerifySDNode(SDNode *N) {
823 // The SDNode allocators cannot be used to allocate nodes with fields that are
824 // not present in an SDNode!
825 assert(!isa<MemSDNode>(N) && "Bad MemSDNode!");
826 assert(!isa<ShuffleVectorSDNode>(N) && "Bad ShuffleVectorSDNode!");
827 assert(!isa<ConstantSDNode>(N) && "Bad ConstantSDNode!");
828 assert(!isa<ConstantFPSDNode>(N) && "Bad ConstantFPSDNode!");
829 assert(!isa<GlobalAddressSDNode>(N) && "Bad GlobalAddressSDNode!");
830 assert(!isa<FrameIndexSDNode>(N) && "Bad FrameIndexSDNode!");
831 assert(!isa<JumpTableSDNode>(N) && "Bad JumpTableSDNode!");
832 assert(!isa<ConstantPoolSDNode>(N) && "Bad ConstantPoolSDNode!");
833 assert(!isa<BasicBlockSDNode>(N) && "Bad BasicBlockSDNode!");
834 assert(!isa<SrcValueSDNode>(N) && "Bad SrcValueSDNode!");
835 assert(!isa<MDNodeSDNode>(N) && "Bad MDNodeSDNode!");
836 assert(!isa<RegisterSDNode>(N) && "Bad RegisterSDNode!");
837 assert(!isa<BlockAddressSDNode>(N) && "Bad BlockAddressSDNode!");
838 assert(!isa<EHLabelSDNode>(N) && "Bad EHLabelSDNode!");
839 assert(!isa<ExternalSymbolSDNode>(N) && "Bad ExternalSymbolSDNode!");
840 assert(!isa<CondCodeSDNode>(N) && "Bad CondCodeSDNode!");
841 assert(!isa<CvtRndSatSDNode>(N) && "Bad CvtRndSatSDNode!");
842 assert(!isa<VTSDNode>(N) && "Bad VTSDNode!");
843 assert(!isa<MachineSDNode>(N) && "Bad MachineSDNode!");
848 /// VerifyMachineNode - Sanity check the given MachineNode. Aborts if it is
850 static void VerifyMachineNode(SDNode *N) {
851 // The MachineNode allocators cannot be used to allocate nodes with fields
852 // that are not present in a MachineNode!
853 // Currently there are no such nodes.
859 /// getEVTAlignment - Compute the default alignment value for the
862 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
863 Type *Ty = VT == MVT::iPTR ?
864 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
865 VT.getTypeForEVT(*getContext());
867 return TLI.getDataLayout()->getABITypeAlignment(Ty);
870 // EntryNode could meaningfully have debug info if we can find it...
871 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
872 : TM(tm), TLI(*tm.getTargetLowering()), TSI(*tm.getSelectionDAGInfo()),
873 TTI(0), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
874 getVTList(MVT::Other)),
875 Root(getEntryNode()), UpdateListeners(0) {
876 AllNodes.push_back(&EntryNode);
877 DbgInfo = new SDDbgInfo();
880 void SelectionDAG::init(MachineFunction &mf, const TargetTransformInfo *tti) {
883 Context = &mf.getFunction()->getContext();
886 SelectionDAG::~SelectionDAG() {
887 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
892 void SelectionDAG::allnodes_clear() {
893 assert(&*AllNodes.begin() == &EntryNode);
894 AllNodes.remove(AllNodes.begin());
895 while (!AllNodes.empty())
896 DeallocateNode(AllNodes.begin());
899 void SelectionDAG::clear() {
901 OperandAllocator.Reset();
904 ExtendedValueTypeNodes.clear();
905 ExternalSymbols.clear();
906 TargetExternalSymbols.clear();
907 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
908 static_cast<CondCodeSDNode*>(0));
909 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
910 static_cast<SDNode*>(0));
912 EntryNode.UseList = 0;
913 AllNodes.push_back(&EntryNode);
914 Root = getEntryNode();
918 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
919 return VT.bitsGT(Op.getValueType()) ?
920 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
921 getNode(ISD::TRUNCATE, DL, VT, Op);
924 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
925 return VT.bitsGT(Op.getValueType()) ?
926 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
927 getNode(ISD::TRUNCATE, DL, VT, Op);
930 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, SDLoc DL, EVT VT) {
931 return VT.bitsGT(Op.getValueType()) ?
932 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
933 getNode(ISD::TRUNCATE, DL, VT, Op);
936 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, SDLoc DL, EVT VT) {
937 assert(!VT.isVector() &&
938 "getZeroExtendInReg should use the vector element type instead of "
940 if (Op.getValueType() == VT) return Op;
941 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
942 APInt Imm = APInt::getLowBitsSet(BitWidth,
944 return getNode(ISD::AND, DL, Op.getValueType(), Op,
945 getConstant(Imm, Op.getValueType()));
948 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
950 SDValue SelectionDAG::getNOT(SDLoc DL, SDValue Val, EVT VT) {
951 EVT EltVT = VT.getScalarType();
953 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
954 return getNode(ISD::XOR, DL, VT, Val, NegOne);
957 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
958 EVT EltVT = VT.getScalarType();
959 assert((EltVT.getSizeInBits() >= 64 ||
960 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
961 "getConstant with a uint64_t value that doesn't fit in the type!");
962 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
965 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
966 return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
969 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
970 assert(VT.isInteger() && "Cannot create FP integer constant!");
972 EVT EltVT = VT.getScalarType();
973 const ConstantInt *Elt = &Val;
975 // In some cases the vector type is legal but the element type is illegal and
976 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
977 // inserted value (the type does not need to match the vector element type).
978 // Any extra bits introduced will be truncated away.
979 if (VT.isVector() && TLI.getTypeAction(*getContext(), EltVT) ==
980 TargetLowering::TypePromoteInteger) {
981 EltVT = TLI.getTypeToTransformTo(*getContext(), EltVT);
982 APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits());
983 Elt = ConstantInt::get(*getContext(), NewVal);
986 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
987 "APInt size does not match type size!");
988 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
990 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
994 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
996 return SDValue(N, 0);
999 N = new (NodeAllocator) ConstantSDNode(isT, Elt, EltVT);
1000 CSEMap.InsertNode(N, IP);
1001 AllNodes.push_back(N);
1004 SDValue Result(N, 0);
1005 if (VT.isVector()) {
1006 SmallVector<SDValue, 8> Ops;
1007 Ops.assign(VT.getVectorNumElements(), Result);
1008 Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, &Ops[0], Ops.size());
1013 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
1014 return getConstant(Val, TLI.getPointerTy(), isTarget);
1018 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
1019 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
1022 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
1023 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1025 EVT EltVT = VT.getScalarType();
1027 // Do the map lookup using the actual bit pattern for the floating point
1028 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1029 // we don't have issues with SNANs.
1030 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1031 FoldingSetNodeID ID;
1032 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
1036 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
1038 return SDValue(N, 0);
1041 N = new (NodeAllocator) ConstantFPSDNode(isTarget, &V, EltVT);
1042 CSEMap.InsertNode(N, IP);
1043 AllNodes.push_back(N);
1046 SDValue Result(N, 0);
1047 if (VT.isVector()) {
1048 SmallVector<SDValue, 8> Ops;
1049 Ops.assign(VT.getVectorNumElements(), Result);
1050 // FIXME SDLoc info might be appropriate here
1051 Result = getNode(ISD::BUILD_VECTOR, SDLoc(), VT, &Ops[0], Ops.size());
1056 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
1057 EVT EltVT = VT.getScalarType();
1058 if (EltVT==MVT::f32)
1059 return getConstantFP(APFloat((float)Val), VT, isTarget);
1060 else if (EltVT==MVT::f64)
1061 return getConstantFP(APFloat(Val), VT, isTarget);
1062 else if (EltVT==MVT::f80 || EltVT==MVT::f128 || EltVT==MVT::ppcf128 ||
1065 APFloat apf = APFloat(Val);
1066 apf.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1068 return getConstantFP(apf, VT, isTarget);
1070 llvm_unreachable("Unsupported type in getConstantFP");
1073 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, SDLoc DL,
1074 EVT VT, int64_t Offset,
1076 unsigned char TargetFlags) {
1077 assert((TargetFlags == 0 || isTargetGA) &&
1078 "Cannot set target flags on target-independent globals");
1080 // Truncate (with sign-extension) the offset value to the pointer size.
1081 unsigned BitWidth = TLI.getPointerTy().getSizeInBits();
1083 Offset = SignExtend64(Offset, BitWidth);
1085 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1087 // If GV is an alias then use the aliasee for determining thread-localness.
1088 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1089 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1093 if (GVar && GVar->isThreadLocal())
1094 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1096 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1098 FoldingSetNodeID ID;
1099 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1101 ID.AddInteger(Offset);
1102 ID.AddInteger(TargetFlags);
1103 ID.AddInteger(GV->getType()->getAddressSpace());
1105 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1106 return SDValue(E, 0);
1108 SDNode *N = new (NodeAllocator) GlobalAddressSDNode(Opc, DL.getIROrder(),
1109 DL.getDebugLoc(), GV, VT,
1110 Offset, TargetFlags);
1111 CSEMap.InsertNode(N, IP);
1112 AllNodes.push_back(N);
1113 return SDValue(N, 0);
1116 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1117 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1118 FoldingSetNodeID ID;
1119 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1122 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1123 return SDValue(E, 0);
1125 SDNode *N = new (NodeAllocator) FrameIndexSDNode(FI, VT, isTarget);
1126 CSEMap.InsertNode(N, IP);
1127 AllNodes.push_back(N);
1128 return SDValue(N, 0);
1131 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1132 unsigned char TargetFlags) {
1133 assert((TargetFlags == 0 || isTarget) &&
1134 "Cannot set target flags on target-independent jump tables");
1135 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1136 FoldingSetNodeID ID;
1137 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1139 ID.AddInteger(TargetFlags);
1141 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1142 return SDValue(E, 0);
1144 SDNode *N = new (NodeAllocator) JumpTableSDNode(JTI, VT, isTarget,
1146 CSEMap.InsertNode(N, IP);
1147 AllNodes.push_back(N);
1148 return SDValue(N, 0);
1151 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1152 unsigned Alignment, int Offset,
1154 unsigned char TargetFlags) {
1155 assert((TargetFlags == 0 || isTarget) &&
1156 "Cannot set target flags on target-independent globals");
1158 Alignment = TLI.getDataLayout()->getPrefTypeAlignment(C->getType());
1159 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1160 FoldingSetNodeID ID;
1161 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1162 ID.AddInteger(Alignment);
1163 ID.AddInteger(Offset);
1165 ID.AddInteger(TargetFlags);
1167 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1168 return SDValue(E, 0);
1170 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1171 Alignment, TargetFlags);
1172 CSEMap.InsertNode(N, IP);
1173 AllNodes.push_back(N);
1174 return SDValue(N, 0);
1178 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1179 unsigned Alignment, int Offset,
1181 unsigned char TargetFlags) {
1182 assert((TargetFlags == 0 || isTarget) &&
1183 "Cannot set target flags on target-independent globals");
1185 Alignment = TLI.getDataLayout()->getPrefTypeAlignment(C->getType());
1186 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1187 FoldingSetNodeID ID;
1188 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1189 ID.AddInteger(Alignment);
1190 ID.AddInteger(Offset);
1191 C->addSelectionDAGCSEId(ID);
1192 ID.AddInteger(TargetFlags);
1194 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1195 return SDValue(E, 0);
1197 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1198 Alignment, TargetFlags);
1199 CSEMap.InsertNode(N, IP);
1200 AllNodes.push_back(N);
1201 return SDValue(N, 0);
1204 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1205 unsigned char TargetFlags) {
1206 FoldingSetNodeID ID;
1207 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), 0, 0);
1208 ID.AddInteger(Index);
1209 ID.AddInteger(Offset);
1210 ID.AddInteger(TargetFlags);
1212 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1213 return SDValue(E, 0);
1215 SDNode *N = new (NodeAllocator) TargetIndexSDNode(Index, VT, Offset,
1217 CSEMap.InsertNode(N, IP);
1218 AllNodes.push_back(N);
1219 return SDValue(N, 0);
1222 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1223 FoldingSetNodeID ID;
1224 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1227 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1228 return SDValue(E, 0);
1230 SDNode *N = new (NodeAllocator) BasicBlockSDNode(MBB);
1231 CSEMap.InsertNode(N, IP);
1232 AllNodes.push_back(N);
1233 return SDValue(N, 0);
1236 SDValue SelectionDAG::getValueType(EVT VT) {
1237 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1238 ValueTypeNodes.size())
1239 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1241 SDNode *&N = VT.isExtended() ?
1242 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1244 if (N) return SDValue(N, 0);
1245 N = new (NodeAllocator) VTSDNode(VT);
1246 AllNodes.push_back(N);
1247 return SDValue(N, 0);
1250 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1251 SDNode *&N = ExternalSymbols[Sym];
1252 if (N) return SDValue(N, 0);
1253 N = new (NodeAllocator) ExternalSymbolSDNode(false, Sym, 0, VT);
1254 AllNodes.push_back(N);
1255 return SDValue(N, 0);
1258 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1259 unsigned char TargetFlags) {
1261 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1263 if (N) return SDValue(N, 0);
1264 N = new (NodeAllocator) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1265 AllNodes.push_back(N);
1266 return SDValue(N, 0);
1269 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1270 if ((unsigned)Cond >= CondCodeNodes.size())
1271 CondCodeNodes.resize(Cond+1);
1273 if (CondCodeNodes[Cond] == 0) {
1274 CondCodeSDNode *N = new (NodeAllocator) CondCodeSDNode(Cond);
1275 CondCodeNodes[Cond] = N;
1276 AllNodes.push_back(N);
1279 return SDValue(CondCodeNodes[Cond], 0);
1282 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1283 // the shuffle mask M that point at N1 to point at N2, and indices that point
1284 // N2 to point at N1.
1285 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1287 int NElts = M.size();
1288 for (int i = 0; i != NElts; ++i) {
1296 SDValue SelectionDAG::getVectorShuffle(EVT VT, SDLoc dl, SDValue N1,
1297 SDValue N2, const int *Mask) {
1298 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1299 assert(VT.isVector() && N1.getValueType().isVector() &&
1300 "Vector Shuffle VTs must be a vectors");
1301 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1302 && "Vector Shuffle VTs must have same element type");
1304 // Canonicalize shuffle undef, undef -> undef
1305 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1306 return getUNDEF(VT);
1308 // Validate that all indices in Mask are within the range of the elements
1309 // input to the shuffle.
1310 unsigned NElts = VT.getVectorNumElements();
1311 SmallVector<int, 8> MaskVec;
1312 for (unsigned i = 0; i != NElts; ++i) {
1313 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1314 MaskVec.push_back(Mask[i]);
1317 // Canonicalize shuffle v, v -> v, undef
1320 for (unsigned i = 0; i != NElts; ++i)
1321 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1324 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1325 if (N1.getOpcode() == ISD::UNDEF)
1326 commuteShuffle(N1, N2, MaskVec);
1328 // Canonicalize all index into lhs, -> shuffle lhs, undef
1329 // Canonicalize all index into rhs, -> shuffle rhs, undef
1330 bool AllLHS = true, AllRHS = true;
1331 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1332 for (unsigned i = 0; i != NElts; ++i) {
1333 if (MaskVec[i] >= (int)NElts) {
1338 } else if (MaskVec[i] >= 0) {
1342 if (AllLHS && AllRHS)
1343 return getUNDEF(VT);
1344 if (AllLHS && !N2Undef)
1348 commuteShuffle(N1, N2, MaskVec);
1351 // If Identity shuffle, or all shuffle in to undef, return that node.
1352 bool AllUndef = true;
1353 bool Identity = true;
1354 for (unsigned i = 0; i != NElts; ++i) {
1355 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1356 if (MaskVec[i] >= 0) AllUndef = false;
1358 if (Identity && NElts == N1.getValueType().getVectorNumElements())
1361 return getUNDEF(VT);
1363 FoldingSetNodeID ID;
1364 SDValue Ops[2] = { N1, N2 };
1365 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1366 for (unsigned i = 0; i != NElts; ++i)
1367 ID.AddInteger(MaskVec[i]);
1370 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1371 return SDValue(E, 0);
1373 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1374 // SDNode doesn't have access to it. This memory will be "leaked" when
1375 // the node is deallocated, but recovered when the NodeAllocator is released.
1376 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1377 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1379 ShuffleVectorSDNode *N =
1380 new (NodeAllocator) ShuffleVectorSDNode(VT, dl.getIROrder(), dl.getDebugLoc(), N1, N2, MaskAlloc);
1381 CSEMap.InsertNode(N, IP);
1382 AllNodes.push_back(N);
1383 return SDValue(N, 0);
1386 SDValue SelectionDAG::getConvertRndSat(EVT VT, SDLoc dl,
1387 SDValue Val, SDValue DTy,
1388 SDValue STy, SDValue Rnd, SDValue Sat,
1389 ISD::CvtCode Code) {
1390 // If the src and dest types are the same and the conversion is between
1391 // integer types of the same sign or two floats, no conversion is necessary.
1393 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1396 FoldingSetNodeID ID;
1397 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1398 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5);
1400 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1401 return SDValue(E, 0);
1403 CvtRndSatSDNode *N = new (NodeAllocator) CvtRndSatSDNode(VT, dl.getIROrder(), dl.getDebugLoc(), Ops, 5,
1405 CSEMap.InsertNode(N, IP);
1406 AllNodes.push_back(N);
1407 return SDValue(N, 0);
1410 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1411 FoldingSetNodeID ID;
1412 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1413 ID.AddInteger(RegNo);
1415 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1416 return SDValue(E, 0);
1418 SDNode *N = new (NodeAllocator) RegisterSDNode(RegNo, VT);
1419 CSEMap.InsertNode(N, IP);
1420 AllNodes.push_back(N);
1421 return SDValue(N, 0);
1424 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1425 FoldingSetNodeID ID;
1426 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), 0, 0);
1427 ID.AddPointer(RegMask);
1429 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1430 return SDValue(E, 0);
1432 SDNode *N = new (NodeAllocator) RegisterMaskSDNode(RegMask);
1433 CSEMap.InsertNode(N, IP);
1434 AllNodes.push_back(N);
1435 return SDValue(N, 0);
1438 SDValue SelectionDAG::getEHLabel(SDLoc dl, SDValue Root, MCSymbol *Label) {
1439 FoldingSetNodeID ID;
1440 SDValue Ops[] = { Root };
1441 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), &Ops[0], 1);
1442 ID.AddPointer(Label);
1444 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1445 return SDValue(E, 0);
1447 SDNode *N = new (NodeAllocator) EHLabelSDNode(dl.getIROrder(), dl.getDebugLoc(), Root, Label);
1448 CSEMap.InsertNode(N, IP);
1449 AllNodes.push_back(N);
1450 return SDValue(N, 0);
1454 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1457 unsigned char TargetFlags) {
1458 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1460 FoldingSetNodeID ID;
1461 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1463 ID.AddInteger(Offset);
1464 ID.AddInteger(TargetFlags);
1466 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1467 return SDValue(E, 0);
1469 SDNode *N = new (NodeAllocator) BlockAddressSDNode(Opc, VT, BA, Offset,
1471 CSEMap.InsertNode(N, IP);
1472 AllNodes.push_back(N);
1473 return SDValue(N, 0);
1476 SDValue SelectionDAG::getSrcValue(const Value *V) {
1477 assert((!V || V->getType()->isPointerTy()) &&
1478 "SrcValue is not a pointer?");
1480 FoldingSetNodeID ID;
1481 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1485 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1486 return SDValue(E, 0);
1488 SDNode *N = new (NodeAllocator) SrcValueSDNode(V);
1489 CSEMap.InsertNode(N, IP);
1490 AllNodes.push_back(N);
1491 return SDValue(N, 0);
1494 /// getMDNode - Return an MDNodeSDNode which holds an MDNode.
1495 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1496 FoldingSetNodeID ID;
1497 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), 0, 0);
1501 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1502 return SDValue(E, 0);
1504 SDNode *N = new (NodeAllocator) MDNodeSDNode(MD);
1505 CSEMap.InsertNode(N, IP);
1506 AllNodes.push_back(N);
1507 return SDValue(N, 0);
1511 /// getShiftAmountOperand - Return the specified value casted to
1512 /// the target's desired shift amount type.
1513 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1514 EVT OpTy = Op.getValueType();
1515 EVT ShTy = TLI.getShiftAmountTy(LHSTy);
1516 if (OpTy == ShTy || OpTy.isVector()) return Op;
1518 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1519 return getNode(Opcode, SDLoc(Op), ShTy, Op);
1522 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1523 /// specified value type.
1524 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1525 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1526 unsigned ByteSize = VT.getStoreSize();
1527 Type *Ty = VT.getTypeForEVT(*getContext());
1528 unsigned StackAlign =
1529 std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty), minAlign);
1531 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1532 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1535 /// CreateStackTemporary - Create a stack temporary suitable for holding
1536 /// either of the specified value types.
1537 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1538 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1539 VT2.getStoreSizeInBits())/8;
1540 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1541 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1542 const DataLayout *TD = TLI.getDataLayout();
1543 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1544 TD->getPrefTypeAlignment(Ty2));
1546 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1547 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1548 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1551 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1552 SDValue N2, ISD::CondCode Cond, SDLoc dl) {
1553 // These setcc operations always fold.
1557 case ISD::SETFALSE2: return getConstant(0, VT);
1559 case ISD::SETTRUE2: return getConstant(1, VT);
1571 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1575 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1576 const APInt &C2 = N2C->getAPIntValue();
1577 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1578 const APInt &C1 = N1C->getAPIntValue();
1581 default: llvm_unreachable("Unknown integer setcc!");
1582 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1583 case ISD::SETNE: return getConstant(C1 != C2, VT);
1584 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1585 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1586 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1587 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1588 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1589 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1590 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1591 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1595 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1596 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1597 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1600 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1601 return getUNDEF(VT);
1603 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1604 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1605 return getUNDEF(VT);
1607 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1608 R==APFloat::cmpLessThan, VT);
1609 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1610 return getUNDEF(VT);
1612 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1613 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1614 return getUNDEF(VT);
1616 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1617 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1618 return getUNDEF(VT);
1620 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1621 R==APFloat::cmpEqual, VT);
1622 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1623 return getUNDEF(VT);
1625 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1626 R==APFloat::cmpEqual, VT);
1627 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1628 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1629 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1630 R==APFloat::cmpEqual, VT);
1631 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1632 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1633 R==APFloat::cmpLessThan, VT);
1634 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1635 R==APFloat::cmpUnordered, VT);
1636 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1637 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1640 // Ensure that the constant occurs on the RHS.
1641 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1645 // Could not fold it.
1649 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1650 /// use this predicate to simplify operations downstream.
1651 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1652 // This predicate is not safe for vector operations.
1653 if (Op.getValueType().isVector())
1656 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1657 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1660 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1661 /// this predicate to simplify operations downstream. Mask is known to be zero
1662 /// for bits that V cannot have.
1663 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1664 unsigned Depth) const {
1665 APInt KnownZero, KnownOne;
1666 ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
1667 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1668 return (KnownZero & Mask) == Mask;
1671 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1672 /// known to be either zero or one and return them in the KnownZero/KnownOne
1673 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1675 void SelectionDAG::ComputeMaskedBits(SDValue Op, APInt &KnownZero,
1676 APInt &KnownOne, unsigned Depth) const {
1677 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1679 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1681 return; // Limit search depth.
1683 APInt KnownZero2, KnownOne2;
1685 switch (Op.getOpcode()) {
1687 // We know all of the bits for a constant!
1688 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
1689 KnownZero = ~KnownOne;
1692 // If either the LHS or the RHS are Zero, the result is zero.
1693 ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1694 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1695 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1696 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1698 // Output known-1 bits are only known if set in both the LHS & RHS.
1699 KnownOne &= KnownOne2;
1700 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1701 KnownZero |= KnownZero2;
1704 ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1705 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1706 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1707 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1709 // Output known-0 bits are only known if clear in both the LHS & RHS.
1710 KnownZero &= KnownZero2;
1711 // Output known-1 are known to be set if set in either the LHS | RHS.
1712 KnownOne |= KnownOne2;
1715 ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1716 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1717 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1718 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1720 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1721 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1722 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1723 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1724 KnownZero = KnownZeroOut;
1728 ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1729 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1730 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1731 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1733 // If low bits are zero in either operand, output low known-0 bits.
1734 // Also compute a conserative estimate for high known-0 bits.
1735 // More trickiness is possible, but this is sufficient for the
1736 // interesting case of alignment computation.
1737 KnownOne.clearAllBits();
1738 unsigned TrailZ = KnownZero.countTrailingOnes() +
1739 KnownZero2.countTrailingOnes();
1740 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1741 KnownZero2.countLeadingOnes(),
1742 BitWidth) - BitWidth;
1744 TrailZ = std::min(TrailZ, BitWidth);
1745 LeadZ = std::min(LeadZ, BitWidth);
1746 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1747 APInt::getHighBitsSet(BitWidth, LeadZ);
1751 // For the purposes of computing leading zeros we can conservatively
1752 // treat a udiv as a logical right shift by the power of 2 known to
1753 // be less than the denominator.
1754 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1755 unsigned LeadZ = KnownZero2.countLeadingOnes();
1757 KnownOne2.clearAllBits();
1758 KnownZero2.clearAllBits();
1759 ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
1760 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1761 if (RHSUnknownLeadingOnes != BitWidth)
1762 LeadZ = std::min(BitWidth,
1763 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1765 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ);
1769 ComputeMaskedBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1);
1770 ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
1771 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1772 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1774 // Only known if known in both the LHS and RHS.
1775 KnownOne &= KnownOne2;
1776 KnownZero &= KnownZero2;
1778 case ISD::SELECT_CC:
1779 ComputeMaskedBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1);
1780 ComputeMaskedBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1);
1781 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1782 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1784 // Only known if known in both the LHS and RHS.
1785 KnownOne &= KnownOne2;
1786 KnownZero &= KnownZero2;
1794 if (Op.getResNo() != 1)
1796 // The boolean result conforms to getBooleanContents. Fall through.
1798 // If we know the result of a setcc has the top bits zero, use this info.
1799 if (TLI.getBooleanContents(Op.getValueType().isVector()) ==
1800 TargetLowering::ZeroOrOneBooleanContent && BitWidth > 1)
1801 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1804 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1805 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1806 unsigned ShAmt = SA->getZExtValue();
1808 // If the shift count is an invalid immediate, don't do anything.
1809 if (ShAmt >= BitWidth)
1812 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1813 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1814 KnownZero <<= ShAmt;
1816 // low bits known zero.
1817 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1821 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1822 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1823 unsigned ShAmt = SA->getZExtValue();
1825 // If the shift count is an invalid immediate, don't do anything.
1826 if (ShAmt >= BitWidth)
1829 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1830 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1831 KnownZero = KnownZero.lshr(ShAmt);
1832 KnownOne = KnownOne.lshr(ShAmt);
1834 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1835 KnownZero |= HighBits; // High bits known zero.
1839 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1840 unsigned ShAmt = SA->getZExtValue();
1842 // If the shift count is an invalid immediate, don't do anything.
1843 if (ShAmt >= BitWidth)
1846 // If any of the demanded bits are produced by the sign extension, we also
1847 // demand the input sign bit.
1848 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
1850 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1851 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1852 KnownZero = KnownZero.lshr(ShAmt);
1853 KnownOne = KnownOne.lshr(ShAmt);
1855 // Handle the sign bits.
1856 APInt SignBit = APInt::getSignBit(BitWidth);
1857 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1859 if (KnownZero.intersects(SignBit)) {
1860 KnownZero |= HighBits; // New bits are known zero.
1861 } else if (KnownOne.intersects(SignBit)) {
1862 KnownOne |= HighBits; // New bits are known one.
1866 case ISD::SIGN_EXTEND_INREG: {
1867 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1868 unsigned EBits = EVT.getScalarType().getSizeInBits();
1870 // Sign extension. Compute the demanded bits in the result that are not
1871 // present in the input.
1872 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
1874 APInt InSignBit = APInt::getSignBit(EBits);
1875 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
1877 // If the sign extended bits are demanded, we know that the sign
1879 InSignBit = InSignBit.zext(BitWidth);
1880 if (NewBits.getBoolValue())
1881 InputDemandedBits |= InSignBit;
1883 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1884 KnownOne &= InputDemandedBits;
1885 KnownZero &= InputDemandedBits;
1886 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1888 // If the sign bit of the input is known set or clear, then we know the
1889 // top bits of the result.
1890 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1891 KnownZero |= NewBits;
1892 KnownOne &= ~NewBits;
1893 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1894 KnownOne |= NewBits;
1895 KnownZero &= ~NewBits;
1896 } else { // Input sign bit unknown
1897 KnownZero &= ~NewBits;
1898 KnownOne &= ~NewBits;
1903 case ISD::CTTZ_ZERO_UNDEF:
1905 case ISD::CTLZ_ZERO_UNDEF:
1907 unsigned LowBits = Log2_32(BitWidth)+1;
1908 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1909 KnownOne.clearAllBits();
1913 LoadSDNode *LD = cast<LoadSDNode>(Op);
1914 // If this is a ZEXTLoad and we are looking at the loaded value.
1915 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1916 EVT VT = LD->getMemoryVT();
1917 unsigned MemBits = VT.getScalarType().getSizeInBits();
1918 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1919 } else if (const MDNode *Ranges = LD->getRanges()) {
1920 computeMaskedBitsLoad(*Ranges, KnownZero);
1924 case ISD::ZERO_EXTEND: {
1925 EVT InVT = Op.getOperand(0).getValueType();
1926 unsigned InBits = InVT.getScalarType().getSizeInBits();
1927 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
1928 KnownZero = KnownZero.trunc(InBits);
1929 KnownOne = KnownOne.trunc(InBits);
1930 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1931 KnownZero = KnownZero.zext(BitWidth);
1932 KnownOne = KnownOne.zext(BitWidth);
1933 KnownZero |= NewBits;
1936 case ISD::SIGN_EXTEND: {
1937 EVT InVT = Op.getOperand(0).getValueType();
1938 unsigned InBits = InVT.getScalarType().getSizeInBits();
1939 APInt InSignBit = APInt::getSignBit(InBits);
1940 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits);
1942 KnownZero = KnownZero.trunc(InBits);
1943 KnownOne = KnownOne.trunc(InBits);
1944 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1946 // Note if the sign bit is known to be zero or one.
1947 bool SignBitKnownZero = KnownZero.isNegative();
1948 bool SignBitKnownOne = KnownOne.isNegative();
1949 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1950 "Sign bit can't be known to be both zero and one!");
1952 KnownZero = KnownZero.zext(BitWidth);
1953 KnownOne = KnownOne.zext(BitWidth);
1955 // If the sign bit is known zero or one, the top bits match.
1956 if (SignBitKnownZero)
1957 KnownZero |= NewBits;
1958 else if (SignBitKnownOne)
1959 KnownOne |= NewBits;
1962 case ISD::ANY_EXTEND: {
1963 EVT InVT = Op.getOperand(0).getValueType();
1964 unsigned InBits = InVT.getScalarType().getSizeInBits();
1965 KnownZero = KnownZero.trunc(InBits);
1966 KnownOne = KnownOne.trunc(InBits);
1967 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1968 KnownZero = KnownZero.zext(BitWidth);
1969 KnownOne = KnownOne.zext(BitWidth);
1972 case ISD::TRUNCATE: {
1973 EVT InVT = Op.getOperand(0).getValueType();
1974 unsigned InBits = InVT.getScalarType().getSizeInBits();
1975 KnownZero = KnownZero.zext(InBits);
1976 KnownOne = KnownOne.zext(InBits);
1977 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1978 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1979 KnownZero = KnownZero.trunc(BitWidth);
1980 KnownOne = KnownOne.trunc(BitWidth);
1983 case ISD::AssertZext: {
1984 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1985 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1986 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
1987 KnownZero |= (~InMask);
1988 KnownOne &= (~KnownZero);
1992 // All bits are zero except the low bit.
1993 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1997 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1998 // We know that the top bits of C-X are clear if X contains less bits
1999 // than C (i.e. no wrap-around can happen). For example, 20-X is
2000 // positive if we can prove that X is >= 0 and < 16.
2001 if (CLHS->getAPIntValue().isNonNegative()) {
2002 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2003 // NLZ can't be BitWidth with no sign bit
2004 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2005 ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2007 // If all of the MaskV bits are known to be zero, then we know the
2008 // output top bits are zero, because we now know that the output is
2010 if ((KnownZero2 & MaskV) == MaskV) {
2011 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2012 // Top bits known zero.
2013 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2);
2021 // Output known-0 bits are known if clear or set in both the low clear bits
2022 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2023 // low 3 bits clear.
2024 ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
2025 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
2026 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
2028 ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2029 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
2030 KnownZeroOut = std::min(KnownZeroOut,
2031 KnownZero2.countTrailingOnes());
2033 if (Op.getOpcode() == ISD::ADD) {
2034 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
2038 // With ADDE, a carry bit may be added in, so we can only use this
2039 // information if we know (at least) that the low two bits are clear. We
2040 // then return to the caller that the low bit is unknown but that other bits
2042 if (KnownZeroOut >= 2) // ADDE
2043 KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroOut);
2047 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2048 const APInt &RA = Rem->getAPIntValue().abs();
2049 if (RA.isPowerOf2()) {
2050 APInt LowBits = RA - 1;
2051 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
2052 ComputeMaskedBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1);
2054 // The low bits of the first operand are unchanged by the srem.
2055 KnownZero = KnownZero2 & LowBits;
2056 KnownOne = KnownOne2 & LowBits;
2058 // If the first operand is non-negative or has all low bits zero, then
2059 // the upper bits are all zero.
2060 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2061 KnownZero |= ~LowBits;
2063 // If the first operand is negative and not all low bits are zero, then
2064 // the upper bits are all one.
2065 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2066 KnownOne |= ~LowBits;
2067 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2072 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2073 const APInt &RA = Rem->getAPIntValue();
2074 if (RA.isPowerOf2()) {
2075 APInt LowBits = (RA - 1);
2076 KnownZero |= ~LowBits;
2077 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne,Depth+1);
2078 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2083 // Since the result is less than or equal to either operand, any leading
2084 // zero bits in either operand must also exist in the result.
2085 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2086 ComputeMaskedBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1);
2088 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2089 KnownZero2.countLeadingOnes());
2090 KnownOne.clearAllBits();
2091 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders);
2094 case ISD::FrameIndex:
2095 case ISD::TargetFrameIndex:
2096 if (unsigned Align = InferPtrAlignment(Op)) {
2097 // The low bits are known zero if the pointer is aligned.
2098 KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align));
2104 if (Op.getOpcode() < ISD::BUILTIN_OP_END)
2107 case ISD::INTRINSIC_WO_CHAIN:
2108 case ISD::INTRINSIC_W_CHAIN:
2109 case ISD::INTRINSIC_VOID:
2110 // Allow the target to implement this method for its nodes.
2111 TLI.computeMaskedBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth);
2116 /// ComputeNumSignBits - Return the number of times the sign bit of the
2117 /// register is replicated into the other bits. We know that at least 1 bit
2118 /// is always equal to the sign bit (itself), but other cases can give us
2119 /// information. For example, immediately after an "SRA X, 2", we know that
2120 /// the top 3 bits are all equal to each other, so we return 3.
2121 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
2122 EVT VT = Op.getValueType();
2123 assert(VT.isInteger() && "Invalid VT!");
2124 unsigned VTBits = VT.getScalarType().getSizeInBits();
2126 unsigned FirstAnswer = 1;
2129 return 1; // Limit search depth.
2131 switch (Op.getOpcode()) {
2133 case ISD::AssertSext:
2134 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2135 return VTBits-Tmp+1;
2136 case ISD::AssertZext:
2137 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2140 case ISD::Constant: {
2141 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2142 return Val.getNumSignBits();
2145 case ISD::SIGN_EXTEND:
2146 Tmp = VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2147 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2149 case ISD::SIGN_EXTEND_INREG:
2150 // Max of the input and what this extends.
2152 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
2155 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2156 return std::max(Tmp, Tmp2);
2159 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2160 // SRA X, C -> adds C sign bits.
2161 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2162 Tmp += C->getZExtValue();
2163 if (Tmp > VTBits) Tmp = VTBits;
2167 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2168 // shl destroys sign bits.
2169 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2170 if (C->getZExtValue() >= VTBits || // Bad shift.
2171 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2172 return Tmp - C->getZExtValue();
2177 case ISD::XOR: // NOT is handled here.
2178 // Logical binary ops preserve the number of sign bits at the worst.
2179 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2181 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2182 FirstAnswer = std::min(Tmp, Tmp2);
2183 // We computed what we know about the sign bits as our first
2184 // answer. Now proceed to the generic code that uses
2185 // ComputeMaskedBits, and pick whichever answer is better.
2190 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2191 if (Tmp == 1) return 1; // Early out.
2192 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2193 return std::min(Tmp, Tmp2);
2201 if (Op.getResNo() != 1)
2203 // The boolean result conforms to getBooleanContents. Fall through.
2205 // If setcc returns 0/-1, all bits are sign bits.
2206 if (TLI.getBooleanContents(Op.getValueType().isVector()) ==
2207 TargetLowering::ZeroOrNegativeOneBooleanContent)
2212 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2213 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2215 // Handle rotate right by N like a rotate left by 32-N.
2216 if (Op.getOpcode() == ISD::ROTR)
2217 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2219 // If we aren't rotating out all of the known-in sign bits, return the
2220 // number that are left. This handles rotl(sext(x), 1) for example.
2221 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2222 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2226 // Add can have at most one carry bit. Thus we know that the output
2227 // is, at worst, one more bit than the inputs.
2228 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2229 if (Tmp == 1) return 1; // Early out.
2231 // Special case decrementing a value (ADD X, -1):
2232 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2233 if (CRHS->isAllOnesValue()) {
2234 APInt KnownZero, KnownOne;
2235 ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
2237 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2239 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2242 // If we are subtracting one from a positive number, there is no carry
2243 // out of the result.
2244 if (KnownZero.isNegative())
2248 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2249 if (Tmp2 == 1) return 1;
2250 return std::min(Tmp, Tmp2)-1;
2253 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2254 if (Tmp2 == 1) return 1;
2257 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2258 if (CLHS->isNullValue()) {
2259 APInt KnownZero, KnownOne;
2260 ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
2261 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2263 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue())
2266 // If the input is known to be positive (the sign bit is known clear),
2267 // the output of the NEG has the same number of sign bits as the input.
2268 if (KnownZero.isNegative())
2271 // Otherwise, we treat this like a SUB.
2274 // Sub can have at most one carry bit. Thus we know that the output
2275 // is, at worst, one more bit than the inputs.
2276 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2277 if (Tmp == 1) return 1; // Early out.
2278 return std::min(Tmp, Tmp2)-1;
2280 // FIXME: it's tricky to do anything useful for this, but it is an important
2281 // case for targets like X86.
2285 // If we are looking at the loaded value of the SDNode.
2286 if (Op.getResNo() == 0) {
2287 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2288 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
2289 unsigned ExtType = LD->getExtensionType();
2292 case ISD::SEXTLOAD: // '17' bits known
2293 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2294 return VTBits-Tmp+1;
2295 case ISD::ZEXTLOAD: // '16' bits known
2296 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2302 // Allow the target to implement this method for its nodes.
2303 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2304 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2305 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2306 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2307 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2308 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2311 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2312 // use this information.
2313 APInt KnownZero, KnownOne;
2314 ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
2317 if (KnownZero.isNegative()) { // sign bit is 0
2319 } else if (KnownOne.isNegative()) { // sign bit is 1;
2326 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2327 // the number of identical bits in the top of the input value.
2329 Mask <<= Mask.getBitWidth()-VTBits;
2330 // Return # leading zeros. We use 'min' here in case Val was zero before
2331 // shifting. We don't want to return '64' as for an i32 "0".
2332 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2335 /// isBaseWithConstantOffset - Return true if the specified operand is an
2336 /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an
2337 /// ISD::OR with a ConstantSDNode that is guaranteed to have the same
2338 /// semantics as an ADD. This handles the equivalence:
2339 /// X|Cst == X+Cst iff X&Cst = 0.
2340 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
2341 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
2342 !isa<ConstantSDNode>(Op.getOperand(1)))
2345 if (Op.getOpcode() == ISD::OR &&
2346 !MaskedValueIsZero(Op.getOperand(0),
2347 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
2354 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2355 // If we're told that NaNs won't happen, assume they won't.
2356 if (getTarget().Options.NoNaNsFPMath)
2359 // If the value is a constant, we can obviously see if it is a NaN or not.
2360 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2361 return !C->getValueAPF().isNaN();
2363 // TODO: Recognize more cases here.
2368 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2369 // If the value is a constant, we can obviously see if it is a zero or not.
2370 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2371 return !C->isZero();
2373 // TODO: Recognize more cases here.
2374 switch (Op.getOpcode()) {
2377 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2378 return !C->isNullValue();
2385 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2386 // Check the obvious case.
2387 if (A == B) return true;
2389 // For for negative and positive zero.
2390 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2391 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2392 if (CA->isZero() && CB->isZero()) return true;
2394 // Otherwise they may not be equal.
2398 /// getNode - Gets or creates the specified node.
2400 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT) {
2401 FoldingSetNodeID ID;
2402 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2404 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2405 return SDValue(E, 0);
2407 SDNode *N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), getVTList(VT));
2408 CSEMap.InsertNode(N, IP);
2410 AllNodes.push_back(N);
2414 return SDValue(N, 0);
2417 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
2418 EVT VT, SDValue Operand) {
2419 // Constant fold unary operations with an integer constant operand.
2420 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2421 const APInt &Val = C->getAPIntValue();
2424 case ISD::SIGN_EXTEND:
2425 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), VT);
2426 case ISD::ANY_EXTEND:
2427 case ISD::ZERO_EXTEND:
2429 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), VT);
2430 case ISD::UINT_TO_FP:
2431 case ISD::SINT_TO_FP: {
2432 APFloat apf(EVTToAPFloatSemantics(VT),
2433 APInt::getNullValue(VT.getSizeInBits()));
2434 (void)apf.convertFromAPInt(Val,
2435 Opcode==ISD::SINT_TO_FP,
2436 APFloat::rmNearestTiesToEven);
2437 return getConstantFP(apf, VT);
2440 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2441 return getConstantFP(APFloat(APFloat::IEEEsingle, Val), VT);
2442 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2443 return getConstantFP(APFloat(APFloat::IEEEdouble, Val), VT);
2446 return getConstant(Val.byteSwap(), VT);
2448 return getConstant(Val.countPopulation(), VT);
2450 case ISD::CTLZ_ZERO_UNDEF:
2451 return getConstant(Val.countLeadingZeros(), VT);
2453 case ISD::CTTZ_ZERO_UNDEF:
2454 return getConstant(Val.countTrailingZeros(), VT);
2458 // Constant fold unary operations with a floating point constant operand.
2459 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2460 APFloat V = C->getValueAPF(); // make copy
2464 return getConstantFP(V, VT);
2467 return getConstantFP(V, VT);
2469 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
2470 if (fs == APFloat::opOK || fs == APFloat::opInexact)
2471 return getConstantFP(V, VT);
2475 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
2476 if (fs == APFloat::opOK || fs == APFloat::opInexact)
2477 return getConstantFP(V, VT);
2481 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
2482 if (fs == APFloat::opOK || fs == APFloat::opInexact)
2483 return getConstantFP(V, VT);
2486 case ISD::FP_EXTEND: {
2488 // This can return overflow, underflow, or inexact; we don't care.
2489 // FIXME need to be more flexible about rounding mode.
2490 (void)V.convert(EVTToAPFloatSemantics(VT),
2491 APFloat::rmNearestTiesToEven, &ignored);
2492 return getConstantFP(V, VT);
2494 case ISD::FP_TO_SINT:
2495 case ISD::FP_TO_UINT: {
2498 assert(integerPartWidth >= 64);
2499 // FIXME need to be more flexible about rounding mode.
2500 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2501 Opcode==ISD::FP_TO_SINT,
2502 APFloat::rmTowardZero, &ignored);
2503 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2505 APInt api(VT.getSizeInBits(), x);
2506 return getConstant(api, VT);
2509 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2510 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2511 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2512 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2517 unsigned OpOpcode = Operand.getNode()->getOpcode();
2519 case ISD::TokenFactor:
2520 case ISD::MERGE_VALUES:
2521 case ISD::CONCAT_VECTORS:
2522 return Operand; // Factor, merge or concat of one node? No need.
2523 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2524 case ISD::FP_EXTEND:
2525 assert(VT.isFloatingPoint() &&
2526 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2527 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2528 assert((!VT.isVector() ||
2529 VT.getVectorNumElements() ==
2530 Operand.getValueType().getVectorNumElements()) &&
2531 "Vector element count mismatch!");
2532 if (Operand.getOpcode() == ISD::UNDEF)
2533 return getUNDEF(VT);
2535 case ISD::SIGN_EXTEND:
2536 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2537 "Invalid SIGN_EXTEND!");
2538 if (Operand.getValueType() == VT) return Operand; // noop extension
2539 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2540 "Invalid sext node, dst < src!");
2541 assert((!VT.isVector() ||
2542 VT.getVectorNumElements() ==
2543 Operand.getValueType().getVectorNumElements()) &&
2544 "Vector element count mismatch!");
2545 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2546 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2547 else if (OpOpcode == ISD::UNDEF)
2548 // sext(undef) = 0, because the top bits will all be the same.
2549 return getConstant(0, VT);
2551 case ISD::ZERO_EXTEND:
2552 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2553 "Invalid ZERO_EXTEND!");
2554 if (Operand.getValueType() == VT) return Operand; // noop extension
2555 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2556 "Invalid zext node, dst < src!");
2557 assert((!VT.isVector() ||
2558 VT.getVectorNumElements() ==
2559 Operand.getValueType().getVectorNumElements()) &&
2560 "Vector element count mismatch!");
2561 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2562 return getNode(ISD::ZERO_EXTEND, DL, VT,
2563 Operand.getNode()->getOperand(0));
2564 else if (OpOpcode == ISD::UNDEF)
2565 // zext(undef) = 0, because the top bits will be zero.
2566 return getConstant(0, VT);
2568 case ISD::ANY_EXTEND:
2569 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2570 "Invalid ANY_EXTEND!");
2571 if (Operand.getValueType() == VT) return Operand; // noop extension
2572 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2573 "Invalid anyext node, dst < src!");
2574 assert((!VT.isVector() ||
2575 VT.getVectorNumElements() ==
2576 Operand.getValueType().getVectorNumElements()) &&
2577 "Vector element count mismatch!");
2579 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2580 OpOpcode == ISD::ANY_EXTEND)
2581 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2582 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2583 else if (OpOpcode == ISD::UNDEF)
2584 return getUNDEF(VT);
2586 // (ext (trunx x)) -> x
2587 if (OpOpcode == ISD::TRUNCATE) {
2588 SDValue OpOp = Operand.getNode()->getOperand(0);
2589 if (OpOp.getValueType() == VT)
2594 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2595 "Invalid TRUNCATE!");
2596 if (Operand.getValueType() == VT) return Operand; // noop truncate
2597 assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2598 "Invalid truncate node, src < dst!");
2599 assert((!VT.isVector() ||
2600 VT.getVectorNumElements() ==
2601 Operand.getValueType().getVectorNumElements()) &&
2602 "Vector element count mismatch!");
2603 if (OpOpcode == ISD::TRUNCATE)
2604 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2605 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2606 OpOpcode == ISD::ANY_EXTEND) {
2607 // If the source is smaller than the dest, we still need an extend.
2608 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2609 .bitsLT(VT.getScalarType()))
2610 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2611 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2612 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2613 return Operand.getNode()->getOperand(0);
2615 if (OpOpcode == ISD::UNDEF)
2616 return getUNDEF(VT);
2619 // Basic sanity checking.
2620 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2621 && "Cannot BITCAST between types of different sizes!");
2622 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2623 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
2624 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
2625 if (OpOpcode == ISD::UNDEF)
2626 return getUNDEF(VT);
2628 case ISD::SCALAR_TO_VECTOR:
2629 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2630 (VT.getVectorElementType() == Operand.getValueType() ||
2631 (VT.getVectorElementType().isInteger() &&
2632 Operand.getValueType().isInteger() &&
2633 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2634 "Illegal SCALAR_TO_VECTOR node!");
2635 if (OpOpcode == ISD::UNDEF)
2636 return getUNDEF(VT);
2637 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2638 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2639 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2640 Operand.getConstantOperandVal(1) == 0 &&
2641 Operand.getOperand(0).getValueType() == VT)
2642 return Operand.getOperand(0);
2645 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2646 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
2647 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2648 Operand.getNode()->getOperand(0));
2649 if (OpOpcode == ISD::FNEG) // --X -> X
2650 return Operand.getNode()->getOperand(0);
2653 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2654 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2659 SDVTList VTs = getVTList(VT);
2660 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
2661 FoldingSetNodeID ID;
2662 SDValue Ops[1] = { Operand };
2663 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2665 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2666 return SDValue(E, 0);
2668 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, Operand);
2669 CSEMap.InsertNode(N, IP);
2671 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, Operand);
2674 AllNodes.push_back(N);
2678 return SDValue(N, 0);
2681 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, EVT VT,
2682 SDNode *Cst1, SDNode *Cst2) {
2683 SmallVector<std::pair<ConstantSDNode *, ConstantSDNode *>, 4> Inputs;
2684 SmallVector<SDValue, 4> Outputs;
2685 EVT SVT = VT.getScalarType();
2687 ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1);
2688 ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2);
2689 if (Scalar1 && Scalar2) {
2690 // Scalar instruction.
2691 Inputs.push_back(std::make_pair(Scalar1, Scalar2));
2693 // For vectors extract each constant element into Inputs so we can constant
2694 // fold them individually.
2695 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
2696 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
2700 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!");
2702 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) {
2703 ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I));
2704 ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I));
2705 if (!V1 || !V2) // Not a constant, bail.
2708 // Avoid BUILD_VECTOR nodes that perform implicit truncation.
2709 // FIXME: This is valid and could be handled by truncating the APInts.
2710 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
2713 Inputs.push_back(std::make_pair(V1, V2));
2717 // We have a number of constant values, constant fold them element by element.
2718 for (unsigned I = 0, E = Inputs.size(); I != E; ++I) {
2719 const APInt &C1 = Inputs[I].first->getAPIntValue();
2720 const APInt &C2 = Inputs[I].second->getAPIntValue();
2724 Outputs.push_back(getConstant(C1 + C2, SVT));
2727 Outputs.push_back(getConstant(C1 - C2, SVT));
2730 Outputs.push_back(getConstant(C1 * C2, SVT));
2733 if (!C2.getBoolValue())
2735 Outputs.push_back(getConstant(C1.udiv(C2), SVT));
2738 if (!C2.getBoolValue())
2740 Outputs.push_back(getConstant(C1.urem(C2), SVT));
2743 if (!C2.getBoolValue())
2745 Outputs.push_back(getConstant(C1.sdiv(C2), SVT));
2748 if (!C2.getBoolValue())
2750 Outputs.push_back(getConstant(C1.srem(C2), SVT));
2753 Outputs.push_back(getConstant(C1 & C2, SVT));
2756 Outputs.push_back(getConstant(C1 | C2, SVT));
2759 Outputs.push_back(getConstant(C1 ^ C2, SVT));
2762 Outputs.push_back(getConstant(C1 << C2, SVT));
2765 Outputs.push_back(getConstant(C1.lshr(C2), SVT));
2768 Outputs.push_back(getConstant(C1.ashr(C2), SVT));
2771 Outputs.push_back(getConstant(C1.rotl(C2), SVT));
2774 Outputs.push_back(getConstant(C1.rotr(C2), SVT));
2781 // Handle the scalar case first.
2782 if (Scalar1 && Scalar2)
2783 return Outputs.back();
2785 // Otherwise build a big vector out of the scalar elements we generated.
2786 return getNode(ISD::BUILD_VECTOR, SDLoc(), VT, Outputs.data(),
2790 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT, SDValue N1,
2792 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2793 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2796 case ISD::TokenFactor:
2797 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2798 N2.getValueType() == MVT::Other && "Invalid token factor!");
2799 // Fold trivial token factors.
2800 if (N1.getOpcode() == ISD::EntryToken) return N2;
2801 if (N2.getOpcode() == ISD::EntryToken) return N1;
2802 if (N1 == N2) return N1;
2804 case ISD::CONCAT_VECTORS:
2805 // Concat of UNDEFs is UNDEF.
2806 if (N1.getOpcode() == ISD::UNDEF &&
2807 N2.getOpcode() == ISD::UNDEF)
2808 return getUNDEF(VT);
2810 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2811 // one big BUILD_VECTOR.
2812 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2813 N2.getOpcode() == ISD::BUILD_VECTOR) {
2814 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
2815 N1.getNode()->op_end());
2816 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
2817 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2821 assert(VT.isInteger() && "This operator does not apply to FP types!");
2822 assert(N1.getValueType() == N2.getValueType() &&
2823 N1.getValueType() == VT && "Binary operator types must match!");
2824 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2825 // worth handling here.
2826 if (N2C && N2C->isNullValue())
2828 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2835 assert(VT.isInteger() && "This operator does not apply to FP types!");
2836 assert(N1.getValueType() == N2.getValueType() &&
2837 N1.getValueType() == VT && "Binary operator types must match!");
2838 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2839 // it's worth handling here.
2840 if (N2C && N2C->isNullValue())
2850 assert(VT.isInteger() && "This operator does not apply to FP types!");
2851 assert(N1.getValueType() == N2.getValueType() &&
2852 N1.getValueType() == VT && "Binary operator types must match!");
2859 if (getTarget().Options.UnsafeFPMath) {
2860 if (Opcode == ISD::FADD) {
2862 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2863 if (CFP->getValueAPF().isZero())
2866 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2867 if (CFP->getValueAPF().isZero())
2869 } else if (Opcode == ISD::FSUB) {
2871 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2872 if (CFP->getValueAPF().isZero())
2874 } else if (Opcode == ISD::FMUL) {
2875 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1);
2878 // If the first operand isn't the constant, try the second
2880 CFP = dyn_cast<ConstantFPSDNode>(N2);
2887 return SDValue(CFP,0);
2889 if (CFP->isExactlyValue(1.0))
2894 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
2895 assert(N1.getValueType() == N2.getValueType() &&
2896 N1.getValueType() == VT && "Binary operator types must match!");
2898 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2899 assert(N1.getValueType() == VT &&
2900 N1.getValueType().isFloatingPoint() &&
2901 N2.getValueType().isFloatingPoint() &&
2902 "Invalid FCOPYSIGN!");
2909 assert(VT == N1.getValueType() &&
2910 "Shift operators return type must be the same as their first arg");
2911 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2912 "Shifts only work on integers");
2913 assert((!VT.isVector() || VT == N2.getValueType()) &&
2914 "Vector shift amounts must be in the same as their first arg");
2915 // Verify that the shift amount VT is bit enough to hold valid shift
2916 // amounts. This catches things like trying to shift an i1024 value by an
2917 // i8, which is easy to fall into in generic code that uses
2918 // TLI.getShiftAmount().
2919 assert(N2.getValueType().getSizeInBits() >=
2920 Log2_32_Ceil(N1.getValueType().getSizeInBits()) &&
2921 "Invalid use of small shift amount with oversized value!");
2923 // Always fold shifts of i1 values so the code generator doesn't need to
2924 // handle them. Since we know the size of the shift has to be less than the
2925 // size of the value, the shift/rotate count is guaranteed to be zero.
2928 if (N2C && N2C->isNullValue())
2931 case ISD::FP_ROUND_INREG: {
2932 EVT EVT = cast<VTSDNode>(N2)->getVT();
2933 assert(VT == N1.getValueType() && "Not an inreg round!");
2934 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2935 "Cannot FP_ROUND_INREG integer types");
2936 assert(EVT.isVector() == VT.isVector() &&
2937 "FP_ROUND_INREG type should be vector iff the operand "
2939 assert((!EVT.isVector() ||
2940 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2941 "Vector element counts must match in FP_ROUND_INREG");
2942 assert(EVT.bitsLE(VT) && "Not rounding down!");
2944 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2948 assert(VT.isFloatingPoint() &&
2949 N1.getValueType().isFloatingPoint() &&
2950 VT.bitsLE(N1.getValueType()) &&
2951 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2952 if (N1.getValueType() == VT) return N1; // noop conversion.
2954 case ISD::AssertSext:
2955 case ISD::AssertZext: {
2956 EVT EVT = cast<VTSDNode>(N2)->getVT();
2957 assert(VT == N1.getValueType() && "Not an inreg extend!");
2958 assert(VT.isInteger() && EVT.isInteger() &&
2959 "Cannot *_EXTEND_INREG FP types");
2960 assert(!EVT.isVector() &&
2961 "AssertSExt/AssertZExt type should be the vector element type "
2962 "rather than the vector type!");
2963 assert(EVT.bitsLE(VT) && "Not extending!");
2964 if (VT == EVT) return N1; // noop assertion.
2967 case ISD::SIGN_EXTEND_INREG: {
2968 EVT EVT = cast<VTSDNode>(N2)->getVT();
2969 assert(VT == N1.getValueType() && "Not an inreg extend!");
2970 assert(VT.isInteger() && EVT.isInteger() &&
2971 "Cannot *_EXTEND_INREG FP types");
2972 assert(EVT.isVector() == VT.isVector() &&
2973 "SIGN_EXTEND_INREG type should be vector iff the operand "
2975 assert((!EVT.isVector() ||
2976 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2977 "Vector element counts must match in SIGN_EXTEND_INREG");
2978 assert(EVT.bitsLE(VT) && "Not extending!");
2979 if (EVT == VT) return N1; // Not actually extending
2982 APInt Val = N1C->getAPIntValue();
2983 unsigned FromBits = EVT.getScalarType().getSizeInBits();
2984 Val <<= Val.getBitWidth()-FromBits;
2985 Val = Val.ashr(Val.getBitWidth()-FromBits);
2986 return getConstant(Val, VT);
2990 case ISD::EXTRACT_VECTOR_ELT:
2991 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2992 if (N1.getOpcode() == ISD::UNDEF)
2993 return getUNDEF(VT);
2995 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2996 // expanding copies of large vectors from registers.
2998 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2999 N1.getNumOperands() > 0) {
3001 N1.getOperand(0).getValueType().getVectorNumElements();
3002 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
3003 N1.getOperand(N2C->getZExtValue() / Factor),
3004 getConstant(N2C->getZExtValue() % Factor,
3005 N2.getValueType()));
3008 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
3009 // expanding large vector constants.
3010 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
3011 SDValue Elt = N1.getOperand(N2C->getZExtValue());
3013 if (VT != Elt.getValueType())
3014 // If the vector element type is not legal, the BUILD_VECTOR operands
3015 // are promoted and implicitly truncated, and the result implicitly
3016 // extended. Make that explicit here.
3017 Elt = getAnyExtOrTrunc(Elt, DL, VT);
3022 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
3023 // operations are lowered to scalars.
3024 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
3025 // If the indices are the same, return the inserted element else
3026 // if the indices are known different, extract the element from
3027 // the original vector.
3028 SDValue N1Op2 = N1.getOperand(2);
3029 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2.getNode());
3031 if (N1Op2C && N2C) {
3032 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
3033 if (VT == N1.getOperand(1).getValueType())
3034 return N1.getOperand(1);
3036 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
3039 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
3043 case ISD::EXTRACT_ELEMENT:
3044 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
3045 assert(!N1.getValueType().isVector() && !VT.isVector() &&
3046 (N1.getValueType().isInteger() == VT.isInteger()) &&
3047 N1.getValueType() != VT &&
3048 "Wrong types for EXTRACT_ELEMENT!");
3050 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
3051 // 64-bit integers into 32-bit parts. Instead of building the extract of
3052 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
3053 if (N1.getOpcode() == ISD::BUILD_PAIR)
3054 return N1.getOperand(N2C->getZExtValue());
3056 // EXTRACT_ELEMENT of a constant int is also very common.
3057 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3058 unsigned ElementSize = VT.getSizeInBits();
3059 unsigned Shift = ElementSize * N2C->getZExtValue();
3060 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
3061 return getConstant(ShiftedVal.trunc(ElementSize), VT);
3064 case ISD::EXTRACT_SUBVECTOR: {
3066 if (VT.isSimple() && N1.getValueType().isSimple()) {
3067 assert(VT.isVector() && N1.getValueType().isVector() &&
3068 "Extract subvector VTs must be a vectors!");
3069 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType() &&
3070 "Extract subvector VTs must have the same element type!");
3071 assert(VT.getSimpleVT() <= N1.getValueType().getSimpleVT() &&
3072 "Extract subvector must be from larger vector to smaller vector!");
3074 if (isa<ConstantSDNode>(Index.getNode())) {
3075 assert((VT.getVectorNumElements() +
3076 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3077 <= N1.getValueType().getVectorNumElements())
3078 && "Extract subvector overflow!");
3081 // Trivial extraction.
3082 if (VT.getSimpleVT() == N1.getValueType().getSimpleVT())
3089 // Perform trivial constant folding.
3090 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1.getNode(), N2.getNode());
3091 if (SV.getNode()) return SV;
3093 // Canonicalize constant to RHS if commutative.
3094 if (N1C && !N2C && isCommutativeBinOp(Opcode)) {
3095 std::swap(N1C, N2C);
3099 // Constant fold FP operations.
3100 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
3101 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
3103 if (!N2CFP && isCommutativeBinOp(Opcode)) {
3104 // Canonicalize constant to RHS if commutative.
3105 std::swap(N1CFP, N2CFP);
3108 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
3109 APFloat::opStatus s;
3112 s = V1.add(V2, APFloat::rmNearestTiesToEven);
3113 if (s != APFloat::opInvalidOp)
3114 return getConstantFP(V1, VT);
3117 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
3118 if (s!=APFloat::opInvalidOp)
3119 return getConstantFP(V1, VT);
3122 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
3123 if (s!=APFloat::opInvalidOp)
3124 return getConstantFP(V1, VT);
3127 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
3128 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
3129 return getConstantFP(V1, VT);
3132 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
3133 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
3134 return getConstantFP(V1, VT);
3136 case ISD::FCOPYSIGN:
3138 return getConstantFP(V1, VT);
3143 if (Opcode == ISD::FP_ROUND) {
3144 APFloat V = N1CFP->getValueAPF(); // make copy
3146 // This can return overflow, underflow, or inexact; we don't care.
3147 // FIXME need to be more flexible about rounding mode.
3148 (void)V.convert(EVTToAPFloatSemantics(VT),
3149 APFloat::rmNearestTiesToEven, &ignored);
3150 return getConstantFP(V, VT);
3154 // Canonicalize an UNDEF to the RHS, even over a constant.
3155 if (N1.getOpcode() == ISD::UNDEF) {
3156 if (isCommutativeBinOp(Opcode)) {
3160 case ISD::FP_ROUND_INREG:
3161 case ISD::SIGN_EXTEND_INREG:
3167 return N1; // fold op(undef, arg2) -> undef
3175 return getConstant(0, VT); // fold op(undef, arg2) -> 0
3176 // For vectors, we can't easily build an all zero vector, just return
3183 // Fold a bunch of operators when the RHS is undef.
3184 if (N2.getOpcode() == ISD::UNDEF) {
3187 if (N1.getOpcode() == ISD::UNDEF)
3188 // Handle undef ^ undef -> 0 special case. This is a common
3190 return getConstant(0, VT);
3200 return N2; // fold op(arg1, undef) -> undef
3206 if (getTarget().Options.UnsafeFPMath)
3214 return getConstant(0, VT); // fold op(arg1, undef) -> 0
3215 // For vectors, we can't easily build an all zero vector, just return
3220 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3221 // For vectors, we can't easily build an all one vector, just return
3229 // Memoize this node if possible.
3231 SDVTList VTs = getVTList(VT);
3232 if (VT != MVT::Glue) {
3233 SDValue Ops[] = { N1, N2 };
3234 FoldingSetNodeID ID;
3235 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
3237 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3238 return SDValue(E, 0);
3240 N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2);
3241 CSEMap.InsertNode(N, IP);
3243 N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2);
3246 AllNodes.push_back(N);
3250 return SDValue(N, 0);
3253 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3254 SDValue N1, SDValue N2, SDValue N3) {
3255 // Perform various simplifications.
3256 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
3259 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3260 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
3261 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
3262 if (N1CFP && N2CFP && N3CFP) {
3263 APFloat V1 = N1CFP->getValueAPF();
3264 const APFloat &V2 = N2CFP->getValueAPF();
3265 const APFloat &V3 = N3CFP->getValueAPF();
3266 APFloat::opStatus s =
3267 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
3268 if (s != APFloat::opInvalidOp)
3269 return getConstantFP(V1, VT);
3273 case ISD::CONCAT_VECTORS:
3274 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3275 // one big BUILD_VECTOR.
3276 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3277 N2.getOpcode() == ISD::BUILD_VECTOR &&
3278 N3.getOpcode() == ISD::BUILD_VECTOR) {
3279 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
3280 N1.getNode()->op_end());
3281 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
3282 Elts.append(N3.getNode()->op_begin(), N3.getNode()->op_end());
3283 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
3287 // Use FoldSetCC to simplify SETCC's.
3288 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3289 if (Simp.getNode()) return Simp;
3294 if (N1C->getZExtValue())
3295 return N2; // select true, X, Y -> X
3296 return N3; // select false, X, Y -> Y
3299 if (N2 == N3) return N2; // select C, X, X -> X
3301 case ISD::VECTOR_SHUFFLE:
3302 llvm_unreachable("should use getVectorShuffle constructor!");
3303 case ISD::INSERT_SUBVECTOR: {
3305 if (VT.isSimple() && N1.getValueType().isSimple()
3306 && N2.getValueType().isSimple()) {
3307 assert(VT.isVector() && N1.getValueType().isVector() &&
3308 N2.getValueType().isVector() &&
3309 "Insert subvector VTs must be a vectors");
3310 assert(VT == N1.getValueType() &&
3311 "Dest and insert subvector source types must match!");
3312 assert(N2.getValueType().getSimpleVT() <= N1.getValueType().getSimpleVT() &&
3313 "Insert subvector must be from smaller vector to larger vector!");
3314 if (isa<ConstantSDNode>(Index.getNode())) {
3315 assert((N2.getValueType().getVectorNumElements() +
3316 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3317 <= VT.getVectorNumElements())
3318 && "Insert subvector overflow!");
3321 // Trivial insertion.
3322 if (VT.getSimpleVT() == N2.getValueType().getSimpleVT())
3328 // Fold bit_convert nodes from a type to themselves.
3329 if (N1.getValueType() == VT)
3334 // Memoize node if it doesn't produce a flag.
3336 SDVTList VTs = getVTList(VT);
3337 if (VT != MVT::Glue) {
3338 SDValue Ops[] = { N1, N2, N3 };
3339 FoldingSetNodeID ID;
3340 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3342 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3343 return SDValue(E, 0);
3345 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2, N3);
3346 CSEMap.InsertNode(N, IP);
3348 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, N1, N2, N3);
3351 AllNodes.push_back(N);
3355 return SDValue(N, 0);
3358 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3359 SDValue N1, SDValue N2, SDValue N3,
3361 SDValue Ops[] = { N1, N2, N3, N4 };
3362 return getNode(Opcode, DL, VT, Ops, 4);
3365 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
3366 SDValue N1, SDValue N2, SDValue N3,
3367 SDValue N4, SDValue N5) {
3368 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3369 return getNode(Opcode, DL, VT, Ops, 5);
3372 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3373 /// the incoming stack arguments to be loaded from the stack.
3374 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3375 SmallVector<SDValue, 8> ArgChains;
3377 // Include the original chain at the beginning of the list. When this is
3378 // used by target LowerCall hooks, this helps legalize find the
3379 // CALLSEQ_BEGIN node.
3380 ArgChains.push_back(Chain);
3382 // Add a chain value for each stack argument.
3383 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3384 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3385 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3386 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3387 if (FI->getIndex() < 0)
3388 ArgChains.push_back(SDValue(L, 1));
3390 // Build a tokenfactor for all the chains.
3391 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other,
3392 &ArgChains[0], ArgChains.size());
3395 /// getMemsetValue - Vectorized representation of the memset value
3397 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3399 assert(Value.getOpcode() != ISD::UNDEF);
3401 unsigned NumBits = VT.getScalarType().getSizeInBits();
3402 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3403 assert(C->getAPIntValue().getBitWidth() == 8);
3404 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
3406 return DAG.getConstant(Val, VT);
3407 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), VT);
3410 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3412 // Use a multiplication with 0x010101... to extend the input to the
3414 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
3415 Value = DAG.getNode(ISD::MUL, dl, VT, Value, DAG.getConstant(Magic, VT));
3421 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3422 /// used when a memcpy is turned into a memset when the source is a constant
3424 static SDValue getMemsetStringVal(EVT VT, SDLoc dl, SelectionDAG &DAG,
3425 const TargetLowering &TLI, StringRef Str) {
3426 // Handle vector with all elements zero.
3429 return DAG.getConstant(0, VT);
3430 else if (VT == MVT::f32 || VT == MVT::f64)
3431 return DAG.getConstantFP(0.0, VT);
3432 else if (VT.isVector()) {
3433 unsigned NumElts = VT.getVectorNumElements();
3434 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3435 return DAG.getNode(ISD::BITCAST, dl, VT,
3436 DAG.getConstant(0, EVT::getVectorVT(*DAG.getContext(),
3439 llvm_unreachable("Expected type!");
3442 assert(!VT.isVector() && "Can't handle vector type here!");
3443 unsigned NumVTBits = VT.getSizeInBits();
3444 unsigned NumVTBytes = NumVTBits / 8;
3445 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size()));
3447 APInt Val(NumVTBits, 0);
3448 if (TLI.isLittleEndian()) {
3449 for (unsigned i = 0; i != NumBytes; ++i)
3450 Val |= (uint64_t)(unsigned char)Str[i] << i*8;
3452 for (unsigned i = 0; i != NumBytes; ++i)
3453 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8;
3456 // If the "cost" of materializing the integer immediate is 1 or free, then
3457 // it is cost effective to turn the load into the immediate.
3458 const TargetTransformInfo *TTI = DAG.getTargetTransformInfo();
3459 if (TTI->getIntImmCost(Val, VT.getTypeForEVT(*DAG.getContext())) < 2)
3460 return DAG.getConstant(Val, VT);
3461 return SDValue(0, 0);
3464 /// getMemBasePlusOffset - Returns base and offset node for the
3466 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset, SDLoc dl,
3467 SelectionDAG &DAG) {
3468 EVT VT = Base.getValueType();
3469 return DAG.getNode(ISD::ADD, dl,
3470 VT, Base, DAG.getConstant(Offset, VT));
3473 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3475 static bool isMemSrcFromString(SDValue Src, StringRef &Str) {
3476 unsigned SrcDelta = 0;
3477 GlobalAddressSDNode *G = NULL;
3478 if (Src.getOpcode() == ISD::GlobalAddress)
3479 G = cast<GlobalAddressSDNode>(Src);
3480 else if (Src.getOpcode() == ISD::ADD &&
3481 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3482 Src.getOperand(1).getOpcode() == ISD::Constant) {
3483 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3484 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3489 return getConstantStringInfo(G->getGlobal(), Str, SrcDelta, false);
3492 /// FindOptimalMemOpLowering - Determines the optimial series memory ops
3493 /// to replace the memset / memcpy. Return true if the number of memory ops
3494 /// is below the threshold. It returns the types of the sequence of
3495 /// memory ops to perform memset / memcpy by reference.
3496 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
3497 unsigned Limit, uint64_t Size,
3498 unsigned DstAlign, unsigned SrcAlign,
3504 const TargetLowering &TLI) {
3505 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
3506 "Expecting memcpy / memset source to meet alignment requirement!");
3507 // If 'SrcAlign' is zero, that means the memory operation does not need to
3508 // load the value, i.e. memset or memcpy from constant string. Otherwise,
3509 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
3510 // is the specified alignment of the memory operation. If it is zero, that
3511 // means it's possible to change the alignment of the destination.
3512 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
3513 // not need to be loaded.
3514 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
3515 IsMemset, ZeroMemset, MemcpyStrSrc,
3516 DAG.getMachineFunction());
3518 if (VT == MVT::Other) {
3519 if (DstAlign >= TLI.getDataLayout()->getPointerPrefAlignment() ||
3520 TLI.allowsUnalignedMemoryAccesses(VT)) {
3521 VT = TLI.getPointerTy();
3523 switch (DstAlign & 7) {
3524 case 0: VT = MVT::i64; break;
3525 case 4: VT = MVT::i32; break;
3526 case 2: VT = MVT::i16; break;
3527 default: VT = MVT::i8; break;
3532 while (!TLI.isTypeLegal(LVT))
3533 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3534 assert(LVT.isInteger());
3540 unsigned NumMemOps = 0;
3542 unsigned VTSize = VT.getSizeInBits() / 8;
3543 while (VTSize > Size) {
3544 // For now, only use non-vector load / store's for the left-over pieces.
3549 if (VT.isVector() || VT.isFloatingPoint()) {
3550 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
3551 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
3552 TLI.isSafeMemOpType(NewVT.getSimpleVT()))
3554 else if (NewVT == MVT::i64 &&
3555 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
3556 TLI.isSafeMemOpType(MVT::f64)) {
3557 // i64 is usually not legal on 32-bit targets, but f64 may be.
3565 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
3566 if (NewVT == MVT::i8)
3568 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
3570 NewVTSize = NewVT.getSizeInBits() / 8;
3572 // If the new VT cannot cover all of the remaining bits, then consider
3573 // issuing a (or a pair of) unaligned and overlapping load / store.
3574 // FIXME: Only does this for 64-bit or more since we don't have proper
3575 // cost model for unaligned load / store.
3577 if (NumMemOps && AllowOverlap &&
3578 VTSize >= 8 && NewVTSize < Size &&
3579 TLI.allowsUnalignedMemoryAccesses(VT, &Fast) && Fast)
3587 if (++NumMemOps > Limit)
3590 MemOps.push_back(VT);
3597 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, SDLoc dl,
3598 SDValue Chain, SDValue Dst,
3599 SDValue Src, uint64_t Size,
3600 unsigned Align, bool isVol,
3602 MachinePointerInfo DstPtrInfo,
3603 MachinePointerInfo SrcPtrInfo) {
3604 // Turn a memcpy of undef to nop.
3605 if (Src.getOpcode() == ISD::UNDEF)
3608 // Expand memcpy to a series of load and store ops if the size operand falls
3609 // below a certain threshold.
3610 // TODO: In the AlwaysInline case, if the size is big then generate a loop
3611 // rather than maybe a humongous number of loads and stores.
3612 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3613 std::vector<EVT> MemOps;
3614 bool DstAlignCanChange = false;
3615 MachineFunction &MF = DAG.getMachineFunction();
3616 MachineFrameInfo *MFI = MF.getFrameInfo();
3618 MF.getFunction()->getAttributes().
3619 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
3620 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3621 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3622 DstAlignCanChange = true;
3623 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3624 if (Align > SrcAlign)
3627 bool CopyFromStr = isMemSrcFromString(Src, Str);
3628 bool isZeroStr = CopyFromStr && Str.empty();
3629 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
3631 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3632 (DstAlignCanChange ? 0 : Align),
3633 (isZeroStr ? 0 : SrcAlign),
3634 false, false, CopyFromStr, true, DAG, TLI))
3637 if (DstAlignCanChange) {
3638 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3639 unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
3641 // Don't promote to an alignment that would require dynamic stack
3643 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
3644 if (!TRI->needsStackRealignment(MF))
3645 while (NewAlign > Align &&
3646 TLI.getDataLayout()->exceedsNaturalStackAlignment(NewAlign))
3649 if (NewAlign > Align) {
3650 // Give the stack frame object a larger alignment if needed.
3651 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3652 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3657 SmallVector<SDValue, 8> OutChains;
3658 unsigned NumMemOps = MemOps.size();
3659 uint64_t SrcOff = 0, DstOff = 0;
3660 for (unsigned i = 0; i != NumMemOps; ++i) {
3662 unsigned VTSize = VT.getSizeInBits() / 8;
3663 SDValue Value, Store;
3665 if (VTSize > Size) {
3666 // Issuing an unaligned load / store pair that overlaps with the previous
3667 // pair. Adjust the offset accordingly.
3668 assert(i == NumMemOps-1 && i != 0);
3669 SrcOff -= VTSize - Size;
3670 DstOff -= VTSize - Size;
3674 (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
3675 // It's unlikely a store of a vector immediate can be done in a single
3676 // instruction. It would require a load from a constantpool first.
3677 // We only handle zero vectors here.
3678 // FIXME: Handle other cases where store of vector immediate is done in
3679 // a single instruction.
3680 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff));
3681 if (Value.getNode())
3682 Store = DAG.getStore(Chain, dl, Value,
3683 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3684 DstPtrInfo.getWithOffset(DstOff), isVol,
3688 if (!Store.getNode()) {
3689 // The type might not be legal for the target. This should only happen
3690 // if the type is smaller than a legal type, as on PPC, so the right
3691 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3692 // to Load/Store if NVT==VT.
3693 // FIXME does the case above also need this?
3694 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3695 assert(NVT.bitsGE(VT));
3696 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3697 getMemBasePlusOffset(Src, SrcOff, dl, DAG),
3698 SrcPtrInfo.getWithOffset(SrcOff), VT, isVol, false,
3699 MinAlign(SrcAlign, SrcOff));
3700 Store = DAG.getTruncStore(Chain, dl, Value,
3701 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3702 DstPtrInfo.getWithOffset(DstOff), VT, isVol,
3705 OutChains.push_back(Store);
3711 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3712 &OutChains[0], OutChains.size());
3715 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, SDLoc dl,
3716 SDValue Chain, SDValue Dst,
3717 SDValue Src, uint64_t Size,
3718 unsigned Align, bool isVol,
3720 MachinePointerInfo DstPtrInfo,
3721 MachinePointerInfo SrcPtrInfo) {
3722 // Turn a memmove of undef to nop.
3723 if (Src.getOpcode() == ISD::UNDEF)
3726 // Expand memmove to a series of load and store ops if the size operand falls
3727 // below a certain threshold.
3728 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3729 std::vector<EVT> MemOps;
3730 bool DstAlignCanChange = false;
3731 MachineFunction &MF = DAG.getMachineFunction();
3732 MachineFrameInfo *MFI = MF.getFrameInfo();
3733 bool OptSize = MF.getFunction()->getAttributes().
3734 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
3735 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3736 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3737 DstAlignCanChange = true;
3738 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3739 if (Align > SrcAlign)
3741 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
3743 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3744 (DstAlignCanChange ? 0 : Align), SrcAlign,
3745 false, false, false, false, DAG, TLI))
3748 if (DstAlignCanChange) {
3749 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3750 unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
3751 if (NewAlign > Align) {
3752 // Give the stack frame object a larger alignment if needed.
3753 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3754 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3759 uint64_t SrcOff = 0, DstOff = 0;
3760 SmallVector<SDValue, 8> LoadValues;
3761 SmallVector<SDValue, 8> LoadChains;
3762 SmallVector<SDValue, 8> OutChains;
3763 unsigned NumMemOps = MemOps.size();
3764 for (unsigned i = 0; i < NumMemOps; i++) {
3766 unsigned VTSize = VT.getSizeInBits() / 8;
3767 SDValue Value, Store;
3769 Value = DAG.getLoad(VT, dl, Chain,
3770 getMemBasePlusOffset(Src, SrcOff, dl, DAG),
3771 SrcPtrInfo.getWithOffset(SrcOff), isVol,
3772 false, false, SrcAlign);
3773 LoadValues.push_back(Value);
3774 LoadChains.push_back(Value.getValue(1));
3777 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3778 &LoadChains[0], LoadChains.size());
3780 for (unsigned i = 0; i < NumMemOps; i++) {
3782 unsigned VTSize = VT.getSizeInBits() / 8;
3783 SDValue Value, Store;
3785 Store = DAG.getStore(Chain, dl, LoadValues[i],
3786 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3787 DstPtrInfo.getWithOffset(DstOff), isVol, false, Align);
3788 OutChains.push_back(Store);
3792 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3793 &OutChains[0], OutChains.size());
3796 static SDValue getMemsetStores(SelectionDAG &DAG, SDLoc dl,
3797 SDValue Chain, SDValue Dst,
3798 SDValue Src, uint64_t Size,
3799 unsigned Align, bool isVol,
3800 MachinePointerInfo DstPtrInfo) {
3801 // Turn a memset of undef to nop.
3802 if (Src.getOpcode() == ISD::UNDEF)
3805 // Expand memset to a series of load/store ops if the size operand
3806 // falls below a certain threshold.
3807 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3808 std::vector<EVT> MemOps;
3809 bool DstAlignCanChange = false;
3810 MachineFunction &MF = DAG.getMachineFunction();
3811 MachineFrameInfo *MFI = MF.getFrameInfo();
3812 bool OptSize = MF.getFunction()->getAttributes().
3813 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
3814 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3815 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3816 DstAlignCanChange = true;
3818 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
3819 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
3820 Size, (DstAlignCanChange ? 0 : Align), 0,
3821 true, IsZeroVal, false, true, DAG, TLI))
3824 if (DstAlignCanChange) {
3825 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3826 unsigned NewAlign = (unsigned) TLI.getDataLayout()->getABITypeAlignment(Ty);
3827 if (NewAlign > Align) {
3828 // Give the stack frame object a larger alignment if needed.
3829 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3830 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3835 SmallVector<SDValue, 8> OutChains;
3836 uint64_t DstOff = 0;
3837 unsigned NumMemOps = MemOps.size();
3839 // Find the largest store and generate the bit pattern for it.
3840 EVT LargestVT = MemOps[0];
3841 for (unsigned i = 1; i < NumMemOps; i++)
3842 if (MemOps[i].bitsGT(LargestVT))
3843 LargestVT = MemOps[i];
3844 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
3846 for (unsigned i = 0; i < NumMemOps; i++) {
3848 unsigned VTSize = VT.getSizeInBits() / 8;
3849 if (VTSize > Size) {
3850 // Issuing an unaligned load / store pair that overlaps with the previous
3851 // pair. Adjust the offset accordingly.
3852 assert(i == NumMemOps-1 && i != 0);
3853 DstOff -= VTSize - Size;
3856 // If this store is smaller than the largest store see whether we can get
3857 // the smaller value for free with a truncate.
3858 SDValue Value = MemSetValue;
3859 if (VT.bitsLT(LargestVT)) {
3860 if (!LargestVT.isVector() && !VT.isVector() &&
3861 TLI.isTruncateFree(LargestVT, VT))
3862 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
3864 Value = getMemsetValue(Src, VT, DAG, dl);
3866 assert(Value.getValueType() == VT && "Value with wrong type.");
3867 SDValue Store = DAG.getStore(Chain, dl, Value,
3868 getMemBasePlusOffset(Dst, DstOff, dl, DAG),
3869 DstPtrInfo.getWithOffset(DstOff),
3870 isVol, false, Align);
3871 OutChains.push_back(Store);
3872 DstOff += VT.getSizeInBits() / 8;
3876 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3877 &OutChains[0], OutChains.size());
3880 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDLoc dl, SDValue Dst,
3881 SDValue Src, SDValue Size,
3882 unsigned Align, bool isVol, bool AlwaysInline,
3883 MachinePointerInfo DstPtrInfo,
3884 MachinePointerInfo SrcPtrInfo) {
3885 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
3887 // Check to see if we should lower the memcpy to loads and stores first.
3888 // For cases within the target-specified limits, this is the best choice.
3889 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3891 // Memcpy with size zero? Just return the original chain.
3892 if (ConstantSize->isNullValue())
3895 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3896 ConstantSize->getZExtValue(),Align,
3897 isVol, false, DstPtrInfo, SrcPtrInfo);
3898 if (Result.getNode())
3902 // Then check to see if we should lower the memcpy with target-specific
3903 // code. If the target chooses to do this, this is the next best.
3905 TSI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3906 isVol, AlwaysInline,
3907 DstPtrInfo, SrcPtrInfo);
3908 if (Result.getNode())
3911 // If we really need inline code and the target declined to provide it,
3912 // use a (potentially long) sequence of loads and stores.
3914 assert(ConstantSize && "AlwaysInline requires a constant size!");
3915 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3916 ConstantSize->getZExtValue(), Align, isVol,
3917 true, DstPtrInfo, SrcPtrInfo);
3920 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
3921 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
3922 // respect volatile, so they may do things like read or write memory
3923 // beyond the given memory regions. But fixing this isn't easy, and most
3924 // people don't care.
3926 // Emit a library call.
3927 TargetLowering::ArgListTy Args;
3928 TargetLowering::ArgListEntry Entry;
3929 Entry.Ty = TLI.getDataLayout()->getIntPtrType(*getContext());
3930 Entry.Node = Dst; Args.push_back(Entry);
3931 Entry.Node = Src; Args.push_back(Entry);
3932 Entry.Node = Size; Args.push_back(Entry);
3933 // FIXME: pass in SDLoc
3935 CallLoweringInfo CLI(Chain, Type::getVoidTy(*getContext()),
3936 false, false, false, false, 0,
3937 TLI.getLibcallCallingConv(RTLIB::MEMCPY),
3938 /*isTailCall=*/false,
3939 /*doesNotReturn=*/false, /*isReturnValueUsed=*/false,
3940 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3941 TLI.getPointerTy()),
3943 std::pair<SDValue,SDValue> CallResult = TLI.LowerCallTo(CLI);
3945 return CallResult.second;
3948 SDValue SelectionDAG::getMemmove(SDValue Chain, SDLoc dl, SDValue Dst,
3949 SDValue Src, SDValue Size,
3950 unsigned Align, bool isVol,
3951 MachinePointerInfo DstPtrInfo,
3952 MachinePointerInfo SrcPtrInfo) {
3953 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
3955 // Check to see if we should lower the memmove to loads and stores first.
3956 // For cases within the target-specified limits, this is the best choice.
3957 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3959 // Memmove with size zero? Just return the original chain.
3960 if (ConstantSize->isNullValue())
3964 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3965 ConstantSize->getZExtValue(), Align, isVol,
3966 false, DstPtrInfo, SrcPtrInfo);
3967 if (Result.getNode())
3971 // Then check to see if we should lower the memmove with target-specific
3972 // code. If the target chooses to do this, this is the next best.
3974 TSI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align, isVol,
3975 DstPtrInfo, SrcPtrInfo);
3976 if (Result.getNode())
3979 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
3980 // not be safe. See memcpy above for more details.
3982 // Emit a library call.
3983 TargetLowering::ArgListTy Args;
3984 TargetLowering::ArgListEntry Entry;
3985 Entry.Ty = TLI.getDataLayout()->getIntPtrType(*getContext());
3986 Entry.Node = Dst; Args.push_back(Entry);
3987 Entry.Node = Src; Args.push_back(Entry);
3988 Entry.Node = Size; Args.push_back(Entry);
3989 // FIXME: pass in SDLoc
3991 CallLoweringInfo CLI(Chain, Type::getVoidTy(*getContext()),
3992 false, false, false, false, 0,
3993 TLI.getLibcallCallingConv(RTLIB::MEMMOVE),
3994 /*isTailCall=*/false,
3995 /*doesNotReturn=*/false, /*isReturnValueUsed=*/false,
3996 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3997 TLI.getPointerTy()),
3999 std::pair<SDValue,SDValue> CallResult = TLI.LowerCallTo(CLI);
4001 return CallResult.second;
4004 SDValue SelectionDAG::getMemset(SDValue Chain, SDLoc dl, SDValue Dst,
4005 SDValue Src, SDValue Size,
4006 unsigned Align, bool isVol,
4007 MachinePointerInfo DstPtrInfo) {
4008 assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
4010 // Check to see if we should lower the memset to stores first.
4011 // For cases within the target-specified limits, this is the best choice.
4012 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4014 // Memset with size zero? Just return the original chain.
4015 if (ConstantSize->isNullValue())
4019 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
4020 Align, isVol, DstPtrInfo);
4022 if (Result.getNode())
4026 // Then check to see if we should lower the memset with target-specific
4027 // code. If the target chooses to do this, this is the next best.
4029 TSI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align, isVol,
4031 if (Result.getNode())
4034 // Emit a library call.
4035 Type *IntPtrTy = TLI.getDataLayout()->getIntPtrType(*getContext());
4036 TargetLowering::ArgListTy Args;
4037 TargetLowering::ArgListEntry Entry;
4038 Entry.Node = Dst; Entry.Ty = IntPtrTy;
4039 Args.push_back(Entry);
4040 // Extend or truncate the argument to be an i32 value for the call.
4041 if (Src.getValueType().bitsGT(MVT::i32))
4042 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
4044 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
4046 Entry.Ty = Type::getInt32Ty(*getContext());
4047 Entry.isSExt = true;
4048 Args.push_back(Entry);
4050 Entry.Ty = IntPtrTy;
4051 Entry.isSExt = false;
4052 Args.push_back(Entry);
4053 // FIXME: pass in SDLoc
4055 CallLoweringInfo CLI(Chain, Type::getVoidTy(*getContext()),
4056 false, false, false, false, 0,
4057 TLI.getLibcallCallingConv(RTLIB::MEMSET),
4058 /*isTailCall=*/false,
4059 /*doesNotReturn*/false, /*isReturnValueUsed=*/false,
4060 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
4061 TLI.getPointerTy()),
4063 std::pair<SDValue,SDValue> CallResult = TLI.LowerCallTo(CLI);
4065 return CallResult.second;
4068 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4069 SDValue Chain, SDValue Ptr, SDValue Cmp,
4070 SDValue Swp, MachinePointerInfo PtrInfo,
4072 AtomicOrdering Ordering,
4073 SynchronizationScope SynchScope) {
4074 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4075 Alignment = getEVTAlignment(MemVT);
4077 MachineFunction &MF = getMachineFunction();
4079 // All atomics are load and store, except for ATMOIC_LOAD and ATOMIC_STORE.
4080 // For now, atomics are considered to be volatile always.
4081 // FIXME: Volatile isn't really correct; we should keep track of atomic
4082 // orderings in the memoperand.
4083 unsigned Flags = MachineMemOperand::MOVolatile;
4084 if (Opcode != ISD::ATOMIC_STORE)
4085 Flags |= MachineMemOperand::MOLoad;
4086 if (Opcode != ISD::ATOMIC_LOAD)
4087 Flags |= MachineMemOperand::MOStore;
4089 MachineMemOperand *MMO =
4090 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment);
4092 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO,
4093 Ordering, SynchScope);
4096 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4098 SDValue Ptr, SDValue Cmp,
4099 SDValue Swp, MachineMemOperand *MMO,
4100 AtomicOrdering Ordering,
4101 SynchronizationScope SynchScope) {
4102 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
4103 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
4105 EVT VT = Cmp.getValueType();
4107 SDVTList VTs = getVTList(VT, MVT::Other);
4108 FoldingSetNodeID ID;
4109 ID.AddInteger(MemVT.getRawBits());
4110 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
4111 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
4112 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4114 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4115 cast<AtomicSDNode>(E)->refineAlignment(MMO);
4116 return SDValue(E, 0);
4118 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, MemVT, Chain,
4119 Ptr, Cmp, Swp, MMO, Ordering,
4121 CSEMap.InsertNode(N, IP);
4122 AllNodes.push_back(N);
4123 return SDValue(N, 0);
4126 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4128 SDValue Ptr, SDValue Val,
4129 const Value* PtrVal,
4131 AtomicOrdering Ordering,
4132 SynchronizationScope SynchScope) {
4133 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4134 Alignment = getEVTAlignment(MemVT);
4136 MachineFunction &MF = getMachineFunction();
4137 // An atomic store does not load. An atomic load does not store.
4138 // (An atomicrmw obviously both loads and stores.)
4139 // For now, atomics are considered to be volatile always, and they are
4141 // FIXME: Volatile isn't really correct; we should keep track of atomic
4142 // orderings in the memoperand.
4143 unsigned Flags = MachineMemOperand::MOVolatile;
4144 if (Opcode != ISD::ATOMIC_STORE)
4145 Flags |= MachineMemOperand::MOLoad;
4146 if (Opcode != ISD::ATOMIC_LOAD)
4147 Flags |= MachineMemOperand::MOStore;
4149 MachineMemOperand *MMO =
4150 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
4151 MemVT.getStoreSize(), Alignment);
4153 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO,
4154 Ordering, SynchScope);
4157 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4159 SDValue Ptr, SDValue Val,
4160 MachineMemOperand *MMO,
4161 AtomicOrdering Ordering,
4162 SynchronizationScope SynchScope) {
4163 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
4164 Opcode == ISD::ATOMIC_LOAD_SUB ||
4165 Opcode == ISD::ATOMIC_LOAD_AND ||
4166 Opcode == ISD::ATOMIC_LOAD_OR ||
4167 Opcode == ISD::ATOMIC_LOAD_XOR ||
4168 Opcode == ISD::ATOMIC_LOAD_NAND ||
4169 Opcode == ISD::ATOMIC_LOAD_MIN ||
4170 Opcode == ISD::ATOMIC_LOAD_MAX ||
4171 Opcode == ISD::ATOMIC_LOAD_UMIN ||
4172 Opcode == ISD::ATOMIC_LOAD_UMAX ||
4173 Opcode == ISD::ATOMIC_SWAP ||
4174 Opcode == ISD::ATOMIC_STORE) &&
4175 "Invalid Atomic Op");
4177 EVT VT = Val.getValueType();
4179 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
4180 getVTList(VT, MVT::Other);
4181 FoldingSetNodeID ID;
4182 ID.AddInteger(MemVT.getRawBits());
4183 SDValue Ops[] = {Chain, Ptr, Val};
4184 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
4185 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4187 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4188 cast<AtomicSDNode>(E)->refineAlignment(MMO);
4189 return SDValue(E, 0);
4191 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, MemVT, Chain,
4193 Ordering, SynchScope);
4194 CSEMap.InsertNode(N, IP);
4195 AllNodes.push_back(N);
4196 return SDValue(N, 0);
4199 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4200 EVT VT, SDValue Chain,
4202 const Value* PtrVal,
4204 AtomicOrdering Ordering,
4205 SynchronizationScope SynchScope) {
4206 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4207 Alignment = getEVTAlignment(MemVT);
4209 MachineFunction &MF = getMachineFunction();
4210 // An atomic store does not load. An atomic load does not store.
4211 // (An atomicrmw obviously both loads and stores.)
4212 // For now, atomics are considered to be volatile always, and they are
4214 // FIXME: Volatile isn't really correct; we should keep track of atomic
4215 // orderings in the memoperand.
4216 unsigned Flags = MachineMemOperand::MOVolatile;
4217 if (Opcode != ISD::ATOMIC_STORE)
4218 Flags |= MachineMemOperand::MOLoad;
4219 if (Opcode != ISD::ATOMIC_LOAD)
4220 Flags |= MachineMemOperand::MOStore;
4222 MachineMemOperand *MMO =
4223 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
4224 MemVT.getStoreSize(), Alignment);
4226 return getAtomic(Opcode, dl, MemVT, VT, Chain, Ptr, MMO,
4227 Ordering, SynchScope);
4230 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDLoc dl, EVT MemVT,
4231 EVT VT, SDValue Chain,
4233 MachineMemOperand *MMO,
4234 AtomicOrdering Ordering,
4235 SynchronizationScope SynchScope) {
4236 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
4238 SDVTList VTs = getVTList(VT, MVT::Other);
4239 FoldingSetNodeID ID;
4240 ID.AddInteger(MemVT.getRawBits());
4241 SDValue Ops[] = {Chain, Ptr};
4242 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
4243 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4245 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4246 cast<AtomicSDNode>(E)->refineAlignment(MMO);
4247 return SDValue(E, 0);
4249 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, MemVT, Chain,
4250 Ptr, MMO, Ordering, SynchScope);
4251 CSEMap.InsertNode(N, IP);
4252 AllNodes.push_back(N);
4253 return SDValue(N, 0);
4256 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
4257 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
4262 SmallVector<EVT, 4> VTs;
4263 VTs.reserve(NumOps);
4264 for (unsigned i = 0; i < NumOps; ++i)
4265 VTs.push_back(Ops[i].getValueType());
4266 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
4271 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl,
4272 const EVT *VTs, unsigned NumVTs,
4273 const SDValue *Ops, unsigned NumOps,
4274 EVT MemVT, MachinePointerInfo PtrInfo,
4275 unsigned Align, bool Vol,
4276 bool ReadMem, bool WriteMem) {
4277 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
4278 MemVT, PtrInfo, Align, Vol,
4283 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
4284 const SDValue *Ops, unsigned NumOps,
4285 EVT MemVT, MachinePointerInfo PtrInfo,
4286 unsigned Align, bool Vol,
4287 bool ReadMem, bool WriteMem) {
4288 if (Align == 0) // Ensure that codegen never sees alignment 0
4289 Align = getEVTAlignment(MemVT);
4291 MachineFunction &MF = getMachineFunction();
4294 Flags |= MachineMemOperand::MOStore;
4296 Flags |= MachineMemOperand::MOLoad;
4298 Flags |= MachineMemOperand::MOVolatile;
4299 MachineMemOperand *MMO =
4300 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Align);
4302 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
4306 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDLoc dl, SDVTList VTList,
4307 const SDValue *Ops, unsigned NumOps,
4308 EVT MemVT, MachineMemOperand *MMO) {
4309 assert((Opcode == ISD::INTRINSIC_VOID ||
4310 Opcode == ISD::INTRINSIC_W_CHAIN ||
4311 Opcode == ISD::PREFETCH ||
4312 Opcode == ISD::LIFETIME_START ||
4313 Opcode == ISD::LIFETIME_END ||
4314 (Opcode <= INT_MAX &&
4315 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
4316 "Opcode is not a memory-accessing opcode!");
4318 // Memoize the node unless it returns a flag.
4319 MemIntrinsicSDNode *N;
4320 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4321 FoldingSetNodeID ID;
4322 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4323 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4325 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4326 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
4327 return SDValue(E, 0);
4330 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTList, Ops, NumOps,
4332 CSEMap.InsertNode(N, IP);
4334 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTList, Ops, NumOps,
4337 AllNodes.push_back(N);
4338 return SDValue(N, 0);
4341 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4342 /// MachinePointerInfo record from it. This is particularly useful because the
4343 /// code generator has many cases where it doesn't bother passing in a
4344 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4345 static MachinePointerInfo InferPointerInfo(SDValue Ptr, int64_t Offset = 0) {
4346 // If this is FI+Offset, we can model it.
4347 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
4348 return MachinePointerInfo::getFixedStack(FI->getIndex(), Offset);
4350 // If this is (FI+Offset1)+Offset2, we can model it.
4351 if (Ptr.getOpcode() != ISD::ADD ||
4352 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
4353 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
4354 return MachinePointerInfo();
4356 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4357 return MachinePointerInfo::getFixedStack(FI, Offset+
4358 cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
4361 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4362 /// MachinePointerInfo record from it. This is particularly useful because the
4363 /// code generator has many cases where it doesn't bother passing in a
4364 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4365 static MachinePointerInfo InferPointerInfo(SDValue Ptr, SDValue OffsetOp) {
4366 // If the 'Offset' value isn't a constant, we can't handle this.
4367 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
4368 return InferPointerInfo(Ptr, OffsetNode->getSExtValue());
4369 if (OffsetOp.getOpcode() == ISD::UNDEF)
4370 return InferPointerInfo(Ptr);
4371 return MachinePointerInfo();
4376 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4377 EVT VT, SDLoc dl, SDValue Chain,
4378 SDValue Ptr, SDValue Offset,
4379 MachinePointerInfo PtrInfo, EVT MemVT,
4380 bool isVolatile, bool isNonTemporal, bool isInvariant,
4381 unsigned Alignment, const MDNode *TBAAInfo,
4382 const MDNode *Ranges) {
4383 assert(Chain.getValueType() == MVT::Other &&
4384 "Invalid chain type");
4385 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4386 Alignment = getEVTAlignment(VT);
4388 unsigned Flags = MachineMemOperand::MOLoad;
4390 Flags |= MachineMemOperand::MOVolatile;
4392 Flags |= MachineMemOperand::MONonTemporal;
4394 Flags |= MachineMemOperand::MOInvariant;
4396 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
4399 PtrInfo = InferPointerInfo(Ptr, Offset);
4401 MachineFunction &MF = getMachineFunction();
4402 MachineMemOperand *MMO =
4403 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
4405 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
4409 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4410 EVT VT, SDLoc dl, SDValue Chain,
4411 SDValue Ptr, SDValue Offset, EVT MemVT,
4412 MachineMemOperand *MMO) {
4414 ExtType = ISD::NON_EXTLOAD;
4415 } else if (ExtType == ISD::NON_EXTLOAD) {
4416 assert(VT == MemVT && "Non-extending load from different memory type!");
4419 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
4420 "Should only be an extending load, not truncating!");
4421 assert(VT.isInteger() == MemVT.isInteger() &&
4422 "Cannot convert from FP to Int or Int -> FP!");
4423 assert(VT.isVector() == MemVT.isVector() &&
4424 "Cannot use trunc store to convert to or from a vector!");
4425 assert((!VT.isVector() ||
4426 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
4427 "Cannot use trunc store to change the number of vector elements!");
4430 bool Indexed = AM != ISD::UNINDEXED;
4431 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
4432 "Unindexed load with an offset!");
4434 SDVTList VTs = Indexed ?
4435 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
4436 SDValue Ops[] = { Chain, Ptr, Offset };
4437 FoldingSetNodeID ID;
4438 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
4439 ID.AddInteger(MemVT.getRawBits());
4440 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
4441 MMO->isNonTemporal(),
4442 MMO->isInvariant()));
4443 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4445 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4446 cast<LoadSDNode>(E)->refineAlignment(MMO);
4447 return SDValue(E, 0);
4449 SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ExtType,
4451 CSEMap.InsertNode(N, IP);
4452 AllNodes.push_back(N);
4453 return SDValue(N, 0);
4456 SDValue SelectionDAG::getLoad(EVT VT, SDLoc dl,
4457 SDValue Chain, SDValue Ptr,
4458 MachinePointerInfo PtrInfo,
4459 bool isVolatile, bool isNonTemporal,
4460 bool isInvariant, unsigned Alignment,
4461 const MDNode *TBAAInfo,
4462 const MDNode *Ranges) {
4463 SDValue Undef = getUNDEF(Ptr.getValueType());
4464 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4465 PtrInfo, VT, isVolatile, isNonTemporal, isInvariant, Alignment,
4469 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, SDLoc dl, EVT VT,
4470 SDValue Chain, SDValue Ptr,
4471 MachinePointerInfo PtrInfo, EVT MemVT,
4472 bool isVolatile, bool isNonTemporal,
4473 unsigned Alignment, const MDNode *TBAAInfo) {
4474 SDValue Undef = getUNDEF(Ptr.getValueType());
4475 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4476 PtrInfo, MemVT, isVolatile, isNonTemporal, false, Alignment,
4482 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDLoc dl, SDValue Base,
4483 SDValue Offset, ISD::MemIndexedMode AM) {
4484 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
4485 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
4486 "Load is already a indexed load!");
4487 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
4488 LD->getChain(), Base, Offset, LD->getPointerInfo(),
4489 LD->getMemoryVT(), LD->isVolatile(), LD->isNonTemporal(),
4490 false, LD->getAlignment());
4493 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val,
4494 SDValue Ptr, MachinePointerInfo PtrInfo,
4495 bool isVolatile, bool isNonTemporal,
4496 unsigned Alignment, const MDNode *TBAAInfo) {
4497 assert(Chain.getValueType() == MVT::Other &&
4498 "Invalid chain type");
4499 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4500 Alignment = getEVTAlignment(Val.getValueType());
4502 unsigned Flags = MachineMemOperand::MOStore;
4504 Flags |= MachineMemOperand::MOVolatile;
4506 Flags |= MachineMemOperand::MONonTemporal;
4509 PtrInfo = InferPointerInfo(Ptr);
4511 MachineFunction &MF = getMachineFunction();
4512 MachineMemOperand *MMO =
4513 MF.getMachineMemOperand(PtrInfo, Flags,
4514 Val.getValueType().getStoreSize(), Alignment,
4517 return getStore(Chain, dl, Val, Ptr, MMO);
4520 SDValue SelectionDAG::getStore(SDValue Chain, SDLoc dl, SDValue Val,
4521 SDValue Ptr, MachineMemOperand *MMO) {
4522 assert(Chain.getValueType() == MVT::Other &&
4523 "Invalid chain type");
4524 EVT VT = Val.getValueType();
4525 SDVTList VTs = getVTList(MVT::Other);
4526 SDValue Undef = getUNDEF(Ptr.getValueType());
4527 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4528 FoldingSetNodeID ID;
4529 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4530 ID.AddInteger(VT.getRawBits());
4531 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
4532 MMO->isNonTemporal(), MMO->isInvariant()));
4533 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4535 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4536 cast<StoreSDNode>(E)->refineAlignment(MMO);
4537 return SDValue(E, 0);
4539 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), dl.getDebugLoc(), VTs, ISD::UNINDEXED,
4541 CSEMap.InsertNode(N, IP);
4542 AllNodes.push_back(N);
4543 return SDValue(N, 0);
4546 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val,
4547 SDValue Ptr, MachinePointerInfo PtrInfo,
4548 EVT SVT,bool isVolatile, bool isNonTemporal,
4550 const MDNode *TBAAInfo) {
4551 assert(Chain.getValueType() == MVT::Other &&
4552 "Invalid chain type");
4553 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4554 Alignment = getEVTAlignment(SVT);
4556 unsigned Flags = MachineMemOperand::MOStore;
4558 Flags |= MachineMemOperand::MOVolatile;
4560 Flags |= MachineMemOperand::MONonTemporal;
4563 PtrInfo = InferPointerInfo(Ptr);
4565 MachineFunction &MF = getMachineFunction();
4566 MachineMemOperand *MMO =
4567 MF.getMachineMemOperand(PtrInfo, Flags, SVT.getStoreSize(), Alignment,
4570 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
4573 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDLoc dl, SDValue Val,
4574 SDValue Ptr, EVT SVT,
4575 MachineMemOperand *MMO) {
4576 EVT VT = Val.getValueType();
4578 assert(Chain.getValueType() == MVT::Other &&
4579 "Invalid chain type");
4581 return getStore(Chain, dl, Val, Ptr, MMO);
4583 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
4584 "Should only be a truncating store, not extending!");
4585 assert(VT.isInteger() == SVT.isInteger() &&
4586 "Can't do FP-INT conversion!");
4587 assert(VT.isVector() == SVT.isVector() &&
4588 "Cannot use trunc store to convert to or from a vector!");
4589 assert((!VT.isVector() ||
4590 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
4591 "Cannot use trunc store to change the number of vector elements!");
4593 SDVTList VTs = getVTList(MVT::Other);
4594 SDValue Undef = getUNDEF(Ptr.getValueType());
4595 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4596 FoldingSetNodeID ID;
4597 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4598 ID.AddInteger(SVT.getRawBits());
4599 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
4600 MMO->isNonTemporal(), MMO->isInvariant()));
4601 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
4603 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4604 cast<StoreSDNode>(E)->refineAlignment(MMO);
4605 return SDValue(E, 0);
4607 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), dl.getDebugLoc(), VTs, ISD::UNINDEXED,
4609 CSEMap.InsertNode(N, IP);
4610 AllNodes.push_back(N);
4611 return SDValue(N, 0);
4615 SelectionDAG::getIndexedStore(SDValue OrigStore, SDLoc dl, SDValue Base,
4616 SDValue Offset, ISD::MemIndexedMode AM) {
4617 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4618 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4619 "Store is already a indexed store!");
4620 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4621 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4622 FoldingSetNodeID ID;
4623 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4624 ID.AddInteger(ST->getMemoryVT().getRawBits());
4625 ID.AddInteger(ST->getRawSubclassData());
4626 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
4628 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4629 return SDValue(E, 0);
4631 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
4632 ST->isTruncatingStore(),
4634 ST->getMemOperand());
4635 CSEMap.InsertNode(N, IP);
4636 AllNodes.push_back(N);
4637 return SDValue(N, 0);
4640 SDValue SelectionDAG::getVAArg(EVT VT, SDLoc dl,
4641 SDValue Chain, SDValue Ptr,
4644 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, MVT::i32) };
4645 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 4);
4648 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
4649 const SDUse *Ops, unsigned NumOps) {
4651 case 0: return getNode(Opcode, DL, VT);
4652 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4653 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4654 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4658 // Copy from an SDUse array into an SDValue array for use with
4659 // the regular getNode logic.
4660 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4661 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4664 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, EVT VT,
4665 const SDValue *Ops, unsigned NumOps) {
4667 case 0: return getNode(Opcode, DL, VT);
4668 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4669 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4670 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4676 case ISD::SELECT_CC: {
4677 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4678 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4679 "LHS and RHS of condition must have same type!");
4680 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4681 "True and False arms of SelectCC must have same type!");
4682 assert(Ops[2].getValueType() == VT &&
4683 "select_cc node must be of same type as true and false value!");
4687 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4688 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4689 "LHS/RHS of comparison should match types!");
4696 SDVTList VTs = getVTList(VT);
4698 if (VT != MVT::Glue) {
4699 FoldingSetNodeID ID;
4700 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4703 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4704 return SDValue(E, 0);
4706 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, Ops, NumOps);
4707 CSEMap.InsertNode(N, IP);
4709 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs, Ops, NumOps);
4712 AllNodes.push_back(N);
4716 return SDValue(N, 0);
4719 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
4720 ArrayRef<EVT> ResultTys,
4721 const SDValue *Ops, unsigned NumOps) {
4722 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4726 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL,
4727 const EVT *VTs, unsigned NumVTs,
4728 const SDValue *Ops, unsigned NumOps) {
4730 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4731 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4734 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4735 const SDValue *Ops, unsigned NumOps) {
4736 if (VTList.NumVTs == 1)
4737 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4741 // FIXME: figure out how to safely handle things like
4742 // int foo(int x) { return 1 << (x & 255); }
4743 // int bar() { return foo(256); }
4744 case ISD::SRA_PARTS:
4745 case ISD::SRL_PARTS:
4746 case ISD::SHL_PARTS:
4747 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4748 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4749 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4750 else if (N3.getOpcode() == ISD::AND)
4751 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4752 // If the and is only masking out bits that cannot effect the shift,
4753 // eliminate the and.
4754 unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
4755 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4756 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4762 // Memoize the node unless it returns a flag.
4764 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4765 FoldingSetNodeID ID;
4766 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4768 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4769 return SDValue(E, 0);
4772 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0]);
4773 } else if (NumOps == 2) {
4774 N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0], Ops[1]);
4775 } else if (NumOps == 3) {
4776 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0], Ops[1],
4779 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops, NumOps);
4781 CSEMap.InsertNode(N, IP);
4784 N = new (NodeAllocator) UnarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0]);
4785 } else if (NumOps == 2) {
4786 N = new (NodeAllocator) BinarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0], Ops[1]);
4787 } else if (NumOps == 3) {
4788 N = new (NodeAllocator) TernarySDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops[0], Ops[1],
4791 N = new (NodeAllocator) SDNode(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList, Ops, NumOps);
4794 AllNodes.push_back(N);
4798 return SDValue(N, 0);
4801 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList) {
4802 return getNode(Opcode, DL, VTList, 0, 0);
4805 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4807 SDValue Ops[] = { N1 };
4808 return getNode(Opcode, DL, VTList, Ops, 1);
4811 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4812 SDValue N1, SDValue N2) {
4813 SDValue Ops[] = { N1, N2 };
4814 return getNode(Opcode, DL, VTList, Ops, 2);
4817 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4818 SDValue N1, SDValue N2, SDValue N3) {
4819 SDValue Ops[] = { N1, N2, N3 };
4820 return getNode(Opcode, DL, VTList, Ops, 3);
4823 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4824 SDValue N1, SDValue N2, SDValue N3,
4826 SDValue Ops[] = { N1, N2, N3, N4 };
4827 return getNode(Opcode, DL, VTList, Ops, 4);
4830 SDValue SelectionDAG::getNode(unsigned Opcode, SDLoc DL, SDVTList VTList,
4831 SDValue N1, SDValue N2, SDValue N3,
4832 SDValue N4, SDValue N5) {
4833 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4834 return getNode(Opcode, DL, VTList, Ops, 5);
4837 SDVTList SelectionDAG::getVTList(EVT VT) {
4838 return makeVTList(SDNode::getValueTypeList(VT), 1);
4841 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4842 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4843 E = VTList.rend(); I != E; ++I)
4844 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4847 EVT *Array = Allocator.Allocate<EVT>(2);
4850 SDVTList Result = makeVTList(Array, 2);
4851 VTList.push_back(Result);
4855 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4856 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4857 E = VTList.rend(); I != E; ++I)
4858 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4862 EVT *Array = Allocator.Allocate<EVT>(3);
4866 SDVTList Result = makeVTList(Array, 3);
4867 VTList.push_back(Result);
4871 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4872 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4873 E = VTList.rend(); I != E; ++I)
4874 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4875 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4878 EVT *Array = Allocator.Allocate<EVT>(4);
4883 SDVTList Result = makeVTList(Array, 4);
4884 VTList.push_back(Result);
4888 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4890 case 0: llvm_unreachable("Cannot have nodes without results!");
4891 case 1: return getVTList(VTs[0]);
4892 case 2: return getVTList(VTs[0], VTs[1]);
4893 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4894 case 4: return getVTList(VTs[0], VTs[1], VTs[2], VTs[3]);
4898 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4899 E = VTList.rend(); I != E; ++I) {
4900 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4903 if (std::equal(&VTs[2], &VTs[NumVTs], &I->VTs[2]))
4907 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4908 std::copy(VTs, VTs+NumVTs, Array);
4909 SDVTList Result = makeVTList(Array, NumVTs);
4910 VTList.push_back(Result);
4915 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4916 /// specified operands. If the resultant node already exists in the DAG,
4917 /// this does not modify the specified node, instead it returns the node that
4918 /// already exists. If the resultant node does not exist in the DAG, the
4919 /// input node is returned. As a degenerate case, if you specify the same
4920 /// input operands as the node already has, the input node is returned.
4921 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
4922 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4924 // Check to see if there is no change.
4925 if (Op == N->getOperand(0)) return N;
4927 // See if the modified node already exists.
4928 void *InsertPos = 0;
4929 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4932 // Nope it doesn't. Remove the node from its current place in the maps.
4934 if (!RemoveNodeFromCSEMaps(N))
4937 // Now we update the operands.
4938 N->OperandList[0].set(Op);
4940 // If this gets put into a CSE map, add it.
4941 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4945 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
4946 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4948 // Check to see if there is no change.
4949 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4950 return N; // No operands changed, just return the input node.
4952 // See if the modified node already exists.
4953 void *InsertPos = 0;
4954 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4957 // Nope it doesn't. Remove the node from its current place in the maps.
4959 if (!RemoveNodeFromCSEMaps(N))
4962 // Now we update the operands.
4963 if (N->OperandList[0] != Op1)
4964 N->OperandList[0].set(Op1);
4965 if (N->OperandList[1] != Op2)
4966 N->OperandList[1].set(Op2);
4968 // If this gets put into a CSE map, add it.
4969 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4973 SDNode *SelectionDAG::
4974 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
4975 SDValue Ops[] = { Op1, Op2, Op3 };
4976 return UpdateNodeOperands(N, Ops, 3);
4979 SDNode *SelectionDAG::
4980 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
4981 SDValue Op3, SDValue Op4) {
4982 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4983 return UpdateNodeOperands(N, Ops, 4);
4986 SDNode *SelectionDAG::
4987 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
4988 SDValue Op3, SDValue Op4, SDValue Op5) {
4989 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4990 return UpdateNodeOperands(N, Ops, 5);
4993 SDNode *SelectionDAG::
4994 UpdateNodeOperands(SDNode *N, const SDValue *Ops, unsigned NumOps) {
4995 assert(N->getNumOperands() == NumOps &&
4996 "Update with wrong number of operands");
4998 // Check to see if there is no change.
4999 bool AnyChange = false;
5000 for (unsigned i = 0; i != NumOps; ++i) {
5001 if (Ops[i] != N->getOperand(i)) {
5007 // No operands changed, just return the input node.
5008 if (!AnyChange) return N;
5010 // See if the modified node already exists.
5011 void *InsertPos = 0;
5012 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
5015 // Nope it doesn't. Remove the node from its current place in the maps.
5017 if (!RemoveNodeFromCSEMaps(N))
5020 // Now we update the operands.
5021 for (unsigned i = 0; i != NumOps; ++i)
5022 if (N->OperandList[i] != Ops[i])
5023 N->OperandList[i].set(Ops[i]);
5025 // If this gets put into a CSE map, add it.
5026 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
5030 /// DropOperands - Release the operands and set this node to have
5032 void SDNode::DropOperands() {
5033 // Unlike the code in MorphNodeTo that does this, we don't need to
5034 // watch for dead nodes here.
5035 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
5041 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
5044 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5046 SDVTList VTs = getVTList(VT);
5047 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
5050 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5051 EVT VT, SDValue Op1) {
5052 SDVTList VTs = getVTList(VT);
5053 SDValue Ops[] = { Op1 };
5054 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
5057 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5058 EVT VT, SDValue Op1,
5060 SDVTList VTs = getVTList(VT);
5061 SDValue Ops[] = { Op1, Op2 };
5062 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
5065 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5066 EVT VT, SDValue Op1,
5067 SDValue Op2, SDValue Op3) {
5068 SDVTList VTs = getVTList(VT);
5069 SDValue Ops[] = { Op1, Op2, Op3 };
5070 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
5073 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5074 EVT VT, const SDValue *Ops,
5076 SDVTList VTs = getVTList(VT);
5077 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
5080 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5081 EVT VT1, EVT VT2, const SDValue *Ops,
5083 SDVTList VTs = getVTList(VT1, VT2);
5084 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
5087 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5089 SDVTList VTs = getVTList(VT1, VT2);
5090 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
5093 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5094 EVT VT1, EVT VT2, EVT VT3,
5095 const SDValue *Ops, unsigned NumOps) {
5096 SDVTList VTs = getVTList(VT1, VT2, VT3);
5097 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
5100 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5101 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
5102 const SDValue *Ops, unsigned NumOps) {
5103 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5104 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
5107 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5110 SDVTList VTs = getVTList(VT1, VT2);
5111 SDValue Ops[] = { Op1 };
5112 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
5115 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5117 SDValue Op1, SDValue Op2) {
5118 SDVTList VTs = getVTList(VT1, VT2);
5119 SDValue Ops[] = { Op1, Op2 };
5120 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
5123 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5125 SDValue Op1, SDValue Op2,
5127 SDVTList VTs = getVTList(VT1, VT2);
5128 SDValue Ops[] = { Op1, Op2, Op3 };
5129 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
5132 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5133 EVT VT1, EVT VT2, EVT VT3,
5134 SDValue Op1, SDValue Op2,
5136 SDVTList VTs = getVTList(VT1, VT2, VT3);
5137 SDValue Ops[] = { Op1, Op2, Op3 };
5138 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
5141 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
5142 SDVTList VTs, const SDValue *Ops,
5144 N = MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
5145 // Reset the NodeID to -1.
5150 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away
5151 /// the line number information on the merged node since it is not possible to
5152 /// preserve the information that operation is associated with multiple lines.
5153 /// This will make the debugger working better at -O0, were there is a higher
5154 /// probability having other instructions associated with that line.
5156 /// For IROrder, we keep the smaller of the two
5157 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, SDLoc OLoc) {
5158 DebugLoc NLoc = N->getDebugLoc();
5159 if (!(NLoc.isUnknown()) && (OptLevel == CodeGenOpt::None) &&
5160 (OLoc.getDebugLoc() != NLoc)) {
5161 N->setDebugLoc(DebugLoc());
5163 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
5164 N->setIROrder(Order);
5168 /// MorphNodeTo - This *mutates* the specified node to have the specified
5169 /// return type, opcode, and operands.
5171 /// Note that MorphNodeTo returns the resultant node. If there is already a
5172 /// node of the specified opcode and operands, it returns that node instead of
5173 /// the current one. Note that the SDLoc need not be the same.
5175 /// Using MorphNodeTo is faster than creating a new node and swapping it in
5176 /// with ReplaceAllUsesWith both because it often avoids allocating a new
5177 /// node, and because it doesn't require CSE recalculation for any of
5178 /// the node's users.
5180 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
5181 SDVTList VTs, const SDValue *Ops,
5183 // If an identical node already exists, use it.
5185 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
5186 FoldingSetNodeID ID;
5187 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
5188 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
5189 return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N));
5192 if (!RemoveNodeFromCSEMaps(N))
5195 // Start the morphing.
5197 N->ValueList = VTs.VTs;
5198 N->NumValues = VTs.NumVTs;
5200 // Clear the operands list, updating used nodes to remove this from their
5201 // use list. Keep track of any operands that become dead as a result.
5202 SmallPtrSet<SDNode*, 16> DeadNodeSet;
5203 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
5205 SDNode *Used = Use.getNode();
5207 if (Used->use_empty())
5208 DeadNodeSet.insert(Used);
5211 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
5212 // Initialize the memory references information.
5213 MN->setMemRefs(0, 0);
5214 // If NumOps is larger than the # of operands we can have in a
5215 // MachineSDNode, reallocate the operand list.
5216 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
5217 if (MN->OperandsNeedDelete)
5218 delete[] MN->OperandList;
5219 if (NumOps > array_lengthof(MN->LocalOperands))
5220 // We're creating a final node that will live unmorphed for the
5221 // remainder of the current SelectionDAG iteration, so we can allocate
5222 // the operands directly out of a pool with no recycling metadata.
5223 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5226 MN->InitOperands(MN->LocalOperands, Ops, NumOps);
5227 MN->OperandsNeedDelete = false;
5229 MN->InitOperands(MN->OperandList, Ops, NumOps);
5231 // If NumOps is larger than the # of operands we currently have, reallocate
5232 // the operand list.
5233 if (NumOps > N->NumOperands) {
5234 if (N->OperandsNeedDelete)
5235 delete[] N->OperandList;
5236 N->InitOperands(new SDUse[NumOps], Ops, NumOps);
5237 N->OperandsNeedDelete = true;
5239 N->InitOperands(N->OperandList, Ops, NumOps);
5242 // Delete any nodes that are still dead after adding the uses for the
5244 if (!DeadNodeSet.empty()) {
5245 SmallVector<SDNode *, 16> DeadNodes;
5246 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
5247 E = DeadNodeSet.end(); I != E; ++I)
5248 if ((*I)->use_empty())
5249 DeadNodes.push_back(*I);
5250 RemoveDeadNodes(DeadNodes);
5254 CSEMap.InsertNode(N, IP); // Memoize the new node.
5259 /// getMachineNode - These are used for target selectors to create a new node
5260 /// with specified return type(s), MachineInstr opcode, and operands.
5262 /// Note that getMachineNode returns the resultant node. If there is already a
5263 /// node of the specified opcode and operands, it returns that node instead of
5264 /// the current one.
5266 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT) {
5267 SDVTList VTs = getVTList(VT);
5268 return getMachineNode(Opcode, dl, VTs, None);
5272 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT, SDValue Op1) {
5273 SDVTList VTs = getVTList(VT);
5274 SDValue Ops[] = { Op1 };
5275 return getMachineNode(Opcode, dl, VTs, Ops);
5279 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5280 SDValue Op1, SDValue Op2) {
5281 SDVTList VTs = getVTList(VT);
5282 SDValue Ops[] = { Op1, Op2 };
5283 return getMachineNode(Opcode, dl, VTs, Ops);
5287 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5288 SDValue Op1, SDValue Op2, SDValue Op3) {
5289 SDVTList VTs = getVTList(VT);
5290 SDValue Ops[] = { Op1, Op2, Op3 };
5291 return getMachineNode(Opcode, dl, VTs, Ops);
5295 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT,
5296 ArrayRef<SDValue> Ops) {
5297 SDVTList VTs = getVTList(VT);
5298 return getMachineNode(Opcode, dl, VTs, Ops);
5302 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1, EVT VT2) {
5303 SDVTList VTs = getVTList(VT1, VT2);
5304 return getMachineNode(Opcode, dl, VTs, None);
5308 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5309 EVT VT1, EVT VT2, SDValue Op1) {
5310 SDVTList VTs = getVTList(VT1, VT2);
5311 SDValue Ops[] = { Op1 };
5312 return getMachineNode(Opcode, dl, VTs, Ops);
5316 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5317 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
5318 SDVTList VTs = getVTList(VT1, VT2);
5319 SDValue Ops[] = { Op1, Op2 };
5320 return getMachineNode(Opcode, dl, VTs, Ops);
5324 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5325 EVT VT1, EVT VT2, SDValue Op1,
5326 SDValue Op2, SDValue Op3) {
5327 SDVTList VTs = getVTList(VT1, VT2);
5328 SDValue Ops[] = { Op1, Op2, Op3 };
5329 return getMachineNode(Opcode, dl, VTs, Ops);
5333 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5335 ArrayRef<SDValue> Ops) {
5336 SDVTList VTs = getVTList(VT1, VT2);
5337 return getMachineNode(Opcode, dl, VTs, Ops);
5341 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5342 EVT VT1, EVT VT2, EVT VT3,
5343 SDValue Op1, SDValue Op2) {
5344 SDVTList VTs = getVTList(VT1, VT2, VT3);
5345 SDValue Ops[] = { Op1, Op2 };
5346 return getMachineNode(Opcode, dl, VTs, Ops);
5350 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5351 EVT VT1, EVT VT2, EVT VT3,
5352 SDValue Op1, SDValue Op2, SDValue Op3) {
5353 SDVTList VTs = getVTList(VT1, VT2, VT3);
5354 SDValue Ops[] = { Op1, Op2, Op3 };
5355 return getMachineNode(Opcode, dl, VTs, Ops);
5359 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5360 EVT VT1, EVT VT2, EVT VT3,
5361 ArrayRef<SDValue> Ops) {
5362 SDVTList VTs = getVTList(VT1, VT2, VT3);
5363 return getMachineNode(Opcode, dl, VTs, Ops);
5367 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl, EVT VT1,
5368 EVT VT2, EVT VT3, EVT VT4,
5369 ArrayRef<SDValue> Ops) {
5370 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5371 return getMachineNode(Opcode, dl, VTs, Ops);
5375 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc dl,
5376 ArrayRef<EVT> ResultTys,
5377 ArrayRef<SDValue> Ops) {
5378 SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
5379 return getMachineNode(Opcode, dl, VTs, Ops);
5383 SelectionDAG::getMachineNode(unsigned Opcode, SDLoc DL, SDVTList VTs,
5384 ArrayRef<SDValue> OpsArray) {
5385 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
5388 const SDValue *Ops = OpsArray.data();
5389 unsigned NumOps = OpsArray.size();
5392 FoldingSetNodeID ID;
5393 AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
5395 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5396 return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL));
5400 // Allocate a new MachineSDNode.
5401 N = new (NodeAllocator) MachineSDNode(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5403 // Initialize the operands list.
5404 if (NumOps > array_lengthof(N->LocalOperands))
5405 // We're creating a final node that will live unmorphed for the
5406 // remainder of the current SelectionDAG iteration, so we can allocate
5407 // the operands directly out of a pool with no recycling metadata.
5408 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5411 N->InitOperands(N->LocalOperands, Ops, NumOps);
5412 N->OperandsNeedDelete = false;
5415 CSEMap.InsertNode(N, IP);
5417 AllNodes.push_back(N);
5419 VerifyMachineNode(N);
5424 /// getTargetExtractSubreg - A convenience function for creating
5425 /// TargetOpcode::EXTRACT_SUBREG nodes.
5427 SelectionDAG::getTargetExtractSubreg(int SRIdx, SDLoc DL, EVT VT,
5429 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5430 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
5431 VT, Operand, SRIdxVal);
5432 return SDValue(Subreg, 0);
5435 /// getTargetInsertSubreg - A convenience function for creating
5436 /// TargetOpcode::INSERT_SUBREG nodes.
5438 SelectionDAG::getTargetInsertSubreg(int SRIdx, SDLoc DL, EVT VT,
5439 SDValue Operand, SDValue Subreg) {
5440 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5441 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
5442 VT, Operand, Subreg, SRIdxVal);
5443 return SDValue(Result, 0);
5446 /// getNodeIfExists - Get the specified node if it's already available, or
5447 /// else return NULL.
5448 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
5449 const SDValue *Ops, unsigned NumOps) {
5450 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5451 FoldingSetNodeID ID;
5452 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
5454 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5460 /// getDbgValue - Creates a SDDbgValue node.
5463 SelectionDAG::getDbgValue(MDNode *MDPtr, SDNode *N, unsigned R, uint64_t Off,
5464 DebugLoc DL, unsigned O) {
5465 return new (Allocator) SDDbgValue(MDPtr, N, R, Off, DL, O);
5469 SelectionDAG::getDbgValue(MDNode *MDPtr, const Value *C, uint64_t Off,
5470 DebugLoc DL, unsigned O) {
5471 return new (Allocator) SDDbgValue(MDPtr, C, Off, DL, O);
5475 SelectionDAG::getDbgValue(MDNode *MDPtr, unsigned FI, uint64_t Off,
5476 DebugLoc DL, unsigned O) {
5477 return new (Allocator) SDDbgValue(MDPtr, FI, Off, DL, O);
5482 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
5483 /// pointed to by a use iterator is deleted, increment the use iterator
5484 /// so that it doesn't dangle.
5486 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
5487 SDNode::use_iterator &UI;
5488 SDNode::use_iterator &UE;
5490 virtual void NodeDeleted(SDNode *N, SDNode *E) {
5491 // Increment the iterator as needed.
5492 while (UI != UE && N == *UI)
5497 RAUWUpdateListener(SelectionDAG &d,
5498 SDNode::use_iterator &ui,
5499 SDNode::use_iterator &ue)
5500 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
5505 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5506 /// This can cause recursive merging of nodes in the DAG.
5508 /// This version assumes From has a single result value.
5510 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
5511 SDNode *From = FromN.getNode();
5512 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
5513 "Cannot replace with this method!");
5514 assert(From != To.getNode() && "Cannot replace uses of with self");
5516 // Iterate over all the existing uses of From. New uses will be added
5517 // to the beginning of the use list, which we avoid visiting.
5518 // This specifically avoids visiting uses of From that arise while the
5519 // replacement is happening, because any such uses would be the result
5520 // of CSE: If an existing node looks like From after one of its operands
5521 // is replaced by To, we don't want to replace of all its users with To
5522 // too. See PR3018 for more info.
5523 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5524 RAUWUpdateListener Listener(*this, UI, UE);
5528 // This node is about to morph, remove its old self from the CSE maps.
5529 RemoveNodeFromCSEMaps(User);
5531 // A user can appear in a use list multiple times, and when this
5532 // happens the uses are usually next to each other in the list.
5533 // To help reduce the number of CSE recomputations, process all
5534 // the uses of this user that we can find this way.
5536 SDUse &Use = UI.getUse();
5539 } while (UI != UE && *UI == User);
5541 // Now that we have modified User, add it back to the CSE maps. If it
5542 // already exists there, recursively merge the results together.
5543 AddModifiedNodeToCSEMaps(User);
5546 // If we just RAUW'd the root, take note.
5547 if (FromN == getRoot())
5551 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5552 /// This can cause recursive merging of nodes in the DAG.
5554 /// This version assumes that for each value of From, there is a
5555 /// corresponding value in To in the same position with the same type.
5557 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
5559 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
5560 assert((!From->hasAnyUseOfValue(i) ||
5561 From->getValueType(i) == To->getValueType(i)) &&
5562 "Cannot use this version of ReplaceAllUsesWith!");
5565 // Handle the trivial case.
5569 // Iterate over just the existing users of From. See the comments in
5570 // the ReplaceAllUsesWith above.
5571 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5572 RAUWUpdateListener Listener(*this, UI, UE);
5576 // This node is about to morph, remove its old self from the CSE maps.
5577 RemoveNodeFromCSEMaps(User);
5579 // A user can appear in a use list multiple times, and when this
5580 // happens the uses are usually next to each other in the list.
5581 // To help reduce the number of CSE recomputations, process all
5582 // the uses of this user that we can find this way.
5584 SDUse &Use = UI.getUse();
5587 } while (UI != UE && *UI == User);
5589 // Now that we have modified User, add it back to the CSE maps. If it
5590 // already exists there, recursively merge the results together.
5591 AddModifiedNodeToCSEMaps(User);
5594 // If we just RAUW'd the root, take note.
5595 if (From == getRoot().getNode())
5596 setRoot(SDValue(To, getRoot().getResNo()));
5599 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5600 /// This can cause recursive merging of nodes in the DAG.
5602 /// This version can replace From with any result values. To must match the
5603 /// number and types of values returned by From.
5604 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
5605 if (From->getNumValues() == 1) // Handle the simple case efficiently.
5606 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
5608 // Iterate over just the existing users of From. See the comments in
5609 // the ReplaceAllUsesWith above.
5610 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5611 RAUWUpdateListener Listener(*this, UI, UE);
5615 // This node is about to morph, remove its old self from the CSE maps.
5616 RemoveNodeFromCSEMaps(User);
5618 // A user can appear in a use list multiple times, and when this
5619 // happens the uses are usually next to each other in the list.
5620 // To help reduce the number of CSE recomputations, process all
5621 // the uses of this user that we can find this way.
5623 SDUse &Use = UI.getUse();
5624 const SDValue &ToOp = To[Use.getResNo()];
5627 } while (UI != UE && *UI == User);
5629 // Now that we have modified User, add it back to the CSE maps. If it
5630 // already exists there, recursively merge the results together.
5631 AddModifiedNodeToCSEMaps(User);
5634 // If we just RAUW'd the root, take note.
5635 if (From == getRoot().getNode())
5636 setRoot(SDValue(To[getRoot().getResNo()]));
5639 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5640 /// uses of other values produced by From.getNode() alone. The Deleted
5641 /// vector is handled the same way as for ReplaceAllUsesWith.
5642 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
5643 // Handle the really simple, really trivial case efficiently.
5644 if (From == To) return;
5646 // Handle the simple, trivial, case efficiently.
5647 if (From.getNode()->getNumValues() == 1) {
5648 ReplaceAllUsesWith(From, To);
5652 // Iterate over just the existing users of From. See the comments in
5653 // the ReplaceAllUsesWith above.
5654 SDNode::use_iterator UI = From.getNode()->use_begin(),
5655 UE = From.getNode()->use_end();
5656 RAUWUpdateListener Listener(*this, UI, UE);
5659 bool UserRemovedFromCSEMaps = false;
5661 // A user can appear in a use list multiple times, and when this
5662 // happens the uses are usually next to each other in the list.
5663 // To help reduce the number of CSE recomputations, process all
5664 // the uses of this user that we can find this way.
5666 SDUse &Use = UI.getUse();
5668 // Skip uses of different values from the same node.
5669 if (Use.getResNo() != From.getResNo()) {
5674 // If this node hasn't been modified yet, it's still in the CSE maps,
5675 // so remove its old self from the CSE maps.
5676 if (!UserRemovedFromCSEMaps) {
5677 RemoveNodeFromCSEMaps(User);
5678 UserRemovedFromCSEMaps = true;
5683 } while (UI != UE && *UI == User);
5685 // We are iterating over all uses of the From node, so if a use
5686 // doesn't use the specific value, no changes are made.
5687 if (!UserRemovedFromCSEMaps)
5690 // Now that we have modified User, add it back to the CSE maps. If it
5691 // already exists there, recursively merge the results together.
5692 AddModifiedNodeToCSEMaps(User);
5695 // If we just RAUW'd the root, take note.
5696 if (From == getRoot())
5701 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5702 /// to record information about a use.
5709 /// operator< - Sort Memos by User.
5710 bool operator<(const UseMemo &L, const UseMemo &R) {
5711 return (intptr_t)L.User < (intptr_t)R.User;
5715 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5716 /// uses of other values produced by From.getNode() alone. The same value
5717 /// may appear in both the From and To list. The Deleted vector is
5718 /// handled the same way as for ReplaceAllUsesWith.
5719 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5722 // Handle the simple, trivial case efficiently.
5724 return ReplaceAllUsesOfValueWith(*From, *To);
5726 // Read up all the uses and make records of them. This helps
5727 // processing new uses that are introduced during the
5728 // replacement process.
5729 SmallVector<UseMemo, 4> Uses;
5730 for (unsigned i = 0; i != Num; ++i) {
5731 unsigned FromResNo = From[i].getResNo();
5732 SDNode *FromNode = From[i].getNode();
5733 for (SDNode::use_iterator UI = FromNode->use_begin(),
5734 E = FromNode->use_end(); UI != E; ++UI) {
5735 SDUse &Use = UI.getUse();
5736 if (Use.getResNo() == FromResNo) {
5737 UseMemo Memo = { *UI, i, &Use };
5738 Uses.push_back(Memo);
5743 // Sort the uses, so that all the uses from a given User are together.
5744 std::sort(Uses.begin(), Uses.end());
5746 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5747 UseIndex != UseIndexEnd; ) {
5748 // We know that this user uses some value of From. If it is the right
5749 // value, update it.
5750 SDNode *User = Uses[UseIndex].User;
5752 // This node is about to morph, remove its old self from the CSE maps.
5753 RemoveNodeFromCSEMaps(User);
5755 // The Uses array is sorted, so all the uses for a given User
5756 // are next to each other in the list.
5757 // To help reduce the number of CSE recomputations, process all
5758 // the uses of this user that we can find this way.
5760 unsigned i = Uses[UseIndex].Index;
5761 SDUse &Use = *Uses[UseIndex].Use;
5765 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5767 // Now that we have modified User, add it back to the CSE maps. If it
5768 // already exists there, recursively merge the results together.
5769 AddModifiedNodeToCSEMaps(User);
5773 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5774 /// based on their topological order. It returns the maximum id and a vector
5775 /// of the SDNodes* in assigned order by reference.
5776 unsigned SelectionDAG::AssignTopologicalOrder() {
5778 unsigned DAGSize = 0;
5780 // SortedPos tracks the progress of the algorithm. Nodes before it are
5781 // sorted, nodes after it are unsorted. When the algorithm completes
5782 // it is at the end of the list.
5783 allnodes_iterator SortedPos = allnodes_begin();
5785 // Visit all the nodes. Move nodes with no operands to the front of
5786 // the list immediately. Annotate nodes that do have operands with their
5787 // operand count. Before we do this, the Node Id fields of the nodes
5788 // may contain arbitrary values. After, the Node Id fields for nodes
5789 // before SortedPos will contain the topological sort index, and the
5790 // Node Id fields for nodes At SortedPos and after will contain the
5791 // count of outstanding operands.
5792 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5795 unsigned Degree = N->getNumOperands();
5797 // A node with no uses, add it to the result array immediately.
5798 N->setNodeId(DAGSize++);
5799 allnodes_iterator Q = N;
5801 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5802 assert(SortedPos != AllNodes.end() && "Overran node list");
5805 // Temporarily use the Node Id as scratch space for the degree count.
5806 N->setNodeId(Degree);
5810 // Visit all the nodes. As we iterate, move nodes into sorted order,
5811 // such that by the time the end is reached all nodes will be sorted.
5812 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5815 // N is in sorted position, so all its uses have one less operand
5816 // that needs to be sorted.
5817 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5820 unsigned Degree = P->getNodeId();
5821 assert(Degree != 0 && "Invalid node degree");
5824 // All of P's operands are sorted, so P may sorted now.
5825 P->setNodeId(DAGSize++);
5827 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5828 assert(SortedPos != AllNodes.end() && "Overran node list");
5831 // Update P's outstanding operand count.
5832 P->setNodeId(Degree);
5835 if (I == SortedPos) {
5838 dbgs() << "Overran sorted position:\n";
5841 llvm_unreachable(0);
5845 assert(SortedPos == AllNodes.end() &&
5846 "Topological sort incomplete!");
5847 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5848 "First node in topological sort is not the entry token!");
5849 assert(AllNodes.front().getNodeId() == 0 &&
5850 "First node in topological sort has non-zero id!");
5851 assert(AllNodes.front().getNumOperands() == 0 &&
5852 "First node in topological sort has operands!");
5853 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5854 "Last node in topologic sort has unexpected id!");
5855 assert(AllNodes.back().use_empty() &&
5856 "Last node in topologic sort has users!");
5857 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5861 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
5862 /// value is produced by SD.
5863 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
5864 DbgInfo->add(DB, SD, isParameter);
5866 SD->setHasDebugValue(true);
5869 /// TransferDbgValues - Transfer SDDbgValues.
5870 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
5871 if (From == To || !From.getNode()->getHasDebugValue())
5873 SDNode *FromNode = From.getNode();
5874 SDNode *ToNode = To.getNode();
5875 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
5876 SmallVector<SDDbgValue *, 2> ClonedDVs;
5877 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
5879 SDDbgValue *Dbg = *I;
5880 if (Dbg->getKind() == SDDbgValue::SDNODE) {
5881 SDDbgValue *Clone = getDbgValue(Dbg->getMDPtr(), ToNode, To.getResNo(),
5882 Dbg->getOffset(), Dbg->getDebugLoc(),
5884 ClonedDVs.push_back(Clone);
5887 for (SmallVector<SDDbgValue *, 2>::iterator I = ClonedDVs.begin(),
5888 E = ClonedDVs.end(); I != E; ++I)
5889 AddDbgValue(*I, ToNode, false);
5892 //===----------------------------------------------------------------------===//
5894 //===----------------------------------------------------------------------===//
5896 HandleSDNode::~HandleSDNode() {
5900 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
5901 DebugLoc DL, const GlobalValue *GA,
5902 EVT VT, int64_t o, unsigned char TF)
5903 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
5907 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
5908 EVT memvt, MachineMemOperand *mmo)
5909 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5910 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5911 MMO->isNonTemporal(), MMO->isInvariant());
5912 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5913 assert(isNonTemporal() == MMO->isNonTemporal() &&
5914 "Non-temporal encoding error!");
5915 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5918 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs,
5919 const SDValue *Ops, unsigned NumOps, EVT memvt,
5920 MachineMemOperand *mmo)
5921 : SDNode(Opc, Order, dl, VTs, Ops, NumOps),
5922 MemoryVT(memvt), MMO(mmo) {
5923 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5924 MMO->isNonTemporal(), MMO->isInvariant());
5925 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5926 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5929 /// Profile - Gather unique data for the node.
5931 void SDNode::Profile(FoldingSetNodeID &ID) const {
5932 AddNodeIDNode(ID, this);
5937 std::vector<EVT> VTs;
5940 VTs.reserve(MVT::LAST_VALUETYPE);
5941 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5942 VTs.push_back(MVT((MVT::SimpleValueType)i));
5947 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5948 static ManagedStatic<EVTArray> SimpleVTArray;
5949 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5951 /// getValueTypeList - Return a pointer to the specified value type.
5953 const EVT *SDNode::getValueTypeList(EVT VT) {
5954 if (VT.isExtended()) {
5955 sys::SmartScopedLock<true> Lock(*VTMutex);
5956 return &(*EVTs->insert(VT).first);
5958 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
5959 "Value type out of range!");
5960 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5964 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5965 /// indicated value. This method ignores uses of other values defined by this
5967 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5968 assert(Value < getNumValues() && "Bad value!");
5970 // TODO: Only iterate over uses of a given value of the node
5971 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5972 if (UI.getUse().getResNo() == Value) {
5979 // Found exactly the right number of uses?
5984 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5985 /// value. This method ignores uses of other values defined by this operation.
5986 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5987 assert(Value < getNumValues() && "Bad value!");
5989 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5990 if (UI.getUse().getResNo() == Value)
5997 /// isOnlyUserOf - Return true if this node is the only use of N.
5999 bool SDNode::isOnlyUserOf(SDNode *N) const {
6001 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
6012 /// isOperand - Return true if this node is an operand of N.
6014 bool SDValue::isOperandOf(SDNode *N) const {
6015 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6016 if (*this == N->getOperand(i))
6021 bool SDNode::isOperandOf(SDNode *N) const {
6022 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
6023 if (this == N->OperandList[i].getNode())
6028 /// reachesChainWithoutSideEffects - Return true if this operand (which must
6029 /// be a chain) reaches the specified operand without crossing any
6030 /// side-effecting instructions on any chain path. In practice, this looks
6031 /// through token factors and non-volatile loads. In order to remain efficient,
6032 /// this only looks a couple of nodes in, it does not do an exhaustive search.
6033 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
6034 unsigned Depth) const {
6035 if (*this == Dest) return true;
6037 // Don't search too deeply, we just want to be able to see through
6038 // TokenFactor's etc.
6039 if (Depth == 0) return false;
6041 // If this is a token factor, all inputs to the TF happen in parallel. If any
6042 // of the operands of the TF does not reach dest, then we cannot do the xform.
6043 if (getOpcode() == ISD::TokenFactor) {
6044 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
6045 if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
6050 // Loads don't have side effects, look through them.
6051 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
6052 if (!Ld->isVolatile())
6053 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
6058 /// hasPredecessor - Return true if N is a predecessor of this node.
6059 /// N is either an operand of this node, or can be reached by recursively
6060 /// traversing up the operands.
6061 /// NOTE: This is an expensive method. Use it carefully.
6062 bool SDNode::hasPredecessor(const SDNode *N) const {
6063 SmallPtrSet<const SDNode *, 32> Visited;
6064 SmallVector<const SDNode *, 16> Worklist;
6065 return hasPredecessorHelper(N, Visited, Worklist);
6068 bool SDNode::hasPredecessorHelper(const SDNode *N,
6069 SmallPtrSet<const SDNode *, 32> &Visited,
6070 SmallVector<const SDNode *, 16> &Worklist) const {
6071 if (Visited.empty()) {
6072 Worklist.push_back(this);
6074 // Take a look in the visited set. If we've already encountered this node
6075 // we needn't search further.
6076 if (Visited.count(N))
6080 // Haven't visited N yet. Continue the search.
6081 while (!Worklist.empty()) {
6082 const SDNode *M = Worklist.pop_back_val();
6083 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
6084 SDNode *Op = M->getOperand(i).getNode();
6085 if (Visited.insert(Op))
6086 Worklist.push_back(Op);
6095 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
6096 assert(Num < NumOperands && "Invalid child # of SDNode!");
6097 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
6100 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6101 assert(N->getNumValues() == 1 &&
6102 "Can't unroll a vector with multiple results!");
6104 EVT VT = N->getValueType(0);
6105 unsigned NE = VT.getVectorNumElements();
6106 EVT EltVT = VT.getVectorElementType();
6109 SmallVector<SDValue, 8> Scalars;
6110 SmallVector<SDValue, 4> Operands(N->getNumOperands());
6112 // If ResNE is 0, fully unroll the vector op.
6115 else if (NE > ResNE)
6119 for (i= 0; i != NE; ++i) {
6120 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
6121 SDValue Operand = N->getOperand(j);
6122 EVT OperandVT = Operand.getValueType();
6123 if (OperandVT.isVector()) {
6124 // A vector operand; extract a single element.
6125 EVT OperandEltVT = OperandVT.getVectorElementType();
6126 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6129 getConstant(i, TLI.getPointerTy()));
6131 // A scalar operand; just use it as is.
6132 Operands[j] = Operand;
6136 switch (N->getOpcode()) {
6138 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6139 &Operands[0], Operands.size()));
6142 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT,
6143 &Operands[0], Operands.size()));
6150 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6151 getShiftAmountOperand(Operands[0].getValueType(),
6154 case ISD::SIGN_EXTEND_INREG:
6155 case ISD::FP_ROUND_INREG: {
6156 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6157 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6159 getValueType(ExtVT)));
6164 for (; i < ResNE; ++i)
6165 Scalars.push_back(getUNDEF(EltVT));
6167 return getNode(ISD::BUILD_VECTOR, dl,
6168 EVT::getVectorVT(*getContext(), EltVT, ResNE),
6169 &Scalars[0], Scalars.size());
6173 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6174 /// location that is 'Dist' units away from the location that the 'Base' load
6175 /// is loading from.
6176 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6177 unsigned Bytes, int Dist) const {
6178 if (LD->getChain() != Base->getChain())
6180 EVT VT = LD->getValueType(0);
6181 if (VT.getSizeInBits() / 8 != Bytes)
6184 SDValue Loc = LD->getOperand(1);
6185 SDValue BaseLoc = Base->getOperand(1);
6186 if (Loc.getOpcode() == ISD::FrameIndex) {
6187 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6189 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6190 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6191 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6192 int FS = MFI->getObjectSize(FI);
6193 int BFS = MFI->getObjectSize(BFI);
6194 if (FS != BFS || FS != (int)Bytes) return false;
6195 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6199 if (isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
6200 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
6203 const GlobalValue *GV1 = NULL;
6204 const GlobalValue *GV2 = NULL;
6205 int64_t Offset1 = 0;
6206 int64_t Offset2 = 0;
6207 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6208 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6209 if (isGA1 && isGA2 && GV1 == GV2)
6210 return Offset1 == (Offset2 + Dist*Bytes);
6215 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6216 /// it cannot be inferred.
6217 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6218 // If this is a GlobalAddress + cst, return the alignment.
6219 const GlobalValue *GV;
6220 int64_t GVOffset = 0;
6221 if (TLI.isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
6222 unsigned PtrWidth = TLI.getPointerTy().getSizeInBits();
6223 APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
6224 llvm::ComputeMaskedBits(const_cast<GlobalValue*>(GV), KnownZero, KnownOne,
6225 TLI.getDataLayout());
6226 unsigned AlignBits = KnownZero.countTrailingOnes();
6227 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
6229 return MinAlign(Align, GVOffset);
6232 // If this is a direct reference to a stack slot, use information about the
6233 // stack slot's alignment.
6234 int FrameIdx = 1 << 31;
6235 int64_t FrameOffset = 0;
6236 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6237 FrameIdx = FI->getIndex();
6238 } else if (isBaseWithConstantOffset(Ptr) &&
6239 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6241 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6242 FrameOffset = Ptr.getConstantOperandVal(1);
6245 if (FrameIdx != (1 << 31)) {
6246 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6247 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6255 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6256 unsigned GlobalAddressSDNode::getAddressSpace() const {
6257 return getGlobal()->getType()->getAddressSpace();
6261 Type *ConstantPoolSDNode::getType() const {
6262 if (isMachineConstantPoolEntry())
6263 return Val.MachineCPVal->getType();
6264 return Val.ConstVal->getType();
6267 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6269 unsigned &SplatBitSize,
6271 unsigned MinSplatBits,
6273 EVT VT = getValueType(0);
6274 assert(VT.isVector() && "Expected a vector type");
6275 unsigned sz = VT.getSizeInBits();
6276 if (MinSplatBits > sz)
6279 SplatValue = APInt(sz, 0);
6280 SplatUndef = APInt(sz, 0);
6282 // Get the bits. Bits with undefined values (when the corresponding element
6283 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6284 // in SplatValue. If any of the values are not constant, give up and return
6286 unsigned int nOps = getNumOperands();
6287 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6288 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6290 for (unsigned j = 0; j < nOps; ++j) {
6291 unsigned i = isBigEndian ? nOps-1-j : j;
6292 SDValue OpVal = getOperand(i);
6293 unsigned BitPos = j * EltBitSize;
6295 if (OpVal.getOpcode() == ISD::UNDEF)
6296 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6297 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6298 SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize).
6299 zextOrTrunc(sz) << BitPos;
6300 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6301 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6306 // The build_vector is all constants or undefs. Find the smallest element
6307 // size that splats the vector.
6309 HasAnyUndefs = (SplatUndef != 0);
6312 unsigned HalfSize = sz / 2;
6313 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
6314 APInt LowValue = SplatValue.trunc(HalfSize);
6315 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
6316 APInt LowUndef = SplatUndef.trunc(HalfSize);
6318 // If the two halves do not match (ignoring undef bits), stop here.
6319 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6320 MinSplatBits > HalfSize)
6323 SplatValue = HighValue | LowValue;
6324 SplatUndef = HighUndef & LowUndef;
6333 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6334 // Find the first non-undef value in the shuffle mask.
6336 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6339 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6341 // Make sure all remaining elements are either undef or the same as the first
6343 for (int Idx = Mask[i]; i != e; ++i)
6344 if (Mask[i] >= 0 && Mask[i] != Idx)
6350 static void checkForCyclesHelper(const SDNode *N,
6351 SmallPtrSet<const SDNode*, 32> &Visited,
6352 SmallPtrSet<const SDNode*, 32> &Checked) {
6353 // If this node has already been checked, don't check it again.
6354 if (Checked.count(N))
6357 // If a node has already been visited on this depth-first walk, reject it as
6359 if (!Visited.insert(N)) {
6360 dbgs() << "Offending node:\n";
6362 errs() << "Detected cycle in SelectionDAG\n";
6366 for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6367 checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked);
6374 void llvm::checkForCycles(const llvm::SDNode *N) {
6376 assert(N && "Checking nonexistant SDNode");
6377 SmallPtrSet<const SDNode*, 32> visited;
6378 SmallPtrSet<const SDNode*, 32> checked;
6379 checkForCyclesHelper(N, visited, checked);
6383 void llvm::checkForCycles(const llvm::SelectionDAG *DAG) {
6384 checkForCycles(DAG->getRoot().getNode());