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/Function.h"
17 #include "llvm/GlobalAlias.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetIntrinsicInfo.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/ManagedStatic.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/System/Mutex.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/SmallVector.h"
45 #include "llvm/ADT/StringExtras.h"
50 /// makeVTList - Return an instance of the SDVTList struct initialized with the
51 /// specified members.
52 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
53 SDVTList Res = {VTs, NumVTs};
57 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
58 switch (VT.getSimpleVT().SimpleTy) {
59 default: llvm_unreachable("Unknown FP format");
60 case MVT::f32: return &APFloat::IEEEsingle;
61 case MVT::f64: return &APFloat::IEEEdouble;
62 case MVT::f80: return &APFloat::x87DoubleExtended;
63 case MVT::f128: return &APFloat::IEEEquad;
64 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
68 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
70 //===----------------------------------------------------------------------===//
71 // ConstantFPSDNode Class
72 //===----------------------------------------------------------------------===//
74 /// isExactlyValue - We don't rely on operator== working on double values, as
75 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
76 /// As such, this method can be used to do an exact bit-for-bit comparison of
77 /// two floating point values.
78 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
79 return getValueAPF().bitwiseIsEqual(V);
82 bool ConstantFPSDNode::isValueValidForType(EVT VT,
84 assert(VT.isFloatingPoint() && "Can only convert between FP types");
86 // PPC long double cannot be converted to any other type.
87 if (VT == MVT::ppcf128 ||
88 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
91 // convert modifies in place, so make a copy.
92 APFloat Val2 = APFloat(Val);
94 (void) Val2.convert(*EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
99 //===----------------------------------------------------------------------===//
101 //===----------------------------------------------------------------------===//
103 /// isBuildVectorAllOnes - Return true if the specified node is a
104 /// BUILD_VECTOR where all of the elements are ~0 or undef.
105 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
106 // Look through a bit convert.
107 if (N->getOpcode() == ISD::BIT_CONVERT)
108 N = N->getOperand(0).getNode();
110 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
112 unsigned i = 0, e = N->getNumOperands();
114 // Skip over all of the undef values.
115 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
118 // Do not accept an all-undef vector.
119 if (i == e) return false;
121 // Do not accept build_vectors that aren't all constants or which have non-~0
123 SDValue NotZero = N->getOperand(i);
124 if (isa<ConstantSDNode>(NotZero)) {
125 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
127 } else if (isa<ConstantFPSDNode>(NotZero)) {
128 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
129 bitcastToAPInt().isAllOnesValue())
134 // Okay, we have at least one ~0 value, check to see if the rest match or are
136 for (++i; i != e; ++i)
137 if (N->getOperand(i) != NotZero &&
138 N->getOperand(i).getOpcode() != ISD::UNDEF)
144 /// isBuildVectorAllZeros - Return true if the specified node is a
145 /// BUILD_VECTOR where all of the elements are 0 or undef.
146 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
147 // Look through a bit convert.
148 if (N->getOpcode() == ISD::BIT_CONVERT)
149 N = N->getOperand(0).getNode();
151 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
153 unsigned i = 0, e = N->getNumOperands();
155 // Skip over all of the undef values.
156 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
159 // Do not accept an all-undef vector.
160 if (i == e) return false;
162 // Do not accept build_vectors that aren't all constants or which have non-0
164 SDValue Zero = N->getOperand(i);
165 if (isa<ConstantSDNode>(Zero)) {
166 if (!cast<ConstantSDNode>(Zero)->isNullValue())
168 } else if (isa<ConstantFPSDNode>(Zero)) {
169 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
174 // Okay, we have at least one 0 value, check to see if the rest match or are
176 for (++i; i != e; ++i)
177 if (N->getOperand(i) != Zero &&
178 N->getOperand(i).getOpcode() != ISD::UNDEF)
183 /// isScalarToVector - Return true if the specified node is a
184 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
185 /// element is not an undef.
186 bool ISD::isScalarToVector(const SDNode *N) {
187 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
190 if (N->getOpcode() != ISD::BUILD_VECTOR)
192 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
194 unsigned NumElems = N->getNumOperands();
195 for (unsigned i = 1; i < NumElems; ++i) {
196 SDValue V = N->getOperand(i);
197 if (V.getOpcode() != ISD::UNDEF)
203 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
204 /// when given the operation for (X op Y).
205 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
206 // To perform this operation, we just need to swap the L and G bits of the
208 unsigned OldL = (Operation >> 2) & 1;
209 unsigned OldG = (Operation >> 1) & 1;
210 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
211 (OldL << 1) | // New G bit
212 (OldG << 2)); // New L bit.
215 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
216 /// 'op' is a valid SetCC operation.
217 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
218 unsigned Operation = Op;
220 Operation ^= 7; // Flip L, G, E bits, but not U.
222 Operation ^= 15; // Flip all of the condition bits.
224 if (Operation > ISD::SETTRUE2)
225 Operation &= ~8; // Don't let N and U bits get set.
227 return ISD::CondCode(Operation);
231 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
232 /// signed operation and 2 if the result is an unsigned comparison. Return zero
233 /// if the operation does not depend on the sign of the input (setne and seteq).
234 static int isSignedOp(ISD::CondCode Opcode) {
236 default: llvm_unreachable("Illegal integer setcc operation!");
238 case ISD::SETNE: return 0;
242 case ISD::SETGE: return 1;
246 case ISD::SETUGE: return 2;
250 /// getSetCCOrOperation - Return the result of a logical OR between different
251 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
252 /// returns SETCC_INVALID if it is not possible to represent the resultant
254 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
256 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
257 // Cannot fold a signed integer setcc with an unsigned integer setcc.
258 return ISD::SETCC_INVALID;
260 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
262 // If the N and U bits get set then the resultant comparison DOES suddenly
263 // care about orderedness, and is true when ordered.
264 if (Op > ISD::SETTRUE2)
265 Op &= ~16; // Clear the U bit if the N bit is set.
267 // Canonicalize illegal integer setcc's.
268 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
271 return ISD::CondCode(Op);
274 /// getSetCCAndOperation - Return the result of a logical AND between different
275 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
276 /// function returns zero if it is not possible to represent the resultant
278 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
280 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
281 // Cannot fold a signed setcc with an unsigned setcc.
282 return ISD::SETCC_INVALID;
284 // Combine all of the condition bits.
285 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
287 // Canonicalize illegal integer setcc's.
291 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
292 case ISD::SETOEQ: // SETEQ & SETU[LG]E
293 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
294 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
295 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
302 const TargetMachine &SelectionDAG::getTarget() const {
303 return MF->getTarget();
306 //===----------------------------------------------------------------------===//
307 // SDNode Profile Support
308 //===----------------------------------------------------------------------===//
310 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
312 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
316 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
317 /// solely with their pointer.
318 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
319 ID.AddPointer(VTList.VTs);
322 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
324 static void AddNodeIDOperands(FoldingSetNodeID &ID,
325 const SDValue *Ops, unsigned NumOps) {
326 for (; NumOps; --NumOps, ++Ops) {
327 ID.AddPointer(Ops->getNode());
328 ID.AddInteger(Ops->getResNo());
332 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
334 static void AddNodeIDOperands(FoldingSetNodeID &ID,
335 const SDUse *Ops, unsigned NumOps) {
336 for (; NumOps; --NumOps, ++Ops) {
337 ID.AddPointer(Ops->getNode());
338 ID.AddInteger(Ops->getResNo());
342 static void AddNodeIDNode(FoldingSetNodeID &ID,
343 unsigned short OpC, SDVTList VTList,
344 const SDValue *OpList, unsigned N) {
345 AddNodeIDOpcode(ID, OpC);
346 AddNodeIDValueTypes(ID, VTList);
347 AddNodeIDOperands(ID, OpList, N);
350 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
352 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
353 switch (N->getOpcode()) {
354 case ISD::TargetExternalSymbol:
355 case ISD::ExternalSymbol:
356 llvm_unreachable("Should only be used on nodes with operands");
357 default: break; // Normal nodes don't need extra info.
358 case ISD::TargetConstant:
360 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
362 case ISD::TargetConstantFP:
363 case ISD::ConstantFP: {
364 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
367 case ISD::TargetGlobalAddress:
368 case ISD::GlobalAddress:
369 case ISD::TargetGlobalTLSAddress:
370 case ISD::GlobalTLSAddress: {
371 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
372 ID.AddPointer(GA->getGlobal());
373 ID.AddInteger(GA->getOffset());
374 ID.AddInteger(GA->getTargetFlags());
377 case ISD::BasicBlock:
378 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
381 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
385 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
387 case ISD::FrameIndex:
388 case ISD::TargetFrameIndex:
389 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
392 case ISD::TargetJumpTable:
393 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
394 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
396 case ISD::ConstantPool:
397 case ISD::TargetConstantPool: {
398 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
399 ID.AddInteger(CP->getAlignment());
400 ID.AddInteger(CP->getOffset());
401 if (CP->isMachineConstantPoolEntry())
402 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
404 ID.AddPointer(CP->getConstVal());
405 ID.AddInteger(CP->getTargetFlags());
409 const LoadSDNode *LD = cast<LoadSDNode>(N);
410 ID.AddInteger(LD->getMemoryVT().getRawBits());
411 ID.AddInteger(LD->getRawSubclassData());
415 const StoreSDNode *ST = cast<StoreSDNode>(N);
416 ID.AddInteger(ST->getMemoryVT().getRawBits());
417 ID.AddInteger(ST->getRawSubclassData());
420 case ISD::ATOMIC_CMP_SWAP:
421 case ISD::ATOMIC_SWAP:
422 case ISD::ATOMIC_LOAD_ADD:
423 case ISD::ATOMIC_LOAD_SUB:
424 case ISD::ATOMIC_LOAD_AND:
425 case ISD::ATOMIC_LOAD_OR:
426 case ISD::ATOMIC_LOAD_XOR:
427 case ISD::ATOMIC_LOAD_NAND:
428 case ISD::ATOMIC_LOAD_MIN:
429 case ISD::ATOMIC_LOAD_MAX:
430 case ISD::ATOMIC_LOAD_UMIN:
431 case ISD::ATOMIC_LOAD_UMAX: {
432 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
433 ID.AddInteger(AT->getMemoryVT().getRawBits());
434 ID.AddInteger(AT->getRawSubclassData());
437 case ISD::VECTOR_SHUFFLE: {
438 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
439 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
441 ID.AddInteger(SVN->getMaskElt(i));
444 case ISD::TargetBlockAddress:
445 case ISD::BlockAddress: {
446 ID.AddPointer(cast<BlockAddressSDNode>(N)->getBlockAddress());
447 ID.AddInteger(cast<BlockAddressSDNode>(N)->getTargetFlags());
450 } // end switch (N->getOpcode())
453 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
455 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
456 AddNodeIDOpcode(ID, N->getOpcode());
457 // Add the return value info.
458 AddNodeIDValueTypes(ID, N->getVTList());
459 // Add the operand info.
460 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
462 // Handle SDNode leafs with special info.
463 AddNodeIDCustom(ID, N);
466 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
467 /// the CSE map that carries volatility, indexing mode, and
468 /// extension/truncation information.
470 static inline unsigned
471 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile) {
472 assert((ConvType & 3) == ConvType &&
473 "ConvType may not require more than 2 bits!");
474 assert((AM & 7) == AM &&
475 "AM may not require more than 3 bits!");
481 //===----------------------------------------------------------------------===//
482 // SelectionDAG Class
483 //===----------------------------------------------------------------------===//
485 /// doNotCSE - Return true if CSE should not be performed for this node.
486 static bool doNotCSE(SDNode *N) {
487 if (N->getValueType(0) == MVT::Flag)
488 return true; // Never CSE anything that produces a flag.
490 switch (N->getOpcode()) {
492 case ISD::HANDLENODE:
494 return true; // Never CSE these nodes.
497 // Check that remaining values produced are not flags.
498 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
499 if (N->getValueType(i) == MVT::Flag)
500 return true; // Never CSE anything that produces a flag.
505 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
507 void SelectionDAG::RemoveDeadNodes() {
508 // Create a dummy node (which is not added to allnodes), that adds a reference
509 // to the root node, preventing it from being deleted.
510 HandleSDNode Dummy(getRoot());
512 SmallVector<SDNode*, 128> DeadNodes;
514 // Add all obviously-dead nodes to the DeadNodes worklist.
515 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
517 DeadNodes.push_back(I);
519 RemoveDeadNodes(DeadNodes);
521 // If the root changed (e.g. it was a dead load, update the root).
522 setRoot(Dummy.getValue());
525 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
526 /// given list, and any nodes that become unreachable as a result.
527 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
528 DAGUpdateListener *UpdateListener) {
530 // Process the worklist, deleting the nodes and adding their uses to the
532 while (!DeadNodes.empty()) {
533 SDNode *N = DeadNodes.pop_back_val();
536 UpdateListener->NodeDeleted(N, 0);
538 // Take the node out of the appropriate CSE map.
539 RemoveNodeFromCSEMaps(N);
541 // Next, brutally remove the operand list. This is safe to do, as there are
542 // no cycles in the graph.
543 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
545 SDNode *Operand = Use.getNode();
548 // Now that we removed this operand, see if there are no uses of it left.
549 if (Operand->use_empty())
550 DeadNodes.push_back(Operand);
557 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
558 SmallVector<SDNode*, 16> DeadNodes(1, N);
559 RemoveDeadNodes(DeadNodes, UpdateListener);
562 void SelectionDAG::DeleteNode(SDNode *N) {
563 // First take this out of the appropriate CSE map.
564 RemoveNodeFromCSEMaps(N);
566 // Finally, remove uses due to operands of this node, remove from the
567 // AllNodes list, and delete the node.
568 DeleteNodeNotInCSEMaps(N);
571 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
572 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
573 assert(N->use_empty() && "Cannot delete a node that is not dead!");
575 // Drop all of the operands and decrement used node's use counts.
581 void SelectionDAG::DeallocateNode(SDNode *N) {
582 if (N->OperandsNeedDelete)
583 delete[] N->OperandList;
585 // Set the opcode to DELETED_NODE to help catch bugs when node
586 // memory is reallocated.
587 N->NodeType = ISD::DELETED_NODE;
589 NodeAllocator.Deallocate(AllNodes.remove(N));
592 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
593 /// correspond to it. This is useful when we're about to delete or repurpose
594 /// the node. We don't want future request for structurally identical nodes
595 /// to return N anymore.
596 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
598 switch (N->getOpcode()) {
599 case ISD::EntryToken:
600 llvm_unreachable("EntryToken should not be in CSEMaps!");
602 case ISD::HANDLENODE: return false; // noop.
604 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
605 "Cond code doesn't exist!");
606 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
607 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
609 case ISD::ExternalSymbol:
610 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
612 case ISD::TargetExternalSymbol: {
613 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
614 Erased = TargetExternalSymbols.erase(
615 std::pair<std::string,unsigned char>(ESN->getSymbol(),
616 ESN->getTargetFlags()));
619 case ISD::VALUETYPE: {
620 EVT VT = cast<VTSDNode>(N)->getVT();
621 if (VT.isExtended()) {
622 Erased = ExtendedValueTypeNodes.erase(VT);
624 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
625 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
630 // Remove it from the CSE Map.
631 Erased = CSEMap.RemoveNode(N);
635 // Verify that the node was actually in one of the CSE maps, unless it has a
636 // flag result (which cannot be CSE'd) or is one of the special cases that are
637 // not subject to CSE.
638 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
639 !N->isMachineOpcode() && !doNotCSE(N)) {
642 llvm_unreachable("Node is not in map!");
648 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
649 /// maps and modified in place. Add it back to the CSE maps, unless an identical
650 /// node already exists, in which case transfer all its users to the existing
651 /// node. This transfer can potentially trigger recursive merging.
654 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
655 DAGUpdateListener *UpdateListener) {
656 // For node types that aren't CSE'd, just act as if no identical node
659 SDNode *Existing = CSEMap.GetOrInsertNode(N);
661 // If there was already an existing matching node, use ReplaceAllUsesWith
662 // to replace the dead one with the existing one. This can cause
663 // recursive merging of other unrelated nodes down the line.
664 ReplaceAllUsesWith(N, Existing, UpdateListener);
666 // N is now dead. Inform the listener if it exists and delete it.
668 UpdateListener->NodeDeleted(N, Existing);
669 DeleteNodeNotInCSEMaps(N);
674 // If the node doesn't already exist, we updated it. Inform a listener if
677 UpdateListener->NodeUpdated(N);
680 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
681 /// were replaced with those specified. If this node is never memoized,
682 /// return null, otherwise return a pointer to the slot it would take. If a
683 /// node already exists with these operands, the slot will be non-null.
684 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
689 SDValue Ops[] = { Op };
691 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
692 AddNodeIDCustom(ID, N);
693 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
696 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
697 /// were replaced with those specified. If this node is never memoized,
698 /// return null, otherwise return a pointer to the slot it would take. If a
699 /// node already exists with these operands, the slot will be non-null.
700 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
701 SDValue Op1, SDValue Op2,
706 SDValue Ops[] = { Op1, Op2 };
708 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
709 AddNodeIDCustom(ID, N);
710 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
714 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
715 /// were replaced with those specified. If this node is never memoized,
716 /// return null, otherwise return a pointer to the slot it would take. If a
717 /// node already exists with these operands, the slot will be non-null.
718 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
719 const SDValue *Ops,unsigned NumOps,
725 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
726 AddNodeIDCustom(ID, N);
727 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
730 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
731 void SelectionDAG::VerifyNode(SDNode *N) {
732 switch (N->getOpcode()) {
735 case ISD::BUILD_PAIR: {
736 EVT VT = N->getValueType(0);
737 assert(N->getNumValues() == 1 && "Too many results!");
738 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
739 "Wrong return type!");
740 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
741 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
742 "Mismatched operand types!");
743 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
744 "Wrong operand type!");
745 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
746 "Wrong return type size");
749 case ISD::BUILD_VECTOR: {
750 assert(N->getNumValues() == 1 && "Too many results!");
751 assert(N->getValueType(0).isVector() && "Wrong return type!");
752 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
753 "Wrong number of operands!");
754 EVT EltVT = N->getValueType(0).getVectorElementType();
755 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
756 assert((I->getValueType() == EltVT ||
757 (EltVT.isInteger() && I->getValueType().isInteger() &&
758 EltVT.bitsLE(I->getValueType()))) &&
759 "Wrong operand type!");
765 /// getEVTAlignment - Compute the default alignment value for the
768 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
769 const Type *Ty = VT == MVT::iPTR ?
770 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
771 VT.getTypeForEVT(*getContext());
773 return TLI.getTargetData()->getABITypeAlignment(Ty);
776 // EntryNode could meaningfully have debug info if we can find it...
777 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
778 : TLI(tli), FLI(fli), DW(0),
779 EntryNode(ISD::EntryToken, DebugLoc::getUnknownLoc(),
780 getVTList(MVT::Other)), Root(getEntryNode()) {
781 AllNodes.push_back(&EntryNode);
784 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
789 Context = &mf.getFunction()->getContext();
792 SelectionDAG::~SelectionDAG() {
796 void SelectionDAG::allnodes_clear() {
797 assert(&*AllNodes.begin() == &EntryNode);
798 AllNodes.remove(AllNodes.begin());
799 while (!AllNodes.empty())
800 DeallocateNode(AllNodes.begin());
803 void SelectionDAG::clear() {
805 OperandAllocator.Reset();
808 ExtendedValueTypeNodes.clear();
809 ExternalSymbols.clear();
810 TargetExternalSymbols.clear();
811 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
812 static_cast<CondCodeSDNode*>(0));
813 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
814 static_cast<SDNode*>(0));
816 EntryNode.UseList = 0;
817 AllNodes.push_back(&EntryNode);
818 Root = getEntryNode();
821 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
822 return VT.bitsGT(Op.getValueType()) ?
823 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
824 getNode(ISD::TRUNCATE, DL, VT, Op);
827 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, DebugLoc DL, EVT VT) {
828 return VT.bitsGT(Op.getValueType()) ?
829 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
830 getNode(ISD::TRUNCATE, DL, VT, Op);
833 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, EVT VT) {
834 if (Op.getValueType() == VT) return Op;
835 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
837 return getNode(ISD::AND, DL, Op.getValueType(), Op,
838 getConstant(Imm, Op.getValueType()));
841 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
843 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, EVT VT) {
844 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
846 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
847 return getNode(ISD::XOR, DL, VT, Val, NegOne);
850 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
851 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
852 assert((EltVT.getSizeInBits() >= 64 ||
853 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
854 "getConstant with a uint64_t value that doesn't fit in the type!");
855 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
858 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
859 return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
862 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
863 assert(VT.isInteger() && "Cannot create FP integer constant!");
865 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
866 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
867 "APInt size does not match type size!");
869 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
871 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
875 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
877 return SDValue(N, 0);
879 N = NodeAllocator.Allocate<ConstantSDNode>();
880 new (N) ConstantSDNode(isT, &Val, EltVT);
881 CSEMap.InsertNode(N, IP);
882 AllNodes.push_back(N);
885 SDValue Result(N, 0);
887 SmallVector<SDValue, 8> Ops;
888 Ops.assign(VT.getVectorNumElements(), Result);
889 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
890 VT, &Ops[0], Ops.size());
895 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
896 return getConstant(Val, TLI.getPointerTy(), isTarget);
900 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
901 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
904 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
905 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
908 VT.isVector() ? VT.getVectorElementType() : VT;
910 // Do the map lookup using the actual bit pattern for the floating point
911 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
912 // we don't have issues with SNANs.
913 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
915 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
919 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
921 return SDValue(N, 0);
923 N = NodeAllocator.Allocate<ConstantFPSDNode>();
924 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
925 CSEMap.InsertNode(N, IP);
926 AllNodes.push_back(N);
929 SDValue Result(N, 0);
931 SmallVector<SDValue, 8> Ops;
932 Ops.assign(VT.getVectorNumElements(), Result);
933 // FIXME DebugLoc info might be appropriate here
934 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
935 VT, &Ops[0], Ops.size());
940 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
942 VT.isVector() ? VT.getVectorElementType() : VT;
944 return getConstantFP(APFloat((float)Val), VT, isTarget);
946 return getConstantFP(APFloat(Val), VT, isTarget);
949 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
950 EVT VT, int64_t Offset,
952 unsigned char TargetFlags) {
953 assert((TargetFlags == 0 || isTargetGA) &&
954 "Cannot set target flags on target-independent globals");
956 // Truncate (with sign-extension) the offset value to the pointer size.
957 EVT PTy = TLI.getPointerTy();
958 unsigned BitWidth = PTy.getSizeInBits();
960 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
962 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
964 // If GV is an alias then use the aliasee for determining thread-localness.
965 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
966 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
970 if (GVar && GVar->isThreadLocal())
971 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
973 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
976 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
978 ID.AddInteger(Offset);
979 ID.AddInteger(TargetFlags);
981 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
982 return SDValue(E, 0);
983 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
984 new (N) GlobalAddressSDNode(Opc, GV, VT, Offset, TargetFlags);
985 CSEMap.InsertNode(N, IP);
986 AllNodes.push_back(N);
987 return SDValue(N, 0);
990 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
991 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
993 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
996 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
997 return SDValue(E, 0);
998 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
999 new (N) FrameIndexSDNode(FI, VT, isTarget);
1000 CSEMap.InsertNode(N, IP);
1001 AllNodes.push_back(N);
1002 return SDValue(N, 0);
1005 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1006 unsigned char TargetFlags) {
1007 assert((TargetFlags == 0 || isTarget) &&
1008 "Cannot set target flags on target-independent jump tables");
1009 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1010 FoldingSetNodeID ID;
1011 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1013 ID.AddInteger(TargetFlags);
1015 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1016 return SDValue(E, 0);
1017 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1018 new (N) JumpTableSDNode(JTI, VT, isTarget, TargetFlags);
1019 CSEMap.InsertNode(N, IP);
1020 AllNodes.push_back(N);
1021 return SDValue(N, 0);
1024 SDValue SelectionDAG::getConstantPool(Constant *C, EVT VT,
1025 unsigned Alignment, int Offset,
1027 unsigned char TargetFlags) {
1028 assert((TargetFlags == 0 || isTarget) &&
1029 "Cannot set target flags on target-independent globals");
1031 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1032 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1033 FoldingSetNodeID ID;
1034 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1035 ID.AddInteger(Alignment);
1036 ID.AddInteger(Offset);
1038 ID.AddInteger(TargetFlags);
1040 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1041 return SDValue(E, 0);
1042 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1043 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1044 CSEMap.InsertNode(N, IP);
1045 AllNodes.push_back(N);
1046 return SDValue(N, 0);
1050 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1051 unsigned Alignment, int Offset,
1053 unsigned char TargetFlags) {
1054 assert((TargetFlags == 0 || isTarget) &&
1055 "Cannot set target flags on target-independent globals");
1057 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1058 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1059 FoldingSetNodeID ID;
1060 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1061 ID.AddInteger(Alignment);
1062 ID.AddInteger(Offset);
1063 C->AddSelectionDAGCSEId(ID);
1064 ID.AddInteger(TargetFlags);
1066 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1067 return SDValue(E, 0);
1068 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1069 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1070 CSEMap.InsertNode(N, IP);
1071 AllNodes.push_back(N);
1072 return SDValue(N, 0);
1075 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1076 FoldingSetNodeID ID;
1077 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1080 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1081 return SDValue(E, 0);
1082 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1083 new (N) BasicBlockSDNode(MBB);
1084 CSEMap.InsertNode(N, IP);
1085 AllNodes.push_back(N);
1086 return SDValue(N, 0);
1089 SDValue SelectionDAG::getValueType(EVT VT) {
1090 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1091 ValueTypeNodes.size())
1092 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1094 SDNode *&N = VT.isExtended() ?
1095 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1097 if (N) return SDValue(N, 0);
1098 N = NodeAllocator.Allocate<VTSDNode>();
1099 new (N) VTSDNode(VT);
1100 AllNodes.push_back(N);
1101 return SDValue(N, 0);
1104 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1105 SDNode *&N = ExternalSymbols[Sym];
1106 if (N) return SDValue(N, 0);
1107 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1108 new (N) ExternalSymbolSDNode(false, Sym, 0, VT);
1109 AllNodes.push_back(N);
1110 return SDValue(N, 0);
1113 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1114 unsigned char TargetFlags) {
1116 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1118 if (N) return SDValue(N, 0);
1119 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1120 new (N) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1121 AllNodes.push_back(N);
1122 return SDValue(N, 0);
1125 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1126 if ((unsigned)Cond >= CondCodeNodes.size())
1127 CondCodeNodes.resize(Cond+1);
1129 if (CondCodeNodes[Cond] == 0) {
1130 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1131 new (N) CondCodeSDNode(Cond);
1132 CondCodeNodes[Cond] = N;
1133 AllNodes.push_back(N);
1135 return SDValue(CondCodeNodes[Cond], 0);
1138 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1139 // the shuffle mask M that point at N1 to point at N2, and indices that point
1140 // N2 to point at N1.
1141 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1143 int NElts = M.size();
1144 for (int i = 0; i != NElts; ++i) {
1152 SDValue SelectionDAG::getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1,
1153 SDValue N2, const int *Mask) {
1154 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1155 assert(VT.isVector() && N1.getValueType().isVector() &&
1156 "Vector Shuffle VTs must be a vectors");
1157 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1158 && "Vector Shuffle VTs must have same element type");
1160 // Canonicalize shuffle undef, undef -> undef
1161 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1162 return getUNDEF(VT);
1164 // Validate that all indices in Mask are within the range of the elements
1165 // input to the shuffle.
1166 unsigned NElts = VT.getVectorNumElements();
1167 SmallVector<int, 8> MaskVec;
1168 for (unsigned i = 0; i != NElts; ++i) {
1169 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1170 MaskVec.push_back(Mask[i]);
1173 // Canonicalize shuffle v, v -> v, undef
1176 for (unsigned i = 0; i != NElts; ++i)
1177 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1180 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1181 if (N1.getOpcode() == ISD::UNDEF)
1182 commuteShuffle(N1, N2, MaskVec);
1184 // Canonicalize all index into lhs, -> shuffle lhs, undef
1185 // Canonicalize all index into rhs, -> shuffle rhs, undef
1186 bool AllLHS = true, AllRHS = true;
1187 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1188 for (unsigned i = 0; i != NElts; ++i) {
1189 if (MaskVec[i] >= (int)NElts) {
1194 } else if (MaskVec[i] >= 0) {
1198 if (AllLHS && AllRHS)
1199 return getUNDEF(VT);
1200 if (AllLHS && !N2Undef)
1204 commuteShuffle(N1, N2, MaskVec);
1207 // If Identity shuffle, or all shuffle in to undef, return that node.
1208 bool AllUndef = true;
1209 bool Identity = true;
1210 for (unsigned i = 0; i != NElts; ++i) {
1211 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1212 if (MaskVec[i] >= 0) AllUndef = false;
1214 if (Identity && NElts == N1.getValueType().getVectorNumElements())
1217 return getUNDEF(VT);
1219 FoldingSetNodeID ID;
1220 SDValue Ops[2] = { N1, N2 };
1221 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1222 for (unsigned i = 0; i != NElts; ++i)
1223 ID.AddInteger(MaskVec[i]);
1226 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1227 return SDValue(E, 0);
1229 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1230 // SDNode doesn't have access to it. This memory will be "leaked" when
1231 // the node is deallocated, but recovered when the NodeAllocator is released.
1232 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1233 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1235 ShuffleVectorSDNode *N = NodeAllocator.Allocate<ShuffleVectorSDNode>();
1236 new (N) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
1237 CSEMap.InsertNode(N, IP);
1238 AllNodes.push_back(N);
1239 return SDValue(N, 0);
1242 SDValue SelectionDAG::getConvertRndSat(EVT VT, DebugLoc dl,
1243 SDValue Val, SDValue DTy,
1244 SDValue STy, SDValue Rnd, SDValue Sat,
1245 ISD::CvtCode Code) {
1246 // If the src and dest types are the same and the conversion is between
1247 // integer types of the same sign or two floats, no conversion is necessary.
1249 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1252 FoldingSetNodeID ID;
1253 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1254 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), &Ops[0], 5);
1256 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1257 return SDValue(E, 0);
1258 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
1259 new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code);
1260 CSEMap.InsertNode(N, IP);
1261 AllNodes.push_back(N);
1262 return SDValue(N, 0);
1265 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1266 FoldingSetNodeID ID;
1267 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1268 ID.AddInteger(RegNo);
1270 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1271 return SDValue(E, 0);
1272 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1273 new (N) RegisterSDNode(RegNo, VT);
1274 CSEMap.InsertNode(N, IP);
1275 AllNodes.push_back(N);
1276 return SDValue(N, 0);
1279 SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
1282 FoldingSetNodeID ID;
1283 SDValue Ops[] = { Root };
1284 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1285 ID.AddInteger(LabelID);
1287 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1288 return SDValue(E, 0);
1289 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1290 new (N) LabelSDNode(Opcode, dl, Root, LabelID);
1291 CSEMap.InsertNode(N, IP);
1292 AllNodes.push_back(N);
1293 return SDValue(N, 0);
1296 SDValue SelectionDAG::getBlockAddress(BlockAddress *BA, EVT VT,
1298 unsigned char TargetFlags) {
1299 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1301 FoldingSetNodeID ID;
1302 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1304 ID.AddInteger(TargetFlags);
1306 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1307 return SDValue(E, 0);
1308 SDNode *N = NodeAllocator.Allocate<BlockAddressSDNode>();
1309 new (N) BlockAddressSDNode(Opc, VT, BA, TargetFlags);
1310 CSEMap.InsertNode(N, IP);
1311 AllNodes.push_back(N);
1312 return SDValue(N, 0);
1315 SDValue SelectionDAG::getSrcValue(const Value *V) {
1316 assert((!V || isa<PointerType>(V->getType())) &&
1317 "SrcValue is not a pointer?");
1319 FoldingSetNodeID ID;
1320 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1324 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1325 return SDValue(E, 0);
1327 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1328 new (N) SrcValueSDNode(V);
1329 CSEMap.InsertNode(N, IP);
1330 AllNodes.push_back(N);
1331 return SDValue(N, 0);
1334 /// getShiftAmountOperand - Return the specified value casted to
1335 /// the target's desired shift amount type.
1336 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
1337 EVT OpTy = Op.getValueType();
1338 MVT ShTy = TLI.getShiftAmountTy();
1339 if (OpTy == ShTy || OpTy.isVector()) return Op;
1341 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1342 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
1345 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1346 /// specified value type.
1347 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1348 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1349 unsigned ByteSize = VT.getStoreSize();
1350 const Type *Ty = VT.getTypeForEVT(*getContext());
1351 unsigned StackAlign =
1352 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1354 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
1355 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1358 /// CreateStackTemporary - Create a stack temporary suitable for holding
1359 /// either of the specified value types.
1360 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1361 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1362 VT2.getStoreSizeInBits())/8;
1363 const Type *Ty1 = VT1.getTypeForEVT(*getContext());
1364 const Type *Ty2 = VT2.getTypeForEVT(*getContext());
1365 const TargetData *TD = TLI.getTargetData();
1366 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1367 TD->getPrefTypeAlignment(Ty2));
1369 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1370 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false);
1371 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1374 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1375 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1376 // These setcc operations always fold.
1380 case ISD::SETFALSE2: return getConstant(0, VT);
1382 case ISD::SETTRUE2: return getConstant(1, VT);
1394 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1398 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1399 const APInt &C2 = N2C->getAPIntValue();
1400 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1401 const APInt &C1 = N1C->getAPIntValue();
1404 default: llvm_unreachable("Unknown integer setcc!");
1405 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1406 case ISD::SETNE: return getConstant(C1 != C2, VT);
1407 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1408 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1409 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1410 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1411 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1412 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1413 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1414 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1418 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1419 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1420 // No compile time operations on this type yet.
1421 if (N1C->getValueType(0) == MVT::ppcf128)
1424 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1427 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1428 return getUNDEF(VT);
1430 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1431 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1432 return getUNDEF(VT);
1434 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1435 R==APFloat::cmpLessThan, VT);
1436 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1437 return getUNDEF(VT);
1439 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1440 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1441 return getUNDEF(VT);
1443 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1444 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1445 return getUNDEF(VT);
1447 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1448 R==APFloat::cmpEqual, VT);
1449 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1450 return getUNDEF(VT);
1452 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1453 R==APFloat::cmpEqual, VT);
1454 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1455 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1456 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1457 R==APFloat::cmpEqual, VT);
1458 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1459 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1460 R==APFloat::cmpLessThan, VT);
1461 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1462 R==APFloat::cmpUnordered, VT);
1463 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1464 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1467 // Ensure that the constant occurs on the RHS.
1468 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1472 // Could not fold it.
1476 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1477 /// use this predicate to simplify operations downstream.
1478 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1479 // This predicate is not safe for vector operations.
1480 if (Op.getValueType().isVector())
1483 unsigned BitWidth = Op.getValueSizeInBits();
1484 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1487 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1488 /// this predicate to simplify operations downstream. Mask is known to be zero
1489 /// for bits that V cannot have.
1490 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1491 unsigned Depth) const {
1492 APInt KnownZero, KnownOne;
1493 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1494 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1495 return (KnownZero & Mask) == Mask;
1498 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1499 /// known to be either zero or one and return them in the KnownZero/KnownOne
1500 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1502 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1503 APInt &KnownZero, APInt &KnownOne,
1504 unsigned Depth) const {
1505 unsigned BitWidth = Mask.getBitWidth();
1506 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1507 "Mask size mismatches value type size!");
1509 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1510 if (Depth == 6 || Mask == 0)
1511 return; // Limit search depth.
1513 APInt KnownZero2, KnownOne2;
1515 switch (Op.getOpcode()) {
1517 // We know all of the bits for a constant!
1518 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1519 KnownZero = ~KnownOne & Mask;
1522 // If either the LHS or the RHS are Zero, the result is zero.
1523 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1524 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1525 KnownZero2, KnownOne2, Depth+1);
1526 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1527 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1529 // Output known-1 bits are only known if set in both the LHS & RHS.
1530 KnownOne &= KnownOne2;
1531 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1532 KnownZero |= KnownZero2;
1535 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1536 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1537 KnownZero2, KnownOne2, Depth+1);
1538 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1539 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1541 // Output known-0 bits are only known if clear in both the LHS & RHS.
1542 KnownZero &= KnownZero2;
1543 // Output known-1 are known to be set if set in either the LHS | RHS.
1544 KnownOne |= KnownOne2;
1547 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1548 ComputeMaskedBits(Op.getOperand(0), 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 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1553 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1554 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1555 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1556 KnownZero = KnownZeroOut;
1560 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1561 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1562 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1563 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1564 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1566 // If low bits are zero in either operand, output low known-0 bits.
1567 // Also compute a conserative estimate for high known-0 bits.
1568 // More trickiness is possible, but this is sufficient for the
1569 // interesting case of alignment computation.
1571 unsigned TrailZ = KnownZero.countTrailingOnes() +
1572 KnownZero2.countTrailingOnes();
1573 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1574 KnownZero2.countLeadingOnes(),
1575 BitWidth) - BitWidth;
1577 TrailZ = std::min(TrailZ, BitWidth);
1578 LeadZ = std::min(LeadZ, BitWidth);
1579 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1580 APInt::getHighBitsSet(BitWidth, LeadZ);
1585 // For the purposes of computing leading zeros we can conservatively
1586 // treat a udiv as a logical right shift by the power of 2 known to
1587 // be less than the denominator.
1588 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1589 ComputeMaskedBits(Op.getOperand(0),
1590 AllOnes, KnownZero2, KnownOne2, Depth+1);
1591 unsigned LeadZ = KnownZero2.countLeadingOnes();
1595 ComputeMaskedBits(Op.getOperand(1),
1596 AllOnes, KnownZero2, KnownOne2, Depth+1);
1597 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1598 if (RHSUnknownLeadingOnes != BitWidth)
1599 LeadZ = std::min(BitWidth,
1600 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1602 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1606 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1607 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1608 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1609 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1611 // Only known if known in both the LHS and RHS.
1612 KnownOne &= KnownOne2;
1613 KnownZero &= KnownZero2;
1615 case ISD::SELECT_CC:
1616 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1617 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1618 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1619 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1621 // Only known if known in both the LHS and RHS.
1622 KnownOne &= KnownOne2;
1623 KnownZero &= KnownZero2;
1631 if (Op.getResNo() != 1)
1633 // The boolean result conforms to getBooleanContents. Fall through.
1635 // If we know the result of a setcc has the top bits zero, use this info.
1636 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1638 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1641 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1642 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1643 unsigned ShAmt = SA->getZExtValue();
1645 // If the shift count is an invalid immediate, don't do anything.
1646 if (ShAmt >= BitWidth)
1649 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1650 KnownZero, KnownOne, Depth+1);
1651 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1652 KnownZero <<= ShAmt;
1654 // low bits known zero.
1655 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1659 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1660 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1661 unsigned ShAmt = SA->getZExtValue();
1663 // If the shift count is an invalid immediate, don't do anything.
1664 if (ShAmt >= BitWidth)
1667 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1668 KnownZero, KnownOne, Depth+1);
1669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1670 KnownZero = KnownZero.lshr(ShAmt);
1671 KnownOne = KnownOne.lshr(ShAmt);
1673 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1674 KnownZero |= HighBits; // High bits known zero.
1678 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1679 unsigned ShAmt = SA->getZExtValue();
1681 // If the shift count is an invalid immediate, don't do anything.
1682 if (ShAmt >= BitWidth)
1685 APInt InDemandedMask = (Mask << ShAmt);
1686 // If any of the demanded bits are produced by the sign extension, we also
1687 // demand the input sign bit.
1688 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1689 if (HighBits.getBoolValue())
1690 InDemandedMask |= APInt::getSignBit(BitWidth);
1692 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1694 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1695 KnownZero = KnownZero.lshr(ShAmt);
1696 KnownOne = KnownOne.lshr(ShAmt);
1698 // Handle the sign bits.
1699 APInt SignBit = APInt::getSignBit(BitWidth);
1700 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1702 if (KnownZero.intersects(SignBit)) {
1703 KnownZero |= HighBits; // New bits are known zero.
1704 } else if (KnownOne.intersects(SignBit)) {
1705 KnownOne |= HighBits; // New bits are known one.
1709 case ISD::SIGN_EXTEND_INREG: {
1710 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1711 unsigned EBits = EVT.getSizeInBits();
1713 // Sign extension. Compute the demanded bits in the result that are not
1714 // present in the input.
1715 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1717 APInt InSignBit = APInt::getSignBit(EBits);
1718 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1720 // If the sign extended bits are demanded, we know that the sign
1722 InSignBit.zext(BitWidth);
1723 if (NewBits.getBoolValue())
1724 InputDemandedBits |= InSignBit;
1726 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1727 KnownZero, KnownOne, Depth+1);
1728 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1730 // If the sign bit of the input is known set or clear, then we know the
1731 // top bits of the result.
1732 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1733 KnownZero |= NewBits;
1734 KnownOne &= ~NewBits;
1735 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1736 KnownOne |= NewBits;
1737 KnownZero &= ~NewBits;
1738 } else { // Input sign bit unknown
1739 KnownZero &= ~NewBits;
1740 KnownOne &= ~NewBits;
1747 unsigned LowBits = Log2_32(BitWidth)+1;
1748 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1753 if (ISD::isZEXTLoad(Op.getNode())) {
1754 LoadSDNode *LD = cast<LoadSDNode>(Op);
1755 EVT VT = LD->getMemoryVT();
1756 unsigned MemBits = VT.getSizeInBits();
1757 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1761 case ISD::ZERO_EXTEND: {
1762 EVT InVT = Op.getOperand(0).getValueType();
1763 unsigned InBits = InVT.getSizeInBits();
1764 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1765 APInt InMask = Mask;
1766 InMask.trunc(InBits);
1767 KnownZero.trunc(InBits);
1768 KnownOne.trunc(InBits);
1769 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1770 KnownZero.zext(BitWidth);
1771 KnownOne.zext(BitWidth);
1772 KnownZero |= NewBits;
1775 case ISD::SIGN_EXTEND: {
1776 EVT InVT = Op.getOperand(0).getValueType();
1777 unsigned InBits = InVT.getSizeInBits();
1778 APInt InSignBit = APInt::getSignBit(InBits);
1779 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1780 APInt InMask = Mask;
1781 InMask.trunc(InBits);
1783 // If any of the sign extended bits are demanded, we know that the sign
1784 // bit is demanded. Temporarily set this bit in the mask for our callee.
1785 if (NewBits.getBoolValue())
1786 InMask |= InSignBit;
1788 KnownZero.trunc(InBits);
1789 KnownOne.trunc(InBits);
1790 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1792 // Note if the sign bit is known to be zero or one.
1793 bool SignBitKnownZero = KnownZero.isNegative();
1794 bool SignBitKnownOne = KnownOne.isNegative();
1795 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1796 "Sign bit can't be known to be both zero and one!");
1798 // If the sign bit wasn't actually demanded by our caller, we don't
1799 // want it set in the KnownZero and KnownOne result values. Reset the
1800 // mask and reapply it to the result values.
1802 InMask.trunc(InBits);
1803 KnownZero &= InMask;
1806 KnownZero.zext(BitWidth);
1807 KnownOne.zext(BitWidth);
1809 // If the sign bit is known zero or one, the top bits match.
1810 if (SignBitKnownZero)
1811 KnownZero |= NewBits;
1812 else if (SignBitKnownOne)
1813 KnownOne |= NewBits;
1816 case ISD::ANY_EXTEND: {
1817 EVT InVT = Op.getOperand(0).getValueType();
1818 unsigned InBits = InVT.getSizeInBits();
1819 APInt InMask = Mask;
1820 InMask.trunc(InBits);
1821 KnownZero.trunc(InBits);
1822 KnownOne.trunc(InBits);
1823 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1824 KnownZero.zext(BitWidth);
1825 KnownOne.zext(BitWidth);
1828 case ISD::TRUNCATE: {
1829 EVT InVT = Op.getOperand(0).getValueType();
1830 unsigned InBits = InVT.getSizeInBits();
1831 APInt InMask = Mask;
1832 InMask.zext(InBits);
1833 KnownZero.zext(InBits);
1834 KnownOne.zext(InBits);
1835 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1836 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1837 KnownZero.trunc(BitWidth);
1838 KnownOne.trunc(BitWidth);
1841 case ISD::AssertZext: {
1842 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1843 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1844 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1846 KnownZero |= (~InMask) & Mask;
1850 // All bits are zero except the low bit.
1851 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1855 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1856 // We know that the top bits of C-X are clear if X contains less bits
1857 // than C (i.e. no wrap-around can happen). For example, 20-X is
1858 // positive if we can prove that X is >= 0 and < 16.
1859 if (CLHS->getAPIntValue().isNonNegative()) {
1860 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1861 // NLZ can't be BitWidth with no sign bit
1862 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1863 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1866 // If all of the MaskV bits are known to be zero, then we know the
1867 // output top bits are zero, because we now know that the output is
1869 if ((KnownZero2 & MaskV) == MaskV) {
1870 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1871 // Top bits known zero.
1872 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1879 // Output known-0 bits are known if clear or set in both the low clear bits
1880 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1881 // low 3 bits clear.
1882 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1883 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1884 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1885 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1887 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1888 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1889 KnownZeroOut = std::min(KnownZeroOut,
1890 KnownZero2.countTrailingOnes());
1892 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1896 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1897 const APInt &RA = Rem->getAPIntValue();
1898 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1899 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1900 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1901 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1903 // If the sign bit of the first operand is zero, the sign bit of
1904 // the result is zero. If the first operand has no one bits below
1905 // the second operand's single 1 bit, its sign will be zero.
1906 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1907 KnownZero2 |= ~LowBits;
1909 KnownZero |= KnownZero2 & Mask;
1911 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1916 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1917 const APInt &RA = Rem->getAPIntValue();
1918 if (RA.isPowerOf2()) {
1919 APInt LowBits = (RA - 1);
1920 APInt Mask2 = LowBits & Mask;
1921 KnownZero |= ~LowBits & Mask;
1922 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1923 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1928 // Since the result is less than or equal to either operand, any leading
1929 // zero bits in either operand must also exist in the result.
1930 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1931 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1933 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1936 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1937 KnownZero2.countLeadingOnes());
1939 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1943 // Allow the target to implement this method for its nodes.
1944 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1945 case ISD::INTRINSIC_WO_CHAIN:
1946 case ISD::INTRINSIC_W_CHAIN:
1947 case ISD::INTRINSIC_VOID:
1948 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
1955 /// ComputeNumSignBits - Return the number of times the sign bit of the
1956 /// register is replicated into the other bits. We know that at least 1 bit
1957 /// is always equal to the sign bit (itself), but other cases can give us
1958 /// information. For example, immediately after an "SRA X, 2", we know that
1959 /// the top 3 bits are all equal to each other, so we return 3.
1960 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1961 EVT VT = Op.getValueType();
1962 assert(VT.isInteger() && "Invalid VT!");
1963 unsigned VTBits = VT.getSizeInBits();
1965 unsigned FirstAnswer = 1;
1968 return 1; // Limit search depth.
1970 switch (Op.getOpcode()) {
1972 case ISD::AssertSext:
1973 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1974 return VTBits-Tmp+1;
1975 case ISD::AssertZext:
1976 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1979 case ISD::Constant: {
1980 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1981 // If negative, return # leading ones.
1982 if (Val.isNegative())
1983 return Val.countLeadingOnes();
1985 // Return # leading zeros.
1986 return Val.countLeadingZeros();
1989 case ISD::SIGN_EXTEND:
1990 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1991 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1993 case ISD::SIGN_EXTEND_INREG:
1994 // Max of the input and what this extends.
1995 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1998 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1999 return std::max(Tmp, Tmp2);
2002 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2003 // SRA X, C -> adds C sign bits.
2004 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2005 Tmp += C->getZExtValue();
2006 if (Tmp > VTBits) Tmp = VTBits;
2010 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2011 // shl destroys sign bits.
2012 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2013 if (C->getZExtValue() >= VTBits || // Bad shift.
2014 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2015 return Tmp - C->getZExtValue();
2020 case ISD::XOR: // NOT is handled here.
2021 // Logical binary ops preserve the number of sign bits at the worst.
2022 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2024 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2025 FirstAnswer = std::min(Tmp, Tmp2);
2026 // We computed what we know about the sign bits as our first
2027 // answer. Now proceed to the generic code that uses
2028 // ComputeMaskedBits, and pick whichever answer is better.
2033 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2034 if (Tmp == 1) return 1; // Early out.
2035 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2036 return std::min(Tmp, Tmp2);
2044 if (Op.getResNo() != 1)
2046 // The boolean result conforms to getBooleanContents. Fall through.
2048 // If setcc returns 0/-1, all bits are sign bits.
2049 if (TLI.getBooleanContents() ==
2050 TargetLowering::ZeroOrNegativeOneBooleanContent)
2055 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2056 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2058 // Handle rotate right by N like a rotate left by 32-N.
2059 if (Op.getOpcode() == ISD::ROTR)
2060 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2062 // If we aren't rotating out all of the known-in sign bits, return the
2063 // number that are left. This handles rotl(sext(x), 1) for example.
2064 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2065 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2069 // Add can have at most one carry bit. Thus we know that the output
2070 // is, at worst, one more bit than the inputs.
2071 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2072 if (Tmp == 1) return 1; // Early out.
2074 // Special case decrementing a value (ADD X, -1):
2075 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2076 if (CRHS->isAllOnesValue()) {
2077 APInt KnownZero, KnownOne;
2078 APInt Mask = APInt::getAllOnesValue(VTBits);
2079 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2081 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2083 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2086 // If we are subtracting one from a positive number, there is no carry
2087 // out of the result.
2088 if (KnownZero.isNegative())
2092 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2093 if (Tmp2 == 1) return 1;
2094 return std::min(Tmp, Tmp2)-1;
2098 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2099 if (Tmp2 == 1) return 1;
2102 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2103 if (CLHS->isNullValue()) {
2104 APInt KnownZero, KnownOne;
2105 APInt Mask = APInt::getAllOnesValue(VTBits);
2106 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2107 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2109 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2112 // If the input is known to be positive (the sign bit is known clear),
2113 // the output of the NEG has the same number of sign bits as the input.
2114 if (KnownZero.isNegative())
2117 // Otherwise, we treat this like a SUB.
2120 // Sub can have at most one carry bit. Thus we know that the output
2121 // is, at worst, one more bit than the inputs.
2122 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2123 if (Tmp == 1) return 1; // Early out.
2124 return std::min(Tmp, Tmp2)-1;
2127 // FIXME: it's tricky to do anything useful for this, but it is an important
2128 // case for targets like X86.
2132 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2133 if (Op.getOpcode() == ISD::LOAD) {
2134 LoadSDNode *LD = cast<LoadSDNode>(Op);
2135 unsigned ExtType = LD->getExtensionType();
2138 case ISD::SEXTLOAD: // '17' bits known
2139 Tmp = LD->getMemoryVT().getSizeInBits();
2140 return VTBits-Tmp+1;
2141 case ISD::ZEXTLOAD: // '16' bits known
2142 Tmp = LD->getMemoryVT().getSizeInBits();
2147 // Allow the target to implement this method for its nodes.
2148 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2149 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2150 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2151 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2152 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2153 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2156 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2157 // use this information.
2158 APInt KnownZero, KnownOne;
2159 APInt Mask = APInt::getAllOnesValue(VTBits);
2160 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2162 if (KnownZero.isNegative()) { // sign bit is 0
2164 } else if (KnownOne.isNegative()) { // sign bit is 1;
2171 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2172 // the number of identical bits in the top of the input value.
2174 Mask <<= Mask.getBitWidth()-VTBits;
2175 // Return # leading zeros. We use 'min' here in case Val was zero before
2176 // shifting. We don't want to return '64' as for an i32 "0".
2177 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2180 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2181 // If we're told that NaNs won't happen, assume they won't.
2182 if (FiniteOnlyFPMath())
2185 // If the value is a constant, we can obviously see if it is a NaN or not.
2186 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2187 return !C->getValueAPF().isNaN();
2189 // TODO: Recognize more cases here.
2194 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2195 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2196 if (!GA) return false;
2197 if (GA->getOffset() != 0) return false;
2198 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2199 if (!GV) return false;
2200 MachineModuleInfo *MMI = getMachineModuleInfo();
2201 return MMI && MMI->hasDebugInfo();
2205 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2206 /// element of the result of the vector shuffle.
2207 SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N,
2209 EVT VT = N->getValueType(0);
2210 DebugLoc dl = N->getDebugLoc();
2211 if (N->getMaskElt(i) < 0)
2212 return getUNDEF(VT.getVectorElementType());
2213 unsigned Index = N->getMaskElt(i);
2214 unsigned NumElems = VT.getVectorNumElements();
2215 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2218 if (V.getOpcode() == ISD::BIT_CONVERT) {
2219 V = V.getOperand(0);
2220 EVT VVT = V.getValueType();
2221 if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems)
2224 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2225 return (Index == 0) ? V.getOperand(0)
2226 : getUNDEF(VT.getVectorElementType());
2227 if (V.getOpcode() == ISD::BUILD_VECTOR)
2228 return V.getOperand(Index);
2229 if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V))
2230 return getShuffleScalarElt(SVN, Index);
2235 /// getNode - Gets or creates the specified node.
2237 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
2238 FoldingSetNodeID ID;
2239 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2241 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2242 return SDValue(E, 0);
2243 SDNode *N = NodeAllocator.Allocate<SDNode>();
2244 new (N) SDNode(Opcode, DL, getVTList(VT));
2245 CSEMap.InsertNode(N, IP);
2247 AllNodes.push_back(N);
2251 return SDValue(N, 0);
2254 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2255 EVT VT, SDValue Operand) {
2256 // Constant fold unary operations with an integer constant operand.
2257 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2258 const APInt &Val = C->getAPIntValue();
2259 unsigned BitWidth = VT.getSizeInBits();
2262 case ISD::SIGN_EXTEND:
2263 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2264 case ISD::ANY_EXTEND:
2265 case ISD::ZERO_EXTEND:
2267 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2268 case ISD::UINT_TO_FP:
2269 case ISD::SINT_TO_FP: {
2270 const uint64_t zero[] = {0, 0};
2271 // No compile time operations on this type.
2272 if (VT==MVT::ppcf128)
2274 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2275 (void)apf.convertFromAPInt(Val,
2276 Opcode==ISD::SINT_TO_FP,
2277 APFloat::rmNearestTiesToEven);
2278 return getConstantFP(apf, VT);
2280 case ISD::BIT_CONVERT:
2281 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2282 return getConstantFP(Val.bitsToFloat(), VT);
2283 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2284 return getConstantFP(Val.bitsToDouble(), VT);
2287 return getConstant(Val.byteSwap(), VT);
2289 return getConstant(Val.countPopulation(), VT);
2291 return getConstant(Val.countLeadingZeros(), VT);
2293 return getConstant(Val.countTrailingZeros(), VT);
2297 // Constant fold unary operations with a floating point constant operand.
2298 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2299 APFloat V = C->getValueAPF(); // make copy
2300 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2304 return getConstantFP(V, VT);
2307 return getConstantFP(V, VT);
2309 case ISD::FP_EXTEND: {
2311 // This can return overflow, underflow, or inexact; we don't care.
2312 // FIXME need to be more flexible about rounding mode.
2313 (void)V.convert(*EVTToAPFloatSemantics(VT),
2314 APFloat::rmNearestTiesToEven, &ignored);
2315 return getConstantFP(V, VT);
2317 case ISD::FP_TO_SINT:
2318 case ISD::FP_TO_UINT: {
2321 assert(integerPartWidth >= 64);
2322 // FIXME need to be more flexible about rounding mode.
2323 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2324 Opcode==ISD::FP_TO_SINT,
2325 APFloat::rmTowardZero, &ignored);
2326 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2328 APInt api(VT.getSizeInBits(), 2, x);
2329 return getConstant(api, VT);
2331 case ISD::BIT_CONVERT:
2332 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2333 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2334 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2335 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2341 unsigned OpOpcode = Operand.getNode()->getOpcode();
2343 case ISD::TokenFactor:
2344 case ISD::MERGE_VALUES:
2345 case ISD::CONCAT_VECTORS:
2346 return Operand; // Factor, merge or concat of one node? No need.
2347 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2348 case ISD::FP_EXTEND:
2349 assert(VT.isFloatingPoint() &&
2350 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2351 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2352 if (Operand.getOpcode() == ISD::UNDEF)
2353 return getUNDEF(VT);
2355 case ISD::SIGN_EXTEND:
2356 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2357 "Invalid SIGN_EXTEND!");
2358 if (Operand.getValueType() == VT) return Operand; // noop extension
2359 assert(Operand.getValueType().bitsLT(VT)
2360 && "Invalid sext node, dst < src!");
2361 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2362 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2364 case ISD::ZERO_EXTEND:
2365 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2366 "Invalid ZERO_EXTEND!");
2367 if (Operand.getValueType() == VT) return Operand; // noop extension
2368 assert(Operand.getValueType().bitsLT(VT)
2369 && "Invalid zext node, dst < src!");
2370 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2371 return getNode(ISD::ZERO_EXTEND, DL, VT,
2372 Operand.getNode()->getOperand(0));
2374 case ISD::ANY_EXTEND:
2375 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2376 "Invalid ANY_EXTEND!");
2377 if (Operand.getValueType() == VT) return Operand; // noop extension
2378 assert(Operand.getValueType().bitsLT(VT)
2379 && "Invalid anyext node, dst < src!");
2380 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2381 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2382 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2385 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2386 "Invalid TRUNCATE!");
2387 if (Operand.getValueType() == VT) return Operand; // noop truncate
2388 assert(Operand.getValueType().bitsGT(VT)
2389 && "Invalid truncate node, src < dst!");
2390 if (OpOpcode == ISD::TRUNCATE)
2391 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2392 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2393 OpOpcode == ISD::ANY_EXTEND) {
2394 // If the source is smaller than the dest, we still need an extend.
2395 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2396 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2397 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2398 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2400 return Operand.getNode()->getOperand(0);
2403 case ISD::BIT_CONVERT:
2404 // Basic sanity checking.
2405 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2406 && "Cannot BIT_CONVERT between types of different sizes!");
2407 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2408 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2409 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2410 if (OpOpcode == ISD::UNDEF)
2411 return getUNDEF(VT);
2413 case ISD::SCALAR_TO_VECTOR:
2414 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2415 (VT.getVectorElementType() == Operand.getValueType() ||
2416 (VT.getVectorElementType().isInteger() &&
2417 Operand.getValueType().isInteger() &&
2418 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2419 "Illegal SCALAR_TO_VECTOR node!");
2420 if (OpOpcode == ISD::UNDEF)
2421 return getUNDEF(VT);
2422 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2423 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2424 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2425 Operand.getConstantOperandVal(1) == 0 &&
2426 Operand.getOperand(0).getValueType() == VT)
2427 return Operand.getOperand(0);
2430 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2431 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2432 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2433 Operand.getNode()->getOperand(0));
2434 if (OpOpcode == ISD::FNEG) // --X -> X
2435 return Operand.getNode()->getOperand(0);
2438 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2439 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2444 SDVTList VTs = getVTList(VT);
2445 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2446 FoldingSetNodeID ID;
2447 SDValue Ops[1] = { Operand };
2448 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2450 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2451 return SDValue(E, 0);
2452 N = NodeAllocator.Allocate<UnarySDNode>();
2453 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2454 CSEMap.InsertNode(N, IP);
2456 N = NodeAllocator.Allocate<UnarySDNode>();
2457 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2460 AllNodes.push_back(N);
2464 return SDValue(N, 0);
2467 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2469 ConstantSDNode *Cst1,
2470 ConstantSDNode *Cst2) {
2471 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2474 case ISD::ADD: return getConstant(C1 + C2, VT);
2475 case ISD::SUB: return getConstant(C1 - C2, VT);
2476 case ISD::MUL: return getConstant(C1 * C2, VT);
2478 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2481 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2484 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2487 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2489 case ISD::AND: return getConstant(C1 & C2, VT);
2490 case ISD::OR: return getConstant(C1 | C2, VT);
2491 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2492 case ISD::SHL: return getConstant(C1 << C2, VT);
2493 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2494 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2495 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2496 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2503 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2504 SDValue N1, SDValue N2) {
2505 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2506 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2509 case ISD::TokenFactor:
2510 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2511 N2.getValueType() == MVT::Other && "Invalid token factor!");
2512 // Fold trivial token factors.
2513 if (N1.getOpcode() == ISD::EntryToken) return N2;
2514 if (N2.getOpcode() == ISD::EntryToken) return N1;
2515 if (N1 == N2) return N1;
2517 case ISD::CONCAT_VECTORS:
2518 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2519 // one big BUILD_VECTOR.
2520 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2521 N2.getOpcode() == ISD::BUILD_VECTOR) {
2522 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2523 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2524 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2528 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2529 N1.getValueType() == VT && "Binary operator types must match!");
2530 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2531 // worth handling here.
2532 if (N2C && N2C->isNullValue())
2534 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2541 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2542 N1.getValueType() == VT && "Binary operator types must match!");
2543 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2544 // it's worth handling here.
2545 if (N2C && N2C->isNullValue())
2555 assert(VT.isInteger() && "This operator does not apply to FP types!");
2563 if (Opcode == ISD::FADD) {
2565 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2566 if (CFP->getValueAPF().isZero())
2569 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2570 if (CFP->getValueAPF().isZero())
2572 } else if (Opcode == ISD::FSUB) {
2574 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2575 if (CFP->getValueAPF().isZero())
2579 assert(N1.getValueType() == N2.getValueType() &&
2580 N1.getValueType() == VT && "Binary operator types must match!");
2582 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2583 assert(N1.getValueType() == VT &&
2584 N1.getValueType().isFloatingPoint() &&
2585 N2.getValueType().isFloatingPoint() &&
2586 "Invalid FCOPYSIGN!");
2593 assert(VT == N1.getValueType() &&
2594 "Shift operators return type must be the same as their first arg");
2595 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2596 "Shifts only work on integers");
2598 // Always fold shifts of i1 values so the code generator doesn't need to
2599 // handle them. Since we know the size of the shift has to be less than the
2600 // size of the value, the shift/rotate count is guaranteed to be zero.
2604 case ISD::FP_ROUND_INREG: {
2605 EVT EVT = cast<VTSDNode>(N2)->getVT();
2606 assert(VT == N1.getValueType() && "Not an inreg round!");
2607 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2608 "Cannot FP_ROUND_INREG integer types");
2609 assert(EVT.bitsLE(VT) && "Not rounding down!");
2610 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2614 assert(VT.isFloatingPoint() &&
2615 N1.getValueType().isFloatingPoint() &&
2616 VT.bitsLE(N1.getValueType()) &&
2617 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2618 if (N1.getValueType() == VT) return N1; // noop conversion.
2620 case ISD::AssertSext:
2621 case ISD::AssertZext: {
2622 EVT EVT = cast<VTSDNode>(N2)->getVT();
2623 assert(VT == N1.getValueType() && "Not an inreg extend!");
2624 assert(VT.isInteger() && EVT.isInteger() &&
2625 "Cannot *_EXTEND_INREG FP types");
2626 assert(EVT.bitsLE(VT) && "Not extending!");
2627 if (VT == EVT) return N1; // noop assertion.
2630 case ISD::SIGN_EXTEND_INREG: {
2631 EVT EVT = cast<VTSDNode>(N2)->getVT();
2632 assert(VT == N1.getValueType() && "Not an inreg extend!");
2633 assert(VT.isInteger() && EVT.isInteger() &&
2634 "Cannot *_EXTEND_INREG FP types");
2635 assert(EVT.bitsLE(VT) && "Not extending!");
2636 if (EVT == VT) return N1; // Not actually extending
2639 APInt Val = N1C->getAPIntValue();
2640 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2641 Val <<= Val.getBitWidth()-FromBits;
2642 Val = Val.ashr(Val.getBitWidth()-FromBits);
2643 return getConstant(Val, VT);
2647 case ISD::EXTRACT_VECTOR_ELT:
2648 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2649 if (N1.getOpcode() == ISD::UNDEF)
2650 return getUNDEF(VT);
2652 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2653 // expanding copies of large vectors from registers.
2655 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2656 N1.getNumOperands() > 0) {
2658 N1.getOperand(0).getValueType().getVectorNumElements();
2659 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2660 N1.getOperand(N2C->getZExtValue() / Factor),
2661 getConstant(N2C->getZExtValue() % Factor,
2662 N2.getValueType()));
2665 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2666 // expanding large vector constants.
2667 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2668 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2669 EVT VEltTy = N1.getValueType().getVectorElementType();
2670 if (Elt.getValueType() != VEltTy) {
2671 // If the vector element type is not legal, the BUILD_VECTOR operands
2672 // are promoted and implicitly truncated. Make that explicit here.
2673 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2676 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2677 // result is implicitly extended.
2678 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2683 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2684 // operations are lowered to scalars.
2685 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2686 // If the indices are the same, return the inserted element.
2687 if (N1.getOperand(2) == N2)
2688 return N1.getOperand(1);
2689 // If the indices are known different, extract the element from
2690 // the original vector.
2691 else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2692 isa<ConstantSDNode>(N2))
2693 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2696 case ISD::EXTRACT_ELEMENT:
2697 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2698 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2699 (N1.getValueType().isInteger() == VT.isInteger()) &&
2700 "Wrong types for EXTRACT_ELEMENT!");
2702 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2703 // 64-bit integers into 32-bit parts. Instead of building the extract of
2704 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2705 if (N1.getOpcode() == ISD::BUILD_PAIR)
2706 return N1.getOperand(N2C->getZExtValue());
2708 // EXTRACT_ELEMENT of a constant int is also very common.
2709 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2710 unsigned ElementSize = VT.getSizeInBits();
2711 unsigned Shift = ElementSize * N2C->getZExtValue();
2712 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2713 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2716 case ISD::EXTRACT_SUBVECTOR:
2717 if (N1.getValueType() == VT) // Trivial extraction.
2724 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2725 if (SV.getNode()) return SV;
2726 } else { // Cannonicalize constant to RHS if commutative
2727 if (isCommutativeBinOp(Opcode)) {
2728 std::swap(N1C, N2C);
2734 // Constant fold FP operations.
2735 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2736 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2738 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2739 // Cannonicalize constant to RHS if commutative
2740 std::swap(N1CFP, N2CFP);
2742 } else if (N2CFP && VT != MVT::ppcf128) {
2743 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2744 APFloat::opStatus s;
2747 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2748 if (s != APFloat::opInvalidOp)
2749 return getConstantFP(V1, VT);
2752 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2753 if (s!=APFloat::opInvalidOp)
2754 return getConstantFP(V1, VT);
2757 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2758 if (s!=APFloat::opInvalidOp)
2759 return getConstantFP(V1, VT);
2762 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2763 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2764 return getConstantFP(V1, VT);
2767 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2768 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2769 return getConstantFP(V1, VT);
2771 case ISD::FCOPYSIGN:
2773 return getConstantFP(V1, VT);
2779 // Canonicalize an UNDEF to the RHS, even over a constant.
2780 if (N1.getOpcode() == ISD::UNDEF) {
2781 if (isCommutativeBinOp(Opcode)) {
2785 case ISD::FP_ROUND_INREG:
2786 case ISD::SIGN_EXTEND_INREG:
2792 return N1; // fold op(undef, arg2) -> undef
2800 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2801 // For vectors, we can't easily build an all zero vector, just return
2808 // Fold a bunch of operators when the RHS is undef.
2809 if (N2.getOpcode() == ISD::UNDEF) {
2812 if (N1.getOpcode() == ISD::UNDEF)
2813 // Handle undef ^ undef -> 0 special case. This is a common
2815 return getConstant(0, VT);
2825 return N2; // fold op(arg1, undef) -> undef
2839 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2840 // For vectors, we can't easily build an all zero vector, just return
2845 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2846 // For vectors, we can't easily build an all one vector, just return
2854 // Memoize this node if possible.
2856 SDVTList VTs = getVTList(VT);
2857 if (VT != MVT::Flag) {
2858 SDValue Ops[] = { N1, N2 };
2859 FoldingSetNodeID ID;
2860 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2862 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2863 return SDValue(E, 0);
2864 N = NodeAllocator.Allocate<BinarySDNode>();
2865 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2866 CSEMap.InsertNode(N, IP);
2868 N = NodeAllocator.Allocate<BinarySDNode>();
2869 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2872 AllNodes.push_back(N);
2876 return SDValue(N, 0);
2879 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2880 SDValue N1, SDValue N2, SDValue N3) {
2881 // Perform various simplifications.
2882 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2883 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2885 case ISD::CONCAT_VECTORS:
2886 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2887 // one big BUILD_VECTOR.
2888 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2889 N2.getOpcode() == ISD::BUILD_VECTOR &&
2890 N3.getOpcode() == ISD::BUILD_VECTOR) {
2891 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2892 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2893 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2894 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2898 // Use FoldSetCC to simplify SETCC's.
2899 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
2900 if (Simp.getNode()) return Simp;
2905 if (N1C->getZExtValue())
2906 return N2; // select true, X, Y -> X
2908 return N3; // select false, X, Y -> Y
2911 if (N2 == N3) return N2; // select C, X, X -> X
2915 if (N2C->getZExtValue()) // Unconditional branch
2916 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
2918 return N1; // Never-taken branch
2921 case ISD::VECTOR_SHUFFLE:
2922 llvm_unreachable("should use getVectorShuffle constructor!");
2924 case ISD::BIT_CONVERT:
2925 // Fold bit_convert nodes from a type to themselves.
2926 if (N1.getValueType() == VT)
2931 // Memoize node if it doesn't produce a flag.
2933 SDVTList VTs = getVTList(VT);
2934 if (VT != MVT::Flag) {
2935 SDValue Ops[] = { N1, N2, N3 };
2936 FoldingSetNodeID ID;
2937 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2939 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2940 return SDValue(E, 0);
2941 N = NodeAllocator.Allocate<TernarySDNode>();
2942 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2943 CSEMap.InsertNode(N, IP);
2945 N = NodeAllocator.Allocate<TernarySDNode>();
2946 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2948 AllNodes.push_back(N);
2952 return SDValue(N, 0);
2955 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2956 SDValue N1, SDValue N2, SDValue N3,
2958 SDValue Ops[] = { N1, N2, N3, N4 };
2959 return getNode(Opcode, DL, VT, Ops, 4);
2962 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2963 SDValue N1, SDValue N2, SDValue N3,
2964 SDValue N4, SDValue N5) {
2965 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2966 return getNode(Opcode, DL, VT, Ops, 5);
2969 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
2970 /// the incoming stack arguments to be loaded from the stack.
2971 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
2972 SmallVector<SDValue, 8> ArgChains;
2974 // Include the original chain at the beginning of the list. When this is
2975 // used by target LowerCall hooks, this helps legalize find the
2976 // CALLSEQ_BEGIN node.
2977 ArgChains.push_back(Chain);
2979 // Add a chain value for each stack argument.
2980 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
2981 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
2982 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2983 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2984 if (FI->getIndex() < 0)
2985 ArgChains.push_back(SDValue(L, 1));
2987 // Build a tokenfactor for all the chains.
2988 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
2989 &ArgChains[0], ArgChains.size());
2992 /// getMemsetValue - Vectorized representation of the memset value
2994 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
2996 unsigned NumBits = VT.isVector() ?
2997 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2998 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2999 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
3001 for (unsigned i = NumBits; i > 8; i >>= 1) {
3002 Val = (Val << Shift) | Val;
3006 return DAG.getConstant(Val, VT);
3007 return DAG.getConstantFP(APFloat(Val), VT);
3010 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3011 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3013 for (unsigned i = NumBits; i > 8; i >>= 1) {
3014 Value = DAG.getNode(ISD::OR, dl, VT,
3015 DAG.getNode(ISD::SHL, dl, VT, Value,
3016 DAG.getConstant(Shift,
3017 TLI.getShiftAmountTy())),
3025 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3026 /// used when a memcpy is turned into a memset when the source is a constant
3028 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3029 const TargetLowering &TLI,
3030 std::string &Str, unsigned Offset) {
3031 // Handle vector with all elements zero.
3034 return DAG.getConstant(0, VT);
3035 unsigned NumElts = VT.getVectorNumElements();
3036 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3037 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3039 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts)));
3042 assert(!VT.isVector() && "Can't handle vector type here!");
3043 unsigned NumBits = VT.getSizeInBits();
3044 unsigned MSB = NumBits / 8;
3046 if (TLI.isLittleEndian())
3047 Offset = Offset + MSB - 1;
3048 for (unsigned i = 0; i != MSB; ++i) {
3049 Val = (Val << 8) | (unsigned char)Str[Offset];
3050 Offset += TLI.isLittleEndian() ? -1 : 1;
3052 return DAG.getConstant(Val, VT);
3055 /// getMemBasePlusOffset - Returns base and offset node for the
3057 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3058 SelectionDAG &DAG) {
3059 EVT VT = Base.getValueType();
3060 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3061 VT, Base, DAG.getConstant(Offset, VT));
3064 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3066 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3067 unsigned SrcDelta = 0;
3068 GlobalAddressSDNode *G = NULL;
3069 if (Src.getOpcode() == ISD::GlobalAddress)
3070 G = cast<GlobalAddressSDNode>(Src);
3071 else if (Src.getOpcode() == ISD::ADD &&
3072 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3073 Src.getOperand(1).getOpcode() == ISD::Constant) {
3074 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3075 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3080 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3081 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3087 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3088 /// to replace the memset / memcpy is below the threshold. It also returns the
3089 /// types of the sequence of memory ops to perform memset / memcpy.
3091 bool MeetsMaxMemopRequirement(std::vector<EVT> &MemOps,
3092 SDValue Dst, SDValue Src,
3093 unsigned Limit, uint64_t Size, unsigned &Align,
3094 std::string &Str, bool &isSrcStr,
3096 const TargetLowering &TLI) {
3097 isSrcStr = isMemSrcFromString(Src, Str);
3098 bool isSrcConst = isa<ConstantSDNode>(Src);
3099 EVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
3100 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses(VT);
3101 if (VT != MVT::iAny) {
3102 const Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3103 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3104 // If source is a string constant, this will require an unaligned load.
3105 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3106 if (Dst.getOpcode() != ISD::FrameIndex) {
3107 // Can't change destination alignment. It requires a unaligned store.
3111 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3112 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3113 if (MFI->isFixedObjectIndex(FI)) {
3114 // Can't change destination alignment. It requires a unaligned store.
3118 // Give the stack frame object a larger alignment if needed.
3119 if (MFI->getObjectAlignment(FI) < NewAlign)
3120 MFI->setObjectAlignment(FI, NewAlign);
3127 if (VT == MVT::iAny) {
3128 if (TLI.allowsUnalignedMemoryAccesses(MVT::i64)) {
3131 switch (Align & 7) {
3132 case 0: VT = MVT::i64; break;
3133 case 4: VT = MVT::i32; break;
3134 case 2: VT = MVT::i16; break;
3135 default: VT = MVT::i8; break;
3140 while (!TLI.isTypeLegal(LVT))
3141 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3142 assert(LVT.isInteger());
3148 unsigned NumMemOps = 0;
3150 unsigned VTSize = VT.getSizeInBits() / 8;
3151 while (VTSize > Size) {
3152 // For now, only use non-vector load / store's for the left-over pieces.
3153 if (VT.isVector()) {
3155 while (!TLI.isTypeLegal(VT))
3156 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3157 VTSize = VT.getSizeInBits() / 8;
3159 // This can result in a type that is not legal on the target, e.g.
3160 // 1 or 2 bytes on PPC.
3161 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3166 if (++NumMemOps > Limit)
3168 MemOps.push_back(VT);
3175 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3176 SDValue Chain, SDValue Dst,
3177 SDValue Src, uint64_t Size,
3178 unsigned Align, bool AlwaysInline,
3179 const Value *DstSV, uint64_t DstSVOff,
3180 const Value *SrcSV, uint64_t SrcSVOff){
3181 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3183 // Expand memcpy to a series of load and store ops if the size operand falls
3184 // below a certain threshold.
3185 std::vector<EVT> MemOps;
3186 uint64_t Limit = -1ULL;
3188 Limit = TLI.getMaxStoresPerMemcpy();
3189 unsigned DstAlign = Align; // Destination alignment can change.
3192 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3193 Str, CopyFromStr, DAG, TLI))
3197 bool isZeroStr = CopyFromStr && Str.empty();
3198 SmallVector<SDValue, 8> OutChains;
3199 unsigned NumMemOps = MemOps.size();
3200 uint64_t SrcOff = 0, DstOff = 0;
3201 for (unsigned i = 0; i != NumMemOps; ++i) {
3203 unsigned VTSize = VT.getSizeInBits() / 8;
3204 SDValue Value, Store;
3206 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3207 // It's unlikely a store of a vector immediate can be done in a single
3208 // instruction. It would require a load from a constantpool first.
3209 // We also handle store a vector with all zero's.
3210 // FIXME: Handle other cases where store of vector immediate is done in
3211 // a single instruction.
3212 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3213 Store = DAG.getStore(Chain, dl, Value,
3214 getMemBasePlusOffset(Dst, DstOff, DAG),
3215 DstSV, DstSVOff + DstOff, false, DstAlign);
3217 // The type might not be legal for the target. This should only happen
3218 // if the type is smaller than a legal type, as on PPC, so the right
3219 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3220 // to Load/Store if NVT==VT.
3221 // FIXME does the case above also need this?
3222 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3223 assert(NVT.bitsGE(VT));
3224 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3225 getMemBasePlusOffset(Src, SrcOff, DAG),
3226 SrcSV, SrcSVOff + SrcOff, VT, false, Align);
3227 Store = DAG.getTruncStore(Chain, dl, Value,
3228 getMemBasePlusOffset(Dst, DstOff, DAG),
3229 DstSV, DstSVOff + DstOff, VT, false, DstAlign);
3231 OutChains.push_back(Store);
3236 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3237 &OutChains[0], OutChains.size());
3240 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3241 SDValue Chain, SDValue Dst,
3242 SDValue Src, uint64_t Size,
3243 unsigned Align, bool AlwaysInline,
3244 const Value *DstSV, uint64_t DstSVOff,
3245 const Value *SrcSV, uint64_t SrcSVOff){
3246 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3248 // Expand memmove to a series of load and store ops if the size operand falls
3249 // below a certain threshold.
3250 std::vector<EVT> MemOps;
3251 uint64_t Limit = -1ULL;
3253 Limit = TLI.getMaxStoresPerMemmove();
3254 unsigned DstAlign = Align; // Destination alignment can change.
3257 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3258 Str, CopyFromStr, DAG, TLI))
3261 uint64_t SrcOff = 0, DstOff = 0;
3263 SmallVector<SDValue, 8> LoadValues;
3264 SmallVector<SDValue, 8> LoadChains;
3265 SmallVector<SDValue, 8> OutChains;
3266 unsigned NumMemOps = MemOps.size();
3267 for (unsigned i = 0; i < NumMemOps; i++) {
3269 unsigned VTSize = VT.getSizeInBits() / 8;
3270 SDValue Value, Store;
3272 Value = DAG.getLoad(VT, dl, Chain,
3273 getMemBasePlusOffset(Src, SrcOff, DAG),
3274 SrcSV, SrcSVOff + SrcOff, false, Align);
3275 LoadValues.push_back(Value);
3276 LoadChains.push_back(Value.getValue(1));
3279 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3280 &LoadChains[0], LoadChains.size());
3282 for (unsigned i = 0; i < NumMemOps; i++) {
3284 unsigned VTSize = VT.getSizeInBits() / 8;
3285 SDValue Value, Store;
3287 Store = DAG.getStore(Chain, dl, LoadValues[i],
3288 getMemBasePlusOffset(Dst, DstOff, DAG),
3289 DstSV, DstSVOff + DstOff, false, DstAlign);
3290 OutChains.push_back(Store);
3294 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3295 &OutChains[0], OutChains.size());
3298 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3299 SDValue Chain, SDValue Dst,
3300 SDValue Src, uint64_t Size,
3302 const Value *DstSV, uint64_t DstSVOff) {
3303 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3305 // Expand memset to a series of load/store ops if the size operand
3306 // falls below a certain threshold.
3307 std::vector<EVT> MemOps;
3310 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3311 Size, Align, Str, CopyFromStr, DAG, TLI))
3314 SmallVector<SDValue, 8> OutChains;
3315 uint64_t DstOff = 0;
3317 unsigned NumMemOps = MemOps.size();
3318 for (unsigned i = 0; i < NumMemOps; i++) {
3320 unsigned VTSize = VT.getSizeInBits() / 8;
3321 SDValue Value = getMemsetValue(Src, VT, DAG, dl);
3322 SDValue Store = DAG.getStore(Chain, dl, Value,
3323 getMemBasePlusOffset(Dst, DstOff, DAG),
3324 DstSV, DstSVOff + DstOff);
3325 OutChains.push_back(Store);
3329 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3330 &OutChains[0], OutChains.size());
3333 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3334 SDValue Src, SDValue Size,
3335 unsigned Align, bool AlwaysInline,
3336 const Value *DstSV, uint64_t DstSVOff,
3337 const Value *SrcSV, uint64_t SrcSVOff) {
3339 // Check to see if we should lower the memcpy to loads and stores first.
3340 // For cases within the target-specified limits, this is the best choice.
3341 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3343 // Memcpy with size zero? Just return the original chain.
3344 if (ConstantSize->isNullValue())
3348 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3349 ConstantSize->getZExtValue(),
3350 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3351 if (Result.getNode())
3355 // Then check to see if we should lower the memcpy with target-specific
3356 // code. If the target chooses to do this, this is the next best.
3358 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3360 DstSV, DstSVOff, SrcSV, SrcSVOff);
3361 if (Result.getNode())
3364 // If we really need inline code and the target declined to provide it,
3365 // use a (potentially long) sequence of loads and stores.
3367 assert(ConstantSize && "AlwaysInline requires a constant size!");
3368 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3369 ConstantSize->getZExtValue(), Align, true,
3370 DstSV, DstSVOff, SrcSV, SrcSVOff);
3373 // Emit a library call.
3374 TargetLowering::ArgListTy Args;
3375 TargetLowering::ArgListEntry Entry;
3376 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3377 Entry.Node = Dst; Args.push_back(Entry);
3378 Entry.Node = Src; Args.push_back(Entry);
3379 Entry.Node = Size; Args.push_back(Entry);
3380 // FIXME: pass in DebugLoc
3381 std::pair<SDValue,SDValue> CallResult =
3382 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3383 false, false, false, false, 0,
3384 TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3385 /*isReturnValueUsed=*/false,
3386 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3387 TLI.getPointerTy()),
3389 return CallResult.second;
3392 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3393 SDValue Src, SDValue Size,
3395 const Value *DstSV, uint64_t DstSVOff,
3396 const Value *SrcSV, uint64_t SrcSVOff) {
3398 // Check to see if we should lower the memmove to loads and stores first.
3399 // For cases within the target-specified limits, this is the best choice.
3400 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3402 // Memmove with size zero? Just return the original chain.
3403 if (ConstantSize->isNullValue())
3407 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3408 ConstantSize->getZExtValue(),
3409 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3410 if (Result.getNode())
3414 // Then check to see if we should lower the memmove with target-specific
3415 // code. If the target chooses to do this, this is the next best.
3417 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
3418 DstSV, DstSVOff, SrcSV, SrcSVOff);
3419 if (Result.getNode())
3422 // Emit a library call.
3423 TargetLowering::ArgListTy Args;
3424 TargetLowering::ArgListEntry Entry;
3425 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3426 Entry.Node = Dst; Args.push_back(Entry);
3427 Entry.Node = Src; Args.push_back(Entry);
3428 Entry.Node = Size; Args.push_back(Entry);
3429 // FIXME: pass in DebugLoc
3430 std::pair<SDValue,SDValue> CallResult =
3431 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3432 false, false, false, false, 0,
3433 TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3434 /*isReturnValueUsed=*/false,
3435 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3436 TLI.getPointerTy()),
3438 return CallResult.second;
3441 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3442 SDValue Src, SDValue Size,
3444 const Value *DstSV, uint64_t DstSVOff) {
3446 // Check to see if we should lower the memset to stores first.
3447 // For cases within the target-specified limits, this is the best choice.
3448 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3450 // Memset with size zero? Just return the original chain.
3451 if (ConstantSize->isNullValue())
3455 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3456 Align, DstSV, DstSVOff);
3457 if (Result.getNode())
3461 // Then check to see if we should lower the memset with target-specific
3462 // code. If the target chooses to do this, this is the next best.
3464 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
3466 if (Result.getNode())
3469 // Emit a library call.
3470 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3471 TargetLowering::ArgListTy Args;
3472 TargetLowering::ArgListEntry Entry;
3473 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3474 Args.push_back(Entry);
3475 // Extend or truncate the argument to be an i32 value for the call.
3476 if (Src.getValueType().bitsGT(MVT::i32))
3477 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3479 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3481 Entry.Ty = Type::getInt32Ty(*getContext());
3482 Entry.isSExt = true;
3483 Args.push_back(Entry);
3485 Entry.Ty = IntPtrTy;
3486 Entry.isSExt = false;
3487 Args.push_back(Entry);
3488 // FIXME: pass in DebugLoc
3489 std::pair<SDValue,SDValue> CallResult =
3490 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3491 false, false, false, false, 0,
3492 TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3493 /*isReturnValueUsed=*/false,
3494 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3495 TLI.getPointerTy()),
3497 return CallResult.second;
3500 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3502 SDValue Ptr, SDValue Cmp,
3503 SDValue Swp, const Value* PtrVal,
3504 unsigned Alignment) {
3505 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3506 Alignment = getEVTAlignment(MemVT);
3508 // Check if the memory reference references a frame index
3510 if (const FrameIndexSDNode *FI =
3511 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3512 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3514 MachineFunction &MF = getMachineFunction();
3515 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3517 // For now, atomics are considered to be volatile always.
3518 Flags |= MachineMemOperand::MOVolatile;
3520 MachineMemOperand *MMO =
3521 MF.getMachineMemOperand(PtrVal, Flags, 0,
3522 MemVT.getStoreSize(), Alignment);
3524 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3527 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3529 SDValue Ptr, SDValue Cmp,
3530 SDValue Swp, MachineMemOperand *MMO) {
3531 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3532 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3534 EVT VT = Cmp.getValueType();
3536 SDVTList VTs = getVTList(VT, MVT::Other);
3537 FoldingSetNodeID ID;
3538 ID.AddInteger(MemVT.getRawBits());
3539 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3540 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3542 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3543 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3544 return SDValue(E, 0);
3546 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3547 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3548 CSEMap.InsertNode(N, IP);
3549 AllNodes.push_back(N);
3550 return SDValue(N, 0);
3553 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3555 SDValue Ptr, SDValue Val,
3556 const Value* PtrVal,
3557 unsigned Alignment) {
3558 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3559 Alignment = getEVTAlignment(MemVT);
3561 // Check if the memory reference references a frame index
3563 if (const FrameIndexSDNode *FI =
3564 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3565 PtrVal = PseudoSourceValue::getFixedStack(FI->getIndex());
3567 MachineFunction &MF = getMachineFunction();
3568 unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3570 // For now, atomics are considered to be volatile always.
3571 Flags |= MachineMemOperand::MOVolatile;
3573 MachineMemOperand *MMO =
3574 MF.getMachineMemOperand(PtrVal, Flags, 0,
3575 MemVT.getStoreSize(), Alignment);
3577 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
3580 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3582 SDValue Ptr, SDValue Val,
3583 MachineMemOperand *MMO) {
3584 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3585 Opcode == ISD::ATOMIC_LOAD_SUB ||
3586 Opcode == ISD::ATOMIC_LOAD_AND ||
3587 Opcode == ISD::ATOMIC_LOAD_OR ||
3588 Opcode == ISD::ATOMIC_LOAD_XOR ||
3589 Opcode == ISD::ATOMIC_LOAD_NAND ||
3590 Opcode == ISD::ATOMIC_LOAD_MIN ||
3591 Opcode == ISD::ATOMIC_LOAD_MAX ||
3592 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3593 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3594 Opcode == ISD::ATOMIC_SWAP) &&
3595 "Invalid Atomic Op");
3597 EVT VT = Val.getValueType();
3599 SDVTList VTs = getVTList(VT, MVT::Other);
3600 FoldingSetNodeID ID;
3601 ID.AddInteger(MemVT.getRawBits());
3602 SDValue Ops[] = {Chain, Ptr, Val};
3603 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3605 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3606 cast<AtomicSDNode>(E)->refineAlignment(MMO);
3607 return SDValue(E, 0);
3609 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3610 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain, Ptr, Val, MMO);
3611 CSEMap.InsertNode(N, IP);
3612 AllNodes.push_back(N);
3613 return SDValue(N, 0);
3616 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3617 /// Allowed to return something different (and simpler) if Simplify is true.
3618 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3623 SmallVector<EVT, 4> VTs;
3624 VTs.reserve(NumOps);
3625 for (unsigned i = 0; i < NumOps; ++i)
3626 VTs.push_back(Ops[i].getValueType());
3627 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3632 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3633 const EVT *VTs, unsigned NumVTs,
3634 const SDValue *Ops, unsigned NumOps,
3635 EVT MemVT, const Value *srcValue, int SVOff,
3636 unsigned Align, bool Vol,
3637 bool ReadMem, bool WriteMem) {
3638 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3639 MemVT, srcValue, SVOff, Align, Vol,
3644 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3645 const SDValue *Ops, unsigned NumOps,
3646 EVT MemVT, const Value *srcValue, int SVOff,
3647 unsigned Align, bool Vol,
3648 bool ReadMem, bool WriteMem) {
3649 if (Align == 0) // Ensure that codegen never sees alignment 0
3650 Align = getEVTAlignment(MemVT);
3652 MachineFunction &MF = getMachineFunction();
3655 Flags |= MachineMemOperand::MOStore;
3657 Flags |= MachineMemOperand::MOLoad;
3659 Flags |= MachineMemOperand::MOVolatile;
3660 MachineMemOperand *MMO =
3661 MF.getMachineMemOperand(srcValue, Flags, SVOff,
3662 MemVT.getStoreSize(), Align);
3664 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3668 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3669 const SDValue *Ops, unsigned NumOps,
3670 EVT MemVT, MachineMemOperand *MMO) {
3671 assert((Opcode == ISD::INTRINSIC_VOID ||
3672 Opcode == ISD::INTRINSIC_W_CHAIN ||
3673 (Opcode <= INT_MAX &&
3674 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
3675 "Opcode is not a memory-accessing opcode!");
3677 // Memoize the node unless it returns a flag.
3678 MemIntrinsicSDNode *N;
3679 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3680 FoldingSetNodeID ID;
3681 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3683 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3684 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
3685 return SDValue(E, 0);
3688 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3689 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3690 CSEMap.InsertNode(N, IP);
3692 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3693 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3695 AllNodes.push_back(N);
3696 return SDValue(N, 0);
3700 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3701 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3702 SDValue Ptr, SDValue Offset,
3703 const Value *SV, int SVOffset, EVT MemVT,
3704 bool isVolatile, unsigned Alignment) {
3705 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3706 Alignment = getEVTAlignment(VT);
3708 // Check if the memory reference references a frame index
3710 if (const FrameIndexSDNode *FI =
3711 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3712 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3714 MachineFunction &MF = getMachineFunction();
3715 unsigned Flags = MachineMemOperand::MOLoad;
3717 Flags |= MachineMemOperand::MOVolatile;
3718 MachineMemOperand *MMO =
3719 MF.getMachineMemOperand(SV, Flags, SVOffset,
3720 MemVT.getStoreSize(), Alignment);
3721 return getLoad(AM, dl, ExtType, VT, Chain, Ptr, Offset, MemVT, MMO);
3725 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3726 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3727 SDValue Ptr, SDValue Offset, EVT MemVT,
3728 MachineMemOperand *MMO) {
3730 ExtType = ISD::NON_EXTLOAD;
3731 } else if (ExtType == ISD::NON_EXTLOAD) {
3732 assert(VT == MemVT && "Non-extending load from different memory type!");
3736 assert(MemVT.getVectorNumElements() == VT.getVectorNumElements() &&
3737 "Invalid vector extload!");
3739 assert(MemVT.bitsLT(VT) &&
3740 "Should only be an extending load, not truncating!");
3741 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3742 "Cannot sign/zero extend a FP/Vector load!");
3743 assert(VT.isInteger() == MemVT.isInteger() &&
3744 "Cannot convert from FP to Int or Int -> FP!");
3747 bool Indexed = AM != ISD::UNINDEXED;
3748 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3749 "Unindexed load with an offset!");
3751 SDVTList VTs = Indexed ?
3752 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3753 SDValue Ops[] = { Chain, Ptr, Offset };
3754 FoldingSetNodeID ID;
3755 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3756 ID.AddInteger(MemVT.getRawBits());
3757 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile()));
3759 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3760 cast<LoadSDNode>(E)->refineAlignment(MMO);
3761 return SDValue(E, 0);
3763 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3764 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, MemVT, MMO);
3765 CSEMap.InsertNode(N, IP);
3766 AllNodes.push_back(N);
3767 return SDValue(N, 0);
3770 SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
3771 SDValue Chain, SDValue Ptr,
3772 const Value *SV, int SVOffset,
3773 bool isVolatile, unsigned Alignment) {
3774 SDValue Undef = getUNDEF(Ptr.getValueType());
3775 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3776 SV, SVOffset, VT, isVolatile, Alignment);
3779 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
3780 SDValue Chain, SDValue Ptr,
3782 int SVOffset, EVT MemVT,
3783 bool isVolatile, unsigned Alignment) {
3784 SDValue Undef = getUNDEF(Ptr.getValueType());
3785 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3786 SV, SVOffset, MemVT, isVolatile, Alignment);
3790 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3791 SDValue Offset, ISD::MemIndexedMode AM) {
3792 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3793 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3794 "Load is already a indexed load!");
3795 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3796 LD->getChain(), Base, Offset, LD->getSrcValue(),
3797 LD->getSrcValueOffset(), LD->getMemoryVT(),
3798 LD->isVolatile(), LD->getAlignment());
3801 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3802 SDValue Ptr, const Value *SV, int SVOffset,
3803 bool isVolatile, unsigned Alignment) {
3804 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3805 Alignment = getEVTAlignment(Val.getValueType());
3807 // Check if the memory reference references a frame index
3809 if (const FrameIndexSDNode *FI =
3810 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3811 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3813 MachineFunction &MF = getMachineFunction();
3814 unsigned Flags = MachineMemOperand::MOStore;
3816 Flags |= MachineMemOperand::MOVolatile;
3817 MachineMemOperand *MMO =
3818 MF.getMachineMemOperand(SV, Flags, SVOffset,
3819 Val.getValueType().getStoreSize(), Alignment);
3821 return getStore(Chain, dl, Val, Ptr, MMO);
3824 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3825 SDValue Ptr, MachineMemOperand *MMO) {
3826 EVT VT = Val.getValueType();
3827 SDVTList VTs = getVTList(MVT::Other);
3828 SDValue Undef = getUNDEF(Ptr.getValueType());
3829 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3830 FoldingSetNodeID ID;
3831 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3832 ID.AddInteger(VT.getRawBits());
3833 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile()));
3835 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3836 cast<StoreSDNode>(E)->refineAlignment(MMO);
3837 return SDValue(E, 0);
3839 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3840 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false, VT, MMO);
3841 CSEMap.InsertNode(N, IP);
3842 AllNodes.push_back(N);
3843 return SDValue(N, 0);
3846 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3847 SDValue Ptr, const Value *SV,
3848 int SVOffset, EVT SVT,
3849 bool isVolatile, unsigned Alignment) {
3850 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3851 Alignment = getEVTAlignment(SVT);
3853 // Check if the memory reference references a frame index
3855 if (const FrameIndexSDNode *FI =
3856 dyn_cast<const FrameIndexSDNode>(Ptr.getNode()))
3857 SV = PseudoSourceValue::getFixedStack(FI->getIndex());
3859 MachineFunction &MF = getMachineFunction();
3860 unsigned Flags = MachineMemOperand::MOStore;
3862 Flags |= MachineMemOperand::MOVolatile;
3863 MachineMemOperand *MMO =
3864 MF.getMachineMemOperand(SV, Flags, SVOffset, SVT.getStoreSize(), Alignment);
3866 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
3869 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3870 SDValue Ptr, EVT SVT,
3871 MachineMemOperand *MMO) {
3872 EVT VT = Val.getValueType();
3875 return getStore(Chain, dl, Val, Ptr, MMO);
3877 assert(VT.bitsGT(SVT) && "Not a truncation?");
3878 assert(VT.isInteger() == SVT.isInteger() &&
3879 "Can't do FP-INT conversion!");
3882 SDVTList VTs = getVTList(MVT::Other);
3883 SDValue Undef = getUNDEF(Ptr.getValueType());
3884 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3885 FoldingSetNodeID ID;
3886 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3887 ID.AddInteger(SVT.getRawBits());
3888 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile()));
3890 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3891 cast<StoreSDNode>(E)->refineAlignment(MMO);
3892 return SDValue(E, 0);
3894 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3895 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true, SVT, MMO);
3896 CSEMap.InsertNode(N, IP);
3897 AllNodes.push_back(N);
3898 return SDValue(N, 0);
3902 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
3903 SDValue Offset, ISD::MemIndexedMode AM) {
3904 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3905 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3906 "Store is already a indexed store!");
3907 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3908 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3909 FoldingSetNodeID ID;
3910 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3911 ID.AddInteger(ST->getMemoryVT().getRawBits());
3912 ID.AddInteger(ST->getRawSubclassData());
3914 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3915 return SDValue(E, 0);
3916 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3917 new (N) StoreSDNode(Ops, dl, VTs, AM,
3918 ST->isTruncatingStore(), ST->getMemoryVT(),
3919 ST->getMemOperand());
3920 CSEMap.InsertNode(N, IP);
3921 AllNodes.push_back(N);
3922 return SDValue(N, 0);
3925 SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
3926 SDValue Chain, SDValue Ptr,
3928 SDValue Ops[] = { Chain, Ptr, SV };
3929 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
3932 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3933 const SDUse *Ops, unsigned NumOps) {
3935 case 0: return getNode(Opcode, DL, VT);
3936 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3937 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3938 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3942 // Copy from an SDUse array into an SDValue array for use with
3943 // the regular getNode logic.
3944 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3945 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
3948 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3949 const SDValue *Ops, unsigned NumOps) {
3951 case 0: return getNode(Opcode, DL, VT);
3952 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3953 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3954 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3960 case ISD::SELECT_CC: {
3961 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3962 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3963 "LHS and RHS of condition must have same type!");
3964 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3965 "True and False arms of SelectCC must have same type!");
3966 assert(Ops[2].getValueType() == VT &&
3967 "select_cc node must be of same type as true and false value!");
3971 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3972 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3973 "LHS/RHS of comparison should match types!");
3980 SDVTList VTs = getVTList(VT);
3982 if (VT != MVT::Flag) {
3983 FoldingSetNodeID ID;
3984 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3987 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3988 return SDValue(E, 0);
3990 N = NodeAllocator.Allocate<SDNode>();
3991 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
3992 CSEMap.InsertNode(N, IP);
3994 N = NodeAllocator.Allocate<SDNode>();
3995 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
3998 AllNodes.push_back(N);
4002 return SDValue(N, 0);
4005 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4006 const std::vector<EVT> &ResultTys,
4007 const SDValue *Ops, unsigned NumOps) {
4008 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4012 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4013 const EVT *VTs, unsigned NumVTs,
4014 const SDValue *Ops, unsigned NumOps) {
4016 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4017 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4020 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4021 const SDValue *Ops, unsigned NumOps) {
4022 if (VTList.NumVTs == 1)
4023 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4027 // FIXME: figure out how to safely handle things like
4028 // int foo(int x) { return 1 << (x & 255); }
4029 // int bar() { return foo(256); }
4030 case ISD::SRA_PARTS:
4031 case ISD::SRL_PARTS:
4032 case ISD::SHL_PARTS:
4033 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4034 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4035 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4036 else if (N3.getOpcode() == ISD::AND)
4037 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4038 // If the and is only masking out bits that cannot effect the shift,
4039 // eliminate the and.
4040 unsigned NumBits = VT.getSizeInBits()*2;
4041 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4042 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4048 // Memoize the node unless it returns a flag.
4050 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4051 FoldingSetNodeID ID;
4052 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4054 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4055 return SDValue(E, 0);
4057 N = NodeAllocator.Allocate<UnarySDNode>();
4058 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4059 } else if (NumOps == 2) {
4060 N = NodeAllocator.Allocate<BinarySDNode>();
4061 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4062 } else if (NumOps == 3) {
4063 N = NodeAllocator.Allocate<TernarySDNode>();
4064 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4066 N = NodeAllocator.Allocate<SDNode>();
4067 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4069 CSEMap.InsertNode(N, IP);
4072 N = NodeAllocator.Allocate<UnarySDNode>();
4073 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4074 } else if (NumOps == 2) {
4075 N = NodeAllocator.Allocate<BinarySDNode>();
4076 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4077 } else if (NumOps == 3) {
4078 N = NodeAllocator.Allocate<TernarySDNode>();
4079 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
4081 N = NodeAllocator.Allocate<SDNode>();
4082 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
4085 AllNodes.push_back(N);
4089 return SDValue(N, 0);
4092 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4093 return getNode(Opcode, DL, VTList, 0, 0);
4096 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4098 SDValue Ops[] = { N1 };
4099 return getNode(Opcode, DL, VTList, Ops, 1);
4102 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4103 SDValue N1, SDValue N2) {
4104 SDValue Ops[] = { N1, N2 };
4105 return getNode(Opcode, DL, VTList, Ops, 2);
4108 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4109 SDValue N1, SDValue N2, SDValue N3) {
4110 SDValue Ops[] = { N1, N2, N3 };
4111 return getNode(Opcode, DL, VTList, Ops, 3);
4114 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4115 SDValue N1, SDValue N2, SDValue N3,
4117 SDValue Ops[] = { N1, N2, N3, N4 };
4118 return getNode(Opcode, DL, VTList, Ops, 4);
4121 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4122 SDValue N1, SDValue N2, SDValue N3,
4123 SDValue N4, SDValue N5) {
4124 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4125 return getNode(Opcode, DL, VTList, Ops, 5);
4128 SDVTList SelectionDAG::getVTList(EVT VT) {
4129 return makeVTList(SDNode::getValueTypeList(VT), 1);
4132 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4133 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4134 E = VTList.rend(); I != E; ++I)
4135 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4138 EVT *Array = Allocator.Allocate<EVT>(2);
4141 SDVTList Result = makeVTList(Array, 2);
4142 VTList.push_back(Result);
4146 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4147 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4148 E = VTList.rend(); I != E; ++I)
4149 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4153 EVT *Array = Allocator.Allocate<EVT>(3);
4157 SDVTList Result = makeVTList(Array, 3);
4158 VTList.push_back(Result);
4162 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4163 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4164 E = VTList.rend(); I != E; ++I)
4165 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4166 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4169 EVT *Array = Allocator.Allocate<EVT>(3);
4174 SDVTList Result = makeVTList(Array, 4);
4175 VTList.push_back(Result);
4179 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4181 case 0: llvm_unreachable("Cannot have nodes without results!");
4182 case 1: return getVTList(VTs[0]);
4183 case 2: return getVTList(VTs[0], VTs[1]);
4184 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4188 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4189 E = VTList.rend(); I != E; ++I) {
4190 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4193 bool NoMatch = false;
4194 for (unsigned i = 2; i != NumVTs; ++i)
4195 if (VTs[i] != I->VTs[i]) {
4203 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4204 std::copy(VTs, VTs+NumVTs, Array);
4205 SDVTList Result = makeVTList(Array, NumVTs);
4206 VTList.push_back(Result);
4211 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4212 /// specified operands. If the resultant node already exists in the DAG,
4213 /// this does not modify the specified node, instead it returns the node that
4214 /// already exists. If the resultant node does not exist in the DAG, the
4215 /// input node is returned. As a degenerate case, if you specify the same
4216 /// input operands as the node already has, the input node is returned.
4217 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4218 SDNode *N = InN.getNode();
4219 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4221 // Check to see if there is no change.
4222 if (Op == N->getOperand(0)) return InN;
4224 // See if the modified node already exists.
4225 void *InsertPos = 0;
4226 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4227 return SDValue(Existing, InN.getResNo());
4229 // Nope it doesn't. Remove the node from its current place in the maps.
4231 if (!RemoveNodeFromCSEMaps(N))
4234 // Now we update the operands.
4235 N->OperandList[0].set(Op);
4237 // If this gets put into a CSE map, add it.
4238 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4242 SDValue SelectionDAG::
4243 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4244 SDNode *N = InN.getNode();
4245 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4247 // Check to see if there is no change.
4248 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4249 return InN; // No operands changed, just return the input node.
4251 // See if the modified node already exists.
4252 void *InsertPos = 0;
4253 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4254 return SDValue(Existing, InN.getResNo());
4256 // Nope it doesn't. Remove the node from its current place in the maps.
4258 if (!RemoveNodeFromCSEMaps(N))
4261 // Now we update the operands.
4262 if (N->OperandList[0] != Op1)
4263 N->OperandList[0].set(Op1);
4264 if (N->OperandList[1] != Op2)
4265 N->OperandList[1].set(Op2);
4267 // If this gets put into a CSE map, add it.
4268 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4272 SDValue SelectionDAG::
4273 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4274 SDValue Ops[] = { Op1, Op2, Op3 };
4275 return UpdateNodeOperands(N, Ops, 3);
4278 SDValue SelectionDAG::
4279 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4280 SDValue Op3, SDValue Op4) {
4281 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4282 return UpdateNodeOperands(N, Ops, 4);
4285 SDValue SelectionDAG::
4286 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4287 SDValue Op3, SDValue Op4, SDValue Op5) {
4288 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4289 return UpdateNodeOperands(N, Ops, 5);
4292 SDValue SelectionDAG::
4293 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4294 SDNode *N = InN.getNode();
4295 assert(N->getNumOperands() == NumOps &&
4296 "Update with wrong number of operands");
4298 // Check to see if there is no change.
4299 bool AnyChange = false;
4300 for (unsigned i = 0; i != NumOps; ++i) {
4301 if (Ops[i] != N->getOperand(i)) {
4307 // No operands changed, just return the input node.
4308 if (!AnyChange) return InN;
4310 // See if the modified node already exists.
4311 void *InsertPos = 0;
4312 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4313 return SDValue(Existing, InN.getResNo());
4315 // Nope it doesn't. Remove the node from its current place in the maps.
4317 if (!RemoveNodeFromCSEMaps(N))
4320 // Now we update the operands.
4321 for (unsigned i = 0; i != NumOps; ++i)
4322 if (N->OperandList[i] != Ops[i])
4323 N->OperandList[i].set(Ops[i]);
4325 // If this gets put into a CSE map, add it.
4326 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4330 /// DropOperands - Release the operands and set this node to have
4332 void SDNode::DropOperands() {
4333 // Unlike the code in MorphNodeTo that does this, we don't need to
4334 // watch for dead nodes here.
4335 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4341 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4344 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4346 SDVTList VTs = getVTList(VT);
4347 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4350 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4351 EVT VT, SDValue Op1) {
4352 SDVTList VTs = getVTList(VT);
4353 SDValue Ops[] = { Op1 };
4354 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4357 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4358 EVT VT, SDValue Op1,
4360 SDVTList VTs = getVTList(VT);
4361 SDValue Ops[] = { Op1, Op2 };
4362 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4365 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4366 EVT VT, SDValue Op1,
4367 SDValue Op2, SDValue Op3) {
4368 SDVTList VTs = getVTList(VT);
4369 SDValue Ops[] = { Op1, Op2, Op3 };
4370 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4373 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4374 EVT VT, const SDValue *Ops,
4376 SDVTList VTs = getVTList(VT);
4377 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4380 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4381 EVT VT1, EVT VT2, const SDValue *Ops,
4383 SDVTList VTs = getVTList(VT1, VT2);
4384 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4387 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4389 SDVTList VTs = getVTList(VT1, VT2);
4390 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4393 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4394 EVT VT1, EVT VT2, EVT VT3,
4395 const SDValue *Ops, unsigned NumOps) {
4396 SDVTList VTs = getVTList(VT1, VT2, VT3);
4397 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4400 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4401 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4402 const SDValue *Ops, unsigned NumOps) {
4403 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4404 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4407 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4410 SDVTList VTs = getVTList(VT1, VT2);
4411 SDValue Ops[] = { Op1 };
4412 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4415 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4417 SDValue Op1, SDValue Op2) {
4418 SDVTList VTs = getVTList(VT1, VT2);
4419 SDValue Ops[] = { Op1, Op2 };
4420 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4423 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4425 SDValue Op1, SDValue Op2,
4427 SDVTList VTs = getVTList(VT1, VT2);
4428 SDValue Ops[] = { Op1, Op2, Op3 };
4429 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4432 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4433 EVT VT1, EVT VT2, EVT VT3,
4434 SDValue Op1, SDValue Op2,
4436 SDVTList VTs = getVTList(VT1, VT2, VT3);
4437 SDValue Ops[] = { Op1, Op2, Op3 };
4438 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4441 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4442 SDVTList VTs, const SDValue *Ops,
4444 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4447 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4449 SDVTList VTs = getVTList(VT);
4450 return MorphNodeTo(N, Opc, VTs, 0, 0);
4453 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4454 EVT VT, SDValue Op1) {
4455 SDVTList VTs = getVTList(VT);
4456 SDValue Ops[] = { Op1 };
4457 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4460 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4461 EVT VT, SDValue Op1,
4463 SDVTList VTs = getVTList(VT);
4464 SDValue Ops[] = { Op1, Op2 };
4465 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4468 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4469 EVT VT, SDValue Op1,
4470 SDValue Op2, SDValue Op3) {
4471 SDVTList VTs = getVTList(VT);
4472 SDValue Ops[] = { Op1, Op2, Op3 };
4473 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4476 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4477 EVT VT, const SDValue *Ops,
4479 SDVTList VTs = getVTList(VT);
4480 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4483 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4484 EVT VT1, EVT VT2, const SDValue *Ops,
4486 SDVTList VTs = getVTList(VT1, VT2);
4487 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4490 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4492 SDVTList VTs = getVTList(VT1, VT2);
4493 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4496 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4497 EVT VT1, EVT VT2, EVT VT3,
4498 const SDValue *Ops, unsigned NumOps) {
4499 SDVTList VTs = getVTList(VT1, VT2, VT3);
4500 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4503 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4506 SDVTList VTs = getVTList(VT1, VT2);
4507 SDValue Ops[] = { Op1 };
4508 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4511 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4513 SDValue Op1, SDValue Op2) {
4514 SDVTList VTs = getVTList(VT1, VT2);
4515 SDValue Ops[] = { Op1, Op2 };
4516 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4519 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4521 SDValue Op1, SDValue Op2,
4523 SDVTList VTs = getVTList(VT1, VT2);
4524 SDValue Ops[] = { Op1, Op2, Op3 };
4525 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4528 /// MorphNodeTo - These *mutate* the specified node to have the specified
4529 /// return type, opcode, and operands.
4531 /// Note that MorphNodeTo returns the resultant node. If there is already a
4532 /// node of the specified opcode and operands, it returns that node instead of
4533 /// the current one. Note that the DebugLoc need not be the same.
4535 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4536 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4537 /// node, and because it doesn't require CSE recalculation for any of
4538 /// the node's users.
4540 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4541 SDVTList VTs, const SDValue *Ops,
4543 // If an identical node already exists, use it.
4545 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4546 FoldingSetNodeID ID;
4547 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4548 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4552 if (!RemoveNodeFromCSEMaps(N))
4555 // Start the morphing.
4557 N->ValueList = VTs.VTs;
4558 N->NumValues = VTs.NumVTs;
4560 // Clear the operands list, updating used nodes to remove this from their
4561 // use list. Keep track of any operands that become dead as a result.
4562 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4563 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4565 SDNode *Used = Use.getNode();
4567 if (Used->use_empty())
4568 DeadNodeSet.insert(Used);
4571 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
4572 // Initialize the memory references information.
4573 MN->setMemRefs(0, 0);
4574 // If NumOps is larger than the # of operands we can have in a
4575 // MachineSDNode, reallocate the operand list.
4576 if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
4577 if (MN->OperandsNeedDelete)
4578 delete[] MN->OperandList;
4579 if (NumOps > array_lengthof(MN->LocalOperands))
4580 // We're creating a final node that will live unmorphed for the
4581 // remainder of the current SelectionDAG iteration, so we can allocate
4582 // the operands directly out of a pool with no recycling metadata.
4583 MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4586 MN->InitOperands(MN->LocalOperands, Ops, NumOps);
4587 MN->OperandsNeedDelete = false;
4589 MN->InitOperands(MN->OperandList, Ops, NumOps);
4591 // If NumOps is larger than the # of operands we currently have, reallocate
4592 // the operand list.
4593 if (NumOps > N->NumOperands) {
4594 if (N->OperandsNeedDelete)
4595 delete[] N->OperandList;
4596 N->InitOperands(new SDUse[NumOps], Ops, NumOps);
4597 N->OperandsNeedDelete = true;
4599 N->InitOperands(N->OperandList, Ops, NumOps);
4602 // Delete any nodes that are still dead after adding the uses for the
4604 SmallVector<SDNode *, 16> DeadNodes;
4605 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4606 E = DeadNodeSet.end(); I != E; ++I)
4607 if ((*I)->use_empty())
4608 DeadNodes.push_back(*I);
4609 RemoveDeadNodes(DeadNodes);
4612 CSEMap.InsertNode(N, IP); // Memoize the new node.
4617 /// getMachineNode - These are used for target selectors to create a new node
4618 /// with specified return type(s), MachineInstr opcode, and operands.
4620 /// Note that getMachineNode returns the resultant node. If there is already a
4621 /// node of the specified opcode and operands, it returns that node instead of
4622 /// the current one.
4624 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
4625 SDVTList VTs = getVTList(VT);
4626 return getMachineNode(Opcode, dl, VTs, 0, 0);
4630 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
4631 SDVTList VTs = getVTList(VT);
4632 SDValue Ops[] = { Op1 };
4633 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4637 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4638 SDValue Op1, SDValue Op2) {
4639 SDVTList VTs = getVTList(VT);
4640 SDValue Ops[] = { Op1, Op2 };
4641 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4645 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4646 SDValue Op1, SDValue Op2, SDValue Op3) {
4647 SDVTList VTs = getVTList(VT);
4648 SDValue Ops[] = { Op1, Op2, Op3 };
4649 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4653 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4654 const SDValue *Ops, unsigned NumOps) {
4655 SDVTList VTs = getVTList(VT);
4656 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4660 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
4661 SDVTList VTs = getVTList(VT1, VT2);
4662 return getMachineNode(Opcode, dl, VTs, 0, 0);
4666 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4667 EVT VT1, EVT VT2, SDValue Op1) {
4668 SDVTList VTs = getVTList(VT1, VT2);
4669 SDValue Ops[] = { Op1 };
4670 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4674 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4675 EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
4676 SDVTList VTs = getVTList(VT1, VT2);
4677 SDValue Ops[] = { Op1, Op2 };
4678 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4682 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4683 EVT VT1, EVT VT2, SDValue Op1,
4684 SDValue Op2, SDValue Op3) {
4685 SDVTList VTs = getVTList(VT1, VT2);
4686 SDValue Ops[] = { Op1, Op2, Op3 };
4687 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4691 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4693 const SDValue *Ops, unsigned NumOps) {
4694 SDVTList VTs = getVTList(VT1, VT2);
4695 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4699 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4700 EVT VT1, EVT VT2, EVT VT3,
4701 SDValue Op1, SDValue Op2) {
4702 SDVTList VTs = getVTList(VT1, VT2, VT3);
4703 SDValue Ops[] = { Op1, Op2 };
4704 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4708 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4709 EVT VT1, EVT VT2, EVT VT3,
4710 SDValue Op1, SDValue Op2, SDValue Op3) {
4711 SDVTList VTs = getVTList(VT1, VT2, VT3);
4712 SDValue Ops[] = { Op1, Op2, Op3 };
4713 return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4717 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4718 EVT VT1, EVT VT2, EVT VT3,
4719 const SDValue *Ops, unsigned NumOps) {
4720 SDVTList VTs = getVTList(VT1, VT2, VT3);
4721 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4725 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4726 EVT VT2, EVT VT3, EVT VT4,
4727 const SDValue *Ops, unsigned NumOps) {
4728 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4729 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4733 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4734 const std::vector<EVT> &ResultTys,
4735 const SDValue *Ops, unsigned NumOps) {
4736 SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
4737 return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4741 SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
4742 const SDValue *Ops, unsigned NumOps) {
4743 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Flag;
4748 FoldingSetNodeID ID;
4749 AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
4751 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4752 return cast<MachineSDNode>(E);
4755 // Allocate a new MachineSDNode.
4756 N = NodeAllocator.Allocate<MachineSDNode>();
4757 new (N) MachineSDNode(~Opcode, DL, VTs);
4759 // Initialize the operands list.
4760 if (NumOps > array_lengthof(N->LocalOperands))
4761 // We're creating a final node that will live unmorphed for the
4762 // remainder of the current SelectionDAG iteration, so we can allocate
4763 // the operands directly out of a pool with no recycling metadata.
4764 N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4767 N->InitOperands(N->LocalOperands, Ops, NumOps);
4768 N->OperandsNeedDelete = false;
4771 CSEMap.InsertNode(N, IP);
4773 AllNodes.push_back(N);
4780 /// getTargetExtractSubreg - A convenience function for creating
4781 /// TargetInstrInfo::EXTRACT_SUBREG nodes.
4783 SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
4785 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4786 SDNode *Subreg = getMachineNode(TargetInstrInfo::EXTRACT_SUBREG, DL,
4787 VT, Operand, SRIdxVal);
4788 return SDValue(Subreg, 0);
4791 /// getTargetInsertSubreg - A convenience function for creating
4792 /// TargetInstrInfo::INSERT_SUBREG nodes.
4794 SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
4795 SDValue Operand, SDValue Subreg) {
4796 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4797 SDNode *Result = getMachineNode(TargetInstrInfo::INSERT_SUBREG, DL,
4798 VT, Operand, Subreg, SRIdxVal);
4799 return SDValue(Result, 0);
4802 /// getNodeIfExists - Get the specified node if it's already available, or
4803 /// else return NULL.
4804 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4805 const SDValue *Ops, unsigned NumOps) {
4806 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4807 FoldingSetNodeID ID;
4808 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4810 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4816 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4817 /// This can cause recursive merging of nodes in the DAG.
4819 /// This version assumes From has a single result value.
4821 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4822 DAGUpdateListener *UpdateListener) {
4823 SDNode *From = FromN.getNode();
4824 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4825 "Cannot replace with this method!");
4826 assert(From != To.getNode() && "Cannot replace uses of with self");
4828 // Iterate over all the existing uses of From. New uses will be added
4829 // to the beginning of the use list, which we avoid visiting.
4830 // This specifically avoids visiting uses of From that arise while the
4831 // replacement is happening, because any such uses would be the result
4832 // of CSE: If an existing node looks like From after one of its operands
4833 // is replaced by To, we don't want to replace of all its users with To
4834 // too. See PR3018 for more info.
4835 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4839 // This node is about to morph, remove its old self from the CSE maps.
4840 RemoveNodeFromCSEMaps(User);
4842 // A user can appear in a use list multiple times, and when this
4843 // happens the uses are usually next to each other in the list.
4844 // To help reduce the number of CSE recomputations, process all
4845 // the uses of this user that we can find this way.
4847 SDUse &Use = UI.getUse();
4850 } while (UI != UE && *UI == User);
4852 // Now that we have modified User, add it back to the CSE maps. If it
4853 // already exists there, recursively merge the results together.
4854 AddModifiedNodeToCSEMaps(User, UpdateListener);
4858 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4859 /// This can cause recursive merging of nodes in the DAG.
4861 /// This version assumes that for each value of From, there is a
4862 /// corresponding value in To in the same position with the same type.
4864 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4865 DAGUpdateListener *UpdateListener) {
4867 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
4868 assert((!From->hasAnyUseOfValue(i) ||
4869 From->getValueType(i) == To->getValueType(i)) &&
4870 "Cannot use this version of ReplaceAllUsesWith!");
4873 // Handle the trivial case.
4877 // Iterate over just the existing users of From. See the comments in
4878 // the ReplaceAllUsesWith above.
4879 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4883 // This node is about to morph, remove its old self from the CSE maps.
4884 RemoveNodeFromCSEMaps(User);
4886 // A user can appear in a use list multiple times, and when this
4887 // happens the uses are usually next to each other in the list.
4888 // To help reduce the number of CSE recomputations, process all
4889 // the uses of this user that we can find this way.
4891 SDUse &Use = UI.getUse();
4894 } while (UI != UE && *UI == User);
4896 // Now that we have modified User, add it back to the CSE maps. If it
4897 // already exists there, recursively merge the results together.
4898 AddModifiedNodeToCSEMaps(User, UpdateListener);
4902 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4903 /// This can cause recursive merging of nodes in the DAG.
4905 /// This version can replace From with any result values. To must match the
4906 /// number and types of values returned by From.
4907 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4909 DAGUpdateListener *UpdateListener) {
4910 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4911 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4913 // Iterate over just the existing users of From. See the comments in
4914 // the ReplaceAllUsesWith above.
4915 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4919 // This node is about to morph, remove its old self from the CSE maps.
4920 RemoveNodeFromCSEMaps(User);
4922 // A user can appear in a use list multiple times, and when this
4923 // happens the uses are usually next to each other in the list.
4924 // To help reduce the number of CSE recomputations, process all
4925 // the uses of this user that we can find this way.
4927 SDUse &Use = UI.getUse();
4928 const SDValue &ToOp = To[Use.getResNo()];
4931 } while (UI != UE && *UI == User);
4933 // Now that we have modified User, add it back to the CSE maps. If it
4934 // already exists there, recursively merge the results together.
4935 AddModifiedNodeToCSEMaps(User, UpdateListener);
4939 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4940 /// uses of other values produced by From.getNode() alone. The Deleted
4941 /// vector is handled the same way as for ReplaceAllUsesWith.
4942 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4943 DAGUpdateListener *UpdateListener){
4944 // Handle the really simple, really trivial case efficiently.
4945 if (From == To) return;
4947 // Handle the simple, trivial, case efficiently.
4948 if (From.getNode()->getNumValues() == 1) {
4949 ReplaceAllUsesWith(From, To, UpdateListener);
4953 // Iterate over just the existing users of From. See the comments in
4954 // the ReplaceAllUsesWith above.
4955 SDNode::use_iterator UI = From.getNode()->use_begin(),
4956 UE = From.getNode()->use_end();
4959 bool UserRemovedFromCSEMaps = false;
4961 // A user can appear in a use list multiple times, and when this
4962 // happens the uses are usually next to each other in the list.
4963 // To help reduce the number of CSE recomputations, process all
4964 // the uses of this user that we can find this way.
4966 SDUse &Use = UI.getUse();
4968 // Skip uses of different values from the same node.
4969 if (Use.getResNo() != From.getResNo()) {
4974 // If this node hasn't been modified yet, it's still in the CSE maps,
4975 // so remove its old self from the CSE maps.
4976 if (!UserRemovedFromCSEMaps) {
4977 RemoveNodeFromCSEMaps(User);
4978 UserRemovedFromCSEMaps = true;
4983 } while (UI != UE && *UI == User);
4985 // We are iterating over all uses of the From node, so if a use
4986 // doesn't use the specific value, no changes are made.
4987 if (!UserRemovedFromCSEMaps)
4990 // Now that we have modified User, add it back to the CSE maps. If it
4991 // already exists there, recursively merge the results together.
4992 AddModifiedNodeToCSEMaps(User, UpdateListener);
4997 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
4998 /// to record information about a use.
5005 /// operator< - Sort Memos by User.
5006 bool operator<(const UseMemo &L, const UseMemo &R) {
5007 return (intptr_t)L.User < (intptr_t)R.User;
5011 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5012 /// uses of other values produced by From.getNode() alone. The same value
5013 /// may appear in both the From and To list. The Deleted vector is
5014 /// handled the same way as for ReplaceAllUsesWith.
5015 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5018 DAGUpdateListener *UpdateListener){
5019 // Handle the simple, trivial case efficiently.
5021 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5023 // Read up all the uses and make records of them. This helps
5024 // processing new uses that are introduced during the
5025 // replacement process.
5026 SmallVector<UseMemo, 4> Uses;
5027 for (unsigned i = 0; i != Num; ++i) {
5028 unsigned FromResNo = From[i].getResNo();
5029 SDNode *FromNode = From[i].getNode();
5030 for (SDNode::use_iterator UI = FromNode->use_begin(),
5031 E = FromNode->use_end(); UI != E; ++UI) {
5032 SDUse &Use = UI.getUse();
5033 if (Use.getResNo() == FromResNo) {
5034 UseMemo Memo = { *UI, i, &Use };
5035 Uses.push_back(Memo);
5040 // Sort the uses, so that all the uses from a given User are together.
5041 std::sort(Uses.begin(), Uses.end());
5043 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5044 UseIndex != UseIndexEnd; ) {
5045 // We know that this user uses some value of From. If it is the right
5046 // value, update it.
5047 SDNode *User = Uses[UseIndex].User;
5049 // This node is about to morph, remove its old self from the CSE maps.
5050 RemoveNodeFromCSEMaps(User);
5052 // The Uses array is sorted, so all the uses for a given User
5053 // are next to each other in the list.
5054 // To help reduce the number of CSE recomputations, process all
5055 // the uses of this user that we can find this way.
5057 unsigned i = Uses[UseIndex].Index;
5058 SDUse &Use = *Uses[UseIndex].Use;
5062 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5064 // Now that we have modified User, add it back to the CSE maps. If it
5065 // already exists there, recursively merge the results together.
5066 AddModifiedNodeToCSEMaps(User, UpdateListener);
5070 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5071 /// based on their topological order. It returns the maximum id and a vector
5072 /// of the SDNodes* in assigned order by reference.
5073 unsigned SelectionDAG::AssignTopologicalOrder() {
5075 unsigned DAGSize = 0;
5077 // SortedPos tracks the progress of the algorithm. Nodes before it are
5078 // sorted, nodes after it are unsorted. When the algorithm completes
5079 // it is at the end of the list.
5080 allnodes_iterator SortedPos = allnodes_begin();
5082 // Visit all the nodes. Move nodes with no operands to the front of
5083 // the list immediately. Annotate nodes that do have operands with their
5084 // operand count. Before we do this, the Node Id fields of the nodes
5085 // may contain arbitrary values. After, the Node Id fields for nodes
5086 // before SortedPos will contain the topological sort index, and the
5087 // Node Id fields for nodes At SortedPos and after will contain the
5088 // count of outstanding operands.
5089 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5091 unsigned Degree = N->getNumOperands();
5093 // A node with no uses, add it to the result array immediately.
5094 N->setNodeId(DAGSize++);
5095 allnodes_iterator Q = N;
5097 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5100 // Temporarily use the Node Id as scratch space for the degree count.
5101 N->setNodeId(Degree);
5105 // Visit all the nodes. As we iterate, moves nodes into sorted order,
5106 // such that by the time the end is reached all nodes will be sorted.
5107 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5109 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5112 unsigned Degree = P->getNodeId();
5115 // All of P's operands are sorted, so P may sorted now.
5116 P->setNodeId(DAGSize++);
5118 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5121 // Update P's outstanding operand count.
5122 P->setNodeId(Degree);
5127 assert(SortedPos == AllNodes.end() &&
5128 "Topological sort incomplete!");
5129 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5130 "First node in topological sort is not the entry token!");
5131 assert(AllNodes.front().getNodeId() == 0 &&
5132 "First node in topological sort has non-zero id!");
5133 assert(AllNodes.front().getNumOperands() == 0 &&
5134 "First node in topological sort has operands!");
5135 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5136 "Last node in topologic sort has unexpected id!");
5137 assert(AllNodes.back().use_empty() &&
5138 "Last node in topologic sort has users!");
5139 assert(DAGSize == allnodes_size() && "Node count mismatch!");
5145 //===----------------------------------------------------------------------===//
5147 //===----------------------------------------------------------------------===//
5149 HandleSDNode::~HandleSDNode() {
5153 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA,
5154 EVT VT, int64_t o, unsigned char TF)
5155 : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)),
5156 Offset(o), TargetFlags(TF) {
5157 TheGlobal = const_cast<GlobalValue*>(GA);
5160 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
5161 MachineMemOperand *mmo)
5162 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5163 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile());
5164 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5165 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5168 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5169 const SDValue *Ops, unsigned NumOps, EVT memvt,
5170 MachineMemOperand *mmo)
5171 : SDNode(Opc, dl, VTs, Ops, NumOps),
5172 MemoryVT(memvt), MMO(mmo) {
5173 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile());
5174 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5175 assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5178 /// Profile - Gather unique data for the node.
5180 void SDNode::Profile(FoldingSetNodeID &ID) const {
5181 AddNodeIDNode(ID, this);
5186 std::vector<EVT> VTs;
5189 VTs.reserve(MVT::LAST_VALUETYPE);
5190 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5191 VTs.push_back(MVT((MVT::SimpleValueType)i));
5196 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5197 static ManagedStatic<EVTArray> SimpleVTArray;
5198 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5200 /// getValueTypeList - Return a pointer to the specified value type.
5202 const EVT *SDNode::getValueTypeList(EVT VT) {
5203 if (VT.isExtended()) {
5204 sys::SmartScopedLock<true> Lock(*VTMutex);
5205 return &(*EVTs->insert(VT).first);
5207 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5211 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5212 /// indicated value. This method ignores uses of other values defined by this
5214 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5215 assert(Value < getNumValues() && "Bad value!");
5217 // TODO: Only iterate over uses of a given value of the node
5218 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5219 if (UI.getUse().getResNo() == Value) {
5226 // Found exactly the right number of uses?
5231 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5232 /// value. This method ignores uses of other values defined by this operation.
5233 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5234 assert(Value < getNumValues() && "Bad value!");
5236 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5237 if (UI.getUse().getResNo() == Value)
5244 /// isOnlyUserOf - Return true if this node is the only use of N.
5246 bool SDNode::isOnlyUserOf(SDNode *N) const {
5248 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5259 /// isOperand - Return true if this node is an operand of N.
5261 bool SDValue::isOperandOf(SDNode *N) const {
5262 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5263 if (*this == N->getOperand(i))
5268 bool SDNode::isOperandOf(SDNode *N) const {
5269 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5270 if (this == N->OperandList[i].getNode())
5275 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5276 /// be a chain) reaches the specified operand without crossing any
5277 /// side-effecting instructions. In practice, this looks through token
5278 /// factors and non-volatile loads. In order to remain efficient, this only
5279 /// looks a couple of nodes in, it does not do an exhaustive search.
5280 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5281 unsigned Depth) const {
5282 if (*this == Dest) return true;
5284 // Don't search too deeply, we just want to be able to see through
5285 // TokenFactor's etc.
5286 if (Depth == 0) return false;
5288 // If this is a token factor, all inputs to the TF happen in parallel. If any
5289 // of the operands of the TF reach dest, then we can do the xform.
5290 if (getOpcode() == ISD::TokenFactor) {
5291 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5292 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5297 // Loads don't have side effects, look through them.
5298 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5299 if (!Ld->isVolatile())
5300 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5305 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5306 /// is either an operand of N or it can be reached by traversing up the operands.
5307 /// NOTE: this is an expensive method. Use it carefully.
5308 bool SDNode::isPredecessorOf(SDNode *N) const {
5309 SmallPtrSet<SDNode *, 32> Visited;
5310 SmallVector<SDNode *, 16> Worklist;
5311 Worklist.push_back(N);
5314 N = Worklist.pop_back_val();
5315 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5316 SDNode *Op = N->getOperand(i).getNode();
5319 if (Visited.insert(Op))
5320 Worklist.push_back(Op);
5322 } while (!Worklist.empty());
5327 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5328 assert(Num < NumOperands && "Invalid child # of SDNode!");
5329 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5332 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5333 switch (getOpcode()) {
5335 if (getOpcode() < ISD::BUILTIN_OP_END)
5336 return "<<Unknown DAG Node>>";
5337 if (isMachineOpcode()) {
5339 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5340 if (getMachineOpcode() < TII->getNumOpcodes())
5341 return TII->get(getMachineOpcode()).getName();
5342 return "<<Unknown Machine Node>>";
5345 const TargetLowering &TLI = G->getTargetLoweringInfo();
5346 const char *Name = TLI.getTargetNodeName(getOpcode());
5347 if (Name) return Name;
5348 return "<<Unknown Target Node>>";
5350 return "<<Unknown Node>>";
5353 case ISD::DELETED_NODE:
5354 return "<<Deleted Node!>>";
5356 case ISD::PREFETCH: return "Prefetch";
5357 case ISD::MEMBARRIER: return "MemBarrier";
5358 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5359 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5360 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5361 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5362 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5363 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5364 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5365 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5366 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5367 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5368 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5369 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5370 case ISD::PCMARKER: return "PCMarker";
5371 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5372 case ISD::SRCVALUE: return "SrcValue";
5373 case ISD::EntryToken: return "EntryToken";
5374 case ISD::TokenFactor: return "TokenFactor";
5375 case ISD::AssertSext: return "AssertSext";
5376 case ISD::AssertZext: return "AssertZext";
5378 case ISD::BasicBlock: return "BasicBlock";
5379 case ISD::VALUETYPE: return "ValueType";
5380 case ISD::Register: return "Register";
5382 case ISD::Constant: return "Constant";
5383 case ISD::ConstantFP: return "ConstantFP";
5384 case ISD::GlobalAddress: return "GlobalAddress";
5385 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5386 case ISD::FrameIndex: return "FrameIndex";
5387 case ISD::JumpTable: return "JumpTable";
5388 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5389 case ISD::RETURNADDR: return "RETURNADDR";
5390 case ISD::FRAMEADDR: return "FRAMEADDR";
5391 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5392 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5393 case ISD::LSDAADDR: return "LSDAADDR";
5394 case ISD::EHSELECTION: return "EHSELECTION";
5395 case ISD::EH_RETURN: return "EH_RETURN";
5396 case ISD::ConstantPool: return "ConstantPool";
5397 case ISD::ExternalSymbol: return "ExternalSymbol";
5398 case ISD::BlockAddress: return "BlockAddress";
5399 case ISD::INTRINSIC_WO_CHAIN:
5400 case ISD::INTRINSIC_VOID:
5401 case ISD::INTRINSIC_W_CHAIN: {
5402 unsigned OpNo = getOpcode() == ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
5403 unsigned IID = cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue();
5404 if (IID < Intrinsic::num_intrinsics)
5405 return Intrinsic::getName((Intrinsic::ID)IID);
5406 else if (const TargetIntrinsicInfo *TII = G->getTarget().getIntrinsicInfo())
5407 return TII->getName(IID);
5408 llvm_unreachable("Invalid intrinsic ID");
5411 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5412 case ISD::TargetConstant: return "TargetConstant";
5413 case ISD::TargetConstantFP:return "TargetConstantFP";
5414 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5415 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5416 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5417 case ISD::TargetJumpTable: return "TargetJumpTable";
5418 case ISD::TargetConstantPool: return "TargetConstantPool";
5419 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5420 case ISD::TargetBlockAddress: return "TargetBlockAddress";
5422 case ISD::CopyToReg: return "CopyToReg";
5423 case ISD::CopyFromReg: return "CopyFromReg";
5424 case ISD::UNDEF: return "undef";
5425 case ISD::MERGE_VALUES: return "merge_values";
5426 case ISD::INLINEASM: return "inlineasm";
5427 case ISD::EH_LABEL: return "eh_label";
5428 case ISD::HANDLENODE: return "handlenode";
5431 case ISD::FABS: return "fabs";
5432 case ISD::FNEG: return "fneg";
5433 case ISD::FSQRT: return "fsqrt";
5434 case ISD::FSIN: return "fsin";
5435 case ISD::FCOS: return "fcos";
5436 case ISD::FPOWI: return "fpowi";
5437 case ISD::FPOW: return "fpow";
5438 case ISD::FTRUNC: return "ftrunc";
5439 case ISD::FFLOOR: return "ffloor";
5440 case ISD::FCEIL: return "fceil";
5441 case ISD::FRINT: return "frint";
5442 case ISD::FNEARBYINT: return "fnearbyint";
5445 case ISD::ADD: return "add";
5446 case ISD::SUB: return "sub";
5447 case ISD::MUL: return "mul";
5448 case ISD::MULHU: return "mulhu";
5449 case ISD::MULHS: return "mulhs";
5450 case ISD::SDIV: return "sdiv";
5451 case ISD::UDIV: return "udiv";
5452 case ISD::SREM: return "srem";
5453 case ISD::UREM: return "urem";
5454 case ISD::SMUL_LOHI: return "smul_lohi";
5455 case ISD::UMUL_LOHI: return "umul_lohi";
5456 case ISD::SDIVREM: return "sdivrem";
5457 case ISD::UDIVREM: return "udivrem";
5458 case ISD::AND: return "and";
5459 case ISD::OR: return "or";
5460 case ISD::XOR: return "xor";
5461 case ISD::SHL: return "shl";
5462 case ISD::SRA: return "sra";
5463 case ISD::SRL: return "srl";
5464 case ISD::ROTL: return "rotl";
5465 case ISD::ROTR: return "rotr";
5466 case ISD::FADD: return "fadd";
5467 case ISD::FSUB: return "fsub";
5468 case ISD::FMUL: return "fmul";
5469 case ISD::FDIV: return "fdiv";
5470 case ISD::FREM: return "frem";
5471 case ISD::FCOPYSIGN: return "fcopysign";
5472 case ISD::FGETSIGN: return "fgetsign";
5474 case ISD::SETCC: return "setcc";
5475 case ISD::VSETCC: return "vsetcc";
5476 case ISD::SELECT: return "select";
5477 case ISD::SELECT_CC: return "select_cc";
5478 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5479 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5480 case ISD::CONCAT_VECTORS: return "concat_vectors";
5481 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5482 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5483 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5484 case ISD::CARRY_FALSE: return "carry_false";
5485 case ISD::ADDC: return "addc";
5486 case ISD::ADDE: return "adde";
5487 case ISD::SADDO: return "saddo";
5488 case ISD::UADDO: return "uaddo";
5489 case ISD::SSUBO: return "ssubo";
5490 case ISD::USUBO: return "usubo";
5491 case ISD::SMULO: return "smulo";
5492 case ISD::UMULO: return "umulo";
5493 case ISD::SUBC: return "subc";
5494 case ISD::SUBE: return "sube";
5495 case ISD::SHL_PARTS: return "shl_parts";
5496 case ISD::SRA_PARTS: return "sra_parts";
5497 case ISD::SRL_PARTS: return "srl_parts";
5499 // Conversion operators.
5500 case ISD::SIGN_EXTEND: return "sign_extend";
5501 case ISD::ZERO_EXTEND: return "zero_extend";
5502 case ISD::ANY_EXTEND: return "any_extend";
5503 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5504 case ISD::TRUNCATE: return "truncate";
5505 case ISD::FP_ROUND: return "fp_round";
5506 case ISD::FLT_ROUNDS_: return "flt_rounds";
5507 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5508 case ISD::FP_EXTEND: return "fp_extend";
5510 case ISD::SINT_TO_FP: return "sint_to_fp";
5511 case ISD::UINT_TO_FP: return "uint_to_fp";
5512 case ISD::FP_TO_SINT: return "fp_to_sint";
5513 case ISD::FP_TO_UINT: return "fp_to_uint";
5514 case ISD::BIT_CONVERT: return "bit_convert";
5516 case ISD::CONVERT_RNDSAT: {
5517 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5518 default: llvm_unreachable("Unknown cvt code!");
5519 case ISD::CVT_FF: return "cvt_ff";
5520 case ISD::CVT_FS: return "cvt_fs";
5521 case ISD::CVT_FU: return "cvt_fu";
5522 case ISD::CVT_SF: return "cvt_sf";
5523 case ISD::CVT_UF: return "cvt_uf";
5524 case ISD::CVT_SS: return "cvt_ss";
5525 case ISD::CVT_SU: return "cvt_su";
5526 case ISD::CVT_US: return "cvt_us";
5527 case ISD::CVT_UU: return "cvt_uu";
5531 // Control flow instructions
5532 case ISD::BR: return "br";
5533 case ISD::BRIND: return "brind";
5534 case ISD::BR_JT: return "br_jt";
5535 case ISD::BRCOND: return "brcond";
5536 case ISD::BR_CC: return "br_cc";
5537 case ISD::CALLSEQ_START: return "callseq_start";
5538 case ISD::CALLSEQ_END: return "callseq_end";
5541 case ISD::LOAD: return "load";
5542 case ISD::STORE: return "store";
5543 case ISD::VAARG: return "vaarg";
5544 case ISD::VACOPY: return "vacopy";
5545 case ISD::VAEND: return "vaend";
5546 case ISD::VASTART: return "vastart";
5547 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5548 case ISD::EXTRACT_ELEMENT: return "extract_element";
5549 case ISD::BUILD_PAIR: return "build_pair";
5550 case ISD::STACKSAVE: return "stacksave";
5551 case ISD::STACKRESTORE: return "stackrestore";
5552 case ISD::TRAP: return "trap";
5555 case ISD::BSWAP: return "bswap";
5556 case ISD::CTPOP: return "ctpop";
5557 case ISD::CTTZ: return "cttz";
5558 case ISD::CTLZ: return "ctlz";
5561 case ISD::TRAMPOLINE: return "trampoline";
5564 switch (cast<CondCodeSDNode>(this)->get()) {
5565 default: llvm_unreachable("Unknown setcc condition!");
5566 case ISD::SETOEQ: return "setoeq";
5567 case ISD::SETOGT: return "setogt";
5568 case ISD::SETOGE: return "setoge";
5569 case ISD::SETOLT: return "setolt";
5570 case ISD::SETOLE: return "setole";
5571 case ISD::SETONE: return "setone";
5573 case ISD::SETO: return "seto";
5574 case ISD::SETUO: return "setuo";
5575 case ISD::SETUEQ: return "setue";
5576 case ISD::SETUGT: return "setugt";
5577 case ISD::SETUGE: return "setuge";
5578 case ISD::SETULT: return "setult";
5579 case ISD::SETULE: return "setule";
5580 case ISD::SETUNE: return "setune";
5582 case ISD::SETEQ: return "seteq";
5583 case ISD::SETGT: return "setgt";
5584 case ISD::SETGE: return "setge";
5585 case ISD::SETLT: return "setlt";
5586 case ISD::SETLE: return "setle";
5587 case ISD::SETNE: return "setne";
5592 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5601 return "<post-inc>";
5603 return "<post-dec>";
5607 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5608 std::string S = "< ";
5622 if (getByValAlign())
5623 S += "byval-align:" + utostr(getByValAlign()) + " ";
5625 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5627 S += "byval-size:" + utostr(getByValSize()) + " ";
5631 void SDNode::dump() const { dump(0); }
5632 void SDNode::dump(const SelectionDAG *G) const {
5636 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
5637 OS << (void*)this << ": ";
5639 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5641 if (getValueType(i) == MVT::Other)
5644 OS << getValueType(i).getEVTString();
5646 OS << " = " << getOperationName(G);
5649 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
5650 if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
5651 if (!MN->memoperands_empty()) {
5654 for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
5655 e = MN->memoperands_end(); i != e; ++i) {
5662 } else if (const ShuffleVectorSDNode *SVN =
5663 dyn_cast<ShuffleVectorSDNode>(this)) {
5665 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
5666 int Idx = SVN->getMaskElt(i);
5674 } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5675 OS << '<' << CSDN->getAPIntValue() << '>';
5676 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5677 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5678 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5679 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5680 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5683 CSDN->getValueAPF().bitcastToAPInt().dump();
5686 } else if (const GlobalAddressSDNode *GADN =
5687 dyn_cast<GlobalAddressSDNode>(this)) {
5688 int64_t offset = GADN->getOffset();
5690 WriteAsOperand(OS, GADN->getGlobal());
5693 OS << " + " << offset;
5695 OS << " " << offset;
5696 if (unsigned int TF = GADN->getTargetFlags())
5697 OS << " [TF=" << TF << ']';
5698 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5699 OS << "<" << FIDN->getIndex() << ">";
5700 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5701 OS << "<" << JTDN->getIndex() << ">";
5702 if (unsigned int TF = JTDN->getTargetFlags())
5703 OS << " [TF=" << TF << ']';
5704 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5705 int offset = CP->getOffset();
5706 if (CP->isMachineConstantPoolEntry())
5707 OS << "<" << *CP->getMachineCPVal() << ">";
5709 OS << "<" << *CP->getConstVal() << ">";
5711 OS << " + " << offset;
5713 OS << " " << offset;
5714 if (unsigned int TF = CP->getTargetFlags())
5715 OS << " [TF=" << TF << ']';
5716 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5718 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5720 OS << LBB->getName() << " ";
5721 OS << (const void*)BBDN->getBasicBlock() << ">";
5722 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5723 if (G && R->getReg() &&
5724 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5725 OS << " %" << G->getTarget().getRegisterInfo()->getName(R->getReg());
5727 OS << " %reg" << R->getReg();
5729 } else if (const ExternalSymbolSDNode *ES =
5730 dyn_cast<ExternalSymbolSDNode>(this)) {
5731 OS << "'" << ES->getSymbol() << "'";
5732 if (unsigned int TF = ES->getTargetFlags())
5733 OS << " [TF=" << TF << ']';
5734 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5736 OS << "<" << M->getValue() << ">";
5739 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5740 OS << ":" << N->getVT().getEVTString();
5742 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5743 OS << "<" << *LD->getMemOperand();
5746 switch (LD->getExtensionType()) {
5747 default: doExt = false; break;
5748 case ISD::EXTLOAD: OS << ", anyext"; break;
5749 case ISD::SEXTLOAD: OS << ", sext"; break;
5750 case ISD::ZEXTLOAD: OS << ", zext"; break;
5753 OS << " from " << LD->getMemoryVT().getEVTString();
5755 const char *AM = getIndexedModeName(LD->getAddressingMode());
5760 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5761 OS << "<" << *ST->getMemOperand();
5763 if (ST->isTruncatingStore())
5764 OS << ", trunc to " << ST->getMemoryVT().getEVTString();
5766 const char *AM = getIndexedModeName(ST->getAddressingMode());
5771 } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
5772 OS << "<" << *M->getMemOperand() << ">";
5773 } else if (const BlockAddressSDNode *BA =
5774 dyn_cast<BlockAddressSDNode>(this)) {
5776 WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
5778 WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
5780 if (unsigned int TF = BA->getTargetFlags())
5781 OS << " [TF=" << TF << ']';
5785 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5787 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5788 if (i) OS << ", "; else OS << " ";
5789 OS << (void*)getOperand(i).getNode();
5790 if (unsigned RN = getOperand(i).getResNo())
5793 print_details(OS, G);
5796 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5797 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5798 if (N->getOperand(i).getNode()->hasOneUse())
5799 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5801 errs() << "\n" << std::string(indent+2, ' ')
5802 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5806 errs().indent(indent);
5810 void SelectionDAG::dump() const {
5811 errs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
5813 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5815 const SDNode *N = I;
5816 if (!N->hasOneUse() && N != getRoot().getNode())
5817 DumpNodes(N, 2, this);
5820 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
5825 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
5827 print_details(OS, G);
5830 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
5831 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
5832 const SelectionDAG *G, VisitedSDNodeSet &once) {
5833 if (!once.insert(N)) // If we've been here before, return now.
5835 // Dump the current SDNode, but don't end the line yet.
5836 OS << std::string(indent, ' ');
5838 // Having printed this SDNode, walk the children:
5839 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5840 const SDNode *child = N->getOperand(i).getNode();
5843 if (child->getNumOperands() == 0) {
5844 // This child has no grandchildren; print it inline right here.
5845 child->printr(OS, G);
5847 } else { // Just the address. FIXME: also print the child's opcode
5849 if (unsigned RN = N->getOperand(i).getResNo())
5854 // Dump children that have grandchildren on their own line(s).
5855 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5856 const SDNode *child = N->getOperand(i).getNode();
5857 DumpNodesr(OS, child, indent+2, G, once);
5861 void SDNode::dumpr() const {
5862 VisitedSDNodeSet once;
5863 DumpNodesr(errs(), this, 0, 0, once);
5866 void SDNode::dumpr(const SelectionDAG *G) const {
5867 VisitedSDNodeSet once;
5868 DumpNodesr(errs(), this, 0, G, once);
5872 // getAddressSpace - Return the address space this GlobalAddress belongs to.
5873 unsigned GlobalAddressSDNode::getAddressSpace() const {
5874 return getGlobal()->getType()->getAddressSpace();
5878 const Type *ConstantPoolSDNode::getType() const {
5879 if (isMachineConstantPoolEntry())
5880 return Val.MachineCPVal->getType();
5881 return Val.ConstVal->getType();
5884 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
5886 unsigned &SplatBitSize,
5888 unsigned MinSplatBits,
5890 EVT VT = getValueType(0);
5891 assert(VT.isVector() && "Expected a vector type");
5892 unsigned sz = VT.getSizeInBits();
5893 if (MinSplatBits > sz)
5896 SplatValue = APInt(sz, 0);
5897 SplatUndef = APInt(sz, 0);
5899 // Get the bits. Bits with undefined values (when the corresponding element
5900 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
5901 // in SplatValue. If any of the values are not constant, give up and return
5903 unsigned int nOps = getNumOperands();
5904 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
5905 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
5907 for (unsigned j = 0; j < nOps; ++j) {
5908 unsigned i = isBigEndian ? nOps-1-j : j;
5909 SDValue OpVal = getOperand(i);
5910 unsigned BitPos = j * EltBitSize;
5912 if (OpVal.getOpcode() == ISD::UNDEF)
5913 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
5914 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
5915 SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
5916 zextOrTrunc(sz) << BitPos);
5917 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
5918 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
5923 // The build_vector is all constants or undefs. Find the smallest element
5924 // size that splats the vector.
5926 HasAnyUndefs = (SplatUndef != 0);
5929 unsigned HalfSize = sz / 2;
5930 APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
5931 APInt LowValue = APInt(SplatValue).trunc(HalfSize);
5932 APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
5933 APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
5935 // If the two halves do not match (ignoring undef bits), stop here.
5936 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
5937 MinSplatBits > HalfSize)
5940 SplatValue = HighValue | LowValue;
5941 SplatUndef = HighUndef & LowUndef;
5950 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
5951 // Find the first non-undef value in the shuffle mask.
5953 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
5956 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
5958 // Make sure all remaining elements are either undef or the same as the first
5960 for (int Idx = Mask[i]; i != e; ++i)
5961 if (Mask[i] >= 0 && Mask[i] != Idx)