1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/GlobalAlias.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/StringExtras.h"
42 /// makeVTList - Return an instance of the SDVTList struct initialized with the
43 /// specified members.
44 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
45 SDVTList Res = {VTs, NumVTs};
49 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
50 switch (VT.getSimpleVT()) {
51 default: assert(0 && "Unknown FP format");
52 case MVT::f32: return &APFloat::IEEEsingle;
53 case MVT::f64: return &APFloat::IEEEdouble;
54 case MVT::f80: return &APFloat::x87DoubleExtended;
55 case MVT::f128: return &APFloat::IEEEquad;
56 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
60 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
62 //===----------------------------------------------------------------------===//
63 // ConstantFPSDNode Class
64 //===----------------------------------------------------------------------===//
66 /// isExactlyValue - We don't rely on operator== working on double values, as
67 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
68 /// As such, this method can be used to do an exact bit-for-bit comparison of
69 /// two floating point values.
70 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
71 return Value.bitwiseIsEqual(V);
74 bool ConstantFPSDNode::isValueValidForType(MVT VT,
76 assert(VT.isFloatingPoint() && "Can only convert between FP types");
78 // PPC long double cannot be converted to any other type.
79 if (VT == MVT::ppcf128 ||
80 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
83 // convert modifies in place, so make a copy.
84 APFloat Val2 = APFloat(Val);
85 return Val2.convert(*MVTToAPFloatSemantics(VT),
86 APFloat::rmNearestTiesToEven) == APFloat::opOK;
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 /// isBuildVectorAllOnes - Return true if the specified node is a
94 /// BUILD_VECTOR where all of the elements are ~0 or undef.
95 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
96 // Look through a bit convert.
97 if (N->getOpcode() == ISD::BIT_CONVERT)
98 N = N->getOperand(0).Val;
100 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
102 unsigned i = 0, e = N->getNumOperands();
104 // Skip over all of the undef values.
105 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
108 // Do not accept an all-undef vector.
109 if (i == e) return false;
111 // Do not accept build_vectors that aren't all constants or which have non-~0
113 SDOperand NotZero = N->getOperand(i);
114 if (isa<ConstantSDNode>(NotZero)) {
115 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
117 } else if (isa<ConstantFPSDNode>(NotZero)) {
118 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
119 convertToAPInt().isAllOnesValue())
124 // Okay, we have at least one ~0 value, check to see if the rest match or are
126 for (++i; i != e; ++i)
127 if (N->getOperand(i) != NotZero &&
128 N->getOperand(i).getOpcode() != ISD::UNDEF)
134 /// isBuildVectorAllZeros - Return true if the specified node is a
135 /// BUILD_VECTOR where all of the elements are 0 or undef.
136 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
137 // Look through a bit convert.
138 if (N->getOpcode() == ISD::BIT_CONVERT)
139 N = N->getOperand(0).Val;
141 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
143 unsigned i = 0, e = N->getNumOperands();
145 // Skip over all of the undef values.
146 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
149 // Do not accept an all-undef vector.
150 if (i == e) return false;
152 // Do not accept build_vectors that aren't all constants or which have non-~0
154 SDOperand Zero = N->getOperand(i);
155 if (isa<ConstantSDNode>(Zero)) {
156 if (!cast<ConstantSDNode>(Zero)->isNullValue())
158 } else if (isa<ConstantFPSDNode>(Zero)) {
159 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
164 // Okay, we have at least one ~0 value, check to see if the rest match or are
166 for (++i; i != e; ++i)
167 if (N->getOperand(i) != Zero &&
168 N->getOperand(i).getOpcode() != ISD::UNDEF)
173 /// isScalarToVector - Return true if the specified node is a
174 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
175 /// element is not an undef.
176 bool ISD::isScalarToVector(const SDNode *N) {
177 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
180 if (N->getOpcode() != ISD::BUILD_VECTOR)
182 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
184 unsigned NumElems = N->getNumOperands();
185 for (unsigned i = 1; i < NumElems; ++i) {
186 SDOperand V = N->getOperand(i);
187 if (V.getOpcode() != ISD::UNDEF)
194 /// isDebugLabel - Return true if the specified node represents a debug
195 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
196 bool ISD::isDebugLabel(const SDNode *N) {
198 if (N->getOpcode() == ISD::DBG_LABEL)
200 if (N->isTargetOpcode() &&
201 N->getTargetOpcode() == TargetInstrInfo::DBG_LABEL)
206 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
207 /// when given the operation for (X op Y).
208 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
209 // To perform this operation, we just need to swap the L and G bits of the
211 unsigned OldL = (Operation >> 2) & 1;
212 unsigned OldG = (Operation >> 1) & 1;
213 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
214 (OldL << 1) | // New G bit
215 (OldG << 2)); // New L bit.
218 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
219 /// 'op' is a valid SetCC operation.
220 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
221 unsigned Operation = Op;
223 Operation ^= 7; // Flip L, G, E bits, but not U.
225 Operation ^= 15; // Flip all of the condition bits.
226 if (Operation > ISD::SETTRUE2)
227 Operation &= ~8; // Don't let N and U bits get set.
228 return ISD::CondCode(Operation);
232 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
233 /// signed operation and 2 if the result is an unsigned comparison. Return zero
234 /// if the operation does not depend on the sign of the input (setne and seteq).
235 static int isSignedOp(ISD::CondCode Opcode) {
237 default: assert(0 && "Illegal integer setcc operation!");
239 case ISD::SETNE: return 0;
243 case ISD::SETGE: return 1;
247 case ISD::SETUGE: return 2;
251 /// getSetCCOrOperation - Return the result of a logical OR between different
252 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
253 /// returns SETCC_INVALID if it is not possible to represent the resultant
255 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
257 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
258 // Cannot fold a signed integer setcc with an unsigned integer setcc.
259 return ISD::SETCC_INVALID;
261 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
263 // If the N and U bits get set then the resultant comparison DOES suddenly
264 // care about orderedness, and is true when ordered.
265 if (Op > ISD::SETTRUE2)
266 Op &= ~16; // Clear the U bit if the N bit is set.
268 // Canonicalize illegal integer setcc's.
269 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
272 return ISD::CondCode(Op);
275 /// getSetCCAndOperation - Return the result of a logical AND between different
276 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
277 /// function returns zero if it is not possible to represent the resultant
279 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
281 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
282 // Cannot fold a signed setcc with an unsigned setcc.
283 return ISD::SETCC_INVALID;
285 // Combine all of the condition bits.
286 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
288 // Canonicalize illegal integer setcc's.
292 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
293 case ISD::SETOEQ: // SETEQ & SETU[LG]E
294 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
295 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
296 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
303 const TargetMachine &SelectionDAG::getTarget() const {
304 return TLI.getTargetMachine();
307 //===----------------------------------------------------------------------===//
308 // SDNode Profile Support
309 //===----------------------------------------------------------------------===//
311 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
313 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
317 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
318 /// solely with their pointer.
319 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
320 ID.AddPointer(VTList.VTs);
323 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
325 static void AddNodeIDOperands(FoldingSetNodeID &ID,
326 SDOperandPtr Ops, unsigned NumOps) {
327 for (; NumOps; --NumOps, ++Ops) {
328 ID.AddPointer(Ops->Val);
329 ID.AddInteger(Ops->ResNo);
333 static void AddNodeIDNode(FoldingSetNodeID &ID,
334 unsigned short OpC, SDVTList VTList,
335 SDOperandPtr OpList, unsigned N) {
336 AddNodeIDOpcode(ID, OpC);
337 AddNodeIDValueTypes(ID, VTList);
338 AddNodeIDOperands(ID, OpList, N);
342 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
344 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
345 AddNodeIDOpcode(ID, N->getOpcode());
346 // Add the return value info.
347 AddNodeIDValueTypes(ID, N->getVTList());
348 // Add the operand info.
349 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
351 // Handle SDNode leafs with special info.
352 switch (N->getOpcode()) {
353 default: break; // Normal nodes don't need extra info.
355 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
357 case ISD::TargetConstant:
359 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
361 case ISD::TargetConstantFP:
362 case ISD::ConstantFP: {
363 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
366 case ISD::TargetGlobalAddress:
367 case ISD::GlobalAddress:
368 case ISD::TargetGlobalTLSAddress:
369 case ISD::GlobalTLSAddress: {
370 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
371 ID.AddPointer(GA->getGlobal());
372 ID.AddInteger(GA->getOffset());
375 case ISD::BasicBlock:
376 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
379 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
381 case ISD::DBG_STOPPOINT: {
382 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
383 ID.AddInteger(DSP->getLine());
384 ID.AddInteger(DSP->getColumn());
385 ID.AddPointer(DSP->getCompileUnit());
390 ID.AddInteger(cast<LabelSDNode>(N)->getLabelID());
393 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
395 case ISD::MEMOPERAND: {
396 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
397 ID.AddPointer(MO.getValue());
398 ID.AddInteger(MO.getFlags());
399 ID.AddInteger(MO.getOffset());
400 ID.AddInteger(MO.getSize());
401 ID.AddInteger(MO.getAlignment());
404 case ISD::FrameIndex:
405 case ISD::TargetFrameIndex:
406 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
409 case ISD::TargetJumpTable:
410 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
412 case ISD::ConstantPool:
413 case ISD::TargetConstantPool: {
414 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
415 ID.AddInteger(CP->getAlignment());
416 ID.AddInteger(CP->getOffset());
417 if (CP->isMachineConstantPoolEntry())
418 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
420 ID.AddPointer(CP->getConstVal());
424 LoadSDNode *LD = cast<LoadSDNode>(N);
425 ID.AddInteger(LD->getAddressingMode());
426 ID.AddInteger(LD->getExtensionType());
427 ID.AddInteger(LD->getMemoryVT().getRawBits());
428 ID.AddInteger(LD->getAlignment());
429 ID.AddInteger(LD->isVolatile());
433 StoreSDNode *ST = cast<StoreSDNode>(N);
434 ID.AddInteger(ST->getAddressingMode());
435 ID.AddInteger(ST->isTruncatingStore());
436 ID.AddInteger(ST->getMemoryVT().getRawBits());
437 ID.AddInteger(ST->getAlignment());
438 ID.AddInteger(ST->isVolatile());
441 case ISD::ATOMIC_CMP_SWAP:
442 case ISD::ATOMIC_LOAD_ADD:
443 case ISD::ATOMIC_SWAP:
444 case ISD::ATOMIC_LOAD_SUB:
445 case ISD::ATOMIC_LOAD_AND:
446 case ISD::ATOMIC_LOAD_OR:
447 case ISD::ATOMIC_LOAD_XOR:
448 case ISD::ATOMIC_LOAD_NAND:
449 case ISD::ATOMIC_LOAD_MIN:
450 case ISD::ATOMIC_LOAD_MAX:
451 case ISD::ATOMIC_LOAD_UMIN:
452 case ISD::ATOMIC_LOAD_UMAX: {
453 AtomicSDNode *AT = cast<AtomicSDNode>(N);
454 ID.AddInteger(AT->getAlignment());
455 ID.AddInteger(AT->isVolatile());
458 } // end switch (N->getOpcode())
461 //===----------------------------------------------------------------------===//
462 // SelectionDAG Class
463 //===----------------------------------------------------------------------===//
465 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
467 void SelectionDAG::RemoveDeadNodes() {
468 // Create a dummy node (which is not added to allnodes), that adds a reference
469 // to the root node, preventing it from being deleted.
470 HandleSDNode Dummy(getRoot());
472 SmallVector<SDNode*, 128> DeadNodes;
474 // Add all obviously-dead nodes to the DeadNodes worklist.
475 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
477 DeadNodes.push_back(I);
479 // Process the worklist, deleting the nodes and adding their uses to the
481 while (!DeadNodes.empty()) {
482 SDNode *N = DeadNodes.back();
483 DeadNodes.pop_back();
485 // Take the node out of the appropriate CSE map.
486 RemoveNodeFromCSEMaps(N);
488 // Next, brutally remove the operand list. This is safe to do, as there are
489 // no cycles in the graph.
490 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
491 SDNode *Operand = I->getVal();
492 Operand->removeUser(std::distance(N->op_begin(), I), N);
494 // Now that we removed this operand, see if there are no uses of it left.
495 if (Operand->use_empty())
496 DeadNodes.push_back(Operand);
498 if (N->OperandsNeedDelete) {
499 delete[] N->OperandList;
504 // Finally, remove N itself.
508 // If the root changed (e.g. it was a dead load, update the root).
509 setRoot(Dummy.getValue());
512 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
513 SmallVector<SDNode*, 16> DeadNodes;
514 DeadNodes.push_back(N);
516 // Process the worklist, deleting the nodes and adding their uses to the
518 while (!DeadNodes.empty()) {
519 SDNode *N = DeadNodes.back();
520 DeadNodes.pop_back();
523 UpdateListener->NodeDeleted(N, 0);
525 // Take the node out of the appropriate CSE map.
526 RemoveNodeFromCSEMaps(N);
528 // Next, brutally remove the operand list. This is safe to do, as there are
529 // no cycles in the graph.
531 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
532 SDNode *Operand = I->getVal();
533 Operand->removeUser(op_num, N);
535 // Now that we removed this operand, see if there are no uses of it left.
536 if (Operand->use_empty())
537 DeadNodes.push_back(Operand);
541 if (N->OperandsNeedDelete) {
542 delete[] N->OperandList;
547 // Finally, remove N itself.
552 void SelectionDAG::DeleteNode(SDNode *N) {
553 assert(N->use_empty() && "Cannot delete a node that is not dead!");
555 // First take this out of the appropriate CSE map.
556 RemoveNodeFromCSEMaps(N);
558 // Finally, remove uses due to operands of this node, remove from the
559 // AllNodes list, and delete the node.
560 DeleteNodeNotInCSEMaps(N);
563 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
565 // Remove it from the AllNodes list.
568 // Drop all of the operands and decrement used nodes use counts.
569 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
570 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
571 if (N->OperandsNeedDelete) {
572 delete[] N->OperandList;
580 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
581 /// correspond to it. This is useful when we're about to delete or repurpose
582 /// the node. We don't want future request for structurally identical nodes
583 /// to return N anymore.
584 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
586 switch (N->getOpcode()) {
587 case ISD::HANDLENODE: return; // noop.
589 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
590 "Cond code doesn't exist!");
591 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
592 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
594 case ISD::ExternalSymbol:
595 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
597 case ISD::TargetExternalSymbol:
599 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
601 case ISD::VALUETYPE: {
602 MVT VT = cast<VTSDNode>(N)->getVT();
603 if (VT.isExtended()) {
604 Erased = ExtendedValueTypeNodes.erase(VT);
606 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
607 ValueTypeNodes[VT.getSimpleVT()] = 0;
612 // Remove it from the CSE Map.
613 Erased = CSEMap.RemoveNode(N);
617 // Verify that the node was actually in one of the CSE maps, unless it has a
618 // flag result (which cannot be CSE'd) or is one of the special cases that are
619 // not subject to CSE.
620 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
621 !N->isTargetOpcode()) {
624 assert(0 && "Node is not in map!");
629 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
630 /// has been taken out and modified in some way. If the specified node already
631 /// exists in the CSE maps, do not modify the maps, but return the existing node
632 /// instead. If it doesn't exist, add it and return null.
634 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
635 assert(N->getNumOperands() && "This is a leaf node!");
636 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
637 return 0; // Never add these nodes.
639 // Check that remaining values produced are not flags.
640 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
641 if (N->getValueType(i) == MVT::Flag)
642 return 0; // Never CSE anything that produces a flag.
644 SDNode *New = CSEMap.GetOrInsertNode(N);
645 if (New != N) return New; // Node already existed.
649 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
650 /// were replaced with those specified. If this node is never memoized,
651 /// return null, otherwise return a pointer to the slot it would take. If a
652 /// node already exists with these operands, the slot will be non-null.
653 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
655 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
656 return 0; // Never add these nodes.
658 // Check that remaining values produced are not flags.
659 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
660 if (N->getValueType(i) == MVT::Flag)
661 return 0; // Never CSE anything that produces a flag.
663 SDOperand Ops[] = { Op };
665 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
666 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
669 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
670 /// were replaced with those specified. If this node is never memoized,
671 /// return null, otherwise return a pointer to the slot it would take. If a
672 /// node already exists with these operands, the slot will be non-null.
673 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
674 SDOperand Op1, SDOperand Op2,
676 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
677 return 0; // Never add these nodes.
679 // Check that remaining values produced are not flags.
680 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
681 if (N->getValueType(i) == MVT::Flag)
682 return 0; // Never CSE anything that produces a flag.
684 SDOperand Ops[] = { Op1, Op2 };
686 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
687 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
691 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
692 /// were replaced with those specified. If this node is never memoized,
693 /// return null, otherwise return a pointer to the slot it would take. If a
694 /// node already exists with these operands, the slot will be non-null.
695 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
696 SDOperandPtr Ops,unsigned NumOps,
698 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
699 return 0; // Never add these nodes.
701 // Check that remaining values produced are not flags.
702 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
703 if (N->getValueType(i) == MVT::Flag)
704 return 0; // Never CSE anything that produces a flag.
707 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
709 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
710 ID.AddInteger(LD->getAddressingMode());
711 ID.AddInteger(LD->getExtensionType());
712 ID.AddInteger(LD->getMemoryVT().getRawBits());
713 ID.AddInteger(LD->getAlignment());
714 ID.AddInteger(LD->isVolatile());
715 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
716 ID.AddInteger(ST->getAddressingMode());
717 ID.AddInteger(ST->isTruncatingStore());
718 ID.AddInteger(ST->getMemoryVT().getRawBits());
719 ID.AddInteger(ST->getAlignment());
720 ID.AddInteger(ST->isVolatile());
723 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
727 SelectionDAG::~SelectionDAG() {
728 while (!AllNodes.empty()) {
729 SDNode *N = AllNodes.begin();
730 N->SetNextInBucket(0);
731 if (N->OperandsNeedDelete) {
732 delete [] N->OperandList;
736 AllNodes.pop_front();
740 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
741 if (Op.getValueType() == VT) return Op;
742 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
744 return getNode(ISD::AND, Op.getValueType(), Op,
745 getConstant(Imm, Op.getValueType()));
748 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
749 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
750 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
753 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
754 assert(VT.isInteger() && "Cannot create FP integer constant!");
756 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
757 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
758 "APInt size does not match type size!");
760 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
762 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
766 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
768 return SDOperand(N, 0);
770 N = new ConstantSDNode(isT, Val, EltVT);
771 CSEMap.InsertNode(N, IP);
772 AllNodes.push_back(N);
775 SDOperand Result(N, 0);
777 SmallVector<SDOperand, 8> Ops;
778 Ops.assign(VT.getVectorNumElements(), Result);
779 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
784 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
785 return getConstant(Val, TLI.getPointerTy(), isTarget);
789 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
790 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
793 VT.isVector() ? VT.getVectorElementType() : VT;
795 // Do the map lookup using the actual bit pattern for the floating point
796 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
797 // we don't have issues with SNANs.
798 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
800 AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
804 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
806 return SDOperand(N, 0);
808 N = new ConstantFPSDNode(isTarget, V, EltVT);
809 CSEMap.InsertNode(N, IP);
810 AllNodes.push_back(N);
813 SDOperand Result(N, 0);
815 SmallVector<SDOperand, 8> Ops;
816 Ops.assign(VT.getVectorNumElements(), Result);
817 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
822 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
824 VT.isVector() ? VT.getVectorElementType() : VT;
826 return getConstantFP(APFloat((float)Val), VT, isTarget);
828 return getConstantFP(APFloat(Val), VT, isTarget);
831 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
836 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
838 // If GV is an alias then use the aliasee for determining thread-localness.
839 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
840 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
843 if (GVar && GVar->isThreadLocal())
844 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
846 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
849 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
851 ID.AddInteger(Offset);
853 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
854 return SDOperand(E, 0);
855 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
856 CSEMap.InsertNode(N, IP);
857 AllNodes.push_back(N);
858 return SDOperand(N, 0);
861 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
862 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
864 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
867 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
868 return SDOperand(E, 0);
869 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
870 CSEMap.InsertNode(N, IP);
871 AllNodes.push_back(N);
872 return SDOperand(N, 0);
875 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
876 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
878 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
881 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
882 return SDOperand(E, 0);
883 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
884 CSEMap.InsertNode(N, IP);
885 AllNodes.push_back(N);
886 return SDOperand(N, 0);
889 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
890 unsigned Alignment, int Offset,
892 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
894 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
895 ID.AddInteger(Alignment);
896 ID.AddInteger(Offset);
899 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
900 return SDOperand(E, 0);
901 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
902 CSEMap.InsertNode(N, IP);
903 AllNodes.push_back(N);
904 return SDOperand(N, 0);
908 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
909 unsigned Alignment, int Offset,
911 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
913 AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
914 ID.AddInteger(Alignment);
915 ID.AddInteger(Offset);
916 C->AddSelectionDAGCSEId(ID);
918 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
919 return SDOperand(E, 0);
920 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
921 CSEMap.InsertNode(N, IP);
922 AllNodes.push_back(N);
923 return SDOperand(N, 0);
927 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
929 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), (SDOperand*)0, 0);
932 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
933 return SDOperand(E, 0);
934 SDNode *N = new BasicBlockSDNode(MBB);
935 CSEMap.InsertNode(N, IP);
936 AllNodes.push_back(N);
937 return SDOperand(N, 0);
940 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
942 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), (SDOperand*)0, 0);
943 ID.AddInteger(Flags.getRawBits());
945 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
946 return SDOperand(E, 0);
947 SDNode *N = new ARG_FLAGSSDNode(Flags);
948 CSEMap.InsertNode(N, IP);
949 AllNodes.push_back(N);
950 return SDOperand(N, 0);
953 SDOperand SelectionDAG::getValueType(MVT VT) {
954 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
955 ValueTypeNodes.resize(VT.getSimpleVT()+1);
957 SDNode *&N = VT.isExtended() ?
958 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
960 if (N) return SDOperand(N, 0);
961 N = new VTSDNode(VT);
962 AllNodes.push_back(N);
963 return SDOperand(N, 0);
966 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
967 SDNode *&N = ExternalSymbols[Sym];
968 if (N) return SDOperand(N, 0);
969 N = new ExternalSymbolSDNode(false, Sym, VT);
970 AllNodes.push_back(N);
971 return SDOperand(N, 0);
974 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
975 SDNode *&N = TargetExternalSymbols[Sym];
976 if (N) return SDOperand(N, 0);
977 N = new ExternalSymbolSDNode(true, Sym, VT);
978 AllNodes.push_back(N);
979 return SDOperand(N, 0);
982 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
983 if ((unsigned)Cond >= CondCodeNodes.size())
984 CondCodeNodes.resize(Cond+1);
986 if (CondCodeNodes[Cond] == 0) {
987 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
988 AllNodes.push_back(CondCodeNodes[Cond]);
990 return SDOperand(CondCodeNodes[Cond], 0);
993 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
995 AddNodeIDNode(ID, ISD::Register, getVTList(VT), (SDOperand*)0, 0);
996 ID.AddInteger(RegNo);
998 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
999 return SDOperand(E, 0);
1000 SDNode *N = new RegisterSDNode(RegNo, VT);
1001 CSEMap.InsertNode(N, IP);
1002 AllNodes.push_back(N);
1003 return SDOperand(N, 0);
1006 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
1007 unsigned Line, unsigned Col,
1008 const CompileUnitDesc *CU) {
1009 FoldingSetNodeID ID;
1010 SDOperand Ops[] = { Root };
1011 AddNodeIDNode(ID, ISD::DBG_STOPPOINT, getVTList(MVT::Other), &Ops[0], 1);
1012 ID.AddInteger(Line);
1016 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1017 return SDOperand(E, 0);
1018 SDNode *N = new DbgStopPointSDNode(Root, Line, Col, CU);
1019 CSEMap.InsertNode(N, IP);
1020 AllNodes.push_back(N);
1021 return SDOperand(N, 0);
1024 SDOperand SelectionDAG::getLabel(unsigned Opcode,
1027 FoldingSetNodeID ID;
1028 SDOperand Ops[] = { Root };
1029 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1030 ID.AddInteger(LabelID);
1032 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1033 return SDOperand(E, 0);
1034 SDNode *N = new LabelSDNode(Opcode, Root, LabelID);
1035 CSEMap.InsertNode(N, IP);
1036 AllNodes.push_back(N);
1037 return SDOperand(N, 0);
1040 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1041 assert((!V || isa<PointerType>(V->getType())) &&
1042 "SrcValue is not a pointer?");
1044 FoldingSetNodeID ID;
1045 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), (SDOperand*)0, 0);
1049 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1050 return SDOperand(E, 0);
1052 SDNode *N = new SrcValueSDNode(V);
1053 CSEMap.InsertNode(N, IP);
1054 AllNodes.push_back(N);
1055 return SDOperand(N, 0);
1058 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1059 const Value *v = MO.getValue();
1060 assert((!v || isa<PointerType>(v->getType())) &&
1061 "SrcValue is not a pointer?");
1063 FoldingSetNodeID ID;
1064 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), (SDOperand*)0, 0);
1066 ID.AddInteger(MO.getFlags());
1067 ID.AddInteger(MO.getOffset());
1068 ID.AddInteger(MO.getSize());
1069 ID.AddInteger(MO.getAlignment());
1072 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1073 return SDOperand(E, 0);
1075 SDNode *N = new MemOperandSDNode(MO);
1076 CSEMap.InsertNode(N, IP);
1077 AllNodes.push_back(N);
1078 return SDOperand(N, 0);
1081 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1082 /// specified value type.
1083 SDOperand SelectionDAG::CreateStackTemporary(MVT VT) {
1084 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1085 unsigned ByteSize = VT.getSizeInBits()/8;
1086 const Type *Ty = VT.getTypeForMVT();
1087 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
1088 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1089 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1093 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1094 SDOperand N2, ISD::CondCode Cond) {
1095 // These setcc operations always fold.
1099 case ISD::SETFALSE2: return getConstant(0, VT);
1101 case ISD::SETTRUE2: return getConstant(1, VT);
1113 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1117 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1118 const APInt &C2 = N2C->getAPIntValue();
1119 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1120 const APInt &C1 = N1C->getAPIntValue();
1123 default: assert(0 && "Unknown integer setcc!");
1124 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1125 case ISD::SETNE: return getConstant(C1 != C2, VT);
1126 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1127 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1128 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1129 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1130 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1131 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1132 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1133 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1137 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1138 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1139 // No compile time operations on this type yet.
1140 if (N1C->getValueType(0) == MVT::ppcf128)
1143 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1146 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1147 return getNode(ISD::UNDEF, VT);
1149 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1150 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1151 return getNode(ISD::UNDEF, VT);
1153 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1154 R==APFloat::cmpLessThan, VT);
1155 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1156 return getNode(ISD::UNDEF, VT);
1158 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1159 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1160 return getNode(ISD::UNDEF, VT);
1162 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1163 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1164 return getNode(ISD::UNDEF, VT);
1166 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1167 R==APFloat::cmpEqual, VT);
1168 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1169 return getNode(ISD::UNDEF, VT);
1171 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1172 R==APFloat::cmpEqual, VT);
1173 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1174 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1175 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1176 R==APFloat::cmpEqual, VT);
1177 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1178 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1179 R==APFloat::cmpLessThan, VT);
1180 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1181 R==APFloat::cmpUnordered, VT);
1182 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1183 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1186 // Ensure that the constant occurs on the RHS.
1187 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1191 // Could not fold it.
1195 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1196 /// use this predicate to simplify operations downstream.
1197 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1198 unsigned BitWidth = Op.getValueSizeInBits();
1199 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1202 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1203 /// this predicate to simplify operations downstream. Mask is known to be zero
1204 /// for bits that V cannot have.
1205 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1206 unsigned Depth) const {
1207 APInt KnownZero, KnownOne;
1208 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1209 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1210 return (KnownZero & Mask) == Mask;
1213 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1214 /// known to be either zero or one and return them in the KnownZero/KnownOne
1215 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1217 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1218 APInt &KnownZero, APInt &KnownOne,
1219 unsigned Depth) const {
1220 unsigned BitWidth = Mask.getBitWidth();
1221 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1222 "Mask size mismatches value type size!");
1224 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1225 if (Depth == 6 || Mask == 0)
1226 return; // Limit search depth.
1228 APInt KnownZero2, KnownOne2;
1230 switch (Op.getOpcode()) {
1232 // We know all of the bits for a constant!
1233 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1234 KnownZero = ~KnownOne & Mask;
1237 // If either the LHS or the RHS are Zero, the result is zero.
1238 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1239 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1240 KnownZero2, KnownOne2, Depth+1);
1241 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1242 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1244 // Output known-1 bits are only known if set in both the LHS & RHS.
1245 KnownOne &= KnownOne2;
1246 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1247 KnownZero |= KnownZero2;
1250 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1251 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1252 KnownZero2, KnownOne2, Depth+1);
1253 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1254 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1256 // Output known-0 bits are only known if clear in both the LHS & RHS.
1257 KnownZero &= KnownZero2;
1258 // Output known-1 are known to be set if set in either the LHS | RHS.
1259 KnownOne |= KnownOne2;
1262 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1263 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1264 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1265 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1267 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1268 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1269 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1270 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1271 KnownZero = KnownZeroOut;
1275 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1276 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1277 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1278 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1279 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1281 // If low bits are zero in either operand, output low known-0 bits.
1282 // Also compute a conserative estimate for high known-0 bits.
1283 // More trickiness is possible, but this is sufficient for the
1284 // interesting case of alignment computation.
1286 unsigned TrailZ = KnownZero.countTrailingOnes() +
1287 KnownZero2.countTrailingOnes();
1288 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1289 KnownZero2.countLeadingOnes(),
1290 BitWidth) - BitWidth;
1292 TrailZ = std::min(TrailZ, BitWidth);
1293 LeadZ = std::min(LeadZ, BitWidth);
1294 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1295 APInt::getHighBitsSet(BitWidth, LeadZ);
1300 // For the purposes of computing leading zeros we can conservatively
1301 // treat a udiv as a logical right shift by the power of 2 known to
1302 // be less than the denominator.
1303 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1304 ComputeMaskedBits(Op.getOperand(0),
1305 AllOnes, KnownZero2, KnownOne2, Depth+1);
1306 unsigned LeadZ = KnownZero2.countLeadingOnes();
1310 ComputeMaskedBits(Op.getOperand(1),
1311 AllOnes, KnownZero2, KnownOne2, Depth+1);
1312 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1313 if (RHSUnknownLeadingOnes != BitWidth)
1314 LeadZ = std::min(BitWidth,
1315 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1317 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1321 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1322 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1323 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1324 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1326 // Only known if known in both the LHS and RHS.
1327 KnownOne &= KnownOne2;
1328 KnownZero &= KnownZero2;
1330 case ISD::SELECT_CC:
1331 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1332 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1333 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1334 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1336 // Only known if known in both the LHS and RHS.
1337 KnownOne &= KnownOne2;
1338 KnownZero &= KnownZero2;
1341 // If we know the result of a setcc has the top bits zero, use this info.
1342 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1344 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1347 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1348 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1349 unsigned ShAmt = SA->getValue();
1351 // If the shift count is an invalid immediate, don't do anything.
1352 if (ShAmt >= BitWidth)
1355 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1356 KnownZero, KnownOne, Depth+1);
1357 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1358 KnownZero <<= ShAmt;
1360 // low bits known zero.
1361 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1365 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1366 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1367 unsigned ShAmt = SA->getValue();
1369 // If the shift count is an invalid immediate, don't do anything.
1370 if (ShAmt >= BitWidth)
1373 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1374 KnownZero, KnownOne, Depth+1);
1375 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1376 KnownZero = KnownZero.lshr(ShAmt);
1377 KnownOne = KnownOne.lshr(ShAmt);
1379 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1380 KnownZero |= HighBits; // High bits known zero.
1384 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1385 unsigned ShAmt = SA->getValue();
1387 // If the shift count is an invalid immediate, don't do anything.
1388 if (ShAmt >= BitWidth)
1391 APInt InDemandedMask = (Mask << ShAmt);
1392 // If any of the demanded bits are produced by the sign extension, we also
1393 // demand the input sign bit.
1394 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1395 if (HighBits.getBoolValue())
1396 InDemandedMask |= APInt::getSignBit(BitWidth);
1398 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1400 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1401 KnownZero = KnownZero.lshr(ShAmt);
1402 KnownOne = KnownOne.lshr(ShAmt);
1404 // Handle the sign bits.
1405 APInt SignBit = APInt::getSignBit(BitWidth);
1406 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1408 if (KnownZero.intersects(SignBit)) {
1409 KnownZero |= HighBits; // New bits are known zero.
1410 } else if (KnownOne.intersects(SignBit)) {
1411 KnownOne |= HighBits; // New bits are known one.
1415 case ISD::SIGN_EXTEND_INREG: {
1416 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1417 unsigned EBits = EVT.getSizeInBits();
1419 // Sign extension. Compute the demanded bits in the result that are not
1420 // present in the input.
1421 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1423 APInt InSignBit = APInt::getSignBit(EBits);
1424 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1426 // If the sign extended bits are demanded, we know that the sign
1428 InSignBit.zext(BitWidth);
1429 if (NewBits.getBoolValue())
1430 InputDemandedBits |= InSignBit;
1432 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1433 KnownZero, KnownOne, Depth+1);
1434 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1436 // If the sign bit of the input is known set or clear, then we know the
1437 // top bits of the result.
1438 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1439 KnownZero |= NewBits;
1440 KnownOne &= ~NewBits;
1441 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1442 KnownOne |= NewBits;
1443 KnownZero &= ~NewBits;
1444 } else { // Input sign bit unknown
1445 KnownZero &= ~NewBits;
1446 KnownOne &= ~NewBits;
1453 unsigned LowBits = Log2_32(BitWidth)+1;
1454 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1459 if (ISD::isZEXTLoad(Op.Val)) {
1460 LoadSDNode *LD = cast<LoadSDNode>(Op);
1461 MVT VT = LD->getMemoryVT();
1462 unsigned MemBits = VT.getSizeInBits();
1463 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1467 case ISD::ZERO_EXTEND: {
1468 MVT InVT = Op.getOperand(0).getValueType();
1469 unsigned InBits = InVT.getSizeInBits();
1470 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1471 APInt InMask = Mask;
1472 InMask.trunc(InBits);
1473 KnownZero.trunc(InBits);
1474 KnownOne.trunc(InBits);
1475 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1476 KnownZero.zext(BitWidth);
1477 KnownOne.zext(BitWidth);
1478 KnownZero |= NewBits;
1481 case ISD::SIGN_EXTEND: {
1482 MVT InVT = Op.getOperand(0).getValueType();
1483 unsigned InBits = InVT.getSizeInBits();
1484 APInt InSignBit = APInt::getSignBit(InBits);
1485 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1486 APInt InMask = Mask;
1487 InMask.trunc(InBits);
1489 // If any of the sign extended bits are demanded, we know that the sign
1490 // bit is demanded. Temporarily set this bit in the mask for our callee.
1491 if (NewBits.getBoolValue())
1492 InMask |= InSignBit;
1494 KnownZero.trunc(InBits);
1495 KnownOne.trunc(InBits);
1496 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1498 // Note if the sign bit is known to be zero or one.
1499 bool SignBitKnownZero = KnownZero.isNegative();
1500 bool SignBitKnownOne = KnownOne.isNegative();
1501 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1502 "Sign bit can't be known to be both zero and one!");
1504 // If the sign bit wasn't actually demanded by our caller, we don't
1505 // want it set in the KnownZero and KnownOne result values. Reset the
1506 // mask and reapply it to the result values.
1508 InMask.trunc(InBits);
1509 KnownZero &= InMask;
1512 KnownZero.zext(BitWidth);
1513 KnownOne.zext(BitWidth);
1515 // If the sign bit is known zero or one, the top bits match.
1516 if (SignBitKnownZero)
1517 KnownZero |= NewBits;
1518 else if (SignBitKnownOne)
1519 KnownOne |= NewBits;
1522 case ISD::ANY_EXTEND: {
1523 MVT InVT = Op.getOperand(0).getValueType();
1524 unsigned InBits = InVT.getSizeInBits();
1525 APInt InMask = Mask;
1526 InMask.trunc(InBits);
1527 KnownZero.trunc(InBits);
1528 KnownOne.trunc(InBits);
1529 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1530 KnownZero.zext(BitWidth);
1531 KnownOne.zext(BitWidth);
1534 case ISD::TRUNCATE: {
1535 MVT InVT = Op.getOperand(0).getValueType();
1536 unsigned InBits = InVT.getSizeInBits();
1537 APInt InMask = Mask;
1538 InMask.zext(InBits);
1539 KnownZero.zext(InBits);
1540 KnownOne.zext(InBits);
1541 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1542 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1543 KnownZero.trunc(BitWidth);
1544 KnownOne.trunc(BitWidth);
1547 case ISD::AssertZext: {
1548 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1549 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1550 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1552 KnownZero |= (~InMask) & Mask;
1556 // All bits are zero except the low bit.
1557 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1561 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1562 // We know that the top bits of C-X are clear if X contains less bits
1563 // than C (i.e. no wrap-around can happen). For example, 20-X is
1564 // positive if we can prove that X is >= 0 and < 16.
1565 if (CLHS->getAPIntValue().isNonNegative()) {
1566 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1567 // NLZ can't be BitWidth with no sign bit
1568 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1569 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1572 // If all of the MaskV bits are known to be zero, then we know the
1573 // output top bits are zero, because we now know that the output is
1575 if ((KnownZero2 & MaskV) == MaskV) {
1576 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1577 // Top bits known zero.
1578 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1585 // Output known-0 bits are known if clear or set in both the low clear bits
1586 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1587 // low 3 bits clear.
1588 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1589 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1590 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1591 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1593 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1594 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1595 KnownZeroOut = std::min(KnownZeroOut,
1596 KnownZero2.countTrailingOnes());
1598 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1602 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1603 const APInt &RA = Rem->getAPIntValue();
1604 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1605 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1606 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1607 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1609 // The sign of a remainder is equal to the sign of the first
1610 // operand (zero being positive).
1611 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1612 KnownZero2 |= ~LowBits;
1613 else if (KnownOne2[BitWidth-1])
1614 KnownOne2 |= ~LowBits;
1616 KnownZero |= KnownZero2 & Mask;
1617 KnownOne |= KnownOne2 & Mask;
1619 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1624 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1625 const APInt &RA = Rem->getAPIntValue();
1626 if (RA.isPowerOf2()) {
1627 APInt LowBits = (RA - 1);
1628 APInt Mask2 = LowBits & Mask;
1629 KnownZero |= ~LowBits & Mask;
1630 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1631 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1636 // Since the result is less than or equal to either operand, any leading
1637 // zero bits in either operand must also exist in the result.
1638 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1639 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1641 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1644 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1645 KnownZero2.countLeadingOnes());
1647 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1651 // Allow the target to implement this method for its nodes.
1652 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1653 case ISD::INTRINSIC_WO_CHAIN:
1654 case ISD::INTRINSIC_W_CHAIN:
1655 case ISD::INTRINSIC_VOID:
1656 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1662 /// ComputeNumSignBits - Return the number of times the sign bit of the
1663 /// register is replicated into the other bits. We know that at least 1 bit
1664 /// is always equal to the sign bit (itself), but other cases can give us
1665 /// information. For example, immediately after an "SRA X, 2", we know that
1666 /// the top 3 bits are all equal to each other, so we return 3.
1667 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1668 MVT VT = Op.getValueType();
1669 assert(VT.isInteger() && "Invalid VT!");
1670 unsigned VTBits = VT.getSizeInBits();
1672 unsigned FirstAnswer = 1;
1675 return 1; // Limit search depth.
1677 switch (Op.getOpcode()) {
1679 case ISD::AssertSext:
1680 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1681 return VTBits-Tmp+1;
1682 case ISD::AssertZext:
1683 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1686 case ISD::Constant: {
1687 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1688 // If negative, return # leading ones.
1689 if (Val.isNegative())
1690 return Val.countLeadingOnes();
1692 // Return # leading zeros.
1693 return Val.countLeadingZeros();
1696 case ISD::SIGN_EXTEND:
1697 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1698 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1700 case ISD::SIGN_EXTEND_INREG:
1701 // Max of the input and what this extends.
1702 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1705 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1706 return std::max(Tmp, Tmp2);
1709 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1710 // SRA X, C -> adds C sign bits.
1711 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1712 Tmp += C->getValue();
1713 if (Tmp > VTBits) Tmp = VTBits;
1717 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1718 // shl destroys sign bits.
1719 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1720 if (C->getValue() >= VTBits || // Bad shift.
1721 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1722 return Tmp - C->getValue();
1727 case ISD::XOR: // NOT is handled here.
1728 // Logical binary ops preserve the number of sign bits at the worst.
1729 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1731 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1732 FirstAnswer = std::min(Tmp, Tmp2);
1733 // We computed what we know about the sign bits as our first
1734 // answer. Now proceed to the generic code that uses
1735 // ComputeMaskedBits, and pick whichever answer is better.
1740 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1741 if (Tmp == 1) return 1; // Early out.
1742 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1743 return std::min(Tmp, Tmp2);
1746 // If setcc returns 0/-1, all bits are sign bits.
1747 if (TLI.getSetCCResultContents() ==
1748 TargetLowering::ZeroOrNegativeOneSetCCResult)
1753 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1754 unsigned RotAmt = C->getValue() & (VTBits-1);
1756 // Handle rotate right by N like a rotate left by 32-N.
1757 if (Op.getOpcode() == ISD::ROTR)
1758 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1760 // If we aren't rotating out all of the known-in sign bits, return the
1761 // number that are left. This handles rotl(sext(x), 1) for example.
1762 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1763 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1767 // Add can have at most one carry bit. Thus we know that the output
1768 // is, at worst, one more bit than the inputs.
1769 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1770 if (Tmp == 1) return 1; // Early out.
1772 // Special case decrementing a value (ADD X, -1):
1773 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1774 if (CRHS->isAllOnesValue()) {
1775 APInt KnownZero, KnownOne;
1776 APInt Mask = APInt::getAllOnesValue(VTBits);
1777 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1779 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1781 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1784 // If we are subtracting one from a positive number, there is no carry
1785 // out of the result.
1786 if (KnownZero.isNegative())
1790 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1791 if (Tmp2 == 1) return 1;
1792 return std::min(Tmp, Tmp2)-1;
1796 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1797 if (Tmp2 == 1) return 1;
1800 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1801 if (CLHS->isNullValue()) {
1802 APInt KnownZero, KnownOne;
1803 APInt Mask = APInt::getAllOnesValue(VTBits);
1804 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1805 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1807 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1810 // If the input is known to be positive (the sign bit is known clear),
1811 // the output of the NEG has the same number of sign bits as the input.
1812 if (KnownZero.isNegative())
1815 // Otherwise, we treat this like a SUB.
1818 // Sub can have at most one carry bit. Thus we know that the output
1819 // is, at worst, one more bit than the inputs.
1820 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1821 if (Tmp == 1) return 1; // Early out.
1822 return std::min(Tmp, Tmp2)-1;
1825 // FIXME: it's tricky to do anything useful for this, but it is an important
1826 // case for targets like X86.
1830 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1831 if (Op.getOpcode() == ISD::LOAD) {
1832 LoadSDNode *LD = cast<LoadSDNode>(Op);
1833 unsigned ExtType = LD->getExtensionType();
1836 case ISD::SEXTLOAD: // '17' bits known
1837 Tmp = LD->getMemoryVT().getSizeInBits();
1838 return VTBits-Tmp+1;
1839 case ISD::ZEXTLOAD: // '16' bits known
1840 Tmp = LD->getMemoryVT().getSizeInBits();
1845 // Allow the target to implement this method for its nodes.
1846 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1847 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1848 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1849 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1850 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1851 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1854 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1855 // use this information.
1856 APInt KnownZero, KnownOne;
1857 APInt Mask = APInt::getAllOnesValue(VTBits);
1858 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1860 if (KnownZero.isNegative()) { // sign bit is 0
1862 } else if (KnownOne.isNegative()) { // sign bit is 1;
1869 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1870 // the number of identical bits in the top of the input value.
1872 Mask <<= Mask.getBitWidth()-VTBits;
1873 // Return # leading zeros. We use 'min' here in case Val was zero before
1874 // shifting. We don't want to return '64' as for an i32 "0".
1875 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1879 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1880 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1881 if (!GA) return false;
1882 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1883 if (!GV) return false;
1884 MachineModuleInfo *MMI = getMachineModuleInfo();
1885 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1889 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1890 /// element of the result of the vector shuffle.
1891 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1892 MVT VT = N->getValueType(0);
1893 SDOperand PermMask = N->getOperand(2);
1894 SDOperand Idx = PermMask.getOperand(i);
1895 if (Idx.getOpcode() == ISD::UNDEF)
1896 return getNode(ISD::UNDEF, VT.getVectorElementType());
1897 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1898 unsigned NumElems = PermMask.getNumOperands();
1899 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1902 if (V.getOpcode() == ISD::BIT_CONVERT) {
1903 V = V.getOperand(0);
1904 if (V.getValueType().getVectorNumElements() != NumElems)
1907 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1908 return (Index == 0) ? V.getOperand(0)
1909 : getNode(ISD::UNDEF, VT.getVectorElementType());
1910 if (V.getOpcode() == ISD::BUILD_VECTOR)
1911 return V.getOperand(Index);
1912 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1913 return getShuffleScalarElt(V.Val, Index);
1918 /// getNode - Gets or creates the specified node.
1920 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1921 FoldingSetNodeID ID;
1922 AddNodeIDNode(ID, Opcode, getVTList(VT), (SDOperand*)0, 0);
1924 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1925 return SDOperand(E, 0);
1926 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1927 CSEMap.InsertNode(N, IP);
1929 AllNodes.push_back(N);
1930 return SDOperand(N, 0);
1933 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1934 // Constant fold unary operations with an integer constant operand.
1935 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1936 const APInt &Val = C->getAPIntValue();
1937 unsigned BitWidth = VT.getSizeInBits();
1940 case ISD::SIGN_EXTEND:
1941 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1942 case ISD::ANY_EXTEND:
1943 case ISD::ZERO_EXTEND:
1945 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1946 case ISD::UINT_TO_FP:
1947 case ISD::SINT_TO_FP: {
1948 const uint64_t zero[] = {0, 0};
1949 // No compile time operations on this type.
1950 if (VT==MVT::ppcf128)
1952 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1953 (void)apf.convertFromAPInt(Val,
1954 Opcode==ISD::SINT_TO_FP,
1955 APFloat::rmNearestTiesToEven);
1956 return getConstantFP(apf, VT);
1958 case ISD::BIT_CONVERT:
1959 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1960 return getConstantFP(Val.bitsToFloat(), VT);
1961 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1962 return getConstantFP(Val.bitsToDouble(), VT);
1965 return getConstant(Val.byteSwap(), VT);
1967 return getConstant(Val.countPopulation(), VT);
1969 return getConstant(Val.countLeadingZeros(), VT);
1971 return getConstant(Val.countTrailingZeros(), VT);
1975 // Constant fold unary operations with a floating point constant operand.
1976 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1977 APFloat V = C->getValueAPF(); // make copy
1978 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1982 return getConstantFP(V, VT);
1985 return getConstantFP(V, VT);
1987 case ISD::FP_EXTEND:
1988 // This can return overflow, underflow, or inexact; we don't care.
1989 // FIXME need to be more flexible about rounding mode.
1990 (void)V.convert(*MVTToAPFloatSemantics(VT),
1991 APFloat::rmNearestTiesToEven);
1992 return getConstantFP(V, VT);
1993 case ISD::FP_TO_SINT:
1994 case ISD::FP_TO_UINT: {
1996 assert(integerPartWidth >= 64);
1997 // FIXME need to be more flexible about rounding mode.
1998 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1999 Opcode==ISD::FP_TO_SINT,
2000 APFloat::rmTowardZero);
2001 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2003 return getConstant(x, VT);
2005 case ISD::BIT_CONVERT:
2006 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2007 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2008 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2009 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2015 unsigned OpOpcode = Operand.Val->getOpcode();
2017 case ISD::TokenFactor:
2018 return Operand; // Factor of one node? No need.
2019 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2020 case ISD::FP_EXTEND:
2021 assert(VT.isFloatingPoint() &&
2022 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2023 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2024 if (Operand.getOpcode() == ISD::UNDEF)
2025 return getNode(ISD::UNDEF, VT);
2027 case ISD::SIGN_EXTEND:
2028 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2029 "Invalid SIGN_EXTEND!");
2030 if (Operand.getValueType() == VT) return Operand; // noop extension
2031 assert(Operand.getValueType().bitsLT(VT)
2032 && "Invalid sext node, dst < src!");
2033 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2034 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2036 case ISD::ZERO_EXTEND:
2037 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2038 "Invalid ZERO_EXTEND!");
2039 if (Operand.getValueType() == VT) return Operand; // noop extension
2040 assert(Operand.getValueType().bitsLT(VT)
2041 && "Invalid zext node, dst < src!");
2042 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2043 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2045 case ISD::ANY_EXTEND:
2046 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2047 "Invalid ANY_EXTEND!");
2048 if (Operand.getValueType() == VT) return Operand; // noop extension
2049 assert(Operand.getValueType().bitsLT(VT)
2050 && "Invalid anyext node, dst < src!");
2051 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2052 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2053 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2056 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2057 "Invalid TRUNCATE!");
2058 if (Operand.getValueType() == VT) return Operand; // noop truncate
2059 assert(Operand.getValueType().bitsGT(VT)
2060 && "Invalid truncate node, src < dst!");
2061 if (OpOpcode == ISD::TRUNCATE)
2062 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2063 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2064 OpOpcode == ISD::ANY_EXTEND) {
2065 // If the source is smaller than the dest, we still need an extend.
2066 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2067 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2068 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2069 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2071 return Operand.Val->getOperand(0);
2074 case ISD::BIT_CONVERT:
2075 // Basic sanity checking.
2076 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2077 && "Cannot BIT_CONVERT between types of different sizes!");
2078 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2079 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2080 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2081 if (OpOpcode == ISD::UNDEF)
2082 return getNode(ISD::UNDEF, VT);
2084 case ISD::SCALAR_TO_VECTOR:
2085 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2086 VT.getVectorElementType() == Operand.getValueType() &&
2087 "Illegal SCALAR_TO_VECTOR node!");
2088 if (OpOpcode == ISD::UNDEF)
2089 return getNode(ISD::UNDEF, VT);
2090 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2091 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2092 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2093 Operand.getConstantOperandVal(1) == 0 &&
2094 Operand.getOperand(0).getValueType() == VT)
2095 return Operand.getOperand(0);
2098 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2099 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2100 Operand.Val->getOperand(0));
2101 if (OpOpcode == ISD::FNEG) // --X -> X
2102 return Operand.Val->getOperand(0);
2105 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2106 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2111 SDVTList VTs = getVTList(VT);
2112 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2113 FoldingSetNodeID ID;
2114 SDOperand Ops[1] = { Operand };
2115 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2117 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2118 return SDOperand(E, 0);
2119 N = new UnarySDNode(Opcode, VTs, Operand);
2120 CSEMap.InsertNode(N, IP);
2122 N = new UnarySDNode(Opcode, VTs, Operand);
2124 AllNodes.push_back(N);
2125 return SDOperand(N, 0);
2130 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2131 SDOperand N1, SDOperand N2) {
2132 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2133 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2136 case ISD::TokenFactor:
2137 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2138 N2.getValueType() == MVT::Other && "Invalid token factor!");
2139 // Fold trivial token factors.
2140 if (N1.getOpcode() == ISD::EntryToken) return N2;
2141 if (N2.getOpcode() == ISD::EntryToken) return N1;
2144 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2145 N1.getValueType() == VT && "Binary operator types must match!");
2146 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2147 // worth handling here.
2148 if (N2C && N2C->isNullValue())
2150 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2157 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2158 N1.getValueType() == VT && "Binary operator types must match!");
2159 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2160 // it's worth handling here.
2161 if (N2C && N2C->isNullValue())
2168 assert(VT.isInteger() && "This operator does not apply to FP types!");
2178 assert(N1.getValueType() == N2.getValueType() &&
2179 N1.getValueType() == VT && "Binary operator types must match!");
2181 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2182 assert(N1.getValueType() == VT &&
2183 N1.getValueType().isFloatingPoint() &&
2184 N2.getValueType().isFloatingPoint() &&
2185 "Invalid FCOPYSIGN!");
2192 assert(VT == N1.getValueType() &&
2193 "Shift operators return type must be the same as their first arg");
2194 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2195 "Shifts only work on integers");
2197 // Always fold shifts of i1 values so the code generator doesn't need to
2198 // handle them. Since we know the size of the shift has to be less than the
2199 // size of the value, the shift/rotate count is guaranteed to be zero.
2203 case ISD::FP_ROUND_INREG: {
2204 MVT EVT = cast<VTSDNode>(N2)->getVT();
2205 assert(VT == N1.getValueType() && "Not an inreg round!");
2206 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2207 "Cannot FP_ROUND_INREG integer types");
2208 assert(EVT.bitsLE(VT) && "Not rounding down!");
2209 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2213 assert(VT.isFloatingPoint() &&
2214 N1.getValueType().isFloatingPoint() &&
2215 VT.bitsLE(N1.getValueType()) &&
2216 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2217 if (N1.getValueType() == VT) return N1; // noop conversion.
2219 case ISD::AssertSext:
2220 case ISD::AssertZext: {
2221 MVT EVT = cast<VTSDNode>(N2)->getVT();
2222 assert(VT == N1.getValueType() && "Not an inreg extend!");
2223 assert(VT.isInteger() && EVT.isInteger() &&
2224 "Cannot *_EXTEND_INREG FP types");
2225 assert(EVT.bitsLE(VT) && "Not extending!");
2226 if (VT == EVT) return N1; // noop assertion.
2229 case ISD::SIGN_EXTEND_INREG: {
2230 MVT EVT = cast<VTSDNode>(N2)->getVT();
2231 assert(VT == N1.getValueType() && "Not an inreg extend!");
2232 assert(VT.isInteger() && EVT.isInteger() &&
2233 "Cannot *_EXTEND_INREG FP types");
2234 assert(EVT.bitsLE(VT) && "Not extending!");
2235 if (EVT == VT) return N1; // Not actually extending
2238 APInt Val = N1C->getAPIntValue();
2239 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2240 Val <<= Val.getBitWidth()-FromBits;
2241 Val = Val.ashr(Val.getBitWidth()-FromBits);
2242 return getConstant(Val, VT);
2246 case ISD::EXTRACT_VECTOR_ELT:
2247 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2249 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2250 if (N1.getOpcode() == ISD::UNDEF)
2251 return getNode(ISD::UNDEF, VT);
2253 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2254 // expanding copies of large vectors from registers.
2255 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2256 N1.getNumOperands() > 0) {
2258 N1.getOperand(0).getValueType().getVectorNumElements();
2259 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2260 N1.getOperand(N2C->getValue() / Factor),
2261 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2264 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2265 // expanding large vector constants.
2266 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2267 return N1.getOperand(N2C->getValue());
2269 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2270 // operations are lowered to scalars.
2271 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2272 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2274 return N1.getOperand(1);
2276 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2279 case ISD::EXTRACT_ELEMENT:
2280 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2281 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2282 (N1.getValueType().isInteger() == VT.isInteger()) &&
2283 "Wrong types for EXTRACT_ELEMENT!");
2285 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2286 // 64-bit integers into 32-bit parts. Instead of building the extract of
2287 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2288 if (N1.getOpcode() == ISD::BUILD_PAIR)
2289 return N1.getOperand(N2C->getValue());
2291 // EXTRACT_ELEMENT of a constant int is also very common.
2292 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2293 unsigned ElementSize = VT.getSizeInBits();
2294 unsigned Shift = ElementSize * N2C->getValue();
2295 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2296 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2299 case ISD::EXTRACT_SUBVECTOR:
2300 if (N1.getValueType() == VT) // Trivial extraction.
2307 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2309 case ISD::ADD: return getConstant(C1 + C2, VT);
2310 case ISD::SUB: return getConstant(C1 - C2, VT);
2311 case ISD::MUL: return getConstant(C1 * C2, VT);
2313 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2316 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2319 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2322 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2324 case ISD::AND : return getConstant(C1 & C2, VT);
2325 case ISD::OR : return getConstant(C1 | C2, VT);
2326 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2327 case ISD::SHL : return getConstant(C1 << C2, VT);
2328 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2329 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2330 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2331 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2334 } else { // Cannonicalize constant to RHS if commutative
2335 if (isCommutativeBinOp(Opcode)) {
2336 std::swap(N1C, N2C);
2342 // Constant fold FP operations.
2343 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2344 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2346 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2347 // Cannonicalize constant to RHS if commutative
2348 std::swap(N1CFP, N2CFP);
2350 } else if (N2CFP && VT != MVT::ppcf128) {
2351 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2352 APFloat::opStatus s;
2355 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2356 if (s != APFloat::opInvalidOp)
2357 return getConstantFP(V1, VT);
2360 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2361 if (s!=APFloat::opInvalidOp)
2362 return getConstantFP(V1, VT);
2365 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2366 if (s!=APFloat::opInvalidOp)
2367 return getConstantFP(V1, VT);
2370 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2371 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2372 return getConstantFP(V1, VT);
2375 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2376 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2377 return getConstantFP(V1, VT);
2379 case ISD::FCOPYSIGN:
2381 return getConstantFP(V1, VT);
2387 // Canonicalize an UNDEF to the RHS, even over a constant.
2388 if (N1.getOpcode() == ISD::UNDEF) {
2389 if (isCommutativeBinOp(Opcode)) {
2393 case ISD::FP_ROUND_INREG:
2394 case ISD::SIGN_EXTEND_INREG:
2400 return N1; // fold op(undef, arg2) -> undef
2408 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2409 // For vectors, we can't easily build an all zero vector, just return
2416 // Fold a bunch of operators when the RHS is undef.
2417 if (N2.getOpcode() == ISD::UNDEF) {
2420 if (N1.getOpcode() == ISD::UNDEF)
2421 // Handle undef ^ undef -> 0 special case. This is a common
2423 return getConstant(0, VT);
2438 return N2; // fold op(arg1, undef) -> undef
2444 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2445 // For vectors, we can't easily build an all zero vector, just return
2450 return getConstant(VT.getIntegerVTBitMask(), VT);
2451 // For vectors, we can't easily build an all one vector, just return
2459 // Memoize this node if possible.
2461 SDVTList VTs = getVTList(VT);
2462 if (VT != MVT::Flag) {
2463 SDOperand Ops[] = { N1, N2 };
2464 FoldingSetNodeID ID;
2465 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2467 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2468 return SDOperand(E, 0);
2469 N = new BinarySDNode(Opcode, VTs, N1, N2);
2470 CSEMap.InsertNode(N, IP);
2472 N = new BinarySDNode(Opcode, VTs, N1, N2);
2475 AllNodes.push_back(N);
2476 return SDOperand(N, 0);
2479 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2480 SDOperand N1, SDOperand N2, SDOperand N3) {
2481 // Perform various simplifications.
2482 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2483 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2486 // Use FoldSetCC to simplify SETCC's.
2487 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2488 if (Simp.Val) return Simp;
2493 if (N1C->getValue())
2494 return N2; // select true, X, Y -> X
2496 return N3; // select false, X, Y -> Y
2499 if (N2 == N3) return N2; // select C, X, X -> X
2503 if (N2C->getValue()) // Unconditional branch
2504 return getNode(ISD::BR, MVT::Other, N1, N3);
2506 return N1; // Never-taken branch
2509 case ISD::VECTOR_SHUFFLE:
2510 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2511 VT.isVector() && N3.getValueType().isVector() &&
2512 N3.getOpcode() == ISD::BUILD_VECTOR &&
2513 VT.getVectorNumElements() == N3.getNumOperands() &&
2514 "Illegal VECTOR_SHUFFLE node!");
2516 case ISD::BIT_CONVERT:
2517 // Fold bit_convert nodes from a type to themselves.
2518 if (N1.getValueType() == VT)
2523 // Memoize node if it doesn't produce a flag.
2525 SDVTList VTs = getVTList(VT);
2526 if (VT != MVT::Flag) {
2527 SDOperand Ops[] = { N1, N2, N3 };
2528 FoldingSetNodeID ID;
2529 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2531 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2532 return SDOperand(E, 0);
2533 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2534 CSEMap.InsertNode(N, IP);
2536 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2538 AllNodes.push_back(N);
2539 return SDOperand(N, 0);
2542 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2543 SDOperand N1, SDOperand N2, SDOperand N3,
2545 SDOperand Ops[] = { N1, N2, N3, N4 };
2546 return getNode(Opcode, VT, Ops, 4);
2549 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2550 SDOperand N1, SDOperand N2, SDOperand N3,
2551 SDOperand N4, SDOperand N5) {
2552 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2553 return getNode(Opcode, VT, Ops, 5);
2556 /// getMemsetValue - Vectorized representation of the memset value
2558 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2559 unsigned NumBits = VT.isVector() ?
2560 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2561 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2562 APInt Val = APInt(NumBits, C->getValue() & 255);
2564 for (unsigned i = NumBits; i > 8; i >>= 1) {
2565 Val = (Val << Shift) | Val;
2569 return DAG.getConstant(Val, VT);
2570 return DAG.getConstantFP(APFloat(Val), VT);
2573 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2575 for (unsigned i = NumBits; i > 8; i >>= 1) {
2576 Value = DAG.getNode(ISD::OR, VT,
2577 DAG.getNode(ISD::SHL, VT, Value,
2578 DAG.getConstant(Shift, MVT::i8)), Value);
2585 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2586 /// used when a memcpy is turned into a memset when the source is a constant
2588 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2589 const TargetLowering &TLI,
2590 std::string &Str, unsigned Offset) {
2591 // Handle vector with all elements zero.
2594 return DAG.getConstant(0, VT);
2595 unsigned NumElts = VT.getVectorNumElements();
2596 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2597 return DAG.getNode(ISD::BIT_CONVERT, VT,
2598 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2601 assert(!VT.isVector() && "Can't handle vector type here!");
2602 unsigned NumBits = VT.getSizeInBits();
2603 unsigned MSB = NumBits / 8;
2605 if (TLI.isLittleEndian())
2606 Offset = Offset + MSB - 1;
2607 for (unsigned i = 0; i != MSB; ++i) {
2608 Val = (Val << 8) | (unsigned char)Str[Offset];
2609 Offset += TLI.isLittleEndian() ? -1 : 1;
2611 return DAG.getConstant(Val, VT);
2614 /// getMemBasePlusOffset - Returns base and offset node for the
2616 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2617 SelectionDAG &DAG) {
2618 MVT VT = Base.getValueType();
2619 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2622 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2624 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2625 unsigned SrcDelta = 0;
2626 GlobalAddressSDNode *G = NULL;
2627 if (Src.getOpcode() == ISD::GlobalAddress)
2628 G = cast<GlobalAddressSDNode>(Src);
2629 else if (Src.getOpcode() == ISD::ADD &&
2630 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2631 Src.getOperand(1).getOpcode() == ISD::Constant) {
2632 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2633 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2638 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2639 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2645 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2646 /// to replace the memset / memcpy is below the threshold. It also returns the
2647 /// types of the sequence of memory ops to perform memset / memcpy.
2649 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2650 SDOperand Dst, SDOperand Src,
2651 unsigned Limit, uint64_t Size, unsigned &Align,
2652 std::string &Str, bool &isSrcStr,
2654 const TargetLowering &TLI) {
2655 isSrcStr = isMemSrcFromString(Src, Str);
2656 bool isSrcConst = isa<ConstantSDNode>(Src);
2657 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2658 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2659 if (VT != MVT::iAny) {
2660 unsigned NewAlign = (unsigned)
2661 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2662 // If source is a string constant, this will require an unaligned load.
2663 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2664 if (Dst.getOpcode() != ISD::FrameIndex) {
2665 // Can't change destination alignment. It requires a unaligned store.
2669 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2670 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2671 if (MFI->isFixedObjectIndex(FI)) {
2672 // Can't change destination alignment. It requires a unaligned store.
2676 // Give the stack frame object a larger alignment if needed.
2677 if (MFI->getObjectAlignment(FI) < NewAlign)
2678 MFI->setObjectAlignment(FI, NewAlign);
2685 if (VT == MVT::iAny) {
2689 switch (Align & 7) {
2690 case 0: VT = MVT::i64; break;
2691 case 4: VT = MVT::i32; break;
2692 case 2: VT = MVT::i16; break;
2693 default: VT = MVT::i8; break;
2698 while (!TLI.isTypeLegal(LVT))
2699 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2700 assert(LVT.isInteger());
2706 unsigned NumMemOps = 0;
2708 unsigned VTSize = VT.getSizeInBits() / 8;
2709 while (VTSize > Size) {
2710 // For now, only use non-vector load / store's for the left-over pieces.
2711 if (VT.isVector()) {
2713 while (!TLI.isTypeLegal(VT))
2714 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2715 VTSize = VT.getSizeInBits() / 8;
2717 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2722 if (++NumMemOps > Limit)
2724 MemOps.push_back(VT);
2731 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2732 SDOperand Chain, SDOperand Dst,
2733 SDOperand Src, uint64_t Size,
2734 unsigned Align, bool AlwaysInline,
2735 const Value *DstSV, uint64_t DstSVOff,
2736 const Value *SrcSV, uint64_t SrcSVOff){
2737 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2739 // Expand memcpy to a series of load and store ops if the size operand falls
2740 // below a certain threshold.
2741 std::vector<MVT> MemOps;
2742 uint64_t Limit = -1;
2744 Limit = TLI.getMaxStoresPerMemcpy();
2745 unsigned DstAlign = Align; // Destination alignment can change.
2748 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2749 Str, CopyFromStr, DAG, TLI))
2753 bool isZeroStr = CopyFromStr && Str.empty();
2754 SmallVector<SDOperand, 8> OutChains;
2755 unsigned NumMemOps = MemOps.size();
2756 uint64_t SrcOff = 0, DstOff = 0;
2757 for (unsigned i = 0; i < NumMemOps; i++) {
2759 unsigned VTSize = VT.getSizeInBits() / 8;
2760 SDOperand Value, Store;
2762 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2763 // It's unlikely a store of a vector immediate can be done in a single
2764 // instruction. It would require a load from a constantpool first.
2765 // We also handle store a vector with all zero's.
2766 // FIXME: Handle other cases where store of vector immediate is done in
2767 // a single instruction.
2768 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2769 Store = DAG.getStore(Chain, Value,
2770 getMemBasePlusOffset(Dst, DstOff, DAG),
2771 DstSV, DstSVOff + DstOff);
2773 Value = DAG.getLoad(VT, Chain,
2774 getMemBasePlusOffset(Src, SrcOff, DAG),
2775 SrcSV, SrcSVOff + SrcOff, false, Align);
2776 Store = DAG.getStore(Chain, Value,
2777 getMemBasePlusOffset(Dst, DstOff, DAG),
2778 DstSV, DstSVOff + DstOff, false, DstAlign);
2780 OutChains.push_back(Store);
2785 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2786 &OutChains[0], OutChains.size());
2789 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2790 SDOperand Chain, SDOperand Dst,
2791 SDOperand Src, uint64_t Size,
2792 unsigned Align, bool AlwaysInline,
2793 const Value *DstSV, uint64_t DstSVOff,
2794 const Value *SrcSV, uint64_t SrcSVOff){
2795 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2797 // Expand memmove to a series of load and store ops if the size operand falls
2798 // below a certain threshold.
2799 std::vector<MVT> MemOps;
2800 uint64_t Limit = -1;
2802 Limit = TLI.getMaxStoresPerMemmove();
2803 unsigned DstAlign = Align; // Destination alignment can change.
2806 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2807 Str, CopyFromStr, DAG, TLI))
2810 uint64_t SrcOff = 0, DstOff = 0;
2812 SmallVector<SDOperand, 8> LoadValues;
2813 SmallVector<SDOperand, 8> LoadChains;
2814 SmallVector<SDOperand, 8> OutChains;
2815 unsigned NumMemOps = MemOps.size();
2816 for (unsigned i = 0; i < NumMemOps; i++) {
2818 unsigned VTSize = VT.getSizeInBits() / 8;
2819 SDOperand Value, Store;
2821 Value = DAG.getLoad(VT, Chain,
2822 getMemBasePlusOffset(Src, SrcOff, DAG),
2823 SrcSV, SrcSVOff + SrcOff, false, Align);
2824 LoadValues.push_back(Value);
2825 LoadChains.push_back(Value.getValue(1));
2828 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2829 &LoadChains[0], LoadChains.size());
2831 for (unsigned i = 0; i < NumMemOps; i++) {
2833 unsigned VTSize = VT.getSizeInBits() / 8;
2834 SDOperand Value, Store;
2836 Store = DAG.getStore(Chain, LoadValues[i],
2837 getMemBasePlusOffset(Dst, DstOff, DAG),
2838 DstSV, DstSVOff + DstOff, false, DstAlign);
2839 OutChains.push_back(Store);
2843 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2844 &OutChains[0], OutChains.size());
2847 static SDOperand getMemsetStores(SelectionDAG &DAG,
2848 SDOperand Chain, SDOperand Dst,
2849 SDOperand Src, uint64_t Size,
2851 const Value *DstSV, uint64_t DstSVOff) {
2852 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2854 // Expand memset to a series of load/store ops if the size operand
2855 // falls below a certain threshold.
2856 std::vector<MVT> MemOps;
2859 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2860 Size, Align, Str, CopyFromStr, DAG, TLI))
2863 SmallVector<SDOperand, 8> OutChains;
2864 uint64_t DstOff = 0;
2866 unsigned NumMemOps = MemOps.size();
2867 for (unsigned i = 0; i < NumMemOps; i++) {
2869 unsigned VTSize = VT.getSizeInBits() / 8;
2870 SDOperand Value = getMemsetValue(Src, VT, DAG);
2871 SDOperand Store = DAG.getStore(Chain, Value,
2872 getMemBasePlusOffset(Dst, DstOff, DAG),
2873 DstSV, DstSVOff + DstOff);
2874 OutChains.push_back(Store);
2878 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2879 &OutChains[0], OutChains.size());
2882 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2883 SDOperand Src, SDOperand Size,
2884 unsigned Align, bool AlwaysInline,
2885 const Value *DstSV, uint64_t DstSVOff,
2886 const Value *SrcSV, uint64_t SrcSVOff) {
2888 // Check to see if we should lower the memcpy to loads and stores first.
2889 // For cases within the target-specified limits, this is the best choice.
2890 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2892 // Memcpy with size zero? Just return the original chain.
2893 if (ConstantSize->isNullValue())
2897 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2898 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2903 // Then check to see if we should lower the memcpy with target-specific
2904 // code. If the target chooses to do this, this is the next best.
2906 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2908 DstSV, DstSVOff, SrcSV, SrcSVOff);
2912 // If we really need inline code and the target declined to provide it,
2913 // use a (potentially long) sequence of loads and stores.
2915 assert(ConstantSize && "AlwaysInline requires a constant size!");
2916 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2917 ConstantSize->getValue(), Align, true,
2918 DstSV, DstSVOff, SrcSV, SrcSVOff);
2921 // Emit a library call.
2922 TargetLowering::ArgListTy Args;
2923 TargetLowering::ArgListEntry Entry;
2924 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2925 Entry.Node = Dst; Args.push_back(Entry);
2926 Entry.Node = Src; Args.push_back(Entry);
2927 Entry.Node = Size; Args.push_back(Entry);
2928 std::pair<SDOperand,SDOperand> CallResult =
2929 TLI.LowerCallTo(Chain, Type::VoidTy,
2930 false, false, false, CallingConv::C, false,
2931 getExternalSymbol("memcpy", TLI.getPointerTy()),
2933 return CallResult.second;
2936 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2937 SDOperand Src, SDOperand Size,
2939 const Value *DstSV, uint64_t DstSVOff,
2940 const Value *SrcSV, uint64_t SrcSVOff) {
2942 // Check to see if we should lower the memmove to loads and stores first.
2943 // For cases within the target-specified limits, this is the best choice.
2944 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2946 // Memmove with size zero? Just return the original chain.
2947 if (ConstantSize->isNullValue())
2951 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2952 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2957 // Then check to see if we should lower the memmove with target-specific
2958 // code. If the target chooses to do this, this is the next best.
2960 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2961 DstSV, DstSVOff, SrcSV, SrcSVOff);
2965 // Emit a library call.
2966 TargetLowering::ArgListTy Args;
2967 TargetLowering::ArgListEntry Entry;
2968 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2969 Entry.Node = Dst; Args.push_back(Entry);
2970 Entry.Node = Src; Args.push_back(Entry);
2971 Entry.Node = Size; Args.push_back(Entry);
2972 std::pair<SDOperand,SDOperand> CallResult =
2973 TLI.LowerCallTo(Chain, Type::VoidTy,
2974 false, false, false, CallingConv::C, false,
2975 getExternalSymbol("memmove", TLI.getPointerTy()),
2977 return CallResult.second;
2980 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2981 SDOperand Src, SDOperand Size,
2983 const Value *DstSV, uint64_t DstSVOff) {
2985 // Check to see if we should lower the memset to stores first.
2986 // For cases within the target-specified limits, this is the best choice.
2987 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2989 // Memset with size zero? Just return the original chain.
2990 if (ConstantSize->isNullValue())
2994 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3000 // Then check to see if we should lower the memset with target-specific
3001 // code. If the target chooses to do this, this is the next best.
3003 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3008 // Emit a library call.
3009 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3010 TargetLowering::ArgListTy Args;
3011 TargetLowering::ArgListEntry Entry;
3012 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3013 Args.push_back(Entry);
3014 // Extend or truncate the argument to be an i32 value for the call.
3015 if (Src.getValueType().bitsGT(MVT::i32))
3016 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3018 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3019 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3020 Args.push_back(Entry);
3021 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3022 Args.push_back(Entry);
3023 std::pair<SDOperand,SDOperand> CallResult =
3024 TLI.LowerCallTo(Chain, Type::VoidTy,
3025 false, false, false, CallingConv::C, false,
3026 getExternalSymbol("memset", TLI.getPointerTy()),
3028 return CallResult.second;
3031 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3032 SDOperand Ptr, SDOperand Cmp,
3033 SDOperand Swp, const Value* PtrVal,
3034 unsigned Alignment) {
3035 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3036 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3037 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
3038 FoldingSetNodeID ID;
3039 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3040 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3042 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3043 return SDOperand(E, 0);
3044 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp,
3046 CSEMap.InsertNode(N, IP);
3047 AllNodes.push_back(N);
3048 return SDOperand(N, 0);
3051 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3052 SDOperand Ptr, SDOperand Val,
3053 const Value* PtrVal,
3054 unsigned Alignment) {
3055 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3056 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3057 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3058 || Opcode == ISD::ATOMIC_LOAD_NAND
3059 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3060 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3061 && "Invalid Atomic Op");
3062 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3063 FoldingSetNodeID ID;
3064 SDOperand Ops[] = {Chain, Ptr, Val};
3065 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3067 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3068 return SDOperand(E, 0);
3069 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val,
3071 CSEMap.InsertNode(N, IP);
3072 AllNodes.push_back(N);
3073 return SDOperand(N, 0);
3076 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3077 /// Allowed to return something different (and simpler) if Simplify is true.
3078 SDOperand SelectionDAG::getMergeValues(SDOperandPtr Ops, unsigned NumOps,
3080 if (Simplify && NumOps == 1)
3083 SmallVector<MVT, 4> VTs;
3084 VTs.reserve(NumOps);
3085 for (unsigned i = 0; i < NumOps; ++i)
3086 VTs.push_back(Ops[i].getValueType());
3087 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3091 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3092 MVT VT, SDOperand Chain,
3093 SDOperand Ptr, SDOperand Offset,
3094 const Value *SV, int SVOffset, MVT EVT,
3095 bool isVolatile, unsigned Alignment) {
3096 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3098 if (VT != MVT::iPTR) {
3099 Ty = VT.getTypeForMVT();
3101 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3102 assert(PT && "Value for load must be a pointer");
3103 Ty = PT->getElementType();
3105 assert(Ty && "Could not get type information for load");
3106 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3110 ExtType = ISD::NON_EXTLOAD;
3111 } else if (ExtType == ISD::NON_EXTLOAD) {
3112 assert(VT == EVT && "Non-extending load from different memory type!");
3116 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3118 assert(EVT.bitsLT(VT) &&
3119 "Should only be an extending load, not truncating!");
3120 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3121 "Cannot sign/zero extend a FP/Vector load!");
3122 assert(VT.isInteger() == EVT.isInteger() &&
3123 "Cannot convert from FP to Int or Int -> FP!");
3126 bool Indexed = AM != ISD::UNINDEXED;
3127 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3128 "Unindexed load with an offset!");
3130 SDVTList VTs = Indexed ?
3131 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3132 SDOperand Ops[] = { Chain, Ptr, Offset };
3133 FoldingSetNodeID ID;
3134 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3136 ID.AddInteger(ExtType);
3137 ID.AddInteger(EVT.getRawBits());
3138 ID.AddInteger(Alignment);
3139 ID.AddInteger(isVolatile);
3141 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3142 return SDOperand(E, 0);
3143 SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3144 Alignment, isVolatile);
3145 CSEMap.InsertNode(N, IP);
3146 AllNodes.push_back(N);
3147 return SDOperand(N, 0);
3150 SDOperand SelectionDAG::getLoad(MVT VT,
3151 SDOperand Chain, SDOperand Ptr,
3152 const Value *SV, int SVOffset,
3153 bool isVolatile, unsigned Alignment) {
3154 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3155 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3156 SV, SVOffset, VT, isVolatile, Alignment);
3159 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3160 SDOperand Chain, SDOperand Ptr,
3162 int SVOffset, MVT EVT,
3163 bool isVolatile, unsigned Alignment) {
3164 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3165 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3166 SV, SVOffset, EVT, isVolatile, Alignment);
3170 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3171 SDOperand Offset, ISD::MemIndexedMode AM) {
3172 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3173 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3174 "Load is already a indexed load!");
3175 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3176 LD->getChain(), Base, Offset, LD->getSrcValue(),
3177 LD->getSrcValueOffset(), LD->getMemoryVT(),
3178 LD->isVolatile(), LD->getAlignment());
3181 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3182 SDOperand Ptr, const Value *SV, int SVOffset,
3183 bool isVolatile, unsigned Alignment) {
3184 MVT VT = Val.getValueType();
3186 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3188 if (VT != MVT::iPTR) {
3189 Ty = VT.getTypeForMVT();
3191 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3192 assert(PT && "Value for store must be a pointer");
3193 Ty = PT->getElementType();
3195 assert(Ty && "Could not get type information for store");
3196 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3198 SDVTList VTs = getVTList(MVT::Other);
3199 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3200 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3201 FoldingSetNodeID ID;
3202 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3203 ID.AddInteger(ISD::UNINDEXED);
3204 ID.AddInteger(false);
3205 ID.AddInteger(VT.getRawBits());
3206 ID.AddInteger(Alignment);
3207 ID.AddInteger(isVolatile);
3209 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3210 return SDOperand(E, 0);
3211 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3212 VT, SV, SVOffset, Alignment, isVolatile);
3213 CSEMap.InsertNode(N, IP);
3214 AllNodes.push_back(N);
3215 return SDOperand(N, 0);
3218 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3219 SDOperand Ptr, const Value *SV,
3220 int SVOffset, MVT SVT,
3221 bool isVolatile, unsigned Alignment) {
3222 MVT VT = Val.getValueType();
3225 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3227 assert(VT.bitsGT(SVT) && "Not a truncation?");
3228 assert(VT.isInteger() == SVT.isInteger() &&
3229 "Can't do FP-INT conversion!");
3231 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3233 if (VT != MVT::iPTR) {
3234 Ty = VT.getTypeForMVT();
3236 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3237 assert(PT && "Value for store must be a pointer");
3238 Ty = PT->getElementType();
3240 assert(Ty && "Could not get type information for store");
3241 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3243 SDVTList VTs = getVTList(MVT::Other);
3244 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3245 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3246 FoldingSetNodeID ID;
3247 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3248 ID.AddInteger(ISD::UNINDEXED);
3250 ID.AddInteger(SVT.getRawBits());
3251 ID.AddInteger(Alignment);
3252 ID.AddInteger(isVolatile);
3254 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3255 return SDOperand(E, 0);
3256 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3257 SVT, SV, SVOffset, Alignment, isVolatile);
3258 CSEMap.InsertNode(N, IP);
3259 AllNodes.push_back(N);
3260 return SDOperand(N, 0);
3264 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3265 SDOperand Offset, ISD::MemIndexedMode AM) {
3266 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3267 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3268 "Store is already a indexed store!");
3269 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3270 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3271 FoldingSetNodeID ID;
3272 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3274 ID.AddInteger(ST->isTruncatingStore());
3275 ID.AddInteger(ST->getMemoryVT().getRawBits());
3276 ID.AddInteger(ST->getAlignment());
3277 ID.AddInteger(ST->isVolatile());
3279 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3280 return SDOperand(E, 0);
3281 SDNode *N = new StoreSDNode(Ops, VTs, AM,
3282 ST->isTruncatingStore(), ST->getMemoryVT(),
3283 ST->getSrcValue(), ST->getSrcValueOffset(),
3284 ST->getAlignment(), ST->isVolatile());
3285 CSEMap.InsertNode(N, IP);
3286 AllNodes.push_back(N);
3287 return SDOperand(N, 0);
3290 SDOperand SelectionDAG::getVAArg(MVT VT,
3291 SDOperand Chain, SDOperand Ptr,
3293 SDOperand Ops[] = { Chain, Ptr, SV };
3294 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3297 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3298 SDOperandPtr Ops, unsigned NumOps) {
3300 case 0: return getNode(Opcode, VT);
3301 case 1: return getNode(Opcode, VT, Ops[0]);
3302 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3303 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3309 case ISD::SELECT_CC: {
3310 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3311 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3312 "LHS and RHS of condition must have same type!");
3313 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3314 "True and False arms of SelectCC must have same type!");
3315 assert(Ops[2].getValueType() == VT &&
3316 "select_cc node must be of same type as true and false value!");
3320 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3321 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3322 "LHS/RHS of comparison should match types!");
3329 SDVTList VTs = getVTList(VT);
3330 if (VT != MVT::Flag) {
3331 FoldingSetNodeID ID;
3332 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3334 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3335 return SDOperand(E, 0);
3336 N = new SDNode(Opcode, VTs, Ops, NumOps);
3337 CSEMap.InsertNode(N, IP);
3339 N = new SDNode(Opcode, VTs, Ops, NumOps);
3341 AllNodes.push_back(N);
3342 return SDOperand(N, 0);
3345 SDOperand SelectionDAG::getNode(unsigned Opcode,
3346 std::vector<MVT> &ResultTys,
3347 SDOperandPtr Ops, unsigned NumOps) {
3348 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3352 SDOperand SelectionDAG::getNode(unsigned Opcode,
3353 const MVT *VTs, unsigned NumVTs,
3354 SDOperandPtr Ops, unsigned NumOps) {
3356 return getNode(Opcode, VTs[0], Ops, NumOps);
3357 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3360 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3361 SDOperandPtr Ops, unsigned NumOps) {
3362 if (VTList.NumVTs == 1)
3363 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3366 // FIXME: figure out how to safely handle things like
3367 // int foo(int x) { return 1 << (x & 255); }
3368 // int bar() { return foo(256); }
3370 case ISD::SRA_PARTS:
3371 case ISD::SRL_PARTS:
3372 case ISD::SHL_PARTS:
3373 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3374 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3375 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3376 else if (N3.getOpcode() == ISD::AND)
3377 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3378 // If the and is only masking out bits that cannot effect the shift,
3379 // eliminate the and.
3380 unsigned NumBits = VT.getSizeInBits()*2;
3381 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3382 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3388 // Memoize the node unless it returns a flag.
3390 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3391 FoldingSetNodeID ID;
3392 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3394 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3395 return SDOperand(E, 0);
3397 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3398 else if (NumOps == 2)
3399 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3400 else if (NumOps == 3)
3401 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3403 N = new SDNode(Opcode, VTList, Ops, NumOps);
3404 CSEMap.InsertNode(N, IP);
3407 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3408 else if (NumOps == 2)
3409 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3410 else if (NumOps == 3)
3411 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3413 N = new SDNode(Opcode, VTList, Ops, NumOps);
3415 AllNodes.push_back(N);
3416 return SDOperand(N, 0);
3419 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3420 return getNode(Opcode, VTList, (SDOperand*)0, 0);
3423 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3425 SDOperand Ops[] = { N1 };
3426 return getNode(Opcode, VTList, Ops, 1);
3429 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3430 SDOperand N1, SDOperand N2) {
3431 SDOperand Ops[] = { N1, N2 };
3432 return getNode(Opcode, VTList, Ops, 2);
3435 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3436 SDOperand N1, SDOperand N2, SDOperand N3) {
3437 SDOperand Ops[] = { N1, N2, N3 };
3438 return getNode(Opcode, VTList, Ops, 3);
3441 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3442 SDOperand N1, SDOperand N2, SDOperand N3,
3444 SDOperand Ops[] = { N1, N2, N3, N4 };
3445 return getNode(Opcode, VTList, Ops, 4);
3448 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3449 SDOperand N1, SDOperand N2, SDOperand N3,
3450 SDOperand N4, SDOperand N5) {
3451 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3452 return getNode(Opcode, VTList, Ops, 5);
3455 SDVTList SelectionDAG::getVTList(MVT VT) {
3456 return makeVTList(SDNode::getValueTypeList(VT), 1);
3459 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3460 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3461 E = VTList.end(); I != E; ++I) {
3462 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3463 return makeVTList(&(*I)[0], 2);
3468 VTList.push_front(V);
3469 return makeVTList(&(*VTList.begin())[0], 2);
3471 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3473 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3474 E = VTList.end(); I != E; ++I) {
3475 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3477 return makeVTList(&(*I)[0], 3);
3483 VTList.push_front(V);
3484 return makeVTList(&(*VTList.begin())[0], 3);
3487 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3489 case 0: assert(0 && "Cannot have nodes without results!");
3490 case 1: return getVTList(VTs[0]);
3491 case 2: return getVTList(VTs[0], VTs[1]);
3492 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3496 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3497 E = VTList.end(); I != E; ++I) {
3498 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3500 bool NoMatch = false;
3501 for (unsigned i = 2; i != NumVTs; ++i)
3502 if (VTs[i] != (*I)[i]) {
3507 return makeVTList(&*I->begin(), NumVTs);
3510 VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3511 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3515 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3516 /// specified operands. If the resultant node already exists in the DAG,
3517 /// this does not modify the specified node, instead it returns the node that
3518 /// already exists. If the resultant node does not exist in the DAG, the
3519 /// input node is returned. As a degenerate case, if you specify the same
3520 /// input operands as the node already has, the input node is returned.
3521 SDOperand SelectionDAG::
3522 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3523 SDNode *N = InN.Val;
3524 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3526 // Check to see if there is no change.
3527 if (Op == N->getOperand(0)) return InN;
3529 // See if the modified node already exists.
3530 void *InsertPos = 0;
3531 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3532 return SDOperand(Existing, InN.ResNo);
3534 // Nope it doesn't. Remove the node from it's current place in the maps.
3536 RemoveNodeFromCSEMaps(N);
3538 // Now we update the operands.
3539 N->OperandList[0].getVal()->removeUser(0, N);
3540 N->OperandList[0] = Op;
3541 N->OperandList[0].setUser(N);
3542 Op.Val->addUser(0, N);
3544 // If this gets put into a CSE map, add it.
3545 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3549 SDOperand SelectionDAG::
3550 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3551 SDNode *N = InN.Val;
3552 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3554 // Check to see if there is no change.
3555 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3556 return InN; // No operands changed, just return the input node.
3558 // See if the modified node already exists.
3559 void *InsertPos = 0;
3560 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3561 return SDOperand(Existing, InN.ResNo);
3563 // Nope it doesn't. Remove the node from it's current place in the maps.
3565 RemoveNodeFromCSEMaps(N);
3567 // Now we update the operands.
3568 if (N->OperandList[0] != Op1) {
3569 N->OperandList[0].getVal()->removeUser(0, N);
3570 N->OperandList[0] = Op1;
3571 N->OperandList[0].setUser(N);
3572 Op1.Val->addUser(0, N);
3574 if (N->OperandList[1] != Op2) {
3575 N->OperandList[1].getVal()->removeUser(1, N);
3576 N->OperandList[1] = Op2;
3577 N->OperandList[1].setUser(N);
3578 Op2.Val->addUser(1, N);
3581 // If this gets put into a CSE map, add it.
3582 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3586 SDOperand SelectionDAG::
3587 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3588 SDOperand Ops[] = { Op1, Op2, Op3 };
3589 return UpdateNodeOperands(N, Ops, 3);
3592 SDOperand SelectionDAG::
3593 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3594 SDOperand Op3, SDOperand Op4) {
3595 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3596 return UpdateNodeOperands(N, Ops, 4);
3599 SDOperand SelectionDAG::
3600 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3601 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3602 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3603 return UpdateNodeOperands(N, Ops, 5);
3606 SDOperand SelectionDAG::
3607 UpdateNodeOperands(SDOperand InN, SDOperandPtr Ops, unsigned NumOps) {
3608 SDNode *N = InN.Val;
3609 assert(N->getNumOperands() == NumOps &&
3610 "Update with wrong number of operands");
3612 // Check to see if there is no change.
3613 bool AnyChange = false;
3614 for (unsigned i = 0; i != NumOps; ++i) {
3615 if (Ops[i] != N->getOperand(i)) {
3621 // No operands changed, just return the input node.
3622 if (!AnyChange) return InN;
3624 // See if the modified node already exists.
3625 void *InsertPos = 0;
3626 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3627 return SDOperand(Existing, InN.ResNo);
3629 // Nope it doesn't. Remove the node from its current place in the maps.
3631 RemoveNodeFromCSEMaps(N);
3633 // Now we update the operands.
3634 for (unsigned i = 0; i != NumOps; ++i) {
3635 if (N->OperandList[i] != Ops[i]) {
3636 N->OperandList[i].getVal()->removeUser(i, N);
3637 N->OperandList[i] = Ops[i];
3638 N->OperandList[i].setUser(N);
3639 Ops[i].Val->addUser(i, N);
3643 // If this gets put into a CSE map, add it.
3644 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3648 /// MorphNodeTo - This frees the operands of the current node, resets the
3649 /// opcode, types, and operands to the specified value. This should only be
3650 /// used by the SelectionDAG class.
3651 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3652 SDOperandPtr Ops, unsigned NumOps) {
3655 NumValues = L.NumVTs;
3657 // Clear the operands list, updating used nodes to remove this from their
3659 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3660 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3662 // If NumOps is larger than the # of operands we currently have, reallocate
3663 // the operand list.
3664 if (NumOps > NumOperands) {
3665 if (OperandsNeedDelete) {
3666 delete [] OperandList;
3668 OperandList = new SDUse[NumOps];
3669 OperandsNeedDelete = true;
3672 // Assign the new operands.
3673 NumOperands = NumOps;
3675 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3676 OperandList[i] = Ops[i];
3677 OperandList[i].setUser(this);
3678 SDNode *N = OperandList[i].getVal();
3679 N->addUser(i, this);
3684 /// SelectNodeTo - These are used for target selectors to *mutate* the
3685 /// specified node to have the specified return type, Target opcode, and
3686 /// operands. Note that target opcodes are stored as
3687 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3689 /// Note that SelectNodeTo returns the resultant node. If there is already a
3690 /// node of the specified opcode and operands, it returns that node instead of
3691 /// the current one.
3692 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3694 SDVTList VTs = getVTList(VT);
3695 return SelectNodeTo(N, TargetOpc, VTs, (SDOperand*)0, 0);
3698 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3699 MVT VT, SDOperand Op1) {
3700 SDVTList VTs = getVTList(VT);
3701 SDOperand Ops[] = { Op1 };
3702 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3705 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3706 MVT VT, SDOperand Op1,
3708 SDVTList VTs = getVTList(VT);
3709 SDOperand Ops[] = { Op1, Op2 };
3710 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3713 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3714 MVT VT, SDOperand Op1,
3715 SDOperand Op2, SDOperand Op3) {
3716 SDVTList VTs = getVTList(VT);
3717 SDOperand Ops[] = { Op1, Op2, Op3 };
3718 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3721 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3722 MVT VT, SDOperandPtr Ops,
3724 SDVTList VTs = getVTList(VT);
3725 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3728 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3729 MVT VT1, MVT VT2, SDOperandPtr Ops,
3731 SDVTList VTs = getVTList(VT1, VT2);
3732 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3735 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3737 SDVTList VTs = getVTList(VT1, VT2);
3738 return SelectNodeTo(N, TargetOpc, VTs, (SDOperand *)0, 0);
3741 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3742 MVT VT1, MVT VT2, MVT VT3, SDOperandPtr Ops,
3744 SDVTList VTs = getVTList(VT1, VT2, VT3);
3745 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3748 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3751 SDVTList VTs = getVTList(VT1, VT2);
3752 SDOperand Ops[] = { Op1 };
3753 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3756 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3758 SDOperand Op1, SDOperand Op2) {
3759 SDVTList VTs = getVTList(VT1, VT2);
3760 SDOperand Ops[] = { Op1, Op2 };
3761 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3764 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3766 SDOperand Op1, SDOperand Op2,
3768 SDVTList VTs = getVTList(VT1, VT2);
3769 SDOperand Ops[] = { Op1, Op2, Op3 };
3770 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3773 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3774 SDVTList VTs, SDOperandPtr Ops,
3776 // If an identical node already exists, use it.
3777 FoldingSetNodeID ID;
3778 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3780 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3783 RemoveNodeFromCSEMaps(N);
3785 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3786 CSEMap.InsertNode(N, IP); // Memoize the new node.
3791 /// getTargetNode - These are used for target selectors to create a new node
3792 /// with specified return type(s), target opcode, and operands.
3794 /// Note that getTargetNode returns the resultant node. If there is already a
3795 /// node of the specified opcode and operands, it returns that node instead of
3796 /// the current one.
3797 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3798 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3800 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3801 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3803 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3804 SDOperand Op1, SDOperand Op2) {
3805 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3807 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3808 SDOperand Op1, SDOperand Op2,
3810 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3812 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3813 SDOperandPtr Ops, unsigned NumOps) {
3814 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3816 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3817 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3819 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3821 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3822 MVT VT2, SDOperand Op1) {
3823 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3824 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3826 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3827 MVT VT2, SDOperand Op1,
3829 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3830 SDOperand Ops[] = { Op1, Op2 };
3831 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3833 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3834 MVT VT2, SDOperand Op1,
3835 SDOperand Op2, SDOperand Op3) {
3836 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3837 SDOperand Ops[] = { Op1, Op2, Op3 };
3838 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3840 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3841 SDOperandPtr Ops, unsigned NumOps) {
3842 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3843 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3845 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3846 SDOperand Op1, SDOperand Op2) {
3847 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3848 SDOperand Ops[] = { Op1, Op2 };
3849 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3851 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3852 SDOperand Op1, SDOperand Op2,
3854 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3855 SDOperand Ops[] = { Op1, Op2, Op3 };
3856 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3858 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3859 SDOperandPtr Ops, unsigned NumOps) {
3860 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3861 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3863 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3864 MVT VT2, MVT VT3, MVT VT4,
3865 SDOperandPtr Ops, unsigned NumOps) {
3866 std::vector<MVT> VTList;
3867 VTList.push_back(VT1);
3868 VTList.push_back(VT2);
3869 VTList.push_back(VT3);
3870 VTList.push_back(VT4);
3871 const MVT *VTs = getNodeValueTypes(VTList);
3872 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3874 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3875 std::vector<MVT> &ResultTys,
3876 SDOperandPtr Ops, unsigned NumOps) {
3877 const MVT *VTs = getNodeValueTypes(ResultTys);
3878 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3882 /// getNodeIfExists - Get the specified node if it's already available, or
3883 /// else return NULL.
3884 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3885 SDOperandPtr Ops, unsigned NumOps) {
3886 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3887 FoldingSetNodeID ID;
3888 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3890 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3897 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3898 /// This can cause recursive merging of nodes in the DAG.
3900 /// This version assumes From has a single result value.
3902 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3903 DAGUpdateListener *UpdateListener) {
3904 SDNode *From = FromN.Val;
3905 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3906 "Cannot replace with this method!");
3907 assert(From != To.Val && "Cannot replace uses of with self");
3909 while (!From->use_empty()) {
3910 SDNode::use_iterator UI = From->use_begin();
3911 SDNode *U = UI->getUser();
3913 // This node is about to morph, remove its old self from the CSE maps.
3914 RemoveNodeFromCSEMaps(U);
3916 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3917 I != E; ++I, ++operandNum)
3918 if (I->getVal() == From) {
3919 From->removeUser(operandNum, U);
3922 To.Val->addUser(operandNum, U);
3925 // Now that we have modified U, add it back to the CSE maps. If it already
3926 // exists there, recursively merge the results together.
3927 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3928 ReplaceAllUsesWith(U, Existing, UpdateListener);
3929 // U is now dead. Inform the listener if it exists and delete it.
3931 UpdateListener->NodeDeleted(U, Existing);
3932 DeleteNodeNotInCSEMaps(U);
3934 // If the node doesn't already exist, we updated it. Inform a listener if
3937 UpdateListener->NodeUpdated(U);
3942 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3943 /// This can cause recursive merging of nodes in the DAG.
3945 /// This version assumes From/To have matching types and numbers of result
3948 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3949 DAGUpdateListener *UpdateListener) {
3950 assert(From != To && "Cannot replace uses of with self");
3951 assert(From->getNumValues() == To->getNumValues() &&
3952 "Cannot use this version of ReplaceAllUsesWith!");
3953 if (From->getNumValues() == 1) // If possible, use the faster version.
3954 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3957 while (!From->use_empty()) {
3958 SDNode::use_iterator UI = From->use_begin();
3959 SDNode *U = UI->getUser();
3961 // This node is about to morph, remove its old self from the CSE maps.
3962 RemoveNodeFromCSEMaps(U);
3964 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3965 I != E; ++I, ++operandNum)
3966 if (I->getVal() == From) {
3967 From->removeUser(operandNum, U);
3969 To->addUser(operandNum, U);
3972 // Now that we have modified U, add it back to the CSE maps. If it already
3973 // exists there, recursively merge the results together.
3974 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3975 ReplaceAllUsesWith(U, Existing, UpdateListener);
3976 // U is now dead. Inform the listener if it exists and delete it.
3978 UpdateListener->NodeDeleted(U, Existing);
3979 DeleteNodeNotInCSEMaps(U);
3981 // If the node doesn't already exist, we updated it. Inform a listener if
3984 UpdateListener->NodeUpdated(U);
3989 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3990 /// This can cause recursive merging of nodes in the DAG.
3992 /// This version can replace From with any result values. To must match the
3993 /// number and types of values returned by From.
3994 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3996 DAGUpdateListener *UpdateListener) {
3997 if (From->getNumValues() == 1) // Handle the simple case efficiently.
3998 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
4000 while (!From->use_empty()) {
4001 SDNode::use_iterator UI = From->use_begin();
4002 SDNode *U = UI->getUser();
4004 // This node is about to morph, remove its old self from the CSE maps.
4005 RemoveNodeFromCSEMaps(U);
4007 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4008 I != E; ++I, ++operandNum)
4009 if (I->getVal() == From) {
4010 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4011 From->removeUser(operandNum, U);
4014 ToOp.Val->addUser(operandNum, U);
4017 // Now that we have modified U, add it back to the CSE maps. If it already
4018 // exists there, recursively merge the results together.
4019 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4020 ReplaceAllUsesWith(U, Existing, UpdateListener);
4021 // U is now dead. Inform the listener if it exists and delete it.
4023 UpdateListener->NodeDeleted(U, Existing);
4024 DeleteNodeNotInCSEMaps(U);
4026 // If the node doesn't already exist, we updated it. Inform a listener if
4029 UpdateListener->NodeUpdated(U);
4035 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4036 /// any deleted nodes from the set passed into its constructor and recursively
4037 /// notifies another update listener if specified.
4038 class ChainedSetUpdaterListener :
4039 public SelectionDAG::DAGUpdateListener {
4040 SmallSetVector<SDNode*, 16> &Set;
4041 SelectionDAG::DAGUpdateListener *Chain;
4043 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4044 SelectionDAG::DAGUpdateListener *chain)
4045 : Set(set), Chain(chain) {}
4047 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4049 if (Chain) Chain->NodeDeleted(N, E);
4051 virtual void NodeUpdated(SDNode *N) {
4052 if (Chain) Chain->NodeUpdated(N);
4057 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4058 /// uses of other values produced by From.Val alone. The Deleted vector is
4059 /// handled the same way as for ReplaceAllUsesWith.
4060 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4061 DAGUpdateListener *UpdateListener){
4062 assert(From != To && "Cannot replace a value with itself");
4064 // Handle the simple, trivial, case efficiently.
4065 if (From.Val->getNumValues() == 1) {
4066 ReplaceAllUsesWith(From, To, UpdateListener);
4070 if (From.use_empty()) return;
4072 // Get all of the users of From.Val. We want these in a nice,
4073 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4074 SmallSetVector<SDNode*, 16> Users;
4075 for (SDNode::use_iterator UI = From.Val->use_begin(),
4076 E = From.Val->use_end(); UI != E; ++UI) {
4077 SDNode *User = UI->getUser();
4081 // When one of the recursive merges deletes nodes from the graph, we need to
4082 // make sure that UpdateListener is notified *and* that the node is removed
4083 // from Users if present. CSUL does this.
4084 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4086 while (!Users.empty()) {
4087 // We know that this user uses some value of From. If it is the right
4088 // value, update it.
4089 SDNode *User = Users.back();
4092 // Scan for an operand that matches From.
4093 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4094 for (; Op != E; ++Op)
4095 if (*Op == From) break;
4097 // If there are no matches, the user must use some other result of From.
4098 if (Op == E) continue;
4100 // Okay, we know this user needs to be updated. Remove its old self
4101 // from the CSE maps.
4102 RemoveNodeFromCSEMaps(User);
4104 // Update all operands that match "From" in case there are multiple uses.
4105 for (; Op != E; ++Op) {
4107 From.Val->removeUser(Op-User->op_begin(), User);
4110 To.Val->addUser(Op-User->op_begin(), User);
4114 // Now that we have modified User, add it back to the CSE maps. If it
4115 // already exists there, recursively merge the results together.
4116 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4118 if (UpdateListener) UpdateListener->NodeUpdated(User);
4119 continue; // Continue on to next user.
4122 // If there was already an existing matching node, use ReplaceAllUsesWith
4123 // to replace the dead one with the existing one. This can cause
4124 // recursive merging of other unrelated nodes down the line. The merging
4125 // can cause deletion of nodes that used the old value. To handle this, we
4126 // use CSUL to remove them from the Users set.
4127 ReplaceAllUsesWith(User, Existing, &CSUL);
4129 // User is now dead. Notify a listener if present.
4130 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4131 DeleteNodeNotInCSEMaps(User);
4135 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4136 /// their allnodes order. It returns the maximum id.
4137 unsigned SelectionDAG::AssignNodeIds() {
4139 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4146 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4147 /// based on their topological order. It returns the maximum id and a vector
4148 /// of the SDNodes* in assigned order by reference.
4149 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4150 unsigned DAGSize = AllNodes.size();
4151 std::vector<unsigned> InDegree(DAGSize);
4152 std::vector<SDNode*> Sources;
4154 // Use a two pass approach to avoid using a std::map which is slow.
4156 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4159 unsigned Degree = N->use_size();
4160 InDegree[N->getNodeId()] = Degree;
4162 Sources.push_back(N);
4166 while (!Sources.empty()) {
4167 SDNode *N = Sources.back();
4169 TopOrder.push_back(N);
4170 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4171 SDNode *P = I->getVal();
4172 unsigned Degree = --InDegree[P->getNodeId()];
4174 Sources.push_back(P);
4178 // Second pass, assign the actual topological order as node ids.
4180 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4182 (*TI)->setNodeId(Id++);
4189 //===----------------------------------------------------------------------===//
4191 //===----------------------------------------------------------------------===//
4193 // Out-of-line virtual method to give class a home.
4194 void SDNode::ANCHOR() {}
4195 void UnarySDNode::ANCHOR() {}
4196 void BinarySDNode::ANCHOR() {}
4197 void TernarySDNode::ANCHOR() {}
4198 void HandleSDNode::ANCHOR() {}
4199 void ConstantSDNode::ANCHOR() {}
4200 void ConstantFPSDNode::ANCHOR() {}
4201 void GlobalAddressSDNode::ANCHOR() {}
4202 void FrameIndexSDNode::ANCHOR() {}
4203 void JumpTableSDNode::ANCHOR() {}
4204 void ConstantPoolSDNode::ANCHOR() {}
4205 void BasicBlockSDNode::ANCHOR() {}
4206 void SrcValueSDNode::ANCHOR() {}
4207 void MemOperandSDNode::ANCHOR() {}
4208 void RegisterSDNode::ANCHOR() {}
4209 void DbgStopPointSDNode::ANCHOR() {}
4210 void LabelSDNode::ANCHOR() {}
4211 void ExternalSymbolSDNode::ANCHOR() {}
4212 void CondCodeSDNode::ANCHOR() {}
4213 void ARG_FLAGSSDNode::ANCHOR() {}
4214 void VTSDNode::ANCHOR() {}
4215 void MemSDNode::ANCHOR() {}
4216 void LoadSDNode::ANCHOR() {}
4217 void StoreSDNode::ANCHOR() {}
4218 void AtomicSDNode::ANCHOR() {}
4220 HandleSDNode::~HandleSDNode() {
4221 SDVTList VTs = { 0, 0 };
4222 MorphNodeTo(ISD::HANDLENODE, VTs, SDOperandPtr(), 0); // Drops operand uses.
4225 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4227 : SDNode(isa<GlobalVariable>(GA) &&
4228 cast<GlobalVariable>(GA)->isThreadLocal() ?
4230 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4232 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4233 getSDVTList(VT)), Offset(o) {
4234 TheGlobal = const_cast<GlobalValue*>(GA);
4237 /// getMemOperand - Return a MachineMemOperand object describing the memory
4238 /// reference performed by this atomic.
4239 MachineMemOperand AtomicSDNode::getMemOperand() const {
4240 int Size = (getValueType(0).getSizeInBits() + 7) >> 3;
4241 int Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4242 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4244 // Check if the atomic references a frame index
4245 const FrameIndexSDNode *FI =
4246 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4247 if (!getSrcValue() && FI)
4248 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4249 FI->getIndex(), Size, getAlignment());
4251 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4252 Size, getAlignment());
4255 /// getMemOperand - Return a MachineMemOperand object describing the memory
4256 /// reference performed by this load or store.
4257 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4258 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4260 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4261 MachineMemOperand::MOStore;
4262 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4264 // Check if the load references a frame index, and does not have
4266 const FrameIndexSDNode *FI =
4267 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4268 if (!getSrcValue() && FI)
4269 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4270 FI->getIndex(), Size, getAlignment());
4272 return MachineMemOperand(getSrcValue(), Flags,
4273 getSrcValueOffset(), Size, getAlignment());
4276 /// Profile - Gather unique data for the node.
4278 void SDNode::Profile(FoldingSetNodeID &ID) {
4279 AddNodeIDNode(ID, this);
4282 /// getValueTypeList - Return a pointer to the specified value type.
4284 const MVT *SDNode::getValueTypeList(MVT VT) {
4285 if (VT.isExtended()) {
4286 static std::set<MVT, MVT::compareRawBits> EVTs;
4287 return &(*EVTs.insert(VT).first);
4289 static MVT VTs[MVT::LAST_VALUETYPE];
4290 VTs[VT.getSimpleVT()] = VT;
4291 return &VTs[VT.getSimpleVT()];
4295 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4296 /// indicated value. This method ignores uses of other values defined by this
4298 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4299 assert(Value < getNumValues() && "Bad value!");
4301 // If there is only one value, this is easy.
4302 if (getNumValues() == 1)
4303 return use_size() == NUses;
4304 if (use_size() < NUses) return false;
4306 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4308 SmallPtrSet<SDNode*, 32> UsersHandled;
4310 // TODO: Only iterate over uses of a given value of the node
4311 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4312 if (*UI == TheValue) {
4319 // Found exactly the right number of uses?
4324 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4325 /// value. This method ignores uses of other values defined by this operation.
4326 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4327 assert(Value < getNumValues() && "Bad value!");
4329 if (use_empty()) return false;
4331 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4333 SmallPtrSet<SDNode*, 32> UsersHandled;
4335 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4336 SDNode *User = UI->getUser();
4337 if (User->getNumOperands() == 1 ||
4338 UsersHandled.insert(User)) // First time we've seen this?
4339 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4340 if (User->getOperand(i) == TheValue) {
4349 /// isOnlyUseOf - Return true if this node is the only use of N.
4351 bool SDNode::isOnlyUseOf(SDNode *N) const {
4353 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4354 SDNode *User = I->getUser();
4364 /// isOperand - Return true if this node is an operand of N.
4366 bool SDOperand::isOperandOf(SDNode *N) const {
4367 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4368 if (*this == N->getOperand(i))
4373 bool SDNode::isOperandOf(SDNode *N) const {
4374 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4375 if (this == N->OperandList[i].getVal())
4380 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4381 /// be a chain) reaches the specified operand without crossing any
4382 /// side-effecting instructions. In practice, this looks through token
4383 /// factors and non-volatile loads. In order to remain efficient, this only
4384 /// looks a couple of nodes in, it does not do an exhaustive search.
4385 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4386 unsigned Depth) const {
4387 if (*this == Dest) return true;
4389 // Don't search too deeply, we just want to be able to see through
4390 // TokenFactor's etc.
4391 if (Depth == 0) return false;
4393 // If this is a token factor, all inputs to the TF happen in parallel. If any
4394 // of the operands of the TF reach dest, then we can do the xform.
4395 if (getOpcode() == ISD::TokenFactor) {
4396 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4397 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4402 // Loads don't have side effects, look through them.
4403 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4404 if (!Ld->isVolatile())
4405 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4411 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4412 SmallPtrSet<SDNode *, 32> &Visited) {
4413 if (found || !Visited.insert(N))
4416 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4417 SDNode *Op = N->getOperand(i).Val;
4422 findPredecessor(Op, P, found, Visited);
4426 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4427 /// is either an operand of N or it can be reached by recursively traversing
4428 /// up the operands.
4429 /// NOTE: this is an expensive method. Use it carefully.
4430 bool SDNode::isPredecessorOf(SDNode *N) const {
4431 SmallPtrSet<SDNode *, 32> Visited;
4433 findPredecessor(N, this, found, Visited);
4437 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4438 assert(Num < NumOperands && "Invalid child # of SDNode!");
4439 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4442 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4443 switch (getOpcode()) {
4445 if (getOpcode() < ISD::BUILTIN_OP_END)
4446 return "<<Unknown DAG Node>>";
4449 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4450 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4451 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4453 TargetLowering &TLI = G->getTargetLoweringInfo();
4455 TLI.getTargetNodeName(getOpcode());
4456 if (Name) return Name;
4459 return "<<Unknown Target Node>>";
4462 case ISD::PREFETCH: return "Prefetch";
4463 case ISD::MEMBARRIER: return "MemBarrier";
4464 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4465 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4466 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4467 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4468 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4469 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4470 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4471 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4472 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4473 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4474 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4475 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4476 case ISD::PCMARKER: return "PCMarker";
4477 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4478 case ISD::SRCVALUE: return "SrcValue";
4479 case ISD::MEMOPERAND: return "MemOperand";
4480 case ISD::EntryToken: return "EntryToken";
4481 case ISD::TokenFactor: return "TokenFactor";
4482 case ISD::AssertSext: return "AssertSext";
4483 case ISD::AssertZext: return "AssertZext";
4485 case ISD::BasicBlock: return "BasicBlock";
4486 case ISD::ARG_FLAGS: return "ArgFlags";
4487 case ISD::VALUETYPE: return "ValueType";
4488 case ISD::Register: return "Register";
4490 case ISD::Constant: return "Constant";
4491 case ISD::ConstantFP: return "ConstantFP";
4492 case ISD::GlobalAddress: return "GlobalAddress";
4493 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4494 case ISD::FrameIndex: return "FrameIndex";
4495 case ISD::JumpTable: return "JumpTable";
4496 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4497 case ISD::RETURNADDR: return "RETURNADDR";
4498 case ISD::FRAMEADDR: return "FRAMEADDR";
4499 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4500 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4501 case ISD::EHSELECTION: return "EHSELECTION";
4502 case ISD::EH_RETURN: return "EH_RETURN";
4503 case ISD::ConstantPool: return "ConstantPool";
4504 case ISD::ExternalSymbol: return "ExternalSymbol";
4505 case ISD::INTRINSIC_WO_CHAIN: {
4506 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4507 return Intrinsic::getName((Intrinsic::ID)IID);
4509 case ISD::INTRINSIC_VOID:
4510 case ISD::INTRINSIC_W_CHAIN: {
4511 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4512 return Intrinsic::getName((Intrinsic::ID)IID);
4515 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4516 case ISD::TargetConstant: return "TargetConstant";
4517 case ISD::TargetConstantFP:return "TargetConstantFP";
4518 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4519 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4520 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4521 case ISD::TargetJumpTable: return "TargetJumpTable";
4522 case ISD::TargetConstantPool: return "TargetConstantPool";
4523 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4525 case ISD::CopyToReg: return "CopyToReg";
4526 case ISD::CopyFromReg: return "CopyFromReg";
4527 case ISD::UNDEF: return "undef";
4528 case ISD::MERGE_VALUES: return "merge_values";
4529 case ISD::INLINEASM: return "inlineasm";
4530 case ISD::DBG_LABEL: return "dbg_label";
4531 case ISD::EH_LABEL: return "eh_label";
4532 case ISD::DECLARE: return "declare";
4533 case ISD::HANDLENODE: return "handlenode";
4534 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4535 case ISD::CALL: return "call";
4538 case ISD::FABS: return "fabs";
4539 case ISD::FNEG: return "fneg";
4540 case ISD::FSQRT: return "fsqrt";
4541 case ISD::FSIN: return "fsin";
4542 case ISD::FCOS: return "fcos";
4543 case ISD::FPOWI: return "fpowi";
4544 case ISD::FPOW: return "fpow";
4547 case ISD::ADD: return "add";
4548 case ISD::SUB: return "sub";
4549 case ISD::MUL: return "mul";
4550 case ISD::MULHU: return "mulhu";
4551 case ISD::MULHS: return "mulhs";
4552 case ISD::SDIV: return "sdiv";
4553 case ISD::UDIV: return "udiv";
4554 case ISD::SREM: return "srem";
4555 case ISD::UREM: return "urem";
4556 case ISD::SMUL_LOHI: return "smul_lohi";
4557 case ISD::UMUL_LOHI: return "umul_lohi";
4558 case ISD::SDIVREM: return "sdivrem";
4559 case ISD::UDIVREM: return "divrem";
4560 case ISD::AND: return "and";
4561 case ISD::OR: return "or";
4562 case ISD::XOR: return "xor";
4563 case ISD::SHL: return "shl";
4564 case ISD::SRA: return "sra";
4565 case ISD::SRL: return "srl";
4566 case ISD::ROTL: return "rotl";
4567 case ISD::ROTR: return "rotr";
4568 case ISD::FADD: return "fadd";
4569 case ISD::FSUB: return "fsub";
4570 case ISD::FMUL: return "fmul";
4571 case ISD::FDIV: return "fdiv";
4572 case ISD::FREM: return "frem";
4573 case ISD::FCOPYSIGN: return "fcopysign";
4574 case ISD::FGETSIGN: return "fgetsign";
4576 case ISD::SETCC: return "setcc";
4577 case ISD::VSETCC: return "vsetcc";
4578 case ISD::SELECT: return "select";
4579 case ISD::SELECT_CC: return "select_cc";
4580 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4581 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4582 case ISD::CONCAT_VECTORS: return "concat_vectors";
4583 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4584 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4585 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4586 case ISD::CARRY_FALSE: return "carry_false";
4587 case ISD::ADDC: return "addc";
4588 case ISD::ADDE: return "adde";
4589 case ISD::SUBC: return "subc";
4590 case ISD::SUBE: return "sube";
4591 case ISD::SHL_PARTS: return "shl_parts";
4592 case ISD::SRA_PARTS: return "sra_parts";
4593 case ISD::SRL_PARTS: return "srl_parts";
4595 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4596 case ISD::INSERT_SUBREG: return "insert_subreg";
4598 // Conversion operators.
4599 case ISD::SIGN_EXTEND: return "sign_extend";
4600 case ISD::ZERO_EXTEND: return "zero_extend";
4601 case ISD::ANY_EXTEND: return "any_extend";
4602 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4603 case ISD::TRUNCATE: return "truncate";
4604 case ISD::FP_ROUND: return "fp_round";
4605 case ISD::FLT_ROUNDS_: return "flt_rounds";
4606 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4607 case ISD::FP_EXTEND: return "fp_extend";
4609 case ISD::SINT_TO_FP: return "sint_to_fp";
4610 case ISD::UINT_TO_FP: return "uint_to_fp";
4611 case ISD::FP_TO_SINT: return "fp_to_sint";
4612 case ISD::FP_TO_UINT: return "fp_to_uint";
4613 case ISD::BIT_CONVERT: return "bit_convert";
4615 // Control flow instructions
4616 case ISD::BR: return "br";
4617 case ISD::BRIND: return "brind";
4618 case ISD::BR_JT: return "br_jt";
4619 case ISD::BRCOND: return "brcond";
4620 case ISD::BR_CC: return "br_cc";
4621 case ISD::RET: return "ret";
4622 case ISD::CALLSEQ_START: return "callseq_start";
4623 case ISD::CALLSEQ_END: return "callseq_end";
4626 case ISD::LOAD: return "load";
4627 case ISD::STORE: return "store";
4628 case ISD::VAARG: return "vaarg";
4629 case ISD::VACOPY: return "vacopy";
4630 case ISD::VAEND: return "vaend";
4631 case ISD::VASTART: return "vastart";
4632 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4633 case ISD::EXTRACT_ELEMENT: return "extract_element";
4634 case ISD::BUILD_PAIR: return "build_pair";
4635 case ISD::STACKSAVE: return "stacksave";
4636 case ISD::STACKRESTORE: return "stackrestore";
4637 case ISD::TRAP: return "trap";
4640 case ISD::BSWAP: return "bswap";
4641 case ISD::CTPOP: return "ctpop";
4642 case ISD::CTTZ: return "cttz";
4643 case ISD::CTLZ: return "ctlz";
4646 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4647 case ISD::DEBUG_LOC: return "debug_loc";
4650 case ISD::TRAMPOLINE: return "trampoline";
4653 switch (cast<CondCodeSDNode>(this)->get()) {
4654 default: assert(0 && "Unknown setcc condition!");
4655 case ISD::SETOEQ: return "setoeq";
4656 case ISD::SETOGT: return "setogt";
4657 case ISD::SETOGE: return "setoge";
4658 case ISD::SETOLT: return "setolt";
4659 case ISD::SETOLE: return "setole";
4660 case ISD::SETONE: return "setone";
4662 case ISD::SETO: return "seto";
4663 case ISD::SETUO: return "setuo";
4664 case ISD::SETUEQ: return "setue";
4665 case ISD::SETUGT: return "setugt";
4666 case ISD::SETUGE: return "setuge";
4667 case ISD::SETULT: return "setult";
4668 case ISD::SETULE: return "setule";
4669 case ISD::SETUNE: return "setune";
4671 case ISD::SETEQ: return "seteq";
4672 case ISD::SETGT: return "setgt";
4673 case ISD::SETGE: return "setge";
4674 case ISD::SETLT: return "setlt";
4675 case ISD::SETLE: return "setle";
4676 case ISD::SETNE: return "setne";
4681 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4690 return "<post-inc>";
4692 return "<post-dec>";
4696 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4697 std::string S = "< ";
4711 if (getByValAlign())
4712 S += "byval-align:" + utostr(getByValAlign()) + " ";
4714 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4716 S += "byval-size:" + utostr(getByValSize()) + " ";
4720 void SDNode::dump() const { dump(0); }
4721 void SDNode::dump(const SelectionDAG *G) const {
4722 cerr << (void*)this << ": ";
4724 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4726 if (getValueType(i) == MVT::Other)
4729 cerr << getValueType(i).getMVTString();
4731 cerr << " = " << getOperationName(G);
4734 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4735 if (i) cerr << ", ";
4736 cerr << (void*)getOperand(i).Val;
4737 if (unsigned RN = getOperand(i).ResNo)
4741 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4742 SDNode *Mask = getOperand(2).Val;
4744 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4746 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4749 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4754 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4755 cerr << "<" << CSDN->getValue() << ">";
4756 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4757 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4758 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4759 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4760 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4762 cerr << "<APFloat(";
4763 CSDN->getValueAPF().convertToAPInt().dump();
4766 } else if (const GlobalAddressSDNode *GADN =
4767 dyn_cast<GlobalAddressSDNode>(this)) {
4768 int offset = GADN->getOffset();
4770 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4772 cerr << " + " << offset;
4774 cerr << " " << offset;
4775 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4776 cerr << "<" << FIDN->getIndex() << ">";
4777 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4778 cerr << "<" << JTDN->getIndex() << ">";
4779 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4780 int offset = CP->getOffset();
4781 if (CP->isMachineConstantPoolEntry())
4782 cerr << "<" << *CP->getMachineCPVal() << ">";
4784 cerr << "<" << *CP->getConstVal() << ">";
4786 cerr << " + " << offset;
4788 cerr << " " << offset;
4789 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4791 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4793 cerr << LBB->getName() << " ";
4794 cerr << (const void*)BBDN->getBasicBlock() << ">";
4795 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4796 if (G && R->getReg() &&
4797 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4798 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4800 cerr << " #" << R->getReg();
4802 } else if (const ExternalSymbolSDNode *ES =
4803 dyn_cast<ExternalSymbolSDNode>(this)) {
4804 cerr << "'" << ES->getSymbol() << "'";
4805 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4807 cerr << "<" << M->getValue() << ">";
4810 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4811 if (M->MO.getValue())
4812 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4814 cerr << "<null:" << M->MO.getOffset() << ">";
4815 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4816 cerr << N->getArgFlags().getArgFlagsString();
4817 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4818 cerr << ":" << N->getVT().getMVTString();
4820 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4821 const Value *SrcValue = LD->getSrcValue();
4822 int SrcOffset = LD->getSrcValueOffset();
4828 cerr << ":" << SrcOffset << ">";
4831 switch (LD->getExtensionType()) {
4832 default: doExt = false; break;
4834 cerr << " <anyext ";
4844 cerr << LD->getMemoryVT().getMVTString() << ">";
4846 const char *AM = getIndexedModeName(LD->getAddressingMode());
4849 if (LD->isVolatile())
4850 cerr << " <volatile>";
4851 cerr << " alignment=" << LD->getAlignment();
4852 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4853 const Value *SrcValue = ST->getSrcValue();
4854 int SrcOffset = ST->getSrcValueOffset();
4860 cerr << ":" << SrcOffset << ">";
4862 if (ST->isTruncatingStore())
4864 << ST->getMemoryVT().getMVTString() << ">";
4866 const char *AM = getIndexedModeName(ST->getAddressingMode());
4869 if (ST->isVolatile())
4870 cerr << " <volatile>";
4871 cerr << " alignment=" << ST->getAlignment();
4872 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4873 const Value *SrcValue = AT->getSrcValue();
4874 int SrcOffset = AT->getSrcValueOffset();
4880 cerr << ":" << SrcOffset << ">";
4881 if (AT->isVolatile())
4882 cerr << " <volatile>";
4883 cerr << " alignment=" << AT->getAlignment();
4887 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4888 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4889 if (N->getOperand(i).Val->hasOneUse())
4890 DumpNodes(N->getOperand(i).Val, indent+2, G);
4892 cerr << "\n" << std::string(indent+2, ' ')
4893 << (void*)N->getOperand(i).Val << ": <multiple use>";
4896 cerr << "\n" << std::string(indent, ' ');
4900 void SelectionDAG::dump() const {
4901 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4902 std::vector<const SDNode*> Nodes;
4903 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4907 std::sort(Nodes.begin(), Nodes.end());
4909 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4910 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4911 DumpNodes(Nodes[i], 2, this);
4914 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4919 const Type *ConstantPoolSDNode::getType() const {
4920 if (isMachineConstantPoolEntry())
4921 return Val.MachineCPVal->getType();
4922 return Val.ConstVal->getType();