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 "SDNodeOrdering.h"
16 #include "SDNodeDbgValue.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Analysis/DebugInfo.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalAlias.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetSelectionDAGInfo.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetIntrinsicInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/ManagedStatic.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Support/Mutex.h"
46 #include "llvm/ADT/SetVector.h"
47 #include "llvm/ADT/SmallPtrSet.h"
48 #include "llvm/ADT/SmallSet.h"
49 #include "llvm/ADT/SmallVector.h"
50 #include "llvm/ADT/StringExtras.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 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
63 switch (VT.getSimpleVT().SimpleTy) {
64 default: llvm_unreachable("Unknown FP format");
65 case MVT::f32: return &APFloat::IEEEsingle;
66 case MVT::f64: return &APFloat::IEEEdouble;
67 case MVT::f80: return &APFloat::x87DoubleExtended;
68 case MVT::f128: return &APFloat::IEEEquad;
69 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
73 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
75 //===----------------------------------------------------------------------===//
76 // ConstantFPSDNode Class
77 //===----------------------------------------------------------------------===//
79 /// isExactlyValue - We don't rely on operator== working on double values, as
80 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
81 /// As such, this method can be used to do an exact bit-for-bit comparison of
82 /// two floating point values.
83 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
84 return getValueAPF().bitwiseIsEqual(V);
87 bool ConstantFPSDNode::isValueValidForType(EVT VT,
89 assert(VT.isFloatingPoint() && "Can only convert between FP types");
91 // PPC long double cannot be converted to any other type.
92 if (VT == MVT::ppcf128 ||
93 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
96 // convert modifies in place, so make a copy.
97 APFloat Val2 = APFloat(Val);
99 (void) Val2.convert(*EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
104 //===----------------------------------------------------------------------===//
106 //===----------------------------------------------------------------------===//
108 /// isBuildVectorAllOnes - Return true if the specified node is a
109 /// BUILD_VECTOR where all of the elements are ~0 or undef.
110 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
111 // Look through a bit convert.
112 if (N->getOpcode() == ISD::BITCAST)
113 N = N->getOperand(0).getNode();
115 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
117 unsigned i = 0, e = N->getNumOperands();
119 // Skip over all of the undef values.
120 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
123 // Do not accept an all-undef vector.
124 if (i == e) return false;
126 // Do not accept build_vectors that aren't all constants or which have non-~0
128 SDValue NotZero = N->getOperand(i);
129 if (isa<ConstantSDNode>(NotZero)) {
130 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
132 } else if (isa<ConstantFPSDNode>(NotZero)) {
133 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
134 bitcastToAPInt().isAllOnesValue())
139 // Okay, we have at least one ~0 value, check to see if the rest match or are
141 for (++i; i != e; ++i)
142 if (N->getOperand(i) != NotZero &&
143 N->getOperand(i).getOpcode() != ISD::UNDEF)
149 /// isBuildVectorAllZeros - Return true if the specified node is a
150 /// BUILD_VECTOR where all of the elements are 0 or undef.
151 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
152 // Look through a bit convert.
153 if (N->getOpcode() == ISD::BITCAST)
154 N = N->getOperand(0).getNode();
156 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
158 unsigned i = 0, e = N->getNumOperands();
160 // Skip over all of the undef values.
161 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
164 // Do not accept an all-undef vector.
165 if (i == e) return false;
167 // Do not accept build_vectors that aren't all constants or which have non-0
169 SDValue Zero = N->getOperand(i);
170 if (isa<ConstantSDNode>(Zero)) {
171 if (!cast<ConstantSDNode>(Zero)->isNullValue())
173 } else if (isa<ConstantFPSDNode>(Zero)) {
174 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
179 // Okay, we have at least one 0 value, check to see if the rest match or are
181 for (++i; i != e; ++i)
182 if (N->getOperand(i) != Zero &&
183 N->getOperand(i).getOpcode() != ISD::UNDEF)
188 /// isScalarToVector - Return true if the specified node is a
189 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
190 /// element is not an undef.
191 bool ISD::isScalarToVector(const SDNode *N) {
192 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
195 if (N->getOpcode() != ISD::BUILD_VECTOR)
197 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
199 unsigned NumElems = N->getNumOperands();
202 for (unsigned i = 1; i < NumElems; ++i) {
203 SDValue V = N->getOperand(i);
204 if (V.getOpcode() != ISD::UNDEF)
210 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
211 /// when given the operation for (X op Y).
212 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
213 // To perform this operation, we just need to swap the L and G bits of the
215 unsigned OldL = (Operation >> 2) & 1;
216 unsigned OldG = (Operation >> 1) & 1;
217 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
218 (OldL << 1) | // New G bit
219 (OldG << 2)); // New L bit.
222 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
223 /// 'op' is a valid SetCC operation.
224 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
225 unsigned Operation = Op;
227 Operation ^= 7; // Flip L, G, E bits, but not U.
229 Operation ^= 15; // Flip all of the condition bits.
231 if (Operation > ISD::SETTRUE2)
232 Operation &= ~8; // Don't let N and U bits get set.
234 return ISD::CondCode(Operation);
238 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
239 /// signed operation and 2 if the result is an unsigned comparison. Return zero
240 /// if the operation does not depend on the sign of the input (setne and seteq).
241 static int isSignedOp(ISD::CondCode Opcode) {
243 default: llvm_unreachable("Illegal integer setcc operation!");
245 case ISD::SETNE: return 0;
249 case ISD::SETGE: return 1;
253 case ISD::SETUGE: return 2;
257 /// getSetCCOrOperation - Return the result of a logical OR between different
258 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
259 /// returns SETCC_INVALID if it is not possible to represent the resultant
261 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
263 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
264 // Cannot fold a signed integer setcc with an unsigned integer setcc.
265 return ISD::SETCC_INVALID;
267 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
269 // If the N and U bits get set then the resultant comparison DOES suddenly
270 // care about orderedness, and is true when ordered.
271 if (Op > ISD::SETTRUE2)
272 Op &= ~16; // Clear the U bit if the N bit is set.
274 // Canonicalize illegal integer setcc's.
275 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
278 return ISD::CondCode(Op);
281 /// getSetCCAndOperation - Return the result of a logical AND between different
282 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
283 /// function returns zero if it is not possible to represent the resultant
285 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
287 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
288 // Cannot fold a signed setcc with an unsigned setcc.
289 return ISD::SETCC_INVALID;
291 // Combine all of the condition bits.
292 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
294 // Canonicalize illegal integer setcc's.
298 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
299 case ISD::SETOEQ: // SETEQ & SETU[LG]E
300 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
301 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
302 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
309 //===----------------------------------------------------------------------===//
310 // SDNode Profile Support
311 //===----------------------------------------------------------------------===//
313 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
315 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
319 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
320 /// solely with their pointer.
321 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
322 ID.AddPointer(VTList.VTs);
325 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
327 static void AddNodeIDOperands(FoldingSetNodeID &ID,
328 const SDValue *Ops, unsigned NumOps) {
329 for (; NumOps; --NumOps, ++Ops) {
330 ID.AddPointer(Ops->getNode());
331 ID.AddInteger(Ops->getResNo());
335 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
337 static void AddNodeIDOperands(FoldingSetNodeID &ID,
338 const SDUse *Ops, unsigned NumOps) {
339 for (; NumOps; --NumOps, ++Ops) {
340 ID.AddPointer(Ops->getNode());
341 ID.AddInteger(Ops->getResNo());
345 static void AddNodeIDNode(FoldingSetNodeID &ID,
346 unsigned short OpC, SDVTList VTList,
347 const SDValue *OpList, unsigned N) {
348 AddNodeIDOpcode(ID, OpC);
349 AddNodeIDValueTypes(ID, VTList);
350 AddNodeIDOperands(ID, OpList, N);
353 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
355 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
356 switch (N->getOpcode()) {
357 case ISD::TargetExternalSymbol:
358 case ISD::ExternalSymbol:
359 llvm_unreachable("Should only be used on nodes with operands");
360 default: break; // Normal nodes don't need extra info.
361 case ISD::TargetConstant:
363 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
365 case ISD::TargetConstantFP:
366 case ISD::ConstantFP: {
367 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
370 case ISD::TargetGlobalAddress:
371 case ISD::GlobalAddress:
372 case ISD::TargetGlobalTLSAddress:
373 case ISD::GlobalTLSAddress: {
374 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
375 ID.AddPointer(GA->getGlobal());
376 ID.AddInteger(GA->getOffset());
377 ID.AddInteger(GA->getTargetFlags());
380 case ISD::BasicBlock:
381 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
384 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
386 case ISD::RegisterMask:
387 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
390 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
392 case ISD::FrameIndex:
393 case ISD::TargetFrameIndex:
394 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
397 case ISD::TargetJumpTable:
398 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
399 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
401 case ISD::ConstantPool:
402 case ISD::TargetConstantPool: {
403 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
404 ID.AddInteger(CP->getAlignment());
405 ID.AddInteger(CP->getOffset());
406 if (CP->isMachineConstantPoolEntry())
407 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
409 ID.AddPointer(CP->getConstVal());
410 ID.AddInteger(CP->getTargetFlags());
414 const LoadSDNode *LD = cast<LoadSDNode>(N);
415 ID.AddInteger(LD->getMemoryVT().getRawBits());
416 ID.AddInteger(LD->getRawSubclassData());
420 const StoreSDNode *ST = cast<StoreSDNode>(N);
421 ID.AddInteger(ST->getMemoryVT().getRawBits());
422 ID.AddInteger(ST->getRawSubclassData());
425 case ISD::ATOMIC_CMP_SWAP:
426 case ISD::ATOMIC_SWAP:
427 case ISD::ATOMIC_LOAD_ADD:
428 case ISD::ATOMIC_LOAD_SUB:
429 case ISD::ATOMIC_LOAD_AND:
430 case ISD::ATOMIC_LOAD_OR:
431 case ISD::ATOMIC_LOAD_XOR:
432 case ISD::ATOMIC_LOAD_NAND:
433 case ISD::ATOMIC_LOAD_MIN:
434 case ISD::ATOMIC_LOAD_MAX:
435 case ISD::ATOMIC_LOAD_UMIN:
436 case ISD::ATOMIC_LOAD_UMAX:
437 case ISD::ATOMIC_LOAD:
438 case ISD::ATOMIC_STORE: {
439 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
440 ID.AddInteger(AT->getMemoryVT().getRawBits());
441 ID.AddInteger(AT->getRawSubclassData());
444 case ISD::VECTOR_SHUFFLE: {
445 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
446 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
448 ID.AddInteger(SVN->getMaskElt(i));
451 case ISD::TargetBlockAddress:
452 case ISD::BlockAddress: {
453 ID.AddPointer(cast<BlockAddressSDNode>(N)->getBlockAddress());
454 ID.AddInteger(cast<BlockAddressSDNode>(N)->getTargetFlags());
457 } // end switch (N->getOpcode())
460 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
462 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
463 AddNodeIDOpcode(ID, N->getOpcode());
464 // Add the return value info.
465 AddNodeIDValueTypes(ID, N->getVTList());
466 // Add the operand info.
467 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
469 // Handle SDNode leafs with special info.
470 AddNodeIDCustom(ID, N);
473 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
474 /// the CSE map that carries volatility, temporalness, indexing mode, and
475 /// extension/truncation information.
477 static inline unsigned
478 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile,
479 bool isNonTemporal, bool isInvariant) {
480 assert((ConvType & 3) == ConvType &&
481 "ConvType may not require more than 2 bits!");
482 assert((AM & 7) == AM &&
483 "AM may not require more than 3 bits!");
487 (isNonTemporal << 6) |
491 //===----------------------------------------------------------------------===//
492 // SelectionDAG Class
493 //===----------------------------------------------------------------------===//
495 /// doNotCSE - Return true if CSE should not be performed for this node.
496 static bool doNotCSE(SDNode *N) {
497 if (N->getValueType(0) == MVT::Glue)
498 return true; // Never CSE anything that produces a flag.
500 switch (N->getOpcode()) {
502 case ISD::HANDLENODE:
504 return true; // Never CSE these nodes.
507 // Check that remaining values produced are not flags.
508 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
509 if (N->getValueType(i) == MVT::Glue)
510 return true; // Never CSE anything that produces a flag.
515 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
517 void SelectionDAG::RemoveDeadNodes() {
518 // Create a dummy node (which is not added to allnodes), that adds a reference
519 // to the root node, preventing it from being deleted.
520 HandleSDNode Dummy(getRoot());
522 SmallVector<SDNode*, 128> DeadNodes;
524 // Add all obviously-dead nodes to the DeadNodes worklist.
525 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
527 DeadNodes.push_back(I);
529 RemoveDeadNodes(DeadNodes);
531 // If the root changed (e.g. it was a dead load, update the root).
532 setRoot(Dummy.getValue());
535 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
536 /// given list, and any nodes that become unreachable as a result.
537 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
538 DAGUpdateListener *UpdateListener) {
540 // Process the worklist, deleting the nodes and adding their uses to the
542 while (!DeadNodes.empty()) {
543 SDNode *N = DeadNodes.pop_back_val();
546 UpdateListener->NodeDeleted(N, 0);
548 // Take the node out of the appropriate CSE map.
549 RemoveNodeFromCSEMaps(N);
551 // Next, brutally remove the operand list. This is safe to do, as there are
552 // no cycles in the graph.
553 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
555 SDNode *Operand = Use.getNode();
558 // Now that we removed this operand, see if there are no uses of it left.
559 if (Operand->use_empty())
560 DeadNodes.push_back(Operand);
567 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
568 SmallVector<SDNode*, 16> DeadNodes(1, N);
570 // Create a dummy node that adds a reference to the root node, preventing
571 // it from being deleted. (This matters if the root is an operand of the
573 HandleSDNode Dummy(getRoot());
575 RemoveDeadNodes(DeadNodes, UpdateListener);
578 void SelectionDAG::DeleteNode(SDNode *N) {
579 // First take this out of the appropriate CSE map.
580 RemoveNodeFromCSEMaps(N);
582 // Finally, remove uses due to operands of this node, remove from the
583 // AllNodes list, and delete the node.
584 DeleteNodeNotInCSEMaps(N);
587 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
588 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
589 assert(N->use_empty() && "Cannot delete a node that is not dead!");
591 // Drop all of the operands and decrement used node's use counts.
597 void SelectionDAG::DeallocateNode(SDNode *N) {
598 if (N->OperandsNeedDelete)
599 delete[] N->OperandList;
601 // Set the opcode to DELETED_NODE to help catch bugs when node
602 // memory is reallocated.
603 N->NodeType = ISD::DELETED_NODE;
605 NodeAllocator.Deallocate(AllNodes.remove(N));
607 // Remove the ordering of this node.
610 // If any of the SDDbgValue nodes refer to this SDNode, invalidate them.
611 ArrayRef<SDDbgValue*> DbgVals = DbgInfo->getSDDbgValues(N);
612 for (unsigned i = 0, e = DbgVals.size(); i != e; ++i)
613 DbgVals[i]->setIsInvalidated();
616 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
617 /// correspond to it. This is useful when we're about to delete or repurpose
618 /// the node. We don't want future request for structurally identical nodes
619 /// to return N anymore.
620 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
622 switch (N->getOpcode()) {
623 case ISD::HANDLENODE: return false; // noop.
625 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
626 "Cond code doesn't exist!");
627 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
628 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
630 case ISD::ExternalSymbol:
631 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
633 case ISD::TargetExternalSymbol: {
634 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
635 Erased = TargetExternalSymbols.erase(
636 std::pair<std::string,unsigned char>(ESN->getSymbol(),
637 ESN->getTargetFlags()));
640 case ISD::VALUETYPE: {
641 EVT VT = cast<VTSDNode>(N)->getVT();
642 if (VT.isExtended()) {
643 Erased = ExtendedValueTypeNodes.erase(VT);
645 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
646 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
651 // Remove it from the CSE Map.
652 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
653 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
654 Erased = CSEMap.RemoveNode(N);
658 // Verify that the node was actually in one of the CSE maps, unless it has a
659 // flag result (which cannot be CSE'd) or is one of the special cases that are
660 // not subject to CSE.
661 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
662 !N->isMachineOpcode() && !doNotCSE(N)) {
665 llvm_unreachable("Node is not in map!");
671 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
672 /// maps and modified in place. Add it back to the CSE maps, unless an identical
673 /// node already exists, in which case transfer all its users to the existing
674 /// node. This transfer can potentially trigger recursive merging.
677 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
678 DAGUpdateListener *UpdateListener) {
679 // For node types that aren't CSE'd, just act as if no identical node
682 SDNode *Existing = CSEMap.GetOrInsertNode(N);
684 // If there was already an existing matching node, use ReplaceAllUsesWith
685 // to replace the dead one with the existing one. This can cause
686 // recursive merging of other unrelated nodes down the line.
687 ReplaceAllUsesWith(N, Existing, UpdateListener);
689 // N is now dead. Inform the listener if it exists and delete it.
691 UpdateListener->NodeDeleted(N, Existing);
692 DeleteNodeNotInCSEMaps(N);
697 // If the node doesn't already exist, we updated it. Inform a listener if
700 UpdateListener->NodeUpdated(N);
703 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
704 /// were replaced with those specified. If this node is never memoized,
705 /// return null, otherwise return a pointer to the slot it would take. If a
706 /// node already exists with these operands, the slot will be non-null.
707 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
712 SDValue Ops[] = { Op };
714 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
715 AddNodeIDCustom(ID, N);
716 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
720 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
721 /// were replaced with those specified. If this node is never memoized,
722 /// return null, otherwise return a pointer to the slot it would take. If a
723 /// node already exists with these operands, the slot will be non-null.
724 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
725 SDValue Op1, SDValue Op2,
730 SDValue Ops[] = { Op1, Op2 };
732 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
733 AddNodeIDCustom(ID, N);
734 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
739 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
740 /// were replaced with those specified. If this node is never memoized,
741 /// return null, otherwise return a pointer to the slot it would take. If a
742 /// node already exists with these operands, the slot will be non-null.
743 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
744 const SDValue *Ops,unsigned NumOps,
750 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
751 AddNodeIDCustom(ID, N);
752 SDNode *Node = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
757 /// VerifyNodeCommon - Sanity check the given node. Aborts if it is invalid.
758 static void VerifyNodeCommon(SDNode *N) {
759 switch (N->getOpcode()) {
762 case ISD::BUILD_PAIR: {
763 EVT VT = N->getValueType(0);
764 assert(N->getNumValues() == 1 && "Too many results!");
765 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
766 "Wrong return type!");
767 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
768 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
769 "Mismatched operand types!");
770 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
771 "Wrong operand type!");
772 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
773 "Wrong return type size");
776 case ISD::BUILD_VECTOR: {
777 assert(N->getNumValues() == 1 && "Too many results!");
778 assert(N->getValueType(0).isVector() && "Wrong return type!");
779 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
780 "Wrong number of operands!");
781 EVT EltVT = N->getValueType(0).getVectorElementType();
782 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
783 assert((I->getValueType() == EltVT ||
784 (EltVT.isInteger() && I->getValueType().isInteger() &&
785 EltVT.bitsLE(I->getValueType()))) &&
786 "Wrong operand type!");
787 assert(I->getValueType() == N->getOperand(0).getValueType() &&
788 "Operands must all have the same type");
795 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid.
796 static void VerifySDNode(SDNode *N) {
797 // The SDNode allocators cannot be used to allocate nodes with fields that are
798 // not present in an SDNode!
799 assert(!isa<MemSDNode>(N) && "Bad MemSDNode!");
800 assert(!isa<ShuffleVectorSDNode>(N) && "Bad ShuffleVectorSDNode!");
801 assert(!isa<ConstantSDNode>(N) && "Bad ConstantSDNode!");
802 assert(!isa<ConstantFPSDNode>(N) && "Bad ConstantFPSDNode!");
803 assert(!isa<GlobalAddressSDNode>(N) && "Bad GlobalAddressSDNode!");
804 assert(!isa<FrameIndexSDNode>(N) && "Bad FrameIndexSDNode!");
805 assert(!isa<JumpTableSDNode>(N) && "Bad JumpTableSDNode!");
806 assert(!isa<ConstantPoolSDNode>(N) && "Bad ConstantPoolSDNode!");
807 assert(!isa<BasicBlockSDNode>(N) && "Bad BasicBlockSDNode!");
808 assert(!isa<SrcValueSDNode>(N) && "Bad SrcValueSDNode!");
809 assert(!isa<MDNodeSDNode>(N) && "Bad MDNodeSDNode!");
810 assert(!isa<RegisterSDNode>(N) && "Bad RegisterSDNode!");
811 assert(!isa<BlockAddressSDNode>(N) && "Bad BlockAddressSDNode!");
812 assert(!isa<EHLabelSDNode>(N) && "Bad EHLabelSDNode!");
813 assert(!isa<ExternalSymbolSDNode>(N) && "Bad ExternalSymbolSDNode!");
814 assert(!isa<CondCodeSDNode>(N) && "Bad CondCodeSDNode!");
815 assert(!isa<CvtRndSatSDNode>(N) && "Bad CvtRndSatSDNode!");
816 assert(!isa<VTSDNode>(N) && "Bad VTSDNode!");
817 assert(!isa<MachineSDNode>(N) && "Bad MachineSDNode!");
822 /// VerifyMachineNode - Sanity check the given MachineNode. Aborts if it is
824 static void VerifyMachineNode(SDNode *N) {
825 // The MachineNode allocators cannot be used to allocate nodes with fields
826 // that are not present in a MachineNode!
827 // Currently there are no such nodes.
833 /// getEVTAlignment - Compute the default alignment value for the
836 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
837 Type *Ty = VT == MVT::iPTR ?
838 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
839 VT.getTypeForEVT(*getContext());
841 return TLI.getTargetData()->getABITypeAlignment(Ty);
844 // EntryNode could meaningfully have debug info if we can find it...
845 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
846 : TM(tm), TLI(*tm.getTargetLowering()), TSI(*tm.getSelectionDAGInfo()),
847 OptLevel(OL), EntryNode(ISD::EntryToken, DebugLoc(), getVTList(MVT::Other)),
848 Root(getEntryNode()), Ordering(0) {
849 AllNodes.push_back(&EntryNode);
850 Ordering = new SDNodeOrdering();
851 DbgInfo = new SDDbgInfo();
854 void SelectionDAG::init(MachineFunction &mf) {
856 Context = &mf.getFunction()->getContext();
859 SelectionDAG::~SelectionDAG() {
865 void SelectionDAG::allnodes_clear() {
866 assert(&*AllNodes.begin() == &EntryNode);
867 AllNodes.remove(AllNodes.begin());
868 while (!AllNodes.empty())
869 DeallocateNode(AllNodes.begin());
872 void SelectionDAG::clear() {
874 OperandAllocator.Reset();
877 ExtendedValueTypeNodes.clear();
878 ExternalSymbols.clear();
879 TargetExternalSymbols.clear();
880 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
881 static_cast<CondCodeSDNode*>(0));
882 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
883 static_cast<SDNode*>(0));
885 EntryNode.UseList = 0;
886 AllNodes.push_back(&EntryNode);
887 Root = getEntryNode();
892 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
893 return VT.bitsGT(Op.getValueType()) ?
894 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
895 getNode(ISD::TRUNCATE, DL, VT, Op);
898 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
899 return VT.bitsGT(Op.getValueType()) ?
900 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
901 getNode(ISD::TRUNCATE, DL, VT, Op);
904 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
905 return VT.bitsGT(Op.getValueType()) ?
906 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
907 getNode(ISD::TRUNCATE, DL, VT, Op);
910 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, EVT VT) {
911 assert(!VT.isVector() &&
912 "getZeroExtendInReg should use the vector element type instead of "
914 if (Op.getValueType() == VT) return Op;
915 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
916 APInt Imm = APInt::getLowBitsSet(BitWidth,
918 return getNode(ISD::AND, DL, Op.getValueType(), Op,
919 getConstant(Imm, Op.getValueType()));
922 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
924 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, EVT VT) {
925 EVT EltVT = VT.getScalarType();
927 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
928 return getNode(ISD::XOR, DL, VT, Val, NegOne);
931 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
932 EVT EltVT = VT.getScalarType();
933 assert((EltVT.getSizeInBits() >= 64 ||
934 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
935 "getConstant with a uint64_t value that doesn't fit in the type!");
936 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
939 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
940 return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
943 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
944 assert(VT.isInteger() && "Cannot create FP integer constant!");
946 EVT EltVT = VT.getScalarType();
947 const ConstantInt *Elt = &Val;
949 // In some cases the vector type is legal but the element type is illegal and
950 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
951 // inserted value (the type does not need to match the vector element type).
952 // Any extra bits introduced will be truncated away.
953 if (VT.isVector() && TLI.getTypeAction(*getContext(), EltVT) ==
954 TargetLowering::TypePromoteInteger) {
955 EltVT = TLI.getTypeToTransformTo(*getContext(), EltVT);
956 APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits());
957 Elt = ConstantInt::get(*getContext(), NewVal);
960 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
961 "APInt size does not match type size!");
962 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
964 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
968 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
970 return SDValue(N, 0);
973 N = new (NodeAllocator) ConstantSDNode(isT, Elt, EltVT);
974 CSEMap.InsertNode(N, IP);
975 AllNodes.push_back(N);
978 SDValue Result(N, 0);
980 SmallVector<SDValue, 8> Ops;
981 Ops.assign(VT.getVectorNumElements(), Result);
982 Result = getNode(ISD::BUILD_VECTOR, DebugLoc(), VT, &Ops[0], Ops.size());
987 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
988 return getConstant(Val, TLI.getPointerTy(), isTarget);
992 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
993 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
996 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
997 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
999 EVT EltVT = VT.getScalarType();
1001 // Do the map lookup using the actual bit pattern for the floating point
1002 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1003 // we don't have issues with SNANs.
1004 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1005 FoldingSetNodeID ID;
1006 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
1010 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
1012 return SDValue(N, 0);
1015 N = new (NodeAllocator) ConstantFPSDNode(isTarget, &V, EltVT);
1016 CSEMap.InsertNode(N, IP);
1017 AllNodes.push_back(N);
1020 SDValue Result(N, 0);
1021 if (VT.isVector()) {
1022 SmallVector<SDValue, 8> Ops;
1023 Ops.assign(VT.getVectorNumElements(), Result);
1024 // FIXME DebugLoc info might be appropriate here
1025 Result = getNode(ISD::BUILD_VECTOR, DebugLoc(), VT, &Ops[0], Ops.size());
1030 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
1031 EVT EltVT = VT.getScalarType();
1032 if (EltVT==MVT::f32)
1033 return getConstantFP(APFloat((float)Val), VT, isTarget);
1034 else if (EltVT==MVT::f64)
1035 return getConstantFP(APFloat(Val), VT, isTarget);
1036 else if (EltVT==MVT::f80 || EltVT==MVT::f128) {
1038 APFloat apf = APFloat(Val);
1039 apf.convert(*EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1041 return getConstantFP(apf, VT, isTarget);
1043 assert(0 && "Unsupported type in getConstantFP");
1048 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, DebugLoc DL,
1049 EVT VT, int64_t Offset,
1051 unsigned char TargetFlags) {
1052 assert((TargetFlags == 0 || isTargetGA) &&
1053 "Cannot set target flags on target-independent globals");
1055 // Truncate (with sign-extension) the offset value to the pointer size.
1056 EVT PTy = TLI.getPointerTy();
1057 unsigned BitWidth = PTy.getSizeInBits();
1059 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
1061 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1063 // If GV is an alias then use the aliasee for determining thread-localness.
1064 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
1065 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
1069 if (GVar && GVar->isThreadLocal())
1070 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1072 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1074 FoldingSetNodeID ID;
1075 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1077 ID.AddInteger(Offset);
1078 ID.AddInteger(TargetFlags);
1080 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1081 return SDValue(E, 0);
1083 SDNode *N = new (NodeAllocator) GlobalAddressSDNode(Opc, DL, GV, VT,
1084 Offset, TargetFlags);
1085 CSEMap.InsertNode(N, IP);
1086 AllNodes.push_back(N);
1087 return SDValue(N, 0);
1090 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1091 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1092 FoldingSetNodeID ID;
1093 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1096 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1097 return SDValue(E, 0);
1099 SDNode *N = new (NodeAllocator) FrameIndexSDNode(FI, VT, isTarget);
1100 CSEMap.InsertNode(N, IP);
1101 AllNodes.push_back(N);
1102 return SDValue(N, 0);
1105 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1106 unsigned char TargetFlags) {
1107 assert((TargetFlags == 0 || isTarget) &&
1108 "Cannot set target flags on target-independent jump tables");
1109 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1110 FoldingSetNodeID ID;
1111 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1113 ID.AddInteger(TargetFlags);
1115 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1116 return SDValue(E, 0);
1118 SDNode *N = new (NodeAllocator) JumpTableSDNode(JTI, VT, isTarget,
1120 CSEMap.InsertNode(N, IP);
1121 AllNodes.push_back(N);
1122 return SDValue(N, 0);
1125 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1126 unsigned Alignment, int Offset,
1128 unsigned char TargetFlags) {
1129 assert((TargetFlags == 0 || isTarget) &&
1130 "Cannot set target flags on target-independent globals");
1132 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1133 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1134 FoldingSetNodeID ID;
1135 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1136 ID.AddInteger(Alignment);
1137 ID.AddInteger(Offset);
1139 ID.AddInteger(TargetFlags);
1141 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1142 return SDValue(E, 0);
1144 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1145 Alignment, TargetFlags);
1146 CSEMap.InsertNode(N, IP);
1147 AllNodes.push_back(N);
1148 return SDValue(N, 0);
1152 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1153 unsigned Alignment, int Offset,
1155 unsigned char TargetFlags) {
1156 assert((TargetFlags == 0 || isTarget) &&
1157 "Cannot set target flags on target-independent globals");
1159 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1160 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1161 FoldingSetNodeID ID;
1162 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1163 ID.AddInteger(Alignment);
1164 ID.AddInteger(Offset);
1165 C->addSelectionDAGCSEId(ID);
1166 ID.AddInteger(TargetFlags);
1168 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1169 return SDValue(E, 0);
1171 SDNode *N = new (NodeAllocator) ConstantPoolSDNode(isTarget, C, VT, Offset,
1172 Alignment, TargetFlags);
1173 CSEMap.InsertNode(N, IP);
1174 AllNodes.push_back(N);
1175 return SDValue(N, 0);
1178 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1179 FoldingSetNodeID ID;
1180 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1183 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1184 return SDValue(E, 0);
1186 SDNode *N = new (NodeAllocator) BasicBlockSDNode(MBB);
1187 CSEMap.InsertNode(N, IP);
1188 AllNodes.push_back(N);
1189 return SDValue(N, 0);
1192 SDValue SelectionDAG::getValueType(EVT VT) {
1193 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1194 ValueTypeNodes.size())
1195 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1197 SDNode *&N = VT.isExtended() ?
1198 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1200 if (N) return SDValue(N, 0);
1201 N = new (NodeAllocator) VTSDNode(VT);
1202 AllNodes.push_back(N);
1203 return SDValue(N, 0);
1206 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1207 SDNode *&N = ExternalSymbols[Sym];
1208 if (N) return SDValue(N, 0);
1209 N = new (NodeAllocator) ExternalSymbolSDNode(false, Sym, 0, VT);
1210 AllNodes.push_back(N);
1211 return SDValue(N, 0);
1214 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1215 unsigned char TargetFlags) {
1217 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1219 if (N) return SDValue(N, 0);
1220 N = new (NodeAllocator) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1221 AllNodes.push_back(N);
1222 return SDValue(N, 0);
1225 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1226 if ((unsigned)Cond >= CondCodeNodes.size())
1227 CondCodeNodes.resize(Cond+1);
1229 if (CondCodeNodes[Cond] == 0) {
1230 CondCodeSDNode *N = new (NodeAllocator) CondCodeSDNode(Cond);
1231 CondCodeNodes[Cond] = N;
1232 AllNodes.push_back(N);
1235 return SDValue(CondCodeNodes[Cond], 0);
1238 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1239 // the shuffle mask M that point at N1 to point at N2, and indices that point
1240 // N2 to point at N1.
1241 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1243 int NElts = M.size();
1244 for (int i = 0; i != NElts; ++i) {
1252 SDValue SelectionDAG::getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1,
1253 SDValue N2, const int *Mask) {
1254 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1255 assert(VT.isVector() && N1.getValueType().isVector() &&
1256 "Vector Shuffle VTs must be a vectors");
1257 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1258 && "Vector Shuffle VTs must have same element type");
1260 // Canonicalize shuffle undef, undef -> undef
1261 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1262 return getUNDEF(VT);
1264 // Validate that all indices in Mask are within the range of the elements
1265 // input to the shuffle.
1266 unsigned NElts = VT.getVectorNumElements();
1267 SmallVector<int, 8> MaskVec;
1268 for (unsigned i = 0; i != NElts; ++i) {
1269 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1270 MaskVec.push_back(Mask[i]);
1273 // Canonicalize shuffle v, v -> v, undef
1276 for (unsigned i = 0; i != NElts; ++i)
1277 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1280 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1281 if (N1.getOpcode() == ISD::UNDEF)
1282 commuteShuffle(N1, N2, MaskVec);
1284 // Canonicalize all index into lhs, -> shuffle lhs, undef
1285 // Canonicalize all index into rhs, -> shuffle rhs, undef
1286 bool AllLHS = true, AllRHS = true;
1287 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1288 for (unsigned i = 0; i != NElts; ++i) {
1289 if (MaskVec[i] >= (int)NElts) {
1294 } else if (MaskVec[i] >= 0) {
1298 if (AllLHS && AllRHS)
1299 return getUNDEF(VT);
1300 if (AllLHS && !N2Undef)
1304 commuteShuffle(N1, N2, MaskVec);
1307 // If Identity shuffle, or all shuffle in to undef, return that node.
1308 bool AllUndef = true;
1309 bool Identity = true;
1310 for (unsigned i = 0; i != NElts; ++i) {
1311 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1312 if (MaskVec[i] >= 0) AllUndef = false;
1314 if (Identity && NElts == N1.getValueType().getVectorNumElements())
1317 return getUNDEF(VT);
1319 FoldingSetNodeID ID;
1320 SDValue Ops[2] = { N1, N2 };
1321 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1322 for (unsigned i = 0; i != NElts; ++i)
1323 ID.AddInteger(MaskVec[i]);
1326 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1327 return SDValue(E, 0);
1329 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1330 // SDNode doesn't have access to it. This memory will be "leaked" when
1331 // the node is deallocated, but recovered when the NodeAllocator is released.
1332 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1333 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1335 ShuffleVectorSDNode *N =
1336 new (NodeAllocator) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
1337 CSEMap.InsertNode(N, IP);
1338 AllNodes.push_back(N);
1339 return SDValue(N, 0);
1342 SDValue SelectionDAG::getConvertRndSat(EVT VT, DebugLoc dl,
1343 SDValue Val, SDValue DTy,
1344 SDValue STy, SDValue Rnd, SDValue Sat,
1345 ISD::CvtCode Code) {
1346 // If the src and dest types are the same and the conversion is between
1347 // integer types of the same sign or two floats, no conversion is necessary.
1349 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1352 FoldingSetNodeID ID;
1353 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1354 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5);
1356 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1357 return SDValue(E, 0);
1359 CvtRndSatSDNode *N = new (NodeAllocator) CvtRndSatSDNode(VT, dl, Ops, 5,
1361 CSEMap.InsertNode(N, IP);
1362 AllNodes.push_back(N);
1363 return SDValue(N, 0);
1366 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1367 FoldingSetNodeID ID;
1368 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1369 ID.AddInteger(RegNo);
1371 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1372 return SDValue(E, 0);
1374 SDNode *N = new (NodeAllocator) RegisterSDNode(RegNo, VT);
1375 CSEMap.InsertNode(N, IP);
1376 AllNodes.push_back(N);
1377 return SDValue(N, 0);
1380 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1381 FoldingSetNodeID ID;
1382 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), 0, 0);
1383 ID.AddPointer(RegMask);
1385 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1386 return SDValue(E, 0);
1388 SDNode *N = new (NodeAllocator) RegisterMaskSDNode(RegMask);
1389 CSEMap.InsertNode(N, IP);
1390 AllNodes.push_back(N);
1391 return SDValue(N, 0);
1394 SDValue SelectionDAG::getEHLabel(DebugLoc dl, SDValue Root, MCSymbol *Label) {
1395 FoldingSetNodeID ID;
1396 SDValue Ops[] = { Root };
1397 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), &Ops[0], 1);
1398 ID.AddPointer(Label);
1400 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1401 return SDValue(E, 0);
1403 SDNode *N = new (NodeAllocator) EHLabelSDNode(dl, Root, Label);
1404 CSEMap.InsertNode(N, IP);
1405 AllNodes.push_back(N);
1406 return SDValue(N, 0);
1410 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1412 unsigned char TargetFlags) {
1413 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1415 FoldingSetNodeID ID;
1416 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1418 ID.AddInteger(TargetFlags);
1420 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1421 return SDValue(E, 0);
1423 SDNode *N = new (NodeAllocator) BlockAddressSDNode(Opc, VT, BA, TargetFlags);
1424 CSEMap.InsertNode(N, IP);
1425 AllNodes.push_back(N);
1426 return SDValue(N, 0);
1429 SDValue SelectionDAG::getSrcValue(const Value *V) {
1430 assert((!V || V->getType()->isPointerTy()) &&
1431 "SrcValue is not a pointer?");
1433 FoldingSetNodeID ID;
1434 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1438 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1439 return SDValue(E, 0);
1441 SDNode *N = new (NodeAllocator) SrcValueSDNode(V);
1442 CSEMap.InsertNode(N, IP);
1443 AllNodes.push_back(N);
1444 return SDValue(N, 0);
1447 /// getMDNode - Return an MDNodeSDNode which holds an MDNode.
1448 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1449 FoldingSetNodeID ID;
1450 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), 0, 0);
1454 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1455 return SDValue(E, 0);
1457 SDNode *N = new (NodeAllocator) MDNodeSDNode(MD);
1458 CSEMap.InsertNode(N, IP);
1459 AllNodes.push_back(N);
1460 return SDValue(N, 0);
1464 /// getShiftAmountOperand - Return the specified value casted to
1465 /// the target's desired shift amount type.
1466 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1467 EVT OpTy = Op.getValueType();
1468 MVT ShTy = TLI.getShiftAmountTy(LHSTy);
1469 if (OpTy == ShTy || OpTy.isVector()) return Op;
1471 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1472 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
1475 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1476 /// specified value type.
1477 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1478 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1479 unsigned ByteSize = VT.getStoreSize();
1480 Type *Ty = VT.getTypeForEVT(*getContext());
1481 unsigned StackAlign =
1482 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1484 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1485 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1488 /// CreateStackTemporary - Create a stack temporary suitable for holding
1489 /// either of the specified value types.
1490 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1491 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1492 VT2.getStoreSizeInBits())/8;
1493 Type *Ty1 = VT1.getTypeForEVT(*getContext());
1494 Type *Ty2 = VT2.getTypeForEVT(*getContext());
1495 const TargetData *TD = TLI.getTargetData();
1496 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1497 TD->getPrefTypeAlignment(Ty2));
1499 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1500 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1501 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1504 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1505 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1506 // These setcc operations always fold.
1510 case ISD::SETFALSE2: return getConstant(0, VT);
1512 case ISD::SETTRUE2: return getConstant(1, VT);
1524 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1528 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1529 const APInt &C2 = N2C->getAPIntValue();
1530 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1531 const APInt &C1 = N1C->getAPIntValue();
1534 default: llvm_unreachable("Unknown integer setcc!");
1535 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1536 case ISD::SETNE: return getConstant(C1 != C2, VT);
1537 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1538 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1539 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1540 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1541 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1542 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1543 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1544 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1548 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1549 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1550 // No compile time operations on this type yet.
1551 if (N1C->getValueType(0) == MVT::ppcf128)
1554 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1557 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1558 return getUNDEF(VT);
1560 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1561 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1562 return getUNDEF(VT);
1564 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1565 R==APFloat::cmpLessThan, VT);
1566 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1567 return getUNDEF(VT);
1569 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1570 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1571 return getUNDEF(VT);
1573 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1574 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1575 return getUNDEF(VT);
1577 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1578 R==APFloat::cmpEqual, VT);
1579 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1580 return getUNDEF(VT);
1582 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1583 R==APFloat::cmpEqual, VT);
1584 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1585 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1586 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1587 R==APFloat::cmpEqual, VT);
1588 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1589 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1590 R==APFloat::cmpLessThan, VT);
1591 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1592 R==APFloat::cmpUnordered, VT);
1593 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1594 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1597 // Ensure that the constant occurs on the RHS.
1598 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1602 // Could not fold it.
1606 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1607 /// use this predicate to simplify operations downstream.
1608 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1609 // This predicate is not safe for vector operations.
1610 if (Op.getValueType().isVector())
1613 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
1614 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1617 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1618 /// this predicate to simplify operations downstream. Mask is known to be zero
1619 /// for bits that V cannot have.
1620 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1621 unsigned Depth) const {
1622 APInt KnownZero, KnownOne;
1623 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1624 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1625 return (KnownZero & Mask) == Mask;
1628 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1629 /// known to be either zero or one and return them in the KnownZero/KnownOne
1630 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1632 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1633 APInt &KnownZero, APInt &KnownOne,
1634 unsigned Depth) const {
1635 unsigned BitWidth = Mask.getBitWidth();
1636 assert(BitWidth == Op.getValueType().getScalarType().getSizeInBits() &&
1637 "Mask size mismatches value type size!");
1639 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1640 if (Depth == 6 || Mask == 0)
1641 return; // Limit search depth.
1643 APInt KnownZero2, KnownOne2;
1645 switch (Op.getOpcode()) {
1647 // We know all of the bits for a constant!
1648 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1649 KnownZero = ~KnownOne & Mask;
1652 // If either the LHS or the RHS are Zero, the result is zero.
1653 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1654 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1655 KnownZero2, KnownOne2, Depth+1);
1656 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1657 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1659 // Output known-1 bits are only known if set in both the LHS & RHS.
1660 KnownOne &= KnownOne2;
1661 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1662 KnownZero |= KnownZero2;
1665 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1666 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1667 KnownZero2, KnownOne2, Depth+1);
1668 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1669 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1671 // Output known-0 bits are only known if clear in both the LHS & RHS.
1672 KnownZero &= KnownZero2;
1673 // Output known-1 are known to be set if set in either the LHS | RHS.
1674 KnownOne |= KnownOne2;
1677 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1678 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1679 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1680 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1682 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1683 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1684 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1685 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1686 KnownZero = KnownZeroOut;
1690 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1691 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1692 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1693 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1694 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1696 // If low bits are zero in either operand, output low known-0 bits.
1697 // Also compute a conserative estimate for high known-0 bits.
1698 // More trickiness is possible, but this is sufficient for the
1699 // interesting case of alignment computation.
1700 KnownOne.clearAllBits();
1701 unsigned TrailZ = KnownZero.countTrailingOnes() +
1702 KnownZero2.countTrailingOnes();
1703 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1704 KnownZero2.countLeadingOnes(),
1705 BitWidth) - BitWidth;
1707 TrailZ = std::min(TrailZ, BitWidth);
1708 LeadZ = std::min(LeadZ, BitWidth);
1709 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1710 APInt::getHighBitsSet(BitWidth, LeadZ);
1715 // For the purposes of computing leading zeros we can conservatively
1716 // treat a udiv as a logical right shift by the power of 2 known to
1717 // be less than the denominator.
1718 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1719 ComputeMaskedBits(Op.getOperand(0),
1720 AllOnes, KnownZero2, KnownOne2, Depth+1);
1721 unsigned LeadZ = KnownZero2.countLeadingOnes();
1723 KnownOne2.clearAllBits();
1724 KnownZero2.clearAllBits();
1725 ComputeMaskedBits(Op.getOperand(1),
1726 AllOnes, KnownZero2, KnownOne2, Depth+1);
1727 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1728 if (RHSUnknownLeadingOnes != BitWidth)
1729 LeadZ = std::min(BitWidth,
1730 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1732 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1736 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1737 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1738 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1739 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1741 // Only known if known in both the LHS and RHS.
1742 KnownOne &= KnownOne2;
1743 KnownZero &= KnownZero2;
1745 case ISD::SELECT_CC:
1746 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1747 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1748 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1749 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1751 // Only known if known in both the LHS and RHS.
1752 KnownOne &= KnownOne2;
1753 KnownZero &= KnownZero2;
1761 if (Op.getResNo() != 1)
1763 // The boolean result conforms to getBooleanContents. Fall through.
1765 // If we know the result of a setcc has the top bits zero, use this info.
1766 if (TLI.getBooleanContents(Op.getValueType().isVector()) ==
1767 TargetLowering::ZeroOrOneBooleanContent && BitWidth > 1)
1768 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1771 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1772 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1773 unsigned ShAmt = SA->getZExtValue();
1775 // If the shift count is an invalid immediate, don't do anything.
1776 if (ShAmt >= BitWidth)
1779 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1780 KnownZero, KnownOne, Depth+1);
1781 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1782 KnownZero <<= ShAmt;
1784 // low bits known zero.
1785 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1789 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1790 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1791 unsigned ShAmt = SA->getZExtValue();
1793 // If the shift count is an invalid immediate, don't do anything.
1794 if (ShAmt >= BitWidth)
1797 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1798 KnownZero, KnownOne, Depth+1);
1799 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1800 KnownZero = KnownZero.lshr(ShAmt);
1801 KnownOne = KnownOne.lshr(ShAmt);
1803 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1804 KnownZero |= HighBits; // High bits known zero.
1808 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1809 unsigned ShAmt = SA->getZExtValue();
1811 // If the shift count is an invalid immediate, don't do anything.
1812 if (ShAmt >= BitWidth)
1815 APInt InDemandedMask = (Mask << ShAmt);
1816 // If any of the demanded bits are produced by the sign extension, we also
1817 // demand the input sign bit.
1818 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1819 if (HighBits.getBoolValue())
1820 InDemandedMask |= APInt::getSignBit(BitWidth);
1822 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1824 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1825 KnownZero = KnownZero.lshr(ShAmt);
1826 KnownOne = KnownOne.lshr(ShAmt);
1828 // Handle the sign bits.
1829 APInt SignBit = APInt::getSignBit(BitWidth);
1830 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1832 if (KnownZero.intersects(SignBit)) {
1833 KnownZero |= HighBits; // New bits are known zero.
1834 } else if (KnownOne.intersects(SignBit)) {
1835 KnownOne |= HighBits; // New bits are known one.
1839 case ISD::SIGN_EXTEND_INREG: {
1840 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1841 unsigned EBits = EVT.getScalarType().getSizeInBits();
1843 // Sign extension. Compute the demanded bits in the result that are not
1844 // present in the input.
1845 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1847 APInt InSignBit = APInt::getSignBit(EBits);
1848 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1850 // If the sign extended bits are demanded, we know that the sign
1852 InSignBit = InSignBit.zext(BitWidth);
1853 if (NewBits.getBoolValue())
1854 InputDemandedBits |= InSignBit;
1856 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1857 KnownZero, KnownOne, Depth+1);
1858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1860 // If the sign bit of the input is known set or clear, then we know the
1861 // top bits of the result.
1862 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1863 KnownZero |= NewBits;
1864 KnownOne &= ~NewBits;
1865 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1866 KnownOne |= NewBits;
1867 KnownZero &= ~NewBits;
1868 } else { // Input sign bit unknown
1869 KnownZero &= ~NewBits;
1870 KnownOne &= ~NewBits;
1875 case ISD::CTTZ_ZERO_UNDEF:
1877 case ISD::CTLZ_ZERO_UNDEF:
1879 unsigned LowBits = Log2_32(BitWidth)+1;
1880 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1881 KnownOne.clearAllBits();
1885 if (ISD::isZEXTLoad(Op.getNode())) {
1886 LoadSDNode *LD = cast<LoadSDNode>(Op);
1887 EVT VT = LD->getMemoryVT();
1888 unsigned MemBits = VT.getScalarType().getSizeInBits();
1889 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1893 case ISD::ZERO_EXTEND: {
1894 EVT InVT = Op.getOperand(0).getValueType();
1895 unsigned InBits = InVT.getScalarType().getSizeInBits();
1896 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1897 APInt InMask = Mask.trunc(InBits);
1898 KnownZero = KnownZero.trunc(InBits);
1899 KnownOne = KnownOne.trunc(InBits);
1900 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1901 KnownZero = KnownZero.zext(BitWidth);
1902 KnownOne = KnownOne.zext(BitWidth);
1903 KnownZero |= NewBits;
1906 case ISD::SIGN_EXTEND: {
1907 EVT InVT = Op.getOperand(0).getValueType();
1908 unsigned InBits = InVT.getScalarType().getSizeInBits();
1909 APInt InSignBit = APInt::getSignBit(InBits);
1910 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1911 APInt InMask = Mask.trunc(InBits);
1913 // If any of the sign extended bits are demanded, we know that the sign
1914 // bit is demanded. Temporarily set this bit in the mask for our callee.
1915 if (NewBits.getBoolValue())
1916 InMask |= InSignBit;
1918 KnownZero = KnownZero.trunc(InBits);
1919 KnownOne = KnownOne.trunc(InBits);
1920 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1922 // Note if the sign bit is known to be zero or one.
1923 bool SignBitKnownZero = KnownZero.isNegative();
1924 bool SignBitKnownOne = KnownOne.isNegative();
1925 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1926 "Sign bit can't be known to be both zero and one!");
1928 // If the sign bit wasn't actually demanded by our caller, we don't
1929 // want it set in the KnownZero and KnownOne result values. Reset the
1930 // mask and reapply it to the result values.
1931 InMask = Mask.trunc(InBits);
1932 KnownZero &= InMask;
1935 KnownZero = KnownZero.zext(BitWidth);
1936 KnownOne = KnownOne.zext(BitWidth);
1938 // If the sign bit is known zero or one, the top bits match.
1939 if (SignBitKnownZero)
1940 KnownZero |= NewBits;
1941 else if (SignBitKnownOne)
1942 KnownOne |= NewBits;
1945 case ISD::ANY_EXTEND: {
1946 EVT InVT = Op.getOperand(0).getValueType();
1947 unsigned InBits = InVT.getScalarType().getSizeInBits();
1948 APInt InMask = Mask.trunc(InBits);
1949 KnownZero = KnownZero.trunc(InBits);
1950 KnownOne = KnownOne.trunc(InBits);
1951 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1952 KnownZero = KnownZero.zext(BitWidth);
1953 KnownOne = KnownOne.zext(BitWidth);
1956 case ISD::TRUNCATE: {
1957 EVT InVT = Op.getOperand(0).getValueType();
1958 unsigned InBits = InVT.getScalarType().getSizeInBits();
1959 APInt InMask = Mask.zext(InBits);
1960 KnownZero = KnownZero.zext(InBits);
1961 KnownOne = KnownOne.zext(InBits);
1962 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1963 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1964 KnownZero = KnownZero.trunc(BitWidth);
1965 KnownOne = KnownOne.trunc(BitWidth);
1968 case ISD::AssertZext: {
1969 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1970 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1971 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1973 KnownZero |= (~InMask) & Mask;
1977 // All bits are zero except the low bit.
1978 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1982 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1983 // We know that the top bits of C-X are clear if X contains less bits
1984 // than C (i.e. no wrap-around can happen). For example, 20-X is
1985 // positive if we can prove that X is >= 0 and < 16.
1986 if (CLHS->getAPIntValue().isNonNegative()) {
1987 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1988 // NLZ can't be BitWidth with no sign bit
1989 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1990 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1993 // If all of the MaskV bits are known to be zero, then we know the
1994 // output top bits are zero, because we now know that the output is
1996 if ((KnownZero2 & MaskV) == MaskV) {
1997 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1998 // Top bits known zero.
1999 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
2007 // Output known-0 bits are known if clear or set in both the low clear bits
2008 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
2009 // low 3 bits clear.
2010 APInt Mask2 = APInt::getLowBitsSet(BitWidth,
2011 BitWidth - Mask.countLeadingZeros());
2012 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
2013 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
2014 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
2016 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
2017 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
2018 KnownZeroOut = std::min(KnownZeroOut,
2019 KnownZero2.countTrailingOnes());
2021 if (Op.getOpcode() == ISD::ADD) {
2022 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
2026 // With ADDE, a carry bit may be added in, so we can only use this
2027 // information if we know (at least) that the low two bits are clear. We
2028 // then return to the caller that the low bit is unknown but that other bits
2030 if (KnownZeroOut >= 2) // ADDE
2031 KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroOut);
2035 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2036 const APInt &RA = Rem->getAPIntValue().abs();
2037 if (RA.isPowerOf2()) {
2038 APInt LowBits = RA - 1;
2039 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
2040 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
2042 // The low bits of the first operand are unchanged by the srem.
2043 KnownZero = KnownZero2 & LowBits;
2044 KnownOne = KnownOne2 & LowBits;
2046 // If the first operand is non-negative or has all low bits zero, then
2047 // the upper bits are all zero.
2048 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2049 KnownZero |= ~LowBits;
2051 // If the first operand is negative and not all low bits are zero, then
2052 // the upper bits are all one.
2053 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2054 KnownOne |= ~LowBits;
2059 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2064 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2065 const APInt &RA = Rem->getAPIntValue();
2066 if (RA.isPowerOf2()) {
2067 APInt LowBits = (RA - 1);
2068 APInt Mask2 = LowBits & Mask;
2069 KnownZero |= ~LowBits & Mask;
2070 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
2071 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2076 // Since the result is less than or equal to either operand, any leading
2077 // zero bits in either operand must also exist in the result.
2078 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2079 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
2081 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
2084 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2085 KnownZero2.countLeadingOnes());
2086 KnownOne.clearAllBits();
2087 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
2090 case ISD::FrameIndex:
2091 case ISD::TargetFrameIndex:
2092 if (unsigned Align = InferPtrAlignment(Op)) {
2093 // The low bits are known zero if the pointer is aligned.
2094 KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align));
2100 if (Op.getOpcode() < ISD::BUILTIN_OP_END)
2103 case ISD::INTRINSIC_WO_CHAIN:
2104 case ISD::INTRINSIC_W_CHAIN:
2105 case ISD::INTRINSIC_VOID:
2106 // Allow the target to implement this method for its nodes.
2107 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
2113 /// ComputeNumSignBits - Return the number of times the sign bit of the
2114 /// register is replicated into the other bits. We know that at least 1 bit
2115 /// is always equal to the sign bit (itself), but other cases can give us
2116 /// information. For example, immediately after an "SRA X, 2", we know that
2117 /// the top 3 bits are all equal to each other, so we return 3.
2118 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
2119 EVT VT = Op.getValueType();
2120 assert(VT.isInteger() && "Invalid VT!");
2121 unsigned VTBits = VT.getScalarType().getSizeInBits();
2123 unsigned FirstAnswer = 1;
2126 return 1; // Limit search depth.
2128 switch (Op.getOpcode()) {
2130 case ISD::AssertSext:
2131 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2132 return VTBits-Tmp+1;
2133 case ISD::AssertZext:
2134 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2137 case ISD::Constant: {
2138 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2139 return Val.getNumSignBits();
2142 case ISD::SIGN_EXTEND:
2143 Tmp = VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2144 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2146 case ISD::SIGN_EXTEND_INREG:
2147 // Max of the input and what this extends.
2149 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
2152 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2153 return std::max(Tmp, Tmp2);
2156 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2157 // SRA X, C -> adds C sign bits.
2158 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2159 Tmp += C->getZExtValue();
2160 if (Tmp > VTBits) Tmp = VTBits;
2164 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2165 // shl destroys sign bits.
2166 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2167 if (C->getZExtValue() >= VTBits || // Bad shift.
2168 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2169 return Tmp - C->getZExtValue();
2174 case ISD::XOR: // NOT is handled here.
2175 // Logical binary ops preserve the number of sign bits at the worst.
2176 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2178 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2179 FirstAnswer = std::min(Tmp, Tmp2);
2180 // We computed what we know about the sign bits as our first
2181 // answer. Now proceed to the generic code that uses
2182 // ComputeMaskedBits, and pick whichever answer is better.
2187 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2188 if (Tmp == 1) return 1; // Early out.
2189 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2190 return std::min(Tmp, Tmp2);
2198 if (Op.getResNo() != 1)
2200 // The boolean result conforms to getBooleanContents. Fall through.
2202 // If setcc returns 0/-1, all bits are sign bits.
2203 if (TLI.getBooleanContents(Op.getValueType().isVector()) ==
2204 TargetLowering::ZeroOrNegativeOneBooleanContent)
2209 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2210 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2212 // Handle rotate right by N like a rotate left by 32-N.
2213 if (Op.getOpcode() == ISD::ROTR)
2214 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2216 // If we aren't rotating out all of the known-in sign bits, return the
2217 // number that are left. This handles rotl(sext(x), 1) for example.
2218 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2219 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2223 // Add can have at most one carry bit. Thus we know that the output
2224 // is, at worst, one more bit than the inputs.
2225 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2226 if (Tmp == 1) return 1; // Early out.
2228 // Special case decrementing a value (ADD X, -1):
2229 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2230 if (CRHS->isAllOnesValue()) {
2231 APInt KnownZero, KnownOne;
2232 APInt Mask = APInt::getAllOnesValue(VTBits);
2233 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2235 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2237 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2240 // If we are subtracting one from a positive number, there is no carry
2241 // out of the result.
2242 if (KnownZero.isNegative())
2246 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2247 if (Tmp2 == 1) return 1;
2248 return std::min(Tmp, Tmp2)-1;
2251 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2252 if (Tmp2 == 1) return 1;
2255 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2256 if (CLHS->isNullValue()) {
2257 APInt KnownZero, KnownOne;
2258 APInt Mask = APInt::getAllOnesValue(VTBits);
2259 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2260 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2262 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2265 // If the input is known to be positive (the sign bit is known clear),
2266 // the output of the NEG has the same number of sign bits as the input.
2267 if (KnownZero.isNegative())
2270 // Otherwise, we treat this like a SUB.
2273 // Sub can have at most one carry bit. Thus we know that the output
2274 // is, at worst, one more bit than the inputs.
2275 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2276 if (Tmp == 1) return 1; // Early out.
2277 return std::min(Tmp, Tmp2)-1;
2279 // FIXME: it's tricky to do anything useful for this, but it is an important
2280 // case for targets like X86.
2284 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2285 if (Op.getOpcode() == ISD::LOAD) {
2286 LoadSDNode *LD = cast<LoadSDNode>(Op);
2287 unsigned ExtType = LD->getExtensionType();
2290 case ISD::SEXTLOAD: // '17' bits known
2291 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2292 return VTBits-Tmp+1;
2293 case ISD::ZEXTLOAD: // '16' bits known
2294 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2299 // Allow the target to implement this method for its nodes.
2300 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2301 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2302 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2303 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2304 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2305 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2308 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2309 // use this information.
2310 APInt KnownZero, KnownOne;
2311 APInt Mask = APInt::getAllOnesValue(VTBits);
2312 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2314 if (KnownZero.isNegative()) { // sign bit is 0
2316 } else if (KnownOne.isNegative()) { // sign bit is 1;
2323 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2324 // the number of identical bits in the top of the input value.
2326 Mask <<= Mask.getBitWidth()-VTBits;
2327 // Return # leading zeros. We use 'min' here in case Val was zero before
2328 // shifting. We don't want to return '64' as for an i32 "0".
2329 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2332 /// isBaseWithConstantOffset - Return true if the specified operand is an
2333 /// ISD::ADD with a ConstantSDNode on the right-hand side, or if it is an
2334 /// ISD::OR with a ConstantSDNode that is guaranteed to have the same
2335 /// semantics as an ADD. This handles the equivalence:
2336 /// X|Cst == X+Cst iff X&Cst = 0.
2337 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
2338 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
2339 !isa<ConstantSDNode>(Op.getOperand(1)))
2342 if (Op.getOpcode() == ISD::OR &&
2343 !MaskedValueIsZero(Op.getOperand(0),
2344 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
2351 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2352 // If we're told that NaNs won't happen, assume they won't.
2353 if (getTarget().Options.NoNaNsFPMath)
2356 // If the value is a constant, we can obviously see if it is a NaN or not.
2357 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2358 return !C->getValueAPF().isNaN();
2360 // TODO: Recognize more cases here.
2365 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2366 // If the value is a constant, we can obviously see if it is a zero or not.
2367 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2368 return !C->isZero();
2370 // TODO: Recognize more cases here.
2371 switch (Op.getOpcode()) {
2374 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2375 return !C->isNullValue();
2382 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2383 // Check the obvious case.
2384 if (A == B) return true;
2386 // For for negative and positive zero.
2387 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2388 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2389 if (CA->isZero() && CB->isZero()) return true;
2391 // Otherwise they may not be equal.
2395 /// getNode - Gets or creates the specified node.
2397 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
2398 FoldingSetNodeID ID;
2399 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2401 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2402 return SDValue(E, 0);
2404 SDNode *N = new (NodeAllocator) SDNode(Opcode, DL, getVTList(VT));
2405 CSEMap.InsertNode(N, IP);
2407 AllNodes.push_back(N);
2411 return SDValue(N, 0);
2414 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2415 EVT VT, SDValue Operand) {
2416 // Constant fold unary operations with an integer constant operand.
2417 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2418 const APInt &Val = C->getAPIntValue();
2421 case ISD::SIGN_EXTEND:
2422 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), VT);
2423 case ISD::ANY_EXTEND:
2424 case ISD::ZERO_EXTEND:
2426 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), VT);
2427 case ISD::UINT_TO_FP:
2428 case ISD::SINT_TO_FP: {
2429 // No compile time operations on ppcf128.
2430 if (VT == MVT::ppcf128) break;
2431 APFloat apf(APInt::getNullValue(VT.getSizeInBits()));
2432 (void)apf.convertFromAPInt(Val,
2433 Opcode==ISD::SINT_TO_FP,
2434 APFloat::rmNearestTiesToEven);
2435 return getConstantFP(apf, VT);
2438 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2439 return getConstantFP(Val.bitsToFloat(), VT);
2440 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2441 return getConstantFP(Val.bitsToDouble(), VT);
2444 return getConstant(Val.byteSwap(), VT);
2446 return getConstant(Val.countPopulation(), VT);
2448 case ISD::CTLZ_ZERO_UNDEF:
2449 return getConstant(Val.countLeadingZeros(), VT);
2451 case ISD::CTTZ_ZERO_UNDEF:
2452 return getConstant(Val.countTrailingZeros(), VT);
2456 // Constant fold unary operations with a floating point constant operand.
2457 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2458 APFloat V = C->getValueAPF(); // make copy
2459 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2463 return getConstantFP(V, VT);
2466 return getConstantFP(V, VT);
2468 case ISD::FP_EXTEND: {
2470 // This can return overflow, underflow, or inexact; we don't care.
2471 // FIXME need to be more flexible about rounding mode.
2472 (void)V.convert(*EVTToAPFloatSemantics(VT),
2473 APFloat::rmNearestTiesToEven, &ignored);
2474 return getConstantFP(V, VT);
2476 case ISD::FP_TO_SINT:
2477 case ISD::FP_TO_UINT: {
2480 assert(integerPartWidth >= 64);
2481 // FIXME need to be more flexible about rounding mode.
2482 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2483 Opcode==ISD::FP_TO_SINT,
2484 APFloat::rmTowardZero, &ignored);
2485 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2487 APInt api(VT.getSizeInBits(), x);
2488 return getConstant(api, VT);
2491 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2492 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2493 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2494 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2500 unsigned OpOpcode = Operand.getNode()->getOpcode();
2502 case ISD::TokenFactor:
2503 case ISD::MERGE_VALUES:
2504 case ISD::CONCAT_VECTORS:
2505 return Operand; // Factor, merge or concat of one node? No need.
2506 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2507 case ISD::FP_EXTEND:
2508 assert(VT.isFloatingPoint() &&
2509 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2510 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2511 assert((!VT.isVector() ||
2512 VT.getVectorNumElements() ==
2513 Operand.getValueType().getVectorNumElements()) &&
2514 "Vector element count mismatch!");
2515 if (Operand.getOpcode() == ISD::UNDEF)
2516 return getUNDEF(VT);
2518 case ISD::SIGN_EXTEND:
2519 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2520 "Invalid SIGN_EXTEND!");
2521 if (Operand.getValueType() == VT) return Operand; // noop extension
2522 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2523 "Invalid sext node, dst < src!");
2524 assert((!VT.isVector() ||
2525 VT.getVectorNumElements() ==
2526 Operand.getValueType().getVectorNumElements()) &&
2527 "Vector element count mismatch!");
2528 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2529 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2530 else if (OpOpcode == ISD::UNDEF)
2531 // sext(undef) = 0, because the top bits will all be the same.
2532 return getConstant(0, VT);
2534 case ISD::ZERO_EXTEND:
2535 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2536 "Invalid ZERO_EXTEND!");
2537 if (Operand.getValueType() == VT) return Operand; // noop extension
2538 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2539 "Invalid zext node, dst < src!");
2540 assert((!VT.isVector() ||
2541 VT.getVectorNumElements() ==
2542 Operand.getValueType().getVectorNumElements()) &&
2543 "Vector element count mismatch!");
2544 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2545 return getNode(ISD::ZERO_EXTEND, DL, VT,
2546 Operand.getNode()->getOperand(0));
2547 else if (OpOpcode == ISD::UNDEF)
2548 // zext(undef) = 0, because the top bits will be zero.
2549 return getConstant(0, VT);
2551 case ISD::ANY_EXTEND:
2552 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2553 "Invalid ANY_EXTEND!");
2554 if (Operand.getValueType() == VT) return Operand; // noop extension
2555 assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2556 "Invalid anyext node, dst < src!");
2557 assert((!VT.isVector() ||
2558 VT.getVectorNumElements() ==
2559 Operand.getValueType().getVectorNumElements()) &&
2560 "Vector element count mismatch!");
2562 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2563 OpOpcode == ISD::ANY_EXTEND)
2564 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2565 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2566 else if (OpOpcode == ISD::UNDEF)
2567 return getUNDEF(VT);
2569 // (ext (trunx x)) -> x
2570 if (OpOpcode == ISD::TRUNCATE) {
2571 SDValue OpOp = Operand.getNode()->getOperand(0);
2572 if (OpOp.getValueType() == VT)
2577 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2578 "Invalid TRUNCATE!");
2579 if (Operand.getValueType() == VT) return Operand; // noop truncate
2580 assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2581 "Invalid truncate node, src < dst!");
2582 assert((!VT.isVector() ||
2583 VT.getVectorNumElements() ==
2584 Operand.getValueType().getVectorNumElements()) &&
2585 "Vector element count mismatch!");
2586 if (OpOpcode == ISD::TRUNCATE)
2587 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2588 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2589 OpOpcode == ISD::ANY_EXTEND) {
2590 // If the source is smaller than the dest, we still need an extend.
2591 if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2592 .bitsLT(VT.getScalarType()))
2593 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2594 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2595 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2596 return Operand.getNode()->getOperand(0);
2598 if (OpOpcode == ISD::UNDEF)
2599 return getUNDEF(VT);
2602 // Basic sanity checking.
2603 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2604 && "Cannot BITCAST between types of different sizes!");
2605 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2606 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
2607 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
2608 if (OpOpcode == ISD::UNDEF)
2609 return getUNDEF(VT);
2611 case ISD::SCALAR_TO_VECTOR:
2612 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2613 (VT.getVectorElementType() == Operand.getValueType() ||
2614 (VT.getVectorElementType().isInteger() &&
2615 Operand.getValueType().isInteger() &&
2616 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2617 "Illegal SCALAR_TO_VECTOR node!");
2618 if (OpOpcode == ISD::UNDEF)
2619 return getUNDEF(VT);
2620 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2621 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2622 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2623 Operand.getConstantOperandVal(1) == 0 &&
2624 Operand.getOperand(0).getValueType() == VT)
2625 return Operand.getOperand(0);
2628 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2629 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB)
2630 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2631 Operand.getNode()->getOperand(0));
2632 if (OpOpcode == ISD::FNEG) // --X -> X
2633 return Operand.getNode()->getOperand(0);
2636 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2637 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2642 SDVTList VTs = getVTList(VT);
2643 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
2644 FoldingSetNodeID ID;
2645 SDValue Ops[1] = { Operand };
2646 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2648 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2649 return SDValue(E, 0);
2651 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTs, Operand);
2652 CSEMap.InsertNode(N, IP);
2654 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTs, Operand);
2657 AllNodes.push_back(N);
2661 return SDValue(N, 0);
2664 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2666 ConstantSDNode *Cst1,
2667 ConstantSDNode *Cst2) {
2668 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2671 case ISD::ADD: return getConstant(C1 + C2, VT);
2672 case ISD::SUB: return getConstant(C1 - C2, VT);
2673 case ISD::MUL: return getConstant(C1 * C2, VT);
2675 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2678 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2681 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2684 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2686 case ISD::AND: return getConstant(C1 & C2, VT);
2687 case ISD::OR: return getConstant(C1 | C2, VT);
2688 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2689 case ISD::SHL: return getConstant(C1 << C2, VT);
2690 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2691 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2692 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2693 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2700 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2701 SDValue N1, SDValue N2) {
2702 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2703 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2706 case ISD::TokenFactor:
2707 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2708 N2.getValueType() == MVT::Other && "Invalid token factor!");
2709 // Fold trivial token factors.
2710 if (N1.getOpcode() == ISD::EntryToken) return N2;
2711 if (N2.getOpcode() == ISD::EntryToken) return N1;
2712 if (N1 == N2) return N1;
2714 case ISD::CONCAT_VECTORS:
2715 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2716 // one big BUILD_VECTOR.
2717 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2718 N2.getOpcode() == ISD::BUILD_VECTOR) {
2719 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
2720 N1.getNode()->op_end());
2721 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
2722 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2726 assert(VT.isInteger() && "This operator does not apply to FP types!");
2727 assert(N1.getValueType() == N2.getValueType() &&
2728 N1.getValueType() == VT && "Binary operator types must match!");
2729 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2730 // worth handling here.
2731 if (N2C && N2C->isNullValue())
2733 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2740 assert(VT.isInteger() && "This operator does not apply to FP types!");
2741 assert(N1.getValueType() == N2.getValueType() &&
2742 N1.getValueType() == VT && "Binary operator types must match!");
2743 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2744 // it's worth handling here.
2745 if (N2C && N2C->isNullValue())
2755 assert(VT.isInteger() && "This operator does not apply to FP types!");
2756 assert(N1.getValueType() == N2.getValueType() &&
2757 N1.getValueType() == VT && "Binary operator types must match!");
2764 if (getTarget().Options.UnsafeFPMath) {
2765 if (Opcode == ISD::FADD) {
2767 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2768 if (CFP->getValueAPF().isZero())
2771 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2772 if (CFP->getValueAPF().isZero())
2774 } else if (Opcode == ISD::FSUB) {
2776 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2777 if (CFP->getValueAPF().isZero())
2781 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
2782 assert(N1.getValueType() == N2.getValueType() &&
2783 N1.getValueType() == VT && "Binary operator types must match!");
2785 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2786 assert(N1.getValueType() == VT &&
2787 N1.getValueType().isFloatingPoint() &&
2788 N2.getValueType().isFloatingPoint() &&
2789 "Invalid FCOPYSIGN!");
2796 assert(VT == N1.getValueType() &&
2797 "Shift operators return type must be the same as their first arg");
2798 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2799 "Shifts only work on integers");
2800 // Verify that the shift amount VT is bit enough to hold valid shift
2801 // amounts. This catches things like trying to shift an i1024 value by an
2802 // i8, which is easy to fall into in generic code that uses
2803 // TLI.getShiftAmount().
2804 assert(N2.getValueType().getSizeInBits() >=
2805 Log2_32_Ceil(N1.getValueType().getSizeInBits()) &&
2806 "Invalid use of small shift amount with oversized value!");
2808 // Always fold shifts of i1 values so the code generator doesn't need to
2809 // handle them. Since we know the size of the shift has to be less than the
2810 // size of the value, the shift/rotate count is guaranteed to be zero.
2813 if (N2C && N2C->isNullValue())
2816 case ISD::FP_ROUND_INREG: {
2817 EVT EVT = cast<VTSDNode>(N2)->getVT();
2818 assert(VT == N1.getValueType() && "Not an inreg round!");
2819 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2820 "Cannot FP_ROUND_INREG integer types");
2821 assert(EVT.isVector() == VT.isVector() &&
2822 "FP_ROUND_INREG type should be vector iff the operand "
2824 assert((!EVT.isVector() ||
2825 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2826 "Vector element counts must match in FP_ROUND_INREG");
2827 assert(EVT.bitsLE(VT) && "Not rounding down!");
2829 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2833 assert(VT.isFloatingPoint() &&
2834 N1.getValueType().isFloatingPoint() &&
2835 VT.bitsLE(N1.getValueType()) &&
2836 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2837 if (N1.getValueType() == VT) return N1; // noop conversion.
2839 case ISD::AssertSext:
2840 case ISD::AssertZext: {
2841 EVT EVT = cast<VTSDNode>(N2)->getVT();
2842 assert(VT == N1.getValueType() && "Not an inreg extend!");
2843 assert(VT.isInteger() && EVT.isInteger() &&
2844 "Cannot *_EXTEND_INREG FP types");
2845 assert(!EVT.isVector() &&
2846 "AssertSExt/AssertZExt type should be the vector element type "
2847 "rather than the vector type!");
2848 assert(EVT.bitsLE(VT) && "Not extending!");
2849 if (VT == EVT) return N1; // noop assertion.
2852 case ISD::SIGN_EXTEND_INREG: {
2853 EVT EVT = cast<VTSDNode>(N2)->getVT();
2854 assert(VT == N1.getValueType() && "Not an inreg extend!");
2855 assert(VT.isInteger() && EVT.isInteger() &&
2856 "Cannot *_EXTEND_INREG FP types");
2857 assert(EVT.isVector() == VT.isVector() &&
2858 "SIGN_EXTEND_INREG type should be vector iff the operand "
2860 assert((!EVT.isVector() ||
2861 EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2862 "Vector element counts must match in SIGN_EXTEND_INREG");
2863 assert(EVT.bitsLE(VT) && "Not extending!");
2864 if (EVT == VT) return N1; // Not actually extending
2867 APInt Val = N1C->getAPIntValue();
2868 unsigned FromBits = EVT.getScalarType().getSizeInBits();
2869 Val <<= Val.getBitWidth()-FromBits;
2870 Val = Val.ashr(Val.getBitWidth()-FromBits);
2871 return getConstant(Val, VT);
2875 case ISD::EXTRACT_VECTOR_ELT:
2876 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2877 if (N1.getOpcode() == ISD::UNDEF)
2878 return getUNDEF(VT);
2880 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2881 // expanding copies of large vectors from registers.
2883 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2884 N1.getNumOperands() > 0) {
2886 N1.getOperand(0).getValueType().getVectorNumElements();
2887 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2888 N1.getOperand(N2C->getZExtValue() / Factor),
2889 getConstant(N2C->getZExtValue() % Factor,
2890 N2.getValueType()));
2893 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2894 // expanding large vector constants.
2895 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2896 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2897 EVT VEltTy = N1.getValueType().getVectorElementType();
2898 if (Elt.getValueType() != VEltTy) {
2899 // If the vector element type is not legal, the BUILD_VECTOR operands
2900 // are promoted and implicitly truncated. Make that explicit here.
2901 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2904 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2905 // result is implicitly extended.
2906 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2911 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2912 // operations are lowered to scalars.
2913 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2914 // If the indices are the same, return the inserted element else
2915 // if the indices are known different, extract the element from
2916 // the original vector.
2917 SDValue N1Op2 = N1.getOperand(2);
2918 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2.getNode());
2920 if (N1Op2C && N2C) {
2921 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
2922 if (VT == N1.getOperand(1).getValueType())
2923 return N1.getOperand(1);
2925 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
2928 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2932 case ISD::EXTRACT_ELEMENT:
2933 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2934 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2935 (N1.getValueType().isInteger() == VT.isInteger()) &&
2936 N1.getValueType() != VT &&
2937 "Wrong types for EXTRACT_ELEMENT!");
2939 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2940 // 64-bit integers into 32-bit parts. Instead of building the extract of
2941 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2942 if (N1.getOpcode() == ISD::BUILD_PAIR)
2943 return N1.getOperand(N2C->getZExtValue());
2945 // EXTRACT_ELEMENT of a constant int is also very common.
2946 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2947 unsigned ElementSize = VT.getSizeInBits();
2948 unsigned Shift = ElementSize * N2C->getZExtValue();
2949 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2950 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2953 case ISD::EXTRACT_SUBVECTOR: {
2955 if (VT.isSimple() && N1.getValueType().isSimple()) {
2956 assert(VT.isVector() && N1.getValueType().isVector() &&
2957 "Extract subvector VTs must be a vectors!");
2958 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType() &&
2959 "Extract subvector VTs must have the same element type!");
2960 assert(VT.getSimpleVT() <= N1.getValueType().getSimpleVT() &&
2961 "Extract subvector must be from larger vector to smaller vector!");
2963 if (isa<ConstantSDNode>(Index.getNode())) {
2964 assert((VT.getVectorNumElements() +
2965 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
2966 <= N1.getValueType().getVectorNumElements())
2967 && "Extract subvector overflow!");
2970 // Trivial extraction.
2971 if (VT.getSimpleVT() == N1.getValueType().getSimpleVT())
2980 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2981 if (SV.getNode()) return SV;
2982 } else { // Cannonicalize constant to RHS if commutative
2983 if (isCommutativeBinOp(Opcode)) {
2984 std::swap(N1C, N2C);
2990 // Constant fold FP operations.
2991 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2992 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2994 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2995 // Cannonicalize constant to RHS if commutative
2996 std::swap(N1CFP, N2CFP);
2998 } else if (N2CFP && VT != MVT::ppcf128) {
2999 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
3000 APFloat::opStatus s;
3003 s = V1.add(V2, APFloat::rmNearestTiesToEven);
3004 if (s != APFloat::opInvalidOp)
3005 return getConstantFP(V1, VT);
3008 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
3009 if (s!=APFloat::opInvalidOp)
3010 return getConstantFP(V1, VT);
3013 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
3014 if (s!=APFloat::opInvalidOp)
3015 return getConstantFP(V1, VT);
3018 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
3019 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
3020 return getConstantFP(V1, VT);
3023 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
3024 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
3025 return getConstantFP(V1, VT);
3027 case ISD::FCOPYSIGN:
3029 return getConstantFP(V1, VT);
3035 // Canonicalize an UNDEF to the RHS, even over a constant.
3036 if (N1.getOpcode() == ISD::UNDEF) {
3037 if (isCommutativeBinOp(Opcode)) {
3041 case ISD::FP_ROUND_INREG:
3042 case ISD::SIGN_EXTEND_INREG:
3048 return N1; // fold op(undef, arg2) -> undef
3056 return getConstant(0, VT); // fold op(undef, arg2) -> 0
3057 // For vectors, we can't easily build an all zero vector, just return
3064 // Fold a bunch of operators when the RHS is undef.
3065 if (N2.getOpcode() == ISD::UNDEF) {
3068 if (N1.getOpcode() == ISD::UNDEF)
3069 // Handle undef ^ undef -> 0 special case. This is a common
3071 return getConstant(0, VT);
3081 return N2; // fold op(arg1, undef) -> undef
3087 if (getTarget().Options.UnsafeFPMath)
3095 return getConstant(0, VT); // fold op(arg1, undef) -> 0
3096 // For vectors, we can't easily build an all zero vector, just return
3101 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
3102 // For vectors, we can't easily build an all one vector, just return
3110 // Memoize this node if possible.
3112 SDVTList VTs = getVTList(VT);
3113 if (VT != MVT::Glue) {
3114 SDValue Ops[] = { N1, N2 };
3115 FoldingSetNodeID ID;
3116 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
3118 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3119 return SDValue(E, 0);
3121 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTs, N1, N2);
3122 CSEMap.InsertNode(N, IP);
3124 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTs, N1, N2);
3127 AllNodes.push_back(N);
3131 return SDValue(N, 0);
3134 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3135 SDValue N1, SDValue N2, SDValue N3) {
3136 // Perform various simplifications.
3137 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
3139 case ISD::CONCAT_VECTORS:
3140 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3141 // one big BUILD_VECTOR.
3142 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3143 N2.getOpcode() == ISD::BUILD_VECTOR &&
3144 N3.getOpcode() == ISD::BUILD_VECTOR) {
3145 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
3146 N1.getNode()->op_end());
3147 Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
3148 Elts.append(N3.getNode()->op_begin(), N3.getNode()->op_end());
3149 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
3153 // Use FoldSetCC to simplify SETCC's.
3154 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3155 if (Simp.getNode()) return Simp;
3160 if (N1C->getZExtValue())
3161 return N2; // select true, X, Y -> X
3162 return N3; // select false, X, Y -> Y
3165 if (N2 == N3) return N2; // select C, X, X -> X
3167 case ISD::VECTOR_SHUFFLE:
3168 llvm_unreachable("should use getVectorShuffle constructor!");
3169 case ISD::INSERT_SUBVECTOR: {
3171 if (VT.isSimple() && N1.getValueType().isSimple()
3172 && N2.getValueType().isSimple()) {
3173 assert(VT.isVector() && N1.getValueType().isVector() &&
3174 N2.getValueType().isVector() &&
3175 "Insert subvector VTs must be a vectors");
3176 assert(VT == N1.getValueType() &&
3177 "Dest and insert subvector source types must match!");
3178 assert(N2.getValueType().getSimpleVT() <= N1.getValueType().getSimpleVT() &&
3179 "Insert subvector must be from smaller vector to larger vector!");
3180 if (isa<ConstantSDNode>(Index.getNode())) {
3181 assert((N2.getValueType().getVectorNumElements() +
3182 cast<ConstantSDNode>(Index.getNode())->getZExtValue()
3183 <= VT.getVectorNumElements())
3184 && "Insert subvector overflow!");
3187 // Trivial insertion.
3188 if (VT.getSimpleVT() == N2.getValueType().getSimpleVT())
3194 // Fold bit_convert nodes from a type to themselves.
3195 if (N1.getValueType() == VT)
3200 // Memoize node if it doesn't produce a flag.
3202 SDVTList VTs = getVTList(VT);
3203 if (VT != MVT::Glue) {
3204 SDValue Ops[] = { N1, N2, N3 };
3205 FoldingSetNodeID ID;
3206 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3208 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3209 return SDValue(E, 0);
3211 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3212 CSEMap.InsertNode(N, IP);
3214 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3217 AllNodes.push_back(N);
3221 return SDValue(N, 0);
3224 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3225 SDValue N1, SDValue N2, SDValue N3,
3227 SDValue Ops[] = { N1, N2, N3, N4 };
3228 return getNode(Opcode, DL, VT, Ops, 4);
3231 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3232 SDValue N1, SDValue N2, SDValue N3,
3233 SDValue N4, SDValue N5) {
3234 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3235 return getNode(Opcode, DL, VT, Ops, 5);
3238 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3239 /// the incoming stack arguments to be loaded from the stack.
3240 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3241 SmallVector<SDValue, 8> ArgChains;
3243 // Include the original chain at the beginning of the list. When this is
3244 // used by target LowerCall hooks, this helps legalize find the
3245 // CALLSEQ_BEGIN node.
3246 ArgChains.push_back(Chain);
3248 // Add a chain value for each stack argument.
3249 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3250 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3251 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3252 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3253 if (FI->getIndex() < 0)
3254 ArgChains.push_back(SDValue(L, 1));
3256 // Build a tokenfactor for all the chains.
3257 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
3258 &ArgChains[0], ArgChains.size());
3261 /// SplatByte - Distribute ByteVal over NumBits bits.
3262 static APInt SplatByte(unsigned NumBits, uint8_t ByteVal) {
3263 APInt Val = APInt(NumBits, ByteVal);
3265 for (unsigned i = NumBits; i > 8; i >>= 1) {
3266 Val = (Val << Shift) | Val;
3272 /// getMemsetValue - Vectorized representation of the memset value
3274 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3276 assert(Value.getOpcode() != ISD::UNDEF);
3278 unsigned NumBits = VT.getScalarType().getSizeInBits();
3279 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3280 APInt Val = SplatByte(NumBits, C->getZExtValue() & 255);
3282 return DAG.getConstant(Val, VT);
3283 return DAG.getConstantFP(APFloat(Val), VT);
3286 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3288 // Use a multiplication with 0x010101... to extend the input to the
3290 APInt Magic = SplatByte(NumBits, 0x01);
3291 Value = DAG.getNode(ISD::MUL, dl, VT, Value, DAG.getConstant(Magic, VT));
3297 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3298 /// used when a memcpy is turned into a memset when the source is a constant
3300 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3301 const TargetLowering &TLI,
3302 std::string &Str, unsigned Offset) {
3303 // Handle vector with all elements zero.
3306 return DAG.getConstant(0, VT);
3307 else if (VT == MVT::f32 || VT == MVT::f64)
3308 return DAG.getConstantFP(0.0, VT);
3309 else if (VT.isVector()) {
3310 unsigned NumElts = VT.getVectorNumElements();
3311 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3312 return DAG.getNode(ISD::BITCAST, dl, VT,
3313 DAG.getConstant(0, EVT::getVectorVT(*DAG.getContext(),
3316 llvm_unreachable("Expected type!");
3319 assert(!VT.isVector() && "Can't handle vector type here!");
3320 unsigned NumBits = VT.getSizeInBits();
3321 unsigned MSB = NumBits / 8;
3323 if (TLI.isLittleEndian())
3324 Offset = Offset + MSB - 1;
3325 for (unsigned i = 0; i != MSB; ++i) {
3328 if (Offset < Str.size())
3329 Val |= (unsigned char)Str[Offset];
3330 Offset += TLI.isLittleEndian() ? -1 : 1;
3332 return DAG.getConstant(Val, VT);
3335 /// getMemBasePlusOffset - Returns base and offset node for the
3337 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3338 SelectionDAG &DAG) {
3339 EVT VT = Base.getValueType();
3340 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3341 VT, Base, DAG.getConstant(Offset, VT));
3344 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3346 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3347 unsigned SrcDelta = 0;
3348 GlobalAddressSDNode *G = NULL;
3349 if (Src.getOpcode() == ISD::GlobalAddress)
3350 G = cast<GlobalAddressSDNode>(Src);
3351 else if (Src.getOpcode() == ISD::ADD &&
3352 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3353 Src.getOperand(1).getOpcode() == ISD::Constant) {
3354 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3355 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3360 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal()))
3361 if (GetConstantStringInfo(GV, Str, SrcDelta)) {
3362 // The nul can also be read.
3370 /// FindOptimalMemOpLowering - Determines the optimial series memory ops
3371 /// to replace the memset / memcpy. Return true if the number of memory ops
3372 /// is below the threshold. It returns the types of the sequence of
3373 /// memory ops to perform memset / memcpy by reference.
3374 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
3375 unsigned Limit, uint64_t Size,
3376 unsigned DstAlign, unsigned SrcAlign,
3380 const TargetLowering &TLI) {
3381 assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
3382 "Expecting memcpy / memset source to meet alignment requirement!");
3383 // If 'SrcAlign' is zero, that means the memory operation does not need to
3384 // load the value, i.e. memset or memcpy from constant string. Otherwise,
3385 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
3386 // is the specified alignment of the memory operation. If it is zero, that
3387 // means it's possible to change the alignment of the destination.
3388 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
3389 // not need to be loaded.
3390 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
3391 IsZeroVal, MemcpyStrSrc,
3392 DAG.getMachineFunction());
3394 if (VT == MVT::Other) {
3395 if (DstAlign >= TLI.getTargetData()->getPointerPrefAlignment() ||
3396 TLI.allowsUnalignedMemoryAccesses(VT)) {
3397 VT = TLI.getPointerTy();
3399 switch (DstAlign & 7) {
3400 case 0: VT = MVT::i64; break;
3401 case 4: VT = MVT::i32; break;
3402 case 2: VT = MVT::i16; break;
3403 default: VT = MVT::i8; break;
3408 while (!TLI.isTypeLegal(LVT))
3409 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3410 assert(LVT.isInteger());
3416 unsigned NumMemOps = 0;
3418 unsigned VTSize = VT.getSizeInBits() / 8;
3419 while (VTSize > Size) {
3420 // For now, only use non-vector load / store's for the left-over pieces.
3421 if (VT.isVector() || VT.isFloatingPoint()) {
3423 while (!TLI.isTypeLegal(VT))
3424 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3425 VTSize = VT.getSizeInBits() / 8;
3427 // This can result in a type that is not legal on the target, e.g.
3428 // 1 or 2 bytes on PPC.
3429 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3434 if (++NumMemOps > Limit)
3436 MemOps.push_back(VT);
3443 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3444 SDValue Chain, SDValue Dst,
3445 SDValue Src, uint64_t Size,
3446 unsigned Align, bool isVol,
3448 MachinePointerInfo DstPtrInfo,
3449 MachinePointerInfo SrcPtrInfo) {
3450 // Turn a memcpy of undef to nop.
3451 if (Src.getOpcode() == ISD::UNDEF)
3454 // Expand memcpy to a series of load and store ops if the size operand falls
3455 // below a certain threshold.
3456 // TODO: In the AlwaysInline case, if the size is big then generate a loop
3457 // rather than maybe a humongous number of loads and stores.
3458 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3459 std::vector<EVT> MemOps;
3460 bool DstAlignCanChange = false;
3461 MachineFunction &MF = DAG.getMachineFunction();
3462 MachineFrameInfo *MFI = MF.getFrameInfo();
3463 bool OptSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
3464 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3465 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3466 DstAlignCanChange = true;
3467 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3468 if (Align > SrcAlign)
3471 bool CopyFromStr = isMemSrcFromString(Src, Str);
3472 bool isZeroStr = CopyFromStr && Str.empty();
3473 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
3475 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3476 (DstAlignCanChange ? 0 : Align),
3477 (isZeroStr ? 0 : SrcAlign),
3478 true, CopyFromStr, DAG, TLI))
3481 if (DstAlignCanChange) {
3482 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3483 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3484 if (NewAlign > Align) {
3485 // Give the stack frame object a larger alignment if needed.
3486 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3487 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3492 SmallVector<SDValue, 8> OutChains;
3493 unsigned NumMemOps = MemOps.size();
3494 uint64_t SrcOff = 0, DstOff = 0;
3495 for (unsigned i = 0; i != NumMemOps; ++i) {
3497 unsigned VTSize = VT.getSizeInBits() / 8;
3498 SDValue Value, Store;
3501 (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
3502 // It's unlikely a store of a vector immediate can be done in a single
3503 // instruction. It would require a load from a constantpool first.
3504 // We only handle zero vectors here.
3505 // FIXME: Handle other cases where store of vector immediate is done in
3506 // a single instruction.
3507 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3508 Store = DAG.getStore(Chain, dl, Value,
3509 getMemBasePlusOffset(Dst, DstOff, DAG),
3510 DstPtrInfo.getWithOffset(DstOff), isVol,
3513 // The type might not be legal for the target. This should only happen
3514 // if the type is smaller than a legal type, as on PPC, so the right
3515 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3516 // to Load/Store if NVT==VT.
3517 // FIXME does the case above also need this?
3518 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3519 assert(NVT.bitsGE(VT));
3520 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3521 getMemBasePlusOffset(Src, SrcOff, DAG),
3522 SrcPtrInfo.getWithOffset(SrcOff), VT, isVol, false,
3523 MinAlign(SrcAlign, SrcOff));
3524 Store = DAG.getTruncStore(Chain, dl, Value,
3525 getMemBasePlusOffset(Dst, DstOff, DAG),
3526 DstPtrInfo.getWithOffset(DstOff), VT, isVol,
3529 OutChains.push_back(Store);
3534 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3535 &OutChains[0], OutChains.size());
3538 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3539 SDValue Chain, SDValue Dst,
3540 SDValue Src, uint64_t Size,
3541 unsigned Align, bool isVol,
3543 MachinePointerInfo DstPtrInfo,
3544 MachinePointerInfo SrcPtrInfo) {
3545 // Turn a memmove of undef to nop.
3546 if (Src.getOpcode() == ISD::UNDEF)
3549 // Expand memmove to a series of load and store ops if the size operand falls
3550 // below a certain threshold.
3551 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3552 std::vector<EVT> MemOps;
3553 bool DstAlignCanChange = false;
3554 MachineFunction &MF = DAG.getMachineFunction();
3555 MachineFrameInfo *MFI = MF.getFrameInfo();
3556 bool OptSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
3557 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3558 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3559 DstAlignCanChange = true;
3560 unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3561 if (Align > SrcAlign)
3563 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
3565 if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3566 (DstAlignCanChange ? 0 : Align),
3567 SrcAlign, true, false, DAG, TLI))
3570 if (DstAlignCanChange) {
3571 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3572 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3573 if (NewAlign > Align) {
3574 // Give the stack frame object a larger alignment if needed.
3575 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3576 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3581 uint64_t SrcOff = 0, DstOff = 0;
3582 SmallVector<SDValue, 8> LoadValues;
3583 SmallVector<SDValue, 8> LoadChains;
3584 SmallVector<SDValue, 8> OutChains;
3585 unsigned NumMemOps = MemOps.size();
3586 for (unsigned i = 0; i < NumMemOps; i++) {
3588 unsigned VTSize = VT.getSizeInBits() / 8;
3589 SDValue Value, Store;
3591 Value = DAG.getLoad(VT, dl, Chain,
3592 getMemBasePlusOffset(Src, SrcOff, DAG),
3593 SrcPtrInfo.getWithOffset(SrcOff), isVol,
3594 false, false, SrcAlign);
3595 LoadValues.push_back(Value);
3596 LoadChains.push_back(Value.getValue(1));
3599 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3600 &LoadChains[0], LoadChains.size());
3602 for (unsigned i = 0; i < NumMemOps; i++) {
3604 unsigned VTSize = VT.getSizeInBits() / 8;
3605 SDValue Value, Store;
3607 Store = DAG.getStore(Chain, dl, LoadValues[i],
3608 getMemBasePlusOffset(Dst, DstOff, DAG),
3609 DstPtrInfo.getWithOffset(DstOff), isVol, false, Align);
3610 OutChains.push_back(Store);
3614 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3615 &OutChains[0], OutChains.size());
3618 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3619 SDValue Chain, SDValue Dst,
3620 SDValue Src, uint64_t Size,
3621 unsigned Align, bool isVol,
3622 MachinePointerInfo DstPtrInfo) {
3623 // Turn a memset of undef to nop.
3624 if (Src.getOpcode() == ISD::UNDEF)
3627 // Expand memset to a series of load/store ops if the size operand
3628 // falls below a certain threshold.
3629 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3630 std::vector<EVT> MemOps;
3631 bool DstAlignCanChange = false;
3632 MachineFunction &MF = DAG.getMachineFunction();
3633 MachineFrameInfo *MFI = MF.getFrameInfo();
3634 bool OptSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
3635 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3636 if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3637 DstAlignCanChange = true;
3639 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
3640 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
3641 Size, (DstAlignCanChange ? 0 : Align), 0,
3642 IsZeroVal, false, DAG, TLI))
3645 if (DstAlignCanChange) {
3646 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3647 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3648 if (NewAlign > Align) {
3649 // Give the stack frame object a larger alignment if needed.
3650 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3651 MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3656 SmallVector<SDValue, 8> OutChains;
3657 uint64_t DstOff = 0;
3658 unsigned NumMemOps = MemOps.size();
3660 // Find the largest store and generate the bit pattern for it.
3661 EVT LargestVT = MemOps[0];
3662 for (unsigned i = 1; i < NumMemOps; i++)
3663 if (MemOps[i].bitsGT(LargestVT))
3664 LargestVT = MemOps[i];
3665 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
3667 for (unsigned i = 0; i < NumMemOps; i++) {
3670 // If this store is smaller than the largest store see whether we can get
3671 // the smaller value for free with a truncate.
3672 SDValue Value = MemSetValue;
3673 if (VT.bitsLT(LargestVT)) {
3674 if (!LargestVT.isVector() && !VT.isVector() &&
3675 TLI.isTruncateFree(LargestVT, VT))
3676 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
3678 Value = getMemsetValue(Src, VT, DAG, dl);
3680 assert(Value.getValueType() == VT && "Value with wrong type.");
3681 SDValue Store = DAG.getStore(Chain, dl, Value,
3682 getMemBasePlusOffset(Dst, DstOff, DAG),
3683 DstPtrInfo.getWithOffset(DstOff),
3684 isVol, false, Align);
3685 OutChains.push_back(Store);
3686 DstOff += VT.getSizeInBits() / 8;
3689 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3690 &OutChains[0], OutChains.size());
3693 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3694 SDValue Src, SDValue Size,
3695 unsigned Align, bool isVol, bool AlwaysInline,
3696 MachinePointerInfo DstPtrInfo,
3697 MachinePointerInfo SrcPtrInfo) {
3699 // Check to see if we should lower the memcpy to loads and stores first.
3700 // For cases within the target-specified limits, this is the best choice.
3701 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3703 // Memcpy with size zero? Just return the original chain.
3704 if (ConstantSize->isNullValue())
3707 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3708 ConstantSize->getZExtValue(),Align,
3709 isVol, false, DstPtrInfo, SrcPtrInfo);
3710 if (Result.getNode())
3714 // Then check to see if we should lower the memcpy with target-specific
3715 // code. If the target chooses to do this, this is the next best.
3717 TSI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3718 isVol, AlwaysInline,
3719 DstPtrInfo, SrcPtrInfo);
3720 if (Result.getNode())
3723 // If we really need inline code and the target declined to provide it,
3724 // use a (potentially long) sequence of loads and stores.
3726 assert(ConstantSize && "AlwaysInline requires a constant size!");
3727 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3728 ConstantSize->getZExtValue(), Align, isVol,
3729 true, DstPtrInfo, SrcPtrInfo);
3732 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
3733 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
3734 // respect volatile, so they may do things like read or write memory
3735 // beyond the given memory regions. But fixing this isn't easy, and most
3736 // people don't care.
3738 // Emit a library call.
3739 TargetLowering::ArgListTy Args;
3740 TargetLowering::ArgListEntry Entry;
3741 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3742 Entry.Node = Dst; Args.push_back(Entry);
3743 Entry.Node = Src; Args.push_back(Entry);
3744 Entry.Node = Size; Args.push_back(Entry);
3745 // FIXME: pass in DebugLoc
3746 std::pair<SDValue,SDValue> CallResult =
3747 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3748 false, false, false, false, 0,
3749 TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3750 /*isReturnValueUsed=*/false,
3751 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3752 TLI.getPointerTy()),
3754 return CallResult.second;
3757 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3758 SDValue Src, SDValue Size,
3759 unsigned Align, bool isVol,
3760 MachinePointerInfo DstPtrInfo,
3761 MachinePointerInfo SrcPtrInfo) {
3763 // Check to see if we should lower the memmove to loads and stores first.
3764 // For cases within the target-specified limits, this is the best choice.
3765 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3767 // Memmove with size zero? Just return the original chain.
3768 if (ConstantSize->isNullValue())
3772 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3773 ConstantSize->getZExtValue(), Align, isVol,
3774 false, DstPtrInfo, SrcPtrInfo);
3775 if (Result.getNode())
3779 // Then check to see if we should lower the memmove with target-specific
3780 // code. If the target chooses to do this, this is the next best.
3782 TSI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align, isVol,
3783 DstPtrInfo, SrcPtrInfo);
3784 if (Result.getNode())
3787 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
3788 // not be safe. See memcpy above for more details.
3790 // Emit a library call.
3791 TargetLowering::ArgListTy Args;
3792 TargetLowering::ArgListEntry Entry;
3793 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3794 Entry.Node = Dst; Args.push_back(Entry);
3795 Entry.Node = Src; Args.push_back(Entry);
3796 Entry.Node = Size; Args.push_back(Entry);
3797 // FIXME: pass in DebugLoc
3798 std::pair<SDValue,SDValue> CallResult =
3799 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3800 false, false, false, false, 0,
3801 TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3802 /*isReturnValueUsed=*/false,
3803 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3804 TLI.getPointerTy()),
3806 return CallResult.second;
3809 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3810 SDValue Src, SDValue Size,
3811 unsigned Align, bool isVol,
3812 MachinePointerInfo DstPtrInfo) {
3814 // Check to see if we should lower the memset to stores first.
3815 // For cases within the target-specified limits, this is the best choice.
3816 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3818 // Memset with size zero? Just return the original chain.
3819 if (ConstantSize->isNullValue())
3823 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3824 Align, isVol, DstPtrInfo);
3826 if (Result.getNode())
3830 // Then check to see if we should lower the memset with target-specific
3831 // code. If the target chooses to do this, this is the next best.
3833 TSI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align, isVol,
3835 if (Result.getNode())
3838 // Emit a library call.
3839 Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3840 TargetLowering::ArgListTy Args;
3841 TargetLowering::ArgListEntry Entry;
3842 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3843 Args.push_back(Entry);
3844 // Extend or truncate the argument to be an i32 value for the call.
3845 if (Src.getValueType().bitsGT(MVT::i32))
3846 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3848 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3850 Entry.Ty = Type::getInt32Ty(*getContext());
3851 Entry.isSExt = true;
3852 Args.push_back(Entry);
3854 Entry.Ty = IntPtrTy;
3855 Entry.isSExt = false;
3856 Args.push_back(Entry);
3857 // FIXME: pass in DebugLoc
3858 std::pair<SDValue,SDValue> CallResult =
3859 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3860 false, false, false, false, 0,
3861 TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3862 /*isReturnValueUsed=*/false,
3863 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3864 TLI.getPointerTy()),
3866 return CallResult.second;
3869 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3870 SDValue Chain, SDValue Ptr, SDValue Cmp,
3871 SDValue Swp, MachinePointerInfo PtrInfo,
3873 AtomicOrdering Ordering,
3874 SynchronizationScope SynchScope) {
3875 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3876 Alignment = getEVTAlignment(MemVT);
3878 MachineFunction &MF = getMachineFunction();
3879 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3881 // For now, atomics are considered to be volatile always.
3882 // FIXME: Volatile isn't really correct; we should keep track of atomic
3883 // orderings in the memoperand.
3884 Flags |= MachineMemOperand::MOVolatile;
3886 MachineMemOperand *MMO =
3887 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment);
3889 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO,
3890 Ordering, SynchScope);
3893 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3895 SDValue Ptr, SDValue Cmp,
3896 SDValue Swp, MachineMemOperand *MMO,
3897 AtomicOrdering Ordering,
3898 SynchronizationScope SynchScope) {
3899 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3900 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3902 EVT VT = Cmp.getValueType();
3904 SDVTList VTs = getVTList(VT, MVT::Other);
3905 FoldingSetNodeID ID;
3906 ID.AddInteger(MemVT.getRawBits());
3907 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3908 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3910 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3911 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3912 return SDValue(E, 0);
3914 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain,
3915 Ptr, Cmp, Swp, MMO, Ordering,
3917 CSEMap.InsertNode(N, IP);
3918 AllNodes.push_back(N);
3919 return SDValue(N, 0);
3922 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3924 SDValue Ptr, SDValue Val,
3925 const Value* PtrVal,
3927 AtomicOrdering Ordering,
3928 SynchronizationScope SynchScope) {
3929 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3930 Alignment = getEVTAlignment(MemVT);
3932 MachineFunction &MF = getMachineFunction();
3933 // A monotonic store does not load; a release store "loads" in the sense
3934 // that other stores cannot be sunk past it.
3935 // (An atomicrmw obviously both loads and stores.)
3936 unsigned Flags = MachineMemOperand::MOStore;
3937 if (Opcode != ISD::ATOMIC_STORE || Ordering > Monotonic)
3938 Flags |= MachineMemOperand::MOLoad;
3940 // For now, atomics are considered to be volatile always.
3941 // FIXME: Volatile isn't really correct; we should keep track of atomic
3942 // orderings in the memoperand.
3943 Flags |= MachineMemOperand::MOVolatile;
3945 MachineMemOperand *MMO =
3946 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
3947 MemVT.getStoreSize(), Alignment);
3949 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO,
3950 Ordering, SynchScope);
3953 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3955 SDValue Ptr, SDValue Val,
3956 MachineMemOperand *MMO,
3957 AtomicOrdering Ordering,
3958 SynchronizationScope SynchScope) {
3959 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3960 Opcode == ISD::ATOMIC_LOAD_SUB ||
3961 Opcode == ISD::ATOMIC_LOAD_AND ||
3962 Opcode == ISD::ATOMIC_LOAD_OR ||
3963 Opcode == ISD::ATOMIC_LOAD_XOR ||
3964 Opcode == ISD::ATOMIC_LOAD_NAND ||
3965 Opcode == ISD::ATOMIC_LOAD_MIN ||
3966 Opcode == ISD::ATOMIC_LOAD_MAX ||
3967 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3968 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3969 Opcode == ISD::ATOMIC_SWAP ||
3970 Opcode == ISD::ATOMIC_STORE) &&
3971 "Invalid Atomic Op");
3973 EVT VT = Val.getValueType();
3975 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
3976 getVTList(VT, MVT::Other);
3977 FoldingSetNodeID ID;
3978 ID.AddInteger(MemVT.getRawBits());
3979 SDValue Ops[] = {Chain, Ptr, Val};
3980 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3982 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3983 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3984 return SDValue(E, 0);
3986 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain,
3988 Ordering, SynchScope);
3989 CSEMap.InsertNode(N, IP);
3990 AllNodes.push_back(N);
3991 return SDValue(N, 0);
3994 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3995 EVT VT, SDValue Chain,
3997 const Value* PtrVal,
3999 AtomicOrdering Ordering,
4000 SynchronizationScope SynchScope) {
4001 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4002 Alignment = getEVTAlignment(MemVT);
4004 MachineFunction &MF = getMachineFunction();
4005 // A monotonic load does not store; an acquire load "stores" in the sense
4006 // that other loads cannot be hoisted past it.
4007 unsigned Flags = MachineMemOperand::MOLoad;
4008 if (Ordering > Monotonic)
4009 Flags |= MachineMemOperand::MOStore;
4011 // For now, atomics are considered to be volatile always.
4012 // FIXME: Volatile isn't really correct; we should keep track of atomic
4013 // orderings in the memoperand.
4014 Flags |= MachineMemOperand::MOVolatile;
4016 MachineMemOperand *MMO =
4017 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
4018 MemVT.getStoreSize(), Alignment);
4020 return getAtomic(Opcode, dl, MemVT, VT, Chain, Ptr, MMO,
4021 Ordering, SynchScope);
4024 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
4025 EVT VT, SDValue Chain,
4027 MachineMemOperand *MMO,
4028 AtomicOrdering Ordering,
4029 SynchronizationScope SynchScope) {
4030 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
4032 SDVTList VTs = getVTList(VT, MVT::Other);
4033 FoldingSetNodeID ID;
4034 ID.AddInteger(MemVT.getRawBits());
4035 SDValue Ops[] = {Chain, Ptr};
4036 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
4038 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4039 cast<AtomicSDNode>(E)->refineAlignment(MMO);
4040 return SDValue(E, 0);
4042 SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain,
4043 Ptr, MMO, Ordering, SynchScope);
4044 CSEMap.InsertNode(N, IP);
4045 AllNodes.push_back(N);
4046 return SDValue(N, 0);
4049 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
4050 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
4055 SmallVector<EVT, 4> VTs;
4056 VTs.reserve(NumOps);
4057 for (unsigned i = 0; i < NumOps; ++i)
4058 VTs.push_back(Ops[i].getValueType());
4059 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
4064 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
4065 const EVT *VTs, unsigned NumVTs,
4066 const SDValue *Ops, unsigned NumOps,
4067 EVT MemVT, MachinePointerInfo PtrInfo,
4068 unsigned Align, bool Vol,
4069 bool ReadMem, bool WriteMem) {
4070 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
4071 MemVT, PtrInfo, Align, Vol,
4076 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
4077 const SDValue *Ops, unsigned NumOps,
4078 EVT MemVT, MachinePointerInfo PtrInfo,
4079 unsigned Align, bool Vol,
4080 bool ReadMem, bool WriteMem) {
4081 if (Align == 0) // Ensure that codegen never sees alignment 0
4082 Align = getEVTAlignment(MemVT);
4084 MachineFunction &MF = getMachineFunction();
4087 Flags |= MachineMemOperand::MOStore;
4089 Flags |= MachineMemOperand::MOLoad;
4091 Flags |= MachineMemOperand::MOVolatile;
4092 MachineMemOperand *MMO =
4093 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Align);
4095 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
4099 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
4100 const SDValue *Ops, unsigned NumOps,
4101 EVT MemVT, MachineMemOperand *MMO) {
4102 assert((Opcode == ISD::INTRINSIC_VOID ||
4103 Opcode == ISD::INTRINSIC_W_CHAIN ||
4104 Opcode == ISD::PREFETCH ||
4105 (Opcode <= INT_MAX &&
4106 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
4107 "Opcode is not a memory-accessing opcode!");
4109 // Memoize the node unless it returns a flag.
4110 MemIntrinsicSDNode *N;
4111 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4112 FoldingSetNodeID ID;
4113 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4115 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4116 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
4117 return SDValue(E, 0);
4120 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps,
4122 CSEMap.InsertNode(N, IP);
4124 N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps,
4127 AllNodes.push_back(N);
4128 return SDValue(N, 0);
4131 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4132 /// MachinePointerInfo record from it. This is particularly useful because the
4133 /// code generator has many cases where it doesn't bother passing in a
4134 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4135 static MachinePointerInfo InferPointerInfo(SDValue Ptr, int64_t Offset = 0) {
4136 // If this is FI+Offset, we can model it.
4137 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
4138 return MachinePointerInfo::getFixedStack(FI->getIndex(), Offset);
4140 // If this is (FI+Offset1)+Offset2, we can model it.
4141 if (Ptr.getOpcode() != ISD::ADD ||
4142 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
4143 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
4144 return MachinePointerInfo();
4146 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4147 return MachinePointerInfo::getFixedStack(FI, Offset+
4148 cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
4151 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
4152 /// MachinePointerInfo record from it. This is particularly useful because the
4153 /// code generator has many cases where it doesn't bother passing in a
4154 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
4155 static MachinePointerInfo InferPointerInfo(SDValue Ptr, SDValue OffsetOp) {
4156 // If the 'Offset' value isn't a constant, we can't handle this.
4157 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
4158 return InferPointerInfo(Ptr, OffsetNode->getSExtValue());
4159 if (OffsetOp.getOpcode() == ISD::UNDEF)
4160 return InferPointerInfo(Ptr);
4161 return MachinePointerInfo();
4166 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4167 EVT VT, DebugLoc dl, SDValue Chain,
4168 SDValue Ptr, SDValue Offset,
4169 MachinePointerInfo PtrInfo, EVT MemVT,
4170 bool isVolatile, bool isNonTemporal, bool isInvariant,
4171 unsigned Alignment, const MDNode *TBAAInfo) {
4172 assert(Chain.getValueType() == MVT::Other &&
4173 "Invalid chain type");
4174 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4175 Alignment = getEVTAlignment(VT);
4177 unsigned Flags = MachineMemOperand::MOLoad;
4179 Flags |= MachineMemOperand::MOVolatile;
4181 Flags |= MachineMemOperand::MONonTemporal;
4183 Flags |= MachineMemOperand::MOInvariant;
4185 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
4188 PtrInfo = InferPointerInfo(Ptr, Offset);
4190 MachineFunction &MF = getMachineFunction();
4191 MachineMemOperand *MMO =
4192 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
4194 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
4198 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
4199 EVT VT, DebugLoc dl, SDValue Chain,
4200 SDValue Ptr, SDValue Offset, EVT MemVT,
4201 MachineMemOperand *MMO) {
4203 ExtType = ISD::NON_EXTLOAD;
4204 } else if (ExtType == ISD::NON_EXTLOAD) {
4205 assert(VT == MemVT && "Non-extending load from different memory type!");
4208 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
4209 "Should only be an extending load, not truncating!");
4210 assert(VT.isInteger() == MemVT.isInteger() &&
4211 "Cannot convert from FP to Int or Int -> FP!");
4212 assert(VT.isVector() == MemVT.isVector() &&
4213 "Cannot use trunc store to convert to or from a vector!");
4214 assert((!VT.isVector() ||
4215 VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
4216 "Cannot use trunc store to change the number of vector elements!");
4219 bool Indexed = AM != ISD::UNINDEXED;
4220 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
4221 "Unindexed load with an offset!");
4223 SDVTList VTs = Indexed ?
4224 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
4225 SDValue Ops[] = { Chain, Ptr, Offset };
4226 FoldingSetNodeID ID;
4227 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
4228 ID.AddInteger(MemVT.getRawBits());
4229 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
4230 MMO->isNonTemporal(),
4231 MMO->isInvariant()));
4233 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4234 cast<LoadSDNode>(E)->refineAlignment(MMO);
4235 return SDValue(E, 0);
4237 SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl, VTs, AM, ExtType,
4239 CSEMap.InsertNode(N, IP);
4240 AllNodes.push_back(N);
4241 return SDValue(N, 0);
4244 SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
4245 SDValue Chain, SDValue Ptr,
4246 MachinePointerInfo PtrInfo,
4247 bool isVolatile, bool isNonTemporal,
4248 bool isInvariant, unsigned Alignment,
4249 const MDNode *TBAAInfo) {
4250 SDValue Undef = getUNDEF(Ptr.getValueType());
4251 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4252 PtrInfo, VT, isVolatile, isNonTemporal, isInvariant, Alignment,
4256 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
4257 SDValue Chain, SDValue Ptr,
4258 MachinePointerInfo PtrInfo, EVT MemVT,
4259 bool isVolatile, bool isNonTemporal,
4260 unsigned Alignment, const MDNode *TBAAInfo) {
4261 SDValue Undef = getUNDEF(Ptr.getValueType());
4262 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4263 PtrInfo, MemVT, isVolatile, isNonTemporal, false, Alignment,
4269 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
4270 SDValue Offset, ISD::MemIndexedMode AM) {
4271 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
4272 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
4273 "Load is already a indexed load!");
4274 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
4275 LD->getChain(), Base, Offset, LD->getPointerInfo(),
4276 LD->getMemoryVT(), LD->isVolatile(), LD->isNonTemporal(),
4277 false, LD->getAlignment());
4280 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
4281 SDValue Ptr, MachinePointerInfo PtrInfo,
4282 bool isVolatile, bool isNonTemporal,
4283 unsigned Alignment, const MDNode *TBAAInfo) {
4284 assert(Chain.getValueType() == MVT::Other &&
4285 "Invalid chain type");
4286 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4287 Alignment = getEVTAlignment(Val.getValueType());
4289 unsigned Flags = MachineMemOperand::MOStore;
4291 Flags |= MachineMemOperand::MOVolatile;
4293 Flags |= MachineMemOperand::MONonTemporal;
4296 PtrInfo = InferPointerInfo(Ptr);
4298 MachineFunction &MF = getMachineFunction();
4299 MachineMemOperand *MMO =
4300 MF.getMachineMemOperand(PtrInfo, Flags,
4301 Val.getValueType().getStoreSize(), Alignment,
4304 return getStore(Chain, dl, Val, Ptr, MMO);
4307 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
4308 SDValue Ptr, MachineMemOperand *MMO) {
4309 assert(Chain.getValueType() == MVT::Other &&
4310 "Invalid chain type");
4311 EVT VT = Val.getValueType();
4312 SDVTList VTs = getVTList(MVT::Other);
4313 SDValue Undef = getUNDEF(Ptr.getValueType());
4314 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4315 FoldingSetNodeID ID;
4316 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4317 ID.AddInteger(VT.getRawBits());
4318 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
4319 MMO->isNonTemporal(), MMO->isInvariant()));
4321 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4322 cast<StoreSDNode>(E)->refineAlignment(MMO);
4323 return SDValue(E, 0);
4325 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED,
4327 CSEMap.InsertNode(N, IP);
4328 AllNodes.push_back(N);
4329 return SDValue(N, 0);
4332 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
4333 SDValue Ptr, MachinePointerInfo PtrInfo,
4334 EVT SVT,bool isVolatile, bool isNonTemporal,
4336 const MDNode *TBAAInfo) {
4337 assert(Chain.getValueType() == MVT::Other &&
4338 "Invalid chain type");
4339 if (Alignment == 0) // Ensure that codegen never sees alignment 0
4340 Alignment = getEVTAlignment(SVT);
4342 unsigned Flags = MachineMemOperand::MOStore;
4344 Flags |= MachineMemOperand::MOVolatile;
4346 Flags |= MachineMemOperand::MONonTemporal;
4349 PtrInfo = InferPointerInfo(Ptr);
4351 MachineFunction &MF = getMachineFunction();
4352 MachineMemOperand *MMO =
4353 MF.getMachineMemOperand(PtrInfo, Flags, SVT.getStoreSize(), Alignment,
4356 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
4359 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
4360 SDValue Ptr, EVT SVT,
4361 MachineMemOperand *MMO) {
4362 EVT VT = Val.getValueType();
4364 assert(Chain.getValueType() == MVT::Other &&
4365 "Invalid chain type");
4367 return getStore(Chain, dl, Val, Ptr, MMO);
4369 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
4370 "Should only be a truncating store, not extending!");
4371 assert(VT.isInteger() == SVT.isInteger() &&
4372 "Can't do FP-INT conversion!");
4373 assert(VT.isVector() == SVT.isVector() &&
4374 "Cannot use trunc store to convert to or from a vector!");
4375 assert((!VT.isVector() ||
4376 VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
4377 "Cannot use trunc store to change the number of vector elements!");
4379 SDVTList VTs = getVTList(MVT::Other);
4380 SDValue Undef = getUNDEF(Ptr.getValueType());
4381 SDValue Ops[] = { Chain, Val, Ptr, Undef };
4382 FoldingSetNodeID ID;
4383 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4384 ID.AddInteger(SVT.getRawBits());
4385 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
4386 MMO->isNonTemporal(), MMO->isInvariant()));
4388 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4389 cast<StoreSDNode>(E)->refineAlignment(MMO);
4390 return SDValue(E, 0);
4392 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED,
4394 CSEMap.InsertNode(N, IP);
4395 AllNodes.push_back(N);
4396 return SDValue(N, 0);
4400 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
4401 SDValue Offset, ISD::MemIndexedMode AM) {
4402 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4403 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4404 "Store is already a indexed store!");
4405 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4406 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4407 FoldingSetNodeID ID;
4408 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4409 ID.AddInteger(ST->getMemoryVT().getRawBits());
4410 ID.AddInteger(ST->getRawSubclassData());
4412 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4413 return SDValue(E, 0);
4415 SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, AM,
4416 ST->isTruncatingStore(),
4418 ST->getMemOperand());
4419 CSEMap.InsertNode(N, IP);
4420 AllNodes.push_back(N);
4421 return SDValue(N, 0);
4424 SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
4425 SDValue Chain, SDValue Ptr,
4428 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, MVT::i32) };
4429 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 4);
4432 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4433 const SDUse *Ops, unsigned NumOps) {
4435 case 0: return getNode(Opcode, DL, VT);
4436 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4437 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4438 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4442 // Copy from an SDUse array into an SDValue array for use with
4443 // the regular getNode logic.
4444 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4445 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4448 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4449 const SDValue *Ops, unsigned NumOps) {
4451 case 0: return getNode(Opcode, DL, VT);
4452 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4453 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4454 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4460 case ISD::SELECT_CC: {
4461 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4462 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4463 "LHS and RHS of condition must have same type!");
4464 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4465 "True and False arms of SelectCC must have same type!");
4466 assert(Ops[2].getValueType() == VT &&
4467 "select_cc node must be of same type as true and false value!");
4471 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4472 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4473 "LHS/RHS of comparison should match types!");
4480 SDVTList VTs = getVTList(VT);
4482 if (VT != MVT::Glue) {
4483 FoldingSetNodeID ID;
4484 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4487 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4488 return SDValue(E, 0);
4490 N = new (NodeAllocator) SDNode(Opcode, DL, VTs, Ops, NumOps);
4491 CSEMap.InsertNode(N, IP);
4493 N = new (NodeAllocator) SDNode(Opcode, DL, VTs, Ops, NumOps);
4496 AllNodes.push_back(N);
4500 return SDValue(N, 0);
4503 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4504 const std::vector<EVT> &ResultTys,
4505 const SDValue *Ops, unsigned NumOps) {
4506 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4510 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4511 const EVT *VTs, unsigned NumVTs,
4512 const SDValue *Ops, unsigned NumOps) {
4514 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4515 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4518 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4519 const SDValue *Ops, unsigned NumOps) {
4520 if (VTList.NumVTs == 1)
4521 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4525 // FIXME: figure out how to safely handle things like
4526 // int foo(int x) { return 1 << (x & 255); }
4527 // int bar() { return foo(256); }
4528 case ISD::SRA_PARTS:
4529 case ISD::SRL_PARTS:
4530 case ISD::SHL_PARTS:
4531 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4532 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4533 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4534 else if (N3.getOpcode() == ISD::AND)
4535 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4536 // If the and is only masking out bits that cannot effect the shift,
4537 // eliminate the and.
4538 unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
4539 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4540 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4546 // Memoize the node unless it returns a flag.
4548 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4549 FoldingSetNodeID ID;
4550 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4552 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4553 return SDValue(E, 0);
4556 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4557 } else if (NumOps == 2) {
4558 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4559 } else if (NumOps == 3) {
4560 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1],
4563 N = new (NodeAllocator) SDNode(Opcode, DL, VTList, Ops, NumOps);
4565 CSEMap.InsertNode(N, IP);
4568 N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4569 } else if (NumOps == 2) {
4570 N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4571 } else if (NumOps == 3) {
4572 N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1],
4575 N = new (NodeAllocator) SDNode(Opcode, DL, VTList, Ops, NumOps);
4578 AllNodes.push_back(N);
4582 return SDValue(N, 0);
4585 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4586 return getNode(Opcode, DL, VTList, 0, 0);
4589 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4591 SDValue Ops[] = { N1 };
4592 return getNode(Opcode, DL, VTList, Ops, 1);
4595 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4596 SDValue N1, SDValue N2) {
4597 SDValue Ops[] = { N1, N2 };
4598 return getNode(Opcode, DL, VTList, Ops, 2);
4601 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4602 SDValue N1, SDValue N2, SDValue N3) {
4603 SDValue Ops[] = { N1, N2, N3 };
4604 return getNode(Opcode, DL, VTList, Ops, 3);
4607 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4608 SDValue N1, SDValue N2, SDValue N3,
4610 SDValue Ops[] = { N1, N2, N3, N4 };
4611 return getNode(Opcode, DL, VTList, Ops, 4);
4614 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4615 SDValue N1, SDValue N2, SDValue N3,
4616 SDValue N4, SDValue N5) {
4617 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4618 return getNode(Opcode, DL, VTList, Ops, 5);
4621 SDVTList SelectionDAG::getVTList(EVT VT) {
4622 return makeVTList(SDNode::getValueTypeList(VT), 1);
4625 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4626 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4627 E = VTList.rend(); I != E; ++I)
4628 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4631 EVT *Array = Allocator.Allocate<EVT>(2);
4634 SDVTList Result = makeVTList(Array, 2);
4635 VTList.push_back(Result);
4639 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4640 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4641 E = VTList.rend(); I != E; ++I)
4642 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4646 EVT *Array = Allocator.Allocate<EVT>(3);
4650 SDVTList Result = makeVTList(Array, 3);
4651 VTList.push_back(Result);
4655 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4656 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4657 E = VTList.rend(); I != E; ++I)
4658 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4659 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4662 EVT *Array = Allocator.Allocate<EVT>(4);
4667 SDVTList Result = makeVTList(Array, 4);
4668 VTList.push_back(Result);
4672 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4674 case 0: llvm_unreachable("Cannot have nodes without results!");
4675 case 1: return getVTList(VTs[0]);
4676 case 2: return getVTList(VTs[0], VTs[1]);
4677 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4678 case 4: return getVTList(VTs[0], VTs[1], VTs[2], VTs[3]);
4682 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4683 E = VTList.rend(); I != E; ++I) {
4684 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4687 bool NoMatch = false;
4688 for (unsigned i = 2; i != NumVTs; ++i)
4689 if (VTs[i] != I->VTs[i]) {
4697 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4698 std::copy(VTs, VTs+NumVTs, Array);
4699 SDVTList Result = makeVTList(Array, NumVTs);
4700 VTList.push_back(Result);
4705 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4706 /// specified operands. If the resultant node already exists in the DAG,
4707 /// this does not modify the specified node, instead it returns the node that
4708 /// already exists. If the resultant node does not exist in the DAG, the
4709 /// input node is returned. As a degenerate case, if you specify the same
4710 /// input operands as the node already has, the input node is returned.
4711 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
4712 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4714 // Check to see if there is no change.
4715 if (Op == N->getOperand(0)) return N;
4717 // See if the modified node already exists.
4718 void *InsertPos = 0;
4719 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4722 // Nope it doesn't. Remove the node from its current place in the maps.
4724 if (!RemoveNodeFromCSEMaps(N))
4727 // Now we update the operands.
4728 N->OperandList[0].set(Op);
4730 // If this gets put into a CSE map, add it.
4731 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4735 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
4736 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4738 // Check to see if there is no change.
4739 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4740 return N; // No operands changed, just return the input node.
4742 // See if the modified node already exists.
4743 void *InsertPos = 0;
4744 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4747 // Nope it doesn't. Remove the node from its current place in the maps.
4749 if (!RemoveNodeFromCSEMaps(N))
4752 // Now we update the operands.
4753 if (N->OperandList[0] != Op1)
4754 N->OperandList[0].set(Op1);
4755 if (N->OperandList[1] != Op2)
4756 N->OperandList[1].set(Op2);
4758 // If this gets put into a CSE map, add it.
4759 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4763 SDNode *SelectionDAG::
4764 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
4765 SDValue Ops[] = { Op1, Op2, Op3 };
4766 return UpdateNodeOperands(N, Ops, 3);
4769 SDNode *SelectionDAG::
4770 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
4771 SDValue Op3, SDValue Op4) {
4772 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4773 return UpdateNodeOperands(N, Ops, 4);
4776 SDNode *SelectionDAG::
4777 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
4778 SDValue Op3, SDValue Op4, SDValue Op5) {
4779 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4780 return UpdateNodeOperands(N, Ops, 5);
4783 SDNode *SelectionDAG::
4784 UpdateNodeOperands(SDNode *N, const SDValue *Ops, unsigned NumOps) {
4785 assert(N->getNumOperands() == NumOps &&
4786 "Update with wrong number of operands");
4788 // Check to see if there is no change.
4789 bool AnyChange = false;
4790 for (unsigned i = 0; i != NumOps; ++i) {
4791 if (Ops[i] != N->getOperand(i)) {
4797 // No operands changed, just return the input node.
4798 if (!AnyChange) return N;
4800 // See if the modified node already exists.
4801 void *InsertPos = 0;
4802 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4805 // Nope it doesn't. Remove the node from its current place in the maps.
4807 if (!RemoveNodeFromCSEMaps(N))
4810 // Now we update the operands.
4811 for (unsigned i = 0; i != NumOps; ++i)
4812 if (N->OperandList[i] != Ops[i])
4813 N->OperandList[i].set(Ops[i]);
4815 // If this gets put into a CSE map, add it.
4816 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4820 /// DropOperands - Release the operands and set this node to have
4822 void SDNode::DropOperands() {
4823 // Unlike the code in MorphNodeTo that does this, we don't need to
4824 // watch for dead nodes here.
4825 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4831 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4834 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4836 SDVTList VTs = getVTList(VT);
4837 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4840 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4841 EVT VT, SDValue Op1) {
4842 SDVTList VTs = getVTList(VT);
4843 SDValue Ops[] = { Op1 };
4844 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4847 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4848 EVT VT, SDValue Op1,
4850 SDVTList VTs = getVTList(VT);
4851 SDValue Ops[] = { Op1, Op2 };
4852 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4855 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4856 EVT VT, SDValue Op1,
4857 SDValue Op2, SDValue Op3) {
4858 SDVTList VTs = getVTList(VT);
4859 SDValue Ops[] = { Op1, Op2, Op3 };
4860 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4863 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4864 EVT VT, const SDValue *Ops,
4866 SDVTList VTs = getVTList(VT);
4867 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4870 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4871 EVT VT1, EVT VT2, const SDValue *Ops,
4873 SDVTList VTs = getVTList(VT1, VT2);
4874 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4877 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4879 SDVTList VTs = getVTList(VT1, VT2);
4880 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4883 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4884 EVT VT1, EVT VT2, EVT VT3,
4885 const SDValue *Ops, unsigned NumOps) {
4886 SDVTList VTs = getVTList(VT1, VT2, VT3);
4887 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4890 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4891 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4892 const SDValue *Ops, unsigned NumOps) {
4893 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4894 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4897 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4900 SDVTList VTs = getVTList(VT1, VT2);
4901 SDValue Ops[] = { Op1 };
4902 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4905 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4907 SDValue Op1, SDValue Op2) {
4908 SDVTList VTs = getVTList(VT1, VT2);
4909 SDValue Ops[] = { Op1, Op2 };
4910 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4913 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4915 SDValue Op1, SDValue Op2,
4917 SDVTList VTs = getVTList(VT1, VT2);
4918 SDValue Ops[] = { Op1, Op2, Op3 };
4919 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4922 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4923 EVT VT1, EVT VT2, EVT VT3,
4924 SDValue Op1, SDValue Op2,
4926 SDVTList VTs = getVTList(VT1, VT2, VT3);
4927 SDValue Ops[] = { Op1, Op2, Op3 };
4928 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4931 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4932 SDVTList VTs, const SDValue *Ops,
4934 N = MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4935 // Reset the NodeID to -1.
4940 /// UpdadeDebugLocOnMergedSDNode - If the opt level is -O0 then it throws away
4941 /// the line number information on the merged node since it is not possible to
4942 /// preserve the information that operation is associated with multiple lines.
4943 /// This will make the debugger working better at -O0, were there is a higher
4944 /// probability having other instructions associated with that line.
4946 SDNode *SelectionDAG::UpdadeDebugLocOnMergedSDNode(SDNode *N, DebugLoc OLoc) {
4947 DebugLoc NLoc = N->getDebugLoc();
4948 if (!(NLoc.isUnknown()) && (OptLevel == CodeGenOpt::None) && (OLoc != NLoc)) {
4949 N->setDebugLoc(DebugLoc());
4954 /// MorphNodeTo - This *mutates* the specified node to have the specified
4955 /// return type, opcode, and operands.
4957 /// Note that MorphNodeTo returns the resultant node. If there is already a
4958 /// node of the specified opcode and operands, it returns that node instead of
4959 /// the current one. Note that the DebugLoc need not be the same.
4961 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4962 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4963 /// node, and because it doesn't require CSE recalculation for any of
4964 /// the node's users.
4966 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4967 SDVTList VTs, const SDValue *Ops,
4969 // If an identical node already exists, use it.
4971 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
4972 FoldingSetNodeID ID;
4973 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4974 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4975 return UpdadeDebugLocOnMergedSDNode(ON, N->getDebugLoc());
4978 if (!RemoveNodeFromCSEMaps(N))
4981 // Start the morphing.
4983 N->ValueList = VTs.VTs;
4984 N->NumValues = VTs.NumVTs;
4986 // Clear the operands list, updating used nodes to remove this from their
4987 // use list. Keep track of any operands that become dead as a result.
4988 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4989 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4991 SDNode *Used = Use.getNode();
4993 if (Used->use_empty())
4994 DeadNodeSet.insert(Used);
4997 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
4998 // Initialize the memory references information.
4999 MN->setMemRefs(0, 0);
5000 // If NumOps is larger than the # of operands we can have in a
5001 // MachineSDNode, reallocate the operand list.
5002 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
5003 if (MN->OperandsNeedDelete)
5004 delete[] MN->OperandList;
5005 if (NumOps > array_lengthof(MN->LocalOperands))
5006 // We're creating a final node that will live unmorphed for the
5007 // remainder of the current SelectionDAG iteration, so we can allocate
5008 // the operands directly out of a pool with no recycling metadata.
5009 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5012 MN->InitOperands(MN->LocalOperands, Ops, NumOps);
5013 MN->OperandsNeedDelete = false;
5015 MN->InitOperands(MN->OperandList, Ops, NumOps);
5017 // If NumOps is larger than the # of operands we currently have, reallocate
5018 // the operand list.
5019 if (NumOps > N->NumOperands) {
5020 if (N->OperandsNeedDelete)
5021 delete[] N->OperandList;
5022 N->InitOperands(new SDUse[NumOps], Ops, NumOps);
5023 N->OperandsNeedDelete = true;
5025 N->InitOperands(N->OperandList, Ops, NumOps);
5028 // Delete any nodes that are still dead after adding the uses for the
5030 if (!DeadNodeSet.empty()) {
5031 SmallVector<SDNode *, 16> DeadNodes;
5032 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
5033 E = DeadNodeSet.end(); I != E; ++I)
5034 if ((*I)->use_empty())
5035 DeadNodes.push_back(*I);
5036 RemoveDeadNodes(DeadNodes);
5040 CSEMap.InsertNode(N, IP); // Memoize the new node.
5045 /// getMachineNode - These are used for target selectors to create a new node
5046 /// with specified return type(s), MachineInstr opcode, and operands.
5048 /// Note that getMachineNode returns the resultant node. If there is already a
5049 /// node of the specified opcode and operands, it returns that node instead of
5050 /// the current one.
5052 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
5053 SDVTList VTs = getVTList(VT);
5054 return getMachineNode(Opcode, dl, VTs, 0, 0);
5058 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
5059 SDVTList VTs = getVTList(VT);
5060 SDValue Ops[] = { Op1 };
5061 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5065 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
5066 SDValue Op1, SDValue Op2) {
5067 SDVTList VTs = getVTList(VT);
5068 SDValue Ops[] = { Op1, Op2 };
5069 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5073 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
5074 SDValue Op1, SDValue Op2, SDValue Op3) {
5075 SDVTList VTs = getVTList(VT);
5076 SDValue Ops[] = { Op1, Op2, Op3 };
5077 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5081 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
5082 const SDValue *Ops, unsigned NumOps) {
5083 SDVTList VTs = getVTList(VT);
5084 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
5088 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
5089 SDVTList VTs = getVTList(VT1, VT2);
5090 return getMachineNode(Opcode, dl, VTs, 0, 0);
5094 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5095 EVT VT1, EVT VT2, SDValue Op1) {
5096 SDVTList VTs = getVTList(VT1, VT2);
5097 SDValue Ops[] = { Op1 };
5098 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5102 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5103 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
5104 SDVTList VTs = getVTList(VT1, VT2);
5105 SDValue Ops[] = { Op1, Op2 };
5106 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5110 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5111 EVT VT1, EVT VT2, SDValue Op1,
5112 SDValue Op2, SDValue Op3) {
5113 SDVTList VTs = getVTList(VT1, VT2);
5114 SDValue Ops[] = { Op1, Op2, Op3 };
5115 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5119 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5121 const SDValue *Ops, unsigned NumOps) {
5122 SDVTList VTs = getVTList(VT1, VT2);
5123 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
5127 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5128 EVT VT1, EVT VT2, EVT VT3,
5129 SDValue Op1, SDValue Op2) {
5130 SDVTList VTs = getVTList(VT1, VT2, VT3);
5131 SDValue Ops[] = { Op1, Op2 };
5132 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5136 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5137 EVT VT1, EVT VT2, EVT VT3,
5138 SDValue Op1, SDValue Op2, SDValue Op3) {
5139 SDVTList VTs = getVTList(VT1, VT2, VT3);
5140 SDValue Ops[] = { Op1, Op2, Op3 };
5141 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
5145 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5146 EVT VT1, EVT VT2, EVT VT3,
5147 const SDValue *Ops, unsigned NumOps) {
5148 SDVTList VTs = getVTList(VT1, VT2, VT3);
5149 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
5153 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
5154 EVT VT2, EVT VT3, EVT VT4,
5155 const SDValue *Ops, unsigned NumOps) {
5156 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
5157 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
5161 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
5162 const std::vector<EVT> &ResultTys,
5163 const SDValue *Ops, unsigned NumOps) {
5164 SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
5165 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
5169 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
5170 const SDValue *Ops, unsigned NumOps) {
5171 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
5176 FoldingSetNodeID ID;
5177 AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
5179 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
5180 return cast<MachineSDNode>(UpdadeDebugLocOnMergedSDNode(E, DL));
5184 // Allocate a new MachineSDNode.
5185 N = new (NodeAllocator) MachineSDNode(~Opcode, DL, VTs);
5187 // Initialize the operands list.
5188 if (NumOps > array_lengthof(N->LocalOperands))
5189 // We're creating a final node that will live unmorphed for the
5190 // remainder of the current SelectionDAG iteration, so we can allocate
5191 // the operands directly out of a pool with no recycling metadata.
5192 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
5195 N->InitOperands(N->LocalOperands, Ops, NumOps);
5196 N->OperandsNeedDelete = false;
5199 CSEMap.InsertNode(N, IP);
5201 AllNodes.push_back(N);
5203 VerifyMachineNode(N);
5208 /// getTargetExtractSubreg - A convenience function for creating
5209 /// TargetOpcode::EXTRACT_SUBREG nodes.
5211 SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
5213 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5214 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
5215 VT, Operand, SRIdxVal);
5216 return SDValue(Subreg, 0);
5219 /// getTargetInsertSubreg - A convenience function for creating
5220 /// TargetOpcode::INSERT_SUBREG nodes.
5222 SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
5223 SDValue Operand, SDValue Subreg) {
5224 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
5225 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
5226 VT, Operand, Subreg, SRIdxVal);
5227 return SDValue(Result, 0);
5230 /// getNodeIfExists - Get the specified node if it's already available, or
5231 /// else return NULL.
5232 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
5233 const SDValue *Ops, unsigned NumOps) {
5234 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
5235 FoldingSetNodeID ID;
5236 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
5238 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5244 /// getDbgValue - Creates a SDDbgValue node.
5247 SelectionDAG::getDbgValue(MDNode *MDPtr, SDNode *N, unsigned R, uint64_t Off,
5248 DebugLoc DL, unsigned O) {
5249 return new (Allocator) SDDbgValue(MDPtr, N, R, Off, DL, O);
5253 SelectionDAG::getDbgValue(MDNode *MDPtr, const Value *C, uint64_t Off,
5254 DebugLoc DL, unsigned O) {
5255 return new (Allocator) SDDbgValue(MDPtr, C, Off, DL, O);
5259 SelectionDAG::getDbgValue(MDNode *MDPtr, unsigned FI, uint64_t Off,
5260 DebugLoc DL, unsigned O) {
5261 return new (Allocator) SDDbgValue(MDPtr, FI, Off, DL, O);
5266 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
5267 /// pointed to by a use iterator is deleted, increment the use iterator
5268 /// so that it doesn't dangle.
5270 /// This class also manages a "downlink" DAGUpdateListener, to forward
5271 /// messages to ReplaceAllUsesWith's callers.
5273 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
5274 SelectionDAG::DAGUpdateListener *DownLink;
5275 SDNode::use_iterator &UI;
5276 SDNode::use_iterator &UE;
5278 virtual void NodeDeleted(SDNode *N, SDNode *E) {
5279 // Increment the iterator as needed.
5280 while (UI != UE && N == *UI)
5283 // Then forward the message.
5284 if (DownLink) DownLink->NodeDeleted(N, E);
5287 virtual void NodeUpdated(SDNode *N) {
5288 // Just forward the message.
5289 if (DownLink) DownLink->NodeUpdated(N);
5293 RAUWUpdateListener(SelectionDAG::DAGUpdateListener *dl,
5294 SDNode::use_iterator &ui,
5295 SDNode::use_iterator &ue)
5296 : DownLink(dl), UI(ui), UE(ue) {}
5301 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5302 /// This can cause recursive merging of nodes in the DAG.
5304 /// This version assumes From has a single result value.
5306 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
5307 DAGUpdateListener *UpdateListener) {
5308 SDNode *From = FromN.getNode();
5309 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
5310 "Cannot replace with this method!");
5311 assert(From != To.getNode() && "Cannot replace uses of with self");
5313 // Iterate over all the existing uses of From. New uses will be added
5314 // to the beginning of the use list, which we avoid visiting.
5315 // This specifically avoids visiting uses of From that arise while the
5316 // replacement is happening, because any such uses would be the result
5317 // of CSE: If an existing node looks like From after one of its operands
5318 // is replaced by To, we don't want to replace of all its users with To
5319 // too. See PR3018 for more info.
5320 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5321 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5325 // This node is about to morph, remove its old self from the CSE maps.
5326 RemoveNodeFromCSEMaps(User);
5328 // A user can appear in a use list multiple times, and when this
5329 // happens the uses are usually next to each other in the list.
5330 // To help reduce the number of CSE recomputations, process all
5331 // the uses of this user that we can find this way.
5333 SDUse &Use = UI.getUse();
5336 } while (UI != UE && *UI == User);
5338 // Now that we have modified User, add it back to the CSE maps. If it
5339 // already exists there, recursively merge the results together.
5340 AddModifiedNodeToCSEMaps(User, &Listener);
5343 // If we just RAUW'd the root, take note.
5344 if (FromN == getRoot())
5348 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5349 /// This can cause recursive merging of nodes in the DAG.
5351 /// This version assumes that for each value of From, there is a
5352 /// corresponding value in To in the same position with the same type.
5354 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
5355 DAGUpdateListener *UpdateListener) {
5357 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
5358 assert((!From->hasAnyUseOfValue(i) ||
5359 From->getValueType(i) == To->getValueType(i)) &&
5360 "Cannot use this version of ReplaceAllUsesWith!");
5363 // Handle the trivial case.
5367 // Iterate over just the existing users of From. See the comments in
5368 // the ReplaceAllUsesWith above.
5369 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5370 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5374 // This node is about to morph, remove its old self from the CSE maps.
5375 RemoveNodeFromCSEMaps(User);
5377 // A user can appear in a use list multiple times, and when this
5378 // happens the uses are usually next to each other in the list.
5379 // To help reduce the number of CSE recomputations, process all
5380 // the uses of this user that we can find this way.
5382 SDUse &Use = UI.getUse();
5385 } while (UI != UE && *UI == User);
5387 // Now that we have modified User, add it back to the CSE maps. If it
5388 // already exists there, recursively merge the results together.
5389 AddModifiedNodeToCSEMaps(User, &Listener);
5392 // If we just RAUW'd the root, take note.
5393 if (From == getRoot().getNode())
5394 setRoot(SDValue(To, getRoot().getResNo()));
5397 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5398 /// This can cause recursive merging of nodes in the DAG.
5400 /// This version can replace From with any result values. To must match the
5401 /// number and types of values returned by From.
5402 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
5404 DAGUpdateListener *UpdateListener) {
5405 if (From->getNumValues() == 1) // Handle the simple case efficiently.
5406 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
5408 // Iterate over just the existing users of From. See the comments in
5409 // the ReplaceAllUsesWith above.
5410 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5411 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5415 // This node is about to morph, remove its old self from the CSE maps.
5416 RemoveNodeFromCSEMaps(User);
5418 // A user can appear in a use list multiple times, and when this
5419 // happens the uses are usually next to each other in the list.
5420 // To help reduce the number of CSE recomputations, process all
5421 // the uses of this user that we can find this way.
5423 SDUse &Use = UI.getUse();
5424 const SDValue &ToOp = To[Use.getResNo()];
5427 } while (UI != UE && *UI == User);
5429 // Now that we have modified User, add it back to the CSE maps. If it
5430 // already exists there, recursively merge the results together.
5431 AddModifiedNodeToCSEMaps(User, &Listener);
5434 // If we just RAUW'd the root, take note.
5435 if (From == getRoot().getNode())
5436 setRoot(SDValue(To[getRoot().getResNo()]));
5439 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5440 /// uses of other values produced by From.getNode() alone. The Deleted
5441 /// vector is handled the same way as for ReplaceAllUsesWith.
5442 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
5443 DAGUpdateListener *UpdateListener){
5444 // Handle the really simple, really trivial case efficiently.
5445 if (From == To) return;
5447 // Handle the simple, trivial, case efficiently.
5448 if (From.getNode()->getNumValues() == 1) {
5449 ReplaceAllUsesWith(From, To, UpdateListener);
5453 // Iterate over just the existing users of From. See the comments in
5454 // the ReplaceAllUsesWith above.
5455 SDNode::use_iterator UI = From.getNode()->use_begin(),
5456 UE = From.getNode()->use_end();
5457 RAUWUpdateListener Listener(UpdateListener, UI, UE);
5460 bool UserRemovedFromCSEMaps = false;
5462 // A user can appear in a use list multiple times, and when this
5463 // happens the uses are usually next to each other in the list.
5464 // To help reduce the number of CSE recomputations, process all
5465 // the uses of this user that we can find this way.
5467 SDUse &Use = UI.getUse();
5469 // Skip uses of different values from the same node.
5470 if (Use.getResNo() != From.getResNo()) {
5475 // If this node hasn't been modified yet, it's still in the CSE maps,
5476 // so remove its old self from the CSE maps.
5477 if (!UserRemovedFromCSEMaps) {
5478 RemoveNodeFromCSEMaps(User);
5479 UserRemovedFromCSEMaps = true;
5484 } while (UI != UE && *UI == User);
5486 // We are iterating over all uses of the From node, so if a use
5487 // doesn't use the specific value, no changes are made.
5488 if (!UserRemovedFromCSEMaps)
5491 // Now that we have modified User, add it back to the CSE maps. If it
5492 // already exists there, recursively merge the results together.
5493 AddModifiedNodeToCSEMaps(User, &Listener);
5496 // If we just RAUW'd the root, take note.
5497 if (From == getRoot())
5502 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5503 /// to record information about a use.
5510 /// operator< - Sort Memos by User.
5511 bool operator<(const UseMemo &L, const UseMemo &R) {
5512 return (intptr_t)L.User < (intptr_t)R.User;
5516 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5517 /// uses of other values produced by From.getNode() alone. The same value
5518 /// may appear in both the From and To list. The Deleted vector is
5519 /// handled the same way as for ReplaceAllUsesWith.
5520 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5523 DAGUpdateListener *UpdateListener){
5524 // Handle the simple, trivial case efficiently.
5526 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5528 // Read up all the uses and make records of them. This helps
5529 // processing new uses that are introduced during the
5530 // replacement process.
5531 SmallVector<UseMemo, 4> Uses;
5532 for (unsigned i = 0; i != Num; ++i) {
5533 unsigned FromResNo = From[i].getResNo();
5534 SDNode *FromNode = From[i].getNode();
5535 for (SDNode::use_iterator UI = FromNode->use_begin(),
5536 E = FromNode->use_end(); UI != E; ++UI) {
5537 SDUse &Use = UI.getUse();
5538 if (Use.getResNo() == FromResNo) {
5539 UseMemo Memo = { *UI, i, &Use };
5540 Uses.push_back(Memo);
5545 // Sort the uses, so that all the uses from a given User are together.
5546 std::sort(Uses.begin(), Uses.end());
5548 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5549 UseIndex != UseIndexEnd; ) {
5550 // We know that this user uses some value of From. If it is the right
5551 // value, update it.
5552 SDNode *User = Uses[UseIndex].User;
5554 // This node is about to morph, remove its old self from the CSE maps.
5555 RemoveNodeFromCSEMaps(User);
5557 // The Uses array is sorted, so all the uses for a given User
5558 // are next to each other in the list.
5559 // To help reduce the number of CSE recomputations, process all
5560 // the uses of this user that we can find this way.
5562 unsigned i = Uses[UseIndex].Index;
5563 SDUse &Use = *Uses[UseIndex].Use;
5567 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5569 // Now that we have modified User, add it back to the CSE maps. If it
5570 // already exists there, recursively merge the results together.
5571 AddModifiedNodeToCSEMaps(User, UpdateListener);
5575 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5576 /// based on their topological order. It returns the maximum id and a vector
5577 /// of the SDNodes* in assigned order by reference.
5578 unsigned SelectionDAG::AssignTopologicalOrder() {
5580 unsigned DAGSize = 0;
5582 // SortedPos tracks the progress of the algorithm. Nodes before it are
5583 // sorted, nodes after it are unsorted. When the algorithm completes
5584 // it is at the end of the list.
5585 allnodes_iterator SortedPos = allnodes_begin();
5587 // Visit all the nodes. Move nodes with no operands to the front of
5588 // the list immediately. Annotate nodes that do have operands with their
5589 // operand count. Before we do this, the Node Id fields of the nodes
5590 // may contain arbitrary values. After, the Node Id fields for nodes
5591 // before SortedPos will contain the topological sort index, and the
5592 // Node Id fields for nodes At SortedPos and after will contain the
5593 // count of outstanding operands.
5594 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5597 unsigned Degree = N->getNumOperands();
5599 // A node with no uses, add it to the result array immediately.
5600 N->setNodeId(DAGSize++);
5601 allnodes_iterator Q = N;
5603 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5604 assert(SortedPos != AllNodes.end() && "Overran node list");
5607 // Temporarily use the Node Id as scratch space for the degree count.
5608 N->setNodeId(Degree);
5612 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5613 // such that by the time the end is reached all nodes will be sorted.
5614 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5617 // N is in sorted position, so all its uses have one less operand
5618 // that needs to be sorted.
5619 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5622 unsigned Degree = P->getNodeId();
5623 assert(Degree != 0 && "Invalid node degree");
5626 // All of P's operands are sorted, so P may sorted now.
5627 P->setNodeId(DAGSize++);
5629 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5630 assert(SortedPos != AllNodes.end() && "Overran node list");
5633 // Update P's outstanding operand count.
5634 P->setNodeId(Degree);
5637 if (I == SortedPos) {
5640 dbgs() << "Overran sorted position:\n";
5643 llvm_unreachable(0);
5647 assert(SortedPos == AllNodes.end() &&
5648 "Topological sort incomplete!");
5649 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5650 "First node in topological sort is not the entry token!");
5651 assert(AllNodes.front().getNodeId() == 0 &&
5652 "First node in topological sort has non-zero id!");
5653 assert(AllNodes.front().getNumOperands() == 0 &&
5654 "First node in topological sort has operands!");
5655 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5656 "Last node in topologic sort has unexpected id!");
5657 assert(AllNodes.back().use_empty() &&
5658 "Last node in topologic sort has users!");
5659 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5663 /// AssignOrdering - Assign an order to the SDNode.
5664 void SelectionDAG::AssignOrdering(const SDNode *SD, unsigned Order) {
5665 assert(SD && "Trying to assign an order to a null node!");
5666 Ordering->add(SD, Order);
5669 /// GetOrdering - Get the order for the SDNode.
5670 unsigned SelectionDAG::GetOrdering(const SDNode *SD) const {
5671 assert(SD && "Trying to get the order of a null node!");
5672 return Ordering->getOrder(SD);
5675 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
5676 /// value is produced by SD.
5677 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
5678 DbgInfo->add(DB, SD, isParameter);
5680 SD->setHasDebugValue(true);
5683 /// TransferDbgValues - Transfer SDDbgValues.
5684 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) {
5685 if (From == To || !From.getNode()->getHasDebugValue())
5687 SDNode *FromNode = From.getNode();
5688 SDNode *ToNode = To.getNode();
5689 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode);
5690 SmallVector<SDDbgValue *, 2> ClonedDVs;
5691 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end();
5693 SDDbgValue *Dbg = *I;
5694 if (Dbg->getKind() == SDDbgValue::SDNODE) {
5695 SDDbgValue *Clone = getDbgValue(Dbg->getMDPtr(), ToNode, To.getResNo(),
5696 Dbg->getOffset(), Dbg->getDebugLoc(),
5698 ClonedDVs.push_back(Clone);
5701 for (SmallVector<SDDbgValue *, 2>::iterator I = ClonedDVs.begin(),
5702 E = ClonedDVs.end(); I != E; ++I)
5703 AddDbgValue(*I, ToNode, false);
5706 //===----------------------------------------------------------------------===//
5708 //===----------------------------------------------------------------------===//
5710 HandleSDNode::~HandleSDNode() {
5714 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, DebugLoc DL,
5715 const GlobalValue *GA,
5716 EVT VT, int64_t o, unsigned char TF)
5717 : SDNode(Opc, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
5721 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
5722 MachineMemOperand *mmo)
5723 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5724 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5725 MMO->isNonTemporal(), MMO->isInvariant());
5726 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5727 assert(isNonTemporal() == MMO->isNonTemporal() &&
5728 "Non-temporal encoding error!");
5729 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5732 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5733 const SDValue *Ops, unsigned NumOps, EVT memvt,
5734 MachineMemOperand *mmo)
5735 : SDNode(Opc, dl, VTs, Ops, NumOps),
5736 MemoryVT(memvt), MMO(mmo) {
5737 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5738 MMO->isNonTemporal(), MMO->isInvariant());
5739 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5740 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5743 /// Profile - Gather unique data for the node.
5745 void SDNode::Profile(FoldingSetNodeID &ID) const {
5746 AddNodeIDNode(ID, this);
5751 std::vector<EVT> VTs;
5754 VTs.reserve(MVT::LAST_VALUETYPE);
5755 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5756 VTs.push_back(MVT((MVT::SimpleValueType)i));
5761 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5762 static ManagedStatic<EVTArray> SimpleVTArray;
5763 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5765 /// getValueTypeList - Return a pointer to the specified value type.
5767 const EVT *SDNode::getValueTypeList(EVT VT) {
5768 if (VT.isExtended()) {
5769 sys::SmartScopedLock<true> Lock(*VTMutex);
5770 return &(*EVTs->insert(VT).first);
5772 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
5773 "Value type out of range!");
5774 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5778 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5779 /// indicated value. This method ignores uses of other values defined by this
5781 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5782 assert(Value < getNumValues() && "Bad value!");
5784 // TODO: Only iterate over uses of a given value of the node
5785 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5786 if (UI.getUse().getResNo() == Value) {
5793 // Found exactly the right number of uses?
5798 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5799 /// value. This method ignores uses of other values defined by this operation.
5800 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5801 assert(Value < getNumValues() && "Bad value!");
5803 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5804 if (UI.getUse().getResNo() == Value)
5811 /// isOnlyUserOf - Return true if this node is the only use of N.
5813 bool SDNode::isOnlyUserOf(SDNode *N) const {
5815 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5826 /// isOperand - Return true if this node is an operand of N.
5828 bool SDValue::isOperandOf(SDNode *N) const {
5829 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5830 if (*this == N->getOperand(i))
5835 bool SDNode::isOperandOf(SDNode *N) const {
5836 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5837 if (this == N->OperandList[i].getNode())
5842 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5843 /// be a chain) reaches the specified operand without crossing any
5844 /// side-effecting instructions on any chain path. In practice, this looks
5845 /// through token factors and non-volatile loads. In order to remain efficient,
5846 /// this only looks a couple of nodes in, it does not do an exhaustive search.
5847 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5848 unsigned Depth) const {
5849 if (*this == Dest) return true;
5851 // Don't search too deeply, we just want to be able to see through
5852 // TokenFactor's etc.
5853 if (Depth == 0) return false;
5855 // If this is a token factor, all inputs to the TF happen in parallel. If any
5856 // of the operands of the TF does not reach dest, then we cannot do the xform.
5857 if (getOpcode() == ISD::TokenFactor) {
5858 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5859 if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5864 // Loads don't have side effects, look through them.
5865 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5866 if (!Ld->isVolatile())
5867 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5872 /// hasPredecessor - Return true if N is a predecessor of this node.
5873 /// N is either an operand of this node, or can be reached by recursively
5874 /// traversing up the operands.
5875 /// NOTE: This is an expensive method. Use it carefully.
5876 bool SDNode::hasPredecessor(const SDNode *N) const {
5877 SmallPtrSet<const SDNode *, 32> Visited;
5878 SmallVector<const SDNode *, 16> Worklist;
5879 return hasPredecessorHelper(N, Visited, Worklist);
5882 bool SDNode::hasPredecessorHelper(const SDNode *N,
5883 SmallPtrSet<const SDNode *, 32> &Visited,
5884 SmallVector<const SDNode *, 16> &Worklist) const {
5885 if (Visited.empty()) {
5886 Worklist.push_back(this);
5888 // Take a look in the visited set. If we've already encountered this node
5889 // we needn't search further.
5890 if (Visited.count(N))
5894 // Haven't visited N yet. Continue the search.
5895 while (!Worklist.empty()) {
5896 const SDNode *M = Worklist.pop_back_val();
5897 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
5898 SDNode *Op = M->getOperand(i).getNode();
5899 if (Visited.insert(Op))
5900 Worklist.push_back(Op);
5909 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5910 assert(Num < NumOperands && "Invalid child # of SDNode!");
5911 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5914 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5915 switch (getOpcode()) {
5917 if (getOpcode() < ISD::BUILTIN_OP_END)
5918 return "<<Unknown DAG Node>>";
5919 if (isMachineOpcode()) {
5921 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5922 if (getMachineOpcode() < TII->getNumOpcodes())
5923 return TII->get(getMachineOpcode()).getName();
5924 return "<<Unknown Machine Node #" + utostr(getOpcode()) + ">>";
5927 const TargetLowering &TLI = G->getTargetLoweringInfo();
5928 const char *Name = TLI.getTargetNodeName(getOpcode());
5929 if (Name) return Name;
5930 return "<<Unknown Target Node #" + utostr(getOpcode()) + ">>";
5932 return "<<Unknown Node #" + utostr(getOpcode()) + ">>";
5935 case ISD::DELETED_NODE:
5936 return "<<Deleted Node!>>";
5938 case ISD::PREFETCH: return "Prefetch";
5939 case ISD::MEMBARRIER: return "MemBarrier";
5940 case ISD::ATOMIC_FENCE: return "AtomicFence";
5941 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5942 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5943 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5944 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5945 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5946 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5947 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5948 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5949 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5950 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5951 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5952 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5953 case ISD::ATOMIC_LOAD: return "AtomicLoad";
5954 case ISD::ATOMIC_STORE: return "AtomicStore";
5955 case ISD::PCMARKER: return "PCMarker";
5956 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5957 case ISD::SRCVALUE: return "SrcValue";
5958 case ISD::MDNODE_SDNODE: return "MDNode";
5959 case ISD::EntryToken: return "EntryToken";
5960 case ISD::TokenFactor: return "TokenFactor";
5961 case ISD::AssertSext: return "AssertSext";
5962 case ISD::AssertZext: return "AssertZext";
5964 case ISD::BasicBlock: return "BasicBlock";
5965 case ISD::VALUETYPE: return "ValueType";
5966 case ISD::Register: return "Register";
5967 case ISD::RegisterMask: return "RegisterMask";
5968 case ISD::Constant: return "Constant";
5969 case ISD::ConstantFP: return "ConstantFP";
5970 case ISD::GlobalAddress: return "GlobalAddress";
5971 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5972 case ISD::FrameIndex: return "FrameIndex";
5973 case ISD::JumpTable: return "JumpTable";
5974 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5975 case ISD::RETURNADDR: return "RETURNADDR";
5976 case ISD::FRAMEADDR: return "FRAMEADDR";
5977 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5978 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5979 case ISD::LSDAADDR: return "LSDAADDR";
5980 case ISD::EHSELECTION: return "EHSELECTION";
5981 case ISD::EH_RETURN: return "EH_RETURN";
5982 case ISD::EH_SJLJ_SETJMP: return "EH_SJLJ_SETJMP";
5983 case ISD::EH_SJLJ_LONGJMP: return "EH_SJLJ_LONGJMP";
5984 case ISD::ConstantPool: return "ConstantPool";
5985 case ISD::ExternalSymbol: return "ExternalSymbol";
5986 case ISD::BlockAddress: return "BlockAddress";
5987 case ISD::INTRINSIC_WO_CHAIN:
5988 case ISD::INTRINSIC_VOID:
5989 case ISD::INTRINSIC_W_CHAIN: {
5990 unsigned OpNo = getOpcode() == ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
5991 unsigned IID = cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue();
5992 if (IID < Intrinsic::num_intrinsics)
5993 return Intrinsic::getName((Intrinsic::ID)IID);
5994 else if (const TargetIntrinsicInfo *TII = G->getTarget().getIntrinsicInfo())
5995 return TII->getName(IID);
5996 llvm_unreachable("Invalid intrinsic ID");
5999 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
6000 case ISD::TargetConstant: return "TargetConstant";
6001 case ISD::TargetConstantFP:return "TargetConstantFP";
6002 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
6003 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
6004 case ISD::TargetFrameIndex: return "TargetFrameIndex";
6005 case ISD::TargetJumpTable: return "TargetJumpTable";
6006 case ISD::TargetConstantPool: return "TargetConstantPool";
6007 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
6008 case ISD::TargetBlockAddress: return "TargetBlockAddress";
6010 case ISD::CopyToReg: return "CopyToReg";
6011 case ISD::CopyFromReg: return "CopyFromReg";
6012 case ISD::UNDEF: return "undef";
6013 case ISD::MERGE_VALUES: return "merge_values";
6014 case ISD::INLINEASM: return "inlineasm";
6015 case ISD::EH_LABEL: return "eh_label";
6016 case ISD::HANDLENODE: return "handlenode";
6019 case ISD::FABS: return "fabs";
6020 case ISD::FNEG: return "fneg";
6021 case ISD::FSQRT: return "fsqrt";
6022 case ISD::FSIN: return "fsin";
6023 case ISD::FCOS: return "fcos";
6024 case ISD::FTRUNC: return "ftrunc";
6025 case ISD::FFLOOR: return "ffloor";
6026 case ISD::FCEIL: return "fceil";
6027 case ISD::FRINT: return "frint";
6028 case ISD::FNEARBYINT: return "fnearbyint";
6029 case ISD::FEXP: return "fexp";
6030 case ISD::FEXP2: return "fexp2";
6031 case ISD::FLOG: return "flog";
6032 case ISD::FLOG2: return "flog2";
6033 case ISD::FLOG10: return "flog10";
6036 case ISD::ADD: return "add";
6037 case ISD::SUB: return "sub";
6038 case ISD::MUL: return "mul";
6039 case ISD::MULHU: return "mulhu";
6040 case ISD::MULHS: return "mulhs";
6041 case ISD::SDIV: return "sdiv";
6042 case ISD::UDIV: return "udiv";
6043 case ISD::SREM: return "srem";
6044 case ISD::UREM: return "urem";
6045 case ISD::SMUL_LOHI: return "smul_lohi";
6046 case ISD::UMUL_LOHI: return "umul_lohi";
6047 case ISD::SDIVREM: return "sdivrem";
6048 case ISD::UDIVREM: return "udivrem";
6049 case ISD::AND: return "and";
6050 case ISD::OR: return "or";
6051 case ISD::XOR: return "xor";
6052 case ISD::SHL: return "shl";
6053 case ISD::SRA: return "sra";
6054 case ISD::SRL: return "srl";
6055 case ISD::ROTL: return "rotl";
6056 case ISD::ROTR: return "rotr";
6057 case ISD::FADD: return "fadd";
6058 case ISD::FSUB: return "fsub";
6059 case ISD::FMUL: return "fmul";
6060 case ISD::FDIV: return "fdiv";
6061 case ISD::FMA: return "fma";
6062 case ISD::FREM: return "frem";
6063 case ISD::FCOPYSIGN: return "fcopysign";
6064 case ISD::FGETSIGN: return "fgetsign";
6065 case ISD::FPOW: return "fpow";
6067 case ISD::FPOWI: return "fpowi";
6068 case ISD::SETCC: return "setcc";
6069 case ISD::SELECT: return "select";
6070 case ISD::VSELECT: return "vselect";
6071 case ISD::SELECT_CC: return "select_cc";
6072 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
6073 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
6074 case ISD::CONCAT_VECTORS: return "concat_vectors";
6075 case ISD::INSERT_SUBVECTOR: return "insert_subvector";
6076 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
6077 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
6078 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
6079 case ISD::CARRY_FALSE: return "carry_false";
6080 case ISD::ADDC: return "addc";
6081 case ISD::ADDE: return "adde";
6082 case ISD::SADDO: return "saddo";
6083 case ISD::UADDO: return "uaddo";
6084 case ISD::SSUBO: return "ssubo";
6085 case ISD::USUBO: return "usubo";
6086 case ISD::SMULO: return "smulo";
6087 case ISD::UMULO: return "umulo";
6088 case ISD::SUBC: return "subc";
6089 case ISD::SUBE: return "sube";
6090 case ISD::SHL_PARTS: return "shl_parts";
6091 case ISD::SRA_PARTS: return "sra_parts";
6092 case ISD::SRL_PARTS: return "srl_parts";
6094 // Conversion operators.
6095 case ISD::SIGN_EXTEND: return "sign_extend";
6096 case ISD::ZERO_EXTEND: return "zero_extend";
6097 case ISD::ANY_EXTEND: return "any_extend";
6098 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
6099 case ISD::TRUNCATE: return "truncate";
6100 case ISD::FP_ROUND: return "fp_round";
6101 case ISD::FLT_ROUNDS_: return "flt_rounds";
6102 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
6103 case ISD::FP_EXTEND: return "fp_extend";
6105 case ISD::SINT_TO_FP: return "sint_to_fp";
6106 case ISD::UINT_TO_FP: return "uint_to_fp";
6107 case ISD::FP_TO_SINT: return "fp_to_sint";
6108 case ISD::FP_TO_UINT: return "fp_to_uint";
6109 case ISD::BITCAST: return "bitcast";
6110 case ISD::FP16_TO_FP32: return "fp16_to_fp32";
6111 case ISD::FP32_TO_FP16: return "fp32_to_fp16";
6113 case ISD::CONVERT_RNDSAT: {
6114 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
6115 default: llvm_unreachable("Unknown cvt code!");
6116 case ISD::CVT_FF: return "cvt_ff";
6117 case ISD::CVT_FS: return "cvt_fs";
6118 case ISD::CVT_FU: return "cvt_fu";
6119 case ISD::CVT_SF: return "cvt_sf";
6120 case ISD::CVT_UF: return "cvt_uf";
6121 case ISD::CVT_SS: return "cvt_ss";
6122 case ISD::CVT_SU: return "cvt_su";
6123 case ISD::CVT_US: return "cvt_us";
6124 case ISD::CVT_UU: return "cvt_uu";
6128 // Control flow instructions
6129 case ISD::BR: return "br";
6130 case ISD::BRIND: return "brind";
6131 case ISD::BR_JT: return "br_jt";
6132 case ISD::BRCOND: return "brcond";
6133 case ISD::BR_CC: return "br_cc";
6134 case ISD::CALLSEQ_START: return "callseq_start";
6135 case ISD::CALLSEQ_END: return "callseq_end";
6138 case ISD::LOAD: return "load";
6139 case ISD::STORE: return "store";
6140 case ISD::VAARG: return "vaarg";
6141 case ISD::VACOPY: return "vacopy";
6142 case ISD::VAEND: return "vaend";
6143 case ISD::VASTART: return "vastart";
6144 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
6145 case ISD::EXTRACT_ELEMENT: return "extract_element";
6146 case ISD::BUILD_PAIR: return "build_pair";
6147 case ISD::STACKSAVE: return "stacksave";
6148 case ISD::STACKRESTORE: return "stackrestore";
6149 case ISD::TRAP: return "trap";
6152 case ISD::BSWAP: return "bswap";
6153 case ISD::CTPOP: return "ctpop";
6154 case ISD::CTTZ: return "cttz";
6155 case ISD::CTTZ_ZERO_UNDEF: return "cttz_zero_undef";
6156 case ISD::CTLZ: return "ctlz";
6157 case ISD::CTLZ_ZERO_UNDEF: return "ctlz_zero_undef";
6160 case ISD::INIT_TRAMPOLINE: return "init_trampoline";
6161 case ISD::ADJUST_TRAMPOLINE: return "adjust_trampoline";
6164 switch (cast<CondCodeSDNode>(this)->get()) {
6165 default: llvm_unreachable("Unknown setcc condition!");
6166 case ISD::SETOEQ: return "setoeq";
6167 case ISD::SETOGT: return "setogt";
6168 case ISD::SETOGE: return "setoge";
6169 case ISD::SETOLT: return "setolt";
6170 case ISD::SETOLE: return "setole";
6171 case ISD::SETONE: return "setone";
6173 case ISD::SETO: return "seto";
6174 case ISD::SETUO: return "setuo";
6175 case ISD::SETUEQ: return "setue";
6176 case ISD::SETUGT: return "setugt";
6177 case ISD::SETUGE: return "setuge";
6178 case ISD::SETULT: return "setult";
6179 case ISD::SETULE: return "setule";
6180 case ISD::SETUNE: return "setune";
6182 case ISD::SETEQ: return "seteq";
6183 case ISD::SETGT: return "setgt";
6184 case ISD::SETGE: return "setge";
6185 case ISD::SETLT: return "setlt";
6186 case ISD::SETLE: return "setle";
6187 case ISD::SETNE: return "setne";
6189 case ISD::SETTRUE: return "settrue";
6190 case ISD::SETTRUE2: return "settrue2";
6191 case ISD::SETFALSE: return "setfalse";
6192 case ISD::SETFALSE2: return "setfalse2";
6197 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
6206 return "<post-inc>";
6208 return "<post-dec>";
6212 std::string ISD::ArgFlagsTy::getArgFlagsString() {
6213 std::string S = "< ";
6227 if (getByValAlign())
6228 S += "byval-align:" + utostr(getByValAlign()) + " ";
6230 S += "orig-align:" + utostr(getOrigAlign()) + " ";
6232 S += "byval-size:" + utostr(getByValSize()) + " ";
6236 void SDNode::dump() const { dump(0); }
6237 void SDNode::dump(const SelectionDAG *G) const {
6242 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
6243 OS << (void*)this << ": ";
6245 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
6247 if (getValueType(i) == MVT::Other)
6250 OS << getValueType(i).getEVTString();
6252 OS << " = " << getOperationName(G);
6255 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
6256 if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
6257 if (!MN->memoperands_empty()) {
6260 for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
6261 e = MN->memoperands_end(); i != e; ++i) {
6263 if (llvm::next(i) != e)
6268 } else if (const ShuffleVectorSDNode *SVN =
6269 dyn_cast<ShuffleVectorSDNode>(this)) {
6271 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
6272 int Idx = SVN->getMaskElt(i);
6280 } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
6281 OS << '<' << CSDN->getAPIntValue() << '>';
6282 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
6283 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
6284 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
6285 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
6286 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
6289 CSDN->getValueAPF().bitcastToAPInt().dump();
6292 } else if (const GlobalAddressSDNode *GADN =
6293 dyn_cast<GlobalAddressSDNode>(this)) {
6294 int64_t offset = GADN->getOffset();
6296 WriteAsOperand(OS, GADN->getGlobal());
6299 OS << " + " << offset;
6301 OS << " " << offset;
6302 if (unsigned int TF = GADN->getTargetFlags())
6303 OS << " [TF=" << TF << ']';
6304 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
6305 OS << "<" << FIDN->getIndex() << ">";
6306 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
6307 OS << "<" << JTDN->getIndex() << ">";
6308 if (unsigned int TF = JTDN->getTargetFlags())
6309 OS << " [TF=" << TF << ']';
6310 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
6311 int offset = CP->getOffset();
6312 if (CP->isMachineConstantPoolEntry())
6313 OS << "<" << *CP->getMachineCPVal() << ">";
6315 OS << "<" << *CP->getConstVal() << ">";
6317 OS << " + " << offset;
6319 OS << " " << offset;
6320 if (unsigned int TF = CP->getTargetFlags())
6321 OS << " [TF=" << TF << ']';
6322 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
6324 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
6326 OS << LBB->getName() << " ";
6327 OS << (const void*)BBDN->getBasicBlock() << ">";
6328 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
6329 OS << ' ' << PrintReg(R->getReg(), G ? G->getTarget().getRegisterInfo() :0);
6330 } else if (const ExternalSymbolSDNode *ES =
6331 dyn_cast<ExternalSymbolSDNode>(this)) {
6332 OS << "'" << ES->getSymbol() << "'";
6333 if (unsigned int TF = ES->getTargetFlags())
6334 OS << " [TF=" << TF << ']';
6335 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
6337 OS << "<" << M->getValue() << ">";
6340 } else if (const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(this)) {
6342 OS << "<" << MD->getMD() << ">";
6345 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
6346 OS << ":" << N->getVT().getEVTString();
6348 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
6349 OS << "<" << *LD->getMemOperand();
6352 switch (LD->getExtensionType()) {
6353 default: doExt = false; break;
6354 case ISD::EXTLOAD: OS << ", anyext"; break;
6355 case ISD::SEXTLOAD: OS << ", sext"; break;
6356 case ISD::ZEXTLOAD: OS << ", zext"; break;
6359 OS << " from " << LD->getMemoryVT().getEVTString();
6361 const char *AM = getIndexedModeName(LD->getAddressingMode());
6366 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
6367 OS << "<" << *ST->getMemOperand();
6369 if (ST->isTruncatingStore())
6370 OS << ", trunc to " << ST->getMemoryVT().getEVTString();
6372 const char *AM = getIndexedModeName(ST->getAddressingMode());
6377 } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
6378 OS << "<" << *M->getMemOperand() << ">";
6379 } else if (const BlockAddressSDNode *BA =
6380 dyn_cast<BlockAddressSDNode>(this)) {
6382 WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
6384 WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
6386 if (unsigned int TF = BA->getTargetFlags())
6387 OS << " [TF=" << TF << ']';
6391 if (unsigned Order = G->GetOrdering(this))
6392 OS << " [ORD=" << Order << ']';
6394 if (getNodeId() != -1)
6395 OS << " [ID=" << getNodeId() << ']';
6397 DebugLoc dl = getDebugLoc();
6398 if (G && !dl.isUnknown()) {
6400 Scope(dl.getScope(G->getMachineFunction().getFunction()->getContext()));
6402 // Omit the directory, since it's usually long and uninteresting.
6404 OS << Scope.getFilename();
6407 OS << ':' << dl.getLine();
6408 if (dl.getCol() != 0)
6409 OS << ':' << dl.getCol();
6413 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
6415 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
6416 if (i) OS << ", "; else OS << " ";
6417 OS << (void*)getOperand(i).getNode();
6418 if (unsigned RN = getOperand(i).getResNo())
6421 print_details(OS, G);
6424 static void printrWithDepthHelper(raw_ostream &OS, const SDNode *N,
6425 const SelectionDAG *G, unsigned depth,
6437 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6438 // Don't follow chain operands.
6439 if (N->getOperand(i).getValueType() == MVT::Other)
6442 printrWithDepthHelper(OS, N->getOperand(i).getNode(), G, depth-1, indent+2);
6446 void SDNode::printrWithDepth(raw_ostream &OS, const SelectionDAG *G,
6447 unsigned depth) const {
6448 printrWithDepthHelper(OS, this, G, depth, 0);
6451 void SDNode::printrFull(raw_ostream &OS, const SelectionDAG *G) const {
6452 // Don't print impossibly deep things.
6453 printrWithDepth(OS, G, 10);
6456 void SDNode::dumprWithDepth(const SelectionDAG *G, unsigned depth) const {
6457 printrWithDepth(dbgs(), G, depth);
6460 void SDNode::dumprFull(const SelectionDAG *G) const {
6461 // Don't print impossibly deep things.
6462 dumprWithDepth(G, 10);
6465 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
6466 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6467 if (N->getOperand(i).getNode()->hasOneUse())
6468 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
6470 dbgs() << "\n" << std::string(indent+2, ' ')
6471 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
6475 dbgs().indent(indent);
6479 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6480 assert(N->getNumValues() == 1 &&
6481 "Can't unroll a vector with multiple results!");
6483 EVT VT = N->getValueType(0);
6484 unsigned NE = VT.getVectorNumElements();
6485 EVT EltVT = VT.getVectorElementType();
6486 DebugLoc dl = N->getDebugLoc();
6488 SmallVector<SDValue, 8> Scalars;
6489 SmallVector<SDValue, 4> Operands(N->getNumOperands());
6491 // If ResNE is 0, fully unroll the vector op.
6494 else if (NE > ResNE)
6498 for (i= 0; i != NE; ++i) {
6499 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
6500 SDValue Operand = N->getOperand(j);
6501 EVT OperandVT = Operand.getValueType();
6502 if (OperandVT.isVector()) {
6503 // A vector operand; extract a single element.
6504 EVT OperandEltVT = OperandVT.getVectorElementType();
6505 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6508 getConstant(i, TLI.getPointerTy()));
6510 // A scalar operand; just use it as is.
6511 Operands[j] = Operand;
6515 switch (N->getOpcode()) {
6517 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6518 &Operands[0], Operands.size()));
6521 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT,
6522 &Operands[0], Operands.size()));
6529 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6530 getShiftAmountOperand(Operands[0].getValueType(),
6533 case ISD::SIGN_EXTEND_INREG:
6534 case ISD::FP_ROUND_INREG: {
6535 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6536 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6538 getValueType(ExtVT)));
6543 for (; i < ResNE; ++i)
6544 Scalars.push_back(getUNDEF(EltVT));
6546 return getNode(ISD::BUILD_VECTOR, dl,
6547 EVT::getVectorVT(*getContext(), EltVT, ResNE),
6548 &Scalars[0], Scalars.size());
6552 /// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6553 /// location that is 'Dist' units away from the location that the 'Base' load
6554 /// is loading from.
6555 bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6556 unsigned Bytes, int Dist) const {
6557 if (LD->getChain() != Base->getChain())
6559 EVT VT = LD->getValueType(0);
6560 if (VT.getSizeInBits() / 8 != Bytes)
6563 SDValue Loc = LD->getOperand(1);
6564 SDValue BaseLoc = Base->getOperand(1);
6565 if (Loc.getOpcode() == ISD::FrameIndex) {
6566 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6568 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6569 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6570 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6571 int FS = MFI->getObjectSize(FI);
6572 int BFS = MFI->getObjectSize(BFI);
6573 if (FS != BFS || FS != (int)Bytes) return false;
6574 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6578 if (isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
6579 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
6582 const GlobalValue *GV1 = NULL;
6583 const GlobalValue *GV2 = NULL;
6584 int64_t Offset1 = 0;
6585 int64_t Offset2 = 0;
6586 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6587 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6588 if (isGA1 && isGA2 && GV1 == GV2)
6589 return Offset1 == (Offset2 + Dist*Bytes);
6594 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6595 /// it cannot be inferred.
6596 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6597 // If this is a GlobalAddress + cst, return the alignment.
6598 const GlobalValue *GV;
6599 int64_t GVOffset = 0;
6600 if (TLI.isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
6601 unsigned PtrWidth = TLI.getPointerTy().getSizeInBits();
6602 APInt AllOnes = APInt::getAllOnesValue(PtrWidth);
6603 APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0);
6604 llvm::ComputeMaskedBits(const_cast<GlobalValue*>(GV), AllOnes,
6605 KnownZero, KnownOne, TLI.getTargetData());
6606 unsigned AlignBits = KnownZero.countTrailingOnes();
6607 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
6609 return MinAlign(Align, GVOffset);
6612 // If this is a direct reference to a stack slot, use information about the
6613 // stack slot's alignment.
6614 int FrameIdx = 1 << 31;
6615 int64_t FrameOffset = 0;
6616 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6617 FrameIdx = FI->getIndex();
6618 } else if (isBaseWithConstantOffset(Ptr) &&
6619 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6621 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6622 FrameOffset = Ptr.getConstantOperandVal(1);
6625 if (FrameIdx != (1 << 31)) {
6626 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6627 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6635 void SelectionDAG::dump() const {
6636 dbgs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
6638 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
6640 const SDNode *N = I;
6641 if (!N->hasOneUse() && N != getRoot().getNode())
6642 DumpNodes(N, 2, this);
6645 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
6650 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
6652 print_details(OS, G);
6655 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
6656 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
6657 const SelectionDAG *G, VisitedSDNodeSet &once) {
6658 if (!once.insert(N)) // If we've been here before, return now.
6661 // Dump the current SDNode, but don't end the line yet.
6665 // Having printed this SDNode, walk the children:
6666 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6667 const SDNode *child = N->getOperand(i).getNode();
6672 if (child->getNumOperands() == 0) {
6673 // This child has no grandchildren; print it inline right here.
6674 child->printr(OS, G);
6676 } else { // Just the address. FIXME: also print the child's opcode.
6678 if (unsigned RN = N->getOperand(i).getResNo())
6685 // Dump children that have grandchildren on their own line(s).
6686 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6687 const SDNode *child = N->getOperand(i).getNode();
6688 DumpNodesr(OS, child, indent+2, G, once);
6692 void SDNode::dumpr() const {
6693 VisitedSDNodeSet once;
6694 DumpNodesr(dbgs(), this, 0, 0, once);
6697 void SDNode::dumpr(const SelectionDAG *G) const {
6698 VisitedSDNodeSet once;
6699 DumpNodesr(dbgs(), this, 0, G, once);
6703 // getAddressSpace - Return the address space this GlobalAddress belongs to.
6704 unsigned GlobalAddressSDNode::getAddressSpace() const {
6705 return getGlobal()->getType()->getAddressSpace();
6709 Type *ConstantPoolSDNode::getType() const {
6710 if (isMachineConstantPoolEntry())
6711 return Val.MachineCPVal->getType();
6712 return Val.ConstVal->getType();
6715 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6717 unsigned &SplatBitSize,
6719 unsigned MinSplatBits,
6721 EVT VT = getValueType(0);
6722 assert(VT.isVector() && "Expected a vector type");
6723 unsigned sz = VT.getSizeInBits();
6724 if (MinSplatBits > sz)
6727 SplatValue = APInt(sz, 0);
6728 SplatUndef = APInt(sz, 0);
6730 // Get the bits. Bits with undefined values (when the corresponding element
6731 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6732 // in SplatValue. If any of the values are not constant, give up and return
6734 unsigned int nOps = getNumOperands();
6735 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6736 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6738 for (unsigned j = 0; j < nOps; ++j) {
6739 unsigned i = isBigEndian ? nOps-1-j : j;
6740 SDValue OpVal = getOperand(i);
6741 unsigned BitPos = j * EltBitSize;
6743 if (OpVal.getOpcode() == ISD::UNDEF)
6744 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6745 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6746 SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize).
6747 zextOrTrunc(sz) << BitPos;
6748 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6749 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6754 // The build_vector is all constants or undefs. Find the smallest element
6755 // size that splats the vector.
6757 HasAnyUndefs = (SplatUndef != 0);
6760 unsigned HalfSize = sz / 2;
6761 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
6762 APInt LowValue = SplatValue.trunc(HalfSize);
6763 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
6764 APInt LowUndef = SplatUndef.trunc(HalfSize);
6766 // If the two halves do not match (ignoring undef bits), stop here.
6767 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6768 MinSplatBits > HalfSize)
6771 SplatValue = HighValue | LowValue;
6772 SplatUndef = HighUndef & LowUndef;
6781 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6782 // Find the first non-undef value in the shuffle mask.
6784 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6787 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6789 // Make sure all remaining elements are either undef or the same as the first
6791 for (int Idx = Mask[i]; i != e; ++i)
6792 if (Mask[i] >= 0 && Mask[i] != Idx)
6798 static void checkForCyclesHelper(const SDNode *N,
6799 SmallPtrSet<const SDNode*, 32> &Visited,
6800 SmallPtrSet<const SDNode*, 32> &Checked) {
6801 // If this node has already been checked, don't check it again.
6802 if (Checked.count(N))
6805 // If a node has already been visited on this depth-first walk, reject it as
6807 if (!Visited.insert(N)) {
6808 dbgs() << "Offending node:\n";
6810 errs() << "Detected cycle in SelectionDAG\n";
6814 for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6815 checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked);
6822 void llvm::checkForCycles(const llvm::SDNode *N) {
6824 assert(N && "Checking nonexistant SDNode");
6825 SmallPtrSet<const SDNode*, 32> visited;
6826 SmallPtrSet<const SDNode*, 32> checked;
6827 checkForCyclesHelper(N, visited, checked);
6831 void llvm::checkForCycles(const llvm::SelectionDAG *DAG) {
6832 checkForCycles(DAG->getRoot().getNode());