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/TargetMachine.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/System/Mutex.h"
40 #include "llvm/ADT/SetVector.h"
41 #include "llvm/ADT/SmallPtrSet.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/StringExtras.h"
49 /// makeVTList - Return an instance of the SDVTList struct initialized with the
50 /// specified members.
51 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
52 SDVTList Res = {VTs, NumVTs};
56 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
57 switch (VT.getSimpleVT().SimpleTy) {
58 default: llvm_unreachable("Unknown FP format");
59 case MVT::f32: return &APFloat::IEEEsingle;
60 case MVT::f64: return &APFloat::IEEEdouble;
61 case MVT::f80: return &APFloat::x87DoubleExtended;
62 case MVT::f128: return &APFloat::IEEEquad;
63 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
67 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
69 //===----------------------------------------------------------------------===//
70 // ConstantFPSDNode Class
71 //===----------------------------------------------------------------------===//
73 /// isExactlyValue - We don't rely on operator== working on double values, as
74 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
75 /// As such, this method can be used to do an exact bit-for-bit comparison of
76 /// two floating point values.
77 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
78 return getValueAPF().bitwiseIsEqual(V);
81 bool ConstantFPSDNode::isValueValidForType(EVT VT,
83 assert(VT.isFloatingPoint() && "Can only convert between FP types");
85 // PPC long double cannot be converted to any other type.
86 if (VT == MVT::ppcf128 ||
87 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
90 // convert modifies in place, so make a copy.
91 APFloat Val2 = APFloat(Val);
93 (void) Val2.convert(*EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
98 //===----------------------------------------------------------------------===//
100 //===----------------------------------------------------------------------===//
102 /// isBuildVectorAllOnes - Return true if the specified node is a
103 /// BUILD_VECTOR where all of the elements are ~0 or undef.
104 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
105 // Look through a bit convert.
106 if (N->getOpcode() == ISD::BIT_CONVERT)
107 N = N->getOperand(0).getNode();
109 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
111 unsigned i = 0, e = N->getNumOperands();
113 // Skip over all of the undef values.
114 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
117 // Do not accept an all-undef vector.
118 if (i == e) return false;
120 // Do not accept build_vectors that aren't all constants or which have non-~0
122 SDValue NotZero = N->getOperand(i);
123 if (isa<ConstantSDNode>(NotZero)) {
124 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
126 } else if (isa<ConstantFPSDNode>(NotZero)) {
127 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
128 bitcastToAPInt().isAllOnesValue())
133 // Okay, we have at least one ~0 value, check to see if the rest match or are
135 for (++i; i != e; ++i)
136 if (N->getOperand(i) != NotZero &&
137 N->getOperand(i).getOpcode() != ISD::UNDEF)
143 /// isBuildVectorAllZeros - Return true if the specified node is a
144 /// BUILD_VECTOR where all of the elements are 0 or undef.
145 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
146 // Look through a bit convert.
147 if (N->getOpcode() == ISD::BIT_CONVERT)
148 N = N->getOperand(0).getNode();
150 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
152 unsigned i = 0, e = N->getNumOperands();
154 // Skip over all of the undef values.
155 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
158 // Do not accept an all-undef vector.
159 if (i == e) return false;
161 // Do not accept build_vectors that aren't all constants or which have non-0
163 SDValue Zero = N->getOperand(i);
164 if (isa<ConstantSDNode>(Zero)) {
165 if (!cast<ConstantSDNode>(Zero)->isNullValue())
167 } else if (isa<ConstantFPSDNode>(Zero)) {
168 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
173 // Okay, we have at least one 0 value, check to see if the rest match or are
175 for (++i; i != e; ++i)
176 if (N->getOperand(i) != Zero &&
177 N->getOperand(i).getOpcode() != ISD::UNDEF)
182 /// isScalarToVector - Return true if the specified node is a
183 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
184 /// element is not an undef.
185 bool ISD::isScalarToVector(const SDNode *N) {
186 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
189 if (N->getOpcode() != ISD::BUILD_VECTOR)
191 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
193 unsigned NumElems = N->getNumOperands();
194 for (unsigned i = 1; i < NumElems; ++i) {
195 SDValue V = N->getOperand(i);
196 if (V.getOpcode() != ISD::UNDEF)
203 /// isDebugLabel - Return true if the specified node represents a debug
204 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
205 bool ISD::isDebugLabel(const SDNode *N) {
207 if (N->getOpcode() == ISD::DBG_LABEL)
209 if (N->isMachineOpcode() &&
210 N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
215 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
216 /// when given the operation for (X op Y).
217 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
218 // To perform this operation, we just need to swap the L and G bits of the
220 unsigned OldL = (Operation >> 2) & 1;
221 unsigned OldG = (Operation >> 1) & 1;
222 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
223 (OldL << 1) | // New G bit
224 (OldG << 2)); // New L bit.
227 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
228 /// 'op' is a valid SetCC operation.
229 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
230 unsigned Operation = Op;
232 Operation ^= 7; // Flip L, G, E bits, but not U.
234 Operation ^= 15; // Flip all of the condition bits.
236 if (Operation > ISD::SETTRUE2)
237 Operation &= ~8; // Don't let N and U bits get set.
239 return ISD::CondCode(Operation);
243 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
244 /// signed operation and 2 if the result is an unsigned comparison. Return zero
245 /// if the operation does not depend on the sign of the input (setne and seteq).
246 static int isSignedOp(ISD::CondCode Opcode) {
248 default: llvm_unreachable("Illegal integer setcc operation!");
250 case ISD::SETNE: return 0;
254 case ISD::SETGE: return 1;
258 case ISD::SETUGE: return 2;
262 /// getSetCCOrOperation - Return the result of a logical OR between different
263 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
264 /// returns SETCC_INVALID if it is not possible to represent the resultant
266 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
268 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
269 // Cannot fold a signed integer setcc with an unsigned integer setcc.
270 return ISD::SETCC_INVALID;
272 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
274 // If the N and U bits get set then the resultant comparison DOES suddenly
275 // care about orderedness, and is true when ordered.
276 if (Op > ISD::SETTRUE2)
277 Op &= ~16; // Clear the U bit if the N bit is set.
279 // Canonicalize illegal integer setcc's.
280 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
283 return ISD::CondCode(Op);
286 /// getSetCCAndOperation - Return the result of a logical AND between different
287 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
288 /// function returns zero if it is not possible to represent the resultant
290 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
292 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
293 // Cannot fold a signed setcc with an unsigned setcc.
294 return ISD::SETCC_INVALID;
296 // Combine all of the condition bits.
297 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
299 // Canonicalize illegal integer setcc's.
303 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
304 case ISD::SETOEQ: // SETEQ & SETU[LG]E
305 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
306 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
307 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
314 const TargetMachine &SelectionDAG::getTarget() const {
315 return MF->getTarget();
318 //===----------------------------------------------------------------------===//
319 // SDNode Profile Support
320 //===----------------------------------------------------------------------===//
322 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
324 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
328 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
329 /// solely with their pointer.
330 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
331 ID.AddPointer(VTList.VTs);
334 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
336 static void AddNodeIDOperands(FoldingSetNodeID &ID,
337 const SDValue *Ops, unsigned NumOps) {
338 for (; NumOps; --NumOps, ++Ops) {
339 ID.AddPointer(Ops->getNode());
340 ID.AddInteger(Ops->getResNo());
344 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
346 static void AddNodeIDOperands(FoldingSetNodeID &ID,
347 const SDUse *Ops, unsigned NumOps) {
348 for (; NumOps; --NumOps, ++Ops) {
349 ID.AddPointer(Ops->getNode());
350 ID.AddInteger(Ops->getResNo());
354 static void AddNodeIDNode(FoldingSetNodeID &ID,
355 unsigned short OpC, SDVTList VTList,
356 const SDValue *OpList, unsigned N) {
357 AddNodeIDOpcode(ID, OpC);
358 AddNodeIDValueTypes(ID, VTList);
359 AddNodeIDOperands(ID, OpList, N);
362 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
364 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
365 switch (N->getOpcode()) {
366 case ISD::TargetExternalSymbol:
367 case ISD::ExternalSymbol:
368 llvm_unreachable("Should only be used on nodes with operands");
369 default: break; // Normal nodes don't need extra info.
370 case ISD::TargetConstant:
372 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
374 case ISD::TargetConstantFP:
375 case ISD::ConstantFP: {
376 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
379 case ISD::TargetGlobalAddress:
380 case ISD::GlobalAddress:
381 case ISD::TargetGlobalTLSAddress:
382 case ISD::GlobalTLSAddress: {
383 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
384 ID.AddPointer(GA->getGlobal());
385 ID.AddInteger(GA->getOffset());
386 ID.AddInteger(GA->getTargetFlags());
389 case ISD::BasicBlock:
390 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
393 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
395 case ISD::DBG_STOPPOINT: {
396 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
397 ID.AddInteger(DSP->getLine());
398 ID.AddInteger(DSP->getColumn());
399 ID.AddPointer(DSP->getCompileUnit());
403 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
405 case ISD::MEMOPERAND: {
406 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
410 case ISD::FrameIndex:
411 case ISD::TargetFrameIndex:
412 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
415 case ISD::TargetJumpTable:
416 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
417 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
419 case ISD::ConstantPool:
420 case ISD::TargetConstantPool: {
421 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
422 ID.AddInteger(CP->getAlignment());
423 ID.AddInteger(CP->getOffset());
424 if (CP->isMachineConstantPoolEntry())
425 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
427 ID.AddPointer(CP->getConstVal());
428 ID.AddInteger(CP->getTargetFlags());
432 const LoadSDNode *LD = cast<LoadSDNode>(N);
433 ID.AddInteger(LD->getMemoryVT().getRawBits());
434 ID.AddInteger(LD->getRawSubclassData());
435 ID.AddInteger(LD->getSrcValueOffset());
439 const StoreSDNode *ST = cast<StoreSDNode>(N);
440 ID.AddInteger(ST->getMemoryVT().getRawBits());
441 ID.AddInteger(ST->getRawSubclassData());
442 ID.AddInteger(ST->getSrcValueOffset());
445 case ISD::ATOMIC_CMP_SWAP:
446 case ISD::ATOMIC_SWAP:
447 case ISD::ATOMIC_LOAD_ADD:
448 case ISD::ATOMIC_LOAD_SUB:
449 case ISD::ATOMIC_LOAD_AND:
450 case ISD::ATOMIC_LOAD_OR:
451 case ISD::ATOMIC_LOAD_XOR:
452 case ISD::ATOMIC_LOAD_NAND:
453 case ISD::ATOMIC_LOAD_MIN:
454 case ISD::ATOMIC_LOAD_MAX:
455 case ISD::ATOMIC_LOAD_UMIN:
456 case ISD::ATOMIC_LOAD_UMAX: {
457 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
458 ID.AddInteger(AT->getMemoryVT().getRawBits());
459 ID.AddInteger(AT->getRawSubclassData());
462 case ISD::VECTOR_SHUFFLE: {
463 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
464 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
466 ID.AddInteger(SVN->getMaskElt(i));
469 } // end switch (N->getOpcode())
472 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
474 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
475 AddNodeIDOpcode(ID, N->getOpcode());
476 // Add the return value info.
477 AddNodeIDValueTypes(ID, N->getVTList());
478 // Add the operand info.
479 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
481 // Handle SDNode leafs with special info.
482 AddNodeIDCustom(ID, N);
485 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
486 /// the CSE map that carries alignment, volatility, indexing mode, and
487 /// extension/truncation information.
489 static inline unsigned
490 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM,
491 bool isVolatile, unsigned Alignment) {
492 assert((ConvType & 3) == ConvType &&
493 "ConvType may not require more than 2 bits!");
494 assert((AM & 7) == AM &&
495 "AM may not require more than 3 bits!");
499 ((Log2_32(Alignment) + 1) << 6);
502 //===----------------------------------------------------------------------===//
503 // SelectionDAG Class
504 //===----------------------------------------------------------------------===//
506 /// doNotCSE - Return true if CSE should not be performed for this node.
507 static bool doNotCSE(SDNode *N) {
508 if (N->getValueType(0) == MVT::Flag)
509 return true; // Never CSE anything that produces a flag.
511 switch (N->getOpcode()) {
513 case ISD::HANDLENODE:
515 case ISD::DBG_STOPPOINT:
517 return true; // Never CSE these nodes.
520 // Check that remaining values produced are not flags.
521 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
522 if (N->getValueType(i) == MVT::Flag)
523 return true; // Never CSE anything that produces a flag.
528 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
530 void SelectionDAG::RemoveDeadNodes() {
531 // Create a dummy node (which is not added to allnodes), that adds a reference
532 // to the root node, preventing it from being deleted.
533 HandleSDNode Dummy(getRoot());
535 SmallVector<SDNode*, 128> DeadNodes;
537 // Add all obviously-dead nodes to the DeadNodes worklist.
538 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
540 DeadNodes.push_back(I);
542 RemoveDeadNodes(DeadNodes);
544 // If the root changed (e.g. it was a dead load, update the root).
545 setRoot(Dummy.getValue());
548 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
549 /// given list, and any nodes that become unreachable as a result.
550 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
551 DAGUpdateListener *UpdateListener) {
553 // Process the worklist, deleting the nodes and adding their uses to the
555 while (!DeadNodes.empty()) {
556 SDNode *N = DeadNodes.pop_back_val();
559 UpdateListener->NodeDeleted(N, 0);
561 // Take the node out of the appropriate CSE map.
562 RemoveNodeFromCSEMaps(N);
564 // Next, brutally remove the operand list. This is safe to do, as there are
565 // no cycles in the graph.
566 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
568 SDNode *Operand = Use.getNode();
571 // Now that we removed this operand, see if there are no uses of it left.
572 if (Operand->use_empty())
573 DeadNodes.push_back(Operand);
580 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
581 SmallVector<SDNode*, 16> DeadNodes(1, N);
582 RemoveDeadNodes(DeadNodes, UpdateListener);
585 void SelectionDAG::DeleteNode(SDNode *N) {
586 // First take this out of the appropriate CSE map.
587 RemoveNodeFromCSEMaps(N);
589 // Finally, remove uses due to operands of this node, remove from the
590 // AllNodes list, and delete the node.
591 DeleteNodeNotInCSEMaps(N);
594 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
595 assert(N != AllNodes.begin() && "Cannot delete the entry node!");
596 assert(N->use_empty() && "Cannot delete a node that is not dead!");
598 // Drop all of the operands and decrement used node's use counts.
604 void SelectionDAG::DeallocateNode(SDNode *N) {
605 if (N->OperandsNeedDelete)
606 delete[] N->OperandList;
608 // Set the opcode to DELETED_NODE to help catch bugs when node
609 // memory is reallocated.
610 N->NodeType = ISD::DELETED_NODE;
612 NodeAllocator.Deallocate(AllNodes.remove(N));
615 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
616 /// correspond to it. This is useful when we're about to delete or repurpose
617 /// the node. We don't want future request for structurally identical nodes
618 /// to return N anymore.
619 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
621 switch (N->getOpcode()) {
622 case ISD::EntryToken:
623 llvm_unreachable("EntryToken should not be in CSEMaps!");
625 case ISD::HANDLENODE: return false; // noop.
627 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
628 "Cond code doesn't exist!");
629 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
630 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
632 case ISD::ExternalSymbol:
633 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
635 case ISD::TargetExternalSymbol: {
636 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
637 Erased = TargetExternalSymbols.erase(
638 std::pair<std::string,unsigned char>(ESN->getSymbol(),
639 ESN->getTargetFlags()));
642 case ISD::VALUETYPE: {
643 EVT VT = cast<VTSDNode>(N)->getVT();
644 if (VT.isExtended()) {
645 Erased = ExtendedValueTypeNodes.erase(VT);
647 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != 0;
648 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = 0;
653 // Remove it from the CSE Map.
654 Erased = CSEMap.RemoveNode(N);
658 // Verify that the node was actually in one of the CSE maps, unless it has a
659 // flag result (which cannot be CSE'd) or is one of the special cases that are
660 // not subject to CSE.
661 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
662 !N->isMachineOpcode() && !doNotCSE(N)) {
665 llvm_unreachable("Node is not in map!");
671 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
672 /// maps and modified in place. Add it back to the CSE maps, unless an identical
673 /// node already exists, in which case transfer all its users to the existing
674 /// node. This transfer can potentially trigger recursive merging.
677 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
678 DAGUpdateListener *UpdateListener) {
679 // For node types that aren't CSE'd, just act as if no identical node
682 SDNode *Existing = CSEMap.GetOrInsertNode(N);
684 // If there was already an existing matching node, use ReplaceAllUsesWith
685 // to replace the dead one with the existing one. This can cause
686 // recursive merging of other unrelated nodes down the line.
687 ReplaceAllUsesWith(N, Existing, UpdateListener);
689 // N is now dead. Inform the listener if it exists and delete it.
691 UpdateListener->NodeDeleted(N, Existing);
692 DeleteNodeNotInCSEMaps(N);
697 // If the node doesn't already exist, we updated it. Inform a listener if
700 UpdateListener->NodeUpdated(N);
703 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
704 /// were replaced with those specified. If this node is never memoized,
705 /// return null, otherwise return a pointer to the slot it would take. If a
706 /// node already exists with these operands, the slot will be non-null.
707 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
712 SDValue Ops[] = { Op };
714 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
715 AddNodeIDCustom(ID, N);
716 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
719 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
720 /// were replaced with those specified. If this node is never memoized,
721 /// return null, otherwise return a pointer to the slot it would take. If a
722 /// node already exists with these operands, the slot will be non-null.
723 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
724 SDValue Op1, SDValue Op2,
729 SDValue Ops[] = { Op1, Op2 };
731 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
732 AddNodeIDCustom(ID, N);
733 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
737 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
738 /// were replaced with those specified. If this node is never memoized,
739 /// return null, otherwise return a pointer to the slot it would take. If a
740 /// node already exists with these operands, the slot will be non-null.
741 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
742 const SDValue *Ops,unsigned NumOps,
748 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
749 AddNodeIDCustom(ID, N);
750 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
753 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
754 void SelectionDAG::VerifyNode(SDNode *N) {
755 switch (N->getOpcode()) {
758 case ISD::BUILD_PAIR: {
759 EVT VT = N->getValueType(0);
760 assert(N->getNumValues() == 1 && "Too many results!");
761 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
762 "Wrong return type!");
763 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
764 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
765 "Mismatched operand types!");
766 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
767 "Wrong operand type!");
768 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
769 "Wrong return type size");
772 case ISD::BUILD_VECTOR: {
773 assert(N->getNumValues() == 1 && "Too many results!");
774 assert(N->getValueType(0).isVector() && "Wrong return type!");
775 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
776 "Wrong number of operands!");
777 EVT EltVT = N->getValueType(0).getVectorElementType();
778 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
779 assert((I->getValueType() == EltVT ||
780 (EltVT.isInteger() && I->getValueType().isInteger() &&
781 EltVT.bitsLE(I->getValueType()))) &&
782 "Wrong operand type!");
788 /// getEVTAlignment - Compute the default alignment value for the
791 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
792 const Type *Ty = VT == MVT::iPTR ?
793 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
794 VT.getTypeForEVT(*getContext());
796 return TLI.getTargetData()->getABITypeAlignment(Ty);
799 // EntryNode could meaningfully have debug info if we can find it...
800 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
801 : TLI(tli), FLI(fli), DW(0),
802 EntryNode(ISD::EntryToken, DebugLoc::getUnknownLoc(),
803 getVTList(MVT::Other)), Root(getEntryNode()) {
804 AllNodes.push_back(&EntryNode);
807 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
812 Context = &mf.getFunction()->getContext();
815 SelectionDAG::~SelectionDAG() {
819 void SelectionDAG::allnodes_clear() {
820 assert(&*AllNodes.begin() == &EntryNode);
821 AllNodes.remove(AllNodes.begin());
822 while (!AllNodes.empty())
823 DeallocateNode(AllNodes.begin());
826 void SelectionDAG::clear() {
828 OperandAllocator.Reset();
831 ExtendedValueTypeNodes.clear();
832 ExternalSymbols.clear();
833 TargetExternalSymbols.clear();
834 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
835 static_cast<CondCodeSDNode*>(0));
836 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
837 static_cast<SDNode*>(0));
839 EntryNode.UseList = 0;
840 AllNodes.push_back(&EntryNode);
841 Root = getEntryNode();
844 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, EVT VT) {
845 if (Op.getValueType() == VT) return Op;
846 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
848 return getNode(ISD::AND, DL, Op.getValueType(), Op,
849 getConstant(Imm, Op.getValueType()));
852 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
854 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, EVT VT) {
855 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
857 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
858 return getNode(ISD::XOR, DL, VT, Val, NegOne);
861 SDValue SelectionDAG::getConstant(uint64_t Val, EVT VT, bool isT) {
862 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
863 assert((EltVT.getSizeInBits() >= 64 ||
864 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
865 "getConstant with a uint64_t value that doesn't fit in the type!");
866 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
869 SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
870 return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
873 SDValue SelectionDAG::getConstant(const ConstantInt &Val, EVT VT, bool isT) {
874 assert(VT.isInteger() && "Cannot create FP integer constant!");
876 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
877 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
878 "APInt size does not match type size!");
880 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
882 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
886 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
888 return SDValue(N, 0);
890 N = NodeAllocator.Allocate<ConstantSDNode>();
891 new (N) ConstantSDNode(isT, &Val, EltVT);
892 CSEMap.InsertNode(N, IP);
893 AllNodes.push_back(N);
896 SDValue Result(N, 0);
898 SmallVector<SDValue, 8> Ops;
899 Ops.assign(VT.getVectorNumElements(), Result);
900 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
901 VT, &Ops[0], Ops.size());
906 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
907 return getConstant(Val, TLI.getPointerTy(), isTarget);
911 SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
912 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
915 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, EVT VT, bool isTarget){
916 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
919 VT.isVector() ? VT.getVectorElementType() : VT;
921 // Do the map lookup using the actual bit pattern for the floating point
922 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
923 // we don't have issues with SNANs.
924 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
926 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
930 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
932 return SDValue(N, 0);
934 N = NodeAllocator.Allocate<ConstantFPSDNode>();
935 new (N) ConstantFPSDNode(isTarget, &V, EltVT);
936 CSEMap.InsertNode(N, IP);
937 AllNodes.push_back(N);
940 SDValue Result(N, 0);
942 SmallVector<SDValue, 8> Ops;
943 Ops.assign(VT.getVectorNumElements(), Result);
944 // FIXME DebugLoc info might be appropriate here
945 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
946 VT, &Ops[0], Ops.size());
951 SDValue SelectionDAG::getConstantFP(double Val, EVT VT, bool isTarget) {
953 VT.isVector() ? VT.getVectorElementType() : VT;
955 return getConstantFP(APFloat((float)Val), VT, isTarget);
957 return getConstantFP(APFloat(Val), VT, isTarget);
960 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
961 EVT VT, int64_t Offset,
963 unsigned char TargetFlags) {
964 assert((TargetFlags == 0 || isTargetGA) &&
965 "Cannot set target flags on target-independent globals");
967 // Truncate (with sign-extension) the offset value to the pointer size.
968 EVT PTy = TLI.getPointerTy();
969 unsigned BitWidth = PTy.getSizeInBits();
971 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
973 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
975 // If GV is an alias then use the aliasee for determining thread-localness.
976 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
977 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
981 if (GVar && GVar->isThreadLocal())
982 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
984 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
987 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
989 ID.AddInteger(Offset);
990 ID.AddInteger(TargetFlags);
992 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
993 return SDValue(E, 0);
994 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
995 new (N) GlobalAddressSDNode(Opc, GV, VT, Offset, TargetFlags);
996 CSEMap.InsertNode(N, IP);
997 AllNodes.push_back(N);
998 return SDValue(N, 0);
1001 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1002 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1003 FoldingSetNodeID ID;
1004 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1007 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1008 return SDValue(E, 0);
1009 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
1010 new (N) FrameIndexSDNode(FI, VT, isTarget);
1011 CSEMap.InsertNode(N, IP);
1012 AllNodes.push_back(N);
1013 return SDValue(N, 0);
1016 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1017 unsigned char TargetFlags) {
1018 assert((TargetFlags == 0 || isTarget) &&
1019 "Cannot set target flags on target-independent jump tables");
1020 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1021 FoldingSetNodeID ID;
1022 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1024 ID.AddInteger(TargetFlags);
1026 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1027 return SDValue(E, 0);
1028 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
1029 new (N) JumpTableSDNode(JTI, VT, isTarget, TargetFlags);
1030 CSEMap.InsertNode(N, IP);
1031 AllNodes.push_back(N);
1032 return SDValue(N, 0);
1035 SDValue SelectionDAG::getConstantPool(Constant *C, EVT VT,
1036 unsigned Alignment, int Offset,
1038 unsigned char TargetFlags) {
1039 assert((TargetFlags == 0 || isTarget) &&
1040 "Cannot set target flags on target-independent globals");
1042 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1043 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1044 FoldingSetNodeID ID;
1045 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1046 ID.AddInteger(Alignment);
1047 ID.AddInteger(Offset);
1049 ID.AddInteger(TargetFlags);
1051 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1052 return SDValue(E, 0);
1053 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1054 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1055 CSEMap.InsertNode(N, IP);
1056 AllNodes.push_back(N);
1057 return SDValue(N, 0);
1061 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1062 unsigned Alignment, int Offset,
1064 unsigned char TargetFlags) {
1065 assert((TargetFlags == 0 || isTarget) &&
1066 "Cannot set target flags on target-independent globals");
1068 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
1069 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1070 FoldingSetNodeID ID;
1071 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
1072 ID.AddInteger(Alignment);
1073 ID.AddInteger(Offset);
1074 C->AddSelectionDAGCSEId(ID);
1075 ID.AddInteger(TargetFlags);
1077 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1078 return SDValue(E, 0);
1079 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
1080 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
1081 CSEMap.InsertNode(N, IP);
1082 AllNodes.push_back(N);
1083 return SDValue(N, 0);
1086 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1087 FoldingSetNodeID ID;
1088 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
1091 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1092 return SDValue(E, 0);
1093 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
1094 new (N) BasicBlockSDNode(MBB);
1095 CSEMap.InsertNode(N, IP);
1096 AllNodes.push_back(N);
1097 return SDValue(N, 0);
1100 SDValue SelectionDAG::getValueType(EVT VT) {
1101 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1102 ValueTypeNodes.size())
1103 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1105 SDNode *&N = VT.isExtended() ?
1106 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1108 if (N) return SDValue(N, 0);
1109 N = NodeAllocator.Allocate<VTSDNode>();
1110 new (N) VTSDNode(VT);
1111 AllNodes.push_back(N);
1112 return SDValue(N, 0);
1115 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1116 SDNode *&N = ExternalSymbols[Sym];
1117 if (N) return SDValue(N, 0);
1118 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1119 new (N) ExternalSymbolSDNode(false, Sym, 0, VT);
1120 AllNodes.push_back(N);
1121 return SDValue(N, 0);
1124 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1125 unsigned char TargetFlags) {
1127 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1129 if (N) return SDValue(N, 0);
1130 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1131 new (N) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
1132 AllNodes.push_back(N);
1133 return SDValue(N, 0);
1136 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1137 if ((unsigned)Cond >= CondCodeNodes.size())
1138 CondCodeNodes.resize(Cond+1);
1140 if (CondCodeNodes[Cond] == 0) {
1141 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1142 new (N) CondCodeSDNode(Cond);
1143 CondCodeNodes[Cond] = N;
1144 AllNodes.push_back(N);
1146 return SDValue(CondCodeNodes[Cond], 0);
1149 // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
1150 // the shuffle mask M that point at N1 to point at N2, and indices that point
1151 // N2 to point at N1.
1152 static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
1154 int NElts = M.size();
1155 for (int i = 0; i != NElts; ++i) {
1163 SDValue SelectionDAG::getVectorShuffle(EVT VT, DebugLoc dl, SDValue N1,
1164 SDValue N2, const int *Mask) {
1165 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
1166 assert(VT.isVector() && N1.getValueType().isVector() &&
1167 "Vector Shuffle VTs must be a vectors");
1168 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
1169 && "Vector Shuffle VTs must have same element type");
1171 // Canonicalize shuffle undef, undef -> undef
1172 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
1173 return getUNDEF(VT);
1175 // Validate that all indices in Mask are within the range of the elements
1176 // input to the shuffle.
1177 unsigned NElts = VT.getVectorNumElements();
1178 SmallVector<int, 8> MaskVec;
1179 for (unsigned i = 0; i != NElts; ++i) {
1180 assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
1181 MaskVec.push_back(Mask[i]);
1184 // Canonicalize shuffle v, v -> v, undef
1187 for (unsigned i = 0; i != NElts; ++i)
1188 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
1191 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1192 if (N1.getOpcode() == ISD::UNDEF)
1193 commuteShuffle(N1, N2, MaskVec);
1195 // Canonicalize all index into lhs, -> shuffle lhs, undef
1196 // Canonicalize all index into rhs, -> shuffle rhs, undef
1197 bool AllLHS = true, AllRHS = true;
1198 bool N2Undef = N2.getOpcode() == ISD::UNDEF;
1199 for (unsigned i = 0; i != NElts; ++i) {
1200 if (MaskVec[i] >= (int)NElts) {
1205 } else if (MaskVec[i] >= 0) {
1209 if (AllLHS && AllRHS)
1210 return getUNDEF(VT);
1211 if (AllLHS && !N2Undef)
1215 commuteShuffle(N1, N2, MaskVec);
1218 // If Identity shuffle, or all shuffle in to undef, return that node.
1219 bool AllUndef = true;
1220 bool Identity = true;
1221 for (unsigned i = 0; i != NElts; ++i) {
1222 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
1223 if (MaskVec[i] >= 0) AllUndef = false;
1225 if (Identity && NElts == N1.getValueType().getVectorNumElements())
1228 return getUNDEF(VT);
1230 FoldingSetNodeID ID;
1231 SDValue Ops[2] = { N1, N2 };
1232 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
1233 for (unsigned i = 0; i != NElts; ++i)
1234 ID.AddInteger(MaskVec[i]);
1237 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1238 return SDValue(E, 0);
1240 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1241 // SDNode doesn't have access to it. This memory will be "leaked" when
1242 // the node is deallocated, but recovered when the NodeAllocator is released.
1243 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1244 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
1246 ShuffleVectorSDNode *N = NodeAllocator.Allocate<ShuffleVectorSDNode>();
1247 new (N) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
1248 CSEMap.InsertNode(N, IP);
1249 AllNodes.push_back(N);
1250 return SDValue(N, 0);
1253 SDValue SelectionDAG::getConvertRndSat(EVT VT, DebugLoc dl,
1254 SDValue Val, SDValue DTy,
1255 SDValue STy, SDValue Rnd, SDValue Sat,
1256 ISD::CvtCode Code) {
1257 // If the src and dest types are the same and the conversion is between
1258 // integer types of the same sign or two floats, no conversion is necessary.
1260 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
1263 FoldingSetNodeID ID;
1265 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1266 return SDValue(E, 0);
1267 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
1268 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
1269 new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code);
1270 CSEMap.InsertNode(N, IP);
1271 AllNodes.push_back(N);
1272 return SDValue(N, 0);
1275 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1276 FoldingSetNodeID ID;
1277 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1278 ID.AddInteger(RegNo);
1280 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1281 return SDValue(E, 0);
1282 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1283 new (N) RegisterSDNode(RegNo, VT);
1284 CSEMap.InsertNode(N, IP);
1285 AllNodes.push_back(N);
1286 return SDValue(N, 0);
1289 SDValue SelectionDAG::getDbgStopPoint(DebugLoc DL, SDValue Root,
1290 unsigned Line, unsigned Col,
1292 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1293 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1295 AllNodes.push_back(N);
1296 return SDValue(N, 0);
1299 SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
1302 FoldingSetNodeID ID;
1303 SDValue Ops[] = { Root };
1304 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1305 ID.AddInteger(LabelID);
1307 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1308 return SDValue(E, 0);
1309 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1310 new (N) LabelSDNode(Opcode, dl, Root, LabelID);
1311 CSEMap.InsertNode(N, IP);
1312 AllNodes.push_back(N);
1313 return SDValue(N, 0);
1316 SDValue SelectionDAG::getSrcValue(const Value *V) {
1317 assert((!V || isa<PointerType>(V->getType())) &&
1318 "SrcValue is not a pointer?");
1320 FoldingSetNodeID ID;
1321 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1325 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1326 return SDValue(E, 0);
1328 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1329 new (N) SrcValueSDNode(V);
1330 CSEMap.InsertNode(N, IP);
1331 AllNodes.push_back(N);
1332 return SDValue(N, 0);
1335 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1337 const Value *v = MO.getValue();
1338 assert((!v || isa<PointerType>(v->getType())) &&
1339 "SrcValue is not a pointer?");
1342 FoldingSetNodeID ID;
1343 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1347 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1348 return SDValue(E, 0);
1350 SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
1351 new (N) MemOperandSDNode(MO);
1352 CSEMap.InsertNode(N, IP);
1353 AllNodes.push_back(N);
1354 return SDValue(N, 0);
1357 /// getShiftAmountOperand - Return the specified value casted to
1358 /// the target's desired shift amount type.
1359 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
1360 EVT OpTy = Op.getValueType();
1361 MVT ShTy = TLI.getShiftAmountTy();
1362 if (OpTy == ShTy || OpTy.isVector()) return Op;
1364 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1365 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
1368 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1369 /// specified value type.
1370 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1371 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1372 unsigned ByteSize = VT.getStoreSizeInBits()/8;
1373 const Type *Ty = VT.getTypeForEVT(*getContext());
1374 unsigned StackAlign =
1375 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1377 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1378 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1381 /// CreateStackTemporary - Create a stack temporary suitable for holding
1382 /// either of the specified value types.
1383 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1384 unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
1385 VT2.getStoreSizeInBits())/8;
1386 const Type *Ty1 = VT1.getTypeForEVT(*getContext());
1387 const Type *Ty2 = VT2.getTypeForEVT(*getContext());
1388 const TargetData *TD = TLI.getTargetData();
1389 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
1390 TD->getPrefTypeAlignment(Ty2));
1392 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1393 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align);
1394 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1397 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1,
1398 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
1399 // These setcc operations always fold.
1403 case ISD::SETFALSE2: return getConstant(0, VT);
1405 case ISD::SETTRUE2: return getConstant(1, VT);
1417 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1421 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
1422 const APInt &C2 = N2C->getAPIntValue();
1423 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1424 const APInt &C1 = N1C->getAPIntValue();
1427 default: llvm_unreachable("Unknown integer setcc!");
1428 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1429 case ISD::SETNE: return getConstant(C1 != C2, VT);
1430 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1431 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1432 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1433 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1434 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1435 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1436 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1437 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1441 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1442 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
1443 // No compile time operations on this type yet.
1444 if (N1C->getValueType(0) == MVT::ppcf128)
1447 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1450 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1451 return getUNDEF(VT);
1453 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1454 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1455 return getUNDEF(VT);
1457 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1458 R==APFloat::cmpLessThan, VT);
1459 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1460 return getUNDEF(VT);
1462 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1463 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1464 return getUNDEF(VT);
1466 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1467 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1468 return getUNDEF(VT);
1470 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1471 R==APFloat::cmpEqual, VT);
1472 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1473 return getUNDEF(VT);
1475 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1476 R==APFloat::cmpEqual, VT);
1477 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1478 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1479 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1480 R==APFloat::cmpEqual, VT);
1481 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1482 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1483 R==APFloat::cmpLessThan, VT);
1484 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1485 R==APFloat::cmpUnordered, VT);
1486 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1487 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1490 // Ensure that the constant occurs on the RHS.
1491 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1495 // Could not fold it.
1499 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1500 /// use this predicate to simplify operations downstream.
1501 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1502 // This predicate is not safe for vector operations.
1503 if (Op.getValueType().isVector())
1506 unsigned BitWidth = Op.getValueSizeInBits();
1507 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1510 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1511 /// this predicate to simplify operations downstream. Mask is known to be zero
1512 /// for bits that V cannot have.
1513 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1514 unsigned Depth) const {
1515 APInt KnownZero, KnownOne;
1516 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1517 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1518 return (KnownZero & Mask) == Mask;
1521 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1522 /// known to be either zero or one and return them in the KnownZero/KnownOne
1523 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1525 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1526 APInt &KnownZero, APInt &KnownOne,
1527 unsigned Depth) const {
1528 unsigned BitWidth = Mask.getBitWidth();
1529 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1530 "Mask size mismatches value type size!");
1532 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1533 if (Depth == 6 || Mask == 0)
1534 return; // Limit search depth.
1536 APInt KnownZero2, KnownOne2;
1538 switch (Op.getOpcode()) {
1540 // We know all of the bits for a constant!
1541 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1542 KnownZero = ~KnownOne & Mask;
1545 // If either the LHS or the RHS are Zero, the result is zero.
1546 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1547 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1548 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-1 bits are only known if set in both the LHS & RHS.
1553 KnownOne &= KnownOne2;
1554 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1555 KnownZero |= KnownZero2;
1558 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1559 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1560 KnownZero2, KnownOne2, Depth+1);
1561 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1562 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1564 // Output known-0 bits are only known if clear in both the LHS & RHS.
1565 KnownZero &= KnownZero2;
1566 // Output known-1 are known to be set if set in either the LHS | RHS.
1567 KnownOne |= KnownOne2;
1570 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1571 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1572 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1573 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1575 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1576 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1577 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1578 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1579 KnownZero = KnownZeroOut;
1583 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1584 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1585 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1586 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1587 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1589 // If low bits are zero in either operand, output low known-0 bits.
1590 // Also compute a conserative estimate for high known-0 bits.
1591 // More trickiness is possible, but this is sufficient for the
1592 // interesting case of alignment computation.
1594 unsigned TrailZ = KnownZero.countTrailingOnes() +
1595 KnownZero2.countTrailingOnes();
1596 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1597 KnownZero2.countLeadingOnes(),
1598 BitWidth) - BitWidth;
1600 TrailZ = std::min(TrailZ, BitWidth);
1601 LeadZ = std::min(LeadZ, BitWidth);
1602 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1603 APInt::getHighBitsSet(BitWidth, LeadZ);
1608 // For the purposes of computing leading zeros we can conservatively
1609 // treat a udiv as a logical right shift by the power of 2 known to
1610 // be less than the denominator.
1611 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1612 ComputeMaskedBits(Op.getOperand(0),
1613 AllOnes, KnownZero2, KnownOne2, Depth+1);
1614 unsigned LeadZ = KnownZero2.countLeadingOnes();
1618 ComputeMaskedBits(Op.getOperand(1),
1619 AllOnes, KnownZero2, KnownOne2, Depth+1);
1620 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1621 if (RHSUnknownLeadingOnes != BitWidth)
1622 LeadZ = std::min(BitWidth,
1623 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1625 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1629 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1630 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1631 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1632 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1634 // Only known if known in both the LHS and RHS.
1635 KnownOne &= KnownOne2;
1636 KnownZero &= KnownZero2;
1638 case ISD::SELECT_CC:
1639 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1640 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1641 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1642 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1644 // Only known if known in both the LHS and RHS.
1645 KnownOne &= KnownOne2;
1646 KnownZero &= KnownZero2;
1654 if (Op.getResNo() != 1)
1656 // The boolean result conforms to getBooleanContents. Fall through.
1658 // If we know the result of a setcc has the top bits zero, use this info.
1659 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
1661 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1664 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1665 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1666 unsigned ShAmt = SA->getZExtValue();
1668 // If the shift count is an invalid immediate, don't do anything.
1669 if (ShAmt >= BitWidth)
1672 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1673 KnownZero, KnownOne, Depth+1);
1674 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1675 KnownZero <<= ShAmt;
1677 // low bits known zero.
1678 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1682 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1683 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1684 unsigned ShAmt = SA->getZExtValue();
1686 // If the shift count is an invalid immediate, don't do anything.
1687 if (ShAmt >= BitWidth)
1690 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1691 KnownZero, KnownOne, Depth+1);
1692 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1693 KnownZero = KnownZero.lshr(ShAmt);
1694 KnownOne = KnownOne.lshr(ShAmt);
1696 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1697 KnownZero |= HighBits; // High bits known zero.
1701 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1702 unsigned ShAmt = SA->getZExtValue();
1704 // If the shift count is an invalid immediate, don't do anything.
1705 if (ShAmt >= BitWidth)
1708 APInt InDemandedMask = (Mask << ShAmt);
1709 // If any of the demanded bits are produced by the sign extension, we also
1710 // demand the input sign bit.
1711 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1712 if (HighBits.getBoolValue())
1713 InDemandedMask |= APInt::getSignBit(BitWidth);
1715 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1717 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1718 KnownZero = KnownZero.lshr(ShAmt);
1719 KnownOne = KnownOne.lshr(ShAmt);
1721 // Handle the sign bits.
1722 APInt SignBit = APInt::getSignBit(BitWidth);
1723 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1725 if (KnownZero.intersects(SignBit)) {
1726 KnownZero |= HighBits; // New bits are known zero.
1727 } else if (KnownOne.intersects(SignBit)) {
1728 KnownOne |= HighBits; // New bits are known one.
1732 case ISD::SIGN_EXTEND_INREG: {
1733 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1734 unsigned EBits = EVT.getSizeInBits();
1736 // Sign extension. Compute the demanded bits in the result that are not
1737 // present in the input.
1738 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1740 APInt InSignBit = APInt::getSignBit(EBits);
1741 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1743 // If the sign extended bits are demanded, we know that the sign
1745 InSignBit.zext(BitWidth);
1746 if (NewBits.getBoolValue())
1747 InputDemandedBits |= InSignBit;
1749 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1750 KnownZero, KnownOne, Depth+1);
1751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1753 // If the sign bit of the input is known set or clear, then we know the
1754 // top bits of the result.
1755 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1756 KnownZero |= NewBits;
1757 KnownOne &= ~NewBits;
1758 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1759 KnownOne |= NewBits;
1760 KnownZero &= ~NewBits;
1761 } else { // Input sign bit unknown
1762 KnownZero &= ~NewBits;
1763 KnownOne &= ~NewBits;
1770 unsigned LowBits = Log2_32(BitWidth)+1;
1771 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1776 if (ISD::isZEXTLoad(Op.getNode())) {
1777 LoadSDNode *LD = cast<LoadSDNode>(Op);
1778 EVT VT = LD->getMemoryVT();
1779 unsigned MemBits = VT.getSizeInBits();
1780 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1784 case ISD::ZERO_EXTEND: {
1785 EVT InVT = Op.getOperand(0).getValueType();
1786 unsigned InBits = InVT.getSizeInBits();
1787 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1788 APInt InMask = Mask;
1789 InMask.trunc(InBits);
1790 KnownZero.trunc(InBits);
1791 KnownOne.trunc(InBits);
1792 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1793 KnownZero.zext(BitWidth);
1794 KnownOne.zext(BitWidth);
1795 KnownZero |= NewBits;
1798 case ISD::SIGN_EXTEND: {
1799 EVT InVT = Op.getOperand(0).getValueType();
1800 unsigned InBits = InVT.getSizeInBits();
1801 APInt InSignBit = APInt::getSignBit(InBits);
1802 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1803 APInt InMask = Mask;
1804 InMask.trunc(InBits);
1806 // If any of the sign extended bits are demanded, we know that the sign
1807 // bit is demanded. Temporarily set this bit in the mask for our callee.
1808 if (NewBits.getBoolValue())
1809 InMask |= InSignBit;
1811 KnownZero.trunc(InBits);
1812 KnownOne.trunc(InBits);
1813 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1815 // Note if the sign bit is known to be zero or one.
1816 bool SignBitKnownZero = KnownZero.isNegative();
1817 bool SignBitKnownOne = KnownOne.isNegative();
1818 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1819 "Sign bit can't be known to be both zero and one!");
1821 // If the sign bit wasn't actually demanded by our caller, we don't
1822 // want it set in the KnownZero and KnownOne result values. Reset the
1823 // mask and reapply it to the result values.
1825 InMask.trunc(InBits);
1826 KnownZero &= InMask;
1829 KnownZero.zext(BitWidth);
1830 KnownOne.zext(BitWidth);
1832 // If the sign bit is known zero or one, the top bits match.
1833 if (SignBitKnownZero)
1834 KnownZero |= NewBits;
1835 else if (SignBitKnownOne)
1836 KnownOne |= NewBits;
1839 case ISD::ANY_EXTEND: {
1840 EVT InVT = Op.getOperand(0).getValueType();
1841 unsigned InBits = InVT.getSizeInBits();
1842 APInt InMask = Mask;
1843 InMask.trunc(InBits);
1844 KnownZero.trunc(InBits);
1845 KnownOne.trunc(InBits);
1846 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1847 KnownZero.zext(BitWidth);
1848 KnownOne.zext(BitWidth);
1851 case ISD::TRUNCATE: {
1852 EVT InVT = Op.getOperand(0).getValueType();
1853 unsigned InBits = InVT.getSizeInBits();
1854 APInt InMask = Mask;
1855 InMask.zext(InBits);
1856 KnownZero.zext(InBits);
1857 KnownOne.zext(InBits);
1858 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1859 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1860 KnownZero.trunc(BitWidth);
1861 KnownOne.trunc(BitWidth);
1864 case ISD::AssertZext: {
1865 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1866 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1867 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1869 KnownZero |= (~InMask) & Mask;
1873 // All bits are zero except the low bit.
1874 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1878 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1879 // We know that the top bits of C-X are clear if X contains less bits
1880 // than C (i.e. no wrap-around can happen). For example, 20-X is
1881 // positive if we can prove that X is >= 0 and < 16.
1882 if (CLHS->getAPIntValue().isNonNegative()) {
1883 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1884 // NLZ can't be BitWidth with no sign bit
1885 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1886 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1889 // If all of the MaskV bits are known to be zero, then we know the
1890 // output top bits are zero, because we now know that the output is
1892 if ((KnownZero2 & MaskV) == MaskV) {
1893 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1894 // Top bits known zero.
1895 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1902 // Output known-0 bits are known if clear or set in both the low clear bits
1903 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1904 // low 3 bits clear.
1905 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1906 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1907 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1908 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1910 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1911 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1912 KnownZeroOut = std::min(KnownZeroOut,
1913 KnownZero2.countTrailingOnes());
1915 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1919 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1920 const APInt &RA = Rem->getAPIntValue();
1921 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1922 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1923 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1924 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1926 // If the sign bit of the first operand is zero, the sign bit of
1927 // the result is zero. If the first operand has no one bits below
1928 // the second operand's single 1 bit, its sign will be zero.
1929 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1930 KnownZero2 |= ~LowBits;
1932 KnownZero |= KnownZero2 & Mask;
1934 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1939 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1940 const APInt &RA = Rem->getAPIntValue();
1941 if (RA.isPowerOf2()) {
1942 APInt LowBits = (RA - 1);
1943 APInt Mask2 = LowBits & Mask;
1944 KnownZero |= ~LowBits & Mask;
1945 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1946 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1951 // Since the result is less than or equal to either operand, any leading
1952 // zero bits in either operand must also exist in the result.
1953 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1954 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1956 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1959 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1960 KnownZero2.countLeadingOnes());
1962 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1966 // Allow the target to implement this method for its nodes.
1967 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1968 case ISD::INTRINSIC_WO_CHAIN:
1969 case ISD::INTRINSIC_W_CHAIN:
1970 case ISD::INTRINSIC_VOID:
1971 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
1978 /// ComputeNumSignBits - Return the number of times the sign bit of the
1979 /// register is replicated into the other bits. We know that at least 1 bit
1980 /// is always equal to the sign bit (itself), but other cases can give us
1981 /// information. For example, immediately after an "SRA X, 2", we know that
1982 /// the top 3 bits are all equal to each other, so we return 3.
1983 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1984 EVT VT = Op.getValueType();
1985 assert(VT.isInteger() && "Invalid VT!");
1986 unsigned VTBits = VT.getSizeInBits();
1988 unsigned FirstAnswer = 1;
1991 return 1; // Limit search depth.
1993 switch (Op.getOpcode()) {
1995 case ISD::AssertSext:
1996 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1997 return VTBits-Tmp+1;
1998 case ISD::AssertZext:
1999 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2002 case ISD::Constant: {
2003 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2004 // If negative, return # leading ones.
2005 if (Val.isNegative())
2006 return Val.countLeadingOnes();
2008 // Return # leading zeros.
2009 return Val.countLeadingZeros();
2012 case ISD::SIGN_EXTEND:
2013 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
2014 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2016 case ISD::SIGN_EXTEND_INREG:
2017 // Max of the input and what this extends.
2018 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2021 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2022 return std::max(Tmp, Tmp2);
2025 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2026 // SRA X, C -> adds C sign bits.
2027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2028 Tmp += C->getZExtValue();
2029 if (Tmp > VTBits) Tmp = VTBits;
2033 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2034 // shl destroys sign bits.
2035 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2036 if (C->getZExtValue() >= VTBits || // Bad shift.
2037 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2038 return Tmp - C->getZExtValue();
2043 case ISD::XOR: // NOT is handled here.
2044 // Logical binary ops preserve the number of sign bits at the worst.
2045 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2047 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2048 FirstAnswer = std::min(Tmp, Tmp2);
2049 // We computed what we know about the sign bits as our first
2050 // answer. Now proceed to the generic code that uses
2051 // ComputeMaskedBits, and pick whichever answer is better.
2056 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2057 if (Tmp == 1) return 1; // Early out.
2058 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2059 return std::min(Tmp, Tmp2);
2067 if (Op.getResNo() != 1)
2069 // The boolean result conforms to getBooleanContents. Fall through.
2071 // If setcc returns 0/-1, all bits are sign bits.
2072 if (TLI.getBooleanContents() ==
2073 TargetLowering::ZeroOrNegativeOneBooleanContent)
2078 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2079 unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2081 // Handle rotate right by N like a rotate left by 32-N.
2082 if (Op.getOpcode() == ISD::ROTR)
2083 RotAmt = (VTBits-RotAmt) & (VTBits-1);
2085 // If we aren't rotating out all of the known-in sign bits, return the
2086 // number that are left. This handles rotl(sext(x), 1) for example.
2087 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2088 if (Tmp > RotAmt+1) return Tmp-RotAmt;
2092 // Add can have at most one carry bit. Thus we know that the output
2093 // is, at worst, one more bit than the inputs.
2094 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2095 if (Tmp == 1) return 1; // Early out.
2097 // Special case decrementing a value (ADD X, -1):
2098 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2099 if (CRHS->isAllOnesValue()) {
2100 APInt KnownZero, KnownOne;
2101 APInt Mask = APInt::getAllOnesValue(VTBits);
2102 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2104 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2106 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2109 // If we are subtracting one from a positive number, there is no carry
2110 // out of the result.
2111 if (KnownZero.isNegative())
2115 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2116 if (Tmp2 == 1) return 1;
2117 return std::min(Tmp, Tmp2)-1;
2121 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2122 if (Tmp2 == 1) return 1;
2125 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2126 if (CLHS->isNullValue()) {
2127 APInt KnownZero, KnownOne;
2128 APInt Mask = APInt::getAllOnesValue(VTBits);
2129 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2130 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2132 if ((KnownZero | APInt(VTBits, 1)) == Mask)
2135 // If the input is known to be positive (the sign bit is known clear),
2136 // the output of the NEG has the same number of sign bits as the input.
2137 if (KnownZero.isNegative())
2140 // Otherwise, we treat this like a SUB.
2143 // Sub can have at most one carry bit. Thus we know that the output
2144 // is, at worst, one more bit than the inputs.
2145 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2146 if (Tmp == 1) return 1; // Early out.
2147 return std::min(Tmp, Tmp2)-1;
2150 // FIXME: it's tricky to do anything useful for this, but it is an important
2151 // case for targets like X86.
2155 // Handle LOADX separately here. EXTLOAD case will fallthrough.
2156 if (Op.getOpcode() == ISD::LOAD) {
2157 LoadSDNode *LD = cast<LoadSDNode>(Op);
2158 unsigned ExtType = LD->getExtensionType();
2161 case ISD::SEXTLOAD: // '17' bits known
2162 Tmp = LD->getMemoryVT().getSizeInBits();
2163 return VTBits-Tmp+1;
2164 case ISD::ZEXTLOAD: // '16' bits known
2165 Tmp = LD->getMemoryVT().getSizeInBits();
2170 // Allow the target to implement this method for its nodes.
2171 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2172 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2173 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2174 Op.getOpcode() == ISD::INTRINSIC_VOID) {
2175 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2176 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2179 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2180 // use this information.
2181 APInt KnownZero, KnownOne;
2182 APInt Mask = APInt::getAllOnesValue(VTBits);
2183 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2185 if (KnownZero.isNegative()) { // sign bit is 0
2187 } else if (KnownOne.isNegative()) { // sign bit is 1;
2194 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2195 // the number of identical bits in the top of the input value.
2197 Mask <<= Mask.getBitWidth()-VTBits;
2198 // Return # leading zeros. We use 'min' here in case Val was zero before
2199 // shifting. We don't want to return '64' as for an i32 "0".
2200 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2203 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2204 // If we're told that NaNs won't happen, assume they won't.
2205 if (FiniteOnlyFPMath())
2208 // If the value is a constant, we can obviously see if it is a NaN or not.
2209 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2210 return !C->getValueAPF().isNaN();
2212 // TODO: Recognize more cases here.
2217 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2218 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2219 if (!GA) return false;
2220 if (GA->getOffset() != 0) return false;
2221 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2222 if (!GV) return false;
2223 MachineModuleInfo *MMI = getMachineModuleInfo();
2224 return MMI && MMI->hasDebugInfo();
2228 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
2229 /// element of the result of the vector shuffle.
2230 SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N,
2232 EVT VT = N->getValueType(0);
2233 DebugLoc dl = N->getDebugLoc();
2234 if (N->getMaskElt(i) < 0)
2235 return getUNDEF(VT.getVectorElementType());
2236 unsigned Index = N->getMaskElt(i);
2237 unsigned NumElems = VT.getVectorNumElements();
2238 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
2241 if (V.getOpcode() == ISD::BIT_CONVERT) {
2242 V = V.getOperand(0);
2243 EVT VVT = V.getValueType();
2244 if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems)
2247 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
2248 return (Index == 0) ? V.getOperand(0)
2249 : getUNDEF(VT.getVectorElementType());
2250 if (V.getOpcode() == ISD::BUILD_VECTOR)
2251 return V.getOperand(Index);
2252 if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V))
2253 return getShuffleScalarElt(SVN, Index);
2258 /// getNode - Gets or creates the specified node.
2260 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
2261 FoldingSetNodeID ID;
2262 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2264 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2265 return SDValue(E, 0);
2266 SDNode *N = NodeAllocator.Allocate<SDNode>();
2267 new (N) SDNode(Opcode, DL, getVTList(VT));
2268 CSEMap.InsertNode(N, IP);
2270 AllNodes.push_back(N);
2274 return SDValue(N, 0);
2277 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2278 EVT VT, SDValue Operand) {
2279 // Constant fold unary operations with an integer constant operand.
2280 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2281 const APInt &Val = C->getAPIntValue();
2282 unsigned BitWidth = VT.getSizeInBits();
2285 case ISD::SIGN_EXTEND:
2286 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2287 case ISD::ANY_EXTEND:
2288 case ISD::ZERO_EXTEND:
2290 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2291 case ISD::UINT_TO_FP:
2292 case ISD::SINT_TO_FP: {
2293 const uint64_t zero[] = {0, 0};
2294 // No compile time operations on this type.
2295 if (VT==MVT::ppcf128)
2297 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2298 (void)apf.convertFromAPInt(Val,
2299 Opcode==ISD::SINT_TO_FP,
2300 APFloat::rmNearestTiesToEven);
2301 return getConstantFP(apf, VT);
2303 case ISD::BIT_CONVERT:
2304 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2305 return getConstantFP(Val.bitsToFloat(), VT);
2306 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2307 return getConstantFP(Val.bitsToDouble(), VT);
2310 return getConstant(Val.byteSwap(), VT);
2312 return getConstant(Val.countPopulation(), VT);
2314 return getConstant(Val.countLeadingZeros(), VT);
2316 return getConstant(Val.countTrailingZeros(), VT);
2320 // Constant fold unary operations with a floating point constant operand.
2321 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2322 APFloat V = C->getValueAPF(); // make copy
2323 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2327 return getConstantFP(V, VT);
2330 return getConstantFP(V, VT);
2332 case ISD::FP_EXTEND: {
2334 // This can return overflow, underflow, or inexact; we don't care.
2335 // FIXME need to be more flexible about rounding mode.
2336 (void)V.convert(*EVTToAPFloatSemantics(VT),
2337 APFloat::rmNearestTiesToEven, &ignored);
2338 return getConstantFP(V, VT);
2340 case ISD::FP_TO_SINT:
2341 case ISD::FP_TO_UINT: {
2344 assert(integerPartWidth >= 64);
2345 // FIXME need to be more flexible about rounding mode.
2346 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2347 Opcode==ISD::FP_TO_SINT,
2348 APFloat::rmTowardZero, &ignored);
2349 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2351 APInt api(VT.getSizeInBits(), 2, x);
2352 return getConstant(api, VT);
2354 case ISD::BIT_CONVERT:
2355 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2356 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2357 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2358 return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2364 unsigned OpOpcode = Operand.getNode()->getOpcode();
2366 case ISD::TokenFactor:
2367 case ISD::MERGE_VALUES:
2368 case ISD::CONCAT_VECTORS:
2369 return Operand; // Factor, merge or concat of one node? No need.
2370 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2371 case ISD::FP_EXTEND:
2372 assert(VT.isFloatingPoint() &&
2373 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2374 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2375 if (Operand.getOpcode() == ISD::UNDEF)
2376 return getUNDEF(VT);
2378 case ISD::SIGN_EXTEND:
2379 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2380 "Invalid SIGN_EXTEND!");
2381 if (Operand.getValueType() == VT) return Operand; // noop extension
2382 assert(Operand.getValueType().bitsLT(VT)
2383 && "Invalid sext node, dst < src!");
2384 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2385 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2387 case ISD::ZERO_EXTEND:
2388 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2389 "Invalid ZERO_EXTEND!");
2390 if (Operand.getValueType() == VT) return Operand; // noop extension
2391 assert(Operand.getValueType().bitsLT(VT)
2392 && "Invalid zext node, dst < src!");
2393 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2394 return getNode(ISD::ZERO_EXTEND, DL, VT,
2395 Operand.getNode()->getOperand(0));
2397 case ISD::ANY_EXTEND:
2398 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2399 "Invalid ANY_EXTEND!");
2400 if (Operand.getValueType() == VT) return Operand; // noop extension
2401 assert(Operand.getValueType().bitsLT(VT)
2402 && "Invalid anyext node, dst < src!");
2403 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2404 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2405 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2408 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2409 "Invalid TRUNCATE!");
2410 if (Operand.getValueType() == VT) return Operand; // noop truncate
2411 assert(Operand.getValueType().bitsGT(VT)
2412 && "Invalid truncate node, src < dst!");
2413 if (OpOpcode == ISD::TRUNCATE)
2414 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2415 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2416 OpOpcode == ISD::ANY_EXTEND) {
2417 // If the source is smaller than the dest, we still need an extend.
2418 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
2419 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2420 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2421 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2423 return Operand.getNode()->getOperand(0);
2426 case ISD::BIT_CONVERT:
2427 // Basic sanity checking.
2428 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2429 && "Cannot BIT_CONVERT between types of different sizes!");
2430 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2431 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2432 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
2433 if (OpOpcode == ISD::UNDEF)
2434 return getUNDEF(VT);
2436 case ISD::SCALAR_TO_VECTOR:
2437 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2438 (VT.getVectorElementType() == Operand.getValueType() ||
2439 (VT.getVectorElementType().isInteger() &&
2440 Operand.getValueType().isInteger() &&
2441 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2442 "Illegal SCALAR_TO_VECTOR node!");
2443 if (OpOpcode == ISD::UNDEF)
2444 return getUNDEF(VT);
2445 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2446 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2447 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2448 Operand.getConstantOperandVal(1) == 0 &&
2449 Operand.getOperand(0).getValueType() == VT)
2450 return Operand.getOperand(0);
2453 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2454 if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2455 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2456 Operand.getNode()->getOperand(0));
2457 if (OpOpcode == ISD::FNEG) // --X -> X
2458 return Operand.getNode()->getOperand(0);
2461 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2462 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2467 SDVTList VTs = getVTList(VT);
2468 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2469 FoldingSetNodeID ID;
2470 SDValue Ops[1] = { Operand };
2471 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2473 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2474 return SDValue(E, 0);
2475 N = NodeAllocator.Allocate<UnarySDNode>();
2476 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2477 CSEMap.InsertNode(N, IP);
2479 N = NodeAllocator.Allocate<UnarySDNode>();
2480 new (N) UnarySDNode(Opcode, DL, VTs, Operand);
2483 AllNodes.push_back(N);
2487 return SDValue(N, 0);
2490 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2492 ConstantSDNode *Cst1,
2493 ConstantSDNode *Cst2) {
2494 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2497 case ISD::ADD: return getConstant(C1 + C2, VT);
2498 case ISD::SUB: return getConstant(C1 - C2, VT);
2499 case ISD::MUL: return getConstant(C1 * C2, VT);
2501 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2504 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2507 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2510 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2512 case ISD::AND: return getConstant(C1 & C2, VT);
2513 case ISD::OR: return getConstant(C1 | C2, VT);
2514 case ISD::XOR: return getConstant(C1 ^ C2, VT);
2515 case ISD::SHL: return getConstant(C1 << C2, VT);
2516 case ISD::SRL: return getConstant(C1.lshr(C2), VT);
2517 case ISD::SRA: return getConstant(C1.ashr(C2), VT);
2518 case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2519 case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2526 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2527 SDValue N1, SDValue N2) {
2528 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2529 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2532 case ISD::TokenFactor:
2533 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2534 N2.getValueType() == MVT::Other && "Invalid token factor!");
2535 // Fold trivial token factors.
2536 if (N1.getOpcode() == ISD::EntryToken) return N2;
2537 if (N2.getOpcode() == ISD::EntryToken) return N1;
2538 if (N1 == N2) return N1;
2540 case ISD::CONCAT_VECTORS:
2541 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2542 // one big BUILD_VECTOR.
2543 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2544 N2.getOpcode() == ISD::BUILD_VECTOR) {
2545 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2546 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2547 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2551 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2552 N1.getValueType() == VT && "Binary operator types must match!");
2553 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2554 // worth handling here.
2555 if (N2C && N2C->isNullValue())
2557 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2564 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2565 N1.getValueType() == VT && "Binary operator types must match!");
2566 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2567 // it's worth handling here.
2568 if (N2C && N2C->isNullValue())
2578 assert(VT.isInteger() && "This operator does not apply to FP types!");
2586 if (Opcode == ISD::FADD) {
2588 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2589 if (CFP->getValueAPF().isZero())
2592 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2593 if (CFP->getValueAPF().isZero())
2595 } else if (Opcode == ISD::FSUB) {
2597 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2598 if (CFP->getValueAPF().isZero())
2602 assert(N1.getValueType() == N2.getValueType() &&
2603 N1.getValueType() == VT && "Binary operator types must match!");
2605 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2606 assert(N1.getValueType() == VT &&
2607 N1.getValueType().isFloatingPoint() &&
2608 N2.getValueType().isFloatingPoint() &&
2609 "Invalid FCOPYSIGN!");
2616 assert(VT == N1.getValueType() &&
2617 "Shift operators return type must be the same as their first arg");
2618 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2619 "Shifts only work on integers");
2621 // Always fold shifts of i1 values so the code generator doesn't need to
2622 // handle them. Since we know the size of the shift has to be less than the
2623 // size of the value, the shift/rotate count is guaranteed to be zero.
2627 case ISD::FP_ROUND_INREG: {
2628 EVT EVT = cast<VTSDNode>(N2)->getVT();
2629 assert(VT == N1.getValueType() && "Not an inreg round!");
2630 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2631 "Cannot FP_ROUND_INREG integer types");
2632 assert(EVT.bitsLE(VT) && "Not rounding down!");
2633 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2637 assert(VT.isFloatingPoint() &&
2638 N1.getValueType().isFloatingPoint() &&
2639 VT.bitsLE(N1.getValueType()) &&
2640 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2641 if (N1.getValueType() == VT) return N1; // noop conversion.
2643 case ISD::AssertSext:
2644 case ISD::AssertZext: {
2645 EVT EVT = cast<VTSDNode>(N2)->getVT();
2646 assert(VT == N1.getValueType() && "Not an inreg extend!");
2647 assert(VT.isInteger() && EVT.isInteger() &&
2648 "Cannot *_EXTEND_INREG FP types");
2649 assert(EVT.bitsLE(VT) && "Not extending!");
2650 if (VT == EVT) return N1; // noop assertion.
2653 case ISD::SIGN_EXTEND_INREG: {
2654 EVT EVT = cast<VTSDNode>(N2)->getVT();
2655 assert(VT == N1.getValueType() && "Not an inreg extend!");
2656 assert(VT.isInteger() && EVT.isInteger() &&
2657 "Cannot *_EXTEND_INREG FP types");
2658 assert(EVT.bitsLE(VT) && "Not extending!");
2659 if (EVT == VT) return N1; // Not actually extending
2662 APInt Val = N1C->getAPIntValue();
2663 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2664 Val <<= Val.getBitWidth()-FromBits;
2665 Val = Val.ashr(Val.getBitWidth()-FromBits);
2666 return getConstant(Val, VT);
2670 case ISD::EXTRACT_VECTOR_ELT:
2671 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2672 if (N1.getOpcode() == ISD::UNDEF)
2673 return getUNDEF(VT);
2675 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2676 // expanding copies of large vectors from registers.
2678 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2679 N1.getNumOperands() > 0) {
2681 N1.getOperand(0).getValueType().getVectorNumElements();
2682 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2683 N1.getOperand(N2C->getZExtValue() / Factor),
2684 getConstant(N2C->getZExtValue() % Factor,
2685 N2.getValueType()));
2688 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2689 // expanding large vector constants.
2690 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2691 SDValue Elt = N1.getOperand(N2C->getZExtValue());
2692 EVT VEltTy = N1.getValueType().getVectorElementType();
2693 if (Elt.getValueType() != VEltTy) {
2694 // If the vector element type is not legal, the BUILD_VECTOR operands
2695 // are promoted and implicitly truncated. Make that explicit here.
2696 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2699 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2700 // result is implicitly extended.
2701 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2706 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2707 // operations are lowered to scalars.
2708 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2709 // If the indices are the same, return the inserted element.
2710 if (N1.getOperand(2) == N2)
2711 return N1.getOperand(1);
2712 // If the indices are known different, extract the element from
2713 // the original vector.
2714 else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
2715 isa<ConstantSDNode>(N2))
2716 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2719 case ISD::EXTRACT_ELEMENT:
2720 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2721 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2722 (N1.getValueType().isInteger() == VT.isInteger()) &&
2723 "Wrong types for EXTRACT_ELEMENT!");
2725 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2726 // 64-bit integers into 32-bit parts. Instead of building the extract of
2727 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2728 if (N1.getOpcode() == ISD::BUILD_PAIR)
2729 return N1.getOperand(N2C->getZExtValue());
2731 // EXTRACT_ELEMENT of a constant int is also very common.
2732 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2733 unsigned ElementSize = VT.getSizeInBits();
2734 unsigned Shift = ElementSize * N2C->getZExtValue();
2735 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2736 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2739 case ISD::EXTRACT_SUBVECTOR:
2740 if (N1.getValueType() == VT) // Trivial extraction.
2747 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2748 if (SV.getNode()) return SV;
2749 } else { // Cannonicalize constant to RHS if commutative
2750 if (isCommutativeBinOp(Opcode)) {
2751 std::swap(N1C, N2C);
2757 // Constant fold FP operations.
2758 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2759 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2761 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2762 // Cannonicalize constant to RHS if commutative
2763 std::swap(N1CFP, N2CFP);
2765 } else if (N2CFP && VT != MVT::ppcf128) {
2766 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2767 APFloat::opStatus s;
2770 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2771 if (s != APFloat::opInvalidOp)
2772 return getConstantFP(V1, VT);
2775 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2776 if (s!=APFloat::opInvalidOp)
2777 return getConstantFP(V1, VT);
2780 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2781 if (s!=APFloat::opInvalidOp)
2782 return getConstantFP(V1, VT);
2785 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2786 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2787 return getConstantFP(V1, VT);
2790 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2791 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2792 return getConstantFP(V1, VT);
2794 case ISD::FCOPYSIGN:
2796 return getConstantFP(V1, VT);
2802 // Canonicalize an UNDEF to the RHS, even over a constant.
2803 if (N1.getOpcode() == ISD::UNDEF) {
2804 if (isCommutativeBinOp(Opcode)) {
2808 case ISD::FP_ROUND_INREG:
2809 case ISD::SIGN_EXTEND_INREG:
2815 return N1; // fold op(undef, arg2) -> undef
2823 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2824 // For vectors, we can't easily build an all zero vector, just return
2831 // Fold a bunch of operators when the RHS is undef.
2832 if (N2.getOpcode() == ISD::UNDEF) {
2835 if (N1.getOpcode() == ISD::UNDEF)
2836 // Handle undef ^ undef -> 0 special case. This is a common
2838 return getConstant(0, VT);
2848 return N2; // fold op(arg1, undef) -> undef
2862 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2863 // For vectors, we can't easily build an all zero vector, just return
2868 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2869 // For vectors, we can't easily build an all one vector, just return
2877 // Memoize this node if possible.
2879 SDVTList VTs = getVTList(VT);
2880 if (VT != MVT::Flag) {
2881 SDValue Ops[] = { N1, N2 };
2882 FoldingSetNodeID ID;
2883 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2885 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2886 return SDValue(E, 0);
2887 N = NodeAllocator.Allocate<BinarySDNode>();
2888 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2889 CSEMap.InsertNode(N, IP);
2891 N = NodeAllocator.Allocate<BinarySDNode>();
2892 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
2895 AllNodes.push_back(N);
2899 return SDValue(N, 0);
2902 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2903 SDValue N1, SDValue N2, SDValue N3) {
2904 // Perform various simplifications.
2905 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2906 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2908 case ISD::CONCAT_VECTORS:
2909 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2910 // one big BUILD_VECTOR.
2911 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2912 N2.getOpcode() == ISD::BUILD_VECTOR &&
2913 N3.getOpcode() == ISD::BUILD_VECTOR) {
2914 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
2915 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
2916 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
2917 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2921 // Use FoldSetCC to simplify SETCC's.
2922 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
2923 if (Simp.getNode()) return Simp;
2928 if (N1C->getZExtValue())
2929 return N2; // select true, X, Y -> X
2931 return N3; // select false, X, Y -> Y
2934 if (N2 == N3) return N2; // select C, X, X -> X
2938 if (N2C->getZExtValue()) // Unconditional branch
2939 return getNode(ISD::BR, DL, MVT::Other, N1, N3);
2941 return N1; // Never-taken branch
2944 case ISD::VECTOR_SHUFFLE:
2945 llvm_unreachable("should use getVectorShuffle constructor!");
2947 case ISD::BIT_CONVERT:
2948 // Fold bit_convert nodes from a type to themselves.
2949 if (N1.getValueType() == VT)
2954 // Memoize node if it doesn't produce a flag.
2956 SDVTList VTs = getVTList(VT);
2957 if (VT != MVT::Flag) {
2958 SDValue Ops[] = { N1, N2, N3 };
2959 FoldingSetNodeID ID;
2960 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2962 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2963 return SDValue(E, 0);
2964 N = NodeAllocator.Allocate<TernarySDNode>();
2965 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2966 CSEMap.InsertNode(N, IP);
2968 N = NodeAllocator.Allocate<TernarySDNode>();
2969 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
2971 AllNodes.push_back(N);
2975 return SDValue(N, 0);
2978 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2979 SDValue N1, SDValue N2, SDValue N3,
2981 SDValue Ops[] = { N1, N2, N3, N4 };
2982 return getNode(Opcode, DL, VT, Ops, 4);
2985 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2986 SDValue N1, SDValue N2, SDValue N3,
2987 SDValue N4, SDValue N5) {
2988 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2989 return getNode(Opcode, DL, VT, Ops, 5);
2992 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
2993 /// the incoming stack arguments to be loaded from the stack.
2994 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
2995 SmallVector<SDValue, 8> ArgChains;
2997 // Include the original chain at the beginning of the list. When this is
2998 // used by target LowerCall hooks, this helps legalize find the
2999 // CALLSEQ_BEGIN node.
3000 ArgChains.push_back(Chain);
3002 // Add a chain value for each stack argument.
3003 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3004 UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3005 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3006 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3007 if (FI->getIndex() < 0)
3008 ArgChains.push_back(SDValue(L, 1));
3010 // Build a tokenfactor for all the chains.
3011 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
3012 &ArgChains[0], ArgChains.size());
3015 /// getMemsetValue - Vectorized representation of the memset value
3017 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3019 unsigned NumBits = VT.isVector() ?
3020 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
3021 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3022 APInt Val = APInt(NumBits, C->getZExtValue() & 255);
3024 for (unsigned i = NumBits; i > 8; i >>= 1) {
3025 Val = (Val << Shift) | Val;
3029 return DAG.getConstant(Val, VT);
3030 return DAG.getConstantFP(APFloat(Val), VT);
3033 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3034 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3036 for (unsigned i = NumBits; i > 8; i >>= 1) {
3037 Value = DAG.getNode(ISD::OR, dl, VT,
3038 DAG.getNode(ISD::SHL, dl, VT, Value,
3039 DAG.getConstant(Shift,
3040 TLI.getShiftAmountTy())),
3048 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3049 /// used when a memcpy is turned into a memset when the source is a constant
3051 static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3052 const TargetLowering &TLI,
3053 std::string &Str, unsigned Offset) {
3054 // Handle vector with all elements zero.
3057 return DAG.getConstant(0, VT);
3058 unsigned NumElts = VT.getVectorNumElements();
3059 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3060 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3062 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts)));
3065 assert(!VT.isVector() && "Can't handle vector type here!");
3066 unsigned NumBits = VT.getSizeInBits();
3067 unsigned MSB = NumBits / 8;
3069 if (TLI.isLittleEndian())
3070 Offset = Offset + MSB - 1;
3071 for (unsigned i = 0; i != MSB; ++i) {
3072 Val = (Val << 8) | (unsigned char)Str[Offset];
3073 Offset += TLI.isLittleEndian() ? -1 : 1;
3075 return DAG.getConstant(Val, VT);
3078 /// getMemBasePlusOffset - Returns base and offset node for the
3080 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3081 SelectionDAG &DAG) {
3082 EVT VT = Base.getValueType();
3083 return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3084 VT, Base, DAG.getConstant(Offset, VT));
3087 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
3089 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3090 unsigned SrcDelta = 0;
3091 GlobalAddressSDNode *G = NULL;
3092 if (Src.getOpcode() == ISD::GlobalAddress)
3093 G = cast<GlobalAddressSDNode>(Src);
3094 else if (Src.getOpcode() == ISD::ADD &&
3095 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3096 Src.getOperand(1).getOpcode() == ISD::Constant) {
3097 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3098 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3103 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3104 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3110 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3111 /// to replace the memset / memcpy is below the threshold. It also returns the
3112 /// types of the sequence of memory ops to perform memset / memcpy.
3114 bool MeetsMaxMemopRequirement(std::vector<EVT> &MemOps,
3115 SDValue Dst, SDValue Src,
3116 unsigned Limit, uint64_t Size, unsigned &Align,
3117 std::string &Str, bool &isSrcStr,
3119 const TargetLowering &TLI) {
3120 isSrcStr = isMemSrcFromString(Src, Str);
3121 bool isSrcConst = isa<ConstantSDNode>(Src);
3122 EVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
3123 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses(VT);
3124 if (VT != MVT::iAny) {
3125 const Type *Ty = VT.getTypeForEVT(*DAG.getContext());
3126 unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3127 // If source is a string constant, this will require an unaligned load.
3128 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
3129 if (Dst.getOpcode() != ISD::FrameIndex) {
3130 // Can't change destination alignment. It requires a unaligned store.
3134 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
3135 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3136 if (MFI->isFixedObjectIndex(FI)) {
3137 // Can't change destination alignment. It requires a unaligned store.
3141 // Give the stack frame object a larger alignment if needed.
3142 if (MFI->getObjectAlignment(FI) < NewAlign)
3143 MFI->setObjectAlignment(FI, NewAlign);
3150 if (VT == MVT::iAny) {
3151 if (TLI.allowsUnalignedMemoryAccesses(MVT::i64)) {
3154 switch (Align & 7) {
3155 case 0: VT = MVT::i64; break;
3156 case 4: VT = MVT::i32; break;
3157 case 2: VT = MVT::i16; break;
3158 default: VT = MVT::i8; break;
3163 while (!TLI.isTypeLegal(LVT))
3164 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3165 assert(LVT.isInteger());
3171 unsigned NumMemOps = 0;
3173 unsigned VTSize = VT.getSizeInBits() / 8;
3174 while (VTSize > Size) {
3175 // For now, only use non-vector load / store's for the left-over pieces.
3176 if (VT.isVector()) {
3178 while (!TLI.isTypeLegal(VT))
3179 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3180 VTSize = VT.getSizeInBits() / 8;
3182 // This can result in a type that is not legal on the target, e.g.
3183 // 1 or 2 bytes on PPC.
3184 VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3189 if (++NumMemOps > Limit)
3191 MemOps.push_back(VT);
3198 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3199 SDValue Chain, SDValue Dst,
3200 SDValue Src, uint64_t Size,
3201 unsigned Align, bool AlwaysInline,
3202 const Value *DstSV, uint64_t DstSVOff,
3203 const Value *SrcSV, uint64_t SrcSVOff){
3204 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3206 // Expand memcpy to a series of load and store ops if the size operand falls
3207 // below a certain threshold.
3208 std::vector<EVT> MemOps;
3209 uint64_t Limit = -1ULL;
3211 Limit = TLI.getMaxStoresPerMemcpy();
3212 unsigned DstAlign = Align; // Destination alignment can change.
3215 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3216 Str, CopyFromStr, DAG, TLI))
3220 bool isZeroStr = CopyFromStr && Str.empty();
3221 SmallVector<SDValue, 8> OutChains;
3222 unsigned NumMemOps = MemOps.size();
3223 uint64_t SrcOff = 0, DstOff = 0;
3224 for (unsigned i = 0; i < NumMemOps; i++) {
3226 unsigned VTSize = VT.getSizeInBits() / 8;
3227 SDValue Value, Store;
3229 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
3230 // It's unlikely a store of a vector immediate can be done in a single
3231 // instruction. It would require a load from a constantpool first.
3232 // We also handle store a vector with all zero's.
3233 // FIXME: Handle other cases where store of vector immediate is done in
3234 // a single instruction.
3235 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3236 Store = DAG.getStore(Chain, dl, Value,
3237 getMemBasePlusOffset(Dst, DstOff, DAG),
3238 DstSV, DstSVOff + DstOff, false, DstAlign);
3240 // The type might not be legal for the target. This should only happen
3241 // if the type is smaller than a legal type, as on PPC, so the right
3242 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
3243 // to Load/Store if NVT==VT.
3244 // FIXME does the case above also need this?
3245 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3246 assert(NVT.bitsGE(VT));
3247 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
3248 getMemBasePlusOffset(Src, SrcOff, DAG),
3249 SrcSV, SrcSVOff + SrcOff, VT, false, Align);
3250 Store = DAG.getTruncStore(Chain, dl, Value,
3251 getMemBasePlusOffset(Dst, DstOff, DAG),
3252 DstSV, DstSVOff + DstOff, VT, false, DstAlign);
3254 OutChains.push_back(Store);
3259 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3260 &OutChains[0], OutChains.size());
3263 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3264 SDValue Chain, SDValue Dst,
3265 SDValue Src, uint64_t Size,
3266 unsigned Align, bool AlwaysInline,
3267 const Value *DstSV, uint64_t DstSVOff,
3268 const Value *SrcSV, uint64_t SrcSVOff){
3269 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3271 // Expand memmove to a series of load and store ops if the size operand falls
3272 // below a certain threshold.
3273 std::vector<EVT> MemOps;
3274 uint64_t Limit = -1ULL;
3276 Limit = TLI.getMaxStoresPerMemmove();
3277 unsigned DstAlign = Align; // Destination alignment can change.
3280 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
3281 Str, CopyFromStr, DAG, TLI))
3284 uint64_t SrcOff = 0, DstOff = 0;
3286 SmallVector<SDValue, 8> LoadValues;
3287 SmallVector<SDValue, 8> LoadChains;
3288 SmallVector<SDValue, 8> OutChains;
3289 unsigned NumMemOps = MemOps.size();
3290 for (unsigned i = 0; i < NumMemOps; i++) {
3292 unsigned VTSize = VT.getSizeInBits() / 8;
3293 SDValue Value, Store;
3295 Value = DAG.getLoad(VT, dl, Chain,
3296 getMemBasePlusOffset(Src, SrcOff, DAG),
3297 SrcSV, SrcSVOff + SrcOff, false, Align);
3298 LoadValues.push_back(Value);
3299 LoadChains.push_back(Value.getValue(1));
3302 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3303 &LoadChains[0], LoadChains.size());
3305 for (unsigned i = 0; i < NumMemOps; i++) {
3307 unsigned VTSize = VT.getSizeInBits() / 8;
3308 SDValue Value, Store;
3310 Store = DAG.getStore(Chain, dl, LoadValues[i],
3311 getMemBasePlusOffset(Dst, DstOff, DAG),
3312 DstSV, DstSVOff + DstOff, false, DstAlign);
3313 OutChains.push_back(Store);
3317 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3318 &OutChains[0], OutChains.size());
3321 static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3322 SDValue Chain, SDValue Dst,
3323 SDValue Src, uint64_t Size,
3325 const Value *DstSV, uint64_t DstSVOff) {
3326 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3328 // Expand memset to a series of load/store ops if the size operand
3329 // falls below a certain threshold.
3330 std::vector<EVT> MemOps;
3333 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
3334 Size, Align, Str, CopyFromStr, DAG, TLI))
3337 SmallVector<SDValue, 8> OutChains;
3338 uint64_t DstOff = 0;
3340 unsigned NumMemOps = MemOps.size();
3341 for (unsigned i = 0; i < NumMemOps; i++) {
3343 unsigned VTSize = VT.getSizeInBits() / 8;
3344 SDValue Value = getMemsetValue(Src, VT, DAG, dl);
3345 SDValue Store = DAG.getStore(Chain, dl, Value,
3346 getMemBasePlusOffset(Dst, DstOff, DAG),
3347 DstSV, DstSVOff + DstOff);
3348 OutChains.push_back(Store);
3352 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3353 &OutChains[0], OutChains.size());
3356 SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3357 SDValue Src, SDValue Size,
3358 unsigned Align, bool AlwaysInline,
3359 const Value *DstSV, uint64_t DstSVOff,
3360 const Value *SrcSV, uint64_t SrcSVOff) {
3362 // Check to see if we should lower the memcpy to loads and stores first.
3363 // For cases within the target-specified limits, this is the best choice.
3364 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3366 // Memcpy with size zero? Just return the original chain.
3367 if (ConstantSize->isNullValue())
3371 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3372 ConstantSize->getZExtValue(),
3373 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3374 if (Result.getNode())
3378 // Then check to see if we should lower the memcpy with target-specific
3379 // code. If the target chooses to do this, this is the next best.
3381 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3383 DstSV, DstSVOff, SrcSV, SrcSVOff);
3384 if (Result.getNode())
3387 // If we really need inline code and the target declined to provide it,
3388 // use a (potentially long) sequence of loads and stores.
3390 assert(ConstantSize && "AlwaysInline requires a constant size!");
3391 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3392 ConstantSize->getZExtValue(), Align, true,
3393 DstSV, DstSVOff, SrcSV, SrcSVOff);
3396 // Emit a library call.
3397 TargetLowering::ArgListTy Args;
3398 TargetLowering::ArgListEntry Entry;
3399 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3400 Entry.Node = Dst; Args.push_back(Entry);
3401 Entry.Node = Src; Args.push_back(Entry);
3402 Entry.Node = Size; Args.push_back(Entry);
3403 // FIXME: pass in DebugLoc
3404 std::pair<SDValue,SDValue> CallResult =
3405 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3406 false, false, false, false, 0,
3407 TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3408 /*isReturnValueUsed=*/false,
3409 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3410 TLI.getPointerTy()),
3412 return CallResult.second;
3415 SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3416 SDValue Src, SDValue Size,
3418 const Value *DstSV, uint64_t DstSVOff,
3419 const Value *SrcSV, uint64_t SrcSVOff) {
3421 // Check to see if we should lower the memmove to loads and stores first.
3422 // For cases within the target-specified limits, this is the best choice.
3423 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3425 // Memmove with size zero? Just return the original chain.
3426 if (ConstantSize->isNullValue())
3430 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3431 ConstantSize->getZExtValue(),
3432 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3433 if (Result.getNode())
3437 // Then check to see if we should lower the memmove with target-specific
3438 // code. If the target chooses to do this, this is the next best.
3440 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
3441 DstSV, DstSVOff, SrcSV, SrcSVOff);
3442 if (Result.getNode())
3445 // Emit a library call.
3446 TargetLowering::ArgListTy Args;
3447 TargetLowering::ArgListEntry Entry;
3448 Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3449 Entry.Node = Dst; Args.push_back(Entry);
3450 Entry.Node = Src; Args.push_back(Entry);
3451 Entry.Node = Size; Args.push_back(Entry);
3452 // FIXME: pass in DebugLoc
3453 std::pair<SDValue,SDValue> CallResult =
3454 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3455 false, false, false, false, 0,
3456 TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3457 /*isReturnValueUsed=*/false,
3458 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3459 TLI.getPointerTy()),
3461 return CallResult.second;
3464 SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3465 SDValue Src, SDValue Size,
3467 const Value *DstSV, uint64_t DstSVOff) {
3469 // Check to see if we should lower the memset to stores first.
3470 // For cases within the target-specified limits, this is the best choice.
3471 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3473 // Memset with size zero? Just return the original chain.
3474 if (ConstantSize->isNullValue())
3478 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3479 Align, DstSV, DstSVOff);
3480 if (Result.getNode())
3484 // Then check to see if we should lower the memset with target-specific
3485 // code. If the target chooses to do this, this is the next best.
3487 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
3489 if (Result.getNode())
3492 // Emit a library call.
3493 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3494 TargetLowering::ArgListTy Args;
3495 TargetLowering::ArgListEntry Entry;
3496 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3497 Args.push_back(Entry);
3498 // Extend or truncate the argument to be an i32 value for the call.
3499 if (Src.getValueType().bitsGT(MVT::i32))
3500 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3502 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3504 Entry.Ty = Type::getInt32Ty(*getContext());
3505 Entry.isSExt = true;
3506 Args.push_back(Entry);
3508 Entry.Ty = IntPtrTy;
3509 Entry.isSExt = false;
3510 Args.push_back(Entry);
3511 // FIXME: pass in DebugLoc
3512 std::pair<SDValue,SDValue> CallResult =
3513 TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3514 false, false, false, false, 0,
3515 TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3516 /*isReturnValueUsed=*/false,
3517 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3518 TLI.getPointerTy()),
3520 return CallResult.second;
3523 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3525 SDValue Ptr, SDValue Cmp,
3526 SDValue Swp, const Value* PtrVal,
3527 unsigned Alignment) {
3528 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3529 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3531 EVT VT = Cmp.getValueType();
3533 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3534 Alignment = getEVTAlignment(MemVT);
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 return SDValue(E, 0);
3544 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3545 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
3546 Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3547 CSEMap.InsertNode(N, IP);
3548 AllNodes.push_back(N);
3549 return SDValue(N, 0);
3552 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3554 SDValue Ptr, SDValue Val,
3555 const Value* PtrVal,
3556 unsigned Alignment) {
3557 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3558 Opcode == ISD::ATOMIC_LOAD_SUB ||
3559 Opcode == ISD::ATOMIC_LOAD_AND ||
3560 Opcode == ISD::ATOMIC_LOAD_OR ||
3561 Opcode == ISD::ATOMIC_LOAD_XOR ||
3562 Opcode == ISD::ATOMIC_LOAD_NAND ||
3563 Opcode == ISD::ATOMIC_LOAD_MIN ||
3564 Opcode == ISD::ATOMIC_LOAD_MAX ||
3565 Opcode == ISD::ATOMIC_LOAD_UMIN ||
3566 Opcode == ISD::ATOMIC_LOAD_UMAX ||
3567 Opcode == ISD::ATOMIC_SWAP) &&
3568 "Invalid Atomic Op");
3570 EVT VT = Val.getValueType();
3572 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3573 Alignment = getEVTAlignment(MemVT);
3575 SDVTList VTs = getVTList(VT, MVT::Other);
3576 FoldingSetNodeID ID;
3577 ID.AddInteger(MemVT.getRawBits());
3578 SDValue Ops[] = {Chain, Ptr, Val};
3579 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3581 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3582 return SDValue(E, 0);
3583 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3584 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
3585 Chain, Ptr, Val, PtrVal, Alignment);
3586 CSEMap.InsertNode(N, IP);
3587 AllNodes.push_back(N);
3588 return SDValue(N, 0);
3591 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3592 /// Allowed to return something different (and simpler) if Simplify is true.
3593 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3598 SmallVector<EVT, 4> VTs;
3599 VTs.reserve(NumOps);
3600 for (unsigned i = 0; i < NumOps; ++i)
3601 VTs.push_back(Ops[i].getValueType());
3602 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3607 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3608 const EVT *VTs, unsigned NumVTs,
3609 const SDValue *Ops, unsigned NumOps,
3610 EVT MemVT, const Value *srcValue, int SVOff,
3611 unsigned Align, bool Vol,
3612 bool ReadMem, bool WriteMem) {
3613 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3614 MemVT, srcValue, SVOff, Align, Vol,
3619 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3620 const SDValue *Ops, unsigned NumOps,
3621 EVT MemVT, const Value *srcValue, int SVOff,
3622 unsigned Align, bool Vol,
3623 bool ReadMem, bool WriteMem) {
3624 // Memoize the node unless it returns a flag.
3625 MemIntrinsicSDNode *N;
3626 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3627 FoldingSetNodeID ID;
3628 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3630 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3631 return SDValue(E, 0);
3633 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3634 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
3635 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3636 CSEMap.InsertNode(N, IP);
3638 N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
3639 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
3640 srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
3642 AllNodes.push_back(N);
3643 return SDValue(N, 0);
3647 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
3648 ISD::LoadExtType ExtType, EVT VT, SDValue Chain,
3649 SDValue Ptr, SDValue Offset,
3650 const Value *SV, int SVOffset, EVT EVT,
3651 bool isVolatile, unsigned Alignment) {
3652 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3653 Alignment = getEVTAlignment(VT);
3656 ExtType = ISD::NON_EXTLOAD;
3657 } else if (ExtType == ISD::NON_EXTLOAD) {
3658 assert(VT == EVT && "Non-extending load from different memory type!");
3662 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3663 "Invalid vector extload!");
3665 assert(EVT.bitsLT(VT) &&
3666 "Should only be an extending load, not truncating!");
3667 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3668 "Cannot sign/zero extend a FP/Vector load!");
3669 assert(VT.isInteger() == EVT.isInteger() &&
3670 "Cannot convert from FP to Int or Int -> FP!");
3673 bool Indexed = AM != ISD::UNINDEXED;
3674 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3675 "Unindexed load with an offset!");
3677 SDVTList VTs = Indexed ?
3678 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3679 SDValue Ops[] = { Chain, Ptr, Offset };
3680 FoldingSetNodeID ID;
3681 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3682 ID.AddInteger(EVT.getRawBits());
3683 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, isVolatile, Alignment));
3684 ID.AddInteger(SVOffset);
3686 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3687 return SDValue(E, 0);
3688 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3689 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, EVT, SV, SVOffset,
3690 Alignment, isVolatile);
3691 CSEMap.InsertNode(N, IP);
3692 AllNodes.push_back(N);
3693 return SDValue(N, 0);
3696 SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
3697 SDValue Chain, SDValue Ptr,
3698 const Value *SV, int SVOffset,
3699 bool isVolatile, unsigned Alignment) {
3700 SDValue Undef = getUNDEF(Ptr.getValueType());
3701 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3702 SV, SVOffset, VT, isVolatile, Alignment);
3705 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, EVT VT,
3706 SDValue Chain, SDValue Ptr,
3708 int SVOffset, EVT EVT,
3709 bool isVolatile, unsigned Alignment) {
3710 SDValue Undef = getUNDEF(Ptr.getValueType());
3711 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
3712 SV, SVOffset, EVT, isVolatile, Alignment);
3716 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
3717 SDValue Offset, ISD::MemIndexedMode AM) {
3718 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3719 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3720 "Load is already a indexed load!");
3721 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
3722 LD->getChain(), Base, Offset, LD->getSrcValue(),
3723 LD->getSrcValueOffset(), LD->getMemoryVT(),
3724 LD->isVolatile(), LD->getAlignment());
3727 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
3728 SDValue Ptr, const Value *SV, int SVOffset,
3729 bool isVolatile, unsigned Alignment) {
3730 EVT VT = Val.getValueType();
3732 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3733 Alignment = getEVTAlignment(VT);
3735 SDVTList VTs = getVTList(MVT::Other);
3736 SDValue Undef = getUNDEF(Ptr.getValueType());
3737 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3738 FoldingSetNodeID ID;
3739 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3740 ID.AddInteger(VT.getRawBits());
3741 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED,
3742 isVolatile, Alignment));
3743 ID.AddInteger(SVOffset);
3745 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3746 return SDValue(E, 0);
3747 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3748 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false,
3749 VT, SV, SVOffset, Alignment, isVolatile);
3750 CSEMap.InsertNode(N, IP);
3751 AllNodes.push_back(N);
3752 return SDValue(N, 0);
3755 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
3756 SDValue Ptr, const Value *SV,
3757 int SVOffset, EVT SVT,
3758 bool isVolatile, unsigned Alignment) {
3759 EVT VT = Val.getValueType();
3762 return getStore(Chain, dl, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3764 assert(VT.bitsGT(SVT) && "Not a truncation?");
3765 assert(VT.isInteger() == SVT.isInteger() &&
3766 "Can't do FP-INT conversion!");
3768 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3769 Alignment = getEVTAlignment(VT);
3771 SDVTList VTs = getVTList(MVT::Other);
3772 SDValue Undef = getUNDEF(Ptr.getValueType());
3773 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3774 FoldingSetNodeID ID;
3775 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3776 ID.AddInteger(SVT.getRawBits());
3777 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED,
3778 isVolatile, Alignment));
3779 ID.AddInteger(SVOffset);
3781 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3782 return SDValue(E, 0);
3783 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3784 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true,
3785 SVT, SV, SVOffset, Alignment, isVolatile);
3786 CSEMap.InsertNode(N, IP);
3787 AllNodes.push_back(N);
3788 return SDValue(N, 0);
3792 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
3793 SDValue Offset, ISD::MemIndexedMode AM) {
3794 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3795 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3796 "Store is already a indexed store!");
3797 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3798 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3799 FoldingSetNodeID ID;
3800 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3801 ID.AddInteger(ST->getMemoryVT().getRawBits());
3802 ID.AddInteger(ST->getRawSubclassData());
3804 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3805 return SDValue(E, 0);
3806 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3807 new (N) StoreSDNode(Ops, dl, VTs, AM,
3808 ST->isTruncatingStore(), ST->getMemoryVT(),
3809 ST->getSrcValue(), ST->getSrcValueOffset(),
3810 ST->getAlignment(), ST->isVolatile());
3811 CSEMap.InsertNode(N, IP);
3812 AllNodes.push_back(N);
3813 return SDValue(N, 0);
3816 SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
3817 SDValue Chain, SDValue Ptr,
3819 SDValue Ops[] = { Chain, Ptr, SV };
3820 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
3823 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3824 const SDUse *Ops, unsigned NumOps) {
3826 case 0: return getNode(Opcode, DL, VT);
3827 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3828 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3829 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3833 // Copy from an SDUse array into an SDValue array for use with
3834 // the regular getNode logic.
3835 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3836 return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
3839 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3840 const SDValue *Ops, unsigned NumOps) {
3842 case 0: return getNode(Opcode, DL, VT);
3843 case 1: return getNode(Opcode, DL, VT, Ops[0]);
3844 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
3845 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
3851 case ISD::SELECT_CC: {
3852 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3853 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3854 "LHS and RHS of condition must have same type!");
3855 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3856 "True and False arms of SelectCC must have same type!");
3857 assert(Ops[2].getValueType() == VT &&
3858 "select_cc node must be of same type as true and false value!");
3862 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3863 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3864 "LHS/RHS of comparison should match types!");
3871 SDVTList VTs = getVTList(VT);
3873 if (VT != MVT::Flag) {
3874 FoldingSetNodeID ID;
3875 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3878 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3879 return SDValue(E, 0);
3881 N = NodeAllocator.Allocate<SDNode>();
3882 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
3883 CSEMap.InsertNode(N, IP);
3885 N = NodeAllocator.Allocate<SDNode>();
3886 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
3889 AllNodes.push_back(N);
3893 return SDValue(N, 0);
3896 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
3897 const std::vector<EVT> &ResultTys,
3898 const SDValue *Ops, unsigned NumOps) {
3899 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
3903 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
3904 const EVT *VTs, unsigned NumVTs,
3905 const SDValue *Ops, unsigned NumOps) {
3907 return getNode(Opcode, DL, VTs[0], Ops, NumOps);
3908 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
3911 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
3912 const SDValue *Ops, unsigned NumOps) {
3913 if (VTList.NumVTs == 1)
3914 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
3918 // FIXME: figure out how to safely handle things like
3919 // int foo(int x) { return 1 << (x & 255); }
3920 // int bar() { return foo(256); }
3921 case ISD::SRA_PARTS:
3922 case ISD::SRL_PARTS:
3923 case ISD::SHL_PARTS:
3924 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3925 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3926 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
3927 else if (N3.getOpcode() == ISD::AND)
3928 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3929 // If the and is only masking out bits that cannot effect the shift,
3930 // eliminate the and.
3931 unsigned NumBits = VT.getSizeInBits()*2;
3932 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3933 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
3939 // Memoize the node unless it returns a flag.
3941 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3942 FoldingSetNodeID ID;
3943 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3945 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3946 return SDValue(E, 0);
3948 N = NodeAllocator.Allocate<UnarySDNode>();
3949 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
3950 } else if (NumOps == 2) {
3951 N = NodeAllocator.Allocate<BinarySDNode>();
3952 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
3953 } else if (NumOps == 3) {
3954 N = NodeAllocator.Allocate<TernarySDNode>();
3955 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
3957 N = NodeAllocator.Allocate<SDNode>();
3958 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
3960 CSEMap.InsertNode(N, IP);
3963 N = NodeAllocator.Allocate<UnarySDNode>();
3964 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
3965 } else if (NumOps == 2) {
3966 N = NodeAllocator.Allocate<BinarySDNode>();
3967 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
3968 } else if (NumOps == 3) {
3969 N = NodeAllocator.Allocate<TernarySDNode>();
3970 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
3972 N = NodeAllocator.Allocate<SDNode>();
3973 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
3976 AllNodes.push_back(N);
3980 return SDValue(N, 0);
3983 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
3984 return getNode(Opcode, DL, VTList, 0, 0);
3987 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
3989 SDValue Ops[] = { N1 };
3990 return getNode(Opcode, DL, VTList, Ops, 1);
3993 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
3994 SDValue N1, SDValue N2) {
3995 SDValue Ops[] = { N1, N2 };
3996 return getNode(Opcode, DL, VTList, Ops, 2);
3999 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4000 SDValue N1, SDValue N2, SDValue N3) {
4001 SDValue Ops[] = { N1, N2, N3 };
4002 return getNode(Opcode, DL, VTList, Ops, 3);
4005 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4006 SDValue N1, SDValue N2, SDValue N3,
4008 SDValue Ops[] = { N1, N2, N3, N4 };
4009 return getNode(Opcode, DL, VTList, Ops, 4);
4012 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4013 SDValue N1, SDValue N2, SDValue N3,
4014 SDValue N4, SDValue N5) {
4015 SDValue Ops[] = { N1, N2, N3, N4, N5 };
4016 return getNode(Opcode, DL, VTList, Ops, 5);
4019 SDVTList SelectionDAG::getVTList(EVT VT) {
4020 return makeVTList(SDNode::getValueTypeList(VT), 1);
4023 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4024 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4025 E = VTList.rend(); I != E; ++I)
4026 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4029 EVT *Array = Allocator.Allocate<EVT>(2);
4032 SDVTList Result = makeVTList(Array, 2);
4033 VTList.push_back(Result);
4037 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4038 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4039 E = VTList.rend(); I != E; ++I)
4040 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4044 EVT *Array = Allocator.Allocate<EVT>(3);
4048 SDVTList Result = makeVTList(Array, 3);
4049 VTList.push_back(Result);
4053 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4054 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4055 E = VTList.rend(); I != E; ++I)
4056 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4057 I->VTs[2] == VT3 && I->VTs[3] == VT4)
4060 EVT *Array = Allocator.Allocate<EVT>(3);
4065 SDVTList Result = makeVTList(Array, 4);
4066 VTList.push_back(Result);
4070 SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4072 case 0: llvm_unreachable("Cannot have nodes without results!");
4073 case 1: return getVTList(VTs[0]);
4074 case 2: return getVTList(VTs[0], VTs[1]);
4075 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4079 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4080 E = VTList.rend(); I != E; ++I) {
4081 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4084 bool NoMatch = false;
4085 for (unsigned i = 2; i != NumVTs; ++i)
4086 if (VTs[i] != I->VTs[i]) {
4094 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4095 std::copy(VTs, VTs+NumVTs, Array);
4096 SDVTList Result = makeVTList(Array, NumVTs);
4097 VTList.push_back(Result);
4102 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4103 /// specified operands. If the resultant node already exists in the DAG,
4104 /// this does not modify the specified node, instead it returns the node that
4105 /// already exists. If the resultant node does not exist in the DAG, the
4106 /// input node is returned. As a degenerate case, if you specify the same
4107 /// input operands as the node already has, the input node is returned.
4108 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
4109 SDNode *N = InN.getNode();
4110 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4112 // Check to see if there is no change.
4113 if (Op == N->getOperand(0)) return InN;
4115 // See if the modified node already exists.
4116 void *InsertPos = 0;
4117 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4118 return SDValue(Existing, InN.getResNo());
4120 // Nope it doesn't. Remove the node from its current place in the maps.
4122 if (!RemoveNodeFromCSEMaps(N))
4125 // Now we update the operands.
4126 N->OperandList[0].set(Op);
4128 // If this gets put into a CSE map, add it.
4129 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4133 SDValue SelectionDAG::
4134 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
4135 SDNode *N = InN.getNode();
4136 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4138 // Check to see if there is no change.
4139 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4140 return InN; // No operands changed, just return the input node.
4142 // See if the modified node already exists.
4143 void *InsertPos = 0;
4144 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4145 return SDValue(Existing, InN.getResNo());
4147 // Nope it doesn't. Remove the node from its current place in the maps.
4149 if (!RemoveNodeFromCSEMaps(N))
4152 // Now we update the operands.
4153 if (N->OperandList[0] != Op1)
4154 N->OperandList[0].set(Op1);
4155 if (N->OperandList[1] != Op2)
4156 N->OperandList[1].set(Op2);
4158 // If this gets put into a CSE map, add it.
4159 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4163 SDValue SelectionDAG::
4164 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
4165 SDValue Ops[] = { Op1, Op2, Op3 };
4166 return UpdateNodeOperands(N, Ops, 3);
4169 SDValue SelectionDAG::
4170 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4171 SDValue Op3, SDValue Op4) {
4172 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4173 return UpdateNodeOperands(N, Ops, 4);
4176 SDValue SelectionDAG::
4177 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
4178 SDValue Op3, SDValue Op4, SDValue Op5) {
4179 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4180 return UpdateNodeOperands(N, Ops, 5);
4183 SDValue SelectionDAG::
4184 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
4185 SDNode *N = InN.getNode();
4186 assert(N->getNumOperands() == NumOps &&
4187 "Update with wrong number of operands");
4189 // Check to see if there is no change.
4190 bool AnyChange = false;
4191 for (unsigned i = 0; i != NumOps; ++i) {
4192 if (Ops[i] != N->getOperand(i)) {
4198 // No operands changed, just return the input node.
4199 if (!AnyChange) return InN;
4201 // See if the modified node already exists.
4202 void *InsertPos = 0;
4203 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4204 return SDValue(Existing, InN.getResNo());
4206 // Nope it doesn't. Remove the node from its current place in the maps.
4208 if (!RemoveNodeFromCSEMaps(N))
4211 // Now we update the operands.
4212 for (unsigned i = 0; i != NumOps; ++i)
4213 if (N->OperandList[i] != Ops[i])
4214 N->OperandList[i].set(Ops[i]);
4216 // If this gets put into a CSE map, add it.
4217 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4221 /// DropOperands - Release the operands and set this node to have
4223 void SDNode::DropOperands() {
4224 // Unlike the code in MorphNodeTo that does this, we don't need to
4225 // watch for dead nodes here.
4226 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4232 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4235 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4237 SDVTList VTs = getVTList(VT);
4238 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4241 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4242 EVT VT, SDValue Op1) {
4243 SDVTList VTs = getVTList(VT);
4244 SDValue Ops[] = { Op1 };
4245 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4248 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4249 EVT VT, SDValue Op1,
4251 SDVTList VTs = getVTList(VT);
4252 SDValue Ops[] = { Op1, Op2 };
4253 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4256 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4257 EVT VT, SDValue Op1,
4258 SDValue Op2, SDValue Op3) {
4259 SDVTList VTs = getVTList(VT);
4260 SDValue Ops[] = { Op1, Op2, Op3 };
4261 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4264 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4265 EVT VT, const SDValue *Ops,
4267 SDVTList VTs = getVTList(VT);
4268 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4271 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4272 EVT VT1, EVT VT2, const SDValue *Ops,
4274 SDVTList VTs = getVTList(VT1, VT2);
4275 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4278 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4280 SDVTList VTs = getVTList(VT1, VT2);
4281 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4284 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4285 EVT VT1, EVT VT2, EVT VT3,
4286 const SDValue *Ops, unsigned NumOps) {
4287 SDVTList VTs = getVTList(VT1, VT2, VT3);
4288 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4291 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4292 EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4293 const SDValue *Ops, unsigned NumOps) {
4294 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4295 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4298 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4301 SDVTList VTs = getVTList(VT1, VT2);
4302 SDValue Ops[] = { Op1 };
4303 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4306 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4308 SDValue Op1, SDValue Op2) {
4309 SDVTList VTs = getVTList(VT1, VT2);
4310 SDValue Ops[] = { Op1, Op2 };
4311 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4314 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4316 SDValue Op1, SDValue Op2,
4318 SDVTList VTs = getVTList(VT1, VT2);
4319 SDValue Ops[] = { Op1, Op2, Op3 };
4320 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4323 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4324 EVT VT1, EVT VT2, EVT VT3,
4325 SDValue Op1, SDValue Op2,
4327 SDVTList VTs = getVTList(VT1, VT2, VT3);
4328 SDValue Ops[] = { Op1, Op2, Op3 };
4329 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4332 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4333 SDVTList VTs, const SDValue *Ops,
4335 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4338 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4340 SDVTList VTs = getVTList(VT);
4341 return MorphNodeTo(N, Opc, VTs, 0, 0);
4344 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4345 EVT VT, SDValue Op1) {
4346 SDVTList VTs = getVTList(VT);
4347 SDValue Ops[] = { Op1 };
4348 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4351 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4352 EVT VT, SDValue Op1,
4354 SDVTList VTs = getVTList(VT);
4355 SDValue Ops[] = { Op1, Op2 };
4356 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4359 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4360 EVT VT, SDValue Op1,
4361 SDValue Op2, SDValue Op3) {
4362 SDVTList VTs = getVTList(VT);
4363 SDValue Ops[] = { Op1, Op2, Op3 };
4364 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4367 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4368 EVT VT, const SDValue *Ops,
4370 SDVTList VTs = getVTList(VT);
4371 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4374 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4375 EVT VT1, EVT VT2, const SDValue *Ops,
4377 SDVTList VTs = getVTList(VT1, VT2);
4378 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4381 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4383 SDVTList VTs = getVTList(VT1, VT2);
4384 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
4387 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4388 EVT VT1, EVT VT2, EVT VT3,
4389 const SDValue *Ops, unsigned NumOps) {
4390 SDVTList VTs = getVTList(VT1, VT2, VT3);
4391 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
4394 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4397 SDVTList VTs = getVTList(VT1, VT2);
4398 SDValue Ops[] = { Op1 };
4399 return MorphNodeTo(N, Opc, VTs, Ops, 1);
4402 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4404 SDValue Op1, SDValue Op2) {
4405 SDVTList VTs = getVTList(VT1, VT2);
4406 SDValue Ops[] = { Op1, Op2 };
4407 return MorphNodeTo(N, Opc, VTs, Ops, 2);
4410 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4412 SDValue Op1, SDValue Op2,
4414 SDVTList VTs = getVTList(VT1, VT2);
4415 SDValue Ops[] = { Op1, Op2, Op3 };
4416 return MorphNodeTo(N, Opc, VTs, Ops, 3);
4419 /// MorphNodeTo - These *mutate* the specified node to have the specified
4420 /// return type, opcode, and operands.
4422 /// Note that MorphNodeTo returns the resultant node. If there is already a
4423 /// node of the specified opcode and operands, it returns that node instead of
4424 /// the current one. Note that the DebugLoc need not be the same.
4426 /// Using MorphNodeTo is faster than creating a new node and swapping it in
4427 /// with ReplaceAllUsesWith both because it often avoids allocating a new
4428 /// node, and because it doesn't require CSE recalculation for any of
4429 /// the node's users.
4431 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4432 SDVTList VTs, const SDValue *Ops,
4434 // If an identical node already exists, use it.
4436 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
4437 FoldingSetNodeID ID;
4438 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4439 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4443 if (!RemoveNodeFromCSEMaps(N))
4446 // Start the morphing.
4448 N->ValueList = VTs.VTs;
4449 N->NumValues = VTs.NumVTs;
4451 // Clear the operands list, updating used nodes to remove this from their
4452 // use list. Keep track of any operands that become dead as a result.
4453 SmallPtrSet<SDNode*, 16> DeadNodeSet;
4454 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4456 SDNode *Used = Use.getNode();
4458 if (Used->use_empty())
4459 DeadNodeSet.insert(Used);
4462 // If NumOps is larger than the # of operands we currently have, reallocate
4463 // the operand list.
4464 if (NumOps > N->NumOperands) {
4465 if (N->OperandsNeedDelete)
4466 delete[] N->OperandList;
4468 if (N->isMachineOpcode()) {
4469 // We're creating a final node that will live unmorphed for the
4470 // remainder of the current SelectionDAG iteration, so we can allocate
4471 // the operands directly out of a pool with no recycling metadata.
4472 N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
4473 N->OperandsNeedDelete = false;
4475 N->OperandList = new SDUse[NumOps];
4476 N->OperandsNeedDelete = true;
4480 // Assign the new operands.
4481 N->NumOperands = NumOps;
4482 for (unsigned i = 0, e = NumOps; i != e; ++i) {
4483 N->OperandList[i].setUser(N);
4484 N->OperandList[i].setInitial(Ops[i]);
4487 // Delete any nodes that are still dead after adding the uses for the
4489 SmallVector<SDNode *, 16> DeadNodes;
4490 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4491 E = DeadNodeSet.end(); I != E; ++I)
4492 if ((*I)->use_empty())
4493 DeadNodes.push_back(*I);
4494 RemoveDeadNodes(DeadNodes);
4497 CSEMap.InsertNode(N, IP); // Memoize the new node.
4502 /// getTargetNode - These are used for target selectors to create a new node
4503 /// with specified return type(s), target opcode, and operands.
4505 /// Note that getTargetNode returns the resultant node. If there is already a
4506 /// node of the specified opcode and operands, it returns that node instead of
4507 /// the current one.
4508 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, EVT VT) {
4509 return getNode(~Opcode, dl, VT).getNode();
4512 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, EVT VT,
4514 return getNode(~Opcode, dl, VT, Op1).getNode();
4517 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, EVT VT,
4518 SDValue Op1, SDValue Op2) {
4519 return getNode(~Opcode, dl, VT, Op1, Op2).getNode();
4522 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, EVT VT,
4523 SDValue Op1, SDValue Op2,
4525 return getNode(~Opcode, dl, VT, Op1, Op2, Op3).getNode();
4528 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, EVT VT,
4529 const SDValue *Ops, unsigned NumOps) {
4530 return getNode(~Opcode, dl, VT, Ops, NumOps).getNode();
4533 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4535 SDVTList VTs = getVTList(VT1, VT2);
4537 return getNode(~Opcode, dl, VTs, &Op, 0).getNode();
4540 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4541 EVT VT2, SDValue Op1) {
4542 SDVTList VTs = getVTList(VT1, VT2);
4543 return getNode(~Opcode, dl, VTs, &Op1, 1).getNode();
4546 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4547 EVT VT2, SDValue Op1,
4549 SDVTList VTs = getVTList(VT1, VT2);
4550 SDValue Ops[] = { Op1, Op2 };
4551 return getNode(~Opcode, dl, VTs, Ops, 2).getNode();
4554 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4555 EVT VT2, SDValue Op1,
4556 SDValue Op2, SDValue Op3) {
4557 SDVTList VTs = getVTList(VT1, VT2);
4558 SDValue Ops[] = { Op1, Op2, Op3 };
4559 return getNode(~Opcode, dl, VTs, Ops, 3).getNode();
4562 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4564 const SDValue *Ops, unsigned NumOps) {
4565 SDVTList VTs = getVTList(VT1, VT2);
4566 return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode();
4569 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4570 EVT VT1, EVT VT2, EVT VT3,
4571 SDValue Op1, SDValue Op2) {
4572 SDVTList VTs = getVTList(VT1, VT2, VT3);
4573 SDValue Ops[] = { Op1, Op2 };
4574 return getNode(~Opcode, dl, VTs, Ops, 2).getNode();
4577 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4578 EVT VT1, EVT VT2, EVT VT3,
4579 SDValue Op1, SDValue Op2,
4581 SDVTList VTs = getVTList(VT1, VT2, VT3);
4582 SDValue Ops[] = { Op1, Op2, Op3 };
4583 return getNode(~Opcode, dl, VTs, Ops, 3).getNode();
4586 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4587 EVT VT1, EVT VT2, EVT VT3,
4588 const SDValue *Ops, unsigned NumOps) {
4589 SDVTList VTs = getVTList(VT1, VT2, VT3);
4590 return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode();
4593 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4594 EVT VT2, EVT VT3, EVT VT4,
4595 const SDValue *Ops, unsigned NumOps) {
4596 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4597 return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode();
4600 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
4601 const std::vector<EVT> &ResultTys,
4602 const SDValue *Ops, unsigned NumOps) {
4603 return getNode(~Opcode, dl, ResultTys, Ops, NumOps).getNode();
4606 /// getTargetExtractSubreg - A convenience function for creating
4607 /// TargetInstrInfo::EXTRACT_SUBREG nodes.
4609 SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
4611 SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4612 SDNode *Subreg = getTargetNode(TargetInstrInfo::EXTRACT_SUBREG, DL,
4613 VT, Operand, SRIdxVal);
4614 return SDValue(Subreg, 0);
4617 /// getNodeIfExists - Get the specified node if it's already available, or
4618 /// else return NULL.
4619 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4620 const SDValue *Ops, unsigned NumOps) {
4621 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4622 FoldingSetNodeID ID;
4623 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4625 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4631 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4632 /// This can cause recursive merging of nodes in the DAG.
4634 /// This version assumes From has a single result value.
4636 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4637 DAGUpdateListener *UpdateListener) {
4638 SDNode *From = FromN.getNode();
4639 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
4640 "Cannot replace with this method!");
4641 assert(From != To.getNode() && "Cannot replace uses of with self");
4643 // Iterate over all the existing uses of From. New uses will be added
4644 // to the beginning of the use list, which we avoid visiting.
4645 // This specifically avoids visiting uses of From that arise while the
4646 // replacement is happening, because any such uses would be the result
4647 // of CSE: If an existing node looks like From after one of its operands
4648 // is replaced by To, we don't want to replace of all its users with To
4649 // too. See PR3018 for more info.
4650 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4654 // This node is about to morph, remove its old self from the CSE maps.
4655 RemoveNodeFromCSEMaps(User);
4657 // A user can appear in a use list multiple times, and when this
4658 // happens the uses are usually next to each other in the list.
4659 // To help reduce the number of CSE recomputations, process all
4660 // the uses of this user that we can find this way.
4662 SDUse &Use = UI.getUse();
4665 } while (UI != UE && *UI == User);
4667 // Now that we have modified User, add it back to the CSE maps. If it
4668 // already exists there, recursively merge the results together.
4669 AddModifiedNodeToCSEMaps(User, UpdateListener);
4673 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4674 /// This can cause recursive merging of nodes in the DAG.
4676 /// This version assumes that for each value of From, there is a
4677 /// corresponding value in To in the same position with the same type.
4679 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4680 DAGUpdateListener *UpdateListener) {
4682 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
4683 assert((!From->hasAnyUseOfValue(i) ||
4684 From->getValueType(i) == To->getValueType(i)) &&
4685 "Cannot use this version of ReplaceAllUsesWith!");
4688 // Handle the trivial case.
4692 // Iterate over just the existing users of From. See the comments in
4693 // the ReplaceAllUsesWith above.
4694 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4698 // This node is about to morph, remove its old self from the CSE maps.
4699 RemoveNodeFromCSEMaps(User);
4701 // A user can appear in a use list multiple times, and when this
4702 // happens the uses are usually next to each other in the list.
4703 // To help reduce the number of CSE recomputations, process all
4704 // the uses of this user that we can find this way.
4706 SDUse &Use = UI.getUse();
4709 } while (UI != UE && *UI == User);
4711 // Now that we have modified User, add it back to the CSE maps. If it
4712 // already exists there, recursively merge the results together.
4713 AddModifiedNodeToCSEMaps(User, UpdateListener);
4717 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4718 /// This can cause recursive merging of nodes in the DAG.
4720 /// This version can replace From with any result values. To must match the
4721 /// number and types of values returned by From.
4722 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4724 DAGUpdateListener *UpdateListener) {
4725 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4726 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4728 // Iterate over just the existing users of From. See the comments in
4729 // the ReplaceAllUsesWith above.
4730 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
4734 // This node is about to morph, remove its old self from the CSE maps.
4735 RemoveNodeFromCSEMaps(User);
4737 // A user can appear in a use list multiple times, and when this
4738 // happens the uses are usually next to each other in the list.
4739 // To help reduce the number of CSE recomputations, process all
4740 // the uses of this user that we can find this way.
4742 SDUse &Use = UI.getUse();
4743 const SDValue &ToOp = To[Use.getResNo()];
4746 } while (UI != UE && *UI == User);
4748 // Now that we have modified User, add it back to the CSE maps. If it
4749 // already exists there, recursively merge the results together.
4750 AddModifiedNodeToCSEMaps(User, UpdateListener);
4754 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4755 /// uses of other values produced by From.getNode() alone. The Deleted
4756 /// vector is handled the same way as for ReplaceAllUsesWith.
4757 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4758 DAGUpdateListener *UpdateListener){
4759 // Handle the really simple, really trivial case efficiently.
4760 if (From == To) return;
4762 // Handle the simple, trivial, case efficiently.
4763 if (From.getNode()->getNumValues() == 1) {
4764 ReplaceAllUsesWith(From, To, UpdateListener);
4768 // Iterate over just the existing users of From. See the comments in
4769 // the ReplaceAllUsesWith above.
4770 SDNode::use_iterator UI = From.getNode()->use_begin(),
4771 UE = From.getNode()->use_end();
4774 bool UserRemovedFromCSEMaps = false;
4776 // A user can appear in a use list multiple times, and when this
4777 // happens the uses are usually next to each other in the list.
4778 // To help reduce the number of CSE recomputations, process all
4779 // the uses of this user that we can find this way.
4781 SDUse &Use = UI.getUse();
4783 // Skip uses of different values from the same node.
4784 if (Use.getResNo() != From.getResNo()) {
4789 // If this node hasn't been modified yet, it's still in the CSE maps,
4790 // so remove its old self from the CSE maps.
4791 if (!UserRemovedFromCSEMaps) {
4792 RemoveNodeFromCSEMaps(User);
4793 UserRemovedFromCSEMaps = true;
4798 } while (UI != UE && *UI == User);
4800 // We are iterating over all uses of the From node, so if a use
4801 // doesn't use the specific value, no changes are made.
4802 if (!UserRemovedFromCSEMaps)
4805 // Now that we have modified User, add it back to the CSE maps. If it
4806 // already exists there, recursively merge the results together.
4807 AddModifiedNodeToCSEMaps(User, UpdateListener);
4812 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
4813 /// to record information about a use.
4820 /// operator< - Sort Memos by User.
4821 bool operator<(const UseMemo &L, const UseMemo &R) {
4822 return (intptr_t)L.User < (intptr_t)R.User;
4826 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
4827 /// uses of other values produced by From.getNode() alone. The same value
4828 /// may appear in both the From and To list. The Deleted vector is
4829 /// handled the same way as for ReplaceAllUsesWith.
4830 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
4833 DAGUpdateListener *UpdateListener){
4834 // Handle the simple, trivial case efficiently.
4836 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
4838 // Read up all the uses and make records of them. This helps
4839 // processing new uses that are introduced during the
4840 // replacement process.
4841 SmallVector<UseMemo, 4> Uses;
4842 for (unsigned i = 0; i != Num; ++i) {
4843 unsigned FromResNo = From[i].getResNo();
4844 SDNode *FromNode = From[i].getNode();
4845 for (SDNode::use_iterator UI = FromNode->use_begin(),
4846 E = FromNode->use_end(); UI != E; ++UI) {
4847 SDUse &Use = UI.getUse();
4848 if (Use.getResNo() == FromResNo) {
4849 UseMemo Memo = { *UI, i, &Use };
4850 Uses.push_back(Memo);
4855 // Sort the uses, so that all the uses from a given User are together.
4856 std::sort(Uses.begin(), Uses.end());
4858 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
4859 UseIndex != UseIndexEnd; ) {
4860 // We know that this user uses some value of From. If it is the right
4861 // value, update it.
4862 SDNode *User = Uses[UseIndex].User;
4864 // This node is about to morph, remove its old self from the CSE maps.
4865 RemoveNodeFromCSEMaps(User);
4867 // The Uses array is sorted, so all the uses for a given User
4868 // are next to each other in the list.
4869 // To help reduce the number of CSE recomputations, process all
4870 // the uses of this user that we can find this way.
4872 unsigned i = Uses[UseIndex].Index;
4873 SDUse &Use = *Uses[UseIndex].Use;
4877 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
4879 // Now that we have modified User, add it back to the CSE maps. If it
4880 // already exists there, recursively merge the results together.
4881 AddModifiedNodeToCSEMaps(User, UpdateListener);
4885 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4886 /// based on their topological order. It returns the maximum id and a vector
4887 /// of the SDNodes* in assigned order by reference.
4888 unsigned SelectionDAG::AssignTopologicalOrder() {
4890 unsigned DAGSize = 0;
4892 // SortedPos tracks the progress of the algorithm. Nodes before it are
4893 // sorted, nodes after it are unsorted. When the algorithm completes
4894 // it is at the end of the list.
4895 allnodes_iterator SortedPos = allnodes_begin();
4897 // Visit all the nodes. Move nodes with no operands to the front of
4898 // the list immediately. Annotate nodes that do have operands with their
4899 // operand count. Before we do this, the Node Id fields of the nodes
4900 // may contain arbitrary values. After, the Node Id fields for nodes
4901 // before SortedPos will contain the topological sort index, and the
4902 // Node Id fields for nodes At SortedPos and after will contain the
4903 // count of outstanding operands.
4904 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
4906 unsigned Degree = N->getNumOperands();
4908 // A node with no uses, add it to the result array immediately.
4909 N->setNodeId(DAGSize++);
4910 allnodes_iterator Q = N;
4912 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
4915 // Temporarily use the Node Id as scratch space for the degree count.
4916 N->setNodeId(Degree);
4920 // Visit all the nodes. As we iterate, moves nodes into sorted order,
4921 // such that by the time the end is reached all nodes will be sorted.
4922 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
4924 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4927 unsigned Degree = P->getNodeId();
4930 // All of P's operands are sorted, so P may sorted now.
4931 P->setNodeId(DAGSize++);
4933 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
4936 // Update P's outstanding operand count.
4937 P->setNodeId(Degree);
4942 assert(SortedPos == AllNodes.end() &&
4943 "Topological sort incomplete!");
4944 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
4945 "First node in topological sort is not the entry token!");
4946 assert(AllNodes.front().getNodeId() == 0 &&
4947 "First node in topological sort has non-zero id!");
4948 assert(AllNodes.front().getNumOperands() == 0 &&
4949 "First node in topological sort has operands!");
4950 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
4951 "Last node in topologic sort has unexpected id!");
4952 assert(AllNodes.back().use_empty() &&
4953 "Last node in topologic sort has users!");
4954 assert(DAGSize == allnodes_size() && "Node count mismatch!");
4960 //===----------------------------------------------------------------------===//
4962 //===----------------------------------------------------------------------===//
4964 HandleSDNode::~HandleSDNode() {
4968 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA,
4969 EVT VT, int64_t o, unsigned char TF)
4970 : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)),
4971 Offset(o), TargetFlags(TF) {
4972 TheGlobal = const_cast<GlobalValue*>(GA);
4975 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
4976 const Value *srcValue, int SVO, unsigned alignment,
4978 : SDNode(Opc, dl, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
4979 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
4980 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4981 assert(getOriginalAlignment() == alignment && "Alignment encoding error!");
4982 assert(isVolatile() == vol && "Volatile encoding error!");
4985 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
4986 const SDValue *Ops, unsigned NumOps, EVT memvt,
4987 const Value *srcValue, int SVO, unsigned alignment,
4989 : SDNode(Opc, dl, VTs, Ops, NumOps),
4990 MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
4991 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
4992 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4993 assert(getOriginalAlignment() == alignment && "Alignment encoding error!");
4994 assert(isVolatile() == vol && "Volatile encoding error!");
4997 /// getMemOperand - Return a MachineMemOperand object describing the memory
4998 /// reference performed by this memory reference.
4999 MachineMemOperand MemSDNode::getMemOperand() const {
5001 if (isa<LoadSDNode>(this))
5002 Flags = MachineMemOperand::MOLoad;
5003 else if (isa<StoreSDNode>(this))
5004 Flags = MachineMemOperand::MOStore;
5005 else if (isa<AtomicSDNode>(this)) {
5006 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
5009 const MemIntrinsicSDNode* MemIntrinNode = dyn_cast<MemIntrinsicSDNode>(this);
5010 assert(MemIntrinNode && "Unknown MemSDNode opcode!");
5011 if (MemIntrinNode->readMem()) Flags |= MachineMemOperand::MOLoad;
5012 if (MemIntrinNode->writeMem()) Flags |= MachineMemOperand::MOStore;
5015 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
5016 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
5018 // Check if the memory reference references a frame index
5019 const FrameIndexSDNode *FI =
5020 dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
5021 if (!getSrcValue() && FI)
5022 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
5023 Flags, 0, Size, getAlignment());
5025 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
5026 Size, getAlignment());
5029 /// Profile - Gather unique data for the node.
5031 void SDNode::Profile(FoldingSetNodeID &ID) const {
5032 AddNodeIDNode(ID, this);
5037 std::vector<EVT> VTs;
5040 VTs.reserve(MVT::LAST_VALUETYPE);
5041 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5042 VTs.push_back(MVT((MVT::SimpleValueType)i));
5047 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5048 static ManagedStatic<EVTArray> SimpleVTArray;
5049 static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5051 /// getValueTypeList - Return a pointer to the specified value type.
5053 const EVT *SDNode::getValueTypeList(EVT VT) {
5054 if (VT.isExtended()) {
5055 sys::SmartScopedLock<true> Lock(*VTMutex);
5056 return &(*EVTs->insert(VT).first);
5058 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5062 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5063 /// indicated value. This method ignores uses of other values defined by this
5065 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5066 assert(Value < getNumValues() && "Bad value!");
5068 // TODO: Only iterate over uses of a given value of the node
5069 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5070 if (UI.getUse().getResNo() == Value) {
5077 // Found exactly the right number of uses?
5082 /// hasAnyUseOfValue - Return true if there are any use of the indicated
5083 /// value. This method ignores uses of other values defined by this operation.
5084 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5085 assert(Value < getNumValues() && "Bad value!");
5087 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5088 if (UI.getUse().getResNo() == Value)
5095 /// isOnlyUserOf - Return true if this node is the only use of N.
5097 bool SDNode::isOnlyUserOf(SDNode *N) const {
5099 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5110 /// isOperand - Return true if this node is an operand of N.
5112 bool SDValue::isOperandOf(SDNode *N) const {
5113 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5114 if (*this == N->getOperand(i))
5119 bool SDNode::isOperandOf(SDNode *N) const {
5120 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5121 if (this == N->OperandList[i].getNode())
5126 /// reachesChainWithoutSideEffects - Return true if this operand (which must
5127 /// be a chain) reaches the specified operand without crossing any
5128 /// side-effecting instructions. In practice, this looks through token
5129 /// factors and non-volatile loads. In order to remain efficient, this only
5130 /// looks a couple of nodes in, it does not do an exhaustive search.
5131 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5132 unsigned Depth) const {
5133 if (*this == Dest) return true;
5135 // Don't search too deeply, we just want to be able to see through
5136 // TokenFactor's etc.
5137 if (Depth == 0) return false;
5139 // If this is a token factor, all inputs to the TF happen in parallel. If any
5140 // of the operands of the TF reach dest, then we can do the xform.
5141 if (getOpcode() == ISD::TokenFactor) {
5142 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5143 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5148 // Loads don't have side effects, look through them.
5149 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5150 if (!Ld->isVolatile())
5151 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5157 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
5158 SmallPtrSet<SDNode *, 32> &Visited) {
5159 if (found || !Visited.insert(N))
5162 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
5163 SDNode *Op = N->getOperand(i).getNode();
5168 findPredecessor(Op, P, found, Visited);
5172 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
5173 /// is either an operand of N or it can be reached by recursively traversing
5174 /// up the operands.
5175 /// NOTE: this is an expensive method. Use it carefully.
5176 bool SDNode::isPredecessorOf(SDNode *N) const {
5177 SmallPtrSet<SDNode *, 32> Visited;
5179 findPredecessor(N, this, found, Visited);
5183 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5184 assert(Num < NumOperands && "Invalid child # of SDNode!");
5185 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5188 std::string SDNode::getOperationName(const SelectionDAG *G) const {
5189 switch (getOpcode()) {
5191 if (getOpcode() < ISD::BUILTIN_OP_END)
5192 return "<<Unknown DAG Node>>";
5193 if (isMachineOpcode()) {
5195 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5196 if (getMachineOpcode() < TII->getNumOpcodes())
5197 return TII->get(getMachineOpcode()).getName();
5198 return "<<Unknown Machine Node>>";
5201 const TargetLowering &TLI = G->getTargetLoweringInfo();
5202 const char *Name = TLI.getTargetNodeName(getOpcode());
5203 if (Name) return Name;
5204 return "<<Unknown Target Node>>";
5206 return "<<Unknown Node>>";
5209 case ISD::DELETED_NODE:
5210 return "<<Deleted Node!>>";
5212 case ISD::PREFETCH: return "Prefetch";
5213 case ISD::MEMBARRIER: return "MemBarrier";
5214 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
5215 case ISD::ATOMIC_SWAP: return "AtomicSwap";
5216 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
5217 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
5218 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
5219 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
5220 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
5221 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
5222 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
5223 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
5224 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
5225 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
5226 case ISD::PCMARKER: return "PCMarker";
5227 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5228 case ISD::SRCVALUE: return "SrcValue";
5229 case ISD::MEMOPERAND: return "MemOperand";
5230 case ISD::EntryToken: return "EntryToken";
5231 case ISD::TokenFactor: return "TokenFactor";
5232 case ISD::AssertSext: return "AssertSext";
5233 case ISD::AssertZext: return "AssertZext";
5235 case ISD::BasicBlock: return "BasicBlock";
5236 case ISD::VALUETYPE: return "ValueType";
5237 case ISD::Register: return "Register";
5239 case ISD::Constant: return "Constant";
5240 case ISD::ConstantFP: return "ConstantFP";
5241 case ISD::GlobalAddress: return "GlobalAddress";
5242 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5243 case ISD::FrameIndex: return "FrameIndex";
5244 case ISD::JumpTable: return "JumpTable";
5245 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5246 case ISD::RETURNADDR: return "RETURNADDR";
5247 case ISD::FRAMEADDR: return "FRAMEADDR";
5248 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5249 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5250 case ISD::LSDAADDR: return "LSDAADDR";
5251 case ISD::EHSELECTION: return "EHSELECTION";
5252 case ISD::EH_RETURN: return "EH_RETURN";
5253 case ISD::ConstantPool: return "ConstantPool";
5254 case ISD::ExternalSymbol: return "ExternalSymbol";
5255 case ISD::INTRINSIC_WO_CHAIN: {
5256 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
5257 return Intrinsic::getName((Intrinsic::ID)IID);
5259 case ISD::INTRINSIC_VOID:
5260 case ISD::INTRINSIC_W_CHAIN: {
5261 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
5262 return Intrinsic::getName((Intrinsic::ID)IID);
5265 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
5266 case ISD::TargetConstant: return "TargetConstant";
5267 case ISD::TargetConstantFP:return "TargetConstantFP";
5268 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5269 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5270 case ISD::TargetFrameIndex: return "TargetFrameIndex";
5271 case ISD::TargetJumpTable: return "TargetJumpTable";
5272 case ISD::TargetConstantPool: return "TargetConstantPool";
5273 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5275 case ISD::CopyToReg: return "CopyToReg";
5276 case ISD::CopyFromReg: return "CopyFromReg";
5277 case ISD::UNDEF: return "undef";
5278 case ISD::MERGE_VALUES: return "merge_values";
5279 case ISD::INLINEASM: return "inlineasm";
5280 case ISD::DBG_LABEL: return "dbg_label";
5281 case ISD::EH_LABEL: return "eh_label";
5282 case ISD::HANDLENODE: return "handlenode";
5285 case ISD::FABS: return "fabs";
5286 case ISD::FNEG: return "fneg";
5287 case ISD::FSQRT: return "fsqrt";
5288 case ISD::FSIN: return "fsin";
5289 case ISD::FCOS: return "fcos";
5290 case ISD::FPOWI: return "fpowi";
5291 case ISD::FPOW: return "fpow";
5292 case ISD::FTRUNC: return "ftrunc";
5293 case ISD::FFLOOR: return "ffloor";
5294 case ISD::FCEIL: return "fceil";
5295 case ISD::FRINT: return "frint";
5296 case ISD::FNEARBYINT: return "fnearbyint";
5299 case ISD::ADD: return "add";
5300 case ISD::SUB: return "sub";
5301 case ISD::MUL: return "mul";
5302 case ISD::MULHU: return "mulhu";
5303 case ISD::MULHS: return "mulhs";
5304 case ISD::SDIV: return "sdiv";
5305 case ISD::UDIV: return "udiv";
5306 case ISD::SREM: return "srem";
5307 case ISD::UREM: return "urem";
5308 case ISD::SMUL_LOHI: return "smul_lohi";
5309 case ISD::UMUL_LOHI: return "umul_lohi";
5310 case ISD::SDIVREM: return "sdivrem";
5311 case ISD::UDIVREM: return "udivrem";
5312 case ISD::AND: return "and";
5313 case ISD::OR: return "or";
5314 case ISD::XOR: return "xor";
5315 case ISD::SHL: return "shl";
5316 case ISD::SRA: return "sra";
5317 case ISD::SRL: return "srl";
5318 case ISD::ROTL: return "rotl";
5319 case ISD::ROTR: return "rotr";
5320 case ISD::FADD: return "fadd";
5321 case ISD::FSUB: return "fsub";
5322 case ISD::FMUL: return "fmul";
5323 case ISD::FDIV: return "fdiv";
5324 case ISD::FREM: return "frem";
5325 case ISD::FCOPYSIGN: return "fcopysign";
5326 case ISD::FGETSIGN: return "fgetsign";
5328 case ISD::SETCC: return "setcc";
5329 case ISD::VSETCC: return "vsetcc";
5330 case ISD::SELECT: return "select";
5331 case ISD::SELECT_CC: return "select_cc";
5332 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
5333 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
5334 case ISD::CONCAT_VECTORS: return "concat_vectors";
5335 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
5336 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
5337 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
5338 case ISD::CARRY_FALSE: return "carry_false";
5339 case ISD::ADDC: return "addc";
5340 case ISD::ADDE: return "adde";
5341 case ISD::SADDO: return "saddo";
5342 case ISD::UADDO: return "uaddo";
5343 case ISD::SSUBO: return "ssubo";
5344 case ISD::USUBO: return "usubo";
5345 case ISD::SMULO: return "smulo";
5346 case ISD::UMULO: return "umulo";
5347 case ISD::SUBC: return "subc";
5348 case ISD::SUBE: return "sube";
5349 case ISD::SHL_PARTS: return "shl_parts";
5350 case ISD::SRA_PARTS: return "sra_parts";
5351 case ISD::SRL_PARTS: return "srl_parts";
5353 // Conversion operators.
5354 case ISD::SIGN_EXTEND: return "sign_extend";
5355 case ISD::ZERO_EXTEND: return "zero_extend";
5356 case ISD::ANY_EXTEND: return "any_extend";
5357 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5358 case ISD::TRUNCATE: return "truncate";
5359 case ISD::FP_ROUND: return "fp_round";
5360 case ISD::FLT_ROUNDS_: return "flt_rounds";
5361 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5362 case ISD::FP_EXTEND: return "fp_extend";
5364 case ISD::SINT_TO_FP: return "sint_to_fp";
5365 case ISD::UINT_TO_FP: return "uint_to_fp";
5366 case ISD::FP_TO_SINT: return "fp_to_sint";
5367 case ISD::FP_TO_UINT: return "fp_to_uint";
5368 case ISD::BIT_CONVERT: return "bit_convert";
5370 case ISD::CONVERT_RNDSAT: {
5371 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5372 default: llvm_unreachable("Unknown cvt code!");
5373 case ISD::CVT_FF: return "cvt_ff";
5374 case ISD::CVT_FS: return "cvt_fs";
5375 case ISD::CVT_FU: return "cvt_fu";
5376 case ISD::CVT_SF: return "cvt_sf";
5377 case ISD::CVT_UF: return "cvt_uf";
5378 case ISD::CVT_SS: return "cvt_ss";
5379 case ISD::CVT_SU: return "cvt_su";
5380 case ISD::CVT_US: return "cvt_us";
5381 case ISD::CVT_UU: return "cvt_uu";
5385 // Control flow instructions
5386 case ISD::BR: return "br";
5387 case ISD::BRIND: return "brind";
5388 case ISD::BR_JT: return "br_jt";
5389 case ISD::BRCOND: return "brcond";
5390 case ISD::BR_CC: return "br_cc";
5391 case ISD::CALLSEQ_START: return "callseq_start";
5392 case ISD::CALLSEQ_END: return "callseq_end";
5395 case ISD::LOAD: return "load";
5396 case ISD::STORE: return "store";
5397 case ISD::VAARG: return "vaarg";
5398 case ISD::VACOPY: return "vacopy";
5399 case ISD::VAEND: return "vaend";
5400 case ISD::VASTART: return "vastart";
5401 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5402 case ISD::EXTRACT_ELEMENT: return "extract_element";
5403 case ISD::BUILD_PAIR: return "build_pair";
5404 case ISD::STACKSAVE: return "stacksave";
5405 case ISD::STACKRESTORE: return "stackrestore";
5406 case ISD::TRAP: return "trap";
5409 case ISD::BSWAP: return "bswap";
5410 case ISD::CTPOP: return "ctpop";
5411 case ISD::CTTZ: return "cttz";
5412 case ISD::CTLZ: return "ctlz";
5415 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
5416 case ISD::DEBUG_LOC: return "debug_loc";
5419 case ISD::TRAMPOLINE: return "trampoline";
5422 switch (cast<CondCodeSDNode>(this)->get()) {
5423 default: llvm_unreachable("Unknown setcc condition!");
5424 case ISD::SETOEQ: return "setoeq";
5425 case ISD::SETOGT: return "setogt";
5426 case ISD::SETOGE: return "setoge";
5427 case ISD::SETOLT: return "setolt";
5428 case ISD::SETOLE: return "setole";
5429 case ISD::SETONE: return "setone";
5431 case ISD::SETO: return "seto";
5432 case ISD::SETUO: return "setuo";
5433 case ISD::SETUEQ: return "setue";
5434 case ISD::SETUGT: return "setugt";
5435 case ISD::SETUGE: return "setuge";
5436 case ISD::SETULT: return "setult";
5437 case ISD::SETULE: return "setule";
5438 case ISD::SETUNE: return "setune";
5440 case ISD::SETEQ: return "seteq";
5441 case ISD::SETGT: return "setgt";
5442 case ISD::SETGE: return "setge";
5443 case ISD::SETLT: return "setlt";
5444 case ISD::SETLE: return "setle";
5445 case ISD::SETNE: return "setne";
5450 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5459 return "<post-inc>";
5461 return "<post-dec>";
5465 std::string ISD::ArgFlagsTy::getArgFlagsString() {
5466 std::string S = "< ";
5480 if (getByValAlign())
5481 S += "byval-align:" + utostr(getByValAlign()) + " ";
5483 S += "orig-align:" + utostr(getOrigAlign()) + " ";
5485 S += "byval-size:" + utostr(getByValSize()) + " ";
5489 void SDNode::dump() const { dump(0); }
5490 void SDNode::dump(const SelectionDAG *G) const {
5494 void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
5495 OS << (void*)this << ": ";
5497 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5499 if (getValueType(i) == MVT::Other)
5502 OS << getValueType(i).getEVTString();
5504 OS << " = " << getOperationName(G);
5507 void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
5508 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
5509 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(this);
5511 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
5512 int Idx = SVN->getMaskElt(i);
5522 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5523 OS << '<' << CSDN->getAPIntValue() << '>';
5524 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5525 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5526 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5527 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5528 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5531 CSDN->getValueAPF().bitcastToAPInt().dump();
5534 } else if (const GlobalAddressSDNode *GADN =
5535 dyn_cast<GlobalAddressSDNode>(this)) {
5536 int64_t offset = GADN->getOffset();
5538 WriteAsOperand(OS, GADN->getGlobal());
5541 OS << " + " << offset;
5543 OS << " " << offset;
5544 if (unsigned int TF = GADN->getTargetFlags())
5545 OS << " [TF=" << TF << ']';
5546 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5547 OS << "<" << FIDN->getIndex() << ">";
5548 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5549 OS << "<" << JTDN->getIndex() << ">";
5550 if (unsigned int TF = JTDN->getTargetFlags())
5551 OS << " [TF=" << TF << ']';
5552 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5553 int offset = CP->getOffset();
5554 if (CP->isMachineConstantPoolEntry())
5555 OS << "<" << *CP->getMachineCPVal() << ">";
5557 OS << "<" << *CP->getConstVal() << ">";
5559 OS << " + " << offset;
5561 OS << " " << offset;
5562 if (unsigned int TF = CP->getTargetFlags())
5563 OS << " [TF=" << TF << ']';
5564 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5566 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5568 OS << LBB->getName() << " ";
5569 OS << (const void*)BBDN->getBasicBlock() << ">";
5570 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5571 if (G && R->getReg() &&
5572 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5573 OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5575 OS << " #" << R->getReg();
5577 } else if (const ExternalSymbolSDNode *ES =
5578 dyn_cast<ExternalSymbolSDNode>(this)) {
5579 OS << "'" << ES->getSymbol() << "'";
5580 if (unsigned int TF = ES->getTargetFlags())
5581 OS << " [TF=" << TF << ']';
5582 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5584 OS << "<" << M->getValue() << ">";
5587 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5588 if (M->MO.getValue())
5589 OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5591 OS << "<null:" << M->MO.getOffset() << ">";
5592 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5593 OS << ":" << N->getVT().getEVTString();
5595 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5596 const Value *SrcValue = LD->getSrcValue();
5597 int SrcOffset = LD->getSrcValueOffset();
5603 OS << ":" << SrcOffset << ">";
5606 switch (LD->getExtensionType()) {
5607 default: doExt = false; break;
5608 case ISD::EXTLOAD: OS << " <anyext "; break;
5609 case ISD::SEXTLOAD: OS << " <sext "; break;
5610 case ISD::ZEXTLOAD: OS << " <zext "; break;
5613 OS << LD->getMemoryVT().getEVTString() << ">";
5615 const char *AM = getIndexedModeName(LD->getAddressingMode());
5618 if (LD->isVolatile())
5619 OS << " <volatile>";
5620 OS << " alignment=" << LD->getAlignment();
5621 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5622 const Value *SrcValue = ST->getSrcValue();
5623 int SrcOffset = ST->getSrcValueOffset();
5629 OS << ":" << SrcOffset << ">";
5631 if (ST->isTruncatingStore())
5632 OS << " <trunc " << ST->getMemoryVT().getEVTString() << ">";
5634 const char *AM = getIndexedModeName(ST->getAddressingMode());
5637 if (ST->isVolatile())
5638 OS << " <volatile>";
5639 OS << " alignment=" << ST->getAlignment();
5640 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5641 const Value *SrcValue = AT->getSrcValue();
5642 int SrcOffset = AT->getSrcValueOffset();
5648 OS << ":" << SrcOffset << ">";
5649 if (AT->isVolatile())
5650 OS << " <volatile>";
5651 OS << " alignment=" << AT->getAlignment();
5655 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
5658 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
5660 OS << (void*)getOperand(i).getNode();
5661 if (unsigned RN = getOperand(i).getResNo())
5664 print_details(OS, G);
5667 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5668 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5669 if (N->getOperand(i).getNode()->hasOneUse())
5670 DumpNodes(N->getOperand(i).getNode(), indent+2, G);
5672 errs() << "\n" << std::string(indent+2, ' ')
5673 << (void*)N->getOperand(i).getNode() << ": <multiple use>";
5677 errs().indent(indent);
5681 void SelectionDAG::dump() const {
5682 errs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
5684 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5686 const SDNode *N = I;
5687 if (!N->hasOneUse() && N != getRoot().getNode())
5688 DumpNodes(N, 2, this);
5691 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
5696 void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
5698 print_details(OS, G);
5701 typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
5702 static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
5703 const SelectionDAG *G, VisitedSDNodeSet &once) {
5704 if (!once.insert(N)) // If we've been here before, return now.
5706 // Dump the current SDNode, but don't end the line yet.
5707 OS << std::string(indent, ' ');
5709 // Having printed this SDNode, walk the children:
5710 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5711 const SDNode *child = N->getOperand(i).getNode();
5714 if (child->getNumOperands() == 0) {
5715 // This child has no grandchildren; print it inline right here.
5716 child->printr(OS, G);
5718 } else { // Just the address. FIXME: also print the child's opcode
5720 if (unsigned RN = N->getOperand(i).getResNo())
5725 // Dump children that have grandchildren on their own line(s).
5726 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5727 const SDNode *child = N->getOperand(i).getNode();
5728 DumpNodesr(OS, child, indent+2, G, once);
5732 void SDNode::dumpr() const {
5733 VisitedSDNodeSet once;
5734 DumpNodesr(errs(), this, 0, 0, once);
5738 // getAddressSpace - Return the address space this GlobalAddress belongs to.
5739 unsigned GlobalAddressSDNode::getAddressSpace() const {
5740 return getGlobal()->getType()->getAddressSpace();
5744 const Type *ConstantPoolSDNode::getType() const {
5745 if (isMachineConstantPoolEntry())
5746 return Val.MachineCPVal->getType();
5747 return Val.ConstVal->getType();
5750 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
5752 unsigned &SplatBitSize,
5754 unsigned MinSplatBits) {
5755 EVT VT = getValueType(0);
5756 assert(VT.isVector() && "Expected a vector type");
5757 unsigned sz = VT.getSizeInBits();
5758 if (MinSplatBits > sz)
5761 SplatValue = APInt(sz, 0);
5762 SplatUndef = APInt(sz, 0);
5764 // Get the bits. Bits with undefined values (when the corresponding element
5765 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
5766 // in SplatValue. If any of the values are not constant, give up and return
5768 unsigned int nOps = getNumOperands();
5769 assert(nOps > 0 && "isConstantSplat has 0-size build vector");
5770 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
5771 for (unsigned i = 0; i < nOps; ++i) {
5772 SDValue OpVal = getOperand(i);
5773 unsigned BitPos = i * EltBitSize;
5775 if (OpVal.getOpcode() == ISD::UNDEF)
5776 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos +EltBitSize);
5777 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
5778 SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
5779 zextOrTrunc(sz) << BitPos);
5780 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
5781 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
5786 // The build_vector is all constants or undefs. Find the smallest element
5787 // size that splats the vector.
5789 HasAnyUndefs = (SplatUndef != 0);
5792 unsigned HalfSize = sz / 2;
5793 APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
5794 APInt LowValue = APInt(SplatValue).trunc(HalfSize);
5795 APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
5796 APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
5798 // If the two halves do not match (ignoring undef bits), stop here.
5799 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
5800 MinSplatBits > HalfSize)
5803 SplatValue = HighValue | LowValue;
5804 SplatUndef = HighUndef & LowUndef;
5813 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
5814 // Find the first non-undef value in the shuffle mask.
5816 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
5819 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
5821 // Make sure all remaining elements are either undef or the same as the first
5823 for (int Idx = Mask[i]; i != e; ++i)
5824 if (Mask[i] >= 0 && Mask[i] != Idx)