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->getAddressingMode());
433 ID.AddInteger(LD->getExtensionType());
434 ID.AddInteger(LD->getMemoryVT().getRawBits());
435 ID.AddInteger(LD->getRawFlags());
439 const StoreSDNode *ST = cast<StoreSDNode>(N);
440 ID.AddInteger(ST->getAddressingMode());
441 ID.AddInteger(ST->isTruncatingStore());
442 ID.AddInteger(ST->getMemoryVT().getRawBits());
443 ID.AddInteger(ST->getRawFlags());
446 case ISD::ATOMIC_CMP_SWAP:
447 case ISD::ATOMIC_SWAP:
448 case ISD::ATOMIC_LOAD_ADD:
449 case ISD::ATOMIC_LOAD_SUB:
450 case ISD::ATOMIC_LOAD_AND:
451 case ISD::ATOMIC_LOAD_OR:
452 case ISD::ATOMIC_LOAD_XOR:
453 case ISD::ATOMIC_LOAD_NAND:
454 case ISD::ATOMIC_LOAD_MIN:
455 case ISD::ATOMIC_LOAD_MAX:
456 case ISD::ATOMIC_LOAD_UMIN:
457 case ISD::ATOMIC_LOAD_UMAX: {
458 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
459 ID.AddInteger(AT->getRawFlags());
462 } // end switch (N->getOpcode())
465 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
467 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
468 AddNodeIDOpcode(ID, N->getOpcode());
469 // Add the return value info.
470 AddNodeIDValueTypes(ID, N->getVTList());
471 // Add the operand info.
472 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
474 // Handle SDNode leafs with special info.
475 AddNodeIDCustom(ID, N);
478 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
479 /// the CSE map that carries both alignment and volatility information.
481 static inline unsigned
482 encodeMemSDNodeFlags(bool isVolatile, unsigned Alignment) {
483 return isVolatile | ((Log2_32(Alignment) + 1) << 1);
486 //===----------------------------------------------------------------------===//
487 // SelectionDAG Class
488 //===----------------------------------------------------------------------===//
490 /// doNotCSE - Return true if CSE should not be performed for this node.
491 static bool doNotCSE(SDNode *N) {
492 if (N->getValueType(0) == MVT::Flag)
493 return true; // Never CSE anything that produces a flag.
495 switch (N->getOpcode()) {
497 case ISD::HANDLENODE:
499 case ISD::DBG_STOPPOINT:
502 return true; // Never CSE these nodes.
505 // Check that remaining values produced are not flags.
506 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
507 if (N->getValueType(i) == MVT::Flag)
508 return true; // Never CSE anything that produces a flag.
513 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
515 void SelectionDAG::RemoveDeadNodes() {
516 // Create a dummy node (which is not added to allnodes), that adds a reference
517 // to the root node, preventing it from being deleted.
518 HandleSDNode Dummy(getRoot());
520 SmallVector<SDNode*, 128> DeadNodes;
522 // Add all obviously-dead nodes to the DeadNodes worklist.
523 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
525 DeadNodes.push_back(I);
527 RemoveDeadNodes(DeadNodes);
529 // If the root changed (e.g. it was a dead load, update the root).
530 setRoot(Dummy.getValue());
533 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
534 /// given list, and any nodes that become unreachable as a result.
535 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
536 DAGUpdateListener *UpdateListener) {
538 // Process the worklist, deleting the nodes and adding their uses to the
540 while (!DeadNodes.empty()) {
541 SDNode *N = DeadNodes.pop_back_val();
544 UpdateListener->NodeDeleted(N, 0);
546 // Take the node out of the appropriate CSE map.
547 RemoveNodeFromCSEMaps(N);
549 // Next, brutally remove the operand list. This is safe to do, as there are
550 // no cycles in the graph.
551 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
553 SDNode *Operand = Use.getNode();
556 // Now that we removed this operand, see if there are no uses of it left.
557 if (Operand->use_empty())
558 DeadNodes.push_back(Operand);
565 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
566 SmallVector<SDNode*, 16> DeadNodes(1, N);
567 RemoveDeadNodes(DeadNodes, UpdateListener);
570 void SelectionDAG::DeleteNode(SDNode *N) {
571 // First take this out of the appropriate CSE map.
572 RemoveNodeFromCSEMaps(N);
574 // Finally, remove uses due to operands of this node, remove from the
575 // AllNodes list, and delete the node.
576 DeleteNodeNotInCSEMaps(N);
579 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
580 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
581 assert(N->use_empty() && "Cannot delete a node that is not dead!");
583 // Drop all of the operands and decrement used node's use counts.
589 void SelectionDAG::DeallocateNode(SDNode *N) {
590 if (N->OperandsNeedDelete)
591 delete[] N->OperandList;
593 // Set the opcode to DELETED_NODE to help catch bugs when node
594 // memory is reallocated.
595 N->NodeType = ISD::DELETED_NODE;
597 NodeAllocator.Deallocate(AllNodes.remove(N));
600 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
601 /// correspond to it. This is useful when we're about to delete or repurpose
602 /// the node. We don't want future request for structurally identical nodes
603 /// to return N anymore.
604 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
606 switch (N->getOpcode()) {
607 case ISD::EntryToken:
608 assert(0 && "EntryToken should not be in CSEMaps!");
610 case ISD::HANDLENODE: return false; // noop.
612 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
613 "Cond code doesn't exist!");
614 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
615 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
617 case ISD::ExternalSymbol:
618 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
620 case ISD::TargetExternalSymbol:
622 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
624 case ISD::VALUETYPE: {
625 MVT VT = cast<VTSDNode>(N)->getVT();
626 if (VT.isExtended()) {
627 Erased = ExtendedValueTypeNodes.erase(VT);
629 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
630 ValueTypeNodes[VT.getSimpleVT()] = 0;
635 // Remove it from the CSE Map.
636 Erased = CSEMap.RemoveNode(N);
640 // Verify that the node was actually in one of the CSE maps, unless it has a
641 // flag result (which cannot be CSE'd) or is one of the special cases that are
642 // not subject to CSE.
643 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
644 !N->isMachineOpcode() && !doNotCSE(N)) {
647 assert(0 && "Node is not in map!");
653 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
654 /// maps and modified in place. Add it back to the CSE maps, unless an identical
655 /// node already exists, in which case transfer all its users to the existing
656 /// node. This transfer can potentially trigger recursive merging.
659 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
660 DAGUpdateListener *UpdateListener) {
661 // For node types that aren't CSE'd, just act as if no identical node
664 SDNode *Existing = CSEMap.GetOrInsertNode(N);
666 // If there was already an existing matching node, use ReplaceAllUsesWith
667 // to replace the dead one with the existing one. This can cause
668 // recursive merging of other unrelated nodes down the line.
669 ReplaceAllUsesWith(N, Existing, UpdateListener);
671 // N is now dead. Inform the listener if it exists and delete it.
673 UpdateListener->NodeDeleted(N, Existing);
674 DeleteNodeNotInCSEMaps(N);
679 // If the node doesn't already exist, we updated it. Inform a listener if
682 UpdateListener->NodeUpdated(N);
685 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
686 /// were replaced with those specified. If this node is never memoized,
687 /// return null, otherwise return a pointer to the slot it would take. If a
688 /// node already exists with these operands, the slot will be non-null.
689 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
694 SDValue Ops[] = { Op };
696 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
697 AddNodeIDCustom(ID, N);
698 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
701 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
702 /// were replaced with those specified. If this node is never memoized,
703 /// return null, otherwise return a pointer to the slot it would take. If a
704 /// node already exists with these operands, the slot will be non-null.
705 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
706 SDValue Op1, SDValue Op2,
711 SDValue Ops[] = { Op1, Op2 };
713 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
714 AddNodeIDCustom(ID, N);
715 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
719 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
720 /// were replaced with those specified. If this node is never memoized,
721 /// return null, otherwise return a pointer to the slot it would take. If a
722 /// node already exists with these operands, the slot will be non-null.
723 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
724 const SDValue *Ops,unsigned NumOps,
730 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
731 AddNodeIDCustom(ID, N);
732 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
735 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
736 void SelectionDAG::VerifyNode(SDNode *N) {
737 switch (N->getOpcode()) {
740 case ISD::BUILD_PAIR: {
741 MVT VT = N->getValueType(0);
742 assert(N->getNumValues() == 1 && "Too many results!");
743 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
744 "Wrong return type!");
745 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
746 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
747 "Mismatched operand types!");
748 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
749 "Wrong operand type!");
750 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
751 "Wrong return type size");
754 case ISD::BUILD_VECTOR: {
755 assert(N->getNumValues() == 1 && "Too many results!");
756 assert(N->getValueType(0).isVector() && "Wrong return type!");
757 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
758 "Wrong number of operands!");
759 // FIXME: Change vector_shuffle to a variadic node with mask elements being
760 // operands of the node. Currently the mask is a BUILD_VECTOR passed as an
761 // operand, and it is not always possible to legalize it. Turning off the
762 // following checks at least makes it possible to legalize most of the time.
763 // MVT EltVT = N->getValueType(0).getVectorElementType();
764 // for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
765 // assert(I->getValueType() == EltVT &&
766 // "Wrong operand type!");
772 /// getMVTAlignment - Compute the default alignment value for the
775 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
776 const Type *Ty = VT == MVT::iPTR ?
777 PointerType::get(Type::Int8Ty, 0) :
780 return TLI.getTargetData()->getABITypeAlignment(Ty);
783 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
784 : TLI(tli), FLI(fli),
785 EntryNode(ISD::EntryToken, getVTList(MVT::Other)),
786 Root(getEntryNode()) {
787 AllNodes.push_back(&EntryNode);
790 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
797 SelectionDAG::~SelectionDAG() {
801 void SelectionDAG::allnodes_clear() {
802 assert(&*AllNodes.begin() == &EntryNode);
803 AllNodes.remove(AllNodes.begin());
804 while (!AllNodes.empty())
805 DeallocateNode(AllNodes.begin());
808 void SelectionDAG::clear() {
810 OperandAllocator.Reset();
813 ExtendedValueTypeNodes.clear();
814 ExternalSymbols.clear();
815 TargetExternalSymbols.clear();
816 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
817 static_cast<CondCodeSDNode*>(0));
818 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
819 static_cast<SDNode*>(0));
821 EntryNode.UseList = 0;
822 AllNodes.push_back(&EntryNode);
823 Root = getEntryNode();
826 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
827 if (Op.getValueType() == VT) return Op;
828 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
830 return getNode(ISD::AND, Op.getValueType(), Op,
831 getConstant(Imm, Op.getValueType()));
834 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, MVT VT) {
835 if (Op.getValueType() == VT) return Op;
836 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
838 return getNode(ISD::AND, DL, Op.getValueType(), Op,
839 getConstant(Imm, Op.getValueType()));
842 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
844 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, MVT VT) {
847 MVT EltVT = VT.getVectorElementType();
848 SDValue NegOneElt = getConstant(EltVT.getIntegerVTBitMask(), EltVT);
849 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOneElt);
850 NegOne = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(), VT,
851 &NegOnes[0], NegOnes.size());
853 NegOne = getConstant(VT.getIntegerVTBitMask(), VT);
856 return getNode(ISD::XOR, DL, VT, Val, NegOne);
859 SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
860 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
861 assert((EltVT.getSizeInBits() >= 64 ||
862 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
863 "getConstant with a uint64_t value that doesn't fit in the type!");
864 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
867 SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
868 return getConstant(*ConstantInt::get(Val), VT, isT);
871 SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) {
872 assert(VT.isInteger() && "Cannot create FP integer constant!");
874 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
875 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
876 "APInt size does not match type size!");
878 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
880 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
884 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
886 return SDValue(N, 0);
888 N = NodeAllocator.Allocate<ConstantSDNode>();
889 new (N) ConstantSDNode(isT, &Val, EltVT);
890 CSEMap.InsertNode(N, IP);
891 AllNodes.push_back(N);
894 SDValue Result(N, 0);
896 SmallVector<SDValue, 8> Ops;
897 Ops.assign(VT.getVectorNumElements(), Result);
898 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
903 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
904 return getConstant(Val, TLI.getPointerTy(), isTarget);
908 SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
909 return getConstantFP(*ConstantFP::get(V), VT, isTarget);
912 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, MVT VT, bool isTarget){
913 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
916 VT.isVector() ? VT.getVectorElementType() : VT;
918 // Do the map lookup using the actual bit pattern for the floating point
919 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
920 // we don't have issues with SNANs.
921 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
923 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
927 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
929 return SDValue(N, 0);
931 N = NodeAllocator.Allocate<ConstantFPSDNode>();
932 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
933 CSEMap.InsertNode(N, IP);
934 AllNodes.push_back(N);
937 SDValue Result(N, 0);
939 SmallVector<SDValue, 8> Ops;
940 Ops.assign(VT.getVectorNumElements(), Result);
941 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
946 SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
948 VT.isVector() ? VT.getVectorElementType() : VT;
950 return getConstantFP(APFloat((float)Val), VT, isTarget);
952 return getConstantFP(APFloat(Val), VT, isTarget);
955 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
956 MVT VT, int64_t Offset,
960 // Truncate (with sign-extension) the offset value to the pointer size.
961 unsigned BitWidth = TLI.getPointerTy().getSizeInBits();
963 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
965 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
967 // If GV is an alias then use the aliasee for determining thread-localness.
968 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
969 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
972 if (GVar && GVar->isThreadLocal())
973 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
975 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
978 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
980 ID.AddInteger(Offset);
982 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
983 return SDValue(E, 0);
984 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
985 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
986 CSEMap.InsertNode(N, IP);
987 AllNodes.push_back(N);
988 return SDValue(N, 0);
991 SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
992 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
994 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
997 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
998 return SDValue(E, 0);
999 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
1000 new (N) FrameIndexSDNode(FI, VT, isTarget);
1001 CSEMap.InsertNode(N, IP);
1002 AllNodes.push_back(N);
1003 return SDValue(N, 0);
1006 SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
1007 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1008 FoldingSetNodeID ID;
1009 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1012 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1013 return SDValue(E, 0);
1014 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1015 new (N) JumpTableSDNode(JTI, VT, isTarget);
1016 CSEMap.InsertNode(N, IP);
1017 AllNodes.push_back(N);
1018 return SDValue(N, 0);
1021 SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
1022 unsigned Alignment, int Offset,
1026 TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
1027 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1028 FoldingSetNodeID ID;
1029 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1030 ID.AddInteger(Alignment);
1031 ID.AddInteger(Offset);
1034 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1035 return SDValue(E, 0);
1036 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1037 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1038 CSEMap.InsertNode(N, IP);
1039 AllNodes.push_back(N);
1040 return SDValue(N, 0);
1044 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
1045 unsigned Alignment, int Offset,
1049 TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
1050 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1051 FoldingSetNodeID ID;
1052 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1053 ID.AddInteger(Alignment);
1054 ID.AddInteger(Offset);
1055 C->AddSelectionDAGCSEId(ID);
1057 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1058 return SDValue(E, 0);
1059 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1060 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
1061 CSEMap.InsertNode(N, IP);
1062 AllNodes.push_back(N);
1063 return SDValue(N, 0);
1067 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1068 FoldingSetNodeID ID;
1069 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1072 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1073 return SDValue(E, 0);
1074 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1075 new (N) BasicBlockSDNode(MBB);
1076 CSEMap.InsertNode(N, IP);
1077 AllNodes.push_back(N);
1078 return SDValue(N, 0);
1081 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB, DebugLoc dl) {
1082 FoldingSetNodeID ID;
1083 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1086 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1087 return SDValue(E, 0);
1088 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1089 new (N) BasicBlockSDNode(MBB, dl);
1090 CSEMap.InsertNode(N, IP);
1091 AllNodes.push_back(N);
1092 return SDValue(N, 0);
1095 SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
1096 FoldingSetNodeID ID;
1097 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
1098 ID.AddInteger(Flags.getRawBits());
1100 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1101 return SDValue(E, 0);
1102 SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
1103 new (N) ARG_FLAGSSDNode(Flags);
1104 CSEMap.InsertNode(N, IP);
1105 AllNodes.push_back(N);
1106 return SDValue(N, 0);
1109 SDValue SelectionDAG::getValueType(MVT VT) {
1110 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1111 ValueTypeNodes.resize(VT.getSimpleVT()+1);
1113 SDNode *&N = VT.isExtended() ?
1114 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1116 if (N) return SDValue(N, 0);
1117 N = NodeAllocator.Allocate<VTSDNode>();
1118 new (N) VTSDNode(VT);
1119 AllNodes.push_back(N);
1120 return SDValue(N, 0);
1123 SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1124 SDNode *&N = ExternalSymbols[Sym];
1125 if (N) return SDValue(N, 0);
1126 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1127 new (N) ExternalSymbolSDNode(false, Sym, VT);
1128 AllNodes.push_back(N);
1129 return SDValue(N, 0);
1132 SDValue SelectionDAG::getExternalSymbol(const char *Sym, DebugLoc dl, MVT VT) {
1133 SDNode *&N = ExternalSymbols[Sym];
1134 if (N) return SDValue(N, 0);
1135 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1136 new (N) ExternalSymbolSDNode(false, dl, Sym, VT);
1137 AllNodes.push_back(N);
1138 return SDValue(N, 0);
1141 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1142 SDNode *&N = TargetExternalSymbols[Sym];
1143 if (N) return SDValue(N, 0);
1144 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1145 new (N) ExternalSymbolSDNode(true, Sym, VT);
1146 AllNodes.push_back(N);
1147 return SDValue(N, 0);
1150 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, DebugLoc dl,
1152 SDNode *&N = TargetExternalSymbols[Sym];
1153 if (N) return SDValue(N, 0);
1154 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1155 new (N) ExternalSymbolSDNode(true, dl, Sym, VT);
1156 AllNodes.push_back(N);
1157 return SDValue(N, 0);
1160 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1161 if ((unsigned)Cond >= CondCodeNodes.size())
1162 CondCodeNodes.resize(Cond+1);
1164 if (CondCodeNodes[Cond] == 0) {
1165 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1166 new (N) CondCodeSDNode(Cond);
1167 CondCodeNodes[Cond] = N;
1168 AllNodes.push_back(N);
1170 return SDValue(CondCodeNodes[Cond], 0);
1173 SDValue SelectionDAG::getConvertRndSat(MVT VT, SDValue Val, SDValue DTy,
1174 SDValue STy, SDValue Rnd, SDValue Sat,
1175 ISD::CvtCode Code) {
1176 // If the src and dest types are the same, no conversion is necessary.
1180 FoldingSetNodeID ID;
1182 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1183 return SDValue(E, 0);
1184 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
1185 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1186 new (N) CvtRndSatSDNode(VT, Ops, 5, Code);
1187 CSEMap.InsertNode(N, IP);
1188 AllNodes.push_back(N);
1189 return SDValue(N, 0);
1192 SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1193 FoldingSetNodeID ID;
1194 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1195 ID.AddInteger(RegNo);
1197 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1198 return SDValue(E, 0);
1199 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1200 new (N) RegisterSDNode(RegNo, VT);
1201 CSEMap.InsertNode(N, IP);
1202 AllNodes.push_back(N);
1203 return SDValue(N, 0);
1206 SDValue SelectionDAG::getDbgStopPoint(SDValue Root,
1207 unsigned Line, unsigned Col,
1209 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1210 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1211 AllNodes.push_back(N);
1212 return SDValue(N, 0);
1215 SDValue SelectionDAG::getLabel(unsigned Opcode,
1218 FoldingSetNodeID ID;
1219 SDValue Ops[] = { Root };
1220 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1221 ID.AddInteger(LabelID);
1223 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1224 return SDValue(E, 0);
1225 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1226 new (N) LabelSDNode(Opcode, Root, LabelID);
1227 CSEMap.InsertNode(N, IP);
1228 AllNodes.push_back(N);
1229 return SDValue(N, 0);
1232 SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
1235 FoldingSetNodeID ID;
1236 SDValue Ops[] = { Root };
1237 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1238 ID.AddInteger(LabelID);
1240 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1241 return SDValue(E, 0);
1242 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1243 new (N) LabelSDNode(Opcode, dl, Root, LabelID);
1244 CSEMap.InsertNode(N, IP);
1245 AllNodes.push_back(N);
1246 return SDValue(N, 0);
1249 SDValue SelectionDAG::getSrcValue(const Value *V) {
1250 assert((!V || isa<PointerType>(V->getType())) &&
1251 "SrcValue is not a pointer?");
1253 FoldingSetNodeID ID;
1254 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1258 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1259 return SDValue(E, 0);
1261 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1262 new (N) SrcValueSDNode(V);
1263 CSEMap.InsertNode(N, IP);
1264 AllNodes.push_back(N);
1265 return SDValue(N, 0);
1268 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1270 const Value *v = MO.getValue();
1271 assert((!v || isa<PointerType>(v->getType())) &&
1272 "SrcValue is not a pointer?");
1275 FoldingSetNodeID ID;
1276 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1280 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1281 return SDValue(E, 0);
1283 SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
1284 new (N) MemOperandSDNode(MO);
1285 CSEMap.InsertNode(N, IP);
1286 AllNodes.push_back(N);
1287 return SDValue(N, 0);
1290 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1291 /// specified value type.
1292 SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1293 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1294 unsigned ByteSize = VT.getStoreSizeInBits()/8;
1295 const Type *Ty = VT.getTypeForMVT();
1296 unsigned StackAlign =
1297 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1299 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1300 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1303 /// CreateStackTemporary - Create a stack temporary suitable for holding
1304 /// either of the specified value types.
1305 SDValue SelectionDAG::CreateStackTemporary(MVT VT1, MVT VT2) {
1306 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1307 VT2.getStoreSizeInBits())/8;
1308 const Type *Ty1 = VT1.getTypeForMVT();
1309 const Type *Ty2 = VT2.getTypeForMVT();
1310 const TargetData *TD = TLI.getTargetData();
1311 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1312 TD->getPrefTypeAlignment(Ty2));
1314 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1315 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align);
1316 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1319 SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
1320 SDValue N2, ISD::CondCode Cond) {
1321 // These setcc operations always fold.
1325 case ISD::SETFALSE2: return getConstant(0, VT);
1327 case ISD::SETTRUE2: return getConstant(1, VT);
1339 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1343 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1344 const APInt &C2 = N2C->getAPIntValue();
1345 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1346 const APInt &C1 = N1C->getAPIntValue();
1349 default: assert(0 && "Unknown integer setcc!");
1350 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1351 case ISD::SETNE: return getConstant(C1 != C2, VT);
1352 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1353 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1354 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1355 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1356 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1357 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1358 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1359 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1363 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1364 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1365 // No compile time operations on this type yet.
1366 if (N1C->getValueType(0) == MVT::ppcf128)
1369 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1372 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1373 return getNode(ISD::UNDEF, VT);
1375 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1376 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1377 return getNode(ISD::UNDEF, VT);
1379 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1380 R==APFloat::cmpLessThan, VT);
1381 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1382 return getNode(ISD::UNDEF, VT);
1384 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1385 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1386 return getNode(ISD::UNDEF, VT);
1388 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1389 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1390 return getNode(ISD::UNDEF, VT);
1392 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1393 R==APFloat::cmpEqual, VT);
1394 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1395 return getNode(ISD::UNDEF, VT);
1397 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1398 R==APFloat::cmpEqual, VT);
1399 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1400 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1401 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1402 R==APFloat::cmpEqual, VT);
1403 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1404 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1405 R==APFloat::cmpLessThan, VT);
1406 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1407 R==APFloat::cmpUnordered, VT);
1408 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1409 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1412 // Ensure that the constant occurs on the RHS.
1413 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1417 // Could not fold it.
1421 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1422 /// use this predicate to simplify operations downstream.
1423 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1424 unsigned BitWidth = Op.getValueSizeInBits();
1425 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1428 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1429 /// this predicate to simplify operations downstream. Mask is known to be zero
1430 /// for bits that V cannot have.
1431 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1432 unsigned Depth) const {
1433 APInt KnownZero, KnownOne;
1434 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1435 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1436 return (KnownZero & Mask) == Mask;
1439 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1440 /// known to be either zero or one and return them in the KnownZero/KnownOne
1441 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1443 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1444 APInt &KnownZero, APInt &KnownOne,
1445 unsigned Depth) const {
1446 unsigned BitWidth = Mask.getBitWidth();
1447 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1448 "Mask size mismatches value type size!");
1450 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1451 if (Depth == 6 || Mask == 0)
1452 return; // Limit search depth.
1454 APInt KnownZero2, KnownOne2;
1456 switch (Op.getOpcode()) {
1458 // We know all of the bits for a constant!
1459 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1460 KnownZero = ~KnownOne & Mask;
1463 // If either the LHS or the RHS are Zero, the result is zero.
1464 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1465 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1466 KnownZero2, KnownOne2, Depth+1);
1467 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1468 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1470 // Output known-1 bits are only known if set in both the LHS & RHS.
1471 KnownOne &= KnownOne2;
1472 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1473 KnownZero |= KnownZero2;
1476 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1477 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1478 KnownZero2, KnownOne2, Depth+1);
1479 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1480 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1482 // Output known-0 bits are only known if clear in both the LHS & RHS.
1483 KnownZero &= KnownZero2;
1484 // Output known-1 are known to be set if set in either the LHS | RHS.
1485 KnownOne |= KnownOne2;
1488 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1489 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1490 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1491 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1493 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1494 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1495 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1496 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1497 KnownZero = KnownZeroOut;
1501 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1502 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1503 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1504 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1505 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1507 // If low bits are zero in either operand, output low known-0 bits.
1508 // Also compute a conserative estimate for high known-0 bits.
1509 // More trickiness is possible, but this is sufficient for the
1510 // interesting case of alignment computation.
1512 unsigned TrailZ = KnownZero.countTrailingOnes() +
1513 KnownZero2.countTrailingOnes();
1514 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1515 KnownZero2.countLeadingOnes(),
1516 BitWidth) - BitWidth;
1518 TrailZ = std::min(TrailZ, BitWidth);
1519 LeadZ = std::min(LeadZ, BitWidth);
1520 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1521 APInt::getHighBitsSet(BitWidth, LeadZ);
1526 // For the purposes of computing leading zeros we can conservatively
1527 // treat a udiv as a logical right shift by the power of 2 known to
1528 // be less than the denominator.
1529 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1530 ComputeMaskedBits(Op.getOperand(0),
1531 AllOnes, KnownZero2, KnownOne2, Depth+1);
1532 unsigned LeadZ = KnownZero2.countLeadingOnes();
1536 ComputeMaskedBits(Op.getOperand(1),
1537 AllOnes, KnownZero2, KnownOne2, Depth+1);
1538 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1539 if (RHSUnknownLeadingOnes != BitWidth)
1540 LeadZ = std::min(BitWidth,
1541 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1543 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1547 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1548 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1549 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1550 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1552 // Only known if known in both the LHS and RHS.
1553 KnownOne &= KnownOne2;
1554 KnownZero &= KnownZero2;
1556 case ISD::SELECT_CC:
1557 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1558 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1559 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1560 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1562 // Only known if known in both the LHS and RHS.
1563 KnownOne &= KnownOne2;
1564 KnownZero &= KnownZero2;
1572 if (Op.getResNo() != 1)
1574 // The boolean result conforms to getBooleanContents. Fall through.
1576 // If we know the result of a setcc has the top bits zero, use this info.
1577 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1579 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1582 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1583 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1584 unsigned ShAmt = SA->getZExtValue();
1586 // If the shift count is an invalid immediate, don't do anything.
1587 if (ShAmt >= BitWidth)
1590 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1591 KnownZero, KnownOne, Depth+1);
1592 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1593 KnownZero <<= ShAmt;
1595 // low bits known zero.
1596 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1600 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1601 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1602 unsigned ShAmt = SA->getZExtValue();
1604 // If the shift count is an invalid immediate, don't do anything.
1605 if (ShAmt >= BitWidth)
1608 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1609 KnownZero, KnownOne, Depth+1);
1610 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1611 KnownZero = KnownZero.lshr(ShAmt);
1612 KnownOne = KnownOne.lshr(ShAmt);
1614 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1615 KnownZero |= HighBits; // High bits known zero.
1619 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1620 unsigned ShAmt = SA->getZExtValue();
1622 // If the shift count is an invalid immediate, don't do anything.
1623 if (ShAmt >= BitWidth)
1626 APInt InDemandedMask = (Mask << ShAmt);
1627 // If any of the demanded bits are produced by the sign extension, we also
1628 // demand the input sign bit.
1629 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1630 if (HighBits.getBoolValue())
1631 InDemandedMask |= APInt::getSignBit(BitWidth);
1633 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1635 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1636 KnownZero = KnownZero.lshr(ShAmt);
1637 KnownOne = KnownOne.lshr(ShAmt);
1639 // Handle the sign bits.
1640 APInt SignBit = APInt::getSignBit(BitWidth);
1641 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1643 if (KnownZero.intersects(SignBit)) {
1644 KnownZero |= HighBits; // New bits are known zero.
1645 } else if (KnownOne.intersects(SignBit)) {
1646 KnownOne |= HighBits; // New bits are known one.
1650 case ISD::SIGN_EXTEND_INREG: {
1651 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1652 unsigned EBits = EVT.getSizeInBits();
1654 // Sign extension. Compute the demanded bits in the result that are not
1655 // present in the input.
1656 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1658 APInt InSignBit = APInt::getSignBit(EBits);
1659 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1661 // If the sign extended bits are demanded, we know that the sign
1663 InSignBit.zext(BitWidth);
1664 if (NewBits.getBoolValue())
1665 InputDemandedBits |= InSignBit;
1667 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1668 KnownZero, KnownOne, Depth+1);
1669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1671 // If the sign bit of the input is known set or clear, then we know the
1672 // top bits of the result.
1673 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1674 KnownZero |= NewBits;
1675 KnownOne &= ~NewBits;
1676 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1677 KnownOne |= NewBits;
1678 KnownZero &= ~NewBits;
1679 } else { // Input sign bit unknown
1680 KnownZero &= ~NewBits;
1681 KnownOne &= ~NewBits;
1688 unsigned LowBits = Log2_32(BitWidth)+1;
1689 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1694 if (ISD::isZEXTLoad(Op.getNode())) {
1695 LoadSDNode *LD = cast<LoadSDNode>(Op);
1696 MVT VT = LD->getMemoryVT();
1697 unsigned MemBits = VT.getSizeInBits();
1698 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1702 case ISD::ZERO_EXTEND: {
1703 MVT InVT = Op.getOperand(0).getValueType();
1704 unsigned InBits = InVT.getSizeInBits();
1705 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1706 APInt InMask = Mask;
1707 InMask.trunc(InBits);
1708 KnownZero.trunc(InBits);
1709 KnownOne.trunc(InBits);
1710 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1711 KnownZero.zext(BitWidth);
1712 KnownOne.zext(BitWidth);
1713 KnownZero |= NewBits;
1716 case ISD::SIGN_EXTEND: {
1717 MVT InVT = Op.getOperand(0).getValueType();
1718 unsigned InBits = InVT.getSizeInBits();
1719 APInt InSignBit = APInt::getSignBit(InBits);
1720 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1721 APInt InMask = Mask;
1722 InMask.trunc(InBits);
1724 // If any of the sign extended bits are demanded, we know that the sign
1725 // bit is demanded. Temporarily set this bit in the mask for our callee.
1726 if (NewBits.getBoolValue())
1727 InMask |= InSignBit;
1729 KnownZero.trunc(InBits);
1730 KnownOne.trunc(InBits);
1731 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1733 // Note if the sign bit is known to be zero or one.
1734 bool SignBitKnownZero = KnownZero.isNegative();
1735 bool SignBitKnownOne = KnownOne.isNegative();
1736 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1737 "Sign bit can't be known to be both zero and one!");
1739 // If the sign bit wasn't actually demanded by our caller, we don't
1740 // want it set in the KnownZero and KnownOne result values. Reset the
1741 // mask and reapply it to the result values.
1743 InMask.trunc(InBits);
1744 KnownZero &= InMask;
1747 KnownZero.zext(BitWidth);
1748 KnownOne.zext(BitWidth);
1750 // If the sign bit is known zero or one, the top bits match.
1751 if (SignBitKnownZero)
1752 KnownZero |= NewBits;
1753 else if (SignBitKnownOne)
1754 KnownOne |= NewBits;
1757 case ISD::ANY_EXTEND: {
1758 MVT InVT = Op.getOperand(0).getValueType();
1759 unsigned InBits = InVT.getSizeInBits();
1760 APInt InMask = Mask;
1761 InMask.trunc(InBits);
1762 KnownZero.trunc(InBits);
1763 KnownOne.trunc(InBits);
1764 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1765 KnownZero.zext(BitWidth);
1766 KnownOne.zext(BitWidth);
1769 case ISD::TRUNCATE: {
1770 MVT InVT = Op.getOperand(0).getValueType();
1771 unsigned InBits = InVT.getSizeInBits();
1772 APInt InMask = Mask;
1773 InMask.zext(InBits);
1774 KnownZero.zext(InBits);
1775 KnownOne.zext(InBits);
1776 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1777 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1778 KnownZero.trunc(BitWidth);
1779 KnownOne.trunc(BitWidth);
1782 case ISD::AssertZext: {
1783 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1784 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1785 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1787 KnownZero |= (~InMask) & Mask;
1791 // All bits are zero except the low bit.
1792 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1796 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1797 // We know that the top bits of C-X are clear if X contains less bits
1798 // than C (i.e. no wrap-around can happen). For example, 20-X is
1799 // positive if we can prove that X is >= 0 and < 16.
1800 if (CLHS->getAPIntValue().isNonNegative()) {
1801 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1802 // NLZ can't be BitWidth with no sign bit
1803 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1804 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1807 // If all of the MaskV bits are known to be zero, then we know the
1808 // output top bits are zero, because we now know that the output is
1810 if ((KnownZero2 & MaskV) == MaskV) {
1811 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1812 // Top bits known zero.
1813 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1820 // Output known-0 bits are known if clear or set in both the low clear bits
1821 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1822 // low 3 bits clear.
1823 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1824 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1825 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1826 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1828 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1829 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1830 KnownZeroOut = std::min(KnownZeroOut,
1831 KnownZero2.countTrailingOnes());
1833 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1837 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1838 const APInt &RA = Rem->getAPIntValue();
1839 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1840 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1841 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1842 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1844 // If the sign bit of the first operand is zero, the sign bit of
1845 // the result is zero. If the first operand has no one bits below
1846 // the second operand's single 1 bit, its sign will be zero.
1847 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1848 KnownZero2 |= ~LowBits;
1850 KnownZero |= KnownZero2 & Mask;
1852 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1857 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1858 const APInt &RA = Rem->getAPIntValue();
1859 if (RA.isPowerOf2()) {
1860 APInt LowBits = (RA - 1);
1861 APInt Mask2 = LowBits & Mask;
1862 KnownZero |= ~LowBits & Mask;
1863 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1864 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1869 // Since the result is less than or equal to either operand, any leading
1870 // zero bits in either operand must also exist in the result.
1871 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1872 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1874 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1877 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1878 KnownZero2.countLeadingOnes());
1880 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1884 // Allow the target to implement this method for its nodes.
1885 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1886 case ISD::INTRINSIC_WO_CHAIN:
1887 case ISD::INTRINSIC_W_CHAIN:
1888 case ISD::INTRINSIC_VOID:
1889 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1895 /// ComputeNumSignBits - Return the number of times the sign bit of the
1896 /// register is replicated into the other bits. We know that at least 1 bit
1897 /// is always equal to the sign bit (itself), but other cases can give us
1898 /// information. For example, immediately after an "SRA X, 2", we know that
1899 /// the top 3 bits are all equal to each other, so we return 3.
1900 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1901 MVT VT = Op.getValueType();
1902 assert(VT.isInteger() && "Invalid VT!");
1903 unsigned VTBits = VT.getSizeInBits();
1905 unsigned FirstAnswer = 1;
1908 return 1; // Limit search depth.
1910 switch (Op.getOpcode()) {
1912 case ISD::AssertSext:
1913 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1914 return VTBits-Tmp+1;
1915 case ISD::AssertZext:
1916 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1919 case ISD::Constant: {
1920 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1921 // If negative, return # leading ones.
1922 if (Val.isNegative())
1923 return Val.countLeadingOnes();
1925 // Return # leading zeros.
1926 return Val.countLeadingZeros();
1929 case ISD::SIGN_EXTEND:
1930 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1931 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1933 case ISD::SIGN_EXTEND_INREG:
1934 // Max of the input and what this extends.
1935 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1938 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1939 return std::max(Tmp, Tmp2);
1942 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1943 // SRA X, C -> adds C sign bits.
1944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1945 Tmp += C->getZExtValue();
1946 if (Tmp > VTBits) Tmp = VTBits;
1950 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1951 // shl destroys sign bits.
1952 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1953 if (C->getZExtValue() >= VTBits || // Bad shift.
1954 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
1955 return Tmp - C->getZExtValue();
1960 case ISD::XOR: // NOT is handled here.
1961 // Logical binary ops preserve the number of sign bits at the worst.
1962 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1964 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1965 FirstAnswer = std::min(Tmp, Tmp2);
1966 // We computed what we know about the sign bits as our first
1967 // answer. Now proceed to the generic code that uses
1968 // ComputeMaskedBits, and pick whichever answer is better.
1973 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1974 if (Tmp == 1) return 1; // Early out.
1975 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1976 return std::min(Tmp, Tmp2);
1984 if (Op.getResNo() != 1)
1986 // The boolean result conforms to getBooleanContents. Fall through.
1988 // If setcc returns 0/-1, all bits are sign bits.
1989 if (TLI.getBooleanContents() ==
1990 TargetLowering::ZeroOrNegativeOneBooleanContent)
1995 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1996 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
1998 // Handle rotate right by N like a rotate left by 32-N.
1999 if (Op.getOpcode() == ISD::ROTR)
2000 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2002 // If we aren't rotating out all of the known-in sign bits, return the
2003 // number that are left. This handles rotl(sext(x), 1) for example.
2004 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2005 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2009 // Add can have at most one carry bit. Thus we know that the output
2010 // is, at worst, one more bit than the inputs.
2011 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2012 if (Tmp == 1) return 1; // Early out.
2014 // Special case decrementing a value (ADD X, -1):
2015 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2016 if (CRHS->isAllOnesValue()) {
2017 APInt KnownZero, KnownOne;
2018 APInt Mask = APInt::getAllOnesValue(VTBits);
2019 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2021 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2023 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2026 // If we are subtracting one from a positive number, there is no carry
2027 // out of the result.
2028 if (KnownZero.isNegative())
2032 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2033 if (Tmp2 == 1) return 1;
2034 return std::min(Tmp, Tmp2)-1;
2038 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2039 if (Tmp2 == 1) return 1;
2042 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2043 if (CLHS->isNullValue()) {
2044 APInt KnownZero, KnownOne;
2045 APInt Mask = APInt::getAllOnesValue(VTBits);
2046 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2047 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2049 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2052 // If the input is known to be positive (the sign bit is known clear),
2053 // the output of the NEG has the same number of sign bits as the input.
2054 if (KnownZero.isNegative())
2057 // Otherwise, we treat this like a SUB.
2060 // Sub can have at most one carry bit. Thus we know that the output
2061 // is, at worst, one more bit than the inputs.
2062 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2063 if (Tmp == 1) return 1; // Early out.
2064 return std::min(Tmp, Tmp2)-1;
2067 // FIXME: it's tricky to do anything useful for this, but it is an important
2068 // case for targets like X86.
2072 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2073 if (Op.getOpcode() == ISD::LOAD) {
2074 LoadSDNode *LD = cast<LoadSDNode>(Op);
2075 unsigned ExtType = LD->getExtensionType();
2078 case ISD::SEXTLOAD: // '17' bits known
2079 Tmp = LD->getMemoryVT().getSizeInBits();
2080 return VTBits-Tmp+1;
2081 case ISD::ZEXTLOAD: // '16' bits known
2082 Tmp = LD->getMemoryVT().getSizeInBits();
2087 // Allow the target to implement this method for its nodes.
2088 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2089 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2090 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2091 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2092 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2093 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2096 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2097 // use this information.
2098 APInt KnownZero, KnownOne;
2099 APInt Mask = APInt::getAllOnesValue(VTBits);
2100 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2102 if (KnownZero.isNegative()) { // sign bit is 0
2104 } else if (KnownOne.isNegative()) { // sign bit is 1;
2111 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2112 // the number of identical bits in the top of the input value.
2114 Mask <<= Mask.getBitWidth()-VTBits;
2115 // Return # leading zeros. We use 'min' here in case Val was zero before
2116 // shifting. We don't want to return '64' as for an i32 "0".
2117 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2121 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2122 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2123 if (!GA) return false;
2124 if (GA->getOffset() != 0) return false;
2125 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2126 if (!GV) return false;
2127 MachineModuleInfo *MMI = getMachineModuleInfo();
2128 return MMI && MMI->hasDebugInfo();
2132 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2133 /// element of the result of the vector shuffle.
2134 SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
2135 MVT VT = N->getValueType(0);
2136 SDValue PermMask = N->getOperand(2);
2137 SDValue Idx = PermMask.getOperand(i);
2138 if (Idx.getOpcode() == ISD::UNDEF)
2139 return getNode(ISD::UNDEF, VT.getVectorElementType());
2140 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
2141 unsigned NumElems = PermMask.getNumOperands();
2142 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2145 if (V.getOpcode() == ISD::BIT_CONVERT) {
2146 V = V.getOperand(0);
2147 MVT VVT = V.getValueType();
2148 if (!VVT.isVector() || VVT.getVectorNumElements() != NumElems)
2151 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2152 return (Index == 0) ? V.getOperand(0)
2153 : getNode(ISD::UNDEF, VT.getVectorElementType());
2154 if (V.getOpcode() == ISD::BUILD_VECTOR)
2155 return V.getOperand(Index);
2156 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
2157 return getShuffleScalarElt(V.getNode(), Index);
2162 /// getNode - Gets or creates the specified node.
2164 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
2165 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT);
2168 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT) {
2169 FoldingSetNodeID ID;
2170 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2172 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2173 return SDValue(E, 0);
2174 SDNode *N = NodeAllocator.Allocate<SDNode>();
2175 new (N) SDNode(Opcode, DL, SDNode::getSDVTList(VT));
2176 CSEMap.InsertNode(N, IP);
2178 AllNodes.push_back(N);
2182 return SDValue(N, 0);
2185 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
2186 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Operand);
2189 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2190 MVT VT, SDValue Operand) {
2191 // Constant fold unary operations with an integer constant operand.
2192 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2193 const APInt &Val = C->getAPIntValue();
2194 unsigned BitWidth = VT.getSizeInBits();
2197 case ISD::SIGN_EXTEND:
2198 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2199 case ISD::ANY_EXTEND:
2200 case ISD::ZERO_EXTEND:
2202 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2203 case ISD::UINT_TO_FP:
2204 case ISD::SINT_TO_FP: {
2205 const uint64_t zero[] = {0, 0};
2206 // No compile time operations on this type.
2207 if (VT==MVT::ppcf128)
2209 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2210 (void)apf.convertFromAPInt(Val,
2211 Opcode==ISD::SINT_TO_FP,
2212 APFloat::rmNearestTiesToEven);
2213 return getConstantFP(apf, VT);
2215 case ISD::BIT_CONVERT:
2216 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2217 return getConstantFP(Val.bitsToFloat(), VT);
2218 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2219 return getConstantFP(Val.bitsToDouble(), VT);
2222 return getConstant(Val.byteSwap(), VT);
2224 return getConstant(Val.countPopulation(), VT);
2226 return getConstant(Val.countLeadingZeros(), VT);
2228 return getConstant(Val.countTrailingZeros(), VT);
2232 // Constant fold unary operations with a floating point constant operand.
2233 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2234 APFloat V = C->getValueAPF(); // make copy
2235 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2239 return getConstantFP(V, VT);
2242 return getConstantFP(V, VT);
2244 case ISD::FP_EXTEND: {
2246 // This can return overflow, underflow, or inexact; we don't care.
2247 // FIXME need to be more flexible about rounding mode.
2248 (void)V.convert(*MVTToAPFloatSemantics(VT),
2249 APFloat::rmNearestTiesToEven, &ignored);
2250 return getConstantFP(V, VT);
2252 case ISD::FP_TO_SINT:
2253 case ISD::FP_TO_UINT: {
2256 assert(integerPartWidth >= 64);
2257 // FIXME need to be more flexible about rounding mode.
2258 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2259 Opcode==ISD::FP_TO_SINT,
2260 APFloat::rmTowardZero, &ignored);
2261 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2263 return getConstant(x, VT);
2265 case ISD::BIT_CONVERT:
2266 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2267 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2268 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2269 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2275 unsigned OpOpcode = Operand.getNode()->getOpcode();
2277 case ISD::TokenFactor:
2278 case ISD::MERGE_VALUES:
2279 case ISD::CONCAT_VECTORS:
2280 return Operand; // Factor, merge or concat of one node? No need.
2281 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2282 case ISD::FP_EXTEND:
2283 assert(VT.isFloatingPoint() &&
2284 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2285 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2286 if (Operand.getOpcode() == ISD::UNDEF)
2287 return getNode(ISD::UNDEF, VT);
2289 case ISD::SIGN_EXTEND:
2290 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2291 "Invalid SIGN_EXTEND!");
2292 if (Operand.getValueType() == VT) return Operand; // noop extension
2293 assert(Operand.getValueType().bitsLT(VT)
2294 && "Invalid sext node, dst < src!");
2295 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2296 return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2298 case ISD::ZERO_EXTEND:
2299 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2300 "Invalid ZERO_EXTEND!");
2301 if (Operand.getValueType() == VT) return Operand; // noop extension
2302 assert(Operand.getValueType().bitsLT(VT)
2303 && "Invalid zext node, dst < src!");
2304 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2305 return getNode(ISD::ZERO_EXTEND, VT, Operand.getNode()->getOperand(0));
2307 case ISD::ANY_EXTEND:
2308 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2309 "Invalid ANY_EXTEND!");
2310 if (Operand.getValueType() == VT) return Operand; // noop extension
2311 assert(Operand.getValueType().bitsLT(VT)
2312 && "Invalid anyext node, dst < src!");
2313 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2314 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2315 return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2318 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2319 "Invalid TRUNCATE!");
2320 if (Operand.getValueType() == VT) return Operand; // noop truncate
2321 assert(Operand.getValueType().bitsGT(VT)
2322 && "Invalid truncate node, src < dst!");
2323 if (OpOpcode == ISD::TRUNCATE)
2324 return getNode(ISD::TRUNCATE, VT, Operand.getNode()->getOperand(0));
2325 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2326 OpOpcode == ISD::ANY_EXTEND) {
2327 // If the source is smaller than the dest, we still need an extend.
2328 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2329 return getNode(OpOpcode, VT, Operand.getNode()->getOperand(0));
2330 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2331 return getNode(ISD::TRUNCATE, VT, Operand.getNode()->getOperand(0));
2333 return Operand.getNode()->getOperand(0);
2336 case ISD::BIT_CONVERT:
2337 // Basic sanity checking.
2338 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2339 && "Cannot BIT_CONVERT between types of different sizes!");
2340 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2341 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2342 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2343 if (OpOpcode == ISD::UNDEF)
2344 return getNode(ISD::UNDEF, VT);
2346 case ISD::SCALAR_TO_VECTOR:
2347 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2348 VT.getVectorElementType() == Operand.getValueType() &&
2349 "Illegal SCALAR_TO_VECTOR node!");
2350 if (OpOpcode == ISD::UNDEF)
2351 return getNode(ISD::UNDEF, VT);
2352 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2353 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2354 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2355 Operand.getConstantOperandVal(1) == 0 &&
2356 Operand.getOperand(0).getValueType() == VT)
2357 return Operand.getOperand(0);
2360 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2361 return getNode(ISD::FSUB, VT, Operand.getNode()->getOperand(1),
2362 Operand.getNode()->getOperand(0));
2363 if (OpOpcode == ISD::FNEG) // --X -> X
2364 return Operand.getNode()->getOperand(0);
2367 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2368 return getNode(ISD::FABS, VT, Operand.getNode()->getOperand(0));
2373 SDVTList VTs = getVTList(VT);
2374 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2375 FoldingSetNodeID ID;
2376 SDValue Ops[1] = { Operand };
2377 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2379 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2380 return SDValue(E, 0);
2381 N = NodeAllocator.Allocate<UnarySDNode>();
2382 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2383 CSEMap.InsertNode(N, IP);
2385 N = NodeAllocator.Allocate<UnarySDNode>();
2386 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2389 AllNodes.push_back(N);
2393 return SDValue(N, 0);
2396 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2398 ConstantSDNode *Cst1,
2399 ConstantSDNode *Cst2) {
2400 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2403 case ISD::ADD: return getConstant(C1 + C2, VT);
2404 case ISD::SUB: return getConstant(C1 - C2, VT);
2405 case ISD::MUL: return getConstant(C1 * C2, VT);
2407 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2410 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2413 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2416 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2418 case ISD::AND: return getConstant(C1 & C2, VT);
2419 case ISD::OR: return getConstant(C1 | C2, VT);
2420 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2421 case ISD::SHL: return getConstant(C1 << C2, VT);
2422 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2423 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2424 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2425 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2432 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2433 SDValue N1, SDValue N2) {
2434 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2);
2437 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2438 SDValue N1, SDValue N2) {
2439 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2440 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2443 case ISD::TokenFactor:
2444 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2445 N2.getValueType() == MVT::Other && "Invalid token factor!");
2446 // Fold trivial token factors.
2447 if (N1.getOpcode() == ISD::EntryToken) return N2;
2448 if (N2.getOpcode() == ISD::EntryToken) return N1;
2449 if (N1 == N2) return N1;
2451 case ISD::CONCAT_VECTORS:
2452 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2453 // one big BUILD_VECTOR.
2454 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2455 N2.getOpcode() == ISD::BUILD_VECTOR) {
2456 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2457 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2458 return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2462 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2463 N1.getValueType() == VT && "Binary operator types must match!");
2464 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2465 // worth handling here.
2466 if (N2C && N2C->isNullValue())
2468 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2475 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2476 N1.getValueType() == VT && "Binary operator types must match!");
2477 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2478 // it's worth handling here.
2479 if (N2C && N2C->isNullValue())
2489 assert(VT.isInteger() && "This operator does not apply to FP types!");
2497 if (Opcode == ISD::FADD) {
2499 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2500 if (CFP->getValueAPF().isZero())
2503 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2504 if (CFP->getValueAPF().isZero())
2506 } else if (Opcode == ISD::FSUB) {
2508 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2509 if (CFP->getValueAPF().isZero())
2513 assert(N1.getValueType() == N2.getValueType() &&
2514 N1.getValueType() == VT && "Binary operator types must match!");
2516 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2517 assert(N1.getValueType() == VT &&
2518 N1.getValueType().isFloatingPoint() &&
2519 N2.getValueType().isFloatingPoint() &&
2520 "Invalid FCOPYSIGN!");
2527 assert(VT == N1.getValueType() &&
2528 "Shift operators return type must be the same as their first arg");
2529 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2530 "Shifts only work on integers");
2531 assert((N2.getValueType() == TLI.getShiftAmountTy() ||
2532 (N2.getValueType().isVector() && N2.getValueType().isInteger())) &&
2533 "Wrong type for shift amount");
2535 // Always fold shifts of i1 values so the code generator doesn't need to
2536 // handle them. Since we know the size of the shift has to be less than the
2537 // size of the value, the shift/rotate count is guaranteed to be zero.
2541 case ISD::FP_ROUND_INREG: {
2542 MVT EVT = cast<VTSDNode>(N2)->getVT();
2543 assert(VT == N1.getValueType() && "Not an inreg round!");
2544 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2545 "Cannot FP_ROUND_INREG integer types");
2546 assert(EVT.bitsLE(VT) && "Not rounding down!");
2547 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2551 assert(VT.isFloatingPoint() &&
2552 N1.getValueType().isFloatingPoint() &&
2553 VT.bitsLE(N1.getValueType()) &&
2554 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2555 if (N1.getValueType() == VT) return N1; // noop conversion.
2557 case ISD::AssertSext:
2558 case ISD::AssertZext: {
2559 MVT EVT = cast<VTSDNode>(N2)->getVT();
2560 assert(VT == N1.getValueType() && "Not an inreg extend!");
2561 assert(VT.isInteger() && EVT.isInteger() &&
2562 "Cannot *_EXTEND_INREG FP types");
2563 assert(EVT.bitsLE(VT) && "Not extending!");
2564 if (VT == EVT) return N1; // noop assertion.
2567 case ISD::SIGN_EXTEND_INREG: {
2568 MVT EVT = cast<VTSDNode>(N2)->getVT();
2569 assert(VT == N1.getValueType() && "Not an inreg extend!");
2570 assert(VT.isInteger() && EVT.isInteger() &&
2571 "Cannot *_EXTEND_INREG FP types");
2572 assert(EVT.bitsLE(VT) && "Not extending!");
2573 if (EVT == VT) return N1; // Not actually extending
2576 APInt Val = N1C->getAPIntValue();
2577 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2578 Val <<= Val.getBitWidth()-FromBits;
2579 Val = Val.ashr(Val.getBitWidth()-FromBits);
2580 return getConstant(Val, VT);
2584 case ISD::EXTRACT_VECTOR_ELT:
2585 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2586 if (N1.getOpcode() == ISD::UNDEF)
2587 return getNode(ISD::UNDEF, VT);
2589 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2590 // expanding copies of large vectors from registers.
2592 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2593 N1.getNumOperands() > 0) {
2595 N1.getOperand(0).getValueType().getVectorNumElements();
2596 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2597 N1.getOperand(N2C->getZExtValue() / Factor),
2598 getConstant(N2C->getZExtValue() % Factor,
2599 N2.getValueType()));
2602 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2603 // expanding large vector constants.
2604 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR)
2605 return N1.getOperand(N2C->getZExtValue());
2607 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2608 // operations are lowered to scalars.
2609 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2610 // If the indices are the same, return the inserted element.
2611 if (N1.getOperand(2) == N2)
2612 return N1.getOperand(1);
2613 // If the indices are known different, extract the element from
2614 // the original vector.
2615 else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2616 isa<ConstantSDNode>(N2))
2617 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2620 case ISD::EXTRACT_ELEMENT:
2621 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2622 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2623 (N1.getValueType().isInteger() == VT.isInteger()) &&
2624 "Wrong types for EXTRACT_ELEMENT!");
2626 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2627 // 64-bit integers into 32-bit parts. Instead of building the extract of
2628 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2629 if (N1.getOpcode() == ISD::BUILD_PAIR)
2630 return N1.getOperand(N2C->getZExtValue());
2632 // EXTRACT_ELEMENT of a constant int is also very common.
2633 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2634 unsigned ElementSize = VT.getSizeInBits();
2635 unsigned Shift = ElementSize * N2C->getZExtValue();
2636 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2637 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2640 case ISD::EXTRACT_SUBVECTOR:
2641 if (N1.getValueType() == VT) // Trivial extraction.
2648 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2649 if (SV.getNode()) return SV;
2650 } else { // Cannonicalize constant to RHS if commutative
2651 if (isCommutativeBinOp(Opcode)) {
2652 std::swap(N1C, N2C);
2658 // Constant fold FP operations.
2659 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2660 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2662 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2663 // Cannonicalize constant to RHS if commutative
2664 std::swap(N1CFP, N2CFP);
2666 } else if (N2CFP && VT != MVT::ppcf128) {
2667 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2668 APFloat::opStatus s;
2671 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2672 if (s != APFloat::opInvalidOp)
2673 return getConstantFP(V1, VT);
2676 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2677 if (s!=APFloat::opInvalidOp)
2678 return getConstantFP(V1, VT);
2681 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2682 if (s!=APFloat::opInvalidOp)
2683 return getConstantFP(V1, VT);
2686 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2687 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2688 return getConstantFP(V1, VT);
2691 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2692 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2693 return getConstantFP(V1, VT);
2695 case ISD::FCOPYSIGN:
2697 return getConstantFP(V1, VT);
2703 // Canonicalize an UNDEF to the RHS, even over a constant.
2704 if (N1.getOpcode() == ISD::UNDEF) {
2705 if (isCommutativeBinOp(Opcode)) {
2709 case ISD::FP_ROUND_INREG:
2710 case ISD::SIGN_EXTEND_INREG:
2716 return N1; // fold op(undef, arg2) -> undef
2724 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2725 // For vectors, we can't easily build an all zero vector, just return
2732 // Fold a bunch of operators when the RHS is undef.
2733 if (N2.getOpcode() == ISD::UNDEF) {
2736 if (N1.getOpcode() == ISD::UNDEF)
2737 // Handle undef ^ undef -> 0 special case. This is a common
2739 return getConstant(0, VT);
2754 return N2; // fold op(arg1, undef) -> undef
2760 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2761 // For vectors, we can't easily build an all zero vector, just return
2766 return getConstant(VT.getIntegerVTBitMask(), VT);
2767 // For vectors, we can't easily build an all one vector, just return
2775 // Memoize this node if possible.
2777 SDVTList VTs = getVTList(VT);
2778 if (VT != MVT::Flag) {
2779 SDValue Ops[] = { N1, N2 };
2780 FoldingSetNodeID ID;
2781 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2783 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2784 return SDValue(E, 0);
2785 N = NodeAllocator.Allocate<BinarySDNode>();
2786 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2787 CSEMap.InsertNode(N, IP);
2789 N = NodeAllocator.Allocate<BinarySDNode>();
2790 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2793 AllNodes.push_back(N);
2797 return SDValue(N, 0);
2800 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2801 SDValue N1, SDValue N2, SDValue N3) {
2802 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3);
2805 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2806 SDValue N1, SDValue N2, SDValue N3) {
2807 // Perform various simplifications.
2808 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2809 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2811 case ISD::CONCAT_VECTORS:
2812 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2813 // one big BUILD_VECTOR.
2814 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2815 N2.getOpcode() == ISD::BUILD_VECTOR &&
2816 N3.getOpcode() == ISD::BUILD_VECTOR) {
2817 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2818 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2819 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2820 return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2824 // Use FoldSetCC to simplify SETCC's.
2825 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2826 if (Simp.getNode()) return Simp;
2831 if (N1C->getZExtValue())
2832 return N2; // select true, X, Y -> X
2834 return N3; // select false, X, Y -> Y
2837 if (N2 == N3) return N2; // select C, X, X -> X
2841 if (N2C->getZExtValue()) // Unconditional branch
2842 return getNode(ISD::BR, MVT::Other, N1, N3);
2844 return N1; // Never-taken branch
2847 case ISD::VECTOR_SHUFFLE:
2848 assert(N1.getValueType() == N2.getValueType() &&
2849 N1.getValueType().isVector() &&
2850 VT.isVector() && N3.getValueType().isVector() &&
2851 N3.getOpcode() == ISD::BUILD_VECTOR &&
2852 VT.getVectorNumElements() == N3.getNumOperands() &&
2853 "Illegal VECTOR_SHUFFLE node!");
2855 case ISD::BIT_CONVERT:
2856 // Fold bit_convert nodes from a type to themselves.
2857 if (N1.getValueType() == VT)
2862 // Memoize node if it doesn't produce a flag.
2864 SDVTList VTs = getVTList(VT);
2865 if (VT != MVT::Flag) {
2866 SDValue Ops[] = { N1, N2, N3 };
2867 FoldingSetNodeID ID;
2868 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2870 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2871 return SDValue(E, 0);
2872 N = NodeAllocator.Allocate<TernarySDNode>();
2873 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2874 CSEMap.InsertNode(N, IP);
2876 N = NodeAllocator.Allocate<TernarySDNode>();
2877 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2879 AllNodes.push_back(N);
2883 return SDValue(N, 0);
2886 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2887 SDValue N1, SDValue N2, SDValue N3,
2889 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3, N4);
2892 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2893 SDValue N1, SDValue N2, SDValue N3,
2895 SDValue Ops[] = { N1, N2, N3, N4 };
2896 return getNode(Opcode, DL, VT, Ops, 4);
2899 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2900 SDValue N1, SDValue N2, SDValue N3,
2901 SDValue N4, SDValue N5) {
2902 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3, N4, N5);
2905 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
2906 SDValue N1, SDValue N2, SDValue N3,
2907 SDValue N4, SDValue N5) {
2908 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2909 return getNode(Opcode, DL, VT, Ops, 5);
2912 /// getMemsetValue - Vectorized representation of the memset value
2914 static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG) {
2915 unsigned NumBits = VT.isVector() ?
2916 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2917 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2918 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
2920 for (unsigned i = NumBits; i > 8; i >>= 1) {
2921 Val = (Val << Shift) | Val;
2925 return DAG.getConstant(Val, VT);
2926 return DAG.getConstantFP(APFloat(Val), VT);
2929 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2930 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2932 for (unsigned i = NumBits; i > 8; i >>= 1) {
2933 Value = DAG.getNode(ISD::OR, VT,
2934 DAG.getNode(ISD::SHL, VT, Value,
2935 DAG.getConstant(Shift,
2936 TLI.getShiftAmountTy())),
2944 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2945 /// used when a memcpy is turned into a memset when the source is a constant
2947 static SDValue getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2948 const TargetLowering &TLI,
2949 std::string &Str, unsigned Offset) {
2950 // Handle vector with all elements zero.
2953 return DAG.getConstant(0, VT);
2954 unsigned NumElts = VT.getVectorNumElements();
2955 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2956 return DAG.getNode(ISD::BIT_CONVERT, VT,
2957 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2960 assert(!VT.isVector() && "Can't handle vector type here!");
2961 unsigned NumBits = VT.getSizeInBits();
2962 unsigned MSB = NumBits / 8;
2964 if (TLI.isLittleEndian())
2965 Offset = Offset + MSB - 1;
2966 for (unsigned i = 0; i != MSB; ++i) {
2967 Val = (Val << 8) | (unsigned char)Str[Offset];
2968 Offset += TLI.isLittleEndian() ? -1 : 1;
2970 return DAG.getConstant(Val, VT);
2973 /// getMemBasePlusOffset - Returns base and offset node for the
2975 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
2976 SelectionDAG &DAG) {
2977 MVT VT = Base.getValueType();
2978 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2981 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2983 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
2984 unsigned SrcDelta = 0;
2985 GlobalAddressSDNode *G = NULL;
2986 if (Src.getOpcode() == ISD::GlobalAddress)
2987 G = cast<GlobalAddressSDNode>(Src);
2988 else if (Src.getOpcode() == ISD::ADD &&
2989 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2990 Src.getOperand(1).getOpcode() == ISD::Constant) {
2991 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2992 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
2997 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2998 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3004 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3005 /// to replace the memset / memcpy is below the threshold. It also returns the
3006 /// types of the sequence of memory ops to perform memset / memcpy.
3008 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
3009 SDValue Dst, SDValue Src,
3010 unsigned Limit, uint64_t Size, unsigned &Align,
3011 std::string &Str, bool &isSrcStr,
3013 const TargetLowering &TLI) {
3014 isSrcStr = isMemSrcFromString(Src, Str);
3015 bool isSrcConst = isa<ConstantSDNode>(Src);
3016 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
3017 MVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
3018 if (VT != MVT::iAny) {
3019 unsigned NewAlign = (unsigned)
3020 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
3021 // If source is a string constant, this will require an unaligned load.
3022 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3023 if (Dst.getOpcode() != ISD::FrameIndex) {
3024 // Can't change destination alignment. It requires a unaligned store.
3028 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3029 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3030 if (MFI->isFixedObjectIndex(FI)) {
3031 // Can't change destination alignment. It requires a unaligned store.
3035 // Give the stack frame object a larger alignment if needed.
3036 if (MFI->getObjectAlignment(FI) < NewAlign)
3037 MFI->setObjectAlignment(FI, NewAlign);
3044 if (VT == MVT::iAny) {
3048 switch (Align & 7) {
3049 case 0: VT = MVT::i64; break;
3050 case 4: VT = MVT::i32; break;
3051 case 2: VT = MVT::i16; break;
3052 default: VT = MVT::i8; break;
3057 while (!TLI.isTypeLegal(LVT))
3058 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
3059 assert(LVT.isInteger());
3065 unsigned NumMemOps = 0;
3067 unsigned VTSize = VT.getSizeInBits() / 8;
3068 while (VTSize > Size) {
3069 // For now, only use non-vector load / store's for the left-over pieces.
3070 if (VT.isVector()) {
3072 while (!TLI.isTypeLegal(VT))
3073 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
3074 VTSize = VT.getSizeInBits() / 8;
3076 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
3081 if (++NumMemOps > Limit)
3083 MemOps.push_back(VT);
3090 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG,
3091 SDValue Chain, SDValue Dst,
3092 SDValue Src, uint64_t Size,
3093 unsigned Align, bool AlwaysInline,
3094 const Value *DstSV, uint64_t DstSVOff,
3095 const Value *SrcSV, uint64_t SrcSVOff){
3096 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3098 // Expand memcpy to a series of load and store ops if the size operand falls
3099 // below a certain threshold.
3100 std::vector<MVT> MemOps;
3101 uint64_t Limit = -1ULL;
3103 Limit = TLI.getMaxStoresPerMemcpy();
3104 unsigned DstAlign = Align; // Destination alignment can change.
3107 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3108 Str, CopyFromStr, DAG, TLI))
3112 bool isZeroStr = CopyFromStr && Str.empty();
3113 SmallVector<SDValue, 8> OutChains;
3114 unsigned NumMemOps = MemOps.size();
3115 uint64_t SrcOff = 0, DstOff = 0;
3116 for (unsigned i = 0; i < NumMemOps; i++) {
3118 unsigned VTSize = VT.getSizeInBits() / 8;
3119 SDValue Value, Store;
3121 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3122 // It's unlikely a store of a vector immediate can be done in a single
3123 // instruction. It would require a load from a constantpool first.
3124 // We also handle store a vector with all zero's.
3125 // FIXME: Handle other cases where store of vector immediate is done in
3126 // a single instruction.
3127 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3128 Store = DAG.getStore(Chain, Value,
3129 getMemBasePlusOffset(Dst, DstOff, DAG),
3130 DstSV, DstSVOff + DstOff, false, DstAlign);
3132 Value = DAG.getLoad(VT, Chain,
3133 getMemBasePlusOffset(Src, SrcOff, DAG),
3134 SrcSV, SrcSVOff + SrcOff, false, Align);
3135 Store = DAG.getStore(Chain, Value,
3136 getMemBasePlusOffset(Dst, DstOff, DAG),
3137 DstSV, DstSVOff + DstOff, false, DstAlign);
3139 OutChains.push_back(Store);
3144 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3145 &OutChains[0], OutChains.size());
3148 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG,
3149 SDValue Chain, SDValue Dst,
3150 SDValue Src, uint64_t Size,
3151 unsigned Align, bool AlwaysInline,
3152 const Value *DstSV, uint64_t DstSVOff,
3153 const Value *SrcSV, uint64_t SrcSVOff){
3154 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3156 // Expand memmove to a series of load and store ops if the size operand falls
3157 // below a certain threshold.
3158 std::vector<MVT> MemOps;
3159 uint64_t Limit = -1ULL;
3161 Limit = TLI.getMaxStoresPerMemmove();
3162 unsigned DstAlign = Align; // Destination alignment can change.
3165 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3166 Str, CopyFromStr, DAG, TLI))
3169 uint64_t SrcOff = 0, DstOff = 0;
3171 SmallVector<SDValue, 8> LoadValues;
3172 SmallVector<SDValue, 8> LoadChains;
3173 SmallVector<SDValue, 8> OutChains;
3174 unsigned NumMemOps = MemOps.size();
3175 for (unsigned i = 0; i < NumMemOps; i++) {
3177 unsigned VTSize = VT.getSizeInBits() / 8;
3178 SDValue Value, Store;
3180 Value = DAG.getLoad(VT, Chain,
3181 getMemBasePlusOffset(Src, SrcOff, DAG),
3182 SrcSV, SrcSVOff + SrcOff, false, Align);
3183 LoadValues.push_back(Value);
3184 LoadChains.push_back(Value.getValue(1));
3187 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
3188 &LoadChains[0], LoadChains.size());
3190 for (unsigned i = 0; i < NumMemOps; i++) {
3192 unsigned VTSize = VT.getSizeInBits() / 8;
3193 SDValue Value, Store;
3195 Store = DAG.getStore(Chain, LoadValues[i],
3196 getMemBasePlusOffset(Dst, DstOff, DAG),
3197 DstSV, DstSVOff + DstOff, false, DstAlign);
3198 OutChains.push_back(Store);
3202 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3203 &OutChains[0], OutChains.size());
3206 static SDValue getMemsetStores(SelectionDAG &DAG,
3207 SDValue Chain, SDValue Dst,
3208 SDValue Src, uint64_t Size,
3210 const Value *DstSV, uint64_t DstSVOff) {
3211 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3213 // Expand memset to a series of load/store ops if the size operand
3214 // falls below a certain threshold.
3215 std::vector<MVT> MemOps;
3218 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3219 Size, Align, Str, CopyFromStr, DAG, TLI))
3222 SmallVector<SDValue, 8> OutChains;
3223 uint64_t DstOff = 0;
3225 unsigned NumMemOps = MemOps.size();
3226 for (unsigned i = 0; i < NumMemOps; i++) {
3228 unsigned VTSize = VT.getSizeInBits() / 8;
3229 SDValue Value = getMemsetValue(Src, VT, DAG);
3230 SDValue Store = DAG.getStore(Chain, Value,
3231 getMemBasePlusOffset(Dst, DstOff, DAG),
3232 DstSV, DstSVOff + DstOff);
3233 OutChains.push_back(Store);
3237 return DAG.getNode(ISD::TokenFactor, MVT::Other,
3238 &OutChains[0], OutChains.size());
3241 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDValue Dst,
3242 SDValue Src, SDValue Size,
3243 unsigned Align, bool AlwaysInline,
3244 const Value *DstSV, uint64_t DstSVOff,
3245 const Value *SrcSV, uint64_t SrcSVOff) {
3247 // Check to see if we should lower the memcpy to loads and stores first.
3248 // For cases within the target-specified limits, this is the best choice.
3249 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3251 // Memcpy with size zero? Just return the original chain.
3252 if (ConstantSize->isNullValue())
3256 getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3257 ConstantSize->getZExtValue(),
3258 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3259 if (Result.getNode())
3263 // Then check to see if we should lower the memcpy with target-specific
3264 // code. If the target chooses to do this, this is the next best.
3266 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
3268 DstSV, DstSVOff, SrcSV, SrcSVOff);
3269 if (Result.getNode())
3272 // If we really need inline code and the target declined to provide it,
3273 // use a (potentially long) sequence of loads and stores.
3275 assert(ConstantSize && "AlwaysInline requires a constant size!");
3276 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
3277 ConstantSize->getZExtValue(), Align, true,
3278 DstSV, DstSVOff, SrcSV, SrcSVOff);
3281 // Emit a library call.
3282 TargetLowering::ArgListTy Args;
3283 TargetLowering::ArgListEntry Entry;
3284 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3285 Entry.Node = Dst; Args.push_back(Entry);
3286 Entry.Node = Src; Args.push_back(Entry);
3287 Entry.Node = Size; Args.push_back(Entry);
3288 // FIXME: pass in DebugLoc
3289 std::pair<SDValue,SDValue> CallResult =
3290 TLI.LowerCallTo(Chain, Type::VoidTy,
3291 false, false, false, false, CallingConv::C, false,
3292 getExternalSymbol("memcpy", TLI.getPointerTy()),
3293 Args, *this, DebugLoc::getUnknownLoc());
3294 return CallResult.second;
3297 SDValue SelectionDAG::getMemmove(SDValue Chain, SDValue Dst,
3298 SDValue Src, SDValue Size,
3300 const Value *DstSV, uint64_t DstSVOff,
3301 const Value *SrcSV, uint64_t SrcSVOff) {
3303 // Check to see if we should lower the memmove to loads and stores first.
3304 // For cases within the target-specified limits, this is the best choice.
3305 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3307 // Memmove with size zero? Just return the original chain.
3308 if (ConstantSize->isNullValue())
3312 getMemmoveLoadsAndStores(*this, Chain, Dst, Src,
3313 ConstantSize->getZExtValue(),
3314 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3315 if (Result.getNode())
3319 // Then check to see if we should lower the memmove with target-specific
3320 // code. If the target chooses to do this, this is the next best.
3322 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
3323 DstSV, DstSVOff, SrcSV, SrcSVOff);
3324 if (Result.getNode())
3327 // Emit a library call.
3328 TargetLowering::ArgListTy Args;
3329 TargetLowering::ArgListEntry Entry;
3330 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3331 Entry.Node = Dst; Args.push_back(Entry);
3332 Entry.Node = Src; Args.push_back(Entry);
3333 Entry.Node = Size; Args.push_back(Entry);
3334 // FIXME: pass in DebugLoc
3335 std::pair<SDValue,SDValue> CallResult =
3336 TLI.LowerCallTo(Chain, Type::VoidTy,
3337 false, false, false, false, CallingConv::C, false,
3338 getExternalSymbol("memmove", TLI.getPointerTy()),
3339 Args, *this, DebugLoc::getUnknownLoc());
3340 return CallResult.second;
3343 SDValue SelectionDAG::getMemset(SDValue Chain, SDValue Dst,
3344 SDValue Src, SDValue Size,
3346 const Value *DstSV, uint64_t DstSVOff) {
3348 // Check to see if we should lower the memset to stores first.
3349 // For cases within the target-specified limits, this is the best choice.
3350 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3352 // Memset with size zero? Just return the original chain.
3353 if (ConstantSize->isNullValue())
3357 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getZExtValue(),
3358 Align, DstSV, DstSVOff);
3359 if (Result.getNode())
3363 // Then check to see if we should lower the memset with target-specific
3364 // code. If the target chooses to do this, this is the next best.
3366 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3368 if (Result.getNode())
3371 // Emit a library call.
3372 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3373 TargetLowering::ArgListTy Args;
3374 TargetLowering::ArgListEntry Entry;
3375 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3376 Args.push_back(Entry);
3377 // Extend or truncate the argument to be an i32 value for the call.
3378 if (Src.getValueType().bitsGT(MVT::i32))
3379 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3381 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3382 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3383 Args.push_back(Entry);
3384 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3385 Args.push_back(Entry);
3386 // FIXME: pass in DebugLoc
3387 std::pair<SDValue,SDValue> CallResult =
3388 TLI.LowerCallTo(Chain, Type::VoidTy,
3389 false, false, false, false, CallingConv::C, false,
3390 getExternalSymbol("memset", TLI.getPointerTy()),
3391 Args, *this, DebugLoc::getUnknownLoc());
3392 return CallResult.second;
3395 SDValue SelectionDAG::getAtomic(unsigned Opcode, MVT MemVT,
3397 SDValue Ptr, SDValue Cmp,
3398 SDValue Swp, const Value* PtrVal,
3399 unsigned Alignment) {
3400 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3401 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3403 MVT VT = Cmp.getValueType();
3405 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3406 Alignment = getMVTAlignment(MemVT);
3408 SDVTList VTs = getVTList(VT, MVT::Other);
3409 FoldingSetNodeID ID;
3410 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3411 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3413 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3414 return SDValue(E, 0);
3415 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3416 new (N) AtomicSDNode(Opcode, VTs, MemVT,
3417 Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3418 CSEMap.InsertNode(N, IP);
3419 AllNodes.push_back(N);
3420 return SDValue(N, 0);
3423 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
3425 SDValue Ptr, SDValue Cmp,
3426 SDValue Swp, const Value* PtrVal,
3427 unsigned Alignment) {
3428 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3429 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3431 MVT VT = Cmp.getValueType();
3433 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3434 Alignment = getMVTAlignment(MemVT);
3436 SDVTList VTs = getVTList(VT, MVT::Other);
3437 FoldingSetNodeID ID;
3438 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3439 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3441 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3442 return SDValue(E, 0);
3443 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3444 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
3445 Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3446 CSEMap.InsertNode(N, IP);
3447 AllNodes.push_back(N);
3448 return SDValue(N, 0);
3451 SDValue SelectionDAG::getAtomic(unsigned Opcode, MVT MemVT,
3453 SDValue Ptr, SDValue Val,
3454 const Value* PtrVal,
3455 unsigned Alignment) {
3456 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3457 Opcode == ISD::ATOMIC_LOAD_SUB ||
3458 Opcode == ISD::ATOMIC_LOAD_AND ||
3459 Opcode == ISD::ATOMIC_LOAD_OR ||
3460 Opcode == ISD::ATOMIC_LOAD_XOR ||
3461 Opcode == ISD::ATOMIC_LOAD_NAND ||
3462 Opcode == ISD::ATOMIC_LOAD_MIN ||
3463 Opcode == ISD::ATOMIC_LOAD_MAX ||
3464 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3465 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3466 Opcode == ISD::ATOMIC_SWAP) &&
3467 "Invalid Atomic Op");
3469 MVT VT = Val.getValueType();
3471 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3472 Alignment = getMVTAlignment(MemVT);
3474 SDVTList VTs = getVTList(VT, MVT::Other);
3475 FoldingSetNodeID ID;
3476 SDValue Ops[] = {Chain, Ptr, Val};
3477 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3479 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3480 return SDValue(E, 0);
3481 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3482 new (N) AtomicSDNode(Opcode, VTs, MemVT,
3483 Chain, Ptr, Val, PtrVal, Alignment);
3484 CSEMap.InsertNode(N, IP);
3485 AllNodes.push_back(N);
3486 return SDValue(N, 0);
3489 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
3491 SDValue Ptr, SDValue Val,
3492 const Value* PtrVal,
3493 unsigned Alignment) {
3494 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3495 Opcode == ISD::ATOMIC_LOAD_SUB ||
3496 Opcode == ISD::ATOMIC_LOAD_AND ||
3497 Opcode == ISD::ATOMIC_LOAD_OR ||
3498 Opcode == ISD::ATOMIC_LOAD_XOR ||
3499 Opcode == ISD::ATOMIC_LOAD_NAND ||
3500 Opcode == ISD::ATOMIC_LOAD_MIN ||
3501 Opcode == ISD::ATOMIC_LOAD_MAX ||
3502 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3503 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3504 Opcode == ISD::ATOMIC_SWAP) &&
3505 "Invalid Atomic Op");
3507 MVT VT = Val.getValueType();
3509 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3510 Alignment = getMVTAlignment(MemVT);
3512 SDVTList VTs = getVTList(VT, MVT::Other);
3513 FoldingSetNodeID ID;
3514 SDValue Ops[] = {Chain, Ptr, Val};
3515 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3517 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3518 return SDValue(E, 0);
3519 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3520 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
3521 Chain, Ptr, Val, PtrVal, Alignment);
3522 CSEMap.InsertNode(N, IP);
3523 AllNodes.push_back(N);
3524 return SDValue(N, 0);
3527 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3528 /// Allowed to return something different (and simpler) if Simplify is true.
3529 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps) {
3533 SmallVector<MVT, 4> VTs;
3534 VTs.reserve(NumOps);
3535 for (unsigned i = 0; i < NumOps; ++i)
3536 VTs.push_back(Ops[i].getValueType());
3537 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3541 SelectionDAG::getMemIntrinsicNode(unsigned Opcode,
3542 const MVT *VTs, unsigned NumVTs,
3543 const SDValue *Ops, unsigned NumOps,
3544 MVT MemVT, const Value *srcValue, int SVOff,
3545 unsigned Align, bool Vol,
3546 bool ReadMem, bool WriteMem) {
3547 return getMemIntrinsicNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps,
3548 MemVT, srcValue, SVOff, Align, Vol,
3553 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3554 const MVT *VTs, unsigned NumVTs,
3555 const SDValue *Ops, unsigned NumOps,
3556 MVT MemVT, const Value *srcValue, int SVOff,
3557 unsigned Align, bool Vol,
3558 bool ReadMem, bool WriteMem) {
3559 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3560 MemVT, srcValue, SVOff, Align, Vol,
3565 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDVTList VTList,
3566 const SDValue *Ops, unsigned NumOps,
3567 MVT MemVT, const Value *srcValue, int SVOff,
3568 unsigned Align, bool Vol,
3569 bool ReadMem, bool WriteMem) {
3570 // Memoize the node unless it returns a flag.
3571 MemIntrinsicSDNode *N;
3572 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3573 FoldingSetNodeID ID;
3574 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3576 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3577 return SDValue(E, 0);
3579 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3580 new (N) MemIntrinsicSDNode(Opcode, VTList, Ops, NumOps, MemVT,
3581 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3582 CSEMap.InsertNode(N, IP);
3584 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3585 new (N) MemIntrinsicSDNode(Opcode, VTList, Ops, NumOps, MemVT,
3586 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3588 AllNodes.push_back(N);
3589 return SDValue(N, 0);
3593 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3594 const SDValue *Ops, unsigned NumOps,
3595 MVT MemVT, const Value *srcValue, int SVOff,
3596 unsigned Align, bool Vol,
3597 bool ReadMem, bool WriteMem) {
3598 // Memoize the node unless it returns a flag.
3599 MemIntrinsicSDNode *N;
3600 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3601 FoldingSetNodeID ID;
3602 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3604 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3605 return SDValue(E, 0);
3607 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3608 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
3609 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3610 CSEMap.InsertNode(N, IP);
3612 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3613 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
3614 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3616 AllNodes.push_back(N);
3617 return SDValue(N, 0);
3621 SelectionDAG::getCall(unsigned CallingConv, bool IsVarArgs, bool IsTailCall,
3622 bool IsInreg, SDVTList VTs,
3623 const SDValue *Operands, unsigned NumOperands) {
3624 // Do not include isTailCall in the folding set profile.
3625 FoldingSetNodeID ID;
3626 AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
3627 ID.AddInteger(CallingConv);
3628 ID.AddInteger(IsVarArgs);
3630 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3631 // Instead of including isTailCall in the folding set, we just
3632 // set the flag of the existing node.
3634 cast<CallSDNode>(E)->setNotTailCall();
3635 return SDValue(E, 0);
3637 SDNode *N = NodeAllocator.Allocate<CallSDNode>();
3638 new (N) CallSDNode(CallingConv, IsVarArgs, IsTailCall, IsInreg,
3639 VTs, Operands, NumOperands);
3640 CSEMap.InsertNode(N, IP);
3641 AllNodes.push_back(N);
3642 return SDValue(N, 0);
3646 SelectionDAG::getCall(unsigned CallingConv, DebugLoc dl, bool IsVarArgs,
3647 bool IsTailCall, bool IsInreg, SDVTList VTs,
3648 const SDValue *Operands, unsigned NumOperands) {
3649 // Do not include isTailCall in the folding set profile.
3650 FoldingSetNodeID ID;
3651 AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
3652 ID.AddInteger(CallingConv);
3653 ID.AddInteger(IsVarArgs);
3655 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3656 // Instead of including isTailCall in the folding set, we just
3657 // set the flag of the existing node.
3659 cast<CallSDNode>(E)->setNotTailCall();
3660 return SDValue(E, 0);
3662 SDNode *N = NodeAllocator.Allocate<CallSDNode>();
3663 new (N) CallSDNode(CallingConv, dl, IsVarArgs, IsTailCall, IsInreg,
3664 VTs, Operands, NumOperands);
3665 CSEMap.InsertNode(N, IP);
3666 AllNodes.push_back(N);
3667 return SDValue(N, 0);
3671 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3672 MVT VT, SDValue Chain,
3673 SDValue Ptr, SDValue Offset,
3674 const Value *SV, int SVOffset, MVT EVT,
3675 bool isVolatile, unsigned Alignment) {
3676 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3677 Alignment = getMVTAlignment(VT);
3680 ExtType = ISD::NON_EXTLOAD;
3681 } else if (ExtType == ISD::NON_EXTLOAD) {
3682 assert(VT == EVT && "Non-extending load from different memory type!");
3686 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3687 "Invalid vector extload!");
3689 assert(EVT.bitsLT(VT) &&
3690 "Should only be an extending load, not truncating!");
3691 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3692 "Cannot sign/zero extend a FP/Vector load!");
3693 assert(VT.isInteger() == EVT.isInteger() &&
3694 "Cannot convert from FP to Int or Int -> FP!");
3697 bool Indexed = AM != ISD::UNINDEXED;
3698 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3699 "Unindexed load with an offset!");
3701 SDVTList VTs = Indexed ?
3702 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3703 SDValue Ops[] = { Chain, Ptr, Offset };
3704 FoldingSetNodeID ID;
3705 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3707 ID.AddInteger(ExtType);
3708 ID.AddInteger(EVT.getRawBits());
3709 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3711 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3712 return SDValue(E, 0);
3713 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3714 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3715 Alignment, isVolatile);
3716 CSEMap.InsertNode(N, IP);
3717 AllNodes.push_back(N);
3718 return SDValue(N, 0);
3722 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3723 ISD::LoadExtType ExtType, MVT VT, SDValue Chain,
3724 SDValue Ptr, SDValue Offset,
3725 const Value *SV, int SVOffset, MVT EVT,
3726 bool isVolatile, unsigned Alignment) {
3727 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3728 Alignment = getMVTAlignment(VT);
3731 ExtType = ISD::NON_EXTLOAD;
3732 } else if (ExtType == ISD::NON_EXTLOAD) {
3733 assert(VT == EVT && "Non-extending load from different memory type!");
3737 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3738 "Invalid vector extload!");
3740 assert(EVT.bitsLT(VT) &&
3741 "Should only be an extending load, not truncating!");
3742 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3743 "Cannot sign/zero extend a FP/Vector load!");
3744 assert(VT.isInteger() == EVT.isInteger() &&
3745 "Cannot convert from FP to Int or Int -> FP!");
3748 bool Indexed = AM != ISD::UNINDEXED;
3749 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3750 "Unindexed load with an offset!");
3752 SDVTList VTs = Indexed ?
3753 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3754 SDValue Ops[] = { Chain, Ptr, Offset };
3755 FoldingSetNodeID ID;
3756 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3758 ID.AddInteger(ExtType);
3759 ID.AddInteger(EVT.getRawBits());
3760 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3762 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3763 return SDValue(E, 0);
3764 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3765 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, EVT, SV, SVOffset,
3766 Alignment, isVolatile);
3767 CSEMap.InsertNode(N, IP);
3768 AllNodes.push_back(N);
3769 return SDValue(N, 0);
3772 SDValue SelectionDAG::getLoad(MVT VT,
3773 SDValue Chain, SDValue Ptr,
3774 const Value *SV, int SVOffset,
3775 bool isVolatile, unsigned Alignment) {
3776 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3777 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3778 SV, SVOffset, VT, isVolatile, Alignment);
3781 SDValue SelectionDAG::getLoad(MVT VT, DebugLoc dl,
3782 SDValue Chain, SDValue Ptr,
3783 const Value *SV, int SVOffset,
3784 bool isVolatile, unsigned Alignment) {
3785 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3786 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3787 SV, SVOffset, VT, isVolatile, Alignment);
3790 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3791 SDValue Chain, SDValue Ptr,
3793 int SVOffset, MVT EVT,
3794 bool isVolatile, unsigned Alignment) {
3795 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3796 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3797 SV, SVOffset, EVT, isVolatile, Alignment);
3800 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, MVT VT,
3801 SDValue Chain, SDValue Ptr,
3803 int SVOffset, MVT EVT,
3804 bool isVolatile, unsigned Alignment) {
3805 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3806 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3807 SV, SVOffset, EVT, isVolatile, Alignment);
3811 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDValue Base,
3812 SDValue Offset, ISD::MemIndexedMode AM) {
3813 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3814 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3815 "Load is already a indexed load!");
3816 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3817 LD->getChain(), Base, Offset, LD->getSrcValue(),
3818 LD->getSrcValueOffset(), LD->getMemoryVT(),
3819 LD->isVolatile(), LD->getAlignment());
3823 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3824 SDValue Offset, ISD::MemIndexedMode AM) {
3825 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3826 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3827 "Load is already a indexed load!");
3828 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3829 LD->getChain(), Base, Offset, LD->getSrcValue(),
3830 LD->getSrcValueOffset(), LD->getMemoryVT(),
3831 LD->isVolatile(), LD->getAlignment());
3834 SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
3835 SDValue Ptr, const Value *SV, int SVOffset,
3836 bool isVolatile, unsigned Alignment) {
3837 MVT VT = Val.getValueType();
3839 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3840 Alignment = getMVTAlignment(VT);
3842 SDVTList VTs = getVTList(MVT::Other);
3843 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3844 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3845 FoldingSetNodeID ID;
3846 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3847 ID.AddInteger(ISD::UNINDEXED);
3848 ID.AddInteger(false);
3849 ID.AddInteger(VT.getRawBits());
3850 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3852 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3853 return SDValue(E, 0);
3854 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3855 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3856 VT, SV, SVOffset, Alignment, isVolatile);
3857 CSEMap.InsertNode(N, IP);
3858 AllNodes.push_back(N);
3859 return SDValue(N, 0);
3862 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3863 SDValue Ptr, const Value *SV, int SVOffset,
3864 bool isVolatile, unsigned Alignment) {
3865 MVT VT = Val.getValueType();
3867 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3868 Alignment = getMVTAlignment(VT);
3870 SDVTList VTs = getVTList(MVT::Other);
3871 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3872 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3873 FoldingSetNodeID ID;
3874 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3875 ID.AddInteger(ISD::UNINDEXED);
3876 ID.AddInteger(false);
3877 ID.AddInteger(VT.getRawBits());
3878 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3880 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3881 return SDValue(E, 0);
3882 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3883 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false,
3884 VT, SV, SVOffset, Alignment, isVolatile);
3885 CSEMap.InsertNode(N, IP);
3886 AllNodes.push_back(N);
3887 return SDValue(N, 0);
3890 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDValue Val,
3891 SDValue Ptr, const Value *SV,
3892 int SVOffset, MVT SVT,
3893 bool isVolatile, unsigned Alignment) {
3894 MVT VT = Val.getValueType();
3897 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3899 assert(VT.bitsGT(SVT) && "Not a truncation?");
3900 assert(VT.isInteger() == SVT.isInteger() &&
3901 "Can't do FP-INT conversion!");
3903 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3904 Alignment = getMVTAlignment(VT);
3906 SDVTList VTs = getVTList(MVT::Other);
3907 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3908 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3909 FoldingSetNodeID ID;
3910 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3911 ID.AddInteger(ISD::UNINDEXED);
3913 ID.AddInteger(SVT.getRawBits());
3914 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3916 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3917 return SDValue(E, 0);
3918 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3919 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3920 SVT, SV, SVOffset, Alignment, isVolatile);
3921 CSEMap.InsertNode(N, IP);
3922 AllNodes.push_back(N);
3923 return SDValue(N, 0);
3926 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3927 SDValue Ptr, const Value *SV,
3928 int SVOffset, MVT SVT,
3929 bool isVolatile, unsigned Alignment) {
3930 MVT VT = Val.getValueType();
3933 return getStore(Chain, dl, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3935 assert(VT.bitsGT(SVT) && "Not a truncation?");
3936 assert(VT.isInteger() == SVT.isInteger() &&
3937 "Can't do FP-INT conversion!");
3939 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3940 Alignment = getMVTAlignment(VT);
3942 SDVTList VTs = getVTList(MVT::Other);
3943 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3944 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3945 FoldingSetNodeID ID;
3946 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3947 ID.AddInteger(ISD::UNINDEXED);
3949 ID.AddInteger(SVT.getRawBits());
3950 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3952 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3953 return SDValue(E, 0);
3954 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3955 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true,
3956 SVT, SV, SVOffset, Alignment, isVolatile);
3957 CSEMap.InsertNode(N, IP);
3958 AllNodes.push_back(N);
3959 return SDValue(N, 0);
3963 SelectionDAG::getIndexedStore(SDValue OrigStore, SDValue Base,
3964 SDValue Offset, ISD::MemIndexedMode AM) {
3965 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3966 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3967 "Store is already a indexed store!");
3968 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3969 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3970 FoldingSetNodeID ID;
3971 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3973 ID.AddInteger(ST->isTruncatingStore());
3974 ID.AddInteger(ST->getMemoryVT().getRawBits());
3975 ID.AddInteger(ST->getRawFlags());
3977 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3978 return SDValue(E, 0);
3979 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3980 new (N) StoreSDNode(Ops, VTs, AM,
3981 ST->isTruncatingStore(), ST->getMemoryVT(),
3982 ST->getSrcValue(), ST->getSrcValueOffset(),
3983 ST->getAlignment(), ST->isVolatile());
3984 CSEMap.InsertNode(N, IP);
3985 AllNodes.push_back(N);
3986 return SDValue(N, 0);
3990 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, 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);
4000 ID.AddInteger(ST->isTruncatingStore());
4001 ID.AddInteger(ST->getMemoryVT().getRawBits());
4002 ID.AddInteger(ST->getRawFlags());
4004 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4005 return SDValue(E, 0);
4006 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
4007 new (N) StoreSDNode(Ops, dl, VTs, AM,
4008 ST->isTruncatingStore(), ST->getMemoryVT(),
4009 ST->getSrcValue(), ST->getSrcValueOffset(),
4010 ST->getAlignment(), ST->isVolatile());
4011 CSEMap.InsertNode(N, IP);
4012 AllNodes.push_back(N);
4013 return SDValue(N, 0);
4016 SDValue SelectionDAG::getVAArg(MVT VT,
4017 SDValue Chain, SDValue Ptr,
4019 SDValue Ops[] = { Chain, Ptr, SV };
4020 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
4023 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
4024 const SDUse *Ops, unsigned NumOps) {
4025 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Ops, NumOps);
4028 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
4029 const SDUse *Ops, unsigned NumOps) {
4031 case 0: return getNode(Opcode, DL, VT);
4032 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4033 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4034 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4038 // Copy from an SDUse array into an SDValue array for use with
4039 // the regular getNode logic.
4040 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4041 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4044 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
4045 const SDValue *Ops, unsigned NumOps) {
4046 return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Ops, NumOps);
4049 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
4050 const SDValue *Ops, unsigned NumOps) {
4052 case 0: return getNode(Opcode, DL, VT);
4053 case 1: return getNode(Opcode, DL, VT, Ops[0]);
4054 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4055 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4061 case ISD::SELECT_CC: {
4062 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4063 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4064 "LHS and RHS of condition must have same type!");
4065 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4066 "True and False arms of SelectCC must have same type!");
4067 assert(Ops[2].getValueType() == VT &&
4068 "select_cc node must be of same type as true and false value!");
4072 assert(NumOps == 5 && "BR_CC takes 5 operands!");
4073 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4074 "LHS/RHS of comparison should match types!");
4081 SDVTList VTs = getVTList(VT);
4083 if (VT != MVT::Flag) {
4084 FoldingSetNodeID ID;
4085 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4088 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4089 return SDValue(E, 0);
4091 N = NodeAllocator.Allocate<SDNode>();
4092 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4093 CSEMap.InsertNode(N, IP);
4095 N = NodeAllocator.Allocate<SDNode>();
4096 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
4099 AllNodes.push_back(N);
4103 return SDValue(N, 0);
4106 SDValue SelectionDAG::getNode(unsigned Opcode,
4107 const std::vector<MVT> &ResultTys,
4108 const SDValue *Ops, unsigned NumOps) {
4109 return getNode(Opcode, DebugLoc::getUnknownLoc(), ResultTys, Ops, NumOps);
4112 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4113 const std::vector<MVT> &ResultTys,
4114 const SDValue *Ops, unsigned NumOps) {
4115 return getNode(Opcode, DL, getNodeValueTypes(ResultTys), ResultTys.size(),
4119 SDValue SelectionDAG::getNode(unsigned Opcode,
4120 const MVT *VTs, unsigned NumVTs,
4121 const SDValue *Ops, unsigned NumOps) {
4122 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTs, NumVTs, Ops, NumOps);
4125 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4126 const MVT *VTs, unsigned NumVTs,
4127 const SDValue *Ops, unsigned NumOps) {
4129 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4130 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4133 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4134 const SDValue *Ops, unsigned NumOps) {
4135 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, Ops, NumOps);
4138 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4139 const SDValue *Ops, unsigned NumOps) {
4140 if (VTList.NumVTs == 1)
4141 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4144 // FIXME: figure out how to safely handle things like
4145 // int foo(int x) { return 1 << (x & 255); }
4146 // int bar() { return foo(256); }
4148 case ISD::SRA_PARTS:
4149 case ISD::SRL_PARTS:
4150 case ISD::SHL_PARTS:
4151 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4152 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4153 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4154 else if (N3.getOpcode() == ISD::AND)
4155 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4156 // If the and is only masking out bits that cannot effect the shift,
4157 // eliminate the and.
4158 unsigned NumBits = VT.getSizeInBits()*2;
4159 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4160 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4166 // Memoize the node unless it returns a flag.
4168 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4169 FoldingSetNodeID ID;
4170 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4172 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4173 return SDValue(E, 0);
4175 N = NodeAllocator.Allocate<UnarySDNode>();
4176 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4177 } else if (NumOps == 2) {
4178 N = NodeAllocator.Allocate<BinarySDNode>();
4179 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4180 } else if (NumOps == 3) {
4181 N = NodeAllocator.Allocate<TernarySDNode>();
4182 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4184 N = NodeAllocator.Allocate<SDNode>();
4185 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4187 CSEMap.InsertNode(N, IP);
4190 N = NodeAllocator.Allocate<UnarySDNode>();
4191 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4192 } else if (NumOps == 2) {
4193 N = NodeAllocator.Allocate<BinarySDNode>();
4194 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4195 } else if (NumOps == 3) {
4196 N = NodeAllocator.Allocate<TernarySDNode>();
4197 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4199 N = NodeAllocator.Allocate<SDNode>();
4200 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4203 AllNodes.push_back(N);
4207 return SDValue(N, 0);
4210 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
4211 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList);
4214 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4215 return getNode(Opcode, DL, VTList, 0, 0);
4218 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4220 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1);
4223 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4225 SDValue Ops[] = { N1 };
4226 return getNode(Opcode, DL, VTList, Ops, 1);
4229 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4230 SDValue N1, SDValue N2) {
4231 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2);
4234 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4235 SDValue N1, SDValue N2) {
4236 SDValue Ops[] = { N1, N2 };
4237 return getNode(Opcode, DL, VTList, Ops, 2);
4240 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4241 SDValue N1, SDValue N2, SDValue N3) {
4242 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3);
4245 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4246 SDValue N1, SDValue N2, SDValue N3) {
4247 SDValue Ops[] = { N1, N2, N3 };
4248 return getNode(Opcode, DL, VTList, Ops, 3);
4251 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4252 SDValue N1, SDValue N2, SDValue N3,
4254 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3, N4);
4257 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4258 SDValue N1, SDValue N2, SDValue N3,
4260 SDValue Ops[] = { N1, N2, N3, N4 };
4261 return getNode(Opcode, DL, VTList, Ops, 4);
4264 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
4265 SDValue N1, SDValue N2, SDValue N3,
4266 SDValue N4, SDValue N5) {
4267 return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3, N4, N5);
4270 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4271 SDValue N1, SDValue N2, SDValue N3,
4272 SDValue N4, SDValue N5) {
4273 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4274 return getNode(Opcode, DL, VTList, Ops, 5);
4277 SDVTList SelectionDAG::getVTList(MVT VT) {
4278 return makeVTList(SDNode::getValueTypeList(VT), 1);
4281 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
4282 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4283 E = VTList.rend(); I != E; ++I)
4284 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4287 MVT *Array = Allocator.Allocate<MVT>(2);
4290 SDVTList Result = makeVTList(Array, 2);
4291 VTList.push_back(Result);
4295 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
4296 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4297 E = VTList.rend(); I != E; ++I)
4298 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4302 MVT *Array = Allocator.Allocate<MVT>(3);
4306 SDVTList Result = makeVTList(Array, 3);
4307 VTList.push_back(Result);
4311 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3, MVT VT4) {
4312 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4313 E = VTList.rend(); I != E; ++I)
4314 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4315 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4318 MVT *Array = Allocator.Allocate<MVT>(3);
4323 SDVTList Result = makeVTList(Array, 4);
4324 VTList.push_back(Result);
4328 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
4330 case 0: assert(0 && "Cannot have nodes without results!");
4331 case 1: return getVTList(VTs[0]);
4332 case 2: return getVTList(VTs[0], VTs[1]);
4333 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4337 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4338 E = VTList.rend(); I != E; ++I) {
4339 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4342 bool NoMatch = false;
4343 for (unsigned i = 2; i != NumVTs; ++i)
4344 if (VTs[i] != I->VTs[i]) {
4352 MVT *Array = Allocator.Allocate<MVT>(NumVTs);
4353 std::copy(VTs, VTs+NumVTs, Array);
4354 SDVTList Result = makeVTList(Array, NumVTs);
4355 VTList.push_back(Result);
4360 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4361 /// specified operands. If the resultant node already exists in the DAG,
4362 /// this does not modify the specified node, instead it returns the node that
4363 /// already exists. If the resultant node does not exist in the DAG, the
4364 /// input node is returned. As a degenerate case, if you specify the same
4365 /// input operands as the node already has, the input node is returned.
4366 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4367 SDNode *N = InN.getNode();
4368 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4370 // Check to see if there is no change.
4371 if (Op == N->getOperand(0)) return InN;
4373 // See if the modified node already exists.
4374 void *InsertPos = 0;
4375 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4376 return SDValue(Existing, InN.getResNo());
4378 // Nope it doesn't. Remove the node from its current place in the maps.
4380 if (!RemoveNodeFromCSEMaps(N))
4383 // Now we update the operands.
4384 N->OperandList[0].set(Op);
4386 // If this gets put into a CSE map, add it.
4387 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4391 SDValue SelectionDAG::
4392 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4393 SDNode *N = InN.getNode();
4394 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4396 // Check to see if there is no change.
4397 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4398 return InN; // No operands changed, just return the input node.
4400 // See if the modified node already exists.
4401 void *InsertPos = 0;
4402 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4403 return SDValue(Existing, InN.getResNo());
4405 // Nope it doesn't. Remove the node from its current place in the maps.
4407 if (!RemoveNodeFromCSEMaps(N))
4410 // Now we update the operands.
4411 if (N->OperandList[0] != Op1)
4412 N->OperandList[0].set(Op1);
4413 if (N->OperandList[1] != Op2)
4414 N->OperandList[1].set(Op2);
4416 // If this gets put into a CSE map, add it.
4417 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4421 SDValue SelectionDAG::
4422 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4423 SDValue Ops[] = { Op1, Op2, Op3 };
4424 return UpdateNodeOperands(N, Ops, 3);
4427 SDValue SelectionDAG::
4428 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4429 SDValue Op3, SDValue Op4) {
4430 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4431 return UpdateNodeOperands(N, Ops, 4);
4434 SDValue SelectionDAG::
4435 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4436 SDValue Op3, SDValue Op4, SDValue Op5) {
4437 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4438 return UpdateNodeOperands(N, Ops, 5);
4441 SDValue SelectionDAG::
4442 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4443 SDNode *N = InN.getNode();
4444 assert(N->getNumOperands() == NumOps &&
4445 "Update with wrong number of operands");
4447 // Check to see if there is no change.
4448 bool AnyChange = false;
4449 for (unsigned i = 0; i != NumOps; ++i) {
4450 if (Ops[i] != N->getOperand(i)) {
4456 // No operands changed, just return the input node.
4457 if (!AnyChange) return InN;
4459 // See if the modified node already exists.
4460 void *InsertPos = 0;
4461 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4462 return SDValue(Existing, InN.getResNo());
4464 // Nope it doesn't. Remove the node from its current place in the maps.
4466 if (!RemoveNodeFromCSEMaps(N))
4469 // Now we update the operands.
4470 for (unsigned i = 0; i != NumOps; ++i)
4471 if (N->OperandList[i] != Ops[i])
4472 N->OperandList[i].set(Ops[i]);
4474 // If this gets put into a CSE map, add it.
4475 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4479 /// DropOperands - Release the operands and set this node to have
4481 void SDNode::DropOperands() {
4482 // Unlike the code in MorphNodeTo that does this, we don't need to
4483 // watch for dead nodes here.
4484 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4490 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4493 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4495 SDVTList VTs = getVTList(VT);
4496 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4499 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4500 MVT VT, SDValue Op1) {
4501 SDVTList VTs = getVTList(VT);
4502 SDValue Ops[] = { Op1 };
4503 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4506 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4507 MVT VT, SDValue Op1,
4509 SDVTList VTs = getVTList(VT);
4510 SDValue Ops[] = { Op1, Op2 };
4511 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4514 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4515 MVT VT, SDValue Op1,
4516 SDValue Op2, SDValue Op3) {
4517 SDVTList VTs = getVTList(VT);
4518 SDValue Ops[] = { Op1, Op2, Op3 };
4519 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4522 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4523 MVT VT, const SDValue *Ops,
4525 SDVTList VTs = getVTList(VT);
4526 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4529 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4530 MVT VT1, MVT VT2, const SDValue *Ops,
4532 SDVTList VTs = getVTList(VT1, VT2);
4533 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4536 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4538 SDVTList VTs = getVTList(VT1, VT2);
4539 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4542 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4543 MVT VT1, MVT VT2, MVT VT3,
4544 const SDValue *Ops, unsigned NumOps) {
4545 SDVTList VTs = getVTList(VT1, VT2, VT3);
4546 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4549 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4550 MVT VT1, MVT VT2, MVT VT3, MVT VT4,
4551 const SDValue *Ops, unsigned NumOps) {
4552 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4553 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4556 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4559 SDVTList VTs = getVTList(VT1, VT2);
4560 SDValue Ops[] = { Op1 };
4561 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4564 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4566 SDValue Op1, SDValue Op2) {
4567 SDVTList VTs = getVTList(VT1, VT2);
4568 SDValue Ops[] = { Op1, Op2 };
4569 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4572 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4574 SDValue Op1, SDValue Op2,
4576 SDVTList VTs = getVTList(VT1, VT2);
4577 SDValue Ops[] = { Op1, Op2, Op3 };
4578 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4581 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4582 MVT VT1, MVT VT2, MVT VT3,
4583 SDValue Op1, SDValue Op2,
4585 SDVTList VTs = getVTList(VT1, VT2, VT3);
4586 SDValue Ops[] = { Op1, Op2, Op3 };
4587 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4590 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4591 SDVTList VTs, const SDValue *Ops,
4593 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4596 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4598 SDVTList VTs = getVTList(VT);
4599 return MorphNodeTo(N, Opc, VTs, 0, 0);
4602 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4603 MVT VT, SDValue Op1) {
4604 SDVTList VTs = getVTList(VT);
4605 SDValue Ops[] = { Op1 };
4606 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4609 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4610 MVT VT, SDValue Op1,
4612 SDVTList VTs = getVTList(VT);
4613 SDValue Ops[] = { Op1, Op2 };
4614 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4617 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4618 MVT VT, SDValue Op1,
4619 SDValue Op2, SDValue Op3) {
4620 SDVTList VTs = getVTList(VT);
4621 SDValue Ops[] = { Op1, Op2, Op3 };
4622 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4625 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4626 MVT VT, const SDValue *Ops,
4628 SDVTList VTs = getVTList(VT);
4629 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4632 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4633 MVT VT1, MVT VT2, const SDValue *Ops,
4635 SDVTList VTs = getVTList(VT1, VT2);
4636 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4639 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4641 SDVTList VTs = getVTList(VT1, VT2);
4642 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4645 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4646 MVT VT1, MVT VT2, MVT VT3,
4647 const SDValue *Ops, unsigned NumOps) {
4648 SDVTList VTs = getVTList(VT1, VT2, VT3);
4649 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4652 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4655 SDVTList VTs = getVTList(VT1, VT2);
4656 SDValue Ops[] = { Op1 };
4657 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4660 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4662 SDValue Op1, SDValue Op2) {
4663 SDVTList VTs = getVTList(VT1, VT2);
4664 SDValue Ops[] = { Op1, Op2 };
4665 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4668 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4670 SDValue Op1, SDValue Op2,
4672 SDVTList VTs = getVTList(VT1, VT2);
4673 SDValue Ops[] = { Op1, Op2, Op3 };
4674 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4677 /// MorphNodeTo - These *mutate* the specified node to have the specified
4678 /// return type, opcode, and operands.
4680 /// Note that MorphNodeTo returns the resultant node. If there is already a
4681 /// node of the specified opcode and operands, it returns that node instead of
4682 /// the current one.
4684 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4685 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4686 /// node, and because it doesn't require CSE recalculation for any of
4687 /// the node's users.
4689 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4690 SDVTList VTs, const SDValue *Ops,
4692 // If an identical node already exists, use it.
4694 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4695 FoldingSetNodeID ID;
4696 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4697 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4701 if (!RemoveNodeFromCSEMaps(N))
4704 // Start the morphing.
4706 N->ValueList = VTs.VTs;
4707 N->NumValues = VTs.NumVTs;
4709 // Clear the operands list, updating used nodes to remove this from their
4710 // use list. Keep track of any operands that become dead as a result.
4711 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4712 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4714 SDNode *Used = Use.getNode();
4716 if (Used->use_empty())
4717 DeadNodeSet.insert(Used);
4720 // If NumOps is larger than the # of operands we currently have, reallocate
4721 // the operand list.
4722 if (NumOps > N->NumOperands) {
4723 if (N->OperandsNeedDelete)
4724 delete[] N->OperandList;
4726 if (N->isMachineOpcode()) {
4727 // We're creating a final node that will live unmorphed for the
4728 // remainder of the current SelectionDAG iteration, so we can allocate
4729 // the operands directly out of a pool with no recycling metadata.
4730 N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
4731 N->OperandsNeedDelete = false;
4733 N->OperandList = new SDUse[NumOps];
4734 N->OperandsNeedDelete = true;
4738 // Assign the new operands.
4739 N->NumOperands = NumOps;
4740 for (unsigned i = 0, e = NumOps; i != e; ++i) {
4741 N->OperandList[i].setUser(N);
4742 N->OperandList[i].setInitial(Ops[i]);
4745 // Delete any nodes that are still dead after adding the uses for the
4747 SmallVector<SDNode *, 16> DeadNodes;
4748 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4749 E = DeadNodeSet.end(); I != E; ++I)
4750 if ((*I)->use_empty())
4751 DeadNodes.push_back(*I);
4752 RemoveDeadNodes(DeadNodes);
4755 CSEMap.InsertNode(N, IP); // Memoize the new node.
4760 /// getTargetNode - These are used for target selectors to create a new node
4761 /// with specified return type(s), target opcode, and operands.
4763 /// Note that getTargetNode returns the resultant node. If there is already a
4764 /// node of the specified opcode and operands, it returns that node instead of
4765 /// the current one.
4766 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
4767 return getNode(~Opcode, VT).getNode();
4769 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT) {
4770 return getNode(~Opcode, dl, VT).getNode();
4773 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
4774 return getNode(~Opcode, VT, Op1).getNode();
4776 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4778 return getNode(~Opcode, dl, VT, Op1).getNode();
4781 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4782 SDValue Op1, SDValue Op2) {
4783 return getNode(~Opcode, VT, Op1, Op2).getNode();
4785 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4786 SDValue Op1, SDValue Op2) {
4787 return getNode(~Opcode, dl, VT, Op1, Op2).getNode();
4790 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4791 SDValue Op1, SDValue Op2,
4793 return getNode(~Opcode, VT, Op1, Op2, Op3).getNode();
4795 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4796 SDValue Op1, SDValue Op2,
4798 return getNode(~Opcode, dl, VT, Op1, Op2, Op3).getNode();
4801 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4802 const SDValue *Ops, unsigned NumOps) {
4803 return getNode(~Opcode, VT, Ops, NumOps).getNode();
4805 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
4806 const SDValue *Ops, unsigned NumOps) {
4807 return getNode(~Opcode, dl, VT, Ops, NumOps).getNode();
4810 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
4811 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4813 return getNode(~Opcode, VTs, 2, &Op, 0).getNode();
4815 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4817 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4819 return getNode(~Opcode, dl, VTs, 2, &Op, 0).getNode();
4822 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4823 MVT VT2, SDValue Op1) {
4824 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4825 return getNode(~Opcode, VTs, 2, &Op1, 1).getNode();
4827 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4828 MVT VT2, SDValue Op1) {
4829 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4830 return getNode(~Opcode, dl, VTs, 2, &Op1, 1).getNode();
4833 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4834 MVT VT2, SDValue Op1,
4836 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4837 SDValue Ops[] = { Op1, Op2 };
4838 return getNode(~Opcode, VTs, 2, Ops, 2).getNode();
4840 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4841 MVT VT2, SDValue Op1,
4843 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4844 SDValue Ops[] = { Op1, Op2 };
4845 return getNode(~Opcode, dl, VTs, 2, Ops, 2).getNode();
4848 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4849 MVT VT2, SDValue Op1,
4850 SDValue Op2, SDValue Op3) {
4851 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4852 SDValue Ops[] = { Op1, Op2, Op3 };
4853 return getNode(~Opcode, VTs, 2, Ops, 3).getNode();
4855 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4856 MVT VT2, SDValue Op1,
4857 SDValue Op2, SDValue Op3) {
4858 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4859 SDValue Ops[] = { Op1, Op2, Op3 };
4860 return getNode(~Opcode, dl, VTs, 2, Ops, 3).getNode();
4863 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
4864 const SDValue *Ops, unsigned NumOps) {
4865 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4866 return getNode(~Opcode, VTs, 2, Ops, NumOps).getNode();
4868 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4870 const SDValue *Ops, unsigned NumOps) {
4871 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4872 return getNode(~Opcode, dl, VTs, 2, Ops, NumOps).getNode();
4875 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4876 SDValue Op1, SDValue Op2) {
4877 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4878 SDValue Ops[] = { Op1, Op2 };
4879 return getNode(~Opcode, VTs, 3, Ops, 2).getNode();
4881 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4882 MVT VT1, MVT VT2, MVT VT3,
4883 SDValue Op1, SDValue Op2) {
4884 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4885 SDValue Ops[] = { Op1, Op2 };
4886 return getNode(~Opcode, dl, VTs, 3, Ops, 2).getNode();
4889 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4890 SDValue Op1, SDValue Op2,
4892 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4893 SDValue Ops[] = { Op1, Op2, Op3 };
4894 return getNode(~Opcode, VTs, 3, Ops, 3).getNode();
4896 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4897 MVT VT1, MVT VT2, MVT VT3,
4898 SDValue Op1, SDValue Op2,
4900 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4901 SDValue Ops[] = { Op1, Op2, Op3 };
4902 return getNode(~Opcode, dl, VTs, 3, Ops, 3).getNode();
4905 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4906 const SDValue *Ops, unsigned NumOps) {
4907 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4908 return getNode(~Opcode, VTs, 3, Ops, NumOps).getNode();
4910 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4911 MVT VT1, MVT VT2, MVT VT3,
4912 const SDValue *Ops, unsigned NumOps) {
4913 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4914 return getNode(~Opcode, VTs, 3, Ops, NumOps).getNode();
4917 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4918 MVT VT2, MVT VT3, MVT VT4,
4919 const SDValue *Ops, unsigned NumOps) {
4920 std::vector<MVT> VTList;
4921 VTList.push_back(VT1);
4922 VTList.push_back(VT2);
4923 VTList.push_back(VT3);
4924 VTList.push_back(VT4);
4925 const MVT *VTs = getNodeValueTypes(VTList);
4926 return getNode(~Opcode, VTs, 4, Ops, NumOps).getNode();
4928 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
4929 MVT VT2, MVT VT3, MVT VT4,
4930 const SDValue *Ops, unsigned NumOps) {
4931 std::vector<MVT> VTList;
4932 VTList.push_back(VT1);
4933 VTList.push_back(VT2);
4934 VTList.push_back(VT3);
4935 VTList.push_back(VT4);
4936 const MVT *VTs = getNodeValueTypes(VTList);
4937 return getNode(~Opcode, dl, VTs, 4, Ops, NumOps).getNode();
4940 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
4941 const std::vector<MVT> &ResultTys,
4942 const SDValue *Ops, unsigned NumOps) {
4943 const MVT *VTs = getNodeValueTypes(ResultTys);
4944 return getNode(~Opcode, VTs, ResultTys.size(),
4945 Ops, NumOps).getNode();
4947 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4948 const std::vector<MVT> &ResultTys,
4949 const SDValue *Ops, unsigned NumOps) {
4950 const MVT *VTs = getNodeValueTypes(ResultTys);
4951 return getNode(~Opcode, dl, VTs, ResultTys.size(),
4952 Ops, NumOps).getNode();
4955 /// getNodeIfExists - Get the specified node if it's already available, or
4956 /// else return NULL.
4957 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4958 const SDValue *Ops, unsigned NumOps) {
4959 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4960 FoldingSetNodeID ID;
4961 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4963 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4969 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4970 /// This can cause recursive merging of nodes in the DAG.
4972 /// This version assumes From has a single result value.
4974 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4975 DAGUpdateListener *UpdateListener) {
4976 SDNode *From = FromN.getNode();
4977 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4978 "Cannot replace with this method!");
4979 assert(From != To.getNode() && "Cannot replace uses of with self");
4981 // Iterate over all the existing uses of From. New uses will be added
4982 // to the beginning of the use list, which we avoid visiting.
4983 // This specifically avoids visiting uses of From that arise while the
4984 // replacement is happening, because any such uses would be the result
4985 // of CSE: If an existing node looks like From after one of its operands
4986 // is replaced by To, we don't want to replace of all its users with To
4987 // too. See PR3018 for more info.
4988 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4992 // This node is about to morph, remove its old self from the CSE maps.
4993 RemoveNodeFromCSEMaps(User);
4995 // A user can appear in a use list multiple times, and when this
4996 // happens the uses are usually next to each other in the list.
4997 // To help reduce the number of CSE recomputations, process all
4998 // the uses of this user that we can find this way.
5000 SDUse &Use = UI.getUse();
5003 } while (UI != UE && *UI == User);
5005 // Now that we have modified User, add it back to the CSE maps. If it
5006 // already exists there, recursively merge the results together.
5007 AddModifiedNodeToCSEMaps(User, UpdateListener);
5011 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5012 /// This can cause recursive merging of nodes in the DAG.
5014 /// This version assumes From/To have matching types and numbers of result
5017 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
5018 DAGUpdateListener *UpdateListener) {
5019 assert(From->getVTList().VTs == To->getVTList().VTs &&
5020 From->getNumValues() == To->getNumValues() &&
5021 "Cannot use this version of ReplaceAllUsesWith!");
5023 // Handle the trivial case.
5027 // Iterate over just the existing users of From. See the comments in
5028 // the ReplaceAllUsesWith above.
5029 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5033 // This node is about to morph, remove its old self from the CSE maps.
5034 RemoveNodeFromCSEMaps(User);
5036 // A user can appear in a use list multiple times, and when this
5037 // happens the uses are usually next to each other in the list.
5038 // To help reduce the number of CSE recomputations, process all
5039 // the uses of this user that we can find this way.
5041 SDUse &Use = UI.getUse();
5044 } while (UI != UE && *UI == User);
5046 // Now that we have modified User, add it back to the CSE maps. If it
5047 // already exists there, recursively merge the results together.
5048 AddModifiedNodeToCSEMaps(User, UpdateListener);
5052 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5053 /// This can cause recursive merging of nodes in the DAG.
5055 /// This version can replace From with any result values. To must match the
5056 /// number and types of values returned by From.
5057 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
5059 DAGUpdateListener *UpdateListener) {
5060 if (From->getNumValues() == 1) // Handle the simple case efficiently.
5061 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
5063 // Iterate over just the existing users of From. See the comments in
5064 // the ReplaceAllUsesWith above.
5065 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5069 // This node is about to morph, remove its old self from the CSE maps.
5070 RemoveNodeFromCSEMaps(User);
5072 // A user can appear in a use list multiple times, and when this
5073 // happens the uses are usually next to each other in the list.
5074 // To help reduce the number of CSE recomputations, process all
5075 // the uses of this user that we can find this way.
5077 SDUse &Use = UI.getUse();
5078 const SDValue &ToOp = To[Use.getResNo()];
5081 } while (UI != UE && *UI == User);
5083 // Now that we have modified User, add it back to the CSE maps. If it
5084 // already exists there, recursively merge the results together.
5085 AddModifiedNodeToCSEMaps(User, UpdateListener);
5089 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5090 /// uses of other values produced by From.getNode() alone. The Deleted
5091 /// vector is handled the same way as for ReplaceAllUsesWith.
5092 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
5093 DAGUpdateListener *UpdateListener){
5094 // Handle the really simple, really trivial case efficiently.
5095 if (From == To) return;
5097 // Handle the simple, trivial, case efficiently.
5098 if (From.getNode()->getNumValues() == 1) {
5099 ReplaceAllUsesWith(From, To, UpdateListener);
5103 // Iterate over just the existing users of From. See the comments in
5104 // the ReplaceAllUsesWith above.
5105 SDNode::use_iterator UI = From.getNode()->use_begin(),
5106 UE = From.getNode()->use_end();
5109 bool UserRemovedFromCSEMaps = false;
5111 // A user can appear in a use list multiple times, and when this
5112 // happens the uses are usually next to each other in the list.
5113 // To help reduce the number of CSE recomputations, process all
5114 // the uses of this user that we can find this way.
5116 SDUse &Use = UI.getUse();
5118 // Skip uses of different values from the same node.
5119 if (Use.getResNo() != From.getResNo()) {
5124 // If this node hasn't been modified yet, it's still in the CSE maps,
5125 // so remove its old self from the CSE maps.
5126 if (!UserRemovedFromCSEMaps) {
5127 RemoveNodeFromCSEMaps(User);
5128 UserRemovedFromCSEMaps = true;
5133 } while (UI != UE && *UI == User);
5135 // We are iterating over all uses of the From node, so if a use
5136 // doesn't use the specific value, no changes are made.
5137 if (!UserRemovedFromCSEMaps)
5140 // Now that we have modified User, add it back to the CSE maps. If it
5141 // already exists there, recursively merge the results together.
5142 AddModifiedNodeToCSEMaps(User, UpdateListener);
5147 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5148 /// to record information about a use.
5155 /// operator< - Sort Memos by User.
5156 bool operator<(const UseMemo &L, const UseMemo &R) {
5157 return (intptr_t)L.User < (intptr_t)R.User;
5161 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5162 /// uses of other values produced by From.getNode() alone. The same value
5163 /// may appear in both the From and To list. The Deleted vector is
5164 /// handled the same way as for ReplaceAllUsesWith.
5165 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5168 DAGUpdateListener *UpdateListener){
5169 // Handle the simple, trivial case efficiently.
5171 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5173 // Read up all the uses and make records of them. This helps
5174 // processing new uses that are introduced during the
5175 // replacement process.
5176 SmallVector<UseMemo, 4> Uses;
5177 for (unsigned i = 0; i != Num; ++i) {
5178 unsigned FromResNo = From[i].getResNo();
5179 SDNode *FromNode = From[i].getNode();
5180 for (SDNode::use_iterator UI = FromNode->use_begin(),
5181 E = FromNode->use_end(); UI != E; ++UI) {
5182 SDUse &Use = UI.getUse();
5183 if (Use.getResNo() == FromResNo) {
5184 UseMemo Memo = { *UI, i, &Use };
5185 Uses.push_back(Memo);
5190 // Sort the uses, so that all the uses from a given User are together.
5191 std::sort(Uses.begin(), Uses.end());
5193 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5194 UseIndex != UseIndexEnd; ) {
5195 // We know that this user uses some value of From. If it is the right
5196 // value, update it.
5197 SDNode *User = Uses[UseIndex].User;
5199 // This node is about to morph, remove its old self from the CSE maps.
5200 RemoveNodeFromCSEMaps(User);
5202 // The Uses array is sorted, so all the uses for a given User
5203 // are next to each other in the list.
5204 // To help reduce the number of CSE recomputations, process all
5205 // the uses of this user that we can find this way.
5207 unsigned i = Uses[UseIndex].Index;
5208 SDUse &Use = *Uses[UseIndex].Use;
5212 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5214 // Now that we have modified User, add it back to the CSE maps. If it
5215 // already exists there, recursively merge the results together.
5216 AddModifiedNodeToCSEMaps(User, UpdateListener);
5220 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5221 /// based on their topological order. It returns the maximum id and a vector
5222 /// of the SDNodes* in assigned order by reference.
5223 unsigned SelectionDAG::AssignTopologicalOrder() {
5225 unsigned DAGSize = 0;
5227 // SortedPos tracks the progress of the algorithm. Nodes before it are
5228 // sorted, nodes after it are unsorted. When the algorithm completes
5229 // it is at the end of the list.
5230 allnodes_iterator SortedPos = allnodes_begin();
5232 // Visit all the nodes. Move nodes with no operands to the front of
5233 // the list immediately. Annotate nodes that do have operands with their
5234 // operand count. Before we do this, the Node Id fields of the nodes
5235 // may contain arbitrary values. After, the Node Id fields for nodes
5236 // before SortedPos will contain the topological sort index, and the
5237 // Node Id fields for nodes At SortedPos and after will contain the
5238 // count of outstanding operands.
5239 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5241 unsigned Degree = N->getNumOperands();
5243 // A node with no uses, add it to the result array immediately.
5244 N->setNodeId(DAGSize++);
5245 allnodes_iterator Q = N;
5247 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5250 // Temporarily use the Node Id as scratch space for the degree count.
5251 N->setNodeId(Degree);
5255 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5256 // such that by the time the end is reached all nodes will be sorted.
5257 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5259 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5262 unsigned Degree = P->getNodeId();
5265 // All of P's operands are sorted, so P may sorted now.
5266 P->setNodeId(DAGSize++);
5268 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5271 // Update P's outstanding operand count.
5272 P->setNodeId(Degree);
5277 assert(SortedPos == AllNodes.end() &&
5278 "Topological sort incomplete!");
5279 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5280 "First node in topological sort is not the entry token!");
5281 assert(AllNodes.front().getNodeId() == 0 &&
5282 "First node in topological sort has non-zero id!");
5283 assert(AllNodes.front().getNumOperands() == 0 &&
5284 "First node in topological sort has operands!");
5285 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5286 "Last node in topologic sort has unexpected id!");
5287 assert(AllNodes.back().use_empty() &&
5288 "Last node in topologic sort has users!");
5289 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5295 //===----------------------------------------------------------------------===//
5297 //===----------------------------------------------------------------------===//
5299 HandleSDNode::~HandleSDNode() {
5303 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
5305 : SDNode(isa<GlobalVariable>(GA) &&
5306 cast<GlobalVariable>(GA)->isThreadLocal() ?
5308 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
5310 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
5311 getSDVTList(VT)), Offset(o) {
5312 TheGlobal = const_cast<GlobalValue*>(GA);
5315 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
5316 const Value *srcValue, int SVO,
5317 unsigned alignment, bool vol)
5318 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
5319 Flags(encodeMemSDNodeFlags(vol, alignment)) {
5321 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5322 assert(getAlignment() == alignment && "Alignment representation error!");
5323 assert(isVolatile() == vol && "Volatile representation error!");
5326 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, const SDValue *Ops,
5327 unsigned NumOps, MVT memvt, const Value *srcValue,
5328 int SVO, unsigned alignment, bool vol)
5329 : SDNode(Opc, VTs, Ops, NumOps),
5330 MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
5331 Flags(vol | ((Log2_32(alignment) + 1) << 1)) {
5332 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5333 assert(getAlignment() == alignment && "Alignment representation error!");
5334 assert(isVolatile() == vol && "Volatile representation error!");
5337 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, MVT memvt,
5338 const Value *srcValue, int SVO,
5339 unsigned alignment, bool vol)
5340 : SDNode(Opc, dl, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
5341 Flags(encodeMemSDNodeFlags(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, DebugLoc dl, SDVTList VTs,
5350 unsigned NumOps, MVT memvt, const Value *srcValue,
5351 int SVO, unsigned alignment, bool vol)
5352 : SDNode(Opc, dl, VTs, Ops, NumOps),
5353 MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
5354 Flags(vol | ((Log2_32(alignment) + 1) << 1)) {
5355 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
5356 assert(getAlignment() == alignment && "Alignment representation error!");
5357 assert(isVolatile() == vol && "Volatile representation error!");
5360 /// getMemOperand - Return a MachineMemOperand object describing the memory
5361 /// reference performed by this memory reference.
5362 MachineMemOperand MemSDNode::getMemOperand() const {
5364 if (isa<LoadSDNode>(this))
5365 Flags = MachineMemOperand::MOLoad;
5366 else if (isa<StoreSDNode>(this))
5367 Flags = MachineMemOperand::MOStore;
5368 else if (isa<AtomicSDNode>(this)) {
5369 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
5372 const MemIntrinsicSDNode* MemIntrinNode = dyn_cast<MemIntrinsicSDNode>(this);
5373 assert(MemIntrinNode && "Unknown MemSDNode opcode!");
5374 if (MemIntrinNode->readMem()) Flags |= MachineMemOperand::MOLoad;
5375 if (MemIntrinNode->writeMem()) Flags |= MachineMemOperand::MOStore;
5378 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
5379 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
5381 // Check if the memory reference references a frame index
5382 const FrameIndexSDNode *FI =
5383 dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
5384 if (!getSrcValue() && FI)
5385 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
5386 Flags, 0, Size, getAlignment());
5388 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
5389 Size, getAlignment());
5392 /// Profile - Gather unique data for the node.
5394 void SDNode::Profile(FoldingSetNodeID &ID) const {
5395 AddNodeIDNode(ID, this);
5398 /// getValueTypeList - Return a pointer to the specified value type.
5400 const MVT *SDNode::getValueTypeList(MVT VT) {
5401 if (VT.isExtended()) {
5402 static std::set<MVT, MVT::compareRawBits> EVTs;
5403 return &(*EVTs.insert(VT).first);
5405 static MVT VTs[MVT::LAST_VALUETYPE];
5406 VTs[VT.getSimpleVT()] = VT;
5407 return &VTs[VT.getSimpleVT()];
5411 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5412 /// indicated value. This method ignores uses of other values defined by this
5414 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5415 assert(Value < getNumValues() && "Bad value!");
5417 // TODO: Only iterate over uses of a given value of the node
5418 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5419 if (UI.getUse().getResNo() == Value) {
5426 // Found exactly the right number of uses?
5431 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5432 /// value. This method ignores uses of other values defined by this operation.
5433 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5434 assert(Value < getNumValues() && "Bad value!");
5436 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5437 if (UI.getUse().getResNo() == Value)
5444 /// isOnlyUserOf - Return true if this node is the only use of N.
5446 bool SDNode::isOnlyUserOf(SDNode *N) const {
5448 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5459 /// isOperand - Return true if this node is an operand of N.
5461 bool SDValue::isOperandOf(SDNode *N) const {
5462 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5463 if (*this == N->getOperand(i))
5468 bool SDNode::isOperandOf(SDNode *N) const {
5469 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5470 if (this == N->OperandList[i].getNode())
5475 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5476 /// be a chain) reaches the specified operand without crossing any
5477 /// side-effecting instructions. In practice, this looks through token
5478 /// factors and non-volatile loads. In order to remain efficient, this only
5479 /// looks a couple of nodes in, it does not do an exhaustive search.
5480 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5481 unsigned Depth) const {
5482 if (*this == Dest) return true;
5484 // Don't search too deeply, we just want to be able to see through
5485 // TokenFactor's etc.
5486 if (Depth == 0) return false;
5488 // If this is a token factor, all inputs to the TF happen in parallel. If any
5489 // of the operands of the TF reach dest, then we can do the xform.
5490 if (getOpcode() == ISD::TokenFactor) {
5491 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5492 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5497 // Loads don't have side effects, look through them.
5498 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5499 if (!Ld->isVolatile())
5500 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5506 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
5507 SmallPtrSet<SDNode *, 32> &Visited) {
5508 if (found || !Visited.insert(N))
5511 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
5512 SDNode *Op = N->getOperand(i).getNode();
5517 findPredecessor(Op, P, found, Visited);
5521 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5522 /// is either an operand of N or it can be reached by recursively traversing
5523 /// up the operands.
5524 /// NOTE: this is an expensive method. Use it carefully.
5525 bool SDNode::isPredecessorOf(SDNode *N) const {
5526 SmallPtrSet<SDNode *, 32> Visited;
5528 findPredecessor(N, this, found, Visited);
5532 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5533 assert(Num < NumOperands && "Invalid child # of SDNode!");
5534 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5537 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5538 switch (getOpcode()) {
5540 if (getOpcode() < ISD::BUILTIN_OP_END)
5541 return "<<Unknown DAG Node>>";
5542 if (isMachineOpcode()) {
5544 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5545 if (getMachineOpcode() < TII->getNumOpcodes())
5546 return TII->get(getMachineOpcode()).getName();
5547 return "<<Unknown Machine Node>>";
5550 const TargetLowering &TLI = G->getTargetLoweringInfo();
5551 const char *Name = TLI.getTargetNodeName(getOpcode());
5552 if (Name) return Name;
5553 return "<<Unknown Target Node>>";
5555 return "<<Unknown Node>>";
5558 case ISD::DELETED_NODE:
5559 return "<<Deleted Node!>>";
5561 case ISD::PREFETCH: return "Prefetch";
5562 case ISD::MEMBARRIER: return "MemBarrier";
5563 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5564 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5565 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5566 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5567 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5568 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5569 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5570 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5571 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5572 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5573 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5574 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5575 case ISD::PCMARKER: return "PCMarker";
5576 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5577 case ISD::SRCVALUE: return "SrcValue";
5578 case ISD::MEMOPERAND: return "MemOperand";
5579 case ISD::EntryToken: return "EntryToken";
5580 case ISD::TokenFactor: return "TokenFactor";
5581 case ISD::AssertSext: return "AssertSext";
5582 case ISD::AssertZext: return "AssertZext";
5584 case ISD::BasicBlock: return "BasicBlock";
5585 case ISD::ARG_FLAGS: return "ArgFlags";
5586 case ISD::VALUETYPE: return "ValueType";
5587 case ISD::Register: return "Register";
5589 case ISD::Constant: return "Constant";
5590 case ISD::ConstantFP: return "ConstantFP";
5591 case ISD::GlobalAddress: return "GlobalAddress";
5592 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5593 case ISD::FrameIndex: return "FrameIndex";
5594 case ISD::JumpTable: return "JumpTable";
5595 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5596 case ISD::RETURNADDR: return "RETURNADDR";
5597 case ISD::FRAMEADDR: return "FRAMEADDR";
5598 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5599 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5600 case ISD::EHSELECTION: return "EHSELECTION";
5601 case ISD::EH_RETURN: return "EH_RETURN";
5602 case ISD::ConstantPool: return "ConstantPool";
5603 case ISD::ExternalSymbol: return "ExternalSymbol";
5604 case ISD::INTRINSIC_WO_CHAIN: {
5605 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
5606 return Intrinsic::getName((Intrinsic::ID)IID);
5608 case ISD::INTRINSIC_VOID:
5609 case ISD::INTRINSIC_W_CHAIN: {
5610 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
5611 return Intrinsic::getName((Intrinsic::ID)IID);
5614 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5615 case ISD::TargetConstant: return "TargetConstant";
5616 case ISD::TargetConstantFP:return "TargetConstantFP";
5617 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5618 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5619 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5620 case ISD::TargetJumpTable: return "TargetJumpTable";
5621 case ISD::TargetConstantPool: return "TargetConstantPool";
5622 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5624 case ISD::CopyToReg: return "CopyToReg";
5625 case ISD::CopyFromReg: return "CopyFromReg";
5626 case ISD::UNDEF: return "undef";
5627 case ISD::MERGE_VALUES: return "merge_values";
5628 case ISD::INLINEASM: return "inlineasm";
5629 case ISD::DBG_LABEL: return "dbg_label";
5630 case ISD::EH_LABEL: return "eh_label";
5631 case ISD::DECLARE: return "declare";
5632 case ISD::HANDLENODE: return "handlenode";
5633 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
5634 case ISD::CALL: return "call";
5637 case ISD::FABS: return "fabs";
5638 case ISD::FNEG: return "fneg";
5639 case ISD::FSQRT: return "fsqrt";
5640 case ISD::FSIN: return "fsin";
5641 case ISD::FCOS: return "fcos";
5642 case ISD::FPOWI: return "fpowi";
5643 case ISD::FPOW: return "fpow";
5644 case ISD::FTRUNC: return "ftrunc";
5645 case ISD::FFLOOR: return "ffloor";
5646 case ISD::FCEIL: return "fceil";
5647 case ISD::FRINT: return "frint";
5648 case ISD::FNEARBYINT: return "fnearbyint";
5651 case ISD::ADD: return "add";
5652 case ISD::SUB: return "sub";
5653 case ISD::MUL: return "mul";
5654 case ISD::MULHU: return "mulhu";
5655 case ISD::MULHS: return "mulhs";
5656 case ISD::SDIV: return "sdiv";
5657 case ISD::UDIV: return "udiv";
5658 case ISD::SREM: return "srem";
5659 case ISD::UREM: return "urem";
5660 case ISD::SMUL_LOHI: return "smul_lohi";
5661 case ISD::UMUL_LOHI: return "umul_lohi";
5662 case ISD::SDIVREM: return "sdivrem";
5663 case ISD::UDIVREM: return "udivrem";
5664 case ISD::AND: return "and";
5665 case ISD::OR: return "or";
5666 case ISD::XOR: return "xor";
5667 case ISD::SHL: return "shl";
5668 case ISD::SRA: return "sra";
5669 case ISD::SRL: return "srl";
5670 case ISD::ROTL: return "rotl";
5671 case ISD::ROTR: return "rotr";
5672 case ISD::FADD: return "fadd";
5673 case ISD::FSUB: return "fsub";
5674 case ISD::FMUL: return "fmul";
5675 case ISD::FDIV: return "fdiv";
5676 case ISD::FREM: return "frem";
5677 case ISD::FCOPYSIGN: return "fcopysign";
5678 case ISD::FGETSIGN: return "fgetsign";
5680 case ISD::SETCC: return "setcc";
5681 case ISD::VSETCC: return "vsetcc";
5682 case ISD::SELECT: return "select";
5683 case ISD::SELECT_CC: return "select_cc";
5684 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5685 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5686 case ISD::CONCAT_VECTORS: return "concat_vectors";
5687 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5688 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5689 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5690 case ISD::CARRY_FALSE: return "carry_false";
5691 case ISD::ADDC: return "addc";
5692 case ISD::ADDE: return "adde";
5693 case ISD::SADDO: return "saddo";
5694 case ISD::UADDO: return "uaddo";
5695 case ISD::SSUBO: return "ssubo";
5696 case ISD::USUBO: return "usubo";
5697 case ISD::SMULO: return "smulo";
5698 case ISD::UMULO: return "umulo";
5699 case ISD::SUBC: return "subc";
5700 case ISD::SUBE: return "sube";
5701 case ISD::SHL_PARTS: return "shl_parts";
5702 case ISD::SRA_PARTS: return "sra_parts";
5703 case ISD::SRL_PARTS: return "srl_parts";
5705 case ISD::EXTRACT_SUBREG: return "extract_subreg";
5706 case ISD::INSERT_SUBREG: return "insert_subreg";
5708 // Conversion operators.
5709 case ISD::SIGN_EXTEND: return "sign_extend";
5710 case ISD::ZERO_EXTEND: return "zero_extend";
5711 case ISD::ANY_EXTEND: return "any_extend";
5712 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5713 case ISD::TRUNCATE: return "truncate";
5714 case ISD::FP_ROUND: return "fp_round";
5715 case ISD::FLT_ROUNDS_: return "flt_rounds";
5716 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5717 case ISD::FP_EXTEND: return "fp_extend";
5719 case ISD::SINT_TO_FP: return "sint_to_fp";
5720 case ISD::UINT_TO_FP: return "uint_to_fp";
5721 case ISD::FP_TO_SINT: return "fp_to_sint";
5722 case ISD::FP_TO_UINT: return "fp_to_uint";
5723 case ISD::BIT_CONVERT: return "bit_convert";
5725 case ISD::CONVERT_RNDSAT: {
5726 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5727 default: assert(0 && "Unknown cvt code!");
5728 case ISD::CVT_FF: return "cvt_ff";
5729 case ISD::CVT_FS: return "cvt_fs";
5730 case ISD::CVT_FU: return "cvt_fu";
5731 case ISD::CVT_SF: return "cvt_sf";
5732 case ISD::CVT_UF: return "cvt_uf";
5733 case ISD::CVT_SS: return "cvt_ss";
5734 case ISD::CVT_SU: return "cvt_su";
5735 case ISD::CVT_US: return "cvt_us";
5736 case ISD::CVT_UU: return "cvt_uu";
5740 // Control flow instructions
5741 case ISD::BR: return "br";
5742 case ISD::BRIND: return "brind";
5743 case ISD::BR_JT: return "br_jt";
5744 case ISD::BRCOND: return "brcond";
5745 case ISD::BR_CC: return "br_cc";
5746 case ISD::RET: return "ret";
5747 case ISD::CALLSEQ_START: return "callseq_start";
5748 case ISD::CALLSEQ_END: return "callseq_end";
5751 case ISD::LOAD: return "load";
5752 case ISD::STORE: return "store";
5753 case ISD::VAARG: return "vaarg";
5754 case ISD::VACOPY: return "vacopy";
5755 case ISD::VAEND: return "vaend";
5756 case ISD::VASTART: return "vastart";
5757 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5758 case ISD::EXTRACT_ELEMENT: return "extract_element";
5759 case ISD::BUILD_PAIR: return "build_pair";
5760 case ISD::STACKSAVE: return "stacksave";
5761 case ISD::STACKRESTORE: return "stackrestore";
5762 case ISD::TRAP: return "trap";
5765 case ISD::BSWAP: return "bswap";
5766 case ISD::CTPOP: return "ctpop";
5767 case ISD::CTTZ: return "cttz";
5768 case ISD::CTLZ: return "ctlz";
5771 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
5772 case ISD::DEBUG_LOC: return "debug_loc";
5775 case ISD::TRAMPOLINE: return "trampoline";
5778 switch (cast<CondCodeSDNode>(this)->get()) {
5779 default: assert(0 && "Unknown setcc condition!");
5780 case ISD::SETOEQ: return "setoeq";
5781 case ISD::SETOGT: return "setogt";
5782 case ISD::SETOGE: return "setoge";
5783 case ISD::SETOLT: return "setolt";
5784 case ISD::SETOLE: return "setole";
5785 case ISD::SETONE: return "setone";
5787 case ISD::SETO: return "seto";
5788 case ISD::SETUO: return "setuo";
5789 case ISD::SETUEQ: return "setue";
5790 case ISD::SETUGT: return "setugt";
5791 case ISD::SETUGE: return "setuge";
5792 case ISD::SETULT: return "setult";
5793 case ISD::SETULE: return "setule";
5794 case ISD::SETUNE: return "setune";
5796 case ISD::SETEQ: return "seteq";
5797 case ISD::SETGT: return "setgt";
5798 case ISD::SETGE: return "setge";
5799 case ISD::SETLT: return "setlt";
5800 case ISD::SETLE: return "setle";
5801 case ISD::SETNE: return "setne";
5806 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5815 return "<post-inc>";
5817 return "<post-dec>";
5821 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5822 std::string S = "< ";
5836 if (getByValAlign())
5837 S += "byval-align:" + utostr(getByValAlign()) + " ";
5839 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5841 S += "byval-size:" + utostr(getByValSize()) + " ";
5845 void SDNode::dump() const { dump(0); }
5846 void SDNode::dump(const SelectionDAG *G) const {
5851 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5852 OS << (void*)this << ": ";
5854 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5856 if (getValueType(i) == MVT::Other)
5859 OS << getValueType(i).getMVTString();
5861 OS << " = " << getOperationName(G);
5864 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5866 OS << (void*)getOperand(i).getNode();
5867 if (unsigned RN = getOperand(i).getResNo())
5871 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
5872 SDNode *Mask = getOperand(2).getNode();
5874 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
5876 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
5879 OS << cast<ConstantSDNode>(Mask->getOperand(i))->getZExtValue();
5884 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5885 OS << '<' << CSDN->getAPIntValue() << '>';
5886 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5887 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5888 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5889 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5890 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5893 CSDN->getValueAPF().bitcastToAPInt().dump();
5896 } else if (const GlobalAddressSDNode *GADN =
5897 dyn_cast<GlobalAddressSDNode>(this)) {
5898 int64_t offset = GADN->getOffset();
5900 WriteAsOperand(OS, GADN->getGlobal());
5903 OS << " + " << offset;
5905 OS << " " << offset;
5906 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5907 OS << "<" << FIDN->getIndex() << ">";
5908 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5909 OS << "<" << JTDN->getIndex() << ">";
5910 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5911 int offset = CP->getOffset();
5912 if (CP->isMachineConstantPoolEntry())
5913 OS << "<" << *CP->getMachineCPVal() << ">";
5915 OS << "<" << *CP->getConstVal() << ">";
5917 OS << " + " << offset;
5919 OS << " " << offset;
5920 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5922 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5924 OS << LBB->getName() << " ";
5925 OS << (const void*)BBDN->getBasicBlock() << ">";
5926 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5927 if (G && R->getReg() &&
5928 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5929 OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5931 OS << " #" << R->getReg();
5933 } else if (const ExternalSymbolSDNode *ES =
5934 dyn_cast<ExternalSymbolSDNode>(this)) {
5935 OS << "'" << ES->getSymbol() << "'";
5936 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5938 OS << "<" << M->getValue() << ">";
5941 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5942 if (M->MO.getValue())
5943 OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5945 OS << "<null:" << M->MO.getOffset() << ">";
5946 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5947 OS << N->getArgFlags().getArgFlagsString();
5948 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5949 OS << ":" << N->getVT().getMVTString();
5951 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5952 const Value *SrcValue = LD->getSrcValue();
5953 int SrcOffset = LD->getSrcValueOffset();
5959 OS << ":" << SrcOffset << ">";
5962 switch (LD->getExtensionType()) {
5963 default: doExt = false; break;
5964 case ISD::EXTLOAD: OS << " <anyext "; break;
5965 case ISD::SEXTLOAD: OS << " <sext "; break;
5966 case ISD::ZEXTLOAD: OS << " <zext "; break;
5969 OS << LD->getMemoryVT().getMVTString() << ">";
5971 const char *AM = getIndexedModeName(LD->getAddressingMode());
5974 if (LD->isVolatile())
5975 OS << " <volatile>";
5976 OS << " alignment=" << LD->getAlignment();
5977 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5978 const Value *SrcValue = ST->getSrcValue();
5979 int SrcOffset = ST->getSrcValueOffset();
5985 OS << ":" << SrcOffset << ">";
5987 if (ST->isTruncatingStore())
5988 OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
5990 const char *AM = getIndexedModeName(ST->getAddressingMode());
5993 if (ST->isVolatile())
5994 OS << " <volatile>";
5995 OS << " alignment=" << ST->getAlignment();
5996 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5997 const Value *SrcValue = AT->getSrcValue();
5998 int SrcOffset = AT->getSrcValueOffset();
6004 OS << ":" << SrcOffset << ">";
6005 if (AT->isVolatile())
6006 OS << " <volatile>";
6007 OS << " alignment=" << AT->getAlignment();
6011 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
6012 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6013 if (N->getOperand(i).getNode()->hasOneUse())
6014 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
6016 cerr << "\n" << std::string(indent+2, ' ')
6017 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
6020 cerr << "\n" << std::string(indent, ' ');
6024 void SelectionDAG::dump() const {
6025 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
6027 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
6029 const SDNode *N = I;
6030 if (!N->hasOneUse() && N != getRoot().getNode())
6031 DumpNodes(N, 2, this);
6034 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
6039 const Type *ConstantPoolSDNode::getType() const {
6040 if (isMachineConstantPoolEntry())
6041 return Val.MachineCPVal->getType();
6042 return Val.ConstVal->getType();