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 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/GlobalAlias.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/SetVector.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/StringExtras.h"
45 /// makeVTList - Return an instance of the SDVTList struct initialized with the
46 /// specified members.
47 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
48 SDVTList Res = {VTs, NumVTs};
52 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
53 switch (VT.getSimpleVT()) {
54 default: assert(0 && "Unknown FP format");
55 case MVT::f32: return &APFloat::IEEEsingle;
56 case MVT::f64: return &APFloat::IEEEdouble;
57 case MVT::f80: return &APFloat::x87DoubleExtended;
58 case MVT::f128: return &APFloat::IEEEquad;
59 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
63 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
65 //===----------------------------------------------------------------------===//
66 // ConstantFPSDNode Class
67 //===----------------------------------------------------------------------===//
69 /// isExactlyValue - We don't rely on operator== working on double values, as
70 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
71 /// As such, this method can be used to do an exact bit-for-bit comparison of
72 /// two floating point values.
73 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
74 return getValueAPF().bitwiseIsEqual(V);
77 bool ConstantFPSDNode::isValueValidForType(MVT VT,
79 assert(VT.isFloatingPoint() && "Can only convert between FP types");
81 // PPC long double cannot be converted to any other type.
82 if (VT == MVT::ppcf128 ||
83 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
86 // convert modifies in place, so make a copy.
87 APFloat Val2 = APFloat(Val);
89 (void) Val2.convert(*MVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
94 //===----------------------------------------------------------------------===//
96 //===----------------------------------------------------------------------===//
98 /// isBuildVectorAllOnes - Return true if the specified node is a
99 /// BUILD_VECTOR where all of the elements are ~0 or undef.
100 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
101 // Look through a bit convert.
102 if (N->getOpcode() == ISD::BIT_CONVERT)
103 N = N->getOperand(0).getNode();
105 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
107 unsigned i = 0, e = N->getNumOperands();
109 // Skip over all of the undef values.
110 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
113 // Do not accept an all-undef vector.
114 if (i == e) return false;
116 // Do not accept build_vectors that aren't all constants or which have non-~0
118 SDValue NotZero = N->getOperand(i);
119 if (isa<ConstantSDNode>(NotZero)) {
120 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
122 } else if (isa<ConstantFPSDNode>(NotZero)) {
123 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
124 bitcastToAPInt().isAllOnesValue())
129 // Okay, we have at least one ~0 value, check to see if the rest match or are
131 for (++i; i != e; ++i)
132 if (N->getOperand(i) != NotZero &&
133 N->getOperand(i).getOpcode() != ISD::UNDEF)
139 /// isBuildVectorAllZeros - Return true if the specified node is a
140 /// BUILD_VECTOR where all of the elements are 0 or undef.
141 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
142 // Look through a bit convert.
143 if (N->getOpcode() == ISD::BIT_CONVERT)
144 N = N->getOperand(0).getNode();
146 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
148 unsigned i = 0, e = N->getNumOperands();
150 // Skip over all of the undef values.
151 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
154 // Do not accept an all-undef vector.
155 if (i == e) return false;
157 // Do not accept build_vectors that aren't all constants or which have non-~0
159 SDValue Zero = N->getOperand(i);
160 if (isa<ConstantSDNode>(Zero)) {
161 if (!cast<ConstantSDNode>(Zero)->isNullValue())
163 } else if (isa<ConstantFPSDNode>(Zero)) {
164 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
169 // Okay, we have at least one ~0 value, check to see if the rest match or are
171 for (++i; i != e; ++i)
172 if (N->getOperand(i) != Zero &&
173 N->getOperand(i).getOpcode() != ISD::UNDEF)
178 /// isScalarToVector - Return true if the specified node is a
179 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
180 /// element is not an undef.
181 bool ISD::isScalarToVector(const SDNode *N) {
182 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
185 if (N->getOpcode() != ISD::BUILD_VECTOR)
187 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
189 unsigned NumElems = N->getNumOperands();
190 for (unsigned i = 1; i < NumElems; ++i) {
191 SDValue V = N->getOperand(i);
192 if (V.getOpcode() != ISD::UNDEF)
199 /// isDebugLabel - Return true if the specified node represents a debug
200 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
201 bool ISD::isDebugLabel(const SDNode *N) {
203 if (N->getOpcode() == ISD::DBG_LABEL)
205 if (N->isMachineOpcode() &&
206 N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
211 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
212 /// when given the operation for (X op Y).
213 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
214 // To perform this operation, we just need to swap the L and G bits of the
216 unsigned OldL = (Operation >> 2) & 1;
217 unsigned OldG = (Operation >> 1) & 1;
218 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
219 (OldL << 1) | // New G bit
220 (OldG << 2)); // New L bit.
223 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
224 /// 'op' is a valid SetCC operation.
225 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
226 unsigned Operation = Op;
228 Operation ^= 7; // Flip L, G, E bits, but not U.
230 Operation ^= 15; // Flip all of the condition bits.
232 if (Operation > ISD::SETTRUE2)
233 Operation &= ~8; // Don't let N and U bits get set.
235 return ISD::CondCode(Operation);
239 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
240 /// signed operation and 2 if the result is an unsigned comparison. Return zero
241 /// if the operation does not depend on the sign of the input (setne and seteq).
242 static int isSignedOp(ISD::CondCode Opcode) {
244 default: assert(0 && "Illegal integer setcc operation!");
246 case ISD::SETNE: return 0;
250 case ISD::SETGE: return 1;
254 case ISD::SETUGE: return 2;
258 /// getSetCCOrOperation - Return the result of a logical OR between different
259 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
260 /// returns SETCC_INVALID if it is not possible to represent the resultant
262 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
264 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
265 // Cannot fold a signed integer setcc with an unsigned integer setcc.
266 return ISD::SETCC_INVALID;
268 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
270 // If the N and U bits get set then the resultant comparison DOES suddenly
271 // care about orderedness, and is true when ordered.
272 if (Op > ISD::SETTRUE2)
273 Op &= ~16; // Clear the U bit if the N bit is set.
275 // Canonicalize illegal integer setcc's.
276 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
279 return ISD::CondCode(Op);
282 /// getSetCCAndOperation - Return the result of a logical AND between different
283 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
284 /// function returns zero if it is not possible to represent the resultant
286 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
288 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
289 // Cannot fold a signed setcc with an unsigned setcc.
290 return ISD::SETCC_INVALID;
292 // Combine all of the condition bits.
293 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
295 // Canonicalize illegal integer setcc's.
299 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
300 case ISD::SETOEQ: // SETEQ & SETU[LG]E
301 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
302 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
303 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
310 const TargetMachine &SelectionDAG::getTarget() const {
311 return MF->getTarget();
314 //===----------------------------------------------------------------------===//
315 // SDNode Profile Support
316 //===----------------------------------------------------------------------===//
318 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
320 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
324 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
325 /// solely with their pointer.
326 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
327 ID.AddPointer(VTList.VTs);
330 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
332 static void AddNodeIDOperands(FoldingSetNodeID &ID,
333 const SDValue *Ops, unsigned NumOps) {
334 for (; NumOps; --NumOps, ++Ops) {
335 ID.AddPointer(Ops->getNode());
336 ID.AddInteger(Ops->getResNo());
340 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
342 static void AddNodeIDOperands(FoldingSetNodeID &ID,
343 const SDUse *Ops, unsigned NumOps) {
344 for (; NumOps; --NumOps, ++Ops) {
345 ID.AddPointer(Ops->getNode());
346 ID.AddInteger(Ops->getResNo());
350 static void AddNodeIDNode(FoldingSetNodeID &ID,
351 unsigned short OpC, SDVTList VTList,
352 const SDValue *OpList, unsigned N) {
353 AddNodeIDOpcode(ID, OpC);
354 AddNodeIDValueTypes(ID, VTList);
355 AddNodeIDOperands(ID, OpList, N);
358 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
360 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
361 switch (N->getOpcode()) {
362 default: break; // Normal nodes don't need extra info.
364 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
366 case ISD::TargetConstant:
368 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
370 case ISD::TargetConstantFP:
371 case ISD::ConstantFP: {
372 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
375 case ISD::TargetGlobalAddress:
376 case ISD::GlobalAddress:
377 case ISD::TargetGlobalTLSAddress:
378 case ISD::GlobalTLSAddress: {
379 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
380 ID.AddPointer(GA->getGlobal());
381 ID.AddInteger(GA->getOffset());
384 case ISD::BasicBlock:
385 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
388 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
390 case ISD::DBG_STOPPOINT: {
391 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
392 ID.AddInteger(DSP->getLine());
393 ID.AddInteger(DSP->getColumn());
394 ID.AddPointer(DSP->getCompileUnit());
398 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
400 case ISD::MEMOPERAND: {
401 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
405 case ISD::FrameIndex:
406 case ISD::TargetFrameIndex:
407 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
410 case ISD::TargetJumpTable:
411 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
413 case ISD::ConstantPool:
414 case ISD::TargetConstantPool: {
415 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
416 ID.AddInteger(CP->getAlignment());
417 ID.AddInteger(CP->getOffset());
418 if (CP->isMachineConstantPoolEntry())
419 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
421 ID.AddPointer(CP->getConstVal());
425 const CallSDNode *Call = cast<CallSDNode>(N);
426 ID.AddInteger(Call->getCallingConv());
427 ID.AddInteger(Call->isVarArg());
431 const LoadSDNode *LD = cast<LoadSDNode>(N);
432 ID.AddInteger(LD->getMemoryVT().getRawBits());
433 ID.AddInteger(LD->getRawSubclassData());
437 const StoreSDNode *ST = cast<StoreSDNode>(N);
438 ID.AddInteger(ST->getMemoryVT().getRawBits());
439 ID.AddInteger(ST->getRawSubclassData());
442 case ISD::ATOMIC_CMP_SWAP:
443 case ISD::ATOMIC_SWAP:
444 case ISD::ATOMIC_LOAD_ADD:
445 case ISD::ATOMIC_LOAD_SUB:
446 case ISD::ATOMIC_LOAD_AND:
447 case ISD::ATOMIC_LOAD_OR:
448 case ISD::ATOMIC_LOAD_XOR:
449 case ISD::ATOMIC_LOAD_NAND:
450 case ISD::ATOMIC_LOAD_MIN:
451 case ISD::ATOMIC_LOAD_MAX:
452 case ISD::ATOMIC_LOAD_UMIN:
453 case ISD::ATOMIC_LOAD_UMAX: {
454 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
455 ID.AddInteger(AT->getMemoryVT().getRawBits());
456 ID.AddInteger(AT->getRawSubclassData());
459 } // end switch (N->getOpcode())
462 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
464 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
465 AddNodeIDOpcode(ID, N->getOpcode());
466 // Add the return value info.
467 AddNodeIDValueTypes(ID, N->getVTList());
468 // Add the operand info.
469 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
471 // Handle SDNode leafs with special info.
472 AddNodeIDCustom(ID, N);
475 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
476 /// the CSE map that carries alignment, volatility, indexing mode, and
477 /// extension/truncation information.
479 static inline unsigned
480 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM,
481 bool isVolatile, unsigned Alignment) {
482 assert((ConvType & 3) == ConvType &&
483 "ConvType may not require more than 2 bits!");
484 assert((AM & 7) == AM &&
485 "AM may not require more than 3 bits!");
489 ((Log2_32(Alignment) + 1) << 6);
492 //===----------------------------------------------------------------------===//
493 // SelectionDAG Class
494 //===----------------------------------------------------------------------===//
496 /// doNotCSE - Return true if CSE should not be performed for this node.
497 static bool doNotCSE(SDNode *N) {
498 if (N->getValueType(0) == MVT::Flag)
499 return true; // Never CSE anything that produces a flag.
501 switch (N->getOpcode()) {
503 case ISD::HANDLENODE:
505 case ISD::DBG_STOPPOINT:
508 return true; // Never CSE these nodes.
511 // Check that remaining values produced are not flags.
512 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
513 if (N->getValueType(i) == MVT::Flag)
514 return true; // Never CSE anything that produces a flag.
519 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
521 void SelectionDAG::RemoveDeadNodes() {
522 // Create a dummy node (which is not added to allnodes), that adds a reference
523 // to the root node, preventing it from being deleted.
524 HandleSDNode Dummy(getRoot());
526 SmallVector<SDNode*, 128> DeadNodes;
528 // Add all obviously-dead nodes to the DeadNodes worklist.
529 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
531 DeadNodes.push_back(I);
533 RemoveDeadNodes(DeadNodes);
535 // If the root changed (e.g. it was a dead load, update the root).
536 setRoot(Dummy.getValue());
539 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
540 /// given list, and any nodes that become unreachable as a result.
541 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
542 DAGUpdateListener *UpdateListener) {
544 // Process the worklist, deleting the nodes and adding their uses to the
546 while (!DeadNodes.empty()) {
547 SDNode *N = DeadNodes.pop_back_val();
550 UpdateListener->NodeDeleted(N, 0);
552 // Take the node out of the appropriate CSE map.
553 RemoveNodeFromCSEMaps(N);
555 // Next, brutally remove the operand list. This is safe to do, as there are
556 // no cycles in the graph.
557 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
559 SDNode *Operand = Use.getNode();
562 // Now that we removed this operand, see if there are no uses of it left.
563 if (Operand->use_empty())
564 DeadNodes.push_back(Operand);
571 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
572 SmallVector<SDNode*, 16> DeadNodes(1, N);
573 RemoveDeadNodes(DeadNodes, UpdateListener);
576 void SelectionDAG::DeleteNode(SDNode *N) {
577 // First take this out of the appropriate CSE map.
578 RemoveNodeFromCSEMaps(N);
580 // Finally, remove uses due to operands of this node, remove from the
581 // AllNodes list, and delete the node.
582 DeleteNodeNotInCSEMaps(N);
585 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
586 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
587 assert(N->use_empty() && "Cannot delete a node that is not dead!");
589 // Drop all of the operands and decrement used node's use counts.
595 void SelectionDAG::DeallocateNode(SDNode *N) {
596 if (N->OperandsNeedDelete)
597 delete[] N->OperandList;
599 // Set the opcode to DELETED_NODE to help catch bugs when node
600 // memory is reallocated.
601 N->NodeType = ISD::DELETED_NODE;
603 NodeAllocator.Deallocate(AllNodes.remove(N));
606 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
607 /// correspond to it. This is useful when we're about to delete or repurpose
608 /// the node. We don't want future request for structurally identical nodes
609 /// to return N anymore.
610 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
612 switch (N->getOpcode()) {
613 case ISD::EntryToken:
614 assert(0 && "EntryToken should not be in CSEMaps!");
616 case ISD::HANDLENODE: return false; // noop.
618 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
619 "Cond code doesn't exist!");
620 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
621 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
623 case ISD::ExternalSymbol:
624 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
626 case ISD::TargetExternalSymbol:
628 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
630 case ISD::VALUETYPE: {
631 MVT VT = cast<VTSDNode>(N)->getVT();
632 if (VT.isExtended()) {
633 Erased = ExtendedValueTypeNodes.erase(VT);
635 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
636 ValueTypeNodes[VT.getSimpleVT()] = 0;
641 // Remove it from the CSE Map.
642 Erased = CSEMap.RemoveNode(N);
646 // Verify that the node was actually in one of the CSE maps, unless it has a
647 // flag result (which cannot be CSE'd) or is one of the special cases that are
648 // not subject to CSE.
649 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
650 !N->isMachineOpcode() && !doNotCSE(N)) {
653 assert(0 && "Node is not in map!");
659 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
660 /// maps and modified in place. Add it back to the CSE maps, unless an identical
661 /// node already exists, in which case transfer all its users to the existing
662 /// node. This transfer can potentially trigger recursive merging.
665 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
666 DAGUpdateListener *UpdateListener) {
667 // For node types that aren't CSE'd, just act as if no identical node
670 SDNode *Existing = CSEMap.GetOrInsertNode(N);
672 // If there was already an existing matching node, use ReplaceAllUsesWith
673 // to replace the dead one with the existing one. This can cause
674 // recursive merging of other unrelated nodes down the line.
675 ReplaceAllUsesWith(N, Existing, UpdateListener);
677 // N is now dead. Inform the listener if it exists and delete it.
679 UpdateListener->NodeDeleted(N, Existing);
680 DeleteNodeNotInCSEMaps(N);
685 // If the node doesn't already exist, we updated it. Inform a listener if
688 UpdateListener->NodeUpdated(N);
691 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
692 /// were replaced with those specified. If this node is never memoized,
693 /// return null, otherwise return a pointer to the slot it would take. If a
694 /// node already exists with these operands, the slot will be non-null.
695 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
700 SDValue Ops[] = { Op };
702 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
703 AddNodeIDCustom(ID, N);
704 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
707 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
708 /// were replaced with those specified. If this node is never memoized,
709 /// return null, otherwise return a pointer to the slot it would take. If a
710 /// node already exists with these operands, the slot will be non-null.
711 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
712 SDValue Op1, SDValue Op2,
717 SDValue Ops[] = { Op1, Op2 };
719 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
720 AddNodeIDCustom(ID, N);
721 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
725 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
726 /// were replaced with those specified. If this node is never memoized,
727 /// return null, otherwise return a pointer to the slot it would take. If a
728 /// node already exists with these operands, the slot will be non-null.
729 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
730 const SDValue *Ops,unsigned NumOps,
736 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
737 AddNodeIDCustom(ID, N);
738 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
741 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
742 void SelectionDAG::VerifyNode(SDNode *N) {
743 switch (N->getOpcode()) {
746 case ISD::BUILD_PAIR: {
747 MVT VT = N->getValueType(0);
748 assert(N->getNumValues() == 1 && "Too many results!");
749 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
750 "Wrong return type!");
751 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
752 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
753 "Mismatched operand types!");
754 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
755 "Wrong operand type!");
756 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
757 "Wrong return type size");
760 case ISD::BUILD_VECTOR: {
761 assert(N->getNumValues() == 1 && "Too many results!");
762 assert(N->getValueType(0).isVector() && "Wrong return type!");
763 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
764 "Wrong number of operands!");
765 // FIXME: Change vector_shuffle to a variadic node with mask elements being
766 // operands of the node. Currently the mask is a BUILD_VECTOR passed as an
767 // operand, and it is not always possible to legalize it. Turning off the
768 // following checks at least makes it possible to legalize most of the time.
769 // MVT EltVT = N->getValueType(0).getVectorElementType();
770 // for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
771 // assert(I->getValueType() == EltVT &&
772 // "Wrong operand type!");
778 /// getMVTAlignment - Compute the default alignment value for the
781 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
782 const Type *Ty = VT == MVT::iPTR ?
783 PointerType::get(Type::Int8Ty, 0) :
786 return TLI.getTargetData()->getABITypeAlignment(Ty);
789 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
790 : TLI(tli), FLI(fli), DW(0),
791 EntryNode(ISD::EntryToken, getVTList(MVT::Other)),
792 Root(getEntryNode()) {
793 AllNodes.push_back(&EntryNode);
796 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
803 SelectionDAG::~SelectionDAG() {
807 void SelectionDAG::allnodes_clear() {
808 assert(&*AllNodes.begin() == &EntryNode);
809 AllNodes.remove(AllNodes.begin());
810 while (!AllNodes.empty())
811 DeallocateNode(AllNodes.begin());
814 void SelectionDAG::clear() {
816 OperandAllocator.Reset();
819 ExtendedValueTypeNodes.clear();
820 ExternalSymbols.clear();
821 TargetExternalSymbols.clear();
822 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
823 static_cast<CondCodeSDNode*>(0));
824 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
825 static_cast<SDNode*>(0));
827 EntryNode.UseList = 0;
828 AllNodes.push_back(&EntryNode);
829 Root = getEntryNode();
832 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
833 if (Op.getValueType() == VT) return Op;
834 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
836 return getNode(ISD::AND, Op.getValueType(), Op,
837 getConstant(Imm, Op.getValueType()));
840 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, MVT VT) {
841 if (Op.getValueType() == VT) return Op;
842 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
844 return getNode(ISD::AND, DL, Op.getValueType(), Op,
845 getConstant(Imm, Op.getValueType()));
848 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
850 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, MVT VT) {
853 MVT EltVT = VT.getVectorElementType();
855 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), EltVT);
856 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOneElt);
857 NegOne = getNode(ISD::BUILD_VECTOR, DL, VT, &NegOnes[0], NegOnes.size());
859 NegOne = getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
861 return getNode(ISD::XOR, DL, VT, Val, NegOne);
864 SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
865 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
866 assert((EltVT.getSizeInBits() >= 64 ||
867 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
868 "getConstant with a uint64_t value that doesn't fit in the type!");
869 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
872 SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
873 return getConstant(*ConstantInt::get(Val), VT, isT);
876 SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) {
877 assert(VT.isInteger() && "Cannot create FP integer constant!");
879 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
880 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
881 "APInt size does not match type size!");
883 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
885 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
889 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
891 return SDValue(N, 0);
893 N = NodeAllocator.Allocate<ConstantSDNode>();
894 new (N) ConstantSDNode(isT, &Val, EltVT);
895 CSEMap.InsertNode(N, IP);
896 AllNodes.push_back(N);
899 SDValue Result(N, 0);
901 SmallVector<SDValue, 8> Ops;
902 Ops.assign(VT.getVectorNumElements(), Result);
903 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
908 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
909 return getConstant(Val, TLI.getPointerTy(), isTarget);
913 SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
914 return getConstantFP(*ConstantFP::get(V), VT, isTarget);
917 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, MVT VT, bool isTarget){
918 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
921 VT.isVector() ? VT.getVectorElementType() : VT;
923 // Do the map lookup using the actual bit pattern for the floating point
924 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
925 // we don't have issues with SNANs.
926 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
928 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
932 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
934 return SDValue(N, 0);
936 N = NodeAllocator.Allocate<ConstantFPSDNode>();
937 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
938 CSEMap.InsertNode(N, IP);
939 AllNodes.push_back(N);
942 SDValue Result(N, 0);
944 SmallVector<SDValue, 8> Ops;
945 Ops.assign(VT.getVectorNumElements(), Result);
946 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
951 SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
953 VT.isVector() ? VT.getVectorElementType() : VT;
955 return getConstantFP(APFloat((float)Val), VT, isTarget);
957 return getConstantFP(APFloat(Val), VT, isTarget);
960 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
961 MVT VT, int64_t Offset,
965 // Truncate (with sign-extension) the offset value to the pointer size.
966 unsigned BitWidth = TLI.getPointerTy().getSizeInBits();
968 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
970 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
972 // If GV is an alias then use the aliasee for determining thread-localness.
973 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
974 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
977 if (GVar && GVar->isThreadLocal())
978 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
980 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
983 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
985 ID.AddInteger(Offset);
987 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
988 return SDValue(E, 0);
989 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
990 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
991 CSEMap.InsertNode(N, IP);
992 AllNodes.push_back(N);
993 return SDValue(N, 0);
996 SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
997 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
999 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1002 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1003 return SDValue(E, 0);
1004 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
1005 new (N) FrameIndexSDNode(FI, VT, isTarget);
1006 CSEMap.InsertNode(N, IP);
1007 AllNodes.push_back(N);
1008 return SDValue(N, 0);
1011 SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
1012 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1013 FoldingSetNodeID ID;
1014 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1017 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1018 return SDValue(E, 0);
1019 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1020 new (N) JumpTableSDNode(JTI, VT, isTarget);
1021 CSEMap.InsertNode(N, IP);
1022 AllNodes.push_back(N);
1023 return SDValue(N, 0);
1026 SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
1027 unsigned Alignment, int Offset,
1031 TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
1032 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1033 FoldingSetNodeID ID;
1034 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1035 ID.AddInteger(Alignment);
1036 ID.AddInteger(Offset);
1039 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1040 return SDValue(E, 0);
1041 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1042 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1043 CSEMap.InsertNode(N, IP);
1044 AllNodes.push_back(N);
1045 return SDValue(N, 0);
1049 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
1050 unsigned Alignment, int Offset,
1054 TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
1055 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1056 FoldingSetNodeID ID;
1057 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1058 ID.AddInteger(Alignment);
1059 ID.AddInteger(Offset);
1060 C->AddSelectionDAGCSEId(ID);
1062 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1063 return SDValue(E, 0);
1064 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1065 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1066 CSEMap.InsertNode(N, IP);
1067 AllNodes.push_back(N);
1068 return SDValue(N, 0);
1071 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1072 FoldingSetNodeID ID;
1073 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1076 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1077 return SDValue(E, 0);
1078 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1079 new (N) BasicBlockSDNode(MBB);
1080 CSEMap.InsertNode(N, IP);
1081 AllNodes.push_back(N);
1082 return SDValue(N, 0);
1085 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB, DebugLoc dl) {
1086 FoldingSetNodeID ID;
1087 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1090 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1091 return SDValue(E, 0);
1092 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1093 new (N) BasicBlockSDNode(MBB, dl);
1094 CSEMap.InsertNode(N, IP);
1095 AllNodes.push_back(N);
1096 return SDValue(N, 0);
1099 SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
1100 FoldingSetNodeID ID;
1101 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
1102 ID.AddInteger(Flags.getRawBits());
1104 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1105 return SDValue(E, 0);
1106 SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
1107 new (N) ARG_FLAGSSDNode(Flags);
1108 CSEMap.InsertNode(N, IP);
1109 AllNodes.push_back(N);
1110 return SDValue(N, 0);
1113 SDValue SelectionDAG::getValueType(MVT VT) {
1114 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1115 ValueTypeNodes.resize(VT.getSimpleVT()+1);
1117 SDNode *&N = VT.isExtended() ?
1118 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1120 if (N) return SDValue(N, 0);
1121 N = NodeAllocator.Allocate<VTSDNode>();
1122 new (N) VTSDNode(VT);
1123 AllNodes.push_back(N);
1124 return SDValue(N, 0);
1127 SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1128 SDNode *&N = ExternalSymbols[Sym];
1129 if (N) return SDValue(N, 0);
1130 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1131 new (N) ExternalSymbolSDNode(false, Sym, VT);
1132 AllNodes.push_back(N);
1133 return SDValue(N, 0);
1136 SDValue SelectionDAG::getExternalSymbol(const char *Sym, DebugLoc dl, MVT VT) {
1137 SDNode *&N = ExternalSymbols[Sym];
1138 if (N) return SDValue(N, 0);
1139 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1140 new (N) ExternalSymbolSDNode(false, dl, Sym, VT);
1141 AllNodes.push_back(N);
1142 return SDValue(N, 0);
1145 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1146 SDNode *&N = TargetExternalSymbols[Sym];
1147 if (N) return SDValue(N, 0);
1148 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1149 new (N) ExternalSymbolSDNode(true, Sym, VT);
1150 AllNodes.push_back(N);
1151 return SDValue(N, 0);
1154 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, DebugLoc dl,
1156 SDNode *&N = TargetExternalSymbols[Sym];
1157 if (N) return SDValue(N, 0);
1158 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1159 new (N) ExternalSymbolSDNode(true, dl, Sym, VT);
1160 AllNodes.push_back(N);
1161 return SDValue(N, 0);
1164 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1165 if ((unsigned)Cond >= CondCodeNodes.size())
1166 CondCodeNodes.resize(Cond+1);
1168 if (CondCodeNodes[Cond] == 0) {
1169 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1170 new (N) CondCodeSDNode(Cond);
1171 CondCodeNodes[Cond] = N;
1172 AllNodes.push_back(N);
1174 return SDValue(CondCodeNodes[Cond], 0);
1177 SDValue SelectionDAG::getConvertRndSat(MVT VT, DebugLoc dl,
1178 SDValue Val, SDValue DTy,
1179 SDValue STy, SDValue Rnd, SDValue Sat,
1180 ISD::CvtCode Code) {
1181 // If the src and dest types are the same, no conversion is necessary.
1185 FoldingSetNodeID ID;
1187 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1188 return SDValue(E, 0);
1189 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
1190 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1191 new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code);
1192 CSEMap.InsertNode(N, IP);
1193 AllNodes.push_back(N);
1194 return SDValue(N, 0);
1197 SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1198 FoldingSetNodeID ID;
1199 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1200 ID.AddInteger(RegNo);
1202 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1203 return SDValue(E, 0);
1204 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1205 new (N) RegisterSDNode(RegNo, VT);
1206 CSEMap.InsertNode(N, IP);
1207 AllNodes.push_back(N);
1208 return SDValue(N, 0);
1211 SDValue SelectionDAG::getDbgStopPoint(SDValue Root,
1212 unsigned Line, unsigned Col,
1214 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1215 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1216 AllNodes.push_back(N);
1217 return SDValue(N, 0);
1220 SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
1223 FoldingSetNodeID ID;
1224 SDValue Ops[] = { Root };
1225 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1226 ID.AddInteger(LabelID);
1228 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1229 return SDValue(E, 0);
1230 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1231 new (N) LabelSDNode(Opcode, dl, Root, LabelID);
1232 CSEMap.InsertNode(N, IP);
1233 AllNodes.push_back(N);
1234 return SDValue(N, 0);
1237 SDValue SelectionDAG::getSrcValue(const Value *V) {
1238 assert((!V || isa<PointerType>(V->getType())) &&
1239 "SrcValue is not a pointer?");
1241 FoldingSetNodeID ID;
1242 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1246 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1247 return SDValue(E, 0);
1249 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1250 new (N) SrcValueSDNode(V);
1251 CSEMap.InsertNode(N, IP);
1252 AllNodes.push_back(N);
1253 return SDValue(N, 0);
1256 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1258 const Value *v = MO.getValue();
1259 assert((!v || isa<PointerType>(v->getType())) &&
1260 "SrcValue is not a pointer?");
1263 FoldingSetNodeID ID;
1264 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1268 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1269 return SDValue(E, 0);
1271 SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
1272 new (N) MemOperandSDNode(MO);
1273 CSEMap.InsertNode(N, IP);
1274 AllNodes.push_back(N);
1275 return SDValue(N, 0);
1278 /// getShiftAmountOperand - Return the specified value casted to
1279 /// the target's desired shift amount type.
1280 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
1281 MVT OpTy = Op.getValueType();
1282 MVT ShTy = TLI.getShiftAmountTy();
1283 if (OpTy == ShTy || OpTy.isVector()) return Op;
1285 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1286 return getNode(Opcode, ShTy, Op);
1289 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1290 /// specified value type.
1291 SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1292 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1293 unsigned ByteSize = VT.getStoreSizeInBits()/8;
1294 const Type *Ty = VT.getTypeForMVT();
1295 unsigned StackAlign =
1296 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1298 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1299 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1302 /// CreateStackTemporary - Create a stack temporary suitable for holding
1303 /// either of the specified value types.
1304 SDValue SelectionDAG::CreateStackTemporary(MVT VT1, MVT VT2) {
1305 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1306 VT2.getStoreSizeInBits())/8;
1307 const Type *Ty1 = VT1.getTypeForMVT();
1308 const Type *Ty2 = VT2.getTypeForMVT();
1309 const TargetData *TD = TLI.getTargetData();
1310 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1311 TD->getPrefTypeAlignment(Ty2));
1313 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1314 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align);
1315 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1318 SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
1319 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1320 // These setcc operations always fold.
1324 case ISD::SETFALSE2: return getConstant(0, VT);
1326 case ISD::SETTRUE2: return getConstant(1, VT);
1338 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1342 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1343 const APInt &C2 = N2C->getAPIntValue();
1344 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1345 const APInt &C1 = N1C->getAPIntValue();
1348 default: assert(0 && "Unknown integer setcc!");
1349 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1350 case ISD::SETNE: return getConstant(C1 != C2, VT);
1351 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1352 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1353 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1354 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1355 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1356 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1357 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1358 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1362 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1363 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1364 // No compile time operations on this type yet.
1365 if (N1C->getValueType(0) == MVT::ppcf128)
1368 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1371 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1372 return getNode(ISD::UNDEF, dl, VT);
1374 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1375 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1376 return getNode(ISD::UNDEF, dl, VT);
1378 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1379 R==APFloat::cmpLessThan, VT);
1380 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1381 return getNode(ISD::UNDEF, dl, VT);
1383 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1384 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1385 return getNode(ISD::UNDEF, dl, VT);
1387 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1388 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1389 return getNode(ISD::UNDEF, dl, VT);
1391 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1392 R==APFloat::cmpEqual, VT);
1393 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1394 return getNode(ISD::UNDEF, dl, VT);
1396 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1397 R==APFloat::cmpEqual, VT);
1398 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1399 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1400 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1401 R==APFloat::cmpEqual, VT);
1402 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1403 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1404 R==APFloat::cmpLessThan, VT);
1405 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1406 R==APFloat::cmpUnordered, VT);
1407 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1408 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1411 // Ensure that the constant occurs on the RHS.
1412 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1416 // Could not fold it.
1420 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1421 /// use this predicate to simplify operations downstream.
1422 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1423 unsigned BitWidth = Op.getValueSizeInBits();
1424 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1427 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1428 /// this predicate to simplify operations downstream. Mask is known to be zero
1429 /// for bits that V cannot have.
1430 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1431 unsigned Depth) const {
1432 APInt KnownZero, KnownOne;
1433 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1434 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1435 return (KnownZero & Mask) == Mask;
1438 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1439 /// known to be either zero or one and return them in the KnownZero/KnownOne
1440 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1442 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1443 APInt &KnownZero, APInt &KnownOne,
1444 unsigned Depth) const {
1445 unsigned BitWidth = Mask.getBitWidth();
1446 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1447 "Mask size mismatches value type size!");
1449 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1450 if (Depth == 6 || Mask == 0)
1451 return; // Limit search depth.
1453 APInt KnownZero2, KnownOne2;
1455 switch (Op.getOpcode()) {
1457 // We know all of the bits for a constant!
1458 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1459 KnownZero = ~KnownOne & Mask;
1462 // If either the LHS or the RHS are Zero, the result is zero.
1463 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1464 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1465 KnownZero2, KnownOne2, Depth+1);
1466 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1467 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1469 // Output known-1 bits are only known if set in both the LHS & RHS.
1470 KnownOne &= KnownOne2;
1471 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1472 KnownZero |= KnownZero2;
1475 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1476 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1477 KnownZero2, KnownOne2, Depth+1);
1478 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1479 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1481 // Output known-0 bits are only known if clear in both the LHS & RHS.
1482 KnownZero &= KnownZero2;
1483 // Output known-1 are known to be set if set in either the LHS | RHS.
1484 KnownOne |= KnownOne2;
1487 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1488 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1489 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1490 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1492 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1493 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1494 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1495 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1496 KnownZero = KnownZeroOut;
1500 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1501 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1502 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1503 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1504 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1506 // If low bits are zero in either operand, output low known-0 bits.
1507 // Also compute a conserative estimate for high known-0 bits.
1508 // More trickiness is possible, but this is sufficient for the
1509 // interesting case of alignment computation.
1511 unsigned TrailZ = KnownZero.countTrailingOnes() +
1512 KnownZero2.countTrailingOnes();
1513 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1514 KnownZero2.countLeadingOnes(),
1515 BitWidth) - BitWidth;
1517 TrailZ = std::min(TrailZ, BitWidth);
1518 LeadZ = std::min(LeadZ, BitWidth);
1519 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1520 APInt::getHighBitsSet(BitWidth, LeadZ);
1525 // For the purposes of computing leading zeros we can conservatively
1526 // treat a udiv as a logical right shift by the power of 2 known to
1527 // be less than the denominator.
1528 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1529 ComputeMaskedBits(Op.getOperand(0),
1530 AllOnes, KnownZero2, KnownOne2, Depth+1);
1531 unsigned LeadZ = KnownZero2.countLeadingOnes();
1535 ComputeMaskedBits(Op.getOperand(1),
1536 AllOnes, KnownZero2, KnownOne2, Depth+1);
1537 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1538 if (RHSUnknownLeadingOnes != BitWidth)
1539 LeadZ = std::min(BitWidth,
1540 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1542 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1546 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1547 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1548 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1549 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1551 // Only known if known in both the LHS and RHS.
1552 KnownOne &= KnownOne2;
1553 KnownZero &= KnownZero2;
1555 case ISD::SELECT_CC:
1556 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1557 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1558 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1559 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1561 // Only known if known in both the LHS and RHS.
1562 KnownOne &= KnownOne2;
1563 KnownZero &= KnownZero2;
1571 if (Op.getResNo() != 1)
1573 // The boolean result conforms to getBooleanContents. Fall through.
1575 // If we know the result of a setcc has the top bits zero, use this info.
1576 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1578 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1581 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1582 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1583 unsigned ShAmt = SA->getZExtValue();
1585 // If the shift count is an invalid immediate, don't do anything.
1586 if (ShAmt >= BitWidth)
1589 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1590 KnownZero, KnownOne, Depth+1);
1591 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1592 KnownZero <<= ShAmt;
1594 // low bits known zero.
1595 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1599 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1600 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1601 unsigned ShAmt = SA->getZExtValue();
1603 // If the shift count is an invalid immediate, don't do anything.
1604 if (ShAmt >= BitWidth)
1607 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1608 KnownZero, KnownOne, Depth+1);
1609 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1610 KnownZero = KnownZero.lshr(ShAmt);
1611 KnownOne = KnownOne.lshr(ShAmt);
1613 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1614 KnownZero |= HighBits; // High bits known zero.
1618 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1619 unsigned ShAmt = SA->getZExtValue();
1621 // If the shift count is an invalid immediate, don't do anything.
1622 if (ShAmt >= BitWidth)
1625 APInt InDemandedMask = (Mask << ShAmt);
1626 // If any of the demanded bits are produced by the sign extension, we also
1627 // demand the input sign bit.
1628 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1629 if (HighBits.getBoolValue())
1630 InDemandedMask |= APInt::getSignBit(BitWidth);
1632 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1634 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1635 KnownZero = KnownZero.lshr(ShAmt);
1636 KnownOne = KnownOne.lshr(ShAmt);
1638 // Handle the sign bits.
1639 APInt SignBit = APInt::getSignBit(BitWidth);
1640 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1642 if (KnownZero.intersects(SignBit)) {
1643 KnownZero |= HighBits; // New bits are known zero.
1644 } else if (KnownOne.intersects(SignBit)) {
1645 KnownOne |= HighBits; // New bits are known one.
1649 case ISD::SIGN_EXTEND_INREG: {
1650 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1651 unsigned EBits = EVT.getSizeInBits();
1653 // Sign extension. Compute the demanded bits in the result that are not
1654 // present in the input.
1655 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1657 APInt InSignBit = APInt::getSignBit(EBits);
1658 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1660 // If the sign extended bits are demanded, we know that the sign
1662 InSignBit.zext(BitWidth);
1663 if (NewBits.getBoolValue())
1664 InputDemandedBits |= InSignBit;
1666 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1667 KnownZero, KnownOne, Depth+1);
1668 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1670 // If the sign bit of the input is known set or clear, then we know the
1671 // top bits of the result.
1672 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1673 KnownZero |= NewBits;
1674 KnownOne &= ~NewBits;
1675 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1676 KnownOne |= NewBits;
1677 KnownZero &= ~NewBits;
1678 } else { // Input sign bit unknown
1679 KnownZero &= ~NewBits;
1680 KnownOne &= ~NewBits;
1687 unsigned LowBits = Log2_32(BitWidth)+1;
1688 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1693 if (ISD::isZEXTLoad(Op.getNode())) {
1694 LoadSDNode *LD = cast<LoadSDNode>(Op);
1695 MVT VT = LD->getMemoryVT();
1696 unsigned MemBits = VT.getSizeInBits();
1697 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1701 case ISD::ZERO_EXTEND: {
1702 MVT InVT = Op.getOperand(0).getValueType();
1703 unsigned InBits = InVT.getSizeInBits();
1704 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1705 APInt InMask = Mask;
1706 InMask.trunc(InBits);
1707 KnownZero.trunc(InBits);
1708 KnownOne.trunc(InBits);
1709 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1710 KnownZero.zext(BitWidth);
1711 KnownOne.zext(BitWidth);
1712 KnownZero |= NewBits;
1715 case ISD::SIGN_EXTEND: {
1716 MVT InVT = Op.getOperand(0).getValueType();
1717 unsigned InBits = InVT.getSizeInBits();
1718 APInt InSignBit = APInt::getSignBit(InBits);
1719 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1720 APInt InMask = Mask;
1721 InMask.trunc(InBits);
1723 // If any of the sign extended bits are demanded, we know that the sign
1724 // bit is demanded. Temporarily set this bit in the mask for our callee.
1725 if (NewBits.getBoolValue())
1726 InMask |= InSignBit;
1728 KnownZero.trunc(InBits);
1729 KnownOne.trunc(InBits);
1730 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1732 // Note if the sign bit is known to be zero or one.
1733 bool SignBitKnownZero = KnownZero.isNegative();
1734 bool SignBitKnownOne = KnownOne.isNegative();
1735 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1736 "Sign bit can't be known to be both zero and one!");
1738 // If the sign bit wasn't actually demanded by our caller, we don't
1739 // want it set in the KnownZero and KnownOne result values. Reset the
1740 // mask and reapply it to the result values.
1742 InMask.trunc(InBits);
1743 KnownZero &= InMask;
1746 KnownZero.zext(BitWidth);
1747 KnownOne.zext(BitWidth);
1749 // If the sign bit is known zero or one, the top bits match.
1750 if (SignBitKnownZero)
1751 KnownZero |= NewBits;
1752 else if (SignBitKnownOne)
1753 KnownOne |= NewBits;
1756 case ISD::ANY_EXTEND: {
1757 MVT InVT = Op.getOperand(0).getValueType();
1758 unsigned InBits = InVT.getSizeInBits();
1759 APInt InMask = Mask;
1760 InMask.trunc(InBits);
1761 KnownZero.trunc(InBits);
1762 KnownOne.trunc(InBits);
1763 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1764 KnownZero.zext(BitWidth);
1765 KnownOne.zext(BitWidth);
1768 case ISD::TRUNCATE: {
1769 MVT InVT = Op.getOperand(0).getValueType();
1770 unsigned InBits = InVT.getSizeInBits();
1771 APInt InMask = Mask;
1772 InMask.zext(InBits);
1773 KnownZero.zext(InBits);
1774 KnownOne.zext(InBits);
1775 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1776 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1777 KnownZero.trunc(BitWidth);
1778 KnownOne.trunc(BitWidth);
1781 case ISD::AssertZext: {
1782 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1783 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1784 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1786 KnownZero |= (~InMask) & Mask;
1790 // All bits are zero except the low bit.
1791 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1795 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1796 // We know that the top bits of C-X are clear if X contains less bits
1797 // than C (i.e. no wrap-around can happen). For example, 20-X is
1798 // positive if we can prove that X is >= 0 and < 16.
1799 if (CLHS->getAPIntValue().isNonNegative()) {
1800 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1801 // NLZ can't be BitWidth with no sign bit
1802 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1803 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1806 // If all of the MaskV bits are known to be zero, then we know the
1807 // output top bits are zero, because we now know that the output is
1809 if ((KnownZero2 & MaskV) == MaskV) {
1810 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1811 // Top bits known zero.
1812 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1819 // Output known-0 bits are known if clear or set in both the low clear bits
1820 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1821 // low 3 bits clear.
1822 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1823 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1824 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1825 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1827 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1828 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1829 KnownZeroOut = std::min(KnownZeroOut,
1830 KnownZero2.countTrailingOnes());
1832 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1836 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1837 const APInt &RA = Rem->getAPIntValue();
1838 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1839 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1840 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1841 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1843 // If the sign bit of the first operand is zero, the sign bit of
1844 // the result is zero. If the first operand has no one bits below
1845 // the second operand's single 1 bit, its sign will be zero.
1846 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1847 KnownZero2 |= ~LowBits;
1849 KnownZero |= KnownZero2 & Mask;
1851 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1856 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1857 const APInt &RA = Rem->getAPIntValue();
1858 if (RA.isPowerOf2()) {
1859 APInt LowBits = (RA - 1);
1860 APInt Mask2 = LowBits & Mask;
1861 KnownZero |= ~LowBits & Mask;
1862 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1863 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1868 // Since the result is less than or equal to either operand, any leading
1869 // zero bits in either operand must also exist in the result.
1870 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1871 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1873 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1876 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1877 KnownZero2.countLeadingOnes());
1879 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1883 // Allow the target to implement this method for its nodes.
1884 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1885 case ISD::INTRINSIC_WO_CHAIN:
1886 case ISD::INTRINSIC_W_CHAIN:
1887 case ISD::INTRINSIC_VOID:
1888 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1894 /// ComputeNumSignBits - Return the number of times the sign bit of the
1895 /// register is replicated into the other bits. We know that at least 1 bit
1896 /// is always equal to the sign bit (itself), but other cases can give us
1897 /// information. For example, immediately after an "SRA X, 2", we know that
1898 /// the top 3 bits are all equal to each other, so we return 3.
1899 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1900 MVT VT = Op.getValueType();
1901 assert(VT.isInteger() && "Invalid VT!");
1902 unsigned VTBits = VT.getSizeInBits();
1904 unsigned FirstAnswer = 1;
1907 return 1; // Limit search depth.
1909 switch (Op.getOpcode()) {
1911 case ISD::AssertSext:
1912 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1913 return VTBits-Tmp+1;
1914 case ISD::AssertZext:
1915 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1918 case ISD::Constant: {
1919 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1920 // If negative, return # leading ones.
1921 if (Val.isNegative())
1922 return Val.countLeadingOnes();
1924 // Return # leading zeros.
1925 return Val.countLeadingZeros();
1928 case ISD::SIGN_EXTEND:
1929 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1930 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1932 case ISD::SIGN_EXTEND_INREG:
1933 // Max of the input and what this extends.
1934 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1937 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1938 return std::max(Tmp, Tmp2);
1941 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1942 // SRA X, C -> adds C sign bits.
1943 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1944 Tmp += C->getZExtValue();
1945 if (Tmp > VTBits) Tmp = VTBits;
1949 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1950 // shl destroys sign bits.
1951 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1952 if (C->getZExtValue() >= VTBits || // Bad shift.
1953 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
1954 return Tmp - C->getZExtValue();
1959 case ISD::XOR: // NOT is handled here.
1960 // Logical binary ops preserve the number of sign bits at the worst.
1961 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1963 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1964 FirstAnswer = std::min(Tmp, Tmp2);
1965 // We computed what we know about the sign bits as our first
1966 // answer. Now proceed to the generic code that uses
1967 // ComputeMaskedBits, and pick whichever answer is better.
1972 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1973 if (Tmp == 1) return 1; // Early out.
1974 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1975 return std::min(Tmp, Tmp2);
1983 if (Op.getResNo() != 1)
1985 // The boolean result conforms to getBooleanContents. Fall through.
1987 // If setcc returns 0/-1, all bits are sign bits.
1988 if (TLI.getBooleanContents() ==
1989 TargetLowering::ZeroOrNegativeOneBooleanContent)
1994 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1995 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
1997 // Handle rotate right by N like a rotate left by 32-N.
1998 if (Op.getOpcode() == ISD::ROTR)
1999 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2001 // If we aren't rotating out all of the known-in sign bits, return the
2002 // number that are left. This handles rotl(sext(x), 1) for example.
2003 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2004 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2008 // Add can have at most one carry bit. Thus we know that the output
2009 // is, at worst, one more bit than the inputs.
2010 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2011 if (Tmp == 1) return 1; // Early out.
2013 // Special case decrementing a value (ADD X, -1):
2014 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2015 if (CRHS->isAllOnesValue()) {
2016 APInt KnownZero, KnownOne;
2017 APInt Mask = APInt::getAllOnesValue(VTBits);
2018 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2020 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2022 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2025 // If we are subtracting one from a positive number, there is no carry
2026 // out of the result.
2027 if (KnownZero.isNegative())
2031 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2032 if (Tmp2 == 1) return 1;
2033 return std::min(Tmp, Tmp2)-1;
2037 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2038 if (Tmp2 == 1) return 1;
2041 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2042 if (CLHS->isNullValue()) {
2043 APInt KnownZero, KnownOne;
2044 APInt Mask = APInt::getAllOnesValue(VTBits);
2045 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2046 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2048 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2051 // If the input is known to be positive (the sign bit is known clear),
2052 // the output of the NEG has the same number of sign bits as the input.
2053 if (KnownZero.isNegative())
2056 // Otherwise, we treat this like a SUB.
2059 // Sub can have at most one carry bit. Thus we know that the output
2060 // is, at worst, one more bit than the inputs.
2061 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2062 if (Tmp == 1) return 1; // Early out.
2063 return std::min(Tmp, Tmp2)-1;
2066 // FIXME: it's tricky to do anything useful for this, but it is an important
2067 // case for targets like X86.
2071 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2072 if (Op.getOpcode() == ISD::LOAD) {
2073 LoadSDNode *LD = cast<LoadSDNode>(Op);
2074 unsigned ExtType = LD->getExtensionType();
2077 case ISD::SEXTLOAD: // '17' bits known
2078 Tmp = LD->getMemoryVT().getSizeInBits();
2079 return VTBits-Tmp+1;
2080 case ISD::ZEXTLOAD: // '16' bits known
2081 Tmp = LD->getMemoryVT().getSizeInBits();
2086 // Allow the target to implement this method for its nodes.
2087 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2088 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2089 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2090 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2091 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2092 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2095 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2096 // use this information.
2097 APInt KnownZero, KnownOne;
2098 APInt Mask = APInt::getAllOnesValue(VTBits);
2099 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2101 if (KnownZero.isNegative()) { // sign bit is 0
2103 } else if (KnownOne.isNegative()) { // sign bit is 1;
2110 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2111 // the number of identical bits in the top of the input value.
2113 Mask <<= Mask.getBitWidth()-VTBits;
2114 // Return # leading zeros. We use 'min' here in case Val was zero before
2115 // shifting. We don't want to return '64' as for an i32 "0".
2116 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2120 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2121 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2122 if (!GA) return false;
2123 if (GA->getOffset() != 0) return false;
2124 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2125 if (!GV) return false;
2126 MachineModuleInfo *MMI = getMachineModuleInfo();
2127 return MMI && MMI->hasDebugInfo();
2131 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2132 /// element of the result of the vector shuffle.
2133 SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
2134 MVT VT = N->getValueType(0);
2135 DebugLoc dl = N->getDebugLoc();
2136 SDValue PermMask = N->getOperand(2);
2137 SDValue Idx = PermMask.getOperand(i);
2138 if (Idx.getOpcode() == ISD::UNDEF)
2139 return getNode(ISD::UNDEF, dl, VT.getVectorElementType());
2140 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
2141 unsigned NumElems = PermMask.getNumOperands();
2142 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2145 if (V.getOpcode() == ISD::BIT_CONVERT) {
2146 V = V.getOperand(0);
2147 MVT VVT = V.getValueType();
2148 if (!VVT.isVector() || VVT.getVectorNumElements() != NumElems)
2151 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2152 return (Index == 0) ? V.getOperand(0)
2153 : getNode(ISD::UNDEF, dl, VT.getVectorElementType());
2154 if (V.getOpcode() == ISD::BUILD_VECTOR)
2155 return V.getOperand(Index);
2156 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
2157 return getShuffleScalarElt(V.getNode(), Index);
2162 /// getNode - Gets or creates the specified node.
2164 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
2165 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT);
2168 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT) {
2169 FoldingSetNodeID ID;
2170 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2172 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2173 return SDValue(E, 0);
2174 SDNode *N = NodeAllocator.Allocate<SDNode>();
2175 new (N) SDNode(Opcode, DL, SDNode::getSDVTList(VT));
2176 CSEMap.InsertNode(N, IP);
2178 AllNodes.push_back(N);
2182 return SDValue(N, 0);
2185 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
2186 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Operand);
2189 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2190 MVT VT, SDValue Operand) {
2191 // Constant fold unary operations with an integer constant operand.
2192 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2193 const APInt &Val = C->getAPIntValue();
2194 unsigned BitWidth = VT.getSizeInBits();
2197 case ISD::SIGN_EXTEND:
2198 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2199 case ISD::ANY_EXTEND:
2200 case ISD::ZERO_EXTEND:
2202 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2203 case ISD::UINT_TO_FP:
2204 case ISD::SINT_TO_FP: {
2205 const uint64_t zero[] = {0, 0};
2206 // No compile time operations on this type.
2207 if (VT==MVT::ppcf128)
2209 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2210 (void)apf.convertFromAPInt(Val,
2211 Opcode==ISD::SINT_TO_FP,
2212 APFloat::rmNearestTiesToEven);
2213 return getConstantFP(apf, VT);
2215 case ISD::BIT_CONVERT:
2216 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2217 return getConstantFP(Val.bitsToFloat(), VT);
2218 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2219 return getConstantFP(Val.bitsToDouble(), VT);
2222 return getConstant(Val.byteSwap(), VT);
2224 return getConstant(Val.countPopulation(), VT);
2226 return getConstant(Val.countLeadingZeros(), VT);
2228 return getConstant(Val.countTrailingZeros(), VT);
2232 // Constant fold unary operations with a floating point constant operand.
2233 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2234 APFloat V = C->getValueAPF(); // make copy
2235 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2239 return getConstantFP(V, VT);
2242 return getConstantFP(V, VT);
2244 case ISD::FP_EXTEND: {
2246 // This can return overflow, underflow, or inexact; we don't care.
2247 // FIXME need to be more flexible about rounding mode.
2248 (void)V.convert(*MVTToAPFloatSemantics(VT),
2249 APFloat::rmNearestTiesToEven, &ignored);
2250 return getConstantFP(V, VT);
2252 case ISD::FP_TO_SINT:
2253 case ISD::FP_TO_UINT: {
2256 assert(integerPartWidth >= 64);
2257 // FIXME need to be more flexible about rounding mode.
2258 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2259 Opcode==ISD::FP_TO_SINT,
2260 APFloat::rmTowardZero, &ignored);
2261 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2263 return getConstant(x, VT);
2265 case ISD::BIT_CONVERT:
2266 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2267 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2268 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2269 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2275 unsigned OpOpcode = Operand.getNode()->getOpcode();
2277 case ISD::TokenFactor:
2278 case ISD::MERGE_VALUES:
2279 case ISD::CONCAT_VECTORS:
2280 return Operand; // Factor, merge or concat of one node? No need.
2281 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2282 case ISD::FP_EXTEND:
2283 assert(VT.isFloatingPoint() &&
2284 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2285 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2286 if (Operand.getOpcode() == ISD::UNDEF)
2287 return getNode(ISD::UNDEF, DL, VT);
2289 case ISD::SIGN_EXTEND:
2290 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2291 "Invalid SIGN_EXTEND!");
2292 if (Operand.getValueType() == VT) return Operand; // noop extension
2293 assert(Operand.getValueType().bitsLT(VT)
2294 && "Invalid sext node, dst < src!");
2295 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2296 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2298 case ISD::ZERO_EXTEND:
2299 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2300 "Invalid ZERO_EXTEND!");
2301 if (Operand.getValueType() == VT) return Operand; // noop extension
2302 assert(Operand.getValueType().bitsLT(VT)
2303 && "Invalid zext node, dst < src!");
2304 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2305 return getNode(ISD::ZERO_EXTEND, DL, VT,
2306 Operand.getNode()->getOperand(0));
2308 case ISD::ANY_EXTEND:
2309 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2310 "Invalid ANY_EXTEND!");
2311 if (Operand.getValueType() == VT) return Operand; // noop extension
2312 assert(Operand.getValueType().bitsLT(VT)
2313 && "Invalid anyext node, dst < src!");
2314 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2315 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2316 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2319 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2320 "Invalid TRUNCATE!");
2321 if (Operand.getValueType() == VT) return Operand; // noop truncate
2322 assert(Operand.getValueType().bitsGT(VT)
2323 && "Invalid truncate node, src < dst!");
2324 if (OpOpcode == ISD::TRUNCATE)
2325 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2326 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2327 OpOpcode == ISD::ANY_EXTEND) {
2328 // If the source is smaller than the dest, we still need an extend.
2329 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2330 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2331 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2332 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2334 return Operand.getNode()->getOperand(0);
2337 case ISD::BIT_CONVERT:
2338 // Basic sanity checking.
2339 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2340 && "Cannot BIT_CONVERT between types of different sizes!");
2341 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2342 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2343 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2344 if (OpOpcode == ISD::UNDEF)
2345 return getNode(ISD::UNDEF, DL, VT);
2347 case ISD::SCALAR_TO_VECTOR:
2348 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2349 VT.getVectorElementType() == Operand.getValueType() &&
2350 "Illegal SCALAR_TO_VECTOR node!");
2351 if (OpOpcode == ISD::UNDEF)
2352 return getNode(ISD::UNDEF, DL, VT);
2353 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2354 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2355 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2356 Operand.getConstantOperandVal(1) == 0 &&
2357 Operand.getOperand(0).getValueType() == VT)
2358 return Operand.getOperand(0);
2361 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2362 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2363 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2364 Operand.getNode()->getOperand(0));
2365 if (OpOpcode == ISD::FNEG) // --X -> X
2366 return Operand.getNode()->getOperand(0);
2369 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2370 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2375 SDVTList VTs = getVTList(VT);
2376 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2377 FoldingSetNodeID ID;
2378 SDValue Ops[1] = { Operand };
2379 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2381 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2382 return SDValue(E, 0);
2383 N = NodeAllocator.Allocate<UnarySDNode>();
2384 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2385 CSEMap.InsertNode(N, IP);
2387 N = NodeAllocator.Allocate<UnarySDNode>();
2388 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2391 AllNodes.push_back(N);
2395 return SDValue(N, 0);
2398 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2400 ConstantSDNode *Cst1,
2401 ConstantSDNode *Cst2) {
2402 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2405 case ISD::ADD: return getConstant(C1 + C2, VT);
2406 case ISD::SUB: return getConstant(C1 - C2, VT);
2407 case ISD::MUL: return getConstant(C1 * C2, VT);
2409 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2412 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2415 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2418 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2420 case ISD::AND: return getConstant(C1 & C2, VT);
2421 case ISD::OR: return getConstant(C1 | C2, VT);
2422 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2423 case ISD::SHL: return getConstant(C1 << C2, VT);
2424 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2425 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2426 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2427 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2434 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2435 SDValue N1, SDValue N2) {
2436 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2);
2439 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2440 SDValue N1, SDValue N2) {
2441 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2442 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2445 case ISD::TokenFactor:
2446 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2447 N2.getValueType() == MVT::Other && "Invalid token factor!");
2448 // Fold trivial token factors.
2449 if (N1.getOpcode() == ISD::EntryToken) return N2;
2450 if (N2.getOpcode() == ISD::EntryToken) return N1;
2451 if (N1 == N2) return N1;
2453 case ISD::CONCAT_VECTORS:
2454 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2455 // one big BUILD_VECTOR.
2456 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2457 N2.getOpcode() == ISD::BUILD_VECTOR) {
2458 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2459 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2460 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2464 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2465 N1.getValueType() == VT && "Binary operator types must match!");
2466 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2467 // worth handling here.
2468 if (N2C && N2C->isNullValue())
2470 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2477 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2478 N1.getValueType() == VT && "Binary operator types must match!");
2479 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2480 // it's worth handling here.
2481 if (N2C && N2C->isNullValue())
2491 assert(VT.isInteger() && "This operator does not apply to FP types!");
2499 if (Opcode == ISD::FADD) {
2501 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2502 if (CFP->getValueAPF().isZero())
2505 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2506 if (CFP->getValueAPF().isZero())
2508 } else if (Opcode == ISD::FSUB) {
2510 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2511 if (CFP->getValueAPF().isZero())
2515 assert(N1.getValueType() == N2.getValueType() &&
2516 N1.getValueType() == VT && "Binary operator types must match!");
2518 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2519 assert(N1.getValueType() == VT &&
2520 N1.getValueType().isFloatingPoint() &&
2521 N2.getValueType().isFloatingPoint() &&
2522 "Invalid FCOPYSIGN!");
2529 assert(VT == N1.getValueType() &&
2530 "Shift operators return type must be the same as their first arg");
2531 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2532 "Shifts only work on integers");
2534 // Always fold shifts of i1 values so the code generator doesn't need to
2535 // handle them. Since we know the size of the shift has to be less than the
2536 // size of the value, the shift/rotate count is guaranteed to be zero.
2540 case ISD::FP_ROUND_INREG: {
2541 MVT EVT = cast<VTSDNode>(N2)->getVT();
2542 assert(VT == N1.getValueType() && "Not an inreg round!");
2543 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2544 "Cannot FP_ROUND_INREG integer types");
2545 assert(EVT.bitsLE(VT) && "Not rounding down!");
2546 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2550 assert(VT.isFloatingPoint() &&
2551 N1.getValueType().isFloatingPoint() &&
2552 VT.bitsLE(N1.getValueType()) &&
2553 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2554 if (N1.getValueType() == VT) return N1; // noop conversion.
2556 case ISD::AssertSext:
2557 case ISD::AssertZext: {
2558 MVT EVT = cast<VTSDNode>(N2)->getVT();
2559 assert(VT == N1.getValueType() && "Not an inreg extend!");
2560 assert(VT.isInteger() && EVT.isInteger() &&
2561 "Cannot *_EXTEND_INREG FP types");
2562 assert(EVT.bitsLE(VT) && "Not extending!");
2563 if (VT == EVT) return N1; // noop assertion.
2566 case ISD::SIGN_EXTEND_INREG: {
2567 MVT EVT = cast<VTSDNode>(N2)->getVT();
2568 assert(VT == N1.getValueType() && "Not an inreg extend!");
2569 assert(VT.isInteger() && EVT.isInteger() &&
2570 "Cannot *_EXTEND_INREG FP types");
2571 assert(EVT.bitsLE(VT) && "Not extending!");
2572 if (EVT == VT) return N1; // Not actually extending
2575 APInt Val = N1C->getAPIntValue();
2576 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2577 Val <<= Val.getBitWidth()-FromBits;
2578 Val = Val.ashr(Val.getBitWidth()-FromBits);
2579 return getConstant(Val, VT);
2583 case ISD::EXTRACT_VECTOR_ELT:
2584 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2585 if (N1.getOpcode() == ISD::UNDEF)
2586 return getNode(ISD::UNDEF, DL, VT);
2588 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2589 // expanding copies of large vectors from registers.
2591 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2592 N1.getNumOperands() > 0) {
2594 N1.getOperand(0).getValueType().getVectorNumElements();
2595 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2596 N1.getOperand(N2C->getZExtValue() / Factor),
2597 getConstant(N2C->getZExtValue() % Factor,
2598 N2.getValueType()));
2601 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2602 // expanding large vector constants.
2603 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR)
2604 return N1.getOperand(N2C->getZExtValue());
2606 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2607 // operations are lowered to scalars.
2608 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2609 // If the indices are the same, return the inserted element.
2610 if (N1.getOperand(2) == N2)
2611 return N1.getOperand(1);
2612 // If the indices are known different, extract the element from
2613 // the original vector.
2614 else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2615 isa<ConstantSDNode>(N2))
2616 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2619 case ISD::EXTRACT_ELEMENT:
2620 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2621 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2622 (N1.getValueType().isInteger() == VT.isInteger()) &&
2623 "Wrong types for EXTRACT_ELEMENT!");
2625 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2626 // 64-bit integers into 32-bit parts. Instead of building the extract of
2627 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2628 if (N1.getOpcode() == ISD::BUILD_PAIR)
2629 return N1.getOperand(N2C->getZExtValue());
2631 // EXTRACT_ELEMENT of a constant int is also very common.
2632 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2633 unsigned ElementSize = VT.getSizeInBits();
2634 unsigned Shift = ElementSize * N2C->getZExtValue();
2635 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2636 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2639 case ISD::EXTRACT_SUBVECTOR:
2640 if (N1.getValueType() == VT) // Trivial extraction.
2647 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2648 if (SV.getNode()) return SV;
2649 } else { // Cannonicalize constant to RHS if commutative
2650 if (isCommutativeBinOp(Opcode)) {
2651 std::swap(N1C, N2C);
2657 // Constant fold FP operations.
2658 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2659 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2661 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2662 // Cannonicalize constant to RHS if commutative
2663 std::swap(N1CFP, N2CFP);
2665 } else if (N2CFP && VT != MVT::ppcf128) {
2666 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2667 APFloat::opStatus s;
2670 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2671 if (s != APFloat::opInvalidOp)
2672 return getConstantFP(V1, VT);
2675 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2676 if (s!=APFloat::opInvalidOp)
2677 return getConstantFP(V1, VT);
2680 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2681 if (s!=APFloat::opInvalidOp)
2682 return getConstantFP(V1, VT);
2685 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2686 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2687 return getConstantFP(V1, VT);
2690 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2691 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2692 return getConstantFP(V1, VT);
2694 case ISD::FCOPYSIGN:
2696 return getConstantFP(V1, VT);
2702 // Canonicalize an UNDEF to the RHS, even over a constant.
2703 if (N1.getOpcode() == ISD::UNDEF) {
2704 if (isCommutativeBinOp(Opcode)) {
2708 case ISD::FP_ROUND_INREG:
2709 case ISD::SIGN_EXTEND_INREG:
2715 return N1; // fold op(undef, arg2) -> undef
2723 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2724 // For vectors, we can't easily build an all zero vector, just return
2731 // Fold a bunch of operators when the RHS is undef.
2732 if (N2.getOpcode() == ISD::UNDEF) {
2735 if (N1.getOpcode() == ISD::UNDEF)
2736 // Handle undef ^ undef -> 0 special case. This is a common
2738 return getConstant(0, VT);
2753 return N2; // fold op(arg1, undef) -> undef
2759 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2760 // For vectors, we can't easily build an all zero vector, just return
2765 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2766 // For vectors, we can't easily build an all one vector, just return
2774 // Memoize this node if possible.
2776 SDVTList VTs = getVTList(VT);
2777 if (VT != MVT::Flag) {
2778 SDValue Ops[] = { N1, N2 };
2779 FoldingSetNodeID ID;
2780 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2782 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2783 return SDValue(E, 0);
2784 N = NodeAllocator.Allocate<BinarySDNode>();
2785 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2786 CSEMap.InsertNode(N, IP);
2788 N = NodeAllocator.Allocate<BinarySDNode>();
2789 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2792 AllNodes.push_back(N);
2796 return SDValue(N, 0);
2799 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2800 SDValue N1, SDValue N2, SDValue N3) {
2801 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3);
2804 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2805 SDValue N1, SDValue N2, SDValue N3) {
2806 // Perform various simplifications.
2807 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2808 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2810 case ISD::CONCAT_VECTORS:
2811 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2812 // one big BUILD_VECTOR.
2813 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2814 N2.getOpcode() == ISD::BUILD_VECTOR &&
2815 N3.getOpcode() == ISD::BUILD_VECTOR) {
2816 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2817 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2818 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2819 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2823 // Use FoldSetCC to simplify SETCC's.
2824 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
2825 if (Simp.getNode()) return Simp;
2830 if (N1C->getZExtValue())
2831 return N2; // select true, X, Y -> X
2833 return N3; // select false, X, Y -> Y
2836 if (N2 == N3) return N2; // select C, X, X -> X
2840 if (N2C->getZExtValue()) // Unconditional branch
2841 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
2843 return N1; // Never-taken branch
2846 case ISD::VECTOR_SHUFFLE:
2847 assert(N1.getValueType() == N2.getValueType() &&
2848 N1.getValueType().isVector() &&
2849 VT.isVector() && N3.getValueType().isVector() &&
2850 N3.getOpcode() == ISD::BUILD_VECTOR &&
2851 VT.getVectorNumElements() == N3.getNumOperands() &&
2852 "Illegal VECTOR_SHUFFLE node!");
2854 case ISD::BIT_CONVERT:
2855 // Fold bit_convert nodes from a type to themselves.
2856 if (N1.getValueType() == VT)
2861 // Memoize node if it doesn't produce a flag.
2863 SDVTList VTs = getVTList(VT);
2864 if (VT != MVT::Flag) {
2865 SDValue Ops[] = { N1, N2, N3 };
2866 FoldingSetNodeID ID;
2867 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2869 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2870 return SDValue(E, 0);
2871 N = NodeAllocator.Allocate<TernarySDNode>();
2872 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2873 CSEMap.InsertNode(N, IP);
2875 N = NodeAllocator.Allocate<TernarySDNode>();
2876 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2878 AllNodes.push_back(N);
2882 return SDValue(N, 0);
2885 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2886 SDValue N1, SDValue N2, SDValue N3,
2888 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3, N4);
2891 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2892 SDValue N1, SDValue N2, SDValue N3,
2894 SDValue Ops[] = { N1, N2, N3, N4 };
2895 return getNode(Opcode, DL, VT, Ops, 4);
2898 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2899 SDValue N1, SDValue N2, SDValue N3,
2900 SDValue N4, SDValue N5) {
2901 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3, N4, N5);
2904 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2905 SDValue N1, SDValue N2, SDValue N3,
2906 SDValue N4, SDValue N5) {
2907 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2908 return getNode(Opcode, DL, VT, Ops, 5);
2911 /// getMemsetValue - Vectorized representation of the memset value
2913 static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG,
2915 unsigned NumBits = VT.isVector() ?
2916 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2917 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2918 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
2920 for (unsigned i = NumBits; i > 8; i >>= 1) {
2921 Val = (Val << Shift) | Val;
2925 return DAG.getConstant(Val, VT);
2926 return DAG.getConstantFP(APFloat(Val), VT);
2929 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2930 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
2932 for (unsigned i = NumBits; i > 8; i >>= 1) {
2933 Value = DAG.getNode(ISD::OR, dl, VT,
2934 DAG.getNode(ISD::SHL, dl, VT, Value,
2935 DAG.getConstant(Shift,
2936 TLI.getShiftAmountTy())),
2944 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2945 /// used when a memcpy is turned into a memset when the source is a constant
2947 static SDValue getMemsetStringVal(MVT VT, DebugLoc dl, SelectionDAG &DAG,
2948 const TargetLowering &TLI,
2949 std::string &Str, unsigned Offset) {
2950 // Handle vector with all elements zero.
2953 return DAG.getConstant(0, VT);
2954 unsigned NumElts = VT.getVectorNumElements();
2955 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2956 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
2957 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2960 assert(!VT.isVector() && "Can't handle vector type here!");
2961 unsigned NumBits = VT.getSizeInBits();
2962 unsigned MSB = NumBits / 8;
2964 if (TLI.isLittleEndian())
2965 Offset = Offset + MSB - 1;
2966 for (unsigned i = 0; i != MSB; ++i) {
2967 Val = (Val << 8) | (unsigned char)Str[Offset];
2968 Offset += TLI.isLittleEndian() ? -1 : 1;
2970 return DAG.getConstant(Val, VT);
2973 /// getMemBasePlusOffset - Returns base and offset node for the
2975 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
2976 SelectionDAG &DAG) {
2977 MVT VT = Base.getValueType();
2978 return DAG.getNode(ISD::ADD, Base.getNode()->getDebugLoc(),
2979 VT, Base, DAG.getConstant(Offset, VT));
2982 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2984 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
2985 unsigned SrcDelta = 0;
2986 GlobalAddressSDNode *G = NULL;
2987 if (Src.getOpcode() == ISD::GlobalAddress)
2988 G = cast<GlobalAddressSDNode>(Src);
2989 else if (Src.getOpcode() == ISD::ADD &&
2990 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2991 Src.getOperand(1).getOpcode() == ISD::Constant) {
2992 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2993 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
2998 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2999 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3005 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3006 /// to replace the memset / memcpy is below the threshold. It also returns the
3007 /// types of the sequence of memory ops to perform memset / memcpy.
3009 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
3010 SDValue Dst, SDValue Src,
3011 unsigned Limit, uint64_t Size, unsigned &Align,
3012 std::string &Str, bool &isSrcStr,
3014 const TargetLowering &TLI) {
3015 isSrcStr = isMemSrcFromString(Src, Str);
3016 bool isSrcConst = isa<ConstantSDNode>(Src);
3017 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
3018 MVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
3019 if (VT != MVT::iAny) {
3020 unsigned NewAlign = (unsigned)
3021 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
3022 // If source is a string constant, this will require an unaligned load.
3023 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3024 if (Dst.getOpcode() != ISD::FrameIndex) {
3025 // Can't change destination alignment. It requires a unaligned store.
3029 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3030 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3031 if (MFI->isFixedObjectIndex(FI)) {
3032 // Can't change destination alignment. It requires a unaligned store.
3036 // Give the stack frame object a larger alignment if needed.
3037 if (MFI->getObjectAlignment(FI) < NewAlign)
3038 MFI->setObjectAlignment(FI, NewAlign);
3045 if (VT == MVT::iAny) {
3049 switch (Align & 7) {
3050 case 0: VT = MVT::i64; break;
3051 case 4: VT = MVT::i32; break;
3052 case 2: VT = MVT::i16; break;
3053 default: VT = MVT::i8; break;
3058 while (!TLI.isTypeLegal(LVT))
3059 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
3060 assert(LVT.isInteger());
3066 unsigned NumMemOps = 0;
3068 unsigned VTSize = VT.getSizeInBits() / 8;
3069 while (VTSize > Size) {
3070 // For now, only use non-vector load / store's for the left-over pieces.
3071 if (VT.isVector()) {
3073 while (!TLI.isTypeLegal(VT))
3074 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
3075 VTSize = VT.getSizeInBits() / 8;
3077 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
3082 if (++NumMemOps > Limit)
3084 MemOps.push_back(VT);
3091 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3092 SDValue Chain, SDValue Dst,
3093 SDValue Src, uint64_t Size,
3094 unsigned Align, bool AlwaysInline,
3095 const Value *DstSV, uint64_t DstSVOff,
3096 const Value *SrcSV, uint64_t SrcSVOff){
3097 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3099 // Expand memcpy to a series of load and store ops if the size operand falls
3100 // below a certain threshold.
3101 std::vector<MVT> MemOps;
3102 uint64_t Limit = -1ULL;
3104 Limit = TLI.getMaxStoresPerMemcpy();
3105 unsigned DstAlign = Align; // Destination alignment can change.
3108 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3109 Str, CopyFromStr, DAG, TLI))
3113 bool isZeroStr = CopyFromStr && Str.empty();
3114 SmallVector<SDValue, 8> OutChains;
3115 unsigned NumMemOps = MemOps.size();
3116 uint64_t SrcOff = 0, DstOff = 0;
3117 for (unsigned i = 0; i < NumMemOps; i++) {
3119 unsigned VTSize = VT.getSizeInBits() / 8;
3120 SDValue Value, Store;
3122 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3123 // It's unlikely a store of a vector immediate can be done in a single
3124 // instruction. It would require a load from a constantpool first.
3125 // We also handle store a vector with all zero's.
3126 // FIXME: Handle other cases where store of vector immediate is done in
3127 // a single instruction.
3128 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3129 Store = DAG.getStore(Chain, dl, Value,
3130 getMemBasePlusOffset(Dst, DstOff, DAG),
3131 DstSV, DstSVOff + DstOff, false, DstAlign);
3133 Value = DAG.getLoad(VT, dl, Chain,
3134 getMemBasePlusOffset(Src, SrcOff, DAG),
3135 SrcSV, SrcSVOff + SrcOff, false, Align);
3136 Store = DAG.getStore(Chain, dl, Value,
3137 getMemBasePlusOffset(Dst, DstOff, DAG),
3138 DstSV, DstSVOff + DstOff, false, DstAlign);
3140 OutChains.push_back(Store);
3145 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3146 &OutChains[0], OutChains.size());
3149 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3150 SDValue Chain, SDValue Dst,
3151 SDValue Src, uint64_t Size,
3152 unsigned Align, bool AlwaysInline,
3153 const Value *DstSV, uint64_t DstSVOff,
3154 const Value *SrcSV, uint64_t SrcSVOff){
3155 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3157 // Expand memmove to a series of load and store ops if the size operand falls
3158 // below a certain threshold.
3159 std::vector<MVT> MemOps;
3160 uint64_t Limit = -1ULL;
3162 Limit = TLI.getMaxStoresPerMemmove();
3163 unsigned DstAlign = Align; // Destination alignment can change.
3166 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3167 Str, CopyFromStr, DAG, TLI))
3170 uint64_t SrcOff = 0, DstOff = 0;
3172 SmallVector<SDValue, 8> LoadValues;
3173 SmallVector<SDValue, 8> LoadChains;
3174 SmallVector<SDValue, 8> OutChains;
3175 unsigned NumMemOps = MemOps.size();
3176 for (unsigned i = 0; i < NumMemOps; i++) {
3178 unsigned VTSize = VT.getSizeInBits() / 8;
3179 SDValue Value, Store;
3181 Value = DAG.getLoad(VT, dl, Chain,
3182 getMemBasePlusOffset(Src, SrcOff, DAG),
3183 SrcSV, SrcSVOff + SrcOff, false, Align);
3184 LoadValues.push_back(Value);
3185 LoadChains.push_back(Value.getValue(1));
3188 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3189 &LoadChains[0], LoadChains.size());
3191 for (unsigned i = 0; i < NumMemOps; i++) {
3193 unsigned VTSize = VT.getSizeInBits() / 8;
3194 SDValue Value, Store;
3196 Store = DAG.getStore(Chain, dl, LoadValues[i],
3197 getMemBasePlusOffset(Dst, DstOff, DAG),
3198 DstSV, DstSVOff + DstOff, false, DstAlign);
3199 OutChains.push_back(Store);
3203 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3204 &OutChains[0], OutChains.size());
3207 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3208 SDValue Chain, SDValue Dst,
3209 SDValue Src, uint64_t Size,
3211 const Value *DstSV, uint64_t DstSVOff) {
3212 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3214 // Expand memset to a series of load/store ops if the size operand
3215 // falls below a certain threshold.
3216 std::vector<MVT> MemOps;
3219 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3220 Size, Align, Str, CopyFromStr, DAG, TLI))
3223 SmallVector<SDValue, 8> OutChains;
3224 uint64_t DstOff = 0;
3226 unsigned NumMemOps = MemOps.size();
3227 for (unsigned i = 0; i < NumMemOps; i++) {
3229 unsigned VTSize = VT.getSizeInBits() / 8;
3230 SDValue Value = getMemsetValue(Src, VT, DAG, dl);
3231 SDValue Store = DAG.getStore(Chain, dl, Value,
3232 getMemBasePlusOffset(Dst, DstOff, DAG),
3233 DstSV, DstSVOff + DstOff);
3234 OutChains.push_back(Store);
3238 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3239 &OutChains[0], OutChains.size());
3242 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3243 SDValue Src, SDValue Size,
3244 unsigned Align, bool AlwaysInline,
3245 const Value *DstSV, uint64_t DstSVOff,
3246 const Value *SrcSV, uint64_t SrcSVOff) {
3248 // Check to see if we should lower the memcpy to loads and stores first.
3249 // For cases within the target-specified limits, this is the best choice.
3250 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3252 // Memcpy with size zero? Just return the original chain.
3253 if (ConstantSize->isNullValue())
3257 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3258 ConstantSize->getZExtValue(),
3259 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3260 if (Result.getNode())
3264 // Then check to see if we should lower the memcpy with target-specific
3265 // code. If the target chooses to do this, this is the next best.
3267 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3269 DstSV, DstSVOff, SrcSV, SrcSVOff);
3270 if (Result.getNode())
3273 // If we really need inline code and the target declined to provide it,
3274 // use a (potentially long) sequence of loads and stores.
3276 assert(ConstantSize && "AlwaysInline requires a constant size!");
3277 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3278 ConstantSize->getZExtValue(), Align, true,
3279 DstSV, DstSVOff, SrcSV, SrcSVOff);
3282 // Emit a library call.
3283 TargetLowering::ArgListTy Args;
3284 TargetLowering::ArgListEntry Entry;
3285 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3286 Entry.Node = Dst; Args.push_back(Entry);
3287 Entry.Node = Src; Args.push_back(Entry);
3288 Entry.Node = Size; Args.push_back(Entry);
3289 // FIXME: pass in DebugLoc
3290 std::pair<SDValue,SDValue> CallResult =
3291 TLI.LowerCallTo(Chain, Type::VoidTy,
3292 false, false, false, false, CallingConv::C, false,
3293 getExternalSymbol("memcpy", TLI.getPointerTy()),
3295 return CallResult.second;
3298 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3299 SDValue Src, SDValue Size,
3301 const Value *DstSV, uint64_t DstSVOff,
3302 const Value *SrcSV, uint64_t SrcSVOff) {
3304 // Check to see if we should lower the memmove to loads and stores first.
3305 // For cases within the target-specified limits, this is the best choice.
3306 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3308 // Memmove with size zero? Just return the original chain.
3309 if (ConstantSize->isNullValue())
3313 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3314 ConstantSize->getZExtValue(),
3315 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3316 if (Result.getNode())
3320 // Then check to see if we should lower the memmove with target-specific
3321 // code. If the target chooses to do this, this is the next best.
3323 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
3324 DstSV, DstSVOff, SrcSV, SrcSVOff);
3325 if (Result.getNode())
3328 // Emit a library call.
3329 TargetLowering::ArgListTy Args;
3330 TargetLowering::ArgListEntry Entry;
3331 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3332 Entry.Node = Dst; Args.push_back(Entry);
3333 Entry.Node = Src; Args.push_back(Entry);
3334 Entry.Node = Size; Args.push_back(Entry);
3335 // FIXME: pass in DebugLoc
3336 std::pair<SDValue,SDValue> CallResult =
3337 TLI.LowerCallTo(Chain, Type::VoidTy,
3338 false, false, false, false, CallingConv::C, false,
3339 getExternalSymbol("memmove", TLI.getPointerTy()),
3341 return CallResult.second;
3344 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3345 SDValue Src, SDValue Size,
3347 const Value *DstSV, uint64_t DstSVOff) {
3349 // Check to see if we should lower the memset to stores first.
3350 // For cases within the target-specified limits, this is the best choice.
3351 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3353 // Memset with size zero? Just return the original chain.
3354 if (ConstantSize->isNullValue())
3358 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3359 Align, DstSV, DstSVOff);
3360 if (Result.getNode())
3364 // Then check to see if we should lower the memset with target-specific
3365 // code. If the target chooses to do this, this is the next best.
3367 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
3369 if (Result.getNode())
3372 // Emit a library call.
3373 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3374 TargetLowering::ArgListTy Args;
3375 TargetLowering::ArgListEntry Entry;
3376 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3377 Args.push_back(Entry);
3378 // Extend or truncate the argument to be an i32 value for the call.
3379 if (Src.getValueType().bitsGT(MVT::i32))
3380 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3382 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3383 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3384 Args.push_back(Entry);
3385 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3386 Args.push_back(Entry);
3387 // FIXME: pass in DebugLoc
3388 std::pair<SDValue,SDValue> CallResult =
3389 TLI.LowerCallTo(Chain, Type::VoidTy,
3390 false, false, false, false, CallingConv::C, false,
3391 getExternalSymbol("memset", TLI.getPointerTy()),
3393 return CallResult.second;
3396 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
3398 SDValue Ptr, SDValue Cmp,
3399 SDValue Swp, const Value* PtrVal,
3400 unsigned Alignment) {
3401 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3402 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3404 MVT VT = Cmp.getValueType();
3406 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3407 Alignment = getMVTAlignment(MemVT);
3409 SDVTList VTs = getVTList(VT, MVT::Other);
3410 FoldingSetNodeID ID;
3411 ID.AddInteger(MemVT.getRawBits());
3412 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3413 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3415 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3416 return SDValue(E, 0);
3417 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3418 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
3419 Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3420 CSEMap.InsertNode(N, IP);
3421 AllNodes.push_back(N);
3422 return SDValue(N, 0);
3425 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
3427 SDValue Ptr, SDValue Val,
3428 const Value* PtrVal,
3429 unsigned Alignment) {
3430 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3431 Opcode == ISD::ATOMIC_LOAD_SUB ||
3432 Opcode == ISD::ATOMIC_LOAD_AND ||
3433 Opcode == ISD::ATOMIC_LOAD_OR ||
3434 Opcode == ISD::ATOMIC_LOAD_XOR ||
3435 Opcode == ISD::ATOMIC_LOAD_NAND ||
3436 Opcode == ISD::ATOMIC_LOAD_MIN ||
3437 Opcode == ISD::ATOMIC_LOAD_MAX ||
3438 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3439 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3440 Opcode == ISD::ATOMIC_SWAP) &&
3441 "Invalid Atomic Op");
3443 MVT VT = Val.getValueType();
3445 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3446 Alignment = getMVTAlignment(MemVT);
3448 SDVTList VTs = getVTList(VT, MVT::Other);
3449 FoldingSetNodeID ID;
3450 ID.AddInteger(MemVT.getRawBits());
3451 SDValue Ops[] = {Chain, Ptr, Val};
3452 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3454 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3455 return SDValue(E, 0);
3456 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3457 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
3458 Chain, Ptr, Val, PtrVal, Alignment);
3459 CSEMap.InsertNode(N, IP);
3460 AllNodes.push_back(N);
3461 return SDValue(N, 0);
3464 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3465 /// Allowed to return something different (and simpler) if Simplify is true.
3466 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps) {
3470 SmallVector<MVT, 4> VTs;
3471 VTs.reserve(NumOps);
3472 for (unsigned i = 0; i < NumOps; ++i)
3473 VTs.push_back(Ops[i].getValueType());
3474 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3477 /// DebugLoc-aware version.
3478 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3483 SmallVector<MVT, 4> VTs;
3484 VTs.reserve(NumOps);
3485 for (unsigned i = 0; i < NumOps; ++i)
3486 VTs.push_back(Ops[i].getValueType());
3487 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3492 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3493 const MVT *VTs, unsigned NumVTs,
3494 const SDValue *Ops, unsigned NumOps,
3495 MVT MemVT, const Value *srcValue, int SVOff,
3496 unsigned Align, bool Vol,
3497 bool ReadMem, bool WriteMem) {
3498 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3499 MemVT, srcValue, SVOff, Align, Vol,
3504 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3505 const SDValue *Ops, unsigned NumOps,
3506 MVT MemVT, const Value *srcValue, int SVOff,
3507 unsigned Align, bool Vol,
3508 bool ReadMem, bool WriteMem) {
3509 // Memoize the node unless it returns a flag.
3510 MemIntrinsicSDNode *N;
3511 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3512 FoldingSetNodeID ID;
3513 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3515 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3516 return SDValue(E, 0);
3518 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3519 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
3520 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3521 CSEMap.InsertNode(N, IP);
3523 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3524 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
3525 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3527 AllNodes.push_back(N);
3528 return SDValue(N, 0);
3532 SelectionDAG::getCall(unsigned CallingConv, DebugLoc dl, bool IsVarArgs,
3533 bool IsTailCall, bool IsInreg, SDVTList VTs,
3534 const SDValue *Operands, unsigned NumOperands) {
3535 // Do not include isTailCall in the folding set profile.
3536 FoldingSetNodeID ID;
3537 AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
3538 ID.AddInteger(CallingConv);
3539 ID.AddInteger(IsVarArgs);
3541 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3542 // Instead of including isTailCall in the folding set, we just
3543 // set the flag of the existing node.
3545 cast<CallSDNode>(E)->setNotTailCall();
3546 return SDValue(E, 0);
3548 SDNode *N = NodeAllocator.Allocate<CallSDNode>();
3549 new (N) CallSDNode(CallingConv, dl, IsVarArgs, IsTailCall, IsInreg,
3550 VTs, Operands, NumOperands);
3551 CSEMap.InsertNode(N, IP);
3552 AllNodes.push_back(N);
3553 return SDValue(N, 0);
3557 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3558 MVT VT, SDValue Chain,
3559 SDValue Ptr, SDValue Offset,
3560 const Value *SV, int SVOffset, MVT EVT,
3561 bool isVolatile, unsigned Alignment) {
3562 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3563 Alignment = getMVTAlignment(VT);
3566 ExtType = ISD::NON_EXTLOAD;
3567 } else if (ExtType == ISD::NON_EXTLOAD) {
3568 assert(VT == EVT && "Non-extending load from different memory type!");
3572 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3573 "Invalid vector extload!");
3575 assert(EVT.bitsLT(VT) &&
3576 "Should only be an extending load, not truncating!");
3577 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3578 "Cannot sign/zero extend a FP/Vector load!");
3579 assert(VT.isInteger() == EVT.isInteger() &&
3580 "Cannot convert from FP to Int or Int -> FP!");
3583 bool Indexed = AM != ISD::UNINDEXED;
3584 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3585 "Unindexed load with an offset!");
3587 SDVTList VTs = Indexed ?
3588 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3589 SDValue Ops[] = { Chain, Ptr, Offset };
3590 FoldingSetNodeID ID;
3591 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3592 ID.AddInteger(EVT.getRawBits());
3593 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, isVolatile, Alignment));
3595 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3596 return SDValue(E, 0);
3597 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3598 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3599 Alignment, isVolatile);
3600 CSEMap.InsertNode(N, IP);
3601 AllNodes.push_back(N);
3602 return SDValue(N, 0);
3606 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3607 ISD::LoadExtType ExtType, MVT VT, SDValue Chain,
3608 SDValue Ptr, SDValue Offset,
3609 const Value *SV, int SVOffset, MVT EVT,
3610 bool isVolatile, unsigned Alignment) {
3611 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3612 Alignment = getMVTAlignment(VT);
3615 ExtType = ISD::NON_EXTLOAD;
3616 } else if (ExtType == ISD::NON_EXTLOAD) {
3617 assert(VT == EVT && "Non-extending load from different memory type!");
3621 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3622 "Invalid vector extload!");
3624 assert(EVT.bitsLT(VT) &&
3625 "Should only be an extending load, not truncating!");
3626 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3627 "Cannot sign/zero extend a FP/Vector load!");
3628 assert(VT.isInteger() == EVT.isInteger() &&
3629 "Cannot convert from FP to Int or Int -> FP!");
3632 bool Indexed = AM != ISD::UNINDEXED;
3633 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3634 "Unindexed load with an offset!");
3636 SDVTList VTs = Indexed ?
3637 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3638 SDValue Ops[] = { Chain, Ptr, Offset };
3639 FoldingSetNodeID ID;
3640 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3641 ID.AddInteger(EVT.getRawBits());
3642 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, isVolatile, Alignment));
3644 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3645 return SDValue(E, 0);
3646 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3647 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, EVT, SV, SVOffset,
3648 Alignment, isVolatile);
3649 CSEMap.InsertNode(N, IP);
3650 AllNodes.push_back(N);
3651 return SDValue(N, 0);
3654 SDValue SelectionDAG::getLoad(MVT VT,
3655 SDValue Chain, SDValue Ptr,
3656 const Value *SV, int SVOffset,
3657 bool isVolatile, unsigned Alignment) {
3658 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3659 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3660 SV, SVOffset, VT, isVolatile, Alignment);
3663 SDValue SelectionDAG::getLoad(MVT VT, DebugLoc dl,
3664 SDValue Chain, SDValue Ptr,
3665 const Value *SV, int SVOffset,
3666 bool isVolatile, unsigned Alignment) {
3667 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3668 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3669 SV, SVOffset, VT, isVolatile, Alignment);
3672 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, MVT VT,
3673 SDValue Chain, SDValue Ptr,
3675 int SVOffset, MVT EVT,
3676 bool isVolatile, unsigned Alignment) {
3677 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3678 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3679 SV, SVOffset, EVT, isVolatile, Alignment);
3683 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3684 SDValue Offset, ISD::MemIndexedMode AM) {
3685 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3686 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3687 "Load is already a indexed load!");
3688 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3689 LD->getChain(), Base, Offset, LD->getSrcValue(),
3690 LD->getSrcValueOffset(), LD->getMemoryVT(),
3691 LD->isVolatile(), LD->getAlignment());
3694 SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
3695 SDValue Ptr, const Value *SV, int SVOffset,
3696 bool isVolatile, unsigned Alignment) {
3697 MVT VT = Val.getValueType();
3699 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3700 Alignment = getMVTAlignment(VT);
3702 SDVTList VTs = getVTList(MVT::Other);
3703 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3704 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3705 FoldingSetNodeID ID;
3706 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3707 ID.AddInteger(VT.getRawBits());
3708 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED,
3709 isVolatile, Alignment));
3711 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3712 return SDValue(E, 0);
3713 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3714 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3715 VT, SV, SVOffset, Alignment, isVolatile);
3716 CSEMap.InsertNode(N, IP);
3717 AllNodes.push_back(N);
3718 return SDValue(N, 0);
3721 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3722 SDValue Ptr, const Value *SV, int SVOffset,
3723 bool isVolatile, unsigned Alignment) {
3724 MVT VT = Val.getValueType();
3726 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3727 Alignment = getMVTAlignment(VT);
3729 SDVTList VTs = getVTList(MVT::Other);
3730 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3731 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3732 FoldingSetNodeID ID;
3733 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3734 ID.AddInteger(VT.getRawBits());
3735 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED,
3736 isVolatile, Alignment));
3738 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3739 return SDValue(E, 0);
3740 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3741 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false,
3742 VT, SV, SVOffset, Alignment, isVolatile);
3743 CSEMap.InsertNode(N, IP);
3744 AllNodes.push_back(N);
3745 return SDValue(N, 0);
3748 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3749 SDValue Ptr, const Value *SV,
3750 int SVOffset, MVT SVT,
3751 bool isVolatile, unsigned Alignment) {
3752 MVT VT = Val.getValueType();
3755 return getStore(Chain, dl, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3757 assert(VT.bitsGT(SVT) && "Not a truncation?");
3758 assert(VT.isInteger() == SVT.isInteger() &&
3759 "Can't do FP-INT conversion!");
3761 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3762 Alignment = getMVTAlignment(VT);
3764 SDVTList VTs = getVTList(MVT::Other);
3765 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3766 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3767 FoldingSetNodeID ID;
3768 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3769 ID.AddInteger(SVT.getRawBits());
3770 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED,
3771 isVolatile, Alignment));
3773 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3774 return SDValue(E, 0);
3775 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3776 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true,
3777 SVT, SV, SVOffset, Alignment, isVolatile);
3778 CSEMap.InsertNode(N, IP);
3779 AllNodes.push_back(N);
3780 return SDValue(N, 0);
3784 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
3785 SDValue Offset, ISD::MemIndexedMode AM) {
3786 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3787 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3788 "Store is already a indexed store!");
3789 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3790 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3791 FoldingSetNodeID ID;
3792 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3793 ID.AddInteger(ST->getMemoryVT().getRawBits());
3794 ID.AddInteger(ST->getRawSubclassData());
3796 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3797 return SDValue(E, 0);
3798 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3799 new (N) StoreSDNode(Ops, dl, VTs, AM,
3800 ST->isTruncatingStore(), ST->getMemoryVT(),
3801 ST->getSrcValue(), ST->getSrcValueOffset(),
3802 ST->getAlignment(), ST->isVolatile());
3803 CSEMap.InsertNode(N, IP);
3804 AllNodes.push_back(N);
3805 return SDValue(N, 0);
3808 SDValue SelectionDAG::getVAArg(MVT VT, DebugLoc dl,
3809 SDValue Chain, SDValue Ptr,
3811 SDValue Ops[] = { Chain, Ptr, SV };
3812 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
3815 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3816 const SDUse *Ops, unsigned NumOps) {
3817 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Ops, NumOps);
3820 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
3821 const SDUse *Ops, unsigned NumOps) {
3823 case 0: return getNode(Opcode, DL, VT);
3824 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3825 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3826 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3830 // Copy from an SDUse array into an SDValue array for use with
3831 // the regular getNode logic.
3832 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3833 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
3836 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3837 const SDValue *Ops, unsigned NumOps) {
3838 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Ops, NumOps);
3841 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
3842 const SDValue *Ops, unsigned NumOps) {
3844 case 0: return getNode(Opcode, DL, VT);
3845 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3846 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3847 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3853 case ISD::SELECT_CC: {
3854 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3855 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3856 "LHS and RHS of condition must have same type!");
3857 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3858 "True and False arms of SelectCC must have same type!");
3859 assert(Ops[2].getValueType() == VT &&
3860 "select_cc node must be of same type as true and false value!");
3864 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3865 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3866 "LHS/RHS of comparison should match types!");
3873 SDVTList VTs = getVTList(VT);
3875 if (VT != MVT::Flag) {
3876 FoldingSetNodeID ID;
3877 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3880 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3881 return SDValue(E, 0);
3883 N = NodeAllocator.Allocate<SDNode>();
3884 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
3885 CSEMap.InsertNode(N, IP);
3887 N = NodeAllocator.Allocate<SDNode>();
3888 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
3891 AllNodes.push_back(N);
3895 return SDValue(N, 0);
3898 SDValue SelectionDAG::getNode(unsigned Opcode,
3899 const std::vector<MVT> &ResultTys,
3900 const SDValue *Ops, unsigned NumOps) {
3901 return getNode(Opcode, DebugLoc::getUnknownLoc(), ResultTys, Ops, NumOps);
3904 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
3905 const std::vector<MVT> &ResultTys,
3906 const SDValue *Ops, unsigned NumOps) {
3907 return getNode(Opcode, DL, getNodeValueTypes(ResultTys), ResultTys.size(),
3911 SDValue SelectionDAG::getNode(unsigned Opcode,
3912 const MVT *VTs, unsigned NumVTs,
3913 const SDValue *Ops, unsigned NumOps) {
3914 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTs, NumVTs, Ops, NumOps);
3917 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
3918 const MVT *VTs, unsigned NumVTs,
3919 const SDValue *Ops, unsigned NumOps) {
3921 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
3922 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
3925 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3926 const SDValue *Ops, unsigned NumOps) {
3927 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, Ops, NumOps);
3930 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
3931 const SDValue *Ops, unsigned NumOps) {
3932 if (VTList.NumVTs == 1)
3933 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
3936 // FIXME: figure out how to safely handle things like
3937 // int foo(int x) { return 1 << (x & 255); }
3938 // int bar() { return foo(256); }
3940 case ISD::SRA_PARTS:
3941 case ISD::SRL_PARTS:
3942 case ISD::SHL_PARTS:
3943 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3944 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3945 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
3946 else if (N3.getOpcode() == ISD::AND)
3947 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3948 // If the and is only masking out bits that cannot effect the shift,
3949 // eliminate the and.
3950 unsigned NumBits = VT.getSizeInBits()*2;
3951 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3952 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
3958 // Memoize the node unless it returns a flag.
3960 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3961 FoldingSetNodeID ID;
3962 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3964 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3965 return SDValue(E, 0);
3967 N = NodeAllocator.Allocate<UnarySDNode>();
3968 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
3969 } else if (NumOps == 2) {
3970 N = NodeAllocator.Allocate<BinarySDNode>();
3971 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
3972 } else if (NumOps == 3) {
3973 N = NodeAllocator.Allocate<TernarySDNode>();
3974 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
3976 N = NodeAllocator.Allocate<SDNode>();
3977 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
3979 CSEMap.InsertNode(N, IP);
3982 N = NodeAllocator.Allocate<UnarySDNode>();
3983 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
3984 } else if (NumOps == 2) {
3985 N = NodeAllocator.Allocate<BinarySDNode>();
3986 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
3987 } else if (NumOps == 3) {
3988 N = NodeAllocator.Allocate<TernarySDNode>();
3989 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
3991 N = NodeAllocator.Allocate<SDNode>();
3992 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
3995 AllNodes.push_back(N);
3999 return SDValue(N, 0);
4002 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
4003 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList);
4006 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4007 return getNode(Opcode, DL, VTList, 0, 0);
4010 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4012 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1);
4015 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4017 SDValue Ops[] = { N1 };
4018 return getNode(Opcode, DL, VTList, Ops, 1);
4021 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4022 SDValue N1, SDValue N2) {
4023 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2);
4026 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4027 SDValue N1, SDValue N2) {
4028 SDValue Ops[] = { N1, N2 };
4029 return getNode(Opcode, DL, VTList, Ops, 2);
4032 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4033 SDValue N1, SDValue N2, SDValue N3) {
4034 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3);
4037 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4038 SDValue N1, SDValue N2, SDValue N3) {
4039 SDValue Ops[] = { N1, N2, N3 };
4040 return getNode(Opcode, DL, VTList, Ops, 3);
4043 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4044 SDValue N1, SDValue N2, SDValue N3,
4046 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3, N4);
4049 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4050 SDValue N1, SDValue N2, SDValue N3,
4052 SDValue Ops[] = { N1, N2, N3, N4 };
4053 return getNode(Opcode, DL, VTList, Ops, 4);
4056 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4057 SDValue N1, SDValue N2, SDValue N3,
4058 SDValue N4, SDValue N5) {
4059 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3, N4, N5);
4062 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4063 SDValue N1, SDValue N2, SDValue N3,
4064 SDValue N4, SDValue N5) {
4065 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4066 return getNode(Opcode, DL, VTList, Ops, 5);
4069 SDVTList SelectionDAG::getVTList(MVT VT) {
4070 return makeVTList(SDNode::getValueTypeList(VT), 1);
4073 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
4074 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4075 E = VTList.rend(); I != E; ++I)
4076 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4079 MVT *Array = Allocator.Allocate<MVT>(2);
4082 SDVTList Result = makeVTList(Array, 2);
4083 VTList.push_back(Result);
4087 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
4088 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4089 E = VTList.rend(); I != E; ++I)
4090 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4094 MVT *Array = Allocator.Allocate<MVT>(3);
4098 SDVTList Result = makeVTList(Array, 3);
4099 VTList.push_back(Result);
4103 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3, MVT VT4) {
4104 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4105 E = VTList.rend(); I != E; ++I)
4106 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4107 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4110 MVT *Array = Allocator.Allocate<MVT>(3);
4115 SDVTList Result = makeVTList(Array, 4);
4116 VTList.push_back(Result);
4120 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
4122 case 0: assert(0 && "Cannot have nodes without results!");
4123 case 1: return getVTList(VTs[0]);
4124 case 2: return getVTList(VTs[0], VTs[1]);
4125 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4129 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4130 E = VTList.rend(); I != E; ++I) {
4131 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4134 bool NoMatch = false;
4135 for (unsigned i = 2; i != NumVTs; ++i)
4136 if (VTs[i] != I->VTs[i]) {
4144 MVT *Array = Allocator.Allocate<MVT>(NumVTs);
4145 std::copy(VTs, VTs+NumVTs, Array);
4146 SDVTList Result = makeVTList(Array, NumVTs);
4147 VTList.push_back(Result);
4152 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4153 /// specified operands. If the resultant node already exists in the DAG,
4154 /// this does not modify the specified node, instead it returns the node that
4155 /// already exists. If the resultant node does not exist in the DAG, the
4156 /// input node is returned. As a degenerate case, if you specify the same
4157 /// input operands as the node already has, the input node is returned.
4158 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4159 SDNode *N = InN.getNode();
4160 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4162 // Check to see if there is no change.
4163 if (Op == N->getOperand(0)) return InN;
4165 // See if the modified node already exists.
4166 void *InsertPos = 0;
4167 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4168 return SDValue(Existing, InN.getResNo());
4170 // Nope it doesn't. Remove the node from its current place in the maps.
4172 if (!RemoveNodeFromCSEMaps(N))
4175 // Now we update the operands.
4176 N->OperandList[0].set(Op);
4178 // If this gets put into a CSE map, add it.
4179 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4183 SDValue SelectionDAG::
4184 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4185 SDNode *N = InN.getNode();
4186 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4188 // Check to see if there is no change.
4189 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4190 return InN; // No operands changed, just return the input node.
4192 // See if the modified node already exists.
4193 void *InsertPos = 0;
4194 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4195 return SDValue(Existing, InN.getResNo());
4197 // Nope it doesn't. Remove the node from its current place in the maps.
4199 if (!RemoveNodeFromCSEMaps(N))
4202 // Now we update the operands.
4203 if (N->OperandList[0] != Op1)
4204 N->OperandList[0].set(Op1);
4205 if (N->OperandList[1] != Op2)
4206 N->OperandList[1].set(Op2);
4208 // If this gets put into a CSE map, add it.
4209 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4213 SDValue SelectionDAG::
4214 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4215 SDValue Ops[] = { Op1, Op2, Op3 };
4216 return UpdateNodeOperands(N, Ops, 3);
4219 SDValue SelectionDAG::
4220 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4221 SDValue Op3, SDValue Op4) {
4222 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4223 return UpdateNodeOperands(N, Ops, 4);
4226 SDValue SelectionDAG::
4227 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4228 SDValue Op3, SDValue Op4, SDValue Op5) {
4229 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4230 return UpdateNodeOperands(N, Ops, 5);
4233 SDValue SelectionDAG::
4234 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4235 SDNode *N = InN.getNode();
4236 assert(N->getNumOperands() == NumOps &&
4237 "Update with wrong number of operands");
4239 // Check to see if there is no change.
4240 bool AnyChange = false;
4241 for (unsigned i = 0; i != NumOps; ++i) {
4242 if (Ops[i] != N->getOperand(i)) {
4248 // No operands changed, just return the input node.
4249 if (!AnyChange) return InN;
4251 // See if the modified node already exists.
4252 void *InsertPos = 0;
4253 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4254 return SDValue(Existing, InN.getResNo());
4256 // Nope it doesn't. Remove the node from its current place in the maps.
4258 if (!RemoveNodeFromCSEMaps(N))
4261 // Now we update the operands.
4262 for (unsigned i = 0; i != NumOps; ++i)
4263 if (N->OperandList[i] != Ops[i])
4264 N->OperandList[i].set(Ops[i]);
4266 // If this gets put into a CSE map, add it.
4267 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4271 /// DropOperands - Release the operands and set this node to have
4273 void SDNode::DropOperands() {
4274 // Unlike the code in MorphNodeTo that does this, we don't need to
4275 // watch for dead nodes here.
4276 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4282 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4285 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4287 SDVTList VTs = getVTList(VT);
4288 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4291 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4292 MVT VT, SDValue Op1) {
4293 SDVTList VTs = getVTList(VT);
4294 SDValue Ops[] = { Op1 };
4295 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4298 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4299 MVT VT, SDValue Op1,
4301 SDVTList VTs = getVTList(VT);
4302 SDValue Ops[] = { Op1, Op2 };
4303 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4306 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4307 MVT VT, SDValue Op1,
4308 SDValue Op2, SDValue Op3) {
4309 SDVTList VTs = getVTList(VT);
4310 SDValue Ops[] = { Op1, Op2, Op3 };
4311 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4314 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4315 MVT VT, const SDValue *Ops,
4317 SDVTList VTs = getVTList(VT);
4318 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4321 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4322 MVT VT1, MVT VT2, const SDValue *Ops,
4324 SDVTList VTs = getVTList(VT1, VT2);
4325 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4328 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4330 SDVTList VTs = getVTList(VT1, VT2);
4331 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4334 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4335 MVT VT1, MVT VT2, MVT VT3,
4336 const SDValue *Ops, unsigned NumOps) {
4337 SDVTList VTs = getVTList(VT1, VT2, VT3);
4338 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4341 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4342 MVT VT1, MVT VT2, MVT VT3, MVT VT4,
4343 const SDValue *Ops, unsigned NumOps) {
4344 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4345 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4348 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4351 SDVTList VTs = getVTList(VT1, VT2);
4352 SDValue Ops[] = { Op1 };
4353 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4356 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4358 SDValue Op1, SDValue Op2) {
4359 SDVTList VTs = getVTList(VT1, VT2);
4360 SDValue Ops[] = { Op1, Op2 };
4361 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4364 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4366 SDValue Op1, SDValue Op2,
4368 SDVTList VTs = getVTList(VT1, VT2);
4369 SDValue Ops[] = { Op1, Op2, Op3 };
4370 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4373 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4374 MVT VT1, MVT VT2, MVT VT3,
4375 SDValue Op1, SDValue Op2,
4377 SDVTList VTs = getVTList(VT1, VT2, VT3);
4378 SDValue Ops[] = { Op1, Op2, Op3 };
4379 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4382 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4383 SDVTList VTs, const SDValue *Ops,
4385 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4388 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4390 SDVTList VTs = getVTList(VT);
4391 return MorphNodeTo(N, Opc, VTs, 0, 0);
4394 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4395 MVT VT, SDValue Op1) {
4396 SDVTList VTs = getVTList(VT);
4397 SDValue Ops[] = { Op1 };
4398 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4401 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4402 MVT VT, SDValue Op1,
4404 SDVTList VTs = getVTList(VT);
4405 SDValue Ops[] = { Op1, Op2 };
4406 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4409 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4410 MVT VT, SDValue Op1,
4411 SDValue Op2, SDValue Op3) {
4412 SDVTList VTs = getVTList(VT);
4413 SDValue Ops[] = { Op1, Op2, Op3 };
4414 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4417 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4418 MVT VT, const SDValue *Ops,
4420 SDVTList VTs = getVTList(VT);
4421 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4424 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4425 MVT VT1, MVT VT2, const SDValue *Ops,
4427 SDVTList VTs = getVTList(VT1, VT2);
4428 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4431 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4433 SDVTList VTs = getVTList(VT1, VT2);
4434 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4437 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4438 MVT VT1, MVT VT2, MVT VT3,
4439 const SDValue *Ops, unsigned NumOps) {
4440 SDVTList VTs = getVTList(VT1, VT2, VT3);
4441 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4444 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4447 SDVTList VTs = getVTList(VT1, VT2);
4448 SDValue Ops[] = { Op1 };
4449 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4452 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4454 SDValue Op1, SDValue Op2) {
4455 SDVTList VTs = getVTList(VT1, VT2);
4456 SDValue Ops[] = { Op1, Op2 };
4457 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4460 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4462 SDValue Op1, SDValue Op2,
4464 SDVTList VTs = getVTList(VT1, VT2);
4465 SDValue Ops[] = { Op1, Op2, Op3 };
4466 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4469 /// MorphNodeTo - These *mutate* the specified node to have the specified
4470 /// return type, opcode, and operands.
4472 /// Note that MorphNodeTo returns the resultant node. If there is already a
4473 /// node of the specified opcode and operands, it returns that node instead of
4474 /// the current one.
4476 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4477 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4478 /// node, and because it doesn't require CSE recalculation for any of
4479 /// the node's users.
4481 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4482 SDVTList VTs, const SDValue *Ops,
4484 // If an identical node already exists, use it.
4486 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4487 FoldingSetNodeID ID;
4488 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4489 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4493 if (!RemoveNodeFromCSEMaps(N))
4496 // Start the morphing.
4498 N->ValueList = VTs.VTs;
4499 N->NumValues = VTs.NumVTs;
4501 // Clear the operands list, updating used nodes to remove this from their
4502 // use list. Keep track of any operands that become dead as a result.
4503 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4504 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4506 SDNode *Used = Use.getNode();
4508 if (Used->use_empty())
4509 DeadNodeSet.insert(Used);
4512 // If NumOps is larger than the # of operands we currently have, reallocate
4513 // the operand list.
4514 if (NumOps > N->NumOperands) {
4515 if (N->OperandsNeedDelete)
4516 delete[] N->OperandList;
4518 if (N->isMachineOpcode()) {
4519 // We're creating a final node that will live unmorphed for the
4520 // remainder of the current SelectionDAG iteration, so we can allocate
4521 // the operands directly out of a pool with no recycling metadata.
4522 N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
4523 N->OperandsNeedDelete = false;
4525 N->OperandList = new SDUse[NumOps];
4526 N->OperandsNeedDelete = true;
4530 // Assign the new operands.
4531 N->NumOperands = NumOps;
4532 for (unsigned i = 0, e = NumOps; i != e; ++i) {
4533 N->OperandList[i].setUser(N);
4534 N->OperandList[i].setInitial(Ops[i]);
4537 // Delete any nodes that are still dead after adding the uses for the
4539 SmallVector<SDNode *, 16> DeadNodes;
4540 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4541 E = DeadNodeSet.end(); I != E; ++I)
4542 if ((*I)->use_empty())
4543 DeadNodes.push_back(*I);
4544 RemoveDeadNodes(DeadNodes);
4547 CSEMap.InsertNode(N, IP); // Memoize the new node.
4552 /// getTargetNode - These are used for target selectors to create a new node
4553 /// with specified return type(s), target opcode, and operands.
4555 /// Note that getTargetNode returns the resultant node. If there is already a
4556 /// node of the specified opcode and operands, it returns that node instead of
4557 /// the current one.
4558 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
4559 return getNode(~Opcode, VT).getNode();
4561 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT) {
4562 return getNode(~Opcode, dl, VT).getNode();
4565 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
4566 return getNode(~Opcode, VT, Op1).getNode();
4568 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4570 return getNode(~Opcode, dl, VT, Op1).getNode();
4573 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4574 SDValue Op1, SDValue Op2) {
4575 return getNode(~Opcode, VT, Op1, Op2).getNode();
4577 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4578 SDValue Op1, SDValue Op2) {
4579 return getNode(~Opcode, dl, VT, Op1, Op2).getNode();
4582 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4583 SDValue Op1, SDValue Op2,
4585 return getNode(~Opcode, VT, Op1, Op2, Op3).getNode();
4587 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4588 SDValue Op1, SDValue Op2,
4590 return getNode(~Opcode, dl, VT, Op1, Op2, Op3).getNode();
4593 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4594 const SDValue *Ops, unsigned NumOps) {
4595 return getNode(~Opcode, VT, Ops, NumOps).getNode();
4597 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4598 const SDValue *Ops, unsigned NumOps) {
4599 return getNode(~Opcode, dl, VT, Ops, NumOps).getNode();
4602 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
4603 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4605 return getNode(~Opcode, VTs, 2, &Op, 0).getNode();
4607 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4609 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4611 return getNode(~Opcode, dl, VTs, 2, &Op, 0).getNode();
4614 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4615 MVT VT2, SDValue Op1) {
4616 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4617 return getNode(~Opcode, VTs, 2, &Op1, 1).getNode();
4619 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4620 MVT VT2, SDValue Op1) {
4621 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4622 return getNode(~Opcode, dl, VTs, 2, &Op1, 1).getNode();
4625 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4626 MVT VT2, SDValue Op1,
4628 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4629 SDValue Ops[] = { Op1, Op2 };
4630 return getNode(~Opcode, VTs, 2, Ops, 2).getNode();
4632 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4633 MVT VT2, SDValue Op1,
4635 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4636 SDValue Ops[] = { Op1, Op2 };
4637 return getNode(~Opcode, dl, VTs, 2, Ops, 2).getNode();
4640 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4641 MVT VT2, SDValue Op1,
4642 SDValue Op2, SDValue Op3) {
4643 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4644 SDValue Ops[] = { Op1, Op2, Op3 };
4645 return getNode(~Opcode, VTs, 2, Ops, 3).getNode();
4647 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4648 MVT VT2, SDValue Op1,
4649 SDValue Op2, SDValue Op3) {
4650 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4651 SDValue Ops[] = { Op1, Op2, Op3 };
4652 return getNode(~Opcode, dl, VTs, 2, Ops, 3).getNode();
4655 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
4656 const SDValue *Ops, unsigned NumOps) {
4657 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4658 return getNode(~Opcode, VTs, 2, Ops, NumOps).getNode();
4660 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4662 const SDValue *Ops, unsigned NumOps) {
4663 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4664 return getNode(~Opcode, dl, VTs, 2, Ops, NumOps).getNode();
4667 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4668 SDValue Op1, SDValue Op2) {
4669 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4670 SDValue Ops[] = { Op1, Op2 };
4671 return getNode(~Opcode, VTs, 3, Ops, 2).getNode();
4673 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4674 MVT VT1, MVT VT2, MVT VT3,
4675 SDValue Op1, SDValue Op2) {
4676 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4677 SDValue Ops[] = { Op1, Op2 };
4678 return getNode(~Opcode, dl, VTs, 3, Ops, 2).getNode();
4681 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4682 SDValue Op1, SDValue Op2,
4684 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4685 SDValue Ops[] = { Op1, Op2, Op3 };
4686 return getNode(~Opcode, VTs, 3, Ops, 3).getNode();
4688 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4689 MVT VT1, MVT VT2, MVT VT3,
4690 SDValue Op1, SDValue Op2,
4692 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4693 SDValue Ops[] = { Op1, Op2, Op3 };
4694 return getNode(~Opcode, dl, VTs, 3, Ops, 3).getNode();
4697 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4698 const SDValue *Ops, unsigned NumOps) {
4699 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4700 return getNode(~Opcode, VTs, 3, Ops, NumOps).getNode();
4702 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4703 MVT VT1, MVT VT2, MVT VT3,
4704 const SDValue *Ops, unsigned NumOps) {
4705 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4706 return getNode(~Opcode, dl, VTs, 3, Ops, NumOps).getNode();
4709 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4710 MVT VT2, MVT VT3, MVT VT4,
4711 const SDValue *Ops, unsigned NumOps) {
4712 std::vector<MVT> VTList;
4713 VTList.push_back(VT1);
4714 VTList.push_back(VT2);
4715 VTList.push_back(VT3);
4716 VTList.push_back(VT4);
4717 const MVT *VTs = getNodeValueTypes(VTList);
4718 return getNode(~Opcode, VTs, 4, Ops, NumOps).getNode();
4720 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4721 MVT VT2, MVT VT3, MVT VT4,
4722 const SDValue *Ops, unsigned NumOps) {
4723 std::vector<MVT> VTList;
4724 VTList.push_back(VT1);
4725 VTList.push_back(VT2);
4726 VTList.push_back(VT3);
4727 VTList.push_back(VT4);
4728 const MVT *VTs = getNodeValueTypes(VTList);
4729 return getNode(~Opcode, dl, VTs, 4, Ops, NumOps).getNode();
4732 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
4733 const std::vector<MVT> &ResultTys,
4734 const SDValue *Ops, unsigned NumOps) {
4735 const MVT *VTs = getNodeValueTypes(ResultTys);
4736 return getNode(~Opcode, VTs, ResultTys.size(),
4737 Ops, NumOps).getNode();
4739 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4740 const std::vector<MVT> &ResultTys,
4741 const SDValue *Ops, unsigned NumOps) {
4742 const MVT *VTs = getNodeValueTypes(ResultTys);
4743 return getNode(~Opcode, dl, VTs, ResultTys.size(),
4744 Ops, NumOps).getNode();
4747 /// getNodeIfExists - Get the specified node if it's already available, or
4748 /// else return NULL.
4749 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4750 const SDValue *Ops, unsigned NumOps) {
4751 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4752 FoldingSetNodeID ID;
4753 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4755 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4761 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4762 /// This can cause recursive merging of nodes in the DAG.
4764 /// This version assumes From has a single result value.
4766 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4767 DAGUpdateListener *UpdateListener) {
4768 SDNode *From = FromN.getNode();
4769 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4770 "Cannot replace with this method!");
4771 assert(From != To.getNode() && "Cannot replace uses of with self");
4773 // Iterate over all the existing uses of From. New uses will be added
4774 // to the beginning of the use list, which we avoid visiting.
4775 // This specifically avoids visiting uses of From that arise while the
4776 // replacement is happening, because any such uses would be the result
4777 // of CSE: If an existing node looks like From after one of its operands
4778 // is replaced by To, we don't want to replace of all its users with To
4779 // too. See PR3018 for more info.
4780 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4784 // This node is about to morph, remove its old self from the CSE maps.
4785 RemoveNodeFromCSEMaps(User);
4787 // A user can appear in a use list multiple times, and when this
4788 // happens the uses are usually next to each other in the list.
4789 // To help reduce the number of CSE recomputations, process all
4790 // the uses of this user that we can find this way.
4792 SDUse &Use = UI.getUse();
4795 } while (UI != UE && *UI == User);
4797 // Now that we have modified User, add it back to the CSE maps. If it
4798 // already exists there, recursively merge the results together.
4799 AddModifiedNodeToCSEMaps(User, UpdateListener);
4803 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4804 /// This can cause recursive merging of nodes in the DAG.
4806 /// This version assumes From/To have matching types and numbers of result
4809 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4810 DAGUpdateListener *UpdateListener) {
4811 assert(From->getVTList().VTs == To->getVTList().VTs &&
4812 From->getNumValues() == To->getNumValues() &&
4813 "Cannot use this version of ReplaceAllUsesWith!");
4815 // Handle the trivial case.
4819 // Iterate over just the existing users of From. See the comments in
4820 // the ReplaceAllUsesWith above.
4821 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4825 // This node is about to morph, remove its old self from the CSE maps.
4826 RemoveNodeFromCSEMaps(User);
4828 // A user can appear in a use list multiple times, and when this
4829 // happens the uses are usually next to each other in the list.
4830 // To help reduce the number of CSE recomputations, process all
4831 // the uses of this user that we can find this way.
4833 SDUse &Use = UI.getUse();
4836 } while (UI != UE && *UI == User);
4838 // Now that we have modified User, add it back to the CSE maps. If it
4839 // already exists there, recursively merge the results together.
4840 AddModifiedNodeToCSEMaps(User, UpdateListener);
4844 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4845 /// This can cause recursive merging of nodes in the DAG.
4847 /// This version can replace From with any result values. To must match the
4848 /// number and types of values returned by From.
4849 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4851 DAGUpdateListener *UpdateListener) {
4852 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4853 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4855 // Iterate over just the existing users of From. See the comments in
4856 // the ReplaceAllUsesWith above.
4857 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4861 // This node is about to morph, remove its old self from the CSE maps.
4862 RemoveNodeFromCSEMaps(User);
4864 // A user can appear in a use list multiple times, and when this
4865 // happens the uses are usually next to each other in the list.
4866 // To help reduce the number of CSE recomputations, process all
4867 // the uses of this user that we can find this way.
4869 SDUse &Use = UI.getUse();
4870 const SDValue &ToOp = To[Use.getResNo()];
4873 } while (UI != UE && *UI == User);
4875 // Now that we have modified User, add it back to the CSE maps. If it
4876 // already exists there, recursively merge the results together.
4877 AddModifiedNodeToCSEMaps(User, UpdateListener);
4881 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4882 /// uses of other values produced by From.getNode() alone. The Deleted
4883 /// vector is handled the same way as for ReplaceAllUsesWith.
4884 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4885 DAGUpdateListener *UpdateListener){
4886 // Handle the really simple, really trivial case efficiently.
4887 if (From == To) return;
4889 // Handle the simple, trivial, case efficiently.
4890 if (From.getNode()->getNumValues() == 1) {
4891 ReplaceAllUsesWith(From, To, UpdateListener);
4895 // Iterate over just the existing users of From. See the comments in
4896 // the ReplaceAllUsesWith above.
4897 SDNode::use_iterator UI = From.getNode()->use_begin(),
4898 UE = From.getNode()->use_end();
4901 bool UserRemovedFromCSEMaps = false;
4903 // A user can appear in a use list multiple times, and when this
4904 // happens the uses are usually next to each other in the list.
4905 // To help reduce the number of CSE recomputations, process all
4906 // the uses of this user that we can find this way.
4908 SDUse &Use = UI.getUse();
4910 // Skip uses of different values from the same node.
4911 if (Use.getResNo() != From.getResNo()) {
4916 // If this node hasn't been modified yet, it's still in the CSE maps,
4917 // so remove its old self from the CSE maps.
4918 if (!UserRemovedFromCSEMaps) {
4919 RemoveNodeFromCSEMaps(User);
4920 UserRemovedFromCSEMaps = true;
4925 } while (UI != UE && *UI == User);
4927 // We are iterating over all uses of the From node, so if a use
4928 // doesn't use the specific value, no changes are made.
4929 if (!UserRemovedFromCSEMaps)
4932 // Now that we have modified User, add it back to the CSE maps. If it
4933 // already exists there, recursively merge the results together.
4934 AddModifiedNodeToCSEMaps(User, UpdateListener);
4939 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
4940 /// to record information about a use.
4947 /// operator< - Sort Memos by User.
4948 bool operator<(const UseMemo &L, const UseMemo &R) {
4949 return (intptr_t)L.User < (intptr_t)R.User;
4953 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
4954 /// uses of other values produced by From.getNode() alone. The same value
4955 /// may appear in both the From and To list. The Deleted vector is
4956 /// handled the same way as for ReplaceAllUsesWith.
4957 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
4960 DAGUpdateListener *UpdateListener){
4961 // Handle the simple, trivial case efficiently.
4963 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
4965 // Read up all the uses and make records of them. This helps
4966 // processing new uses that are introduced during the
4967 // replacement process.
4968 SmallVector<UseMemo, 4> Uses;
4969 for (unsigned i = 0; i != Num; ++i) {
4970 unsigned FromResNo = From[i].getResNo();
4971 SDNode *FromNode = From[i].getNode();
4972 for (SDNode::use_iterator UI = FromNode->use_begin(),
4973 E = FromNode->use_end(); UI != E; ++UI) {
4974 SDUse &Use = UI.getUse();
4975 if (Use.getResNo() == FromResNo) {
4976 UseMemo Memo = { *UI, i, &Use };
4977 Uses.push_back(Memo);
4982 // Sort the uses, so that all the uses from a given User are together.
4983 std::sort(Uses.begin(), Uses.end());
4985 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
4986 UseIndex != UseIndexEnd; ) {
4987 // We know that this user uses some value of From. If it is the right
4988 // value, update it.
4989 SDNode *User = Uses[UseIndex].User;
4991 // This node is about to morph, remove its old self from the CSE maps.
4992 RemoveNodeFromCSEMaps(User);
4994 // The Uses array is sorted, so all the uses for a given User
4995 // are next to each other in the list.
4996 // To help reduce the number of CSE recomputations, process all
4997 // the uses of this user that we can find this way.
4999 unsigned i = Uses[UseIndex].Index;
5000 SDUse &Use = *Uses[UseIndex].Use;
5004 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5006 // Now that we have modified User, add it back to the CSE maps. If it
5007 // already exists there, recursively merge the results together.
5008 AddModifiedNodeToCSEMaps(User, UpdateListener);
5012 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5013 /// based on their topological order. It returns the maximum id and a vector
5014 /// of the SDNodes* in assigned order by reference.
5015 unsigned SelectionDAG::AssignTopologicalOrder() {
5017 unsigned DAGSize = 0;
5019 // SortedPos tracks the progress of the algorithm. Nodes before it are
5020 // sorted, nodes after it are unsorted. When the algorithm completes
5021 // it is at the end of the list.
5022 allnodes_iterator SortedPos = allnodes_begin();
5024 // Visit all the nodes. Move nodes with no operands to the front of
5025 // the list immediately. Annotate nodes that do have operands with their
5026 // operand count. Before we do this, the Node Id fields of the nodes
5027 // may contain arbitrary values. After, the Node Id fields for nodes
5028 // before SortedPos will contain the topological sort index, and the
5029 // Node Id fields for nodes At SortedPos and after will contain the
5030 // count of outstanding operands.
5031 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5033 unsigned Degree = N->getNumOperands();
5035 // A node with no uses, add it to the result array immediately.
5036 N->setNodeId(DAGSize++);
5037 allnodes_iterator Q = N;
5039 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5042 // Temporarily use the Node Id as scratch space for the degree count.
5043 N->setNodeId(Degree);
5047 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5048 // such that by the time the end is reached all nodes will be sorted.
5049 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5051 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5054 unsigned Degree = P->getNodeId();
5057 // All of P's operands are sorted, so P may sorted now.
5058 P->setNodeId(DAGSize++);
5060 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5063 // Update P's outstanding operand count.
5064 P->setNodeId(Degree);
5069 assert(SortedPos == AllNodes.end() &&
5070 "Topological sort incomplete!");
5071 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5072 "First node in topological sort is not the entry token!");
5073 assert(AllNodes.front().getNodeId() == 0 &&
5074 "First node in topological sort has non-zero id!");
5075 assert(AllNodes.front().getNumOperands() == 0 &&
5076 "First node in topological sort has operands!");
5077 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5078 "Last node in topologic sort has unexpected id!");
5079 assert(AllNodes.back().use_empty() &&
5080 "Last node in topologic sort has users!");
5081 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5087 //===----------------------------------------------------------------------===//
5089 //===----------------------------------------------------------------------===//
5091 HandleSDNode::~HandleSDNode() {
5095 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
5097 : SDNode(isa<GlobalVariable>(GA) &&
5098 cast<GlobalVariable>(GA)->isThreadLocal() ?
5100 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
5102 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
5103 getSDVTList(VT)), Offset(o) {
5104 TheGlobal = const_cast<GlobalValue*>(GA);
5107 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
5108 const Value *srcValue, int SVO,
5109 unsigned alignment, bool vol)
5110 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
5111 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
5112 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5113 assert(getAlignment() == alignment && "Alignment representation error!");
5114 assert(isVolatile() == vol && "Volatile representation error!");
5117 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, const SDValue *Ops,
5118 unsigned NumOps, MVT memvt, const Value *srcValue,
5119 int SVO, unsigned alignment, bool vol)
5120 : SDNode(Opc, VTs, Ops, NumOps),
5121 MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
5122 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
5123 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5124 assert(getAlignment() == alignment && "Alignment representation error!");
5125 assert(isVolatile() == vol && "Volatile representation error!");
5128 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, MVT memvt,
5129 const Value *srcValue, int SVO,
5130 unsigned alignment, bool vol)
5131 : SDNode(Opc, dl, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
5132 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
5133 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5134 assert(getAlignment() == alignment && "Alignment representation error!");
5135 assert(isVolatile() == vol && "Volatile representation error!");
5138 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5140 unsigned NumOps, MVT memvt, const Value *srcValue,
5141 int SVO, unsigned alignment, bool vol)
5142 : SDNode(Opc, dl, VTs, Ops, NumOps),
5143 MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
5144 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
5145 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5146 assert(getAlignment() == alignment && "Alignment representation error!");
5147 assert(isVolatile() == vol && "Volatile representation error!");
5150 /// getMemOperand - Return a MachineMemOperand object describing the memory
5151 /// reference performed by this memory reference.
5152 MachineMemOperand MemSDNode::getMemOperand() const {
5154 if (isa<LoadSDNode>(this))
5155 Flags = MachineMemOperand::MOLoad;
5156 else if (isa<StoreSDNode>(this))
5157 Flags = MachineMemOperand::MOStore;
5158 else if (isa<AtomicSDNode>(this)) {
5159 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
5162 const MemIntrinsicSDNode* MemIntrinNode = dyn_cast<MemIntrinsicSDNode>(this);
5163 assert(MemIntrinNode && "Unknown MemSDNode opcode!");
5164 if (MemIntrinNode->readMem()) Flags |= MachineMemOperand::MOLoad;
5165 if (MemIntrinNode->writeMem()) Flags |= MachineMemOperand::MOStore;
5168 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
5169 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
5171 // Check if the memory reference references a frame index
5172 const FrameIndexSDNode *FI =
5173 dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
5174 if (!getSrcValue() && FI)
5175 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
5176 Flags, 0, Size, getAlignment());
5178 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
5179 Size, getAlignment());
5182 /// Profile - Gather unique data for the node.
5184 void SDNode::Profile(FoldingSetNodeID &ID) const {
5185 AddNodeIDNode(ID, this);
5188 /// getValueTypeList - Return a pointer to the specified value type.
5190 const MVT *SDNode::getValueTypeList(MVT VT) {
5191 if (VT.isExtended()) {
5192 static std::set<MVT, MVT::compareRawBits> EVTs;
5193 return &(*EVTs.insert(VT).first);
5195 static MVT VTs[MVT::LAST_VALUETYPE];
5196 VTs[VT.getSimpleVT()] = VT;
5197 return &VTs[VT.getSimpleVT()];
5201 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5202 /// indicated value. This method ignores uses of other values defined by this
5204 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5205 assert(Value < getNumValues() && "Bad value!");
5207 // TODO: Only iterate over uses of a given value of the node
5208 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5209 if (UI.getUse().getResNo() == Value) {
5216 // Found exactly the right number of uses?
5221 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5222 /// value. This method ignores uses of other values defined by this operation.
5223 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5224 assert(Value < getNumValues() && "Bad value!");
5226 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5227 if (UI.getUse().getResNo() == Value)
5234 /// isOnlyUserOf - Return true if this node is the only use of N.
5236 bool SDNode::isOnlyUserOf(SDNode *N) const {
5238 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5249 /// isOperand - Return true if this node is an operand of N.
5251 bool SDValue::isOperandOf(SDNode *N) const {
5252 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5253 if (*this == N->getOperand(i))
5258 bool SDNode::isOperandOf(SDNode *N) const {
5259 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5260 if (this == N->OperandList[i].getNode())
5265 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5266 /// be a chain) reaches the specified operand without crossing any
5267 /// side-effecting instructions. In practice, this looks through token
5268 /// factors and non-volatile loads. In order to remain efficient, this only
5269 /// looks a couple of nodes in, it does not do an exhaustive search.
5270 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5271 unsigned Depth) const {
5272 if (*this == Dest) return true;
5274 // Don't search too deeply, we just want to be able to see through
5275 // TokenFactor's etc.
5276 if (Depth == 0) return false;
5278 // If this is a token factor, all inputs to the TF happen in parallel. If any
5279 // of the operands of the TF reach dest, then we can do the xform.
5280 if (getOpcode() == ISD::TokenFactor) {
5281 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5282 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5287 // Loads don't have side effects, look through them.
5288 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5289 if (!Ld->isVolatile())
5290 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5296 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
5297 SmallPtrSet<SDNode *, 32> &Visited) {
5298 if (found || !Visited.insert(N))
5301 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
5302 SDNode *Op = N->getOperand(i).getNode();
5307 findPredecessor(Op, P, found, Visited);
5311 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5312 /// is either an operand of N or it can be reached by recursively traversing
5313 /// up the operands.
5314 /// NOTE: this is an expensive method. Use it carefully.
5315 bool SDNode::isPredecessorOf(SDNode *N) const {
5316 SmallPtrSet<SDNode *, 32> Visited;
5318 findPredecessor(N, this, found, Visited);
5322 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5323 assert(Num < NumOperands && "Invalid child # of SDNode!");
5324 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5327 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5328 switch (getOpcode()) {
5330 if (getOpcode() < ISD::BUILTIN_OP_END)
5331 return "<<Unknown DAG Node>>";
5332 if (isMachineOpcode()) {
5334 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5335 if (getMachineOpcode() < TII->getNumOpcodes())
5336 return TII->get(getMachineOpcode()).getName();
5337 return "<<Unknown Machine Node>>";
5340 const TargetLowering &TLI = G->getTargetLoweringInfo();
5341 const char *Name = TLI.getTargetNodeName(getOpcode());
5342 if (Name) return Name;
5343 return "<<Unknown Target Node>>";
5345 return "<<Unknown Node>>";
5348 case ISD::DELETED_NODE:
5349 return "<<Deleted Node!>>";
5351 case ISD::PREFETCH: return "Prefetch";
5352 case ISD::MEMBARRIER: return "MemBarrier";
5353 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5354 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5355 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5356 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5357 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5358 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5359 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5360 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5361 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5362 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5363 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5364 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5365 case ISD::PCMARKER: return "PCMarker";
5366 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5367 case ISD::SRCVALUE: return "SrcValue";
5368 case ISD::MEMOPERAND: return "MemOperand";
5369 case ISD::EntryToken: return "EntryToken";
5370 case ISD::TokenFactor: return "TokenFactor";
5371 case ISD::AssertSext: return "AssertSext";
5372 case ISD::AssertZext: return "AssertZext";
5374 case ISD::BasicBlock: return "BasicBlock";
5375 case ISD::ARG_FLAGS: return "ArgFlags";
5376 case ISD::VALUETYPE: return "ValueType";
5377 case ISD::Register: return "Register";
5379 case ISD::Constant: return "Constant";
5380 case ISD::ConstantFP: return "ConstantFP";
5381 case ISD::GlobalAddress: return "GlobalAddress";
5382 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5383 case ISD::FrameIndex: return "FrameIndex";
5384 case ISD::JumpTable: return "JumpTable";
5385 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5386 case ISD::RETURNADDR: return "RETURNADDR";
5387 case ISD::FRAMEADDR: return "FRAMEADDR";
5388 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5389 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5390 case ISD::EHSELECTION: return "EHSELECTION";
5391 case ISD::EH_RETURN: return "EH_RETURN";
5392 case ISD::ConstantPool: return "ConstantPool";
5393 case ISD::ExternalSymbol: return "ExternalSymbol";
5394 case ISD::INTRINSIC_WO_CHAIN: {
5395 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
5396 return Intrinsic::getName((Intrinsic::ID)IID);
5398 case ISD::INTRINSIC_VOID:
5399 case ISD::INTRINSIC_W_CHAIN: {
5400 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
5401 return Intrinsic::getName((Intrinsic::ID)IID);
5404 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5405 case ISD::TargetConstant: return "TargetConstant";
5406 case ISD::TargetConstantFP:return "TargetConstantFP";
5407 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5408 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5409 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5410 case ISD::TargetJumpTable: return "TargetJumpTable";
5411 case ISD::TargetConstantPool: return "TargetConstantPool";
5412 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5414 case ISD::CopyToReg: return "CopyToReg";
5415 case ISD::CopyFromReg: return "CopyFromReg";
5416 case ISD::UNDEF: return "undef";
5417 case ISD::MERGE_VALUES: return "merge_values";
5418 case ISD::INLINEASM: return "inlineasm";
5419 case ISD::DBG_LABEL: return "dbg_label";
5420 case ISD::EH_LABEL: return "eh_label";
5421 case ISD::DECLARE: return "declare";
5422 case ISD::HANDLENODE: return "handlenode";
5423 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
5424 case ISD::CALL: return "call";
5427 case ISD::FABS: return "fabs";
5428 case ISD::FNEG: return "fneg";
5429 case ISD::FSQRT: return "fsqrt";
5430 case ISD::FSIN: return "fsin";
5431 case ISD::FCOS: return "fcos";
5432 case ISD::FPOWI: return "fpowi";
5433 case ISD::FPOW: return "fpow";
5434 case ISD::FTRUNC: return "ftrunc";
5435 case ISD::FFLOOR: return "ffloor";
5436 case ISD::FCEIL: return "fceil";
5437 case ISD::FRINT: return "frint";
5438 case ISD::FNEARBYINT: return "fnearbyint";
5441 case ISD::ADD: return "add";
5442 case ISD::SUB: return "sub";
5443 case ISD::MUL: return "mul";
5444 case ISD::MULHU: return "mulhu";
5445 case ISD::MULHS: return "mulhs";
5446 case ISD::SDIV: return "sdiv";
5447 case ISD::UDIV: return "udiv";
5448 case ISD::SREM: return "srem";
5449 case ISD::UREM: return "urem";
5450 case ISD::SMUL_LOHI: return "smul_lohi";
5451 case ISD::UMUL_LOHI: return "umul_lohi";
5452 case ISD::SDIVREM: return "sdivrem";
5453 case ISD::UDIVREM: return "udivrem";
5454 case ISD::AND: return "and";
5455 case ISD::OR: return "or";
5456 case ISD::XOR: return "xor";
5457 case ISD::SHL: return "shl";
5458 case ISD::SRA: return "sra";
5459 case ISD::SRL: return "srl";
5460 case ISD::ROTL: return "rotl";
5461 case ISD::ROTR: return "rotr";
5462 case ISD::FADD: return "fadd";
5463 case ISD::FSUB: return "fsub";
5464 case ISD::FMUL: return "fmul";
5465 case ISD::FDIV: return "fdiv";
5466 case ISD::FREM: return "frem";
5467 case ISD::FCOPYSIGN: return "fcopysign";
5468 case ISD::FGETSIGN: return "fgetsign";
5470 case ISD::SETCC: return "setcc";
5471 case ISD::VSETCC: return "vsetcc";
5472 case ISD::SELECT: return "select";
5473 case ISD::SELECT_CC: return "select_cc";
5474 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5475 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5476 case ISD::CONCAT_VECTORS: return "concat_vectors";
5477 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5478 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5479 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5480 case ISD::CARRY_FALSE: return "carry_false";
5481 case ISD::ADDC: return "addc";
5482 case ISD::ADDE: return "adde";
5483 case ISD::SADDO: return "saddo";
5484 case ISD::UADDO: return "uaddo";
5485 case ISD::SSUBO: return "ssubo";
5486 case ISD::USUBO: return "usubo";
5487 case ISD::SMULO: return "smulo";
5488 case ISD::UMULO: return "umulo";
5489 case ISD::SUBC: return "subc";
5490 case ISD::SUBE: return "sube";
5491 case ISD::SHL_PARTS: return "shl_parts";
5492 case ISD::SRA_PARTS: return "sra_parts";
5493 case ISD::SRL_PARTS: return "srl_parts";
5495 case ISD::EXTRACT_SUBREG: return "extract_subreg";
5496 case ISD::INSERT_SUBREG: return "insert_subreg";
5498 // Conversion operators.
5499 case ISD::SIGN_EXTEND: return "sign_extend";
5500 case ISD::ZERO_EXTEND: return "zero_extend";
5501 case ISD::ANY_EXTEND: return "any_extend";
5502 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5503 case ISD::TRUNCATE: return "truncate";
5504 case ISD::FP_ROUND: return "fp_round";
5505 case ISD::FLT_ROUNDS_: return "flt_rounds";
5506 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5507 case ISD::FP_EXTEND: return "fp_extend";
5509 case ISD::SINT_TO_FP: return "sint_to_fp";
5510 case ISD::UINT_TO_FP: return "uint_to_fp";
5511 case ISD::FP_TO_SINT: return "fp_to_sint";
5512 case ISD::FP_TO_UINT: return "fp_to_uint";
5513 case ISD::BIT_CONVERT: return "bit_convert";
5515 case ISD::CONVERT_RNDSAT: {
5516 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5517 default: assert(0 && "Unknown cvt code!");
5518 case ISD::CVT_FF: return "cvt_ff";
5519 case ISD::CVT_FS: return "cvt_fs";
5520 case ISD::CVT_FU: return "cvt_fu";
5521 case ISD::CVT_SF: return "cvt_sf";
5522 case ISD::CVT_UF: return "cvt_uf";
5523 case ISD::CVT_SS: return "cvt_ss";
5524 case ISD::CVT_SU: return "cvt_su";
5525 case ISD::CVT_US: return "cvt_us";
5526 case ISD::CVT_UU: return "cvt_uu";
5530 // Control flow instructions
5531 case ISD::BR: return "br";
5532 case ISD::BRIND: return "brind";
5533 case ISD::BR_JT: return "br_jt";
5534 case ISD::BRCOND: return "brcond";
5535 case ISD::BR_CC: return "br_cc";
5536 case ISD::RET: return "ret";
5537 case ISD::CALLSEQ_START: return "callseq_start";
5538 case ISD::CALLSEQ_END: return "callseq_end";
5541 case ISD::LOAD: return "load";
5542 case ISD::STORE: return "store";
5543 case ISD::VAARG: return "vaarg";
5544 case ISD::VACOPY: return "vacopy";
5545 case ISD::VAEND: return "vaend";
5546 case ISD::VASTART: return "vastart";
5547 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5548 case ISD::EXTRACT_ELEMENT: return "extract_element";
5549 case ISD::BUILD_PAIR: return "build_pair";
5550 case ISD::STACKSAVE: return "stacksave";
5551 case ISD::STACKRESTORE: return "stackrestore";
5552 case ISD::TRAP: return "trap";
5555 case ISD::BSWAP: return "bswap";
5556 case ISD::CTPOP: return "ctpop";
5557 case ISD::CTTZ: return "cttz";
5558 case ISD::CTLZ: return "ctlz";
5561 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
5562 case ISD::DEBUG_LOC: return "debug_loc";
5565 case ISD::TRAMPOLINE: return "trampoline";
5568 switch (cast<CondCodeSDNode>(this)->get()) {
5569 default: assert(0 && "Unknown setcc condition!");
5570 case ISD::SETOEQ: return "setoeq";
5571 case ISD::SETOGT: return "setogt";
5572 case ISD::SETOGE: return "setoge";
5573 case ISD::SETOLT: return "setolt";
5574 case ISD::SETOLE: return "setole";
5575 case ISD::SETONE: return "setone";
5577 case ISD::SETO: return "seto";
5578 case ISD::SETUO: return "setuo";
5579 case ISD::SETUEQ: return "setue";
5580 case ISD::SETUGT: return "setugt";
5581 case ISD::SETUGE: return "setuge";
5582 case ISD::SETULT: return "setult";
5583 case ISD::SETULE: return "setule";
5584 case ISD::SETUNE: return "setune";
5586 case ISD::SETEQ: return "seteq";
5587 case ISD::SETGT: return "setgt";
5588 case ISD::SETGE: return "setge";
5589 case ISD::SETLT: return "setlt";
5590 case ISD::SETLE: return "setle";
5591 case ISD::SETNE: return "setne";
5596 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5605 return "<post-inc>";
5607 return "<post-dec>";
5611 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5612 std::string S = "< ";
5626 if (getByValAlign())
5627 S += "byval-align:" + utostr(getByValAlign()) + " ";
5629 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5631 S += "byval-size:" + utostr(getByValSize()) + " ";
5635 void SDNode::dump() const { dump(0); }
5636 void SDNode::dump(const SelectionDAG *G) const {
5641 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5642 OS << (void*)this << ": ";
5644 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5646 if (getValueType(i) == MVT::Other)
5649 OS << getValueType(i).getMVTString();
5651 OS << " = " << getOperationName(G);
5654 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5656 OS << (void*)getOperand(i).getNode();
5657 if (unsigned RN = getOperand(i).getResNo())
5661 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
5662 SDNode *Mask = getOperand(2).getNode();
5664 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
5666 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
5669 OS << cast<ConstantSDNode>(Mask->getOperand(i))->getZExtValue();
5674 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5675 OS << '<' << CSDN->getAPIntValue() << '>';
5676 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5677 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5678 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5679 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5680 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5683 CSDN->getValueAPF().bitcastToAPInt().dump();
5686 } else if (const GlobalAddressSDNode *GADN =
5687 dyn_cast<GlobalAddressSDNode>(this)) {
5688 int64_t offset = GADN->getOffset();
5690 WriteAsOperand(OS, GADN->getGlobal());
5693 OS << " + " << offset;
5695 OS << " " << offset;
5696 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5697 OS << "<" << FIDN->getIndex() << ">";
5698 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5699 OS << "<" << JTDN->getIndex() << ">";
5700 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5701 int offset = CP->getOffset();
5702 if (CP->isMachineConstantPoolEntry())
5703 OS << "<" << *CP->getMachineCPVal() << ">";
5705 OS << "<" << *CP->getConstVal() << ">";
5707 OS << " + " << offset;
5709 OS << " " << offset;
5710 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5712 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5714 OS << LBB->getName() << " ";
5715 OS << (const void*)BBDN->getBasicBlock() << ">";
5716 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5717 if (G && R->getReg() &&
5718 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5719 OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5721 OS << " #" << R->getReg();
5723 } else if (const ExternalSymbolSDNode *ES =
5724 dyn_cast<ExternalSymbolSDNode>(this)) {
5725 OS << "'" << ES->getSymbol() << "'";
5726 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5728 OS << "<" << M->getValue() << ">";
5731 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5732 if (M->MO.getValue())
5733 OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5735 OS << "<null:" << M->MO.getOffset() << ">";
5736 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5737 OS << N->getArgFlags().getArgFlagsString();
5738 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5739 OS << ":" << N->getVT().getMVTString();
5741 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5742 const Value *SrcValue = LD->getSrcValue();
5743 int SrcOffset = LD->getSrcValueOffset();
5749 OS << ":" << SrcOffset << ">";
5752 switch (LD->getExtensionType()) {
5753 default: doExt = false; break;
5754 case ISD::EXTLOAD: OS << " <anyext "; break;
5755 case ISD::SEXTLOAD: OS << " <sext "; break;
5756 case ISD::ZEXTLOAD: OS << " <zext "; break;
5759 OS << LD->getMemoryVT().getMVTString() << ">";
5761 const char *AM = getIndexedModeName(LD->getAddressingMode());
5764 if (LD->isVolatile())
5765 OS << " <volatile>";
5766 OS << " alignment=" << LD->getAlignment();
5767 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5768 const Value *SrcValue = ST->getSrcValue();
5769 int SrcOffset = ST->getSrcValueOffset();
5775 OS << ":" << SrcOffset << ">";
5777 if (ST->isTruncatingStore())
5778 OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
5780 const char *AM = getIndexedModeName(ST->getAddressingMode());
5783 if (ST->isVolatile())
5784 OS << " <volatile>";
5785 OS << " alignment=" << ST->getAlignment();
5786 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5787 const Value *SrcValue = AT->getSrcValue();
5788 int SrcOffset = AT->getSrcValueOffset();
5794 OS << ":" << SrcOffset << ">";
5795 if (AT->isVolatile())
5796 OS << " <volatile>";
5797 OS << " alignment=" << AT->getAlignment();
5801 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5802 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5803 if (N->getOperand(i).getNode()->hasOneUse())
5804 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5806 cerr << "\n" << std::string(indent+2, ' ')
5807 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5810 cerr << "\n" << std::string(indent, ' ');
5814 void SelectionDAG::dump() const {
5815 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5817 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5819 const SDNode *N = I;
5820 if (!N->hasOneUse() && N != getRoot().getNode())
5821 DumpNodes(N, 2, this);
5824 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
5829 const Type *ConstantPoolSDNode::getType() const {
5830 if (isMachineConstantPoolEntry())
5831 return Val.MachineCPVal->getType();
5832 return Val.ConstVal->getType();