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),
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);
1072 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1073 FoldingSetNodeID ID;
1074 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1077 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1078 return SDValue(E, 0);
1079 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1080 new (N) BasicBlockSDNode(MBB);
1081 CSEMap.InsertNode(N, IP);
1082 AllNodes.push_back(N);
1083 return SDValue(N, 0);
1086 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB, DebugLoc dl) {
1087 FoldingSetNodeID ID;
1088 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1091 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1092 return SDValue(E, 0);
1093 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1094 new (N) BasicBlockSDNode(MBB, dl);
1095 CSEMap.InsertNode(N, IP);
1096 AllNodes.push_back(N);
1097 return SDValue(N, 0);
1100 SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
1101 FoldingSetNodeID ID;
1102 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
1103 ID.AddInteger(Flags.getRawBits());
1105 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1106 return SDValue(E, 0);
1107 SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
1108 new (N) ARG_FLAGSSDNode(Flags);
1109 CSEMap.InsertNode(N, IP);
1110 AllNodes.push_back(N);
1111 return SDValue(N, 0);
1114 SDValue SelectionDAG::getValueType(MVT VT) {
1115 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1116 ValueTypeNodes.resize(VT.getSimpleVT()+1);
1118 SDNode *&N = VT.isExtended() ?
1119 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1121 if (N) return SDValue(N, 0);
1122 N = NodeAllocator.Allocate<VTSDNode>();
1123 new (N) VTSDNode(VT);
1124 AllNodes.push_back(N);
1125 return SDValue(N, 0);
1128 SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1129 SDNode *&N = ExternalSymbols[Sym];
1130 if (N) return SDValue(N, 0);
1131 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1132 new (N) ExternalSymbolSDNode(false, Sym, VT);
1133 AllNodes.push_back(N);
1134 return SDValue(N, 0);
1137 SDValue SelectionDAG::getExternalSymbol(const char *Sym, DebugLoc dl, MVT VT) {
1138 SDNode *&N = ExternalSymbols[Sym];
1139 if (N) return SDValue(N, 0);
1140 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1141 new (N) ExternalSymbolSDNode(false, dl, Sym, VT);
1142 AllNodes.push_back(N);
1143 return SDValue(N, 0);
1146 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1147 SDNode *&N = TargetExternalSymbols[Sym];
1148 if (N) return SDValue(N, 0);
1149 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1150 new (N) ExternalSymbolSDNode(true, Sym, VT);
1151 AllNodes.push_back(N);
1152 return SDValue(N, 0);
1155 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, DebugLoc dl,
1157 SDNode *&N = TargetExternalSymbols[Sym];
1158 if (N) return SDValue(N, 0);
1159 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1160 new (N) ExternalSymbolSDNode(true, dl, Sym, VT);
1161 AllNodes.push_back(N);
1162 return SDValue(N, 0);
1165 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1166 if ((unsigned)Cond >= CondCodeNodes.size())
1167 CondCodeNodes.resize(Cond+1);
1169 if (CondCodeNodes[Cond] == 0) {
1170 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1171 new (N) CondCodeSDNode(Cond);
1172 CondCodeNodes[Cond] = N;
1173 AllNodes.push_back(N);
1175 return SDValue(CondCodeNodes[Cond], 0);
1178 SDValue SelectionDAG::getConvertRndSat(MVT VT, 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, 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,
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, Root, LabelID);
1232 CSEMap.InsertNode(N, IP);
1233 AllNodes.push_back(N);
1234 return SDValue(N, 0);
1237 SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
1240 FoldingSetNodeID ID;
1241 SDValue Ops[] = { Root };
1242 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1243 ID.AddInteger(LabelID);
1245 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1246 return SDValue(E, 0);
1247 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1248 new (N) LabelSDNode(Opcode, dl, Root, LabelID);
1249 CSEMap.InsertNode(N, IP);
1250 AllNodes.push_back(N);
1251 return SDValue(N, 0);
1254 SDValue SelectionDAG::getSrcValue(const Value *V) {
1255 assert((!V || isa<PointerType>(V->getType())) &&
1256 "SrcValue is not a pointer?");
1258 FoldingSetNodeID ID;
1259 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1263 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1264 return SDValue(E, 0);
1266 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1267 new (N) SrcValueSDNode(V);
1268 CSEMap.InsertNode(N, IP);
1269 AllNodes.push_back(N);
1270 return SDValue(N, 0);
1273 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1275 const Value *v = MO.getValue();
1276 assert((!v || isa<PointerType>(v->getType())) &&
1277 "SrcValue is not a pointer?");
1280 FoldingSetNodeID ID;
1281 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1285 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1286 return SDValue(E, 0);
1288 SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
1289 new (N) MemOperandSDNode(MO);
1290 CSEMap.InsertNode(N, IP);
1291 AllNodes.push_back(N);
1292 return SDValue(N, 0);
1295 /// getShiftAmountOperand - Return the specified value casted to
1296 /// the target's desired shift amount type.
1297 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
1298 MVT OpTy = Op.getValueType();
1299 MVT ShTy = TLI.getShiftAmountTy();
1300 if (OpTy == ShTy || OpTy.isVector()) return Op;
1302 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1303 return getNode(Opcode, ShTy, Op);
1306 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1307 /// specified value type.
1308 SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1309 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1310 unsigned ByteSize = VT.getStoreSizeInBits()/8;
1311 const Type *Ty = VT.getTypeForMVT();
1312 unsigned StackAlign =
1313 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1315 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1316 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1319 /// CreateStackTemporary - Create a stack temporary suitable for holding
1320 /// either of the specified value types.
1321 SDValue SelectionDAG::CreateStackTemporary(MVT VT1, MVT VT2) {
1322 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1323 VT2.getStoreSizeInBits())/8;
1324 const Type *Ty1 = VT1.getTypeForMVT();
1325 const Type *Ty2 = VT2.getTypeForMVT();
1326 const TargetData *TD = TLI.getTargetData();
1327 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1328 TD->getPrefTypeAlignment(Ty2));
1330 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1331 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align);
1332 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1335 SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
1336 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1337 // These setcc operations always fold.
1341 case ISD::SETFALSE2: return getConstant(0, VT);
1343 case ISD::SETTRUE2: return getConstant(1, VT);
1355 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1359 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1360 const APInt &C2 = N2C->getAPIntValue();
1361 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1362 const APInt &C1 = N1C->getAPIntValue();
1365 default: assert(0 && "Unknown integer setcc!");
1366 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1367 case ISD::SETNE: return getConstant(C1 != C2, VT);
1368 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1369 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1370 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1371 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1372 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1373 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1374 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1375 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1379 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1380 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1381 // No compile time operations on this type yet.
1382 if (N1C->getValueType(0) == MVT::ppcf128)
1385 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1388 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1389 return getNode(ISD::UNDEF, dl, VT);
1391 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1392 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1393 return getNode(ISD::UNDEF, dl, VT);
1395 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1396 R==APFloat::cmpLessThan, VT);
1397 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1398 return getNode(ISD::UNDEF, dl, VT);
1400 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1401 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1402 return getNode(ISD::UNDEF, dl, VT);
1404 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1405 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1406 return getNode(ISD::UNDEF, dl, VT);
1408 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1409 R==APFloat::cmpEqual, VT);
1410 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1411 return getNode(ISD::UNDEF, dl, VT);
1413 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1414 R==APFloat::cmpEqual, VT);
1415 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1416 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1417 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1418 R==APFloat::cmpEqual, VT);
1419 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1420 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1421 R==APFloat::cmpLessThan, VT);
1422 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1423 R==APFloat::cmpUnordered, VT);
1424 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1425 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1428 // Ensure that the constant occurs on the RHS.
1429 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1433 // Could not fold it.
1437 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1438 /// use this predicate to simplify operations downstream.
1439 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1440 unsigned BitWidth = Op.getValueSizeInBits();
1441 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1444 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1445 /// this predicate to simplify operations downstream. Mask is known to be zero
1446 /// for bits that V cannot have.
1447 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1448 unsigned Depth) const {
1449 APInt KnownZero, KnownOne;
1450 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1451 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1452 return (KnownZero & Mask) == Mask;
1455 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1456 /// known to be either zero or one and return them in the KnownZero/KnownOne
1457 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1459 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1460 APInt &KnownZero, APInt &KnownOne,
1461 unsigned Depth) const {
1462 unsigned BitWidth = Mask.getBitWidth();
1463 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1464 "Mask size mismatches value type size!");
1466 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1467 if (Depth == 6 || Mask == 0)
1468 return; // Limit search depth.
1470 APInt KnownZero2, KnownOne2;
1472 switch (Op.getOpcode()) {
1474 // We know all of the bits for a constant!
1475 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1476 KnownZero = ~KnownOne & Mask;
1479 // If either the LHS or the RHS are Zero, the result is zero.
1480 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1481 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1482 KnownZero2, KnownOne2, Depth+1);
1483 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1484 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1486 // Output known-1 bits are only known if set in both the LHS & RHS.
1487 KnownOne &= KnownOne2;
1488 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1489 KnownZero |= KnownZero2;
1492 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1493 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1494 KnownZero2, KnownOne2, Depth+1);
1495 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1496 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1498 // Output known-0 bits are only known if clear in both the LHS & RHS.
1499 KnownZero &= KnownZero2;
1500 // Output known-1 are known to be set if set in either the LHS | RHS.
1501 KnownOne |= KnownOne2;
1504 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1505 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1506 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1507 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1509 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1510 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1511 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1512 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1513 KnownZero = KnownZeroOut;
1517 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1518 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1519 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1520 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1521 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1523 // If low bits are zero in either operand, output low known-0 bits.
1524 // Also compute a conserative estimate for high known-0 bits.
1525 // More trickiness is possible, but this is sufficient for the
1526 // interesting case of alignment computation.
1528 unsigned TrailZ = KnownZero.countTrailingOnes() +
1529 KnownZero2.countTrailingOnes();
1530 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1531 KnownZero2.countLeadingOnes(),
1532 BitWidth) - BitWidth;
1534 TrailZ = std::min(TrailZ, BitWidth);
1535 LeadZ = std::min(LeadZ, BitWidth);
1536 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1537 APInt::getHighBitsSet(BitWidth, LeadZ);
1542 // For the purposes of computing leading zeros we can conservatively
1543 // treat a udiv as a logical right shift by the power of 2 known to
1544 // be less than the denominator.
1545 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1546 ComputeMaskedBits(Op.getOperand(0),
1547 AllOnes, KnownZero2, KnownOne2, Depth+1);
1548 unsigned LeadZ = KnownZero2.countLeadingOnes();
1552 ComputeMaskedBits(Op.getOperand(1),
1553 AllOnes, KnownZero2, KnownOne2, Depth+1);
1554 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1555 if (RHSUnknownLeadingOnes != BitWidth)
1556 LeadZ = std::min(BitWidth,
1557 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1559 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1563 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1564 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1565 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1566 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1568 // Only known if known in both the LHS and RHS.
1569 KnownOne &= KnownOne2;
1570 KnownZero &= KnownZero2;
1572 case ISD::SELECT_CC:
1573 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1574 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1575 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1576 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1578 // Only known if known in both the LHS and RHS.
1579 KnownOne &= KnownOne2;
1580 KnownZero &= KnownZero2;
1588 if (Op.getResNo() != 1)
1590 // The boolean result conforms to getBooleanContents. Fall through.
1592 // If we know the result of a setcc has the top bits zero, use this info.
1593 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1595 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1598 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1599 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1600 unsigned ShAmt = SA->getZExtValue();
1602 // If the shift count is an invalid immediate, don't do anything.
1603 if (ShAmt >= BitWidth)
1606 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1607 KnownZero, KnownOne, Depth+1);
1608 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1609 KnownZero <<= ShAmt;
1611 // low bits known zero.
1612 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1616 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1617 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1618 unsigned ShAmt = SA->getZExtValue();
1620 // If the shift count is an invalid immediate, don't do anything.
1621 if (ShAmt >= BitWidth)
1624 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1625 KnownZero, KnownOne, Depth+1);
1626 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1627 KnownZero = KnownZero.lshr(ShAmt);
1628 KnownOne = KnownOne.lshr(ShAmt);
1630 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1631 KnownZero |= HighBits; // High bits known zero.
1635 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1636 unsigned ShAmt = SA->getZExtValue();
1638 // If the shift count is an invalid immediate, don't do anything.
1639 if (ShAmt >= BitWidth)
1642 APInt InDemandedMask = (Mask << ShAmt);
1643 // If any of the demanded bits are produced by the sign extension, we also
1644 // demand the input sign bit.
1645 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1646 if (HighBits.getBoolValue())
1647 InDemandedMask |= APInt::getSignBit(BitWidth);
1649 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1651 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1652 KnownZero = KnownZero.lshr(ShAmt);
1653 KnownOne = KnownOne.lshr(ShAmt);
1655 // Handle the sign bits.
1656 APInt SignBit = APInt::getSignBit(BitWidth);
1657 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1659 if (KnownZero.intersects(SignBit)) {
1660 KnownZero |= HighBits; // New bits are known zero.
1661 } else if (KnownOne.intersects(SignBit)) {
1662 KnownOne |= HighBits; // New bits are known one.
1666 case ISD::SIGN_EXTEND_INREG: {
1667 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1668 unsigned EBits = EVT.getSizeInBits();
1670 // Sign extension. Compute the demanded bits in the result that are not
1671 // present in the input.
1672 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1674 APInt InSignBit = APInt::getSignBit(EBits);
1675 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1677 // If the sign extended bits are demanded, we know that the sign
1679 InSignBit.zext(BitWidth);
1680 if (NewBits.getBoolValue())
1681 InputDemandedBits |= InSignBit;
1683 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1684 KnownZero, KnownOne, Depth+1);
1685 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1687 // If the sign bit of the input is known set or clear, then we know the
1688 // top bits of the result.
1689 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1690 KnownZero |= NewBits;
1691 KnownOne &= ~NewBits;
1692 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1693 KnownOne |= NewBits;
1694 KnownZero &= ~NewBits;
1695 } else { // Input sign bit unknown
1696 KnownZero &= ~NewBits;
1697 KnownOne &= ~NewBits;
1704 unsigned LowBits = Log2_32(BitWidth)+1;
1705 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1710 if (ISD::isZEXTLoad(Op.getNode())) {
1711 LoadSDNode *LD = cast<LoadSDNode>(Op);
1712 MVT VT = LD->getMemoryVT();
1713 unsigned MemBits = VT.getSizeInBits();
1714 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1718 case ISD::ZERO_EXTEND: {
1719 MVT InVT = Op.getOperand(0).getValueType();
1720 unsigned InBits = InVT.getSizeInBits();
1721 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1722 APInt InMask = Mask;
1723 InMask.trunc(InBits);
1724 KnownZero.trunc(InBits);
1725 KnownOne.trunc(InBits);
1726 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1727 KnownZero.zext(BitWidth);
1728 KnownOne.zext(BitWidth);
1729 KnownZero |= NewBits;
1732 case ISD::SIGN_EXTEND: {
1733 MVT InVT = Op.getOperand(0).getValueType();
1734 unsigned InBits = InVT.getSizeInBits();
1735 APInt InSignBit = APInt::getSignBit(InBits);
1736 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1737 APInt InMask = Mask;
1738 InMask.trunc(InBits);
1740 // If any of the sign extended bits are demanded, we know that the sign
1741 // bit is demanded. Temporarily set this bit in the mask for our callee.
1742 if (NewBits.getBoolValue())
1743 InMask |= InSignBit;
1745 KnownZero.trunc(InBits);
1746 KnownOne.trunc(InBits);
1747 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1749 // Note if the sign bit is known to be zero or one.
1750 bool SignBitKnownZero = KnownZero.isNegative();
1751 bool SignBitKnownOne = KnownOne.isNegative();
1752 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1753 "Sign bit can't be known to be both zero and one!");
1755 // If the sign bit wasn't actually demanded by our caller, we don't
1756 // want it set in the KnownZero and KnownOne result values. Reset the
1757 // mask and reapply it to the result values.
1759 InMask.trunc(InBits);
1760 KnownZero &= InMask;
1763 KnownZero.zext(BitWidth);
1764 KnownOne.zext(BitWidth);
1766 // If the sign bit is known zero or one, the top bits match.
1767 if (SignBitKnownZero)
1768 KnownZero |= NewBits;
1769 else if (SignBitKnownOne)
1770 KnownOne |= NewBits;
1773 case ISD::ANY_EXTEND: {
1774 MVT InVT = Op.getOperand(0).getValueType();
1775 unsigned InBits = InVT.getSizeInBits();
1776 APInt InMask = Mask;
1777 InMask.trunc(InBits);
1778 KnownZero.trunc(InBits);
1779 KnownOne.trunc(InBits);
1780 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1781 KnownZero.zext(BitWidth);
1782 KnownOne.zext(BitWidth);
1785 case ISD::TRUNCATE: {
1786 MVT InVT = Op.getOperand(0).getValueType();
1787 unsigned InBits = InVT.getSizeInBits();
1788 APInt InMask = Mask;
1789 InMask.zext(InBits);
1790 KnownZero.zext(InBits);
1791 KnownOne.zext(InBits);
1792 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1793 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1794 KnownZero.trunc(BitWidth);
1795 KnownOne.trunc(BitWidth);
1798 case ISD::AssertZext: {
1799 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1800 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1801 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1803 KnownZero |= (~InMask) & Mask;
1807 // All bits are zero except the low bit.
1808 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1812 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1813 // We know that the top bits of C-X are clear if X contains less bits
1814 // than C (i.e. no wrap-around can happen). For example, 20-X is
1815 // positive if we can prove that X is >= 0 and < 16.
1816 if (CLHS->getAPIntValue().isNonNegative()) {
1817 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1818 // NLZ can't be BitWidth with no sign bit
1819 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1820 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1823 // If all of the MaskV bits are known to be zero, then we know the
1824 // output top bits are zero, because we now know that the output is
1826 if ((KnownZero2 & MaskV) == MaskV) {
1827 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1828 // Top bits known zero.
1829 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1836 // Output known-0 bits are known if clear or set in both the low clear bits
1837 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1838 // low 3 bits clear.
1839 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1840 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1841 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1842 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1844 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1845 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1846 KnownZeroOut = std::min(KnownZeroOut,
1847 KnownZero2.countTrailingOnes());
1849 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1853 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1854 const APInt &RA = Rem->getAPIntValue();
1855 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1856 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1857 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1858 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1860 // If the sign bit of the first operand is zero, the sign bit of
1861 // the result is zero. If the first operand has no one bits below
1862 // the second operand's single 1 bit, its sign will be zero.
1863 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1864 KnownZero2 |= ~LowBits;
1866 KnownZero |= KnownZero2 & Mask;
1868 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1873 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1874 const APInt &RA = Rem->getAPIntValue();
1875 if (RA.isPowerOf2()) {
1876 APInt LowBits = (RA - 1);
1877 APInt Mask2 = LowBits & Mask;
1878 KnownZero |= ~LowBits & Mask;
1879 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1880 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1885 // Since the result is less than or equal to either operand, any leading
1886 // zero bits in either operand must also exist in the result.
1887 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1888 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1890 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1893 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1894 KnownZero2.countLeadingOnes());
1896 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1900 // Allow the target to implement this method for its nodes.
1901 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1902 case ISD::INTRINSIC_WO_CHAIN:
1903 case ISD::INTRINSIC_W_CHAIN:
1904 case ISD::INTRINSIC_VOID:
1905 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1911 /// ComputeNumSignBits - Return the number of times the sign bit of the
1912 /// register is replicated into the other bits. We know that at least 1 bit
1913 /// is always equal to the sign bit (itself), but other cases can give us
1914 /// information. For example, immediately after an "SRA X, 2", we know that
1915 /// the top 3 bits are all equal to each other, so we return 3.
1916 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1917 MVT VT = Op.getValueType();
1918 assert(VT.isInteger() && "Invalid VT!");
1919 unsigned VTBits = VT.getSizeInBits();
1921 unsigned FirstAnswer = 1;
1924 return 1; // Limit search depth.
1926 switch (Op.getOpcode()) {
1928 case ISD::AssertSext:
1929 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1930 return VTBits-Tmp+1;
1931 case ISD::AssertZext:
1932 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1935 case ISD::Constant: {
1936 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1937 // If negative, return # leading ones.
1938 if (Val.isNegative())
1939 return Val.countLeadingOnes();
1941 // Return # leading zeros.
1942 return Val.countLeadingZeros();
1945 case ISD::SIGN_EXTEND:
1946 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1947 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1949 case ISD::SIGN_EXTEND_INREG:
1950 // Max of the input and what this extends.
1951 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1954 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1955 return std::max(Tmp, Tmp2);
1958 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1959 // SRA X, C -> adds C sign bits.
1960 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1961 Tmp += C->getZExtValue();
1962 if (Tmp > VTBits) Tmp = VTBits;
1966 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1967 // shl destroys sign bits.
1968 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1969 if (C->getZExtValue() >= VTBits || // Bad shift.
1970 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
1971 return Tmp - C->getZExtValue();
1976 case ISD::XOR: // NOT is handled here.
1977 // Logical binary ops preserve the number of sign bits at the worst.
1978 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1980 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1981 FirstAnswer = std::min(Tmp, Tmp2);
1982 // We computed what we know about the sign bits as our first
1983 // answer. Now proceed to the generic code that uses
1984 // ComputeMaskedBits, and pick whichever answer is better.
1989 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1990 if (Tmp == 1) return 1; // Early out.
1991 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1992 return std::min(Tmp, Tmp2);
2000 if (Op.getResNo() != 1)
2002 // The boolean result conforms to getBooleanContents. Fall through.
2004 // If setcc returns 0/-1, all bits are sign bits.
2005 if (TLI.getBooleanContents() ==
2006 TargetLowering::ZeroOrNegativeOneBooleanContent)
2011 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2012 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2014 // Handle rotate right by N like a rotate left by 32-N.
2015 if (Op.getOpcode() == ISD::ROTR)
2016 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2018 // If we aren't rotating out all of the known-in sign bits, return the
2019 // number that are left. This handles rotl(sext(x), 1) for example.
2020 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2021 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2025 // Add can have at most one carry bit. Thus we know that the output
2026 // is, at worst, one more bit than the inputs.
2027 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2028 if (Tmp == 1) return 1; // Early out.
2030 // Special case decrementing a value (ADD X, -1):
2031 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2032 if (CRHS->isAllOnesValue()) {
2033 APInt KnownZero, KnownOne;
2034 APInt Mask = APInt::getAllOnesValue(VTBits);
2035 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2037 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2039 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2042 // If we are subtracting one from a positive number, there is no carry
2043 // out of the result.
2044 if (KnownZero.isNegative())
2048 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2049 if (Tmp2 == 1) return 1;
2050 return std::min(Tmp, Tmp2)-1;
2054 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2055 if (Tmp2 == 1) return 1;
2058 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2059 if (CLHS->isNullValue()) {
2060 APInt KnownZero, KnownOne;
2061 APInt Mask = APInt::getAllOnesValue(VTBits);
2062 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2063 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2065 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2068 // If the input is known to be positive (the sign bit is known clear),
2069 // the output of the NEG has the same number of sign bits as the input.
2070 if (KnownZero.isNegative())
2073 // Otherwise, we treat this like a SUB.
2076 // Sub can have at most one carry bit. Thus we know that the output
2077 // is, at worst, one more bit than the inputs.
2078 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2079 if (Tmp == 1) return 1; // Early out.
2080 return std::min(Tmp, Tmp2)-1;
2083 // FIXME: it's tricky to do anything useful for this, but it is an important
2084 // case for targets like X86.
2088 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2089 if (Op.getOpcode() == ISD::LOAD) {
2090 LoadSDNode *LD = cast<LoadSDNode>(Op);
2091 unsigned ExtType = LD->getExtensionType();
2094 case ISD::SEXTLOAD: // '17' bits known
2095 Tmp = LD->getMemoryVT().getSizeInBits();
2096 return VTBits-Tmp+1;
2097 case ISD::ZEXTLOAD: // '16' bits known
2098 Tmp = LD->getMemoryVT().getSizeInBits();
2103 // Allow the target to implement this method for its nodes.
2104 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2105 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2106 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2107 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2108 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2109 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2112 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2113 // use this information.
2114 APInt KnownZero, KnownOne;
2115 APInt Mask = APInt::getAllOnesValue(VTBits);
2116 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2118 if (KnownZero.isNegative()) { // sign bit is 0
2120 } else if (KnownOne.isNegative()) { // sign bit is 1;
2127 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2128 // the number of identical bits in the top of the input value.
2130 Mask <<= Mask.getBitWidth()-VTBits;
2131 // Return # leading zeros. We use 'min' here in case Val was zero before
2132 // shifting. We don't want to return '64' as for an i32 "0".
2133 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2137 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2138 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2139 if (!GA) return false;
2140 if (GA->getOffset() != 0) return false;
2141 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2142 if (!GV) return false;
2143 MachineModuleInfo *MMI = getMachineModuleInfo();
2144 return MMI && MMI->hasDebugInfo();
2148 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2149 /// element of the result of the vector shuffle.
2150 SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
2151 MVT VT = N->getValueType(0);
2152 DebugLoc dl = N->getDebugLoc();
2153 SDValue PermMask = N->getOperand(2);
2154 SDValue Idx = PermMask.getOperand(i);
2155 if (Idx.getOpcode() == ISD::UNDEF)
2156 return getNode(ISD::UNDEF, dl, VT.getVectorElementType());
2157 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
2158 unsigned NumElems = PermMask.getNumOperands();
2159 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2162 if (V.getOpcode() == ISD::BIT_CONVERT) {
2163 V = V.getOperand(0);
2164 MVT VVT = V.getValueType();
2165 if (!VVT.isVector() || VVT.getVectorNumElements() != NumElems)
2168 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2169 return (Index == 0) ? V.getOperand(0)
2170 : getNode(ISD::UNDEF, dl, VT.getVectorElementType());
2171 if (V.getOpcode() == ISD::BUILD_VECTOR)
2172 return V.getOperand(Index);
2173 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
2174 return getShuffleScalarElt(V.getNode(), Index);
2179 /// getNode - Gets or creates the specified node.
2181 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
2182 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT);
2185 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT) {
2186 FoldingSetNodeID ID;
2187 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2189 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2190 return SDValue(E, 0);
2191 SDNode *N = NodeAllocator.Allocate<SDNode>();
2192 new (N) SDNode(Opcode, DL, SDNode::getSDVTList(VT));
2193 CSEMap.InsertNode(N, IP);
2195 AllNodes.push_back(N);
2199 return SDValue(N, 0);
2202 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
2203 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Operand);
2206 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2207 MVT VT, SDValue Operand) {
2208 // Constant fold unary operations with an integer constant operand.
2209 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2210 const APInt &Val = C->getAPIntValue();
2211 unsigned BitWidth = VT.getSizeInBits();
2214 case ISD::SIGN_EXTEND:
2215 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2216 case ISD::ANY_EXTEND:
2217 case ISD::ZERO_EXTEND:
2219 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2220 case ISD::UINT_TO_FP:
2221 case ISD::SINT_TO_FP: {
2222 const uint64_t zero[] = {0, 0};
2223 // No compile time operations on this type.
2224 if (VT==MVT::ppcf128)
2226 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2227 (void)apf.convertFromAPInt(Val,
2228 Opcode==ISD::SINT_TO_FP,
2229 APFloat::rmNearestTiesToEven);
2230 return getConstantFP(apf, VT);
2232 case ISD::BIT_CONVERT:
2233 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2234 return getConstantFP(Val.bitsToFloat(), VT);
2235 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2236 return getConstantFP(Val.bitsToDouble(), VT);
2239 return getConstant(Val.byteSwap(), VT);
2241 return getConstant(Val.countPopulation(), VT);
2243 return getConstant(Val.countLeadingZeros(), VT);
2245 return getConstant(Val.countTrailingZeros(), VT);
2249 // Constant fold unary operations with a floating point constant operand.
2250 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2251 APFloat V = C->getValueAPF(); // make copy
2252 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2256 return getConstantFP(V, VT);
2259 return getConstantFP(V, VT);
2261 case ISD::FP_EXTEND: {
2263 // This can return overflow, underflow, or inexact; we don't care.
2264 // FIXME need to be more flexible about rounding mode.
2265 (void)V.convert(*MVTToAPFloatSemantics(VT),
2266 APFloat::rmNearestTiesToEven, &ignored);
2267 return getConstantFP(V, VT);
2269 case ISD::FP_TO_SINT:
2270 case ISD::FP_TO_UINT: {
2273 assert(integerPartWidth >= 64);
2274 // FIXME need to be more flexible about rounding mode.
2275 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2276 Opcode==ISD::FP_TO_SINT,
2277 APFloat::rmTowardZero, &ignored);
2278 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2280 return getConstant(x, VT);
2282 case ISD::BIT_CONVERT:
2283 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2284 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2285 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2286 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2292 unsigned OpOpcode = Operand.getNode()->getOpcode();
2294 case ISD::TokenFactor:
2295 case ISD::MERGE_VALUES:
2296 case ISD::CONCAT_VECTORS:
2297 return Operand; // Factor, merge or concat of one node? No need.
2298 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2299 case ISD::FP_EXTEND:
2300 assert(VT.isFloatingPoint() &&
2301 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2302 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2303 if (Operand.getOpcode() == ISD::UNDEF)
2304 return getNode(ISD::UNDEF, DL, VT);
2306 case ISD::SIGN_EXTEND:
2307 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2308 "Invalid SIGN_EXTEND!");
2309 if (Operand.getValueType() == VT) return Operand; // noop extension
2310 assert(Operand.getValueType().bitsLT(VT)
2311 && "Invalid sext node, dst < src!");
2312 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2313 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2315 case ISD::ZERO_EXTEND:
2316 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2317 "Invalid ZERO_EXTEND!");
2318 if (Operand.getValueType() == VT) return Operand; // noop extension
2319 assert(Operand.getValueType().bitsLT(VT)
2320 && "Invalid zext node, dst < src!");
2321 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2322 return getNode(ISD::ZERO_EXTEND, DL, VT,
2323 Operand.getNode()->getOperand(0));
2325 case ISD::ANY_EXTEND:
2326 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2327 "Invalid ANY_EXTEND!");
2328 if (Operand.getValueType() == VT) return Operand; // noop extension
2329 assert(Operand.getValueType().bitsLT(VT)
2330 && "Invalid anyext node, dst < src!");
2331 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2332 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2333 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2336 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2337 "Invalid TRUNCATE!");
2338 if (Operand.getValueType() == VT) return Operand; // noop truncate
2339 assert(Operand.getValueType().bitsGT(VT)
2340 && "Invalid truncate node, src < dst!");
2341 if (OpOpcode == ISD::TRUNCATE)
2342 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2343 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2344 OpOpcode == ISD::ANY_EXTEND) {
2345 // If the source is smaller than the dest, we still need an extend.
2346 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2347 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2348 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2349 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2351 return Operand.getNode()->getOperand(0);
2354 case ISD::BIT_CONVERT:
2355 // Basic sanity checking.
2356 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2357 && "Cannot BIT_CONVERT between types of different sizes!");
2358 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2359 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2360 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2361 if (OpOpcode == ISD::UNDEF)
2362 return getNode(ISD::UNDEF, DL, VT);
2364 case ISD::SCALAR_TO_VECTOR:
2365 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2366 VT.getVectorElementType() == Operand.getValueType() &&
2367 "Illegal SCALAR_TO_VECTOR node!");
2368 if (OpOpcode == ISD::UNDEF)
2369 return getNode(ISD::UNDEF, DL, VT);
2370 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2371 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2372 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2373 Operand.getConstantOperandVal(1) == 0 &&
2374 Operand.getOperand(0).getValueType() == VT)
2375 return Operand.getOperand(0);
2378 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2379 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2380 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2381 Operand.getNode()->getOperand(0));
2382 if (OpOpcode == ISD::FNEG) // --X -> X
2383 return Operand.getNode()->getOperand(0);
2386 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2387 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2392 SDVTList VTs = getVTList(VT);
2393 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2394 FoldingSetNodeID ID;
2395 SDValue Ops[1] = { Operand };
2396 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2398 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2399 return SDValue(E, 0);
2400 N = NodeAllocator.Allocate<UnarySDNode>();
2401 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2402 CSEMap.InsertNode(N, IP);
2404 N = NodeAllocator.Allocate<UnarySDNode>();
2405 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2408 AllNodes.push_back(N);
2412 return SDValue(N, 0);
2415 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2417 ConstantSDNode *Cst1,
2418 ConstantSDNode *Cst2) {
2419 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2422 case ISD::ADD: return getConstant(C1 + C2, VT);
2423 case ISD::SUB: return getConstant(C1 - C2, VT);
2424 case ISD::MUL: return getConstant(C1 * C2, VT);
2426 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2429 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2432 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2435 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2437 case ISD::AND: return getConstant(C1 & C2, VT);
2438 case ISD::OR: return getConstant(C1 | C2, VT);
2439 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2440 case ISD::SHL: return getConstant(C1 << C2, VT);
2441 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2442 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2443 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2444 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2451 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2452 SDValue N1, SDValue N2) {
2453 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2);
2456 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2457 SDValue N1, SDValue N2) {
2458 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2459 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2462 case ISD::TokenFactor:
2463 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2464 N2.getValueType() == MVT::Other && "Invalid token factor!");
2465 // Fold trivial token factors.
2466 if (N1.getOpcode() == ISD::EntryToken) return N2;
2467 if (N2.getOpcode() == ISD::EntryToken) return N1;
2468 if (N1 == N2) return N1;
2470 case ISD::CONCAT_VECTORS:
2471 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2472 // one big BUILD_VECTOR.
2473 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2474 N2.getOpcode() == ISD::BUILD_VECTOR) {
2475 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2476 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2477 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2481 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2482 N1.getValueType() == VT && "Binary operator types must match!");
2483 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2484 // worth handling here.
2485 if (N2C && N2C->isNullValue())
2487 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2494 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2495 N1.getValueType() == VT && "Binary operator types must match!");
2496 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2497 // it's worth handling here.
2498 if (N2C && N2C->isNullValue())
2508 assert(VT.isInteger() && "This operator does not apply to FP types!");
2516 if (Opcode == ISD::FADD) {
2518 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2519 if (CFP->getValueAPF().isZero())
2522 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2523 if (CFP->getValueAPF().isZero())
2525 } else if (Opcode == ISD::FSUB) {
2527 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2528 if (CFP->getValueAPF().isZero())
2532 assert(N1.getValueType() == N2.getValueType() &&
2533 N1.getValueType() == VT && "Binary operator types must match!");
2535 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2536 assert(N1.getValueType() == VT &&
2537 N1.getValueType().isFloatingPoint() &&
2538 N2.getValueType().isFloatingPoint() &&
2539 "Invalid FCOPYSIGN!");
2546 assert(VT == N1.getValueType() &&
2547 "Shift operators return type must be the same as their first arg");
2548 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2549 "Shifts only work on integers");
2551 // Always fold shifts of i1 values so the code generator doesn't need to
2552 // handle them. Since we know the size of the shift has to be less than the
2553 // size of the value, the shift/rotate count is guaranteed to be zero.
2557 case ISD::FP_ROUND_INREG: {
2558 MVT EVT = cast<VTSDNode>(N2)->getVT();
2559 assert(VT == N1.getValueType() && "Not an inreg round!");
2560 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2561 "Cannot FP_ROUND_INREG integer types");
2562 assert(EVT.bitsLE(VT) && "Not rounding down!");
2563 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2567 assert(VT.isFloatingPoint() &&
2568 N1.getValueType().isFloatingPoint() &&
2569 VT.bitsLE(N1.getValueType()) &&
2570 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2571 if (N1.getValueType() == VT) return N1; // noop conversion.
2573 case ISD::AssertSext:
2574 case ISD::AssertZext: {
2575 MVT EVT = cast<VTSDNode>(N2)->getVT();
2576 assert(VT == N1.getValueType() && "Not an inreg extend!");
2577 assert(VT.isInteger() && EVT.isInteger() &&
2578 "Cannot *_EXTEND_INREG FP types");
2579 assert(EVT.bitsLE(VT) && "Not extending!");
2580 if (VT == EVT) return N1; // noop assertion.
2583 case ISD::SIGN_EXTEND_INREG: {
2584 MVT EVT = cast<VTSDNode>(N2)->getVT();
2585 assert(VT == N1.getValueType() && "Not an inreg extend!");
2586 assert(VT.isInteger() && EVT.isInteger() &&
2587 "Cannot *_EXTEND_INREG FP types");
2588 assert(EVT.bitsLE(VT) && "Not extending!");
2589 if (EVT == VT) return N1; // Not actually extending
2592 APInt Val = N1C->getAPIntValue();
2593 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2594 Val <<= Val.getBitWidth()-FromBits;
2595 Val = Val.ashr(Val.getBitWidth()-FromBits);
2596 return getConstant(Val, VT);
2600 case ISD::EXTRACT_VECTOR_ELT:
2601 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2602 if (N1.getOpcode() == ISD::UNDEF)
2603 return getNode(ISD::UNDEF, DL, VT);
2605 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2606 // expanding copies of large vectors from registers.
2608 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2609 N1.getNumOperands() > 0) {
2611 N1.getOperand(0).getValueType().getVectorNumElements();
2612 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2613 N1.getOperand(N2C->getZExtValue() / Factor),
2614 getConstant(N2C->getZExtValue() % Factor,
2615 N2.getValueType()));
2618 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2619 // expanding large vector constants.
2620 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR)
2621 return N1.getOperand(N2C->getZExtValue());
2623 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2624 // operations are lowered to scalars.
2625 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2626 // If the indices are the same, return the inserted element.
2627 if (N1.getOperand(2) == N2)
2628 return N1.getOperand(1);
2629 // If the indices are known different, extract the element from
2630 // the original vector.
2631 else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2632 isa<ConstantSDNode>(N2))
2633 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2636 case ISD::EXTRACT_ELEMENT:
2637 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2638 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2639 (N1.getValueType().isInteger() == VT.isInteger()) &&
2640 "Wrong types for EXTRACT_ELEMENT!");
2642 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2643 // 64-bit integers into 32-bit parts. Instead of building the extract of
2644 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2645 if (N1.getOpcode() == ISD::BUILD_PAIR)
2646 return N1.getOperand(N2C->getZExtValue());
2648 // EXTRACT_ELEMENT of a constant int is also very common.
2649 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2650 unsigned ElementSize = VT.getSizeInBits();
2651 unsigned Shift = ElementSize * N2C->getZExtValue();
2652 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2653 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2656 case ISD::EXTRACT_SUBVECTOR:
2657 if (N1.getValueType() == VT) // Trivial extraction.
2664 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2665 if (SV.getNode()) return SV;
2666 } else { // Cannonicalize constant to RHS if commutative
2667 if (isCommutativeBinOp(Opcode)) {
2668 std::swap(N1C, N2C);
2674 // Constant fold FP operations.
2675 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2676 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2678 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2679 // Cannonicalize constant to RHS if commutative
2680 std::swap(N1CFP, N2CFP);
2682 } else if (N2CFP && VT != MVT::ppcf128) {
2683 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2684 APFloat::opStatus s;
2687 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2688 if (s != APFloat::opInvalidOp)
2689 return getConstantFP(V1, VT);
2692 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2693 if (s!=APFloat::opInvalidOp)
2694 return getConstantFP(V1, VT);
2697 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2698 if (s!=APFloat::opInvalidOp)
2699 return getConstantFP(V1, VT);
2702 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2703 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2704 return getConstantFP(V1, VT);
2707 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2708 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2709 return getConstantFP(V1, VT);
2711 case ISD::FCOPYSIGN:
2713 return getConstantFP(V1, VT);
2719 // Canonicalize an UNDEF to the RHS, even over a constant.
2720 if (N1.getOpcode() == ISD::UNDEF) {
2721 if (isCommutativeBinOp(Opcode)) {
2725 case ISD::FP_ROUND_INREG:
2726 case ISD::SIGN_EXTEND_INREG:
2732 return N1; // fold op(undef, arg2) -> undef
2740 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2741 // For vectors, we can't easily build an all zero vector, just return
2748 // Fold a bunch of operators when the RHS is undef.
2749 if (N2.getOpcode() == ISD::UNDEF) {
2752 if (N1.getOpcode() == ISD::UNDEF)
2753 // Handle undef ^ undef -> 0 special case. This is a common
2755 return getConstant(0, VT);
2770 return N2; // fold op(arg1, undef) -> undef
2776 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2777 // For vectors, we can't easily build an all zero vector, just return
2782 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2783 // For vectors, we can't easily build an all one vector, just return
2791 // Memoize this node if possible.
2793 SDVTList VTs = getVTList(VT);
2794 if (VT != MVT::Flag) {
2795 SDValue Ops[] = { N1, N2 };
2796 FoldingSetNodeID ID;
2797 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2799 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2800 return SDValue(E, 0);
2801 N = NodeAllocator.Allocate<BinarySDNode>();
2802 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2803 CSEMap.InsertNode(N, IP);
2805 N = NodeAllocator.Allocate<BinarySDNode>();
2806 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2809 AllNodes.push_back(N);
2813 return SDValue(N, 0);
2816 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2817 SDValue N1, SDValue N2, SDValue N3) {
2818 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3);
2821 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2822 SDValue N1, SDValue N2, SDValue N3) {
2823 // Perform various simplifications.
2824 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2825 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2827 case ISD::CONCAT_VECTORS:
2828 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2829 // one big BUILD_VECTOR.
2830 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2831 N2.getOpcode() == ISD::BUILD_VECTOR &&
2832 N3.getOpcode() == ISD::BUILD_VECTOR) {
2833 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2834 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2835 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2836 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2840 // Use FoldSetCC to simplify SETCC's.
2841 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
2842 if (Simp.getNode()) return Simp;
2847 if (N1C->getZExtValue())
2848 return N2; // select true, X, Y -> X
2850 return N3; // select false, X, Y -> Y
2853 if (N2 == N3) return N2; // select C, X, X -> X
2857 if (N2C->getZExtValue()) // Unconditional branch
2858 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
2860 return N1; // Never-taken branch
2863 case ISD::VECTOR_SHUFFLE:
2864 assert(N1.getValueType() == N2.getValueType() &&
2865 N1.getValueType().isVector() &&
2866 VT.isVector() && N3.getValueType().isVector() &&
2867 N3.getOpcode() == ISD::BUILD_VECTOR &&
2868 VT.getVectorNumElements() == N3.getNumOperands() &&
2869 "Illegal VECTOR_SHUFFLE node!");
2871 case ISD::BIT_CONVERT:
2872 // Fold bit_convert nodes from a type to themselves.
2873 if (N1.getValueType() == VT)
2878 // Memoize node if it doesn't produce a flag.
2880 SDVTList VTs = getVTList(VT);
2881 if (VT != MVT::Flag) {
2882 SDValue Ops[] = { N1, N2, N3 };
2883 FoldingSetNodeID ID;
2884 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2886 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2887 return SDValue(E, 0);
2888 N = NodeAllocator.Allocate<TernarySDNode>();
2889 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2890 CSEMap.InsertNode(N, IP);
2892 N = NodeAllocator.Allocate<TernarySDNode>();
2893 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2895 AllNodes.push_back(N);
2899 return SDValue(N, 0);
2902 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2903 SDValue N1, SDValue N2, SDValue N3,
2905 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3, N4);
2908 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2909 SDValue N1, SDValue N2, SDValue N3,
2911 SDValue Ops[] = { N1, N2, N3, N4 };
2912 return getNode(Opcode, DL, VT, Ops, 4);
2915 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2916 SDValue N1, SDValue N2, SDValue N3,
2917 SDValue N4, SDValue N5) {
2918 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3, N4, N5);
2921 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2922 SDValue N1, SDValue N2, SDValue N3,
2923 SDValue N4, SDValue N5) {
2924 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2925 return getNode(Opcode, DL, VT, Ops, 5);
2928 /// getMemsetValue - Vectorized representation of the memset value
2930 static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG) {
2931 unsigned NumBits = VT.isVector() ?
2932 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2933 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2934 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
2936 for (unsigned i = NumBits; i > 8; i >>= 1) {
2937 Val = (Val << Shift) | Val;
2941 return DAG.getConstant(Val, VT);
2942 return DAG.getConstantFP(APFloat(Val), VT);
2945 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2946 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2948 for (unsigned i = NumBits; i > 8; i >>= 1) {
2949 Value = DAG.getNode(ISD::OR, VT,
2950 DAG.getNode(ISD::SHL, VT, Value,
2951 DAG.getConstant(Shift,
2952 TLI.getShiftAmountTy())),
2960 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2961 /// used when a memcpy is turned into a memset when the source is a constant
2963 static SDValue getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2964 const TargetLowering &TLI,
2965 std::string &Str, unsigned Offset) {
2966 // Handle vector with all elements zero.
2969 return DAG.getConstant(0, VT);
2970 unsigned NumElts = VT.getVectorNumElements();
2971 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2972 return DAG.getNode(ISD::BIT_CONVERT, VT,
2973 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2976 assert(!VT.isVector() && "Can't handle vector type here!");
2977 unsigned NumBits = VT.getSizeInBits();
2978 unsigned MSB = NumBits / 8;
2980 if (TLI.isLittleEndian())
2981 Offset = Offset + MSB - 1;
2982 for (unsigned i = 0; i != MSB; ++i) {
2983 Val = (Val << 8) | (unsigned char)Str[Offset];
2984 Offset += TLI.isLittleEndian() ? -1 : 1;
2986 return DAG.getConstant(Val, VT);
2989 /// getMemBasePlusOffset - Returns base and offset node for the
2991 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
2992 SelectionDAG &DAG) {
2993 MVT VT = Base.getValueType();
2994 return DAG.getNode(ISD::ADD, Base.getNode()->getDebugLoc(),
2995 VT, Base, DAG.getConstant(Offset, VT));
2998 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3000 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3001 unsigned SrcDelta = 0;
3002 GlobalAddressSDNode *G = NULL;
3003 if (Src.getOpcode() == ISD::GlobalAddress)
3004 G = cast<GlobalAddressSDNode>(Src);
3005 else if (Src.getOpcode() == ISD::ADD &&
3006 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3007 Src.getOperand(1).getOpcode() == ISD::Constant) {
3008 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3009 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3014 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3015 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3021 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3022 /// to replace the memset / memcpy is below the threshold. It also returns the
3023 /// types of the sequence of memory ops to perform memset / memcpy.
3025 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
3026 SDValue Dst, SDValue Src,
3027 unsigned Limit, uint64_t Size, unsigned &Align,
3028 std::string &Str, bool &isSrcStr,
3030 const TargetLowering &TLI) {
3031 isSrcStr = isMemSrcFromString(Src, Str);
3032 bool isSrcConst = isa<ConstantSDNode>(Src);
3033 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
3034 MVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
3035 if (VT != MVT::iAny) {
3036 unsigned NewAlign = (unsigned)
3037 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
3038 // If source is a string constant, this will require an unaligned load.
3039 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3040 if (Dst.getOpcode() != ISD::FrameIndex) {
3041 // Can't change destination alignment. It requires a unaligned store.
3045 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3046 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3047 if (MFI->isFixedObjectIndex(FI)) {
3048 // Can't change destination alignment. It requires a unaligned store.
3052 // Give the stack frame object a larger alignment if needed.
3053 if (MFI->getObjectAlignment(FI) < NewAlign)
3054 MFI->setObjectAlignment(FI, NewAlign);
3061 if (VT == MVT::iAny) {
3065 switch (Align & 7) {
3066 case 0: VT = MVT::i64; break;
3067 case 4: VT = MVT::i32; break;
3068 case 2: VT = MVT::i16; break;
3069 default: VT = MVT::i8; break;
3074 while (!TLI.isTypeLegal(LVT))
3075 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
3076 assert(LVT.isInteger());
3082 unsigned NumMemOps = 0;
3084 unsigned VTSize = VT.getSizeInBits() / 8;
3085 while (VTSize > Size) {
3086 // For now, only use non-vector load / store's for the left-over pieces.
3087 if (VT.isVector()) {
3089 while (!TLI.isTypeLegal(VT))
3090 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
3091 VTSize = VT.getSizeInBits() / 8;
3093 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
3098 if (++NumMemOps > Limit)
3100 MemOps.push_back(VT);
3107 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG,
3108 SDValue Chain, SDValue Dst,
3109 SDValue Src, uint64_t Size,
3110 unsigned Align, bool AlwaysInline,
3111 const Value *DstSV, uint64_t DstSVOff,
3112 const Value *SrcSV, uint64_t SrcSVOff){
3113 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3115 // Expand memcpy to a series of load and store ops if the size operand falls
3116 // below a certain threshold.
3117 std::vector<MVT> MemOps;
3118 uint64_t Limit = -1ULL;
3120 Limit = TLI.getMaxStoresPerMemcpy();
3121 unsigned DstAlign = Align; // Destination alignment can change.
3124 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3125 Str, CopyFromStr, DAG, TLI))
3129 bool isZeroStr = CopyFromStr && Str.empty();
3130 SmallVector<SDValue, 8> OutChains;
3131 unsigned NumMemOps = MemOps.size();
3132 uint64_t SrcOff = 0, DstOff = 0;
3133 for (unsigned i = 0; i < NumMemOps; i++) {
3135 unsigned VTSize = VT.getSizeInBits() / 8;
3136 SDValue Value, Store;
3138 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3139 // It's unlikely a store of a vector immediate can be done in a single
3140 // instruction. It would require a load from a constantpool first.
3141 // We also handle store a vector with all zero's.
3142 // FIXME: Handle other cases where store of vector immediate is done in
3143 // a single instruction.
3144 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3145 Store = DAG.getStore(Chain, Value,
3146 getMemBasePlusOffset(Dst, DstOff, DAG),
3147 DstSV, DstSVOff + DstOff, false, DstAlign);
3149 Value = DAG.getLoad(VT, Chain,
3150 getMemBasePlusOffset(Src, SrcOff, DAG),
3151 SrcSV, SrcSVOff + SrcOff, false, Align);
3152 Store = DAG.getStore(Chain, Value,
3153 getMemBasePlusOffset(Dst, DstOff, DAG),
3154 DstSV, DstSVOff + DstOff, false, DstAlign);
3156 OutChains.push_back(Store);
3161 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3162 &OutChains[0], OutChains.size());
3165 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG,
3166 SDValue Chain, SDValue Dst,
3167 SDValue Src, uint64_t Size,
3168 unsigned Align, bool AlwaysInline,
3169 const Value *DstSV, uint64_t DstSVOff,
3170 const Value *SrcSV, uint64_t SrcSVOff){
3171 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3173 // Expand memmove to a series of load and store ops if the size operand falls
3174 // below a certain threshold.
3175 std::vector<MVT> MemOps;
3176 uint64_t Limit = -1ULL;
3178 Limit = TLI.getMaxStoresPerMemmove();
3179 unsigned DstAlign = Align; // Destination alignment can change.
3182 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3183 Str, CopyFromStr, DAG, TLI))
3186 uint64_t SrcOff = 0, DstOff = 0;
3188 SmallVector<SDValue, 8> LoadValues;
3189 SmallVector<SDValue, 8> LoadChains;
3190 SmallVector<SDValue, 8> OutChains;
3191 unsigned NumMemOps = MemOps.size();
3192 for (unsigned i = 0; i < NumMemOps; i++) {
3194 unsigned VTSize = VT.getSizeInBits() / 8;
3195 SDValue Value, Store;
3197 Value = DAG.getLoad(VT, Chain,
3198 getMemBasePlusOffset(Src, SrcOff, DAG),
3199 SrcSV, SrcSVOff + SrcOff, false, Align);
3200 LoadValues.push_back(Value);
3201 LoadChains.push_back(Value.getValue(1));
3204 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3205 &LoadChains[0], LoadChains.size());
3207 for (unsigned i = 0; i < NumMemOps; i++) {
3209 unsigned VTSize = VT.getSizeInBits() / 8;
3210 SDValue Value, Store;
3212 Store = DAG.getStore(Chain, LoadValues[i],
3213 getMemBasePlusOffset(Dst, DstOff, DAG),
3214 DstSV, DstSVOff + DstOff, false, DstAlign);
3215 OutChains.push_back(Store);
3219 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3220 &OutChains[0], OutChains.size());
3223 static SDValue getMemsetStores(SelectionDAG &DAG,
3224 SDValue Chain, SDValue Dst,
3225 SDValue Src, uint64_t Size,
3227 const Value *DstSV, uint64_t DstSVOff) {
3228 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3230 // Expand memset to a series of load/store ops if the size operand
3231 // falls below a certain threshold.
3232 std::vector<MVT> MemOps;
3235 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3236 Size, Align, Str, CopyFromStr, DAG, TLI))
3239 SmallVector<SDValue, 8> OutChains;
3240 uint64_t DstOff = 0;
3242 unsigned NumMemOps = MemOps.size();
3243 for (unsigned i = 0; i < NumMemOps; i++) {
3245 unsigned VTSize = VT.getSizeInBits() / 8;
3246 SDValue Value = getMemsetValue(Src, VT, DAG);
3247 SDValue Store = DAG.getStore(Chain, Value,
3248 getMemBasePlusOffset(Dst, DstOff, DAG),
3249 DstSV, DstSVOff + DstOff);
3250 OutChains.push_back(Store);
3254 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3255 &OutChains[0], OutChains.size());
3258 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDValue Dst,
3259 SDValue Src, SDValue Size,
3260 unsigned Align, bool AlwaysInline,
3261 const Value *DstSV, uint64_t DstSVOff,
3262 const Value *SrcSV, uint64_t SrcSVOff) {
3264 // Check to see if we should lower the memcpy to loads and stores first.
3265 // For cases within the target-specified limits, this is the best choice.
3266 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3268 // Memcpy with size zero? Just return the original chain.
3269 if (ConstantSize->isNullValue())
3273 getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3274 ConstantSize->getZExtValue(),
3275 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3276 if (Result.getNode())
3280 // Then check to see if we should lower the memcpy with target-specific
3281 // code. If the target chooses to do this, this is the next best.
3283 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
3285 DstSV, DstSVOff, SrcSV, SrcSVOff);
3286 if (Result.getNode())
3289 // If we really need inline code and the target declined to provide it,
3290 // use a (potentially long) sequence of loads and stores.
3292 assert(ConstantSize && "AlwaysInline requires a constant size!");
3293 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3294 ConstantSize->getZExtValue(), Align, true,
3295 DstSV, DstSVOff, SrcSV, SrcSVOff);
3298 // Emit a library call.
3299 TargetLowering::ArgListTy Args;
3300 TargetLowering::ArgListEntry Entry;
3301 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3302 Entry.Node = Dst; Args.push_back(Entry);
3303 Entry.Node = Src; Args.push_back(Entry);
3304 Entry.Node = Size; Args.push_back(Entry);
3305 // FIXME: pass in DebugLoc
3306 std::pair<SDValue,SDValue> CallResult =
3307 TLI.LowerCallTo(Chain, Type::VoidTy,
3308 false, false, false, false, CallingConv::C, false,
3309 getExternalSymbol("memcpy", TLI.getPointerTy()),
3310 Args, *this, DebugLoc::getUnknownLoc());
3311 return CallResult.second;
3314 SDValue SelectionDAG::getMemmove(SDValue Chain, SDValue Dst,
3315 SDValue Src, SDValue Size,
3317 const Value *DstSV, uint64_t DstSVOff,
3318 const Value *SrcSV, uint64_t SrcSVOff) {
3320 // Check to see if we should lower the memmove to loads and stores first.
3321 // For cases within the target-specified limits, this is the best choice.
3322 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3324 // Memmove with size zero? Just return the original chain.
3325 if (ConstantSize->isNullValue())
3329 getMemmoveLoadsAndStores(*this, Chain, Dst, Src,
3330 ConstantSize->getZExtValue(),
3331 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3332 if (Result.getNode())
3336 // Then check to see if we should lower the memmove with target-specific
3337 // code. If the target chooses to do this, this is the next best.
3339 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
3340 DstSV, DstSVOff, SrcSV, SrcSVOff);
3341 if (Result.getNode())
3344 // Emit a library call.
3345 TargetLowering::ArgListTy Args;
3346 TargetLowering::ArgListEntry Entry;
3347 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3348 Entry.Node = Dst; Args.push_back(Entry);
3349 Entry.Node = Src; Args.push_back(Entry);
3350 Entry.Node = Size; Args.push_back(Entry);
3351 // FIXME: pass in DebugLoc
3352 std::pair<SDValue,SDValue> CallResult =
3353 TLI.LowerCallTo(Chain, Type::VoidTy,
3354 false, false, false, false, CallingConv::C, false,
3355 getExternalSymbol("memmove", TLI.getPointerTy()),
3356 Args, *this, DebugLoc::getUnknownLoc());
3357 return CallResult.second;
3360 SDValue SelectionDAG::getMemset(SDValue Chain, SDValue Dst,
3361 SDValue Src, SDValue Size,
3363 const Value *DstSV, uint64_t DstSVOff) {
3365 // Check to see if we should lower the memset to stores first.
3366 // For cases within the target-specified limits, this is the best choice.
3367 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3369 // Memset with size zero? Just return the original chain.
3370 if (ConstantSize->isNullValue())
3374 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getZExtValue(),
3375 Align, DstSV, DstSVOff);
3376 if (Result.getNode())
3380 // Then check to see if we should lower the memset with target-specific
3381 // code. If the target chooses to do this, this is the next best.
3383 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3385 if (Result.getNode())
3388 // Emit a library call.
3389 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3390 TargetLowering::ArgListTy Args;
3391 TargetLowering::ArgListEntry Entry;
3392 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3393 Args.push_back(Entry);
3394 // Extend or truncate the argument to be an i32 value for the call.
3395 if (Src.getValueType().bitsGT(MVT::i32))
3396 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3398 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3399 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3400 Args.push_back(Entry);
3401 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3402 Args.push_back(Entry);
3403 // FIXME: pass in DebugLoc
3404 std::pair<SDValue,SDValue> CallResult =
3405 TLI.LowerCallTo(Chain, Type::VoidTy,
3406 false, false, false, false, CallingConv::C, false,
3407 getExternalSymbol("memset", TLI.getPointerTy()),
3408 Args, *this, DebugLoc::getUnknownLoc());
3409 return CallResult.second;
3412 SDValue SelectionDAG::getAtomic(unsigned Opcode, MVT MemVT,
3414 SDValue Ptr, SDValue Cmp,
3415 SDValue Swp, const Value* PtrVal,
3416 unsigned Alignment) {
3417 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3418 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3420 MVT VT = Cmp.getValueType();
3422 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3423 Alignment = getMVTAlignment(MemVT);
3425 SDVTList VTs = getVTList(VT, MVT::Other);
3426 FoldingSetNodeID ID;
3427 ID.AddInteger(MemVT.getRawBits());
3428 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3429 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3431 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3432 return SDValue(E, 0);
3433 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3434 new (N) AtomicSDNode(Opcode, VTs, MemVT,
3435 Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3436 CSEMap.InsertNode(N, IP);
3437 AllNodes.push_back(N);
3438 return SDValue(N, 0);
3441 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
3443 SDValue Ptr, SDValue Cmp,
3444 SDValue Swp, const Value* PtrVal,
3445 unsigned Alignment) {
3446 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3447 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3449 MVT VT = Cmp.getValueType();
3451 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3452 Alignment = getMVTAlignment(MemVT);
3454 SDVTList VTs = getVTList(VT, MVT::Other);
3455 FoldingSetNodeID ID;
3456 ID.AddInteger(MemVT.getRawBits());
3457 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3458 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3460 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3461 return SDValue(E, 0);
3462 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3463 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
3464 Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3465 CSEMap.InsertNode(N, IP);
3466 AllNodes.push_back(N);
3467 return SDValue(N, 0);
3470 SDValue SelectionDAG::getAtomic(unsigned Opcode, MVT MemVT,
3472 SDValue Ptr, SDValue Val,
3473 const Value* PtrVal,
3474 unsigned Alignment) {
3475 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3476 Opcode == ISD::ATOMIC_LOAD_SUB ||
3477 Opcode == ISD::ATOMIC_LOAD_AND ||
3478 Opcode == ISD::ATOMIC_LOAD_OR ||
3479 Opcode == ISD::ATOMIC_LOAD_XOR ||
3480 Opcode == ISD::ATOMIC_LOAD_NAND ||
3481 Opcode == ISD::ATOMIC_LOAD_MIN ||
3482 Opcode == ISD::ATOMIC_LOAD_MAX ||
3483 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3484 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3485 Opcode == ISD::ATOMIC_SWAP) &&
3486 "Invalid Atomic Op");
3488 MVT VT = Val.getValueType();
3490 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3491 Alignment = getMVTAlignment(MemVT);
3493 SDVTList VTs = getVTList(VT, MVT::Other);
3494 FoldingSetNodeID ID;
3495 ID.AddInteger(MemVT.getRawBits());
3496 SDValue Ops[] = {Chain, Ptr, Val};
3497 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3499 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3500 return SDValue(E, 0);
3501 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3502 new (N) AtomicSDNode(Opcode, VTs, MemVT,
3503 Chain, Ptr, Val, PtrVal, Alignment);
3504 CSEMap.InsertNode(N, IP);
3505 AllNodes.push_back(N);
3506 return SDValue(N, 0);
3509 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
3511 SDValue Ptr, SDValue Val,
3512 const Value* PtrVal,
3513 unsigned Alignment) {
3514 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3515 Opcode == ISD::ATOMIC_LOAD_SUB ||
3516 Opcode == ISD::ATOMIC_LOAD_AND ||
3517 Opcode == ISD::ATOMIC_LOAD_OR ||
3518 Opcode == ISD::ATOMIC_LOAD_XOR ||
3519 Opcode == ISD::ATOMIC_LOAD_NAND ||
3520 Opcode == ISD::ATOMIC_LOAD_MIN ||
3521 Opcode == ISD::ATOMIC_LOAD_MAX ||
3522 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3523 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3524 Opcode == ISD::ATOMIC_SWAP) &&
3525 "Invalid Atomic Op");
3527 MVT VT = Val.getValueType();
3529 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3530 Alignment = getMVTAlignment(MemVT);
3532 SDVTList VTs = getVTList(VT, MVT::Other);
3533 FoldingSetNodeID ID;
3534 ID.AddInteger(MemVT.getRawBits());
3535 SDValue Ops[] = {Chain, Ptr, Val};
3536 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3538 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3539 return SDValue(E, 0);
3540 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3541 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
3542 Chain, Ptr, Val, PtrVal, Alignment);
3543 CSEMap.InsertNode(N, IP);
3544 AllNodes.push_back(N);
3545 return SDValue(N, 0);
3548 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3549 /// Allowed to return something different (and simpler) if Simplify is true.
3550 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps) {
3554 SmallVector<MVT, 4> VTs;
3555 VTs.reserve(NumOps);
3556 for (unsigned i = 0; i < NumOps; ++i)
3557 VTs.push_back(Ops[i].getValueType());
3558 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3561 /// DebugLoc-aware version.
3562 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3567 SmallVector<MVT, 4> VTs;
3568 VTs.reserve(NumOps);
3569 for (unsigned i = 0; i < NumOps; ++i)
3570 VTs.push_back(Ops[i].getValueType());
3571 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3576 SelectionDAG::getMemIntrinsicNode(unsigned Opcode,
3577 const MVT *VTs, unsigned NumVTs,
3578 const SDValue *Ops, unsigned NumOps,
3579 MVT MemVT, const Value *srcValue, int SVOff,
3580 unsigned Align, bool Vol,
3581 bool ReadMem, bool WriteMem) {
3582 return getMemIntrinsicNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps,
3583 MemVT, srcValue, SVOff, Align, Vol,
3588 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3589 const MVT *VTs, unsigned NumVTs,
3590 const SDValue *Ops, unsigned NumOps,
3591 MVT MemVT, const Value *srcValue, int SVOff,
3592 unsigned Align, bool Vol,
3593 bool ReadMem, bool WriteMem) {
3594 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3595 MemVT, srcValue, SVOff, Align, Vol,
3600 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDVTList VTList,
3601 const SDValue *Ops, unsigned NumOps,
3602 MVT MemVT, const Value *srcValue, int SVOff,
3603 unsigned Align, bool Vol,
3604 bool ReadMem, bool WriteMem) {
3605 // Memoize the node unless it returns a flag.
3606 MemIntrinsicSDNode *N;
3607 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3608 FoldingSetNodeID ID;
3609 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3611 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3612 return SDValue(E, 0);
3614 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3615 new (N) MemIntrinsicSDNode(Opcode, VTList, Ops, NumOps, MemVT,
3616 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3617 CSEMap.InsertNode(N, IP);
3619 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3620 new (N) MemIntrinsicSDNode(Opcode, VTList, Ops, NumOps, MemVT,
3621 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3623 AllNodes.push_back(N);
3624 return SDValue(N, 0);
3628 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3629 const SDValue *Ops, unsigned NumOps,
3630 MVT MemVT, const Value *srcValue, int SVOff,
3631 unsigned Align, bool Vol,
3632 bool ReadMem, bool WriteMem) {
3633 // Memoize the node unless it returns a flag.
3634 MemIntrinsicSDNode *N;
3635 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3636 FoldingSetNodeID ID;
3637 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3639 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3640 return SDValue(E, 0);
3642 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3643 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
3644 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3645 CSEMap.InsertNode(N, IP);
3647 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3648 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
3649 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3651 AllNodes.push_back(N);
3652 return SDValue(N, 0);
3656 SelectionDAG::getCall(unsigned CallingConv, bool IsVarArgs, bool IsTailCall,
3657 bool IsInreg, SDVTList VTs,
3658 const SDValue *Operands, unsigned NumOperands) {
3659 // Do not include isTailCall in the folding set profile.
3660 FoldingSetNodeID ID;
3661 AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
3662 ID.AddInteger(CallingConv);
3663 ID.AddInteger(IsVarArgs);
3665 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3666 // Instead of including isTailCall in the folding set, we just
3667 // set the flag of the existing node.
3669 cast<CallSDNode>(E)->setNotTailCall();
3670 return SDValue(E, 0);
3672 SDNode *N = NodeAllocator.Allocate<CallSDNode>();
3673 new (N) CallSDNode(CallingConv, IsVarArgs, IsTailCall, IsInreg,
3674 VTs, Operands, NumOperands);
3675 CSEMap.InsertNode(N, IP);
3676 AllNodes.push_back(N);
3677 return SDValue(N, 0);
3681 SelectionDAG::getCall(unsigned CallingConv, DebugLoc dl, bool IsVarArgs,
3682 bool IsTailCall, bool IsInreg, SDVTList VTs,
3683 const SDValue *Operands, unsigned NumOperands) {
3684 // Do not include isTailCall in the folding set profile.
3685 FoldingSetNodeID ID;
3686 AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
3687 ID.AddInteger(CallingConv);
3688 ID.AddInteger(IsVarArgs);
3690 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3691 // Instead of including isTailCall in the folding set, we just
3692 // set the flag of the existing node.
3694 cast<CallSDNode>(E)->setNotTailCall();
3695 return SDValue(E, 0);
3697 SDNode *N = NodeAllocator.Allocate<CallSDNode>();
3698 new (N) CallSDNode(CallingConv, dl, IsVarArgs, IsTailCall, IsInreg,
3699 VTs, Operands, NumOperands);
3700 CSEMap.InsertNode(N, IP);
3701 AllNodes.push_back(N);
3702 return SDValue(N, 0);
3706 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3707 MVT VT, SDValue Chain,
3708 SDValue Ptr, SDValue Offset,
3709 const Value *SV, int SVOffset, MVT EVT,
3710 bool isVolatile, unsigned Alignment) {
3711 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3712 Alignment = getMVTAlignment(VT);
3715 ExtType = ISD::NON_EXTLOAD;
3716 } else if (ExtType == ISD::NON_EXTLOAD) {
3717 assert(VT == EVT && "Non-extending load from different memory type!");
3721 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3722 "Invalid vector extload!");
3724 assert(EVT.bitsLT(VT) &&
3725 "Should only be an extending load, not truncating!");
3726 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3727 "Cannot sign/zero extend a FP/Vector load!");
3728 assert(VT.isInteger() == EVT.isInteger() &&
3729 "Cannot convert from FP to Int or Int -> FP!");
3732 bool Indexed = AM != ISD::UNINDEXED;
3733 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3734 "Unindexed load with an offset!");
3736 SDVTList VTs = Indexed ?
3737 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3738 SDValue Ops[] = { Chain, Ptr, Offset };
3739 FoldingSetNodeID ID;
3740 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3741 ID.AddInteger(EVT.getRawBits());
3742 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, isVolatile, Alignment));
3744 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3745 return SDValue(E, 0);
3746 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3747 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3748 Alignment, isVolatile);
3749 CSEMap.InsertNode(N, IP);
3750 AllNodes.push_back(N);
3751 return SDValue(N, 0);
3755 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3756 ISD::LoadExtType ExtType, MVT VT, SDValue Chain,
3757 SDValue Ptr, SDValue Offset,
3758 const Value *SV, int SVOffset, MVT EVT,
3759 bool isVolatile, unsigned Alignment) {
3760 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3761 Alignment = getMVTAlignment(VT);
3764 ExtType = ISD::NON_EXTLOAD;
3765 } else if (ExtType == ISD::NON_EXTLOAD) {
3766 assert(VT == EVT && "Non-extending load from different memory type!");
3770 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3771 "Invalid vector extload!");
3773 assert(EVT.bitsLT(VT) &&
3774 "Should only be an extending load, not truncating!");
3775 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3776 "Cannot sign/zero extend a FP/Vector load!");
3777 assert(VT.isInteger() == EVT.isInteger() &&
3778 "Cannot convert from FP to Int or Int -> FP!");
3781 bool Indexed = AM != ISD::UNINDEXED;
3782 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3783 "Unindexed load with an offset!");
3785 SDVTList VTs = Indexed ?
3786 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3787 SDValue Ops[] = { Chain, Ptr, Offset };
3788 FoldingSetNodeID ID;
3789 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3790 ID.AddInteger(EVT.getRawBits());
3791 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, isVolatile, Alignment));
3793 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3794 return SDValue(E, 0);
3795 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3796 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, EVT, SV, SVOffset,
3797 Alignment, isVolatile);
3798 CSEMap.InsertNode(N, IP);
3799 AllNodes.push_back(N);
3800 return SDValue(N, 0);
3803 SDValue SelectionDAG::getLoad(MVT VT,
3804 SDValue Chain, SDValue Ptr,
3805 const Value *SV, int SVOffset,
3806 bool isVolatile, unsigned Alignment) {
3807 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3808 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3809 SV, SVOffset, VT, isVolatile, Alignment);
3812 SDValue SelectionDAG::getLoad(MVT VT, DebugLoc dl,
3813 SDValue Chain, SDValue Ptr,
3814 const Value *SV, int SVOffset,
3815 bool isVolatile, unsigned Alignment) {
3816 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3817 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3818 SV, SVOffset, VT, isVolatile, Alignment);
3821 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3822 SDValue Chain, SDValue Ptr,
3824 int SVOffset, MVT EVT,
3825 bool isVolatile, unsigned Alignment) {
3826 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3827 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3828 SV, SVOffset, EVT, isVolatile, Alignment);
3831 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, MVT VT,
3832 SDValue Chain, SDValue Ptr,
3834 int SVOffset, MVT EVT,
3835 bool isVolatile, unsigned Alignment) {
3836 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3837 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3838 SV, SVOffset, EVT, isVolatile, Alignment);
3842 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDValue Base,
3843 SDValue Offset, ISD::MemIndexedMode AM) {
3844 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3845 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3846 "Load is already a indexed load!");
3847 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3848 LD->getChain(), Base, Offset, LD->getSrcValue(),
3849 LD->getSrcValueOffset(), LD->getMemoryVT(),
3850 LD->isVolatile(), LD->getAlignment());
3854 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3855 SDValue Offset, ISD::MemIndexedMode AM) {
3856 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3857 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3858 "Load is already a indexed load!");
3859 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3860 LD->getChain(), Base, Offset, LD->getSrcValue(),
3861 LD->getSrcValueOffset(), LD->getMemoryVT(),
3862 LD->isVolatile(), LD->getAlignment());
3865 SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
3866 SDValue Ptr, const Value *SV, int SVOffset,
3867 bool isVolatile, unsigned Alignment) {
3868 MVT VT = Val.getValueType();
3870 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3871 Alignment = getMVTAlignment(VT);
3873 SDVTList VTs = getVTList(MVT::Other);
3874 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3875 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3876 FoldingSetNodeID ID;
3877 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3878 ID.AddInteger(VT.getRawBits());
3879 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED,
3880 isVolatile, Alignment));
3882 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3883 return SDValue(E, 0);
3884 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3885 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3886 VT, SV, SVOffset, Alignment, isVolatile);
3887 CSEMap.InsertNode(N, IP);
3888 AllNodes.push_back(N);
3889 return SDValue(N, 0);
3892 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3893 SDValue Ptr, const Value *SV, int SVOffset,
3894 bool isVolatile, unsigned Alignment) {
3895 MVT VT = Val.getValueType();
3897 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3898 Alignment = getMVTAlignment(VT);
3900 SDVTList VTs = getVTList(MVT::Other);
3901 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3902 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3903 FoldingSetNodeID ID;
3904 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3905 ID.AddInteger(VT.getRawBits());
3906 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED,
3907 isVolatile, Alignment));
3909 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3910 return SDValue(E, 0);
3911 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3912 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false,
3913 VT, SV, SVOffset, Alignment, isVolatile);
3914 CSEMap.InsertNode(N, IP);
3915 AllNodes.push_back(N);
3916 return SDValue(N, 0);
3919 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDValue Val,
3920 SDValue Ptr, const Value *SV,
3921 int SVOffset, MVT SVT,
3922 bool isVolatile, unsigned Alignment) {
3923 MVT VT = Val.getValueType();
3926 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3928 assert(VT.bitsGT(SVT) && "Not a truncation?");
3929 assert(VT.isInteger() == SVT.isInteger() &&
3930 "Can't do FP-INT conversion!");
3932 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3933 Alignment = getMVTAlignment(VT);
3935 SDVTList VTs = getVTList(MVT::Other);
3936 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3937 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3938 FoldingSetNodeID ID;
3939 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3940 ID.AddInteger(SVT.getRawBits());
3941 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED,
3942 isVolatile, Alignment));
3944 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3945 return SDValue(E, 0);
3946 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3947 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3948 SVT, SV, SVOffset, Alignment, isVolatile);
3949 CSEMap.InsertNode(N, IP);
3950 AllNodes.push_back(N);
3951 return SDValue(N, 0);
3954 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3955 SDValue Ptr, const Value *SV,
3956 int SVOffset, MVT SVT,
3957 bool isVolatile, unsigned Alignment) {
3958 MVT VT = Val.getValueType();
3961 return getStore(Chain, dl, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3963 assert(VT.bitsGT(SVT) && "Not a truncation?");
3964 assert(VT.isInteger() == SVT.isInteger() &&
3965 "Can't do FP-INT conversion!");
3967 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3968 Alignment = getMVTAlignment(VT);
3970 SDVTList VTs = getVTList(MVT::Other);
3971 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3972 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3973 FoldingSetNodeID ID;
3974 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3975 ID.AddInteger(SVT.getRawBits());
3976 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED,
3977 isVolatile, Alignment));
3979 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3980 return SDValue(E, 0);
3981 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3982 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true,
3983 SVT, SV, SVOffset, Alignment, isVolatile);
3984 CSEMap.InsertNode(N, IP);
3985 AllNodes.push_back(N);
3986 return SDValue(N, 0);
3990 SelectionDAG::getIndexedStore(SDValue OrigStore, SDValue Base,
3991 SDValue Offset, ISD::MemIndexedMode AM) {
3992 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3993 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3994 "Store is already a indexed store!");
3995 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3996 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3997 FoldingSetNodeID ID;
3998 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3999 ID.AddInteger(ST->getMemoryVT().getRawBits());
4000 ID.AddInteger(ST->getRawSubclassData());
4002 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4003 return SDValue(E, 0);
4004 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
4005 new (N) StoreSDNode(Ops, VTs, AM,
4006 ST->isTruncatingStore(), ST->getMemoryVT(),
4007 ST->getSrcValue(), ST->getSrcValueOffset(),
4008 ST->getAlignment(), ST->isVolatile());
4009 CSEMap.InsertNode(N, IP);
4010 AllNodes.push_back(N);
4011 return SDValue(N, 0);
4015 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
4016 SDValue Offset, ISD::MemIndexedMode AM) {
4017 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4018 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4019 "Store is already a indexed store!");
4020 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4021 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4022 FoldingSetNodeID ID;
4023 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4024 ID.AddInteger(ST->getMemoryVT().getRawBits());
4025 ID.AddInteger(ST->getRawSubclassData());
4027 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4028 return SDValue(E, 0);
4029 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
4030 new (N) StoreSDNode(Ops, dl, VTs, AM,
4031 ST->isTruncatingStore(), ST->getMemoryVT(),
4032 ST->getSrcValue(), ST->getSrcValueOffset(),
4033 ST->getAlignment(), ST->isVolatile());
4034 CSEMap.InsertNode(N, IP);
4035 AllNodes.push_back(N);
4036 return SDValue(N, 0);
4039 SDValue SelectionDAG::getVAArg(MVT VT,
4040 SDValue Chain, SDValue Ptr,
4042 SDValue Ops[] = { Chain, Ptr, SV };
4043 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
4046 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
4047 const SDUse *Ops, unsigned NumOps) {
4048 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Ops, NumOps);
4051 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
4052 const SDUse *Ops, unsigned NumOps) {
4054 case 0: return getNode(Opcode, DL, VT);
4055 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4056 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4057 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4061 // Copy from an SDUse array into an SDValue array for use with
4062 // the regular getNode logic.
4063 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4064 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4067 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
4068 const SDValue *Ops, unsigned NumOps) {
4069 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Ops, NumOps);
4072 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
4073 const SDValue *Ops, unsigned NumOps) {
4075 case 0: return getNode(Opcode, DL, VT);
4076 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4077 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4078 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4084 case ISD::SELECT_CC: {
4085 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4086 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4087 "LHS and RHS of condition must have same type!");
4088 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4089 "True and False arms of SelectCC must have same type!");
4090 assert(Ops[2].getValueType() == VT &&
4091 "select_cc node must be of same type as true and false value!");
4095 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4096 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4097 "LHS/RHS of comparison should match types!");
4104 SDVTList VTs = getVTList(VT);
4106 if (VT != MVT::Flag) {
4107 FoldingSetNodeID ID;
4108 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4111 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4112 return SDValue(E, 0);
4114 N = NodeAllocator.Allocate<SDNode>();
4115 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4116 CSEMap.InsertNode(N, IP);
4118 N = NodeAllocator.Allocate<SDNode>();
4119 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4122 AllNodes.push_back(N);
4126 return SDValue(N, 0);
4129 SDValue SelectionDAG::getNode(unsigned Opcode,
4130 const std::vector<MVT> &ResultTys,
4131 const SDValue *Ops, unsigned NumOps) {
4132 return getNode(Opcode, DebugLoc::getUnknownLoc(), ResultTys, Ops, NumOps);
4135 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4136 const std::vector<MVT> &ResultTys,
4137 const SDValue *Ops, unsigned NumOps) {
4138 return getNode(Opcode, DL, getNodeValueTypes(ResultTys), ResultTys.size(),
4142 SDValue SelectionDAG::getNode(unsigned Opcode,
4143 const MVT *VTs, unsigned NumVTs,
4144 const SDValue *Ops, unsigned NumOps) {
4145 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTs, NumVTs, Ops, NumOps);
4148 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4149 const MVT *VTs, unsigned NumVTs,
4150 const SDValue *Ops, unsigned NumOps) {
4152 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4153 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4156 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4157 const SDValue *Ops, unsigned NumOps) {
4158 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, Ops, NumOps);
4161 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4162 const SDValue *Ops, unsigned NumOps) {
4163 if (VTList.NumVTs == 1)
4164 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4167 // FIXME: figure out how to safely handle things like
4168 // int foo(int x) { return 1 << (x & 255); }
4169 // int bar() { return foo(256); }
4171 case ISD::SRA_PARTS:
4172 case ISD::SRL_PARTS:
4173 case ISD::SHL_PARTS:
4174 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4175 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4176 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4177 else if (N3.getOpcode() == ISD::AND)
4178 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4179 // If the and is only masking out bits that cannot effect the shift,
4180 // eliminate the and.
4181 unsigned NumBits = VT.getSizeInBits()*2;
4182 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4183 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4189 // Memoize the node unless it returns a flag.
4191 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4192 FoldingSetNodeID ID;
4193 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4195 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4196 return SDValue(E, 0);
4198 N = NodeAllocator.Allocate<UnarySDNode>();
4199 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4200 } else if (NumOps == 2) {
4201 N = NodeAllocator.Allocate<BinarySDNode>();
4202 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4203 } else if (NumOps == 3) {
4204 N = NodeAllocator.Allocate<TernarySDNode>();
4205 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4207 N = NodeAllocator.Allocate<SDNode>();
4208 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4210 CSEMap.InsertNode(N, IP);
4213 N = NodeAllocator.Allocate<UnarySDNode>();
4214 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4215 } else if (NumOps == 2) {
4216 N = NodeAllocator.Allocate<BinarySDNode>();
4217 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4218 } else if (NumOps == 3) {
4219 N = NodeAllocator.Allocate<TernarySDNode>();
4220 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4222 N = NodeAllocator.Allocate<SDNode>();
4223 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4226 AllNodes.push_back(N);
4230 return SDValue(N, 0);
4233 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
4234 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList);
4237 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4238 return getNode(Opcode, DL, VTList, 0, 0);
4241 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4243 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1);
4246 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4248 SDValue Ops[] = { N1 };
4249 return getNode(Opcode, DL, VTList, Ops, 1);
4252 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4253 SDValue N1, SDValue N2) {
4254 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2);
4257 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4258 SDValue N1, SDValue N2) {
4259 SDValue Ops[] = { N1, N2 };
4260 return getNode(Opcode, DL, VTList, Ops, 2);
4263 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4264 SDValue N1, SDValue N2, SDValue N3) {
4265 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3);
4268 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4269 SDValue N1, SDValue N2, SDValue N3) {
4270 SDValue Ops[] = { N1, N2, N3 };
4271 return getNode(Opcode, DL, VTList, Ops, 3);
4274 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4275 SDValue N1, SDValue N2, SDValue N3,
4277 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3, N4);
4280 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4281 SDValue N1, SDValue N2, SDValue N3,
4283 SDValue Ops[] = { N1, N2, N3, N4 };
4284 return getNode(Opcode, DL, VTList, Ops, 4);
4287 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4288 SDValue N1, SDValue N2, SDValue N3,
4289 SDValue N4, SDValue N5) {
4290 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3, N4, N5);
4293 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4294 SDValue N1, SDValue N2, SDValue N3,
4295 SDValue N4, SDValue N5) {
4296 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4297 return getNode(Opcode, DL, VTList, Ops, 5);
4300 SDVTList SelectionDAG::getVTList(MVT VT) {
4301 return makeVTList(SDNode::getValueTypeList(VT), 1);
4304 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
4305 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4306 E = VTList.rend(); I != E; ++I)
4307 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4310 MVT *Array = Allocator.Allocate<MVT>(2);
4313 SDVTList Result = makeVTList(Array, 2);
4314 VTList.push_back(Result);
4318 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
4319 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4320 E = VTList.rend(); I != E; ++I)
4321 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4325 MVT *Array = Allocator.Allocate<MVT>(3);
4329 SDVTList Result = makeVTList(Array, 3);
4330 VTList.push_back(Result);
4334 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3, MVT VT4) {
4335 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4336 E = VTList.rend(); I != E; ++I)
4337 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4338 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4341 MVT *Array = Allocator.Allocate<MVT>(3);
4346 SDVTList Result = makeVTList(Array, 4);
4347 VTList.push_back(Result);
4351 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
4353 case 0: assert(0 && "Cannot have nodes without results!");
4354 case 1: return getVTList(VTs[0]);
4355 case 2: return getVTList(VTs[0], VTs[1]);
4356 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4360 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4361 E = VTList.rend(); I != E; ++I) {
4362 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4365 bool NoMatch = false;
4366 for (unsigned i = 2; i != NumVTs; ++i)
4367 if (VTs[i] != I->VTs[i]) {
4375 MVT *Array = Allocator.Allocate<MVT>(NumVTs);
4376 std::copy(VTs, VTs+NumVTs, Array);
4377 SDVTList Result = makeVTList(Array, NumVTs);
4378 VTList.push_back(Result);
4383 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4384 /// specified operands. If the resultant node already exists in the DAG,
4385 /// this does not modify the specified node, instead it returns the node that
4386 /// already exists. If the resultant node does not exist in the DAG, the
4387 /// input node is returned. As a degenerate case, if you specify the same
4388 /// input operands as the node already has, the input node is returned.
4389 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4390 SDNode *N = InN.getNode();
4391 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4393 // Check to see if there is no change.
4394 if (Op == N->getOperand(0)) return InN;
4396 // See if the modified node already exists.
4397 void *InsertPos = 0;
4398 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4399 return SDValue(Existing, InN.getResNo());
4401 // Nope it doesn't. Remove the node from its current place in the maps.
4403 if (!RemoveNodeFromCSEMaps(N))
4406 // Now we update the operands.
4407 N->OperandList[0].set(Op);
4409 // If this gets put into a CSE map, add it.
4410 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4414 SDValue SelectionDAG::
4415 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4416 SDNode *N = InN.getNode();
4417 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4419 // Check to see if there is no change.
4420 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4421 return InN; // No operands changed, just return the input node.
4423 // See if the modified node already exists.
4424 void *InsertPos = 0;
4425 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4426 return SDValue(Existing, InN.getResNo());
4428 // Nope it doesn't. Remove the node from its current place in the maps.
4430 if (!RemoveNodeFromCSEMaps(N))
4433 // Now we update the operands.
4434 if (N->OperandList[0] != Op1)
4435 N->OperandList[0].set(Op1);
4436 if (N->OperandList[1] != Op2)
4437 N->OperandList[1].set(Op2);
4439 // If this gets put into a CSE map, add it.
4440 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4444 SDValue SelectionDAG::
4445 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4446 SDValue Ops[] = { Op1, Op2, Op3 };
4447 return UpdateNodeOperands(N, Ops, 3);
4450 SDValue SelectionDAG::
4451 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4452 SDValue Op3, SDValue Op4) {
4453 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4454 return UpdateNodeOperands(N, Ops, 4);
4457 SDValue SelectionDAG::
4458 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4459 SDValue Op3, SDValue Op4, SDValue Op5) {
4460 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4461 return UpdateNodeOperands(N, Ops, 5);
4464 SDValue SelectionDAG::
4465 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4466 SDNode *N = InN.getNode();
4467 assert(N->getNumOperands() == NumOps &&
4468 "Update with wrong number of operands");
4470 // Check to see if there is no change.
4471 bool AnyChange = false;
4472 for (unsigned i = 0; i != NumOps; ++i) {
4473 if (Ops[i] != N->getOperand(i)) {
4479 // No operands changed, just return the input node.
4480 if (!AnyChange) return InN;
4482 // See if the modified node already exists.
4483 void *InsertPos = 0;
4484 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4485 return SDValue(Existing, InN.getResNo());
4487 // Nope it doesn't. Remove the node from its current place in the maps.
4489 if (!RemoveNodeFromCSEMaps(N))
4492 // Now we update the operands.
4493 for (unsigned i = 0; i != NumOps; ++i)
4494 if (N->OperandList[i] != Ops[i])
4495 N->OperandList[i].set(Ops[i]);
4497 // If this gets put into a CSE map, add it.
4498 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4502 /// DropOperands - Release the operands and set this node to have
4504 void SDNode::DropOperands() {
4505 // Unlike the code in MorphNodeTo that does this, we don't need to
4506 // watch for dead nodes here.
4507 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4513 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4516 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4518 SDVTList VTs = getVTList(VT);
4519 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4522 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4523 MVT VT, SDValue Op1) {
4524 SDVTList VTs = getVTList(VT);
4525 SDValue Ops[] = { Op1 };
4526 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4529 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4530 MVT VT, SDValue Op1,
4532 SDVTList VTs = getVTList(VT);
4533 SDValue Ops[] = { Op1, Op2 };
4534 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4537 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4538 MVT VT, SDValue Op1,
4539 SDValue Op2, SDValue Op3) {
4540 SDVTList VTs = getVTList(VT);
4541 SDValue Ops[] = { Op1, Op2, Op3 };
4542 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4545 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4546 MVT VT, const SDValue *Ops,
4548 SDVTList VTs = getVTList(VT);
4549 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4552 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4553 MVT VT1, MVT VT2, const SDValue *Ops,
4555 SDVTList VTs = getVTList(VT1, VT2);
4556 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4559 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4561 SDVTList VTs = getVTList(VT1, VT2);
4562 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4565 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4566 MVT VT1, MVT VT2, MVT VT3,
4567 const SDValue *Ops, unsigned NumOps) {
4568 SDVTList VTs = getVTList(VT1, VT2, VT3);
4569 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4572 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4573 MVT VT1, MVT VT2, MVT VT3, MVT VT4,
4574 const SDValue *Ops, unsigned NumOps) {
4575 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4576 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4579 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4582 SDVTList VTs = getVTList(VT1, VT2);
4583 SDValue Ops[] = { Op1 };
4584 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4587 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4589 SDValue Op1, SDValue Op2) {
4590 SDVTList VTs = getVTList(VT1, VT2);
4591 SDValue Ops[] = { Op1, Op2 };
4592 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4595 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4597 SDValue Op1, SDValue Op2,
4599 SDVTList VTs = getVTList(VT1, VT2);
4600 SDValue Ops[] = { Op1, Op2, Op3 };
4601 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4604 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4605 MVT VT1, MVT VT2, MVT VT3,
4606 SDValue Op1, SDValue Op2,
4608 SDVTList VTs = getVTList(VT1, VT2, VT3);
4609 SDValue Ops[] = { Op1, Op2, Op3 };
4610 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4613 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4614 SDVTList VTs, const SDValue *Ops,
4616 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4619 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4621 SDVTList VTs = getVTList(VT);
4622 return MorphNodeTo(N, Opc, VTs, 0, 0);
4625 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4626 MVT VT, SDValue Op1) {
4627 SDVTList VTs = getVTList(VT);
4628 SDValue Ops[] = { Op1 };
4629 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4632 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4633 MVT VT, SDValue Op1,
4635 SDVTList VTs = getVTList(VT);
4636 SDValue Ops[] = { Op1, Op2 };
4637 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4640 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4641 MVT VT, SDValue Op1,
4642 SDValue Op2, SDValue Op3) {
4643 SDVTList VTs = getVTList(VT);
4644 SDValue Ops[] = { Op1, Op2, Op3 };
4645 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4648 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4649 MVT VT, const SDValue *Ops,
4651 SDVTList VTs = getVTList(VT);
4652 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4655 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4656 MVT VT1, MVT VT2, const SDValue *Ops,
4658 SDVTList VTs = getVTList(VT1, VT2);
4659 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4662 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4664 SDVTList VTs = getVTList(VT1, VT2);
4665 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4668 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4669 MVT VT1, MVT VT2, MVT VT3,
4670 const SDValue *Ops, unsigned NumOps) {
4671 SDVTList VTs = getVTList(VT1, VT2, VT3);
4672 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4675 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4678 SDVTList VTs = getVTList(VT1, VT2);
4679 SDValue Ops[] = { Op1 };
4680 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4683 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4685 SDValue Op1, SDValue Op2) {
4686 SDVTList VTs = getVTList(VT1, VT2);
4687 SDValue Ops[] = { Op1, Op2 };
4688 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4691 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4693 SDValue Op1, SDValue Op2,
4695 SDVTList VTs = getVTList(VT1, VT2);
4696 SDValue Ops[] = { Op1, Op2, Op3 };
4697 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4700 /// MorphNodeTo - These *mutate* the specified node to have the specified
4701 /// return type, opcode, and operands.
4703 /// Note that MorphNodeTo returns the resultant node. If there is already a
4704 /// node of the specified opcode and operands, it returns that node instead of
4705 /// the current one.
4707 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4708 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4709 /// node, and because it doesn't require CSE recalculation for any of
4710 /// the node's users.
4712 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4713 SDVTList VTs, const SDValue *Ops,
4715 // If an identical node already exists, use it.
4717 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4718 FoldingSetNodeID ID;
4719 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4720 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4724 if (!RemoveNodeFromCSEMaps(N))
4727 // Start the morphing.
4729 N->ValueList = VTs.VTs;
4730 N->NumValues = VTs.NumVTs;
4732 // Clear the operands list, updating used nodes to remove this from their
4733 // use list. Keep track of any operands that become dead as a result.
4734 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4735 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4737 SDNode *Used = Use.getNode();
4739 if (Used->use_empty())
4740 DeadNodeSet.insert(Used);
4743 // If NumOps is larger than the # of operands we currently have, reallocate
4744 // the operand list.
4745 if (NumOps > N->NumOperands) {
4746 if (N->OperandsNeedDelete)
4747 delete[] N->OperandList;
4749 if (N->isMachineOpcode()) {
4750 // We're creating a final node that will live unmorphed for the
4751 // remainder of the current SelectionDAG iteration, so we can allocate
4752 // the operands directly out of a pool with no recycling metadata.
4753 N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
4754 N->OperandsNeedDelete = false;
4756 N->OperandList = new SDUse[NumOps];
4757 N->OperandsNeedDelete = true;
4761 // Assign the new operands.
4762 N->NumOperands = NumOps;
4763 for (unsigned i = 0, e = NumOps; i != e; ++i) {
4764 N->OperandList[i].setUser(N);
4765 N->OperandList[i].setInitial(Ops[i]);
4768 // Delete any nodes that are still dead after adding the uses for the
4770 SmallVector<SDNode *, 16> DeadNodes;
4771 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4772 E = DeadNodeSet.end(); I != E; ++I)
4773 if ((*I)->use_empty())
4774 DeadNodes.push_back(*I);
4775 RemoveDeadNodes(DeadNodes);
4778 CSEMap.InsertNode(N, IP); // Memoize the new node.
4783 /// getTargetNode - These are used for target selectors to create a new node
4784 /// with specified return type(s), target opcode, and operands.
4786 /// Note that getTargetNode returns the resultant node. If there is already a
4787 /// node of the specified opcode and operands, it returns that node instead of
4788 /// the current one.
4789 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
4790 return getNode(~Opcode, VT).getNode();
4792 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT) {
4793 return getNode(~Opcode, dl, VT).getNode();
4796 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
4797 return getNode(~Opcode, VT, Op1).getNode();
4799 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4801 return getNode(~Opcode, dl, VT, Op1).getNode();
4804 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4805 SDValue Op1, SDValue Op2) {
4806 return getNode(~Opcode, VT, Op1, Op2).getNode();
4808 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4809 SDValue Op1, SDValue Op2) {
4810 return getNode(~Opcode, dl, VT, Op1, Op2).getNode();
4813 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4814 SDValue Op1, SDValue Op2,
4816 return getNode(~Opcode, VT, Op1, Op2, Op3).getNode();
4818 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4819 SDValue Op1, SDValue Op2,
4821 return getNode(~Opcode, dl, VT, Op1, Op2, Op3).getNode();
4824 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4825 const SDValue *Ops, unsigned NumOps) {
4826 return getNode(~Opcode, VT, Ops, NumOps).getNode();
4828 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4829 const SDValue *Ops, unsigned NumOps) {
4830 return getNode(~Opcode, dl, VT, Ops, NumOps).getNode();
4833 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
4834 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4836 return getNode(~Opcode, VTs, 2, &Op, 0).getNode();
4838 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4840 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4842 return getNode(~Opcode, dl, VTs, 2, &Op, 0).getNode();
4845 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4846 MVT VT2, SDValue Op1) {
4847 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4848 return getNode(~Opcode, VTs, 2, &Op1, 1).getNode();
4850 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4851 MVT VT2, SDValue Op1) {
4852 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4853 return getNode(~Opcode, dl, VTs, 2, &Op1, 1).getNode();
4856 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4857 MVT VT2, SDValue Op1,
4859 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4860 SDValue Ops[] = { Op1, Op2 };
4861 return getNode(~Opcode, VTs, 2, Ops, 2).getNode();
4863 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4864 MVT VT2, SDValue Op1,
4866 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4867 SDValue Ops[] = { Op1, Op2 };
4868 return getNode(~Opcode, dl, VTs, 2, Ops, 2).getNode();
4871 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4872 MVT VT2, SDValue Op1,
4873 SDValue Op2, SDValue Op3) {
4874 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4875 SDValue Ops[] = { Op1, Op2, Op3 };
4876 return getNode(~Opcode, VTs, 2, Ops, 3).getNode();
4878 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4879 MVT VT2, SDValue Op1,
4880 SDValue Op2, SDValue Op3) {
4881 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4882 SDValue Ops[] = { Op1, Op2, Op3 };
4883 return getNode(~Opcode, dl, VTs, 2, Ops, 3).getNode();
4886 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
4887 const SDValue *Ops, unsigned NumOps) {
4888 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4889 return getNode(~Opcode, VTs, 2, Ops, NumOps).getNode();
4891 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4893 const SDValue *Ops, unsigned NumOps) {
4894 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4895 return getNode(~Opcode, dl, VTs, 2, Ops, NumOps).getNode();
4898 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4899 SDValue Op1, SDValue Op2) {
4900 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4901 SDValue Ops[] = { Op1, Op2 };
4902 return getNode(~Opcode, VTs, 3, Ops, 2).getNode();
4904 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4905 MVT VT1, MVT VT2, MVT VT3,
4906 SDValue Op1, SDValue Op2) {
4907 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4908 SDValue Ops[] = { Op1, Op2 };
4909 return getNode(~Opcode, dl, VTs, 3, Ops, 2).getNode();
4912 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4913 SDValue Op1, SDValue Op2,
4915 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4916 SDValue Ops[] = { Op1, Op2, Op3 };
4917 return getNode(~Opcode, VTs, 3, Ops, 3).getNode();
4919 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4920 MVT VT1, MVT VT2, MVT VT3,
4921 SDValue Op1, SDValue Op2,
4923 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4924 SDValue Ops[] = { Op1, Op2, Op3 };
4925 return getNode(~Opcode, dl, VTs, 3, Ops, 3).getNode();
4928 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4929 const SDValue *Ops, unsigned NumOps) {
4930 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4931 return getNode(~Opcode, VTs, 3, Ops, NumOps).getNode();
4933 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4934 MVT VT1, MVT VT2, MVT VT3,
4935 const SDValue *Ops, unsigned NumOps) {
4936 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4937 return getNode(~Opcode, dl, VTs, 3, Ops, NumOps).getNode();
4940 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4941 MVT VT2, MVT VT3, MVT VT4,
4942 const SDValue *Ops, unsigned NumOps) {
4943 std::vector<MVT> VTList;
4944 VTList.push_back(VT1);
4945 VTList.push_back(VT2);
4946 VTList.push_back(VT3);
4947 VTList.push_back(VT4);
4948 const MVT *VTs = getNodeValueTypes(VTList);
4949 return getNode(~Opcode, VTs, 4, Ops, NumOps).getNode();
4951 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4952 MVT VT2, MVT VT3, MVT VT4,
4953 const SDValue *Ops, unsigned NumOps) {
4954 std::vector<MVT> VTList;
4955 VTList.push_back(VT1);
4956 VTList.push_back(VT2);
4957 VTList.push_back(VT3);
4958 VTList.push_back(VT4);
4959 const MVT *VTs = getNodeValueTypes(VTList);
4960 return getNode(~Opcode, dl, VTs, 4, Ops, NumOps).getNode();
4963 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
4964 const std::vector<MVT> &ResultTys,
4965 const SDValue *Ops, unsigned NumOps) {
4966 const MVT *VTs = getNodeValueTypes(ResultTys);
4967 return getNode(~Opcode, VTs, ResultTys.size(),
4968 Ops, NumOps).getNode();
4970 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4971 const std::vector<MVT> &ResultTys,
4972 const SDValue *Ops, unsigned NumOps) {
4973 const MVT *VTs = getNodeValueTypes(ResultTys);
4974 return getNode(~Opcode, dl, VTs, ResultTys.size(),
4975 Ops, NumOps).getNode();
4978 /// getNodeIfExists - Get the specified node if it's already available, or
4979 /// else return NULL.
4980 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4981 const SDValue *Ops, unsigned NumOps) {
4982 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4983 FoldingSetNodeID ID;
4984 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4986 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4992 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4993 /// This can cause recursive merging of nodes in the DAG.
4995 /// This version assumes From has a single result value.
4997 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4998 DAGUpdateListener *UpdateListener) {
4999 SDNode *From = FromN.getNode();
5000 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
5001 "Cannot replace with this method!");
5002 assert(From != To.getNode() && "Cannot replace uses of with self");
5004 // Iterate over all the existing uses of From. New uses will be added
5005 // to the beginning of the use list, which we avoid visiting.
5006 // This specifically avoids visiting uses of From that arise while the
5007 // replacement is happening, because any such uses would be the result
5008 // of CSE: If an existing node looks like From after one of its operands
5009 // is replaced by To, we don't want to replace of all its users with To
5010 // too. See PR3018 for more info.
5011 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5015 // This node is about to morph, remove its old self from the CSE maps.
5016 RemoveNodeFromCSEMaps(User);
5018 // A user can appear in a use list multiple times, and when this
5019 // happens the uses are usually next to each other in the list.
5020 // To help reduce the number of CSE recomputations, process all
5021 // the uses of this user that we can find this way.
5023 SDUse &Use = UI.getUse();
5026 } while (UI != UE && *UI == User);
5028 // Now that we have modified User, add it back to the CSE maps. If it
5029 // already exists there, recursively merge the results together.
5030 AddModifiedNodeToCSEMaps(User, UpdateListener);
5034 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5035 /// This can cause recursive merging of nodes in the DAG.
5037 /// This version assumes From/To have matching types and numbers of result
5040 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
5041 DAGUpdateListener *UpdateListener) {
5042 assert(From->getVTList().VTs == To->getVTList().VTs &&
5043 From->getNumValues() == To->getNumValues() &&
5044 "Cannot use this version of ReplaceAllUsesWith!");
5046 // Handle the trivial case.
5050 // Iterate over just the existing users of From. See the comments in
5051 // the ReplaceAllUsesWith above.
5052 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5056 // This node is about to morph, remove its old self from the CSE maps.
5057 RemoveNodeFromCSEMaps(User);
5059 // A user can appear in a use list multiple times, and when this
5060 // happens the uses are usually next to each other in the list.
5061 // To help reduce the number of CSE recomputations, process all
5062 // the uses of this user that we can find this way.
5064 SDUse &Use = UI.getUse();
5067 } while (UI != UE && *UI == User);
5069 // Now that we have modified User, add it back to the CSE maps. If it
5070 // already exists there, recursively merge the results together.
5071 AddModifiedNodeToCSEMaps(User, UpdateListener);
5075 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5076 /// This can cause recursive merging of nodes in the DAG.
5078 /// This version can replace From with any result values. To must match the
5079 /// number and types of values returned by From.
5080 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
5082 DAGUpdateListener *UpdateListener) {
5083 if (From->getNumValues() == 1) // Handle the simple case efficiently.
5084 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
5086 // Iterate over just the existing users of From. See the comments in
5087 // the ReplaceAllUsesWith above.
5088 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5092 // This node is about to morph, remove its old self from the CSE maps.
5093 RemoveNodeFromCSEMaps(User);
5095 // A user can appear in a use list multiple times, and when this
5096 // happens the uses are usually next to each other in the list.
5097 // To help reduce the number of CSE recomputations, process all
5098 // the uses of this user that we can find this way.
5100 SDUse &Use = UI.getUse();
5101 const SDValue &ToOp = To[Use.getResNo()];
5104 } while (UI != UE && *UI == User);
5106 // Now that we have modified User, add it back to the CSE maps. If it
5107 // already exists there, recursively merge the results together.
5108 AddModifiedNodeToCSEMaps(User, UpdateListener);
5112 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5113 /// uses of other values produced by From.getNode() alone. The Deleted
5114 /// vector is handled the same way as for ReplaceAllUsesWith.
5115 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
5116 DAGUpdateListener *UpdateListener){
5117 // Handle the really simple, really trivial case efficiently.
5118 if (From == To) return;
5120 // Handle the simple, trivial, case efficiently.
5121 if (From.getNode()->getNumValues() == 1) {
5122 ReplaceAllUsesWith(From, To, UpdateListener);
5126 // Iterate over just the existing users of From. See the comments in
5127 // the ReplaceAllUsesWith above.
5128 SDNode::use_iterator UI = From.getNode()->use_begin(),
5129 UE = From.getNode()->use_end();
5132 bool UserRemovedFromCSEMaps = false;
5134 // A user can appear in a use list multiple times, and when this
5135 // happens the uses are usually next to each other in the list.
5136 // To help reduce the number of CSE recomputations, process all
5137 // the uses of this user that we can find this way.
5139 SDUse &Use = UI.getUse();
5141 // Skip uses of different values from the same node.
5142 if (Use.getResNo() != From.getResNo()) {
5147 // If this node hasn't been modified yet, it's still in the CSE maps,
5148 // so remove its old self from the CSE maps.
5149 if (!UserRemovedFromCSEMaps) {
5150 RemoveNodeFromCSEMaps(User);
5151 UserRemovedFromCSEMaps = true;
5156 } while (UI != UE && *UI == User);
5158 // We are iterating over all uses of the From node, so if a use
5159 // doesn't use the specific value, no changes are made.
5160 if (!UserRemovedFromCSEMaps)
5163 // Now that we have modified User, add it back to the CSE maps. If it
5164 // already exists there, recursively merge the results together.
5165 AddModifiedNodeToCSEMaps(User, UpdateListener);
5170 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5171 /// to record information about a use.
5178 /// operator< - Sort Memos by User.
5179 bool operator<(const UseMemo &L, const UseMemo &R) {
5180 return (intptr_t)L.User < (intptr_t)R.User;
5184 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5185 /// uses of other values produced by From.getNode() alone. The same value
5186 /// may appear in both the From and To list. The Deleted vector is
5187 /// handled the same way as for ReplaceAllUsesWith.
5188 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5191 DAGUpdateListener *UpdateListener){
5192 // Handle the simple, trivial case efficiently.
5194 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5196 // Read up all the uses and make records of them. This helps
5197 // processing new uses that are introduced during the
5198 // replacement process.
5199 SmallVector<UseMemo, 4> Uses;
5200 for (unsigned i = 0; i != Num; ++i) {
5201 unsigned FromResNo = From[i].getResNo();
5202 SDNode *FromNode = From[i].getNode();
5203 for (SDNode::use_iterator UI = FromNode->use_begin(),
5204 E = FromNode->use_end(); UI != E; ++UI) {
5205 SDUse &Use = UI.getUse();
5206 if (Use.getResNo() == FromResNo) {
5207 UseMemo Memo = { *UI, i, &Use };
5208 Uses.push_back(Memo);
5213 // Sort the uses, so that all the uses from a given User are together.
5214 std::sort(Uses.begin(), Uses.end());
5216 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5217 UseIndex != UseIndexEnd; ) {
5218 // We know that this user uses some value of From. If it is the right
5219 // value, update it.
5220 SDNode *User = Uses[UseIndex].User;
5222 // This node is about to morph, remove its old self from the CSE maps.
5223 RemoveNodeFromCSEMaps(User);
5225 // The Uses array is sorted, so all the uses for a given User
5226 // are next to each other in the list.
5227 // To help reduce the number of CSE recomputations, process all
5228 // the uses of this user that we can find this way.
5230 unsigned i = Uses[UseIndex].Index;
5231 SDUse &Use = *Uses[UseIndex].Use;
5235 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5237 // Now that we have modified User, add it back to the CSE maps. If it
5238 // already exists there, recursively merge the results together.
5239 AddModifiedNodeToCSEMaps(User, UpdateListener);
5243 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5244 /// based on their topological order. It returns the maximum id and a vector
5245 /// of the SDNodes* in assigned order by reference.
5246 unsigned SelectionDAG::AssignTopologicalOrder() {
5248 unsigned DAGSize = 0;
5250 // SortedPos tracks the progress of the algorithm. Nodes before it are
5251 // sorted, nodes after it are unsorted. When the algorithm completes
5252 // it is at the end of the list.
5253 allnodes_iterator SortedPos = allnodes_begin();
5255 // Visit all the nodes. Move nodes with no operands to the front of
5256 // the list immediately. Annotate nodes that do have operands with their
5257 // operand count. Before we do this, the Node Id fields of the nodes
5258 // may contain arbitrary values. After, the Node Id fields for nodes
5259 // before SortedPos will contain the topological sort index, and the
5260 // Node Id fields for nodes At SortedPos and after will contain the
5261 // count of outstanding operands.
5262 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5264 unsigned Degree = N->getNumOperands();
5266 // A node with no uses, add it to the result array immediately.
5267 N->setNodeId(DAGSize++);
5268 allnodes_iterator Q = N;
5270 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5273 // Temporarily use the Node Id as scratch space for the degree count.
5274 N->setNodeId(Degree);
5278 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5279 // such that by the time the end is reached all nodes will be sorted.
5280 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5282 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5285 unsigned Degree = P->getNodeId();
5288 // All of P's operands are sorted, so P may sorted now.
5289 P->setNodeId(DAGSize++);
5291 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5294 // Update P's outstanding operand count.
5295 P->setNodeId(Degree);
5300 assert(SortedPos == AllNodes.end() &&
5301 "Topological sort incomplete!");
5302 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5303 "First node in topological sort is not the entry token!");
5304 assert(AllNodes.front().getNodeId() == 0 &&
5305 "First node in topological sort has non-zero id!");
5306 assert(AllNodes.front().getNumOperands() == 0 &&
5307 "First node in topological sort has operands!");
5308 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5309 "Last node in topologic sort has unexpected id!");
5310 assert(AllNodes.back().use_empty() &&
5311 "Last node in topologic sort has users!");
5312 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5318 //===----------------------------------------------------------------------===//
5320 //===----------------------------------------------------------------------===//
5322 HandleSDNode::~HandleSDNode() {
5326 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
5328 : SDNode(isa<GlobalVariable>(GA) &&
5329 cast<GlobalVariable>(GA)->isThreadLocal() ?
5331 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
5333 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
5334 getSDVTList(VT)), Offset(o) {
5335 TheGlobal = const_cast<GlobalValue*>(GA);
5338 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
5339 const Value *srcValue, int SVO,
5340 unsigned alignment, bool vol)
5341 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
5342 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
5343 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5344 assert(getAlignment() == alignment && "Alignment representation error!");
5345 assert(isVolatile() == vol && "Volatile representation error!");
5348 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, const SDValue *Ops,
5349 unsigned NumOps, MVT memvt, const Value *srcValue,
5350 int SVO, unsigned alignment, bool vol)
5351 : SDNode(Opc, VTs, Ops, NumOps),
5352 MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
5353 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
5354 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5355 assert(getAlignment() == alignment && "Alignment representation error!");
5356 assert(isVolatile() == vol && "Volatile representation error!");
5359 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, MVT memvt,
5360 const Value *srcValue, int SVO,
5361 unsigned alignment, bool vol)
5362 : SDNode(Opc, dl, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
5363 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
5364 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5365 assert(getAlignment() == alignment && "Alignment representation error!");
5366 assert(isVolatile() == vol && "Volatile representation error!");
5369 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5371 unsigned NumOps, MVT memvt, const Value *srcValue,
5372 int SVO, unsigned alignment, bool vol)
5373 : SDNode(Opc, dl, VTs, Ops, NumOps),
5374 MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
5375 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
5376 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5377 assert(getAlignment() == alignment && "Alignment representation error!");
5378 assert(isVolatile() == vol && "Volatile representation error!");
5381 /// getMemOperand - Return a MachineMemOperand object describing the memory
5382 /// reference performed by this memory reference.
5383 MachineMemOperand MemSDNode::getMemOperand() const {
5385 if (isa<LoadSDNode>(this))
5386 Flags = MachineMemOperand::MOLoad;
5387 else if (isa<StoreSDNode>(this))
5388 Flags = MachineMemOperand::MOStore;
5389 else if (isa<AtomicSDNode>(this)) {
5390 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
5393 const MemIntrinsicSDNode* MemIntrinNode = dyn_cast<MemIntrinsicSDNode>(this);
5394 assert(MemIntrinNode && "Unknown MemSDNode opcode!");
5395 if (MemIntrinNode->readMem()) Flags |= MachineMemOperand::MOLoad;
5396 if (MemIntrinNode->writeMem()) Flags |= MachineMemOperand::MOStore;
5399 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
5400 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
5402 // Check if the memory reference references a frame index
5403 const FrameIndexSDNode *FI =
5404 dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
5405 if (!getSrcValue() && FI)
5406 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
5407 Flags, 0, Size, getAlignment());
5409 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
5410 Size, getAlignment());
5413 /// Profile - Gather unique data for the node.
5415 void SDNode::Profile(FoldingSetNodeID &ID) const {
5416 AddNodeIDNode(ID, this);
5419 /// getValueTypeList - Return a pointer to the specified value type.
5421 const MVT *SDNode::getValueTypeList(MVT VT) {
5422 if (VT.isExtended()) {
5423 static std::set<MVT, MVT::compareRawBits> EVTs;
5424 return &(*EVTs.insert(VT).first);
5426 static MVT VTs[MVT::LAST_VALUETYPE];
5427 VTs[VT.getSimpleVT()] = VT;
5428 return &VTs[VT.getSimpleVT()];
5432 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5433 /// indicated value. This method ignores uses of other values defined by this
5435 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5436 assert(Value < getNumValues() && "Bad value!");
5438 // TODO: Only iterate over uses of a given value of the node
5439 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5440 if (UI.getUse().getResNo() == Value) {
5447 // Found exactly the right number of uses?
5452 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5453 /// value. This method ignores uses of other values defined by this operation.
5454 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5455 assert(Value < getNumValues() && "Bad value!");
5457 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5458 if (UI.getUse().getResNo() == Value)
5465 /// isOnlyUserOf - Return true if this node is the only use of N.
5467 bool SDNode::isOnlyUserOf(SDNode *N) const {
5469 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5480 /// isOperand - Return true if this node is an operand of N.
5482 bool SDValue::isOperandOf(SDNode *N) const {
5483 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5484 if (*this == N->getOperand(i))
5489 bool SDNode::isOperandOf(SDNode *N) const {
5490 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5491 if (this == N->OperandList[i].getNode())
5496 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5497 /// be a chain) reaches the specified operand without crossing any
5498 /// side-effecting instructions. In practice, this looks through token
5499 /// factors and non-volatile loads. In order to remain efficient, this only
5500 /// looks a couple of nodes in, it does not do an exhaustive search.
5501 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5502 unsigned Depth) const {
5503 if (*this == Dest) return true;
5505 // Don't search too deeply, we just want to be able to see through
5506 // TokenFactor's etc.
5507 if (Depth == 0) return false;
5509 // If this is a token factor, all inputs to the TF happen in parallel. If any
5510 // of the operands of the TF reach dest, then we can do the xform.
5511 if (getOpcode() == ISD::TokenFactor) {
5512 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5513 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5518 // Loads don't have side effects, look through them.
5519 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5520 if (!Ld->isVolatile())
5521 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5527 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
5528 SmallPtrSet<SDNode *, 32> &Visited) {
5529 if (found || !Visited.insert(N))
5532 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
5533 SDNode *Op = N->getOperand(i).getNode();
5538 findPredecessor(Op, P, found, Visited);
5542 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5543 /// is either an operand of N or it can be reached by recursively traversing
5544 /// up the operands.
5545 /// NOTE: this is an expensive method. Use it carefully.
5546 bool SDNode::isPredecessorOf(SDNode *N) const {
5547 SmallPtrSet<SDNode *, 32> Visited;
5549 findPredecessor(N, this, found, Visited);
5553 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5554 assert(Num < NumOperands && "Invalid child # of SDNode!");
5555 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5558 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5559 switch (getOpcode()) {
5561 if (getOpcode() < ISD::BUILTIN_OP_END)
5562 return "<<Unknown DAG Node>>";
5563 if (isMachineOpcode()) {
5565 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5566 if (getMachineOpcode() < TII->getNumOpcodes())
5567 return TII->get(getMachineOpcode()).getName();
5568 return "<<Unknown Machine Node>>";
5571 const TargetLowering &TLI = G->getTargetLoweringInfo();
5572 const char *Name = TLI.getTargetNodeName(getOpcode());
5573 if (Name) return Name;
5574 return "<<Unknown Target Node>>";
5576 return "<<Unknown Node>>";
5579 case ISD::DELETED_NODE:
5580 return "<<Deleted Node!>>";
5582 case ISD::PREFETCH: return "Prefetch";
5583 case ISD::MEMBARRIER: return "MemBarrier";
5584 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5585 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5586 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5587 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5588 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5589 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5590 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5591 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5592 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5593 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5594 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5595 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5596 case ISD::PCMARKER: return "PCMarker";
5597 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5598 case ISD::SRCVALUE: return "SrcValue";
5599 case ISD::MEMOPERAND: return "MemOperand";
5600 case ISD::EntryToken: return "EntryToken";
5601 case ISD::TokenFactor: return "TokenFactor";
5602 case ISD::AssertSext: return "AssertSext";
5603 case ISD::AssertZext: return "AssertZext";
5605 case ISD::BasicBlock: return "BasicBlock";
5606 case ISD::ARG_FLAGS: return "ArgFlags";
5607 case ISD::VALUETYPE: return "ValueType";
5608 case ISD::Register: return "Register";
5610 case ISD::Constant: return "Constant";
5611 case ISD::ConstantFP: return "ConstantFP";
5612 case ISD::GlobalAddress: return "GlobalAddress";
5613 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5614 case ISD::FrameIndex: return "FrameIndex";
5615 case ISD::JumpTable: return "JumpTable";
5616 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5617 case ISD::RETURNADDR: return "RETURNADDR";
5618 case ISD::FRAMEADDR: return "FRAMEADDR";
5619 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5620 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5621 case ISD::EHSELECTION: return "EHSELECTION";
5622 case ISD::EH_RETURN: return "EH_RETURN";
5623 case ISD::ConstantPool: return "ConstantPool";
5624 case ISD::ExternalSymbol: return "ExternalSymbol";
5625 case ISD::INTRINSIC_WO_CHAIN: {
5626 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
5627 return Intrinsic::getName((Intrinsic::ID)IID);
5629 case ISD::INTRINSIC_VOID:
5630 case ISD::INTRINSIC_W_CHAIN: {
5631 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
5632 return Intrinsic::getName((Intrinsic::ID)IID);
5635 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5636 case ISD::TargetConstant: return "TargetConstant";
5637 case ISD::TargetConstantFP:return "TargetConstantFP";
5638 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5639 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5640 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5641 case ISD::TargetJumpTable: return "TargetJumpTable";
5642 case ISD::TargetConstantPool: return "TargetConstantPool";
5643 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5645 case ISD::CopyToReg: return "CopyToReg";
5646 case ISD::CopyFromReg: return "CopyFromReg";
5647 case ISD::UNDEF: return "undef";
5648 case ISD::MERGE_VALUES: return "merge_values";
5649 case ISD::INLINEASM: return "inlineasm";
5650 case ISD::DBG_LABEL: return "dbg_label";
5651 case ISD::EH_LABEL: return "eh_label";
5652 case ISD::DECLARE: return "declare";
5653 case ISD::HANDLENODE: return "handlenode";
5654 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
5655 case ISD::CALL: return "call";
5658 case ISD::FABS: return "fabs";
5659 case ISD::FNEG: return "fneg";
5660 case ISD::FSQRT: return "fsqrt";
5661 case ISD::FSIN: return "fsin";
5662 case ISD::FCOS: return "fcos";
5663 case ISD::FPOWI: return "fpowi";
5664 case ISD::FPOW: return "fpow";
5665 case ISD::FTRUNC: return "ftrunc";
5666 case ISD::FFLOOR: return "ffloor";
5667 case ISD::FCEIL: return "fceil";
5668 case ISD::FRINT: return "frint";
5669 case ISD::FNEARBYINT: return "fnearbyint";
5672 case ISD::ADD: return "add";
5673 case ISD::SUB: return "sub";
5674 case ISD::MUL: return "mul";
5675 case ISD::MULHU: return "mulhu";
5676 case ISD::MULHS: return "mulhs";
5677 case ISD::SDIV: return "sdiv";
5678 case ISD::UDIV: return "udiv";
5679 case ISD::SREM: return "srem";
5680 case ISD::UREM: return "urem";
5681 case ISD::SMUL_LOHI: return "smul_lohi";
5682 case ISD::UMUL_LOHI: return "umul_lohi";
5683 case ISD::SDIVREM: return "sdivrem";
5684 case ISD::UDIVREM: return "udivrem";
5685 case ISD::AND: return "and";
5686 case ISD::OR: return "or";
5687 case ISD::XOR: return "xor";
5688 case ISD::SHL: return "shl";
5689 case ISD::SRA: return "sra";
5690 case ISD::SRL: return "srl";
5691 case ISD::ROTL: return "rotl";
5692 case ISD::ROTR: return "rotr";
5693 case ISD::FADD: return "fadd";
5694 case ISD::FSUB: return "fsub";
5695 case ISD::FMUL: return "fmul";
5696 case ISD::FDIV: return "fdiv";
5697 case ISD::FREM: return "frem";
5698 case ISD::FCOPYSIGN: return "fcopysign";
5699 case ISD::FGETSIGN: return "fgetsign";
5701 case ISD::SETCC: return "setcc";
5702 case ISD::VSETCC: return "vsetcc";
5703 case ISD::SELECT: return "select";
5704 case ISD::SELECT_CC: return "select_cc";
5705 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5706 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5707 case ISD::CONCAT_VECTORS: return "concat_vectors";
5708 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5709 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5710 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5711 case ISD::CARRY_FALSE: return "carry_false";
5712 case ISD::ADDC: return "addc";
5713 case ISD::ADDE: return "adde";
5714 case ISD::SADDO: return "saddo";
5715 case ISD::UADDO: return "uaddo";
5716 case ISD::SSUBO: return "ssubo";
5717 case ISD::USUBO: return "usubo";
5718 case ISD::SMULO: return "smulo";
5719 case ISD::UMULO: return "umulo";
5720 case ISD::SUBC: return "subc";
5721 case ISD::SUBE: return "sube";
5722 case ISD::SHL_PARTS: return "shl_parts";
5723 case ISD::SRA_PARTS: return "sra_parts";
5724 case ISD::SRL_PARTS: return "srl_parts";
5726 case ISD::EXTRACT_SUBREG: return "extract_subreg";
5727 case ISD::INSERT_SUBREG: return "insert_subreg";
5729 // Conversion operators.
5730 case ISD::SIGN_EXTEND: return "sign_extend";
5731 case ISD::ZERO_EXTEND: return "zero_extend";
5732 case ISD::ANY_EXTEND: return "any_extend";
5733 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5734 case ISD::TRUNCATE: return "truncate";
5735 case ISD::FP_ROUND: return "fp_round";
5736 case ISD::FLT_ROUNDS_: return "flt_rounds";
5737 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5738 case ISD::FP_EXTEND: return "fp_extend";
5740 case ISD::SINT_TO_FP: return "sint_to_fp";
5741 case ISD::UINT_TO_FP: return "uint_to_fp";
5742 case ISD::FP_TO_SINT: return "fp_to_sint";
5743 case ISD::FP_TO_UINT: return "fp_to_uint";
5744 case ISD::BIT_CONVERT: return "bit_convert";
5746 case ISD::CONVERT_RNDSAT: {
5747 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5748 default: assert(0 && "Unknown cvt code!");
5749 case ISD::CVT_FF: return "cvt_ff";
5750 case ISD::CVT_FS: return "cvt_fs";
5751 case ISD::CVT_FU: return "cvt_fu";
5752 case ISD::CVT_SF: return "cvt_sf";
5753 case ISD::CVT_UF: return "cvt_uf";
5754 case ISD::CVT_SS: return "cvt_ss";
5755 case ISD::CVT_SU: return "cvt_su";
5756 case ISD::CVT_US: return "cvt_us";
5757 case ISD::CVT_UU: return "cvt_uu";
5761 // Control flow instructions
5762 case ISD::BR: return "br";
5763 case ISD::BRIND: return "brind";
5764 case ISD::BR_JT: return "br_jt";
5765 case ISD::BRCOND: return "brcond";
5766 case ISD::BR_CC: return "br_cc";
5767 case ISD::RET: return "ret";
5768 case ISD::CALLSEQ_START: return "callseq_start";
5769 case ISD::CALLSEQ_END: return "callseq_end";
5772 case ISD::LOAD: return "load";
5773 case ISD::STORE: return "store";
5774 case ISD::VAARG: return "vaarg";
5775 case ISD::VACOPY: return "vacopy";
5776 case ISD::VAEND: return "vaend";
5777 case ISD::VASTART: return "vastart";
5778 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5779 case ISD::EXTRACT_ELEMENT: return "extract_element";
5780 case ISD::BUILD_PAIR: return "build_pair";
5781 case ISD::STACKSAVE: return "stacksave";
5782 case ISD::STACKRESTORE: return "stackrestore";
5783 case ISD::TRAP: return "trap";
5786 case ISD::BSWAP: return "bswap";
5787 case ISD::CTPOP: return "ctpop";
5788 case ISD::CTTZ: return "cttz";
5789 case ISD::CTLZ: return "ctlz";
5792 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
5793 case ISD::DEBUG_LOC: return "debug_loc";
5796 case ISD::TRAMPOLINE: return "trampoline";
5799 switch (cast<CondCodeSDNode>(this)->get()) {
5800 default: assert(0 && "Unknown setcc condition!");
5801 case ISD::SETOEQ: return "setoeq";
5802 case ISD::SETOGT: return "setogt";
5803 case ISD::SETOGE: return "setoge";
5804 case ISD::SETOLT: return "setolt";
5805 case ISD::SETOLE: return "setole";
5806 case ISD::SETONE: return "setone";
5808 case ISD::SETO: return "seto";
5809 case ISD::SETUO: return "setuo";
5810 case ISD::SETUEQ: return "setue";
5811 case ISD::SETUGT: return "setugt";
5812 case ISD::SETUGE: return "setuge";
5813 case ISD::SETULT: return "setult";
5814 case ISD::SETULE: return "setule";
5815 case ISD::SETUNE: return "setune";
5817 case ISD::SETEQ: return "seteq";
5818 case ISD::SETGT: return "setgt";
5819 case ISD::SETGE: return "setge";
5820 case ISD::SETLT: return "setlt";
5821 case ISD::SETLE: return "setle";
5822 case ISD::SETNE: return "setne";
5827 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5836 return "<post-inc>";
5838 return "<post-dec>";
5842 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5843 std::string S = "< ";
5857 if (getByValAlign())
5858 S += "byval-align:" + utostr(getByValAlign()) + " ";
5860 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5862 S += "byval-size:" + utostr(getByValSize()) + " ";
5866 void SDNode::dump() const { dump(0); }
5867 void SDNode::dump(const SelectionDAG *G) const {
5872 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5873 OS << (void*)this << ": ";
5875 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5877 if (getValueType(i) == MVT::Other)
5880 OS << getValueType(i).getMVTString();
5882 OS << " = " << getOperationName(G);
5885 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5887 OS << (void*)getOperand(i).getNode();
5888 if (unsigned RN = getOperand(i).getResNo())
5892 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
5893 SDNode *Mask = getOperand(2).getNode();
5895 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
5897 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
5900 OS << cast<ConstantSDNode>(Mask->getOperand(i))->getZExtValue();
5905 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5906 OS << '<' << CSDN->getAPIntValue() << '>';
5907 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5908 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5909 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5910 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5911 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5914 CSDN->getValueAPF().bitcastToAPInt().dump();
5917 } else if (const GlobalAddressSDNode *GADN =
5918 dyn_cast<GlobalAddressSDNode>(this)) {
5919 int64_t offset = GADN->getOffset();
5921 WriteAsOperand(OS, GADN->getGlobal());
5924 OS << " + " << offset;
5926 OS << " " << offset;
5927 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5928 OS << "<" << FIDN->getIndex() << ">";
5929 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5930 OS << "<" << JTDN->getIndex() << ">";
5931 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5932 int offset = CP->getOffset();
5933 if (CP->isMachineConstantPoolEntry())
5934 OS << "<" << *CP->getMachineCPVal() << ">";
5936 OS << "<" << *CP->getConstVal() << ">";
5938 OS << " + " << offset;
5940 OS << " " << offset;
5941 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5943 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5945 OS << LBB->getName() << " ";
5946 OS << (const void*)BBDN->getBasicBlock() << ">";
5947 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5948 if (G && R->getReg() &&
5949 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5950 OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5952 OS << " #" << R->getReg();
5954 } else if (const ExternalSymbolSDNode *ES =
5955 dyn_cast<ExternalSymbolSDNode>(this)) {
5956 OS << "'" << ES->getSymbol() << "'";
5957 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5959 OS << "<" << M->getValue() << ">";
5962 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5963 if (M->MO.getValue())
5964 OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5966 OS << "<null:" << M->MO.getOffset() << ">";
5967 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5968 OS << N->getArgFlags().getArgFlagsString();
5969 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5970 OS << ":" << N->getVT().getMVTString();
5972 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5973 const Value *SrcValue = LD->getSrcValue();
5974 int SrcOffset = LD->getSrcValueOffset();
5980 OS << ":" << SrcOffset << ">";
5983 switch (LD->getExtensionType()) {
5984 default: doExt = false; break;
5985 case ISD::EXTLOAD: OS << " <anyext "; break;
5986 case ISD::SEXTLOAD: OS << " <sext "; break;
5987 case ISD::ZEXTLOAD: OS << " <zext "; break;
5990 OS << LD->getMemoryVT().getMVTString() << ">";
5992 const char *AM = getIndexedModeName(LD->getAddressingMode());
5995 if (LD->isVolatile())
5996 OS << " <volatile>";
5997 OS << " alignment=" << LD->getAlignment();
5998 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5999 const Value *SrcValue = ST->getSrcValue();
6000 int SrcOffset = ST->getSrcValueOffset();
6006 OS << ":" << SrcOffset << ">";
6008 if (ST->isTruncatingStore())
6009 OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
6011 const char *AM = getIndexedModeName(ST->getAddressingMode());
6014 if (ST->isVolatile())
6015 OS << " <volatile>";
6016 OS << " alignment=" << ST->getAlignment();
6017 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
6018 const Value *SrcValue = AT->getSrcValue();
6019 int SrcOffset = AT->getSrcValueOffset();
6025 OS << ":" << SrcOffset << ">";
6026 if (AT->isVolatile())
6027 OS << " <volatile>";
6028 OS << " alignment=" << AT->getAlignment();
6032 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
6033 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6034 if (N->getOperand(i).getNode()->hasOneUse())
6035 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
6037 cerr << "\n" << std::string(indent+2, ' ')
6038 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
6041 cerr << "\n" << std::string(indent, ' ');
6045 void SelectionDAG::dump() const {
6046 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
6048 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
6050 const SDNode *N = I;
6051 if (!N->hasOneUse() && N != getRoot().getNode())
6052 DumpNodes(N, 2, this);
6055 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
6060 const Type *ConstantPoolSDNode::getType() const {
6061 if (isMachineConstantPoolEntry())
6062 return Val.MachineCPVal->getType();
6063 return Val.ConstVal->getType();