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 const SDOperand *Ops, unsigned NumOps) {
327 for (; NumOps; --NumOps, ++Ops) {
328 ID.AddPointer(Ops->Val);
329 ID.AddInteger(Ops->ResNo);
333 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
335 static void AddNodeIDOperands(FoldingSetNodeID &ID,
336 const SDUse *Ops, unsigned NumOps) {
337 for (; NumOps; --NumOps, ++Ops) {
338 ID.AddPointer(Ops->getSDOperand().Val);
339 ID.AddInteger(Ops->getSDOperand().ResNo);
343 static void AddNodeIDNode(FoldingSetNodeID &ID,
344 unsigned short OpC, SDVTList VTList,
345 const SDOperand *OpList, unsigned N) {
346 AddNodeIDOpcode(ID, OpC);
347 AddNodeIDValueTypes(ID, VTList);
348 AddNodeIDOperands(ID, OpList, N);
352 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
354 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
355 AddNodeIDOpcode(ID, N->getOpcode());
356 // Add the return value info.
357 AddNodeIDValueTypes(ID, N->getVTList());
358 // Add the operand info.
359 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
361 // Handle SDNode leafs with special info.
362 switch (N->getOpcode()) {
363 default: break; // Normal nodes don't need extra info.
365 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
367 case ISD::TargetConstant:
369 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
371 case ISD::TargetConstantFP:
372 case ISD::ConstantFP: {
373 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
376 case ISD::TargetGlobalAddress:
377 case ISD::GlobalAddress:
378 case ISD::TargetGlobalTLSAddress:
379 case ISD::GlobalTLSAddress: {
380 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
381 ID.AddPointer(GA->getGlobal());
382 ID.AddInteger(GA->getOffset());
385 case ISD::BasicBlock:
386 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
389 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
391 case ISD::DBG_STOPPOINT: {
392 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
393 ID.AddInteger(DSP->getLine());
394 ID.AddInteger(DSP->getColumn());
395 ID.AddPointer(DSP->getCompileUnit());
400 ID.AddInteger(cast<LabelSDNode>(N)->getLabelID());
403 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
405 case ISD::MEMOPERAND: {
406 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
407 ID.AddPointer(MO.getValue());
408 ID.AddInteger(MO.getFlags());
409 ID.AddInteger(MO.getOffset());
410 ID.AddInteger(MO.getSize());
411 ID.AddInteger(MO.getAlignment());
414 case ISD::FrameIndex:
415 case ISD::TargetFrameIndex:
416 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
419 case ISD::TargetJumpTable:
420 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
422 case ISD::ConstantPool:
423 case ISD::TargetConstantPool: {
424 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
425 ID.AddInteger(CP->getAlignment());
426 ID.AddInteger(CP->getOffset());
427 if (CP->isMachineConstantPoolEntry())
428 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
430 ID.AddPointer(CP->getConstVal());
434 LoadSDNode *LD = cast<LoadSDNode>(N);
435 ID.AddInteger(LD->getAddressingMode());
436 ID.AddInteger(LD->getExtensionType());
437 ID.AddInteger(LD->getMemoryVT().getRawBits());
438 ID.AddInteger(LD->getAlignment());
439 ID.AddInteger(LD->isVolatile());
443 StoreSDNode *ST = cast<StoreSDNode>(N);
444 ID.AddInteger(ST->getAddressingMode());
445 ID.AddInteger(ST->isTruncatingStore());
446 ID.AddInteger(ST->getMemoryVT().getRawBits());
447 ID.AddInteger(ST->getAlignment());
448 ID.AddInteger(ST->isVolatile());
451 case ISD::ATOMIC_CMP_SWAP:
452 case ISD::ATOMIC_LOAD_ADD:
453 case ISD::ATOMIC_SWAP:
454 case ISD::ATOMIC_LOAD_SUB:
455 case ISD::ATOMIC_LOAD_AND:
456 case ISD::ATOMIC_LOAD_OR:
457 case ISD::ATOMIC_LOAD_XOR:
458 case ISD::ATOMIC_LOAD_NAND:
459 case ISD::ATOMIC_LOAD_MIN:
460 case ISD::ATOMIC_LOAD_MAX:
461 case ISD::ATOMIC_LOAD_UMIN:
462 case ISD::ATOMIC_LOAD_UMAX: {
463 AtomicSDNode *AT = cast<AtomicSDNode>(N);
464 ID.AddInteger(AT->getAlignment());
465 ID.AddInteger(AT->isVolatile());
468 } // end switch (N->getOpcode())
471 //===----------------------------------------------------------------------===//
472 // SelectionDAG Class
473 //===----------------------------------------------------------------------===//
475 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
477 void SelectionDAG::RemoveDeadNodes() {
478 // Create a dummy node (which is not added to allnodes), that adds a reference
479 // to the root node, preventing it from being deleted.
480 HandleSDNode Dummy(getRoot());
482 SmallVector<SDNode*, 128> DeadNodes;
484 // Add all obviously-dead nodes to the DeadNodes worklist.
485 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
487 DeadNodes.push_back(I);
489 // Process the worklist, deleting the nodes and adding their uses to the
491 while (!DeadNodes.empty()) {
492 SDNode *N = DeadNodes.back();
493 DeadNodes.pop_back();
495 // Take the node out of the appropriate CSE map.
496 RemoveNodeFromCSEMaps(N);
498 // Next, brutally remove the operand list. This is safe to do, as there are
499 // no cycles in the graph.
500 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
501 SDNode *Operand = I->getVal();
502 Operand->removeUser(std::distance(N->op_begin(), I), N);
504 // Now that we removed this operand, see if there are no uses of it left.
505 if (Operand->use_empty())
506 DeadNodes.push_back(Operand);
508 if (N->OperandsNeedDelete) {
509 delete[] N->OperandList;
514 // Finally, remove N itself.
518 // If the root changed (e.g. it was a dead load, update the root).
519 setRoot(Dummy.getValue());
522 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
523 SmallVector<SDNode*, 16> DeadNodes;
524 DeadNodes.push_back(N);
526 // Process the worklist, deleting the nodes and adding their uses to the
528 while (!DeadNodes.empty()) {
529 SDNode *N = DeadNodes.back();
530 DeadNodes.pop_back();
533 UpdateListener->NodeDeleted(N, 0);
535 // Take the node out of the appropriate CSE map.
536 RemoveNodeFromCSEMaps(N);
538 // Next, brutally remove the operand list. This is safe to do, as there are
539 // no cycles in the graph.
541 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
542 SDNode *Operand = I->getVal();
543 Operand->removeUser(op_num, N);
545 // Now that we removed this operand, see if there are no uses of it left.
546 if (Operand->use_empty())
547 DeadNodes.push_back(Operand);
551 if (N->OperandsNeedDelete) {
552 delete[] N->OperandList;
557 // Finally, remove N itself.
562 void SelectionDAG::DeleteNode(SDNode *N) {
563 assert(N->use_empty() && "Cannot delete a node that is not dead!");
565 // First take this out of the appropriate CSE map.
566 RemoveNodeFromCSEMaps(N);
568 // Finally, remove uses due to operands of this node, remove from the
569 // AllNodes list, and delete the node.
570 DeleteNodeNotInCSEMaps(N);
573 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
575 // Remove it from the AllNodes list.
578 // Drop all of the operands and decrement used nodes use counts.
579 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
580 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
581 if (N->OperandsNeedDelete) {
582 delete[] N->OperandList;
590 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
591 /// correspond to it. This is useful when we're about to delete or repurpose
592 /// the node. We don't want future request for structurally identical nodes
593 /// to return N anymore.
594 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
596 switch (N->getOpcode()) {
597 case ISD::HANDLENODE: return; // noop.
599 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
600 "Cond code doesn't exist!");
601 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
602 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
604 case ISD::ExternalSymbol:
605 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
607 case ISD::TargetExternalSymbol:
609 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
611 case ISD::VALUETYPE: {
612 MVT VT = cast<VTSDNode>(N)->getVT();
613 if (VT.isExtended()) {
614 Erased = ExtendedValueTypeNodes.erase(VT);
616 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
617 ValueTypeNodes[VT.getSimpleVT()] = 0;
622 // Remove it from the CSE Map.
623 Erased = CSEMap.RemoveNode(N);
627 // Verify that the node was actually in one of the CSE maps, unless it has a
628 // flag result (which cannot be CSE'd) or is one of the special cases that are
629 // not subject to CSE.
630 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
631 !N->isTargetOpcode()) {
634 assert(0 && "Node is not in map!");
639 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
640 /// has been taken out and modified in some way. If the specified node already
641 /// exists in the CSE maps, do not modify the maps, but return the existing node
642 /// instead. If it doesn't exist, add it and return null.
644 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
645 assert(N->getNumOperands() && "This is a leaf node!");
646 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
647 return 0; // Never add these nodes.
649 // Check that remaining values produced are not flags.
650 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
651 if (N->getValueType(i) == MVT::Flag)
652 return 0; // Never CSE anything that produces a flag.
654 SDNode *New = CSEMap.GetOrInsertNode(N);
655 if (New != N) return New; // Node already existed.
659 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
660 /// were replaced with those specified. If this node is never memoized,
661 /// return null, otherwise return a pointer to the slot it would take. If a
662 /// node already exists with these operands, the slot will be non-null.
663 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
665 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
666 return 0; // Never add these nodes.
668 // Check that remaining values produced are not flags.
669 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
670 if (N->getValueType(i) == MVT::Flag)
671 return 0; // Never CSE anything that produces a flag.
673 SDOperand Ops[] = { Op };
675 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
676 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
679 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
680 /// were replaced with those specified. If this node is never memoized,
681 /// return null, otherwise return a pointer to the slot it would take. If a
682 /// node already exists with these operands, the slot will be non-null.
683 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
684 SDOperand Op1, SDOperand Op2,
686 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
687 return 0; // Never add these nodes.
689 // Check that remaining values produced are not flags.
690 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
691 if (N->getValueType(i) == MVT::Flag)
692 return 0; // Never CSE anything that produces a flag.
694 SDOperand Ops[] = { Op1, Op2 };
696 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
697 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
701 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
702 /// were replaced with those specified. If this node is never memoized,
703 /// return null, otherwise return a pointer to the slot it would take. If a
704 /// node already exists with these operands, the slot will be non-null.
705 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
706 const SDOperand *Ops,unsigned NumOps,
708 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
709 return 0; // Never add these nodes.
711 // Check that remaining values produced are not flags.
712 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
713 if (N->getValueType(i) == MVT::Flag)
714 return 0; // Never CSE anything that produces a flag.
717 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
719 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
720 ID.AddInteger(LD->getAddressingMode());
721 ID.AddInteger(LD->getExtensionType());
722 ID.AddInteger(LD->getMemoryVT().getRawBits());
723 ID.AddInteger(LD->getAlignment());
724 ID.AddInteger(LD->isVolatile());
725 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
726 ID.AddInteger(ST->getAddressingMode());
727 ID.AddInteger(ST->isTruncatingStore());
728 ID.AddInteger(ST->getMemoryVT().getRawBits());
729 ID.AddInteger(ST->getAlignment());
730 ID.AddInteger(ST->isVolatile());
733 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
737 SelectionDAG::~SelectionDAG() {
738 while (!AllNodes.empty()) {
739 SDNode *N = AllNodes.begin();
740 N->SetNextInBucket(0);
741 if (N->OperandsNeedDelete) {
742 delete [] N->OperandList;
746 AllNodes.pop_front();
750 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
751 if (Op.getValueType() == VT) return Op;
752 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
754 return getNode(ISD::AND, Op.getValueType(), Op,
755 getConstant(Imm, Op.getValueType()));
758 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
759 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
760 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
763 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
764 assert(VT.isInteger() && "Cannot create FP integer constant!");
766 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
767 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
768 "APInt size does not match type size!");
770 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
772 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
776 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
778 return SDOperand(N, 0);
780 N = new ConstantSDNode(isT, Val, EltVT);
781 CSEMap.InsertNode(N, IP);
782 AllNodes.push_back(N);
785 SDOperand Result(N, 0);
787 SmallVector<SDOperand, 8> Ops;
788 Ops.assign(VT.getVectorNumElements(), Result);
789 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
794 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
795 return getConstant(Val, TLI.getPointerTy(), isTarget);
799 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
800 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
803 VT.isVector() ? VT.getVectorElementType() : VT;
805 // Do the map lookup using the actual bit pattern for the floating point
806 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
807 // we don't have issues with SNANs.
808 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
810 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
814 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
816 return SDOperand(N, 0);
818 N = new ConstantFPSDNode(isTarget, V, EltVT);
819 CSEMap.InsertNode(N, IP);
820 AllNodes.push_back(N);
823 SDOperand Result(N, 0);
825 SmallVector<SDOperand, 8> Ops;
826 Ops.assign(VT.getVectorNumElements(), Result);
827 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
832 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
834 VT.isVector() ? VT.getVectorElementType() : VT;
836 return getConstantFP(APFloat((float)Val), VT, isTarget);
838 return getConstantFP(APFloat(Val), VT, isTarget);
841 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
846 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
848 // If GV is an alias then use the aliasee for determining thread-localness.
849 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
850 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
853 if (GVar && GVar->isThreadLocal())
854 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
856 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
859 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
861 ID.AddInteger(Offset);
863 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
864 return SDOperand(E, 0);
865 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
866 CSEMap.InsertNode(N, IP);
867 AllNodes.push_back(N);
868 return SDOperand(N, 0);
871 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
872 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
874 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
877 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
878 return SDOperand(E, 0);
879 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
880 CSEMap.InsertNode(N, IP);
881 AllNodes.push_back(N);
882 return SDOperand(N, 0);
885 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
886 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
888 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
891 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
892 return SDOperand(E, 0);
893 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
894 CSEMap.InsertNode(N, IP);
895 AllNodes.push_back(N);
896 return SDOperand(N, 0);
899 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
900 unsigned Alignment, int Offset,
902 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
904 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
905 ID.AddInteger(Alignment);
906 ID.AddInteger(Offset);
909 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
910 return SDOperand(E, 0);
911 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
912 CSEMap.InsertNode(N, IP);
913 AllNodes.push_back(N);
914 return SDOperand(N, 0);
918 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
919 unsigned Alignment, int Offset,
921 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
923 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
924 ID.AddInteger(Alignment);
925 ID.AddInteger(Offset);
926 C->AddSelectionDAGCSEId(ID);
928 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
929 return SDOperand(E, 0);
930 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
931 CSEMap.InsertNode(N, IP);
932 AllNodes.push_back(N);
933 return SDOperand(N, 0);
937 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
939 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
942 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
943 return SDOperand(E, 0);
944 SDNode *N = new BasicBlockSDNode(MBB);
945 CSEMap.InsertNode(N, IP);
946 AllNodes.push_back(N);
947 return SDOperand(N, 0);
950 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
952 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
953 ID.AddInteger(Flags.getRawBits());
955 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
956 return SDOperand(E, 0);
957 SDNode *N = new ARG_FLAGSSDNode(Flags);
958 CSEMap.InsertNode(N, IP);
959 AllNodes.push_back(N);
960 return SDOperand(N, 0);
963 SDOperand SelectionDAG::getValueType(MVT VT) {
964 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
965 ValueTypeNodes.resize(VT.getSimpleVT()+1);
967 SDNode *&N = VT.isExtended() ?
968 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
970 if (N) return SDOperand(N, 0);
971 N = new VTSDNode(VT);
972 AllNodes.push_back(N);
973 return SDOperand(N, 0);
976 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
977 SDNode *&N = ExternalSymbols[Sym];
978 if (N) return SDOperand(N, 0);
979 N = new ExternalSymbolSDNode(false, Sym, VT);
980 AllNodes.push_back(N);
981 return SDOperand(N, 0);
984 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
985 SDNode *&N = TargetExternalSymbols[Sym];
986 if (N) return SDOperand(N, 0);
987 N = new ExternalSymbolSDNode(true, Sym, VT);
988 AllNodes.push_back(N);
989 return SDOperand(N, 0);
992 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
993 if ((unsigned)Cond >= CondCodeNodes.size())
994 CondCodeNodes.resize(Cond+1);
996 if (CondCodeNodes[Cond] == 0) {
997 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
998 AllNodes.push_back(CondCodeNodes[Cond]);
1000 return SDOperand(CondCodeNodes[Cond], 0);
1003 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1004 FoldingSetNodeID ID;
1005 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1006 ID.AddInteger(RegNo);
1008 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1009 return SDOperand(E, 0);
1010 SDNode *N = new RegisterSDNode(RegNo, VT);
1011 CSEMap.InsertNode(N, IP);
1012 AllNodes.push_back(N);
1013 return SDOperand(N, 0);
1016 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
1017 unsigned Line, unsigned Col,
1018 const CompileUnitDesc *CU) {
1019 FoldingSetNodeID ID;
1020 SDOperand Ops[] = { Root };
1021 AddNodeIDNode(ID, ISD::DBG_STOPPOINT, getVTList(MVT::Other), &Ops[0], 1);
1022 ID.AddInteger(Line);
1026 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1027 return SDOperand(E, 0);
1028 SDNode *N = new DbgStopPointSDNode(Root, Line, Col, CU);
1029 CSEMap.InsertNode(N, IP);
1030 AllNodes.push_back(N);
1031 return SDOperand(N, 0);
1034 SDOperand SelectionDAG::getLabel(unsigned Opcode,
1037 FoldingSetNodeID ID;
1038 SDOperand Ops[] = { Root };
1039 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1040 ID.AddInteger(LabelID);
1042 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1043 return SDOperand(E, 0);
1044 SDNode *N = new LabelSDNode(Opcode, Root, LabelID);
1045 CSEMap.InsertNode(N, IP);
1046 AllNodes.push_back(N);
1047 return SDOperand(N, 0);
1050 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1051 assert((!V || isa<PointerType>(V->getType())) &&
1052 "SrcValue is not a pointer?");
1054 FoldingSetNodeID ID;
1055 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1059 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1060 return SDOperand(E, 0);
1062 SDNode *N = new SrcValueSDNode(V);
1063 CSEMap.InsertNode(N, IP);
1064 AllNodes.push_back(N);
1065 return SDOperand(N, 0);
1068 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1069 const Value *v = MO.getValue();
1070 assert((!v || isa<PointerType>(v->getType())) &&
1071 "SrcValue is not a pointer?");
1073 FoldingSetNodeID ID;
1074 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1076 ID.AddInteger(MO.getFlags());
1077 ID.AddInteger(MO.getOffset());
1078 ID.AddInteger(MO.getSize());
1079 ID.AddInteger(MO.getAlignment());
1082 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1083 return SDOperand(E, 0);
1085 SDNode *N = new MemOperandSDNode(MO);
1086 CSEMap.InsertNode(N, IP);
1087 AllNodes.push_back(N);
1088 return SDOperand(N, 0);
1091 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1092 /// specified value type.
1093 SDOperand SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1094 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1095 unsigned ByteSize = VT.getSizeInBits()/8;
1096 const Type *Ty = VT.getTypeForMVT();
1097 unsigned StackAlign =
1098 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1100 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1101 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1104 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1105 SDOperand N2, ISD::CondCode Cond) {
1106 // These setcc operations always fold.
1110 case ISD::SETFALSE2: return getConstant(0, VT);
1112 case ISD::SETTRUE2: return getConstant(1, VT);
1124 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1128 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1129 const APInt &C2 = N2C->getAPIntValue();
1130 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1131 const APInt &C1 = N1C->getAPIntValue();
1134 default: assert(0 && "Unknown integer setcc!");
1135 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1136 case ISD::SETNE: return getConstant(C1 != C2, VT);
1137 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1138 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1139 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1140 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1141 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1142 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1143 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1144 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1148 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1149 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1150 // No compile time operations on this type yet.
1151 if (N1C->getValueType(0) == MVT::ppcf128)
1154 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1157 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1158 return getNode(ISD::UNDEF, VT);
1160 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1161 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1162 return getNode(ISD::UNDEF, VT);
1164 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1165 R==APFloat::cmpLessThan, VT);
1166 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1167 return getNode(ISD::UNDEF, VT);
1169 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1170 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1171 return getNode(ISD::UNDEF, VT);
1173 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1174 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1175 return getNode(ISD::UNDEF, VT);
1177 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1178 R==APFloat::cmpEqual, VT);
1179 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1180 return getNode(ISD::UNDEF, VT);
1182 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1183 R==APFloat::cmpEqual, VT);
1184 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1185 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1186 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1187 R==APFloat::cmpEqual, VT);
1188 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1189 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1190 R==APFloat::cmpLessThan, VT);
1191 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1192 R==APFloat::cmpUnordered, VT);
1193 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1194 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1197 // Ensure that the constant occurs on the RHS.
1198 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1202 // Could not fold it.
1206 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1207 /// use this predicate to simplify operations downstream.
1208 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1209 unsigned BitWidth = Op.getValueSizeInBits();
1210 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1213 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1214 /// this predicate to simplify operations downstream. Mask is known to be zero
1215 /// for bits that V cannot have.
1216 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1217 unsigned Depth) const {
1218 APInt KnownZero, KnownOne;
1219 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1220 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1221 return (KnownZero & Mask) == Mask;
1224 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1225 /// known to be either zero or one and return them in the KnownZero/KnownOne
1226 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1228 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1229 APInt &KnownZero, APInt &KnownOne,
1230 unsigned Depth) const {
1231 unsigned BitWidth = Mask.getBitWidth();
1232 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1233 "Mask size mismatches value type size!");
1235 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1236 if (Depth == 6 || Mask == 0)
1237 return; // Limit search depth.
1239 APInt KnownZero2, KnownOne2;
1241 switch (Op.getOpcode()) {
1243 // We know all of the bits for a constant!
1244 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1245 KnownZero = ~KnownOne & Mask;
1248 // If either the LHS or the RHS are Zero, the result is zero.
1249 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1250 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1251 KnownZero2, KnownOne2, Depth+1);
1252 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1253 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1255 // Output known-1 bits are only known if set in both the LHS & RHS.
1256 KnownOne &= KnownOne2;
1257 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1258 KnownZero |= KnownZero2;
1261 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1262 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1263 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 only known if clear in both the LHS & RHS.
1268 KnownZero &= KnownZero2;
1269 // Output known-1 are known to be set if set in either the LHS | RHS.
1270 KnownOne |= KnownOne2;
1273 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1274 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1275 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1276 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1278 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1279 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1280 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1281 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1282 KnownZero = KnownZeroOut;
1286 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1287 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1288 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1289 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1290 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1292 // If low bits are zero in either operand, output low known-0 bits.
1293 // Also compute a conserative estimate for high known-0 bits.
1294 // More trickiness is possible, but this is sufficient for the
1295 // interesting case of alignment computation.
1297 unsigned TrailZ = KnownZero.countTrailingOnes() +
1298 KnownZero2.countTrailingOnes();
1299 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1300 KnownZero2.countLeadingOnes(),
1301 BitWidth) - BitWidth;
1303 TrailZ = std::min(TrailZ, BitWidth);
1304 LeadZ = std::min(LeadZ, BitWidth);
1305 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1306 APInt::getHighBitsSet(BitWidth, LeadZ);
1311 // For the purposes of computing leading zeros we can conservatively
1312 // treat a udiv as a logical right shift by the power of 2 known to
1313 // be less than the denominator.
1314 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1315 ComputeMaskedBits(Op.getOperand(0),
1316 AllOnes, KnownZero2, KnownOne2, Depth+1);
1317 unsigned LeadZ = KnownZero2.countLeadingOnes();
1321 ComputeMaskedBits(Op.getOperand(1),
1322 AllOnes, KnownZero2, KnownOne2, Depth+1);
1323 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1324 if (RHSUnknownLeadingOnes != BitWidth)
1325 LeadZ = std::min(BitWidth,
1326 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1328 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1332 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1333 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1334 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1335 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1337 // Only known if known in both the LHS and RHS.
1338 KnownOne &= KnownOne2;
1339 KnownZero &= KnownZero2;
1341 case ISD::SELECT_CC:
1342 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1343 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1344 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1345 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1347 // Only known if known in both the LHS and RHS.
1348 KnownOne &= KnownOne2;
1349 KnownZero &= KnownZero2;
1352 // If we know the result of a setcc has the top bits zero, use this info.
1353 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1355 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1358 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1359 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1360 unsigned ShAmt = SA->getValue();
1362 // If the shift count is an invalid immediate, don't do anything.
1363 if (ShAmt >= BitWidth)
1366 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1367 KnownZero, KnownOne, Depth+1);
1368 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1369 KnownZero <<= ShAmt;
1371 // low bits known zero.
1372 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1376 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1377 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1378 unsigned ShAmt = SA->getValue();
1380 // If the shift count is an invalid immediate, don't do anything.
1381 if (ShAmt >= BitWidth)
1384 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1385 KnownZero, KnownOne, Depth+1);
1386 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1387 KnownZero = KnownZero.lshr(ShAmt);
1388 KnownOne = KnownOne.lshr(ShAmt);
1390 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1391 KnownZero |= HighBits; // High bits known zero.
1395 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1396 unsigned ShAmt = SA->getValue();
1398 // If the shift count is an invalid immediate, don't do anything.
1399 if (ShAmt >= BitWidth)
1402 APInt InDemandedMask = (Mask << ShAmt);
1403 // If any of the demanded bits are produced by the sign extension, we also
1404 // demand the input sign bit.
1405 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1406 if (HighBits.getBoolValue())
1407 InDemandedMask |= APInt::getSignBit(BitWidth);
1409 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1411 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1412 KnownZero = KnownZero.lshr(ShAmt);
1413 KnownOne = KnownOne.lshr(ShAmt);
1415 // Handle the sign bits.
1416 APInt SignBit = APInt::getSignBit(BitWidth);
1417 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1419 if (KnownZero.intersects(SignBit)) {
1420 KnownZero |= HighBits; // New bits are known zero.
1421 } else if (KnownOne.intersects(SignBit)) {
1422 KnownOne |= HighBits; // New bits are known one.
1426 case ISD::SIGN_EXTEND_INREG: {
1427 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1428 unsigned EBits = EVT.getSizeInBits();
1430 // Sign extension. Compute the demanded bits in the result that are not
1431 // present in the input.
1432 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1434 APInt InSignBit = APInt::getSignBit(EBits);
1435 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1437 // If the sign extended bits are demanded, we know that the sign
1439 InSignBit.zext(BitWidth);
1440 if (NewBits.getBoolValue())
1441 InputDemandedBits |= InSignBit;
1443 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1444 KnownZero, KnownOne, Depth+1);
1445 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1447 // If the sign bit of the input is known set or clear, then we know the
1448 // top bits of the result.
1449 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1450 KnownZero |= NewBits;
1451 KnownOne &= ~NewBits;
1452 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1453 KnownOne |= NewBits;
1454 KnownZero &= ~NewBits;
1455 } else { // Input sign bit unknown
1456 KnownZero &= ~NewBits;
1457 KnownOne &= ~NewBits;
1464 unsigned LowBits = Log2_32(BitWidth)+1;
1465 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1470 if (ISD::isZEXTLoad(Op.Val)) {
1471 LoadSDNode *LD = cast<LoadSDNode>(Op);
1472 MVT VT = LD->getMemoryVT();
1473 unsigned MemBits = VT.getSizeInBits();
1474 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1478 case ISD::ZERO_EXTEND: {
1479 MVT InVT = Op.getOperand(0).getValueType();
1480 unsigned InBits = InVT.getSizeInBits();
1481 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1482 APInt InMask = Mask;
1483 InMask.trunc(InBits);
1484 KnownZero.trunc(InBits);
1485 KnownOne.trunc(InBits);
1486 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1487 KnownZero.zext(BitWidth);
1488 KnownOne.zext(BitWidth);
1489 KnownZero |= NewBits;
1492 case ISD::SIGN_EXTEND: {
1493 MVT InVT = Op.getOperand(0).getValueType();
1494 unsigned InBits = InVT.getSizeInBits();
1495 APInt InSignBit = APInt::getSignBit(InBits);
1496 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1497 APInt InMask = Mask;
1498 InMask.trunc(InBits);
1500 // If any of the sign extended bits are demanded, we know that the sign
1501 // bit is demanded. Temporarily set this bit in the mask for our callee.
1502 if (NewBits.getBoolValue())
1503 InMask |= InSignBit;
1505 KnownZero.trunc(InBits);
1506 KnownOne.trunc(InBits);
1507 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1509 // Note if the sign bit is known to be zero or one.
1510 bool SignBitKnownZero = KnownZero.isNegative();
1511 bool SignBitKnownOne = KnownOne.isNegative();
1512 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1513 "Sign bit can't be known to be both zero and one!");
1515 // If the sign bit wasn't actually demanded by our caller, we don't
1516 // want it set in the KnownZero and KnownOne result values. Reset the
1517 // mask and reapply it to the result values.
1519 InMask.trunc(InBits);
1520 KnownZero &= InMask;
1523 KnownZero.zext(BitWidth);
1524 KnownOne.zext(BitWidth);
1526 // If the sign bit is known zero or one, the top bits match.
1527 if (SignBitKnownZero)
1528 KnownZero |= NewBits;
1529 else if (SignBitKnownOne)
1530 KnownOne |= NewBits;
1533 case ISD::ANY_EXTEND: {
1534 MVT InVT = Op.getOperand(0).getValueType();
1535 unsigned InBits = InVT.getSizeInBits();
1536 APInt InMask = Mask;
1537 InMask.trunc(InBits);
1538 KnownZero.trunc(InBits);
1539 KnownOne.trunc(InBits);
1540 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1541 KnownZero.zext(BitWidth);
1542 KnownOne.zext(BitWidth);
1545 case ISD::TRUNCATE: {
1546 MVT InVT = Op.getOperand(0).getValueType();
1547 unsigned InBits = InVT.getSizeInBits();
1548 APInt InMask = Mask;
1549 InMask.zext(InBits);
1550 KnownZero.zext(InBits);
1551 KnownOne.zext(InBits);
1552 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1553 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1554 KnownZero.trunc(BitWidth);
1555 KnownOne.trunc(BitWidth);
1558 case ISD::AssertZext: {
1559 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1560 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1561 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1563 KnownZero |= (~InMask) & Mask;
1567 // All bits are zero except the low bit.
1568 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1572 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1573 // We know that the top bits of C-X are clear if X contains less bits
1574 // than C (i.e. no wrap-around can happen). For example, 20-X is
1575 // positive if we can prove that X is >= 0 and < 16.
1576 if (CLHS->getAPIntValue().isNonNegative()) {
1577 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1578 // NLZ can't be BitWidth with no sign bit
1579 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1580 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1583 // If all of the MaskV bits are known to be zero, then we know the
1584 // output top bits are zero, because we now know that the output is
1586 if ((KnownZero2 & MaskV) == MaskV) {
1587 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1588 // Top bits known zero.
1589 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1596 // Output known-0 bits are known if clear or set in both the low clear bits
1597 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1598 // low 3 bits clear.
1599 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1600 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1601 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1602 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1604 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1605 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1606 KnownZeroOut = std::min(KnownZeroOut,
1607 KnownZero2.countTrailingOnes());
1609 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1613 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1614 const APInt &RA = Rem->getAPIntValue();
1615 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1616 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1617 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1618 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1620 // The sign of a remainder is equal to the sign of the first
1621 // operand (zero being positive).
1622 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1623 KnownZero2 |= ~LowBits;
1624 else if (KnownOne2[BitWidth-1])
1625 KnownOne2 |= ~LowBits;
1627 KnownZero |= KnownZero2 & Mask;
1628 KnownOne |= KnownOne2 & Mask;
1630 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1635 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1636 const APInt &RA = Rem->getAPIntValue();
1637 if (RA.isPowerOf2()) {
1638 APInt LowBits = (RA - 1);
1639 APInt Mask2 = LowBits & Mask;
1640 KnownZero |= ~LowBits & Mask;
1641 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1642 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1647 // Since the result is less than or equal to either operand, any leading
1648 // zero bits in either operand must also exist in the result.
1649 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1650 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1652 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1655 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1656 KnownZero2.countLeadingOnes());
1658 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1662 // Allow the target to implement this method for its nodes.
1663 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1664 case ISD::INTRINSIC_WO_CHAIN:
1665 case ISD::INTRINSIC_W_CHAIN:
1666 case ISD::INTRINSIC_VOID:
1667 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1673 /// ComputeNumSignBits - Return the number of times the sign bit of the
1674 /// register is replicated into the other bits. We know that at least 1 bit
1675 /// is always equal to the sign bit (itself), but other cases can give us
1676 /// information. For example, immediately after an "SRA X, 2", we know that
1677 /// the top 3 bits are all equal to each other, so we return 3.
1678 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1679 MVT VT = Op.getValueType();
1680 assert(VT.isInteger() && "Invalid VT!");
1681 unsigned VTBits = VT.getSizeInBits();
1683 unsigned FirstAnswer = 1;
1686 return 1; // Limit search depth.
1688 switch (Op.getOpcode()) {
1690 case ISD::AssertSext:
1691 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1692 return VTBits-Tmp+1;
1693 case ISD::AssertZext:
1694 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1697 case ISD::Constant: {
1698 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1699 // If negative, return # leading ones.
1700 if (Val.isNegative())
1701 return Val.countLeadingOnes();
1703 // Return # leading zeros.
1704 return Val.countLeadingZeros();
1707 case ISD::SIGN_EXTEND:
1708 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1709 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1711 case ISD::SIGN_EXTEND_INREG:
1712 // Max of the input and what this extends.
1713 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1716 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1717 return std::max(Tmp, Tmp2);
1720 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1721 // SRA X, C -> adds C sign bits.
1722 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1723 Tmp += C->getValue();
1724 if (Tmp > VTBits) Tmp = VTBits;
1728 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1729 // shl destroys sign bits.
1730 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1731 if (C->getValue() >= VTBits || // Bad shift.
1732 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1733 return Tmp - C->getValue();
1738 case ISD::XOR: // NOT is handled here.
1739 // Logical binary ops preserve the number of sign bits at the worst.
1740 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1742 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1743 FirstAnswer = std::min(Tmp, Tmp2);
1744 // We computed what we know about the sign bits as our first
1745 // answer. Now proceed to the generic code that uses
1746 // ComputeMaskedBits, and pick whichever answer is better.
1751 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1752 if (Tmp == 1) return 1; // Early out.
1753 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1754 return std::min(Tmp, Tmp2);
1757 // If setcc returns 0/-1, all bits are sign bits.
1758 if (TLI.getSetCCResultContents() ==
1759 TargetLowering::ZeroOrNegativeOneSetCCResult)
1764 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1765 unsigned RotAmt = C->getValue() & (VTBits-1);
1767 // Handle rotate right by N like a rotate left by 32-N.
1768 if (Op.getOpcode() == ISD::ROTR)
1769 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1771 // If we aren't rotating out all of the known-in sign bits, return the
1772 // number that are left. This handles rotl(sext(x), 1) for example.
1773 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1774 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1778 // Add can have at most one carry bit. Thus we know that the output
1779 // is, at worst, one more bit than the inputs.
1780 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1781 if (Tmp == 1) return 1; // Early out.
1783 // Special case decrementing a value (ADD X, -1):
1784 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1785 if (CRHS->isAllOnesValue()) {
1786 APInt KnownZero, KnownOne;
1787 APInt Mask = APInt::getAllOnesValue(VTBits);
1788 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1790 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1792 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1795 // If we are subtracting one from a positive number, there is no carry
1796 // out of the result.
1797 if (KnownZero.isNegative())
1801 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1802 if (Tmp2 == 1) return 1;
1803 return std::min(Tmp, Tmp2)-1;
1807 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1808 if (Tmp2 == 1) return 1;
1811 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1812 if (CLHS->isNullValue()) {
1813 APInt KnownZero, KnownOne;
1814 APInt Mask = APInt::getAllOnesValue(VTBits);
1815 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1816 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1818 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1821 // If the input is known to be positive (the sign bit is known clear),
1822 // the output of the NEG has the same number of sign bits as the input.
1823 if (KnownZero.isNegative())
1826 // Otherwise, we treat this like a SUB.
1829 // Sub can have at most one carry bit. Thus we know that the output
1830 // is, at worst, one more bit than the inputs.
1831 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1832 if (Tmp == 1) return 1; // Early out.
1833 return std::min(Tmp, Tmp2)-1;
1836 // FIXME: it's tricky to do anything useful for this, but it is an important
1837 // case for targets like X86.
1841 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1842 if (Op.getOpcode() == ISD::LOAD) {
1843 LoadSDNode *LD = cast<LoadSDNode>(Op);
1844 unsigned ExtType = LD->getExtensionType();
1847 case ISD::SEXTLOAD: // '17' bits known
1848 Tmp = LD->getMemoryVT().getSizeInBits();
1849 return VTBits-Tmp+1;
1850 case ISD::ZEXTLOAD: // '16' bits known
1851 Tmp = LD->getMemoryVT().getSizeInBits();
1856 // Allow the target to implement this method for its nodes.
1857 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1858 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1859 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1860 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1861 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1862 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1865 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1866 // use this information.
1867 APInt KnownZero, KnownOne;
1868 APInt Mask = APInt::getAllOnesValue(VTBits);
1869 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1871 if (KnownZero.isNegative()) { // sign bit is 0
1873 } else if (KnownOne.isNegative()) { // sign bit is 1;
1880 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1881 // the number of identical bits in the top of the input value.
1883 Mask <<= Mask.getBitWidth()-VTBits;
1884 // Return # leading zeros. We use 'min' here in case Val was zero before
1885 // shifting. We don't want to return '64' as for an i32 "0".
1886 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1890 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1891 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1892 if (!GA) return false;
1893 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1894 if (!GV) return false;
1895 MachineModuleInfo *MMI = getMachineModuleInfo();
1896 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1900 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1901 /// element of the result of the vector shuffle.
1902 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1903 MVT VT = N->getValueType(0);
1904 SDOperand PermMask = N->getOperand(2);
1905 SDOperand Idx = PermMask.getOperand(i);
1906 if (Idx.getOpcode() == ISD::UNDEF)
1907 return getNode(ISD::UNDEF, VT.getVectorElementType());
1908 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1909 unsigned NumElems = PermMask.getNumOperands();
1910 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1913 if (V.getOpcode() == ISD::BIT_CONVERT) {
1914 V = V.getOperand(0);
1915 if (V.getValueType().getVectorNumElements() != NumElems)
1918 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1919 return (Index == 0) ? V.getOperand(0)
1920 : getNode(ISD::UNDEF, VT.getVectorElementType());
1921 if (V.getOpcode() == ISD::BUILD_VECTOR)
1922 return V.getOperand(Index);
1923 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1924 return getShuffleScalarElt(V.Val, Index);
1929 /// getNode - Gets or creates the specified node.
1931 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1932 FoldingSetNodeID ID;
1933 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1935 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1936 return SDOperand(E, 0);
1937 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1938 CSEMap.InsertNode(N, IP);
1940 AllNodes.push_back(N);
1941 return SDOperand(N, 0);
1944 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1945 // Constant fold unary operations with an integer constant operand.
1946 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1947 const APInt &Val = C->getAPIntValue();
1948 unsigned BitWidth = VT.getSizeInBits();
1951 case ISD::SIGN_EXTEND:
1952 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1953 case ISD::ANY_EXTEND:
1954 case ISD::ZERO_EXTEND:
1956 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1957 case ISD::UINT_TO_FP:
1958 case ISD::SINT_TO_FP: {
1959 const uint64_t zero[] = {0, 0};
1960 // No compile time operations on this type.
1961 if (VT==MVT::ppcf128)
1963 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1964 (void)apf.convertFromAPInt(Val,
1965 Opcode==ISD::SINT_TO_FP,
1966 APFloat::rmNearestTiesToEven);
1967 return getConstantFP(apf, VT);
1969 case ISD::BIT_CONVERT:
1970 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1971 return getConstantFP(Val.bitsToFloat(), VT);
1972 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1973 return getConstantFP(Val.bitsToDouble(), VT);
1976 return getConstant(Val.byteSwap(), VT);
1978 return getConstant(Val.countPopulation(), VT);
1980 return getConstant(Val.countLeadingZeros(), VT);
1982 return getConstant(Val.countTrailingZeros(), VT);
1986 // Constant fold unary operations with a floating point constant operand.
1987 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1988 APFloat V = C->getValueAPF(); // make copy
1989 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1993 return getConstantFP(V, VT);
1996 return getConstantFP(V, VT);
1998 case ISD::FP_EXTEND:
1999 // This can return overflow, underflow, or inexact; we don't care.
2000 // FIXME need to be more flexible about rounding mode.
2001 (void)V.convert(*MVTToAPFloatSemantics(VT),
2002 APFloat::rmNearestTiesToEven);
2003 return getConstantFP(V, VT);
2004 case ISD::FP_TO_SINT:
2005 case ISD::FP_TO_UINT: {
2007 assert(integerPartWidth >= 64);
2008 // FIXME need to be more flexible about rounding mode.
2009 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2010 Opcode==ISD::FP_TO_SINT,
2011 APFloat::rmTowardZero);
2012 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2014 return getConstant(x, VT);
2016 case ISD::BIT_CONVERT:
2017 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2018 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2019 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2020 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2026 unsigned OpOpcode = Operand.Val->getOpcode();
2028 case ISD::TokenFactor:
2029 return Operand; // Factor of one node? No need.
2030 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2031 case ISD::FP_EXTEND:
2032 assert(VT.isFloatingPoint() &&
2033 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2034 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2035 if (Operand.getOpcode() == ISD::UNDEF)
2036 return getNode(ISD::UNDEF, VT);
2038 case ISD::SIGN_EXTEND:
2039 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2040 "Invalid SIGN_EXTEND!");
2041 if (Operand.getValueType() == VT) return Operand; // noop extension
2042 assert(Operand.getValueType().bitsLT(VT)
2043 && "Invalid sext node, dst < src!");
2044 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2045 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2047 case ISD::ZERO_EXTEND:
2048 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2049 "Invalid ZERO_EXTEND!");
2050 if (Operand.getValueType() == VT) return Operand; // noop extension
2051 assert(Operand.getValueType().bitsLT(VT)
2052 && "Invalid zext node, dst < src!");
2053 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2054 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2056 case ISD::ANY_EXTEND:
2057 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2058 "Invalid ANY_EXTEND!");
2059 if (Operand.getValueType() == VT) return Operand; // noop extension
2060 assert(Operand.getValueType().bitsLT(VT)
2061 && "Invalid anyext node, dst < src!");
2062 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2063 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2064 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2067 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2068 "Invalid TRUNCATE!");
2069 if (Operand.getValueType() == VT) return Operand; // noop truncate
2070 assert(Operand.getValueType().bitsGT(VT)
2071 && "Invalid truncate node, src < dst!");
2072 if (OpOpcode == ISD::TRUNCATE)
2073 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2074 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2075 OpOpcode == ISD::ANY_EXTEND) {
2076 // If the source is smaller than the dest, we still need an extend.
2077 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2078 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2079 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2080 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2082 return Operand.Val->getOperand(0);
2085 case ISD::BIT_CONVERT:
2086 // Basic sanity checking.
2087 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2088 && "Cannot BIT_CONVERT between types of different sizes!");
2089 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2090 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2091 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2092 if (OpOpcode == ISD::UNDEF)
2093 return getNode(ISD::UNDEF, VT);
2095 case ISD::SCALAR_TO_VECTOR:
2096 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2097 VT.getVectorElementType() == Operand.getValueType() &&
2098 "Illegal SCALAR_TO_VECTOR node!");
2099 if (OpOpcode == ISD::UNDEF)
2100 return getNode(ISD::UNDEF, VT);
2101 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2102 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2103 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2104 Operand.getConstantOperandVal(1) == 0 &&
2105 Operand.getOperand(0).getValueType() == VT)
2106 return Operand.getOperand(0);
2109 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2110 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2111 Operand.Val->getOperand(0));
2112 if (OpOpcode == ISD::FNEG) // --X -> X
2113 return Operand.Val->getOperand(0);
2116 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2117 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2122 SDVTList VTs = getVTList(VT);
2123 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2124 FoldingSetNodeID ID;
2125 SDOperand Ops[1] = { Operand };
2126 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2128 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2129 return SDOperand(E, 0);
2130 N = new UnarySDNode(Opcode, VTs, Operand);
2131 CSEMap.InsertNode(N, IP);
2133 N = new UnarySDNode(Opcode, VTs, Operand);
2135 AllNodes.push_back(N);
2136 return SDOperand(N, 0);
2141 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2142 SDOperand N1, SDOperand N2) {
2143 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2144 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2147 case ISD::TokenFactor:
2148 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2149 N2.getValueType() == MVT::Other && "Invalid token factor!");
2150 // Fold trivial token factors.
2151 if (N1.getOpcode() == ISD::EntryToken) return N2;
2152 if (N2.getOpcode() == ISD::EntryToken) return N1;
2155 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2156 N1.getValueType() == VT && "Binary operator types must match!");
2157 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2158 // worth handling here.
2159 if (N2C && N2C->isNullValue())
2161 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2168 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2169 N1.getValueType() == VT && "Binary operator types must match!");
2170 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2171 // it's worth handling here.
2172 if (N2C && N2C->isNullValue())
2179 assert(VT.isInteger() && "This operator does not apply to FP types!");
2189 assert(N1.getValueType() == N2.getValueType() &&
2190 N1.getValueType() == VT && "Binary operator types must match!");
2192 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2193 assert(N1.getValueType() == VT &&
2194 N1.getValueType().isFloatingPoint() &&
2195 N2.getValueType().isFloatingPoint() &&
2196 "Invalid FCOPYSIGN!");
2203 assert(VT == N1.getValueType() &&
2204 "Shift operators return type must be the same as their first arg");
2205 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2206 "Shifts only work on integers");
2208 // Always fold shifts of i1 values so the code generator doesn't need to
2209 // handle them. Since we know the size of the shift has to be less than the
2210 // size of the value, the shift/rotate count is guaranteed to be zero.
2214 case ISD::FP_ROUND_INREG: {
2215 MVT EVT = cast<VTSDNode>(N2)->getVT();
2216 assert(VT == N1.getValueType() && "Not an inreg round!");
2217 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2218 "Cannot FP_ROUND_INREG integer types");
2219 assert(EVT.bitsLE(VT) && "Not rounding down!");
2220 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2224 assert(VT.isFloatingPoint() &&
2225 N1.getValueType().isFloatingPoint() &&
2226 VT.bitsLE(N1.getValueType()) &&
2227 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2228 if (N1.getValueType() == VT) return N1; // noop conversion.
2230 case ISD::AssertSext:
2231 case ISD::AssertZext: {
2232 MVT EVT = cast<VTSDNode>(N2)->getVT();
2233 assert(VT == N1.getValueType() && "Not an inreg extend!");
2234 assert(VT.isInteger() && EVT.isInteger() &&
2235 "Cannot *_EXTEND_INREG FP types");
2236 assert(EVT.bitsLE(VT) && "Not extending!");
2237 if (VT == EVT) return N1; // noop assertion.
2240 case ISD::SIGN_EXTEND_INREG: {
2241 MVT EVT = cast<VTSDNode>(N2)->getVT();
2242 assert(VT == N1.getValueType() && "Not an inreg extend!");
2243 assert(VT.isInteger() && EVT.isInteger() &&
2244 "Cannot *_EXTEND_INREG FP types");
2245 assert(EVT.bitsLE(VT) && "Not extending!");
2246 if (EVT == VT) return N1; // Not actually extending
2249 APInt Val = N1C->getAPIntValue();
2250 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2251 Val <<= Val.getBitWidth()-FromBits;
2252 Val = Val.ashr(Val.getBitWidth()-FromBits);
2253 return getConstant(Val, VT);
2257 case ISD::EXTRACT_VECTOR_ELT:
2258 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2260 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2261 if (N1.getOpcode() == ISD::UNDEF)
2262 return getNode(ISD::UNDEF, VT);
2264 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2265 // expanding copies of large vectors from registers.
2266 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2267 N1.getNumOperands() > 0) {
2269 N1.getOperand(0).getValueType().getVectorNumElements();
2270 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2271 N1.getOperand(N2C->getValue() / Factor),
2272 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2275 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2276 // expanding large vector constants.
2277 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2278 return N1.getOperand(N2C->getValue());
2280 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2281 // operations are lowered to scalars.
2282 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2283 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2285 return N1.getOperand(1);
2287 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2290 case ISD::EXTRACT_ELEMENT:
2291 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2292 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2293 (N1.getValueType().isInteger() == VT.isInteger()) &&
2294 "Wrong types for EXTRACT_ELEMENT!");
2296 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2297 // 64-bit integers into 32-bit parts. Instead of building the extract of
2298 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2299 if (N1.getOpcode() == ISD::BUILD_PAIR)
2300 return N1.getOperand(N2C->getValue());
2302 // EXTRACT_ELEMENT of a constant int is also very common.
2303 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2304 unsigned ElementSize = VT.getSizeInBits();
2305 unsigned Shift = ElementSize * N2C->getValue();
2306 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2307 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2310 case ISD::EXTRACT_SUBVECTOR:
2311 if (N1.getValueType() == VT) // Trivial extraction.
2318 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2320 case ISD::ADD: return getConstant(C1 + C2, VT);
2321 case ISD::SUB: return getConstant(C1 - C2, VT);
2322 case ISD::MUL: return getConstant(C1 * C2, VT);
2324 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2327 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2330 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2333 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2335 case ISD::AND : return getConstant(C1 & C2, VT);
2336 case ISD::OR : return getConstant(C1 | C2, VT);
2337 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2338 case ISD::SHL : return getConstant(C1 << C2, VT);
2339 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2340 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2341 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2342 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2345 } else { // Cannonicalize constant to RHS if commutative
2346 if (isCommutativeBinOp(Opcode)) {
2347 std::swap(N1C, N2C);
2353 // Constant fold FP operations.
2354 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2355 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2357 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2358 // Cannonicalize constant to RHS if commutative
2359 std::swap(N1CFP, N2CFP);
2361 } else if (N2CFP && VT != MVT::ppcf128) {
2362 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2363 APFloat::opStatus s;
2366 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2367 if (s != APFloat::opInvalidOp)
2368 return getConstantFP(V1, VT);
2371 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2372 if (s!=APFloat::opInvalidOp)
2373 return getConstantFP(V1, VT);
2376 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2377 if (s!=APFloat::opInvalidOp)
2378 return getConstantFP(V1, VT);
2381 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2382 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2383 return getConstantFP(V1, VT);
2386 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2387 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2388 return getConstantFP(V1, VT);
2390 case ISD::FCOPYSIGN:
2392 return getConstantFP(V1, VT);
2398 // Canonicalize an UNDEF to the RHS, even over a constant.
2399 if (N1.getOpcode() == ISD::UNDEF) {
2400 if (isCommutativeBinOp(Opcode)) {
2404 case ISD::FP_ROUND_INREG:
2405 case ISD::SIGN_EXTEND_INREG:
2411 return N1; // fold op(undef, arg2) -> undef
2419 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2420 // For vectors, we can't easily build an all zero vector, just return
2427 // Fold a bunch of operators when the RHS is undef.
2428 if (N2.getOpcode() == ISD::UNDEF) {
2431 if (N1.getOpcode() == ISD::UNDEF)
2432 // Handle undef ^ undef -> 0 special case. This is a common
2434 return getConstant(0, VT);
2449 return N2; // fold op(arg1, undef) -> undef
2455 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2456 // For vectors, we can't easily build an all zero vector, just return
2461 return getConstant(VT.getIntegerVTBitMask(), VT);
2462 // For vectors, we can't easily build an all one vector, just return
2470 // Memoize this node if possible.
2472 SDVTList VTs = getVTList(VT);
2473 if (VT != MVT::Flag) {
2474 SDOperand Ops[] = { N1, N2 };
2475 FoldingSetNodeID ID;
2476 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2478 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2479 return SDOperand(E, 0);
2480 N = new BinarySDNode(Opcode, VTs, N1, N2);
2481 CSEMap.InsertNode(N, IP);
2483 N = new BinarySDNode(Opcode, VTs, N1, N2);
2486 AllNodes.push_back(N);
2487 return SDOperand(N, 0);
2490 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2491 SDOperand N1, SDOperand N2, SDOperand N3) {
2492 // Perform various simplifications.
2493 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2494 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2497 // Use FoldSetCC to simplify SETCC's.
2498 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2499 if (Simp.Val) return Simp;
2504 if (N1C->getValue())
2505 return N2; // select true, X, Y -> X
2507 return N3; // select false, X, Y -> Y
2510 if (N2 == N3) return N2; // select C, X, X -> X
2514 if (N2C->getValue()) // Unconditional branch
2515 return getNode(ISD::BR, MVT::Other, N1, N3);
2517 return N1; // Never-taken branch
2520 case ISD::VECTOR_SHUFFLE:
2521 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2522 VT.isVector() && N3.getValueType().isVector() &&
2523 N3.getOpcode() == ISD::BUILD_VECTOR &&
2524 VT.getVectorNumElements() == N3.getNumOperands() &&
2525 "Illegal VECTOR_SHUFFLE node!");
2527 case ISD::BIT_CONVERT:
2528 // Fold bit_convert nodes from a type to themselves.
2529 if (N1.getValueType() == VT)
2534 // Memoize node if it doesn't produce a flag.
2536 SDVTList VTs = getVTList(VT);
2537 if (VT != MVT::Flag) {
2538 SDOperand Ops[] = { N1, N2, N3 };
2539 FoldingSetNodeID ID;
2540 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2542 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2543 return SDOperand(E, 0);
2544 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2545 CSEMap.InsertNode(N, IP);
2547 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2549 AllNodes.push_back(N);
2550 return SDOperand(N, 0);
2553 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2554 SDOperand N1, SDOperand N2, SDOperand N3,
2556 SDOperand Ops[] = { N1, N2, N3, N4 };
2557 return getNode(Opcode, VT, Ops, 4);
2560 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2561 SDOperand N1, SDOperand N2, SDOperand N3,
2562 SDOperand N4, SDOperand N5) {
2563 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2564 return getNode(Opcode, VT, Ops, 5);
2567 /// getMemsetValue - Vectorized representation of the memset value
2569 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2570 unsigned NumBits = VT.isVector() ?
2571 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2572 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2573 APInt Val = APInt(NumBits, C->getValue() & 255);
2575 for (unsigned i = NumBits; i > 8; i >>= 1) {
2576 Val = (Val << Shift) | Val;
2580 return DAG.getConstant(Val, VT);
2581 return DAG.getConstantFP(APFloat(Val), VT);
2584 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2586 for (unsigned i = NumBits; i > 8; i >>= 1) {
2587 Value = DAG.getNode(ISD::OR, VT,
2588 DAG.getNode(ISD::SHL, VT, Value,
2589 DAG.getConstant(Shift, MVT::i8)), Value);
2596 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2597 /// used when a memcpy is turned into a memset when the source is a constant
2599 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2600 const TargetLowering &TLI,
2601 std::string &Str, unsigned Offset) {
2602 // Handle vector with all elements zero.
2605 return DAG.getConstant(0, VT);
2606 unsigned NumElts = VT.getVectorNumElements();
2607 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2608 return DAG.getNode(ISD::BIT_CONVERT, VT,
2609 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2612 assert(!VT.isVector() && "Can't handle vector type here!");
2613 unsigned NumBits = VT.getSizeInBits();
2614 unsigned MSB = NumBits / 8;
2616 if (TLI.isLittleEndian())
2617 Offset = Offset + MSB - 1;
2618 for (unsigned i = 0; i != MSB; ++i) {
2619 Val = (Val << 8) | (unsigned char)Str[Offset];
2620 Offset += TLI.isLittleEndian() ? -1 : 1;
2622 return DAG.getConstant(Val, VT);
2625 /// getMemBasePlusOffset - Returns base and offset node for the
2627 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2628 SelectionDAG &DAG) {
2629 MVT VT = Base.getValueType();
2630 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2633 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2635 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2636 unsigned SrcDelta = 0;
2637 GlobalAddressSDNode *G = NULL;
2638 if (Src.getOpcode() == ISD::GlobalAddress)
2639 G = cast<GlobalAddressSDNode>(Src);
2640 else if (Src.getOpcode() == ISD::ADD &&
2641 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2642 Src.getOperand(1).getOpcode() == ISD::Constant) {
2643 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2644 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2649 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2650 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2656 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2657 /// to replace the memset / memcpy is below the threshold. It also returns the
2658 /// types of the sequence of memory ops to perform memset / memcpy.
2660 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2661 SDOperand Dst, SDOperand Src,
2662 unsigned Limit, uint64_t Size, unsigned &Align,
2663 std::string &Str, bool &isSrcStr,
2665 const TargetLowering &TLI) {
2666 isSrcStr = isMemSrcFromString(Src, Str);
2667 bool isSrcConst = isa<ConstantSDNode>(Src);
2668 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2669 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2670 if (VT != MVT::iAny) {
2671 unsigned NewAlign = (unsigned)
2672 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2673 // If source is a string constant, this will require an unaligned load.
2674 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2675 if (Dst.getOpcode() != ISD::FrameIndex) {
2676 // Can't change destination alignment. It requires a unaligned store.
2680 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2681 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2682 if (MFI->isFixedObjectIndex(FI)) {
2683 // Can't change destination alignment. It requires a unaligned store.
2687 // Give the stack frame object a larger alignment if needed.
2688 if (MFI->getObjectAlignment(FI) < NewAlign)
2689 MFI->setObjectAlignment(FI, NewAlign);
2696 if (VT == MVT::iAny) {
2700 switch (Align & 7) {
2701 case 0: VT = MVT::i64; break;
2702 case 4: VT = MVT::i32; break;
2703 case 2: VT = MVT::i16; break;
2704 default: VT = MVT::i8; break;
2709 while (!TLI.isTypeLegal(LVT))
2710 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2711 assert(LVT.isInteger());
2717 unsigned NumMemOps = 0;
2719 unsigned VTSize = VT.getSizeInBits() / 8;
2720 while (VTSize > Size) {
2721 // For now, only use non-vector load / store's for the left-over pieces.
2722 if (VT.isVector()) {
2724 while (!TLI.isTypeLegal(VT))
2725 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2726 VTSize = VT.getSizeInBits() / 8;
2728 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2733 if (++NumMemOps > Limit)
2735 MemOps.push_back(VT);
2742 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2743 SDOperand Chain, SDOperand Dst,
2744 SDOperand Src, uint64_t Size,
2745 unsigned Align, bool AlwaysInline,
2746 const Value *DstSV, uint64_t DstSVOff,
2747 const Value *SrcSV, uint64_t SrcSVOff){
2748 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2750 // Expand memcpy to a series of load and store ops if the size operand falls
2751 // below a certain threshold.
2752 std::vector<MVT> MemOps;
2753 uint64_t Limit = -1;
2755 Limit = TLI.getMaxStoresPerMemcpy();
2756 unsigned DstAlign = Align; // Destination alignment can change.
2759 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2760 Str, CopyFromStr, DAG, TLI))
2764 bool isZeroStr = CopyFromStr && Str.empty();
2765 SmallVector<SDOperand, 8> OutChains;
2766 unsigned NumMemOps = MemOps.size();
2767 uint64_t SrcOff = 0, DstOff = 0;
2768 for (unsigned i = 0; i < NumMemOps; i++) {
2770 unsigned VTSize = VT.getSizeInBits() / 8;
2771 SDOperand Value, Store;
2773 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2774 // It's unlikely a store of a vector immediate can be done in a single
2775 // instruction. It would require a load from a constantpool first.
2776 // We also handle store a vector with all zero's.
2777 // FIXME: Handle other cases where store of vector immediate is done in
2778 // a single instruction.
2779 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2780 Store = DAG.getStore(Chain, Value,
2781 getMemBasePlusOffset(Dst, DstOff, DAG),
2782 DstSV, DstSVOff + DstOff);
2784 Value = DAG.getLoad(VT, Chain,
2785 getMemBasePlusOffset(Src, SrcOff, DAG),
2786 SrcSV, SrcSVOff + SrcOff, false, Align);
2787 Store = DAG.getStore(Chain, Value,
2788 getMemBasePlusOffset(Dst, DstOff, DAG),
2789 DstSV, DstSVOff + DstOff, false, DstAlign);
2791 OutChains.push_back(Store);
2796 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2797 &OutChains[0], OutChains.size());
2800 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2801 SDOperand Chain, SDOperand Dst,
2802 SDOperand Src, uint64_t Size,
2803 unsigned Align, bool AlwaysInline,
2804 const Value *DstSV, uint64_t DstSVOff,
2805 const Value *SrcSV, uint64_t SrcSVOff){
2806 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2808 // Expand memmove to a series of load and store ops if the size operand falls
2809 // below a certain threshold.
2810 std::vector<MVT> MemOps;
2811 uint64_t Limit = -1;
2813 Limit = TLI.getMaxStoresPerMemmove();
2814 unsigned DstAlign = Align; // Destination alignment can change.
2817 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2818 Str, CopyFromStr, DAG, TLI))
2821 uint64_t SrcOff = 0, DstOff = 0;
2823 SmallVector<SDOperand, 8> LoadValues;
2824 SmallVector<SDOperand, 8> LoadChains;
2825 SmallVector<SDOperand, 8> OutChains;
2826 unsigned NumMemOps = MemOps.size();
2827 for (unsigned i = 0; i < NumMemOps; i++) {
2829 unsigned VTSize = VT.getSizeInBits() / 8;
2830 SDOperand Value, Store;
2832 Value = DAG.getLoad(VT, Chain,
2833 getMemBasePlusOffset(Src, SrcOff, DAG),
2834 SrcSV, SrcSVOff + SrcOff, false, Align);
2835 LoadValues.push_back(Value);
2836 LoadChains.push_back(Value.getValue(1));
2839 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2840 &LoadChains[0], LoadChains.size());
2842 for (unsigned i = 0; i < NumMemOps; i++) {
2844 unsigned VTSize = VT.getSizeInBits() / 8;
2845 SDOperand Value, Store;
2847 Store = DAG.getStore(Chain, LoadValues[i],
2848 getMemBasePlusOffset(Dst, DstOff, DAG),
2849 DstSV, DstSVOff + DstOff, false, DstAlign);
2850 OutChains.push_back(Store);
2854 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2855 &OutChains[0], OutChains.size());
2858 static SDOperand getMemsetStores(SelectionDAG &DAG,
2859 SDOperand Chain, SDOperand Dst,
2860 SDOperand Src, uint64_t Size,
2862 const Value *DstSV, uint64_t DstSVOff) {
2863 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2865 // Expand memset to a series of load/store ops if the size operand
2866 // falls below a certain threshold.
2867 std::vector<MVT> MemOps;
2870 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2871 Size, Align, Str, CopyFromStr, DAG, TLI))
2874 SmallVector<SDOperand, 8> OutChains;
2875 uint64_t DstOff = 0;
2877 unsigned NumMemOps = MemOps.size();
2878 for (unsigned i = 0; i < NumMemOps; i++) {
2880 unsigned VTSize = VT.getSizeInBits() / 8;
2881 SDOperand Value = getMemsetValue(Src, VT, DAG);
2882 SDOperand Store = DAG.getStore(Chain, Value,
2883 getMemBasePlusOffset(Dst, DstOff, DAG),
2884 DstSV, DstSVOff + DstOff);
2885 OutChains.push_back(Store);
2889 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2890 &OutChains[0], OutChains.size());
2893 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2894 SDOperand Src, SDOperand Size,
2895 unsigned Align, bool AlwaysInline,
2896 const Value *DstSV, uint64_t DstSVOff,
2897 const Value *SrcSV, uint64_t SrcSVOff) {
2899 // Check to see if we should lower the memcpy to loads and stores first.
2900 // For cases within the target-specified limits, this is the best choice.
2901 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2903 // Memcpy with size zero? Just return the original chain.
2904 if (ConstantSize->isNullValue())
2908 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2909 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2914 // Then check to see if we should lower the memcpy with target-specific
2915 // code. If the target chooses to do this, this is the next best.
2917 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2919 DstSV, DstSVOff, SrcSV, SrcSVOff);
2923 // If we really need inline code and the target declined to provide it,
2924 // use a (potentially long) sequence of loads and stores.
2926 assert(ConstantSize && "AlwaysInline requires a constant size!");
2927 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2928 ConstantSize->getValue(), Align, true,
2929 DstSV, DstSVOff, SrcSV, SrcSVOff);
2932 // Emit a library call.
2933 TargetLowering::ArgListTy Args;
2934 TargetLowering::ArgListEntry Entry;
2935 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2936 Entry.Node = Dst; Args.push_back(Entry);
2937 Entry.Node = Src; Args.push_back(Entry);
2938 Entry.Node = Size; Args.push_back(Entry);
2939 std::pair<SDOperand,SDOperand> CallResult =
2940 TLI.LowerCallTo(Chain, Type::VoidTy,
2941 false, false, false, CallingConv::C, false,
2942 getExternalSymbol("memcpy", TLI.getPointerTy()),
2944 return CallResult.second;
2947 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2948 SDOperand Src, SDOperand Size,
2950 const Value *DstSV, uint64_t DstSVOff,
2951 const Value *SrcSV, uint64_t SrcSVOff) {
2953 // Check to see if we should lower the memmove to loads and stores first.
2954 // For cases within the target-specified limits, this is the best choice.
2955 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2957 // Memmove with size zero? Just return the original chain.
2958 if (ConstantSize->isNullValue())
2962 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2963 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2968 // Then check to see if we should lower the memmove with target-specific
2969 // code. If the target chooses to do this, this is the next best.
2971 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2972 DstSV, DstSVOff, SrcSV, SrcSVOff);
2976 // Emit a library call.
2977 TargetLowering::ArgListTy Args;
2978 TargetLowering::ArgListEntry Entry;
2979 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2980 Entry.Node = Dst; Args.push_back(Entry);
2981 Entry.Node = Src; Args.push_back(Entry);
2982 Entry.Node = Size; Args.push_back(Entry);
2983 std::pair<SDOperand,SDOperand> CallResult =
2984 TLI.LowerCallTo(Chain, Type::VoidTy,
2985 false, false, false, CallingConv::C, false,
2986 getExternalSymbol("memmove", TLI.getPointerTy()),
2988 return CallResult.second;
2991 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2992 SDOperand Src, SDOperand Size,
2994 const Value *DstSV, uint64_t DstSVOff) {
2996 // Check to see if we should lower the memset to stores first.
2997 // For cases within the target-specified limits, this is the best choice.
2998 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3000 // Memset with size zero? Just return the original chain.
3001 if (ConstantSize->isNullValue())
3005 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3011 // Then check to see if we should lower the memset with target-specific
3012 // code. If the target chooses to do this, this is the next best.
3014 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3019 // Emit a library call.
3020 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3021 TargetLowering::ArgListTy Args;
3022 TargetLowering::ArgListEntry Entry;
3023 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3024 Args.push_back(Entry);
3025 // Extend or truncate the argument to be an i32 value for the call.
3026 if (Src.getValueType().bitsGT(MVT::i32))
3027 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3029 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3030 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3031 Args.push_back(Entry);
3032 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3033 Args.push_back(Entry);
3034 std::pair<SDOperand,SDOperand> CallResult =
3035 TLI.LowerCallTo(Chain, Type::VoidTy,
3036 false, false, false, CallingConv::C, false,
3037 getExternalSymbol("memset", TLI.getPointerTy()),
3039 return CallResult.second;
3042 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3043 SDOperand Ptr, SDOperand Cmp,
3044 SDOperand Swp, const Value* PtrVal,
3045 unsigned Alignment) {
3046 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3047 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3048 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
3049 FoldingSetNodeID ID;
3050 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3051 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3053 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3054 return SDOperand(E, 0);
3055 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp,
3057 CSEMap.InsertNode(N, IP);
3058 AllNodes.push_back(N);
3059 return SDOperand(N, 0);
3062 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3063 SDOperand Ptr, SDOperand Val,
3064 const Value* PtrVal,
3065 unsigned Alignment) {
3066 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3067 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3068 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3069 || Opcode == ISD::ATOMIC_LOAD_NAND
3070 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3071 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3072 && "Invalid Atomic Op");
3073 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3074 FoldingSetNodeID ID;
3075 SDOperand Ops[] = {Chain, Ptr, Val};
3076 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3078 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3079 return SDOperand(E, 0);
3080 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val,
3082 CSEMap.InsertNode(N, IP);
3083 AllNodes.push_back(N);
3084 return SDOperand(N, 0);
3087 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3088 /// Allowed to return something different (and simpler) if Simplify is true.
3089 SDOperand SelectionDAG::getMergeValues(const SDOperand *Ops, unsigned NumOps,
3091 if (Simplify && NumOps == 1)
3094 SmallVector<MVT, 4> VTs;
3095 VTs.reserve(NumOps);
3096 for (unsigned i = 0; i < NumOps; ++i)
3097 VTs.push_back(Ops[i].getValueType());
3098 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3102 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3103 MVT VT, SDOperand Chain,
3104 SDOperand Ptr, SDOperand Offset,
3105 const Value *SV, int SVOffset, MVT EVT,
3106 bool isVolatile, unsigned Alignment) {
3107 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3109 if (VT != MVT::iPTR) {
3110 Ty = VT.getTypeForMVT();
3112 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3113 assert(PT && "Value for load must be a pointer");
3114 Ty = PT->getElementType();
3116 assert(Ty && "Could not get type information for load");
3117 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3121 ExtType = ISD::NON_EXTLOAD;
3122 } else if (ExtType == ISD::NON_EXTLOAD) {
3123 assert(VT == EVT && "Non-extending load from different memory type!");
3127 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3129 assert(EVT.bitsLT(VT) &&
3130 "Should only be an extending load, not truncating!");
3131 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3132 "Cannot sign/zero extend a FP/Vector load!");
3133 assert(VT.isInteger() == EVT.isInteger() &&
3134 "Cannot convert from FP to Int or Int -> FP!");
3137 bool Indexed = AM != ISD::UNINDEXED;
3138 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3139 "Unindexed load with an offset!");
3141 SDVTList VTs = Indexed ?
3142 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3143 SDOperand Ops[] = { Chain, Ptr, Offset };
3144 FoldingSetNodeID ID;
3145 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3147 ID.AddInteger(ExtType);
3148 ID.AddInteger(EVT.getRawBits());
3149 ID.AddInteger(Alignment);
3150 ID.AddInteger(isVolatile);
3152 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3153 return SDOperand(E, 0);
3154 SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3155 Alignment, isVolatile);
3156 CSEMap.InsertNode(N, IP);
3157 AllNodes.push_back(N);
3158 return SDOperand(N, 0);
3161 SDOperand SelectionDAG::getLoad(MVT VT,
3162 SDOperand Chain, SDOperand Ptr,
3163 const Value *SV, int SVOffset,
3164 bool isVolatile, unsigned Alignment) {
3165 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3166 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3167 SV, SVOffset, VT, isVolatile, Alignment);
3170 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3171 SDOperand Chain, SDOperand Ptr,
3173 int SVOffset, MVT EVT,
3174 bool isVolatile, unsigned Alignment) {
3175 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3176 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3177 SV, SVOffset, EVT, isVolatile, Alignment);
3181 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3182 SDOperand Offset, ISD::MemIndexedMode AM) {
3183 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3184 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3185 "Load is already a indexed load!");
3186 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3187 LD->getChain(), Base, Offset, LD->getSrcValue(),
3188 LD->getSrcValueOffset(), LD->getMemoryVT(),
3189 LD->isVolatile(), LD->getAlignment());
3192 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3193 SDOperand Ptr, const Value *SV, int SVOffset,
3194 bool isVolatile, unsigned Alignment) {
3195 MVT VT = Val.getValueType();
3197 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3199 if (VT != MVT::iPTR) {
3200 Ty = VT.getTypeForMVT();
3202 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3203 assert(PT && "Value for store must be a pointer");
3204 Ty = PT->getElementType();
3206 assert(Ty && "Could not get type information for store");
3207 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3209 SDVTList VTs = getVTList(MVT::Other);
3210 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3211 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3212 FoldingSetNodeID ID;
3213 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3214 ID.AddInteger(ISD::UNINDEXED);
3215 ID.AddInteger(false);
3216 ID.AddInteger(VT.getRawBits());
3217 ID.AddInteger(Alignment);
3218 ID.AddInteger(isVolatile);
3220 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3221 return SDOperand(E, 0);
3222 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3223 VT, SV, SVOffset, Alignment, isVolatile);
3224 CSEMap.InsertNode(N, IP);
3225 AllNodes.push_back(N);
3226 return SDOperand(N, 0);
3229 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3230 SDOperand Ptr, const Value *SV,
3231 int SVOffset, MVT SVT,
3232 bool isVolatile, unsigned Alignment) {
3233 MVT VT = Val.getValueType();
3236 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3238 assert(VT.bitsGT(SVT) && "Not a truncation?");
3239 assert(VT.isInteger() == SVT.isInteger() &&
3240 "Can't do FP-INT conversion!");
3242 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3244 if (VT != MVT::iPTR) {
3245 Ty = VT.getTypeForMVT();
3247 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3248 assert(PT && "Value for store must be a pointer");
3249 Ty = PT->getElementType();
3251 assert(Ty && "Could not get type information for store");
3252 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3254 SDVTList VTs = getVTList(MVT::Other);
3255 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3256 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3257 FoldingSetNodeID ID;
3258 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3259 ID.AddInteger(ISD::UNINDEXED);
3261 ID.AddInteger(SVT.getRawBits());
3262 ID.AddInteger(Alignment);
3263 ID.AddInteger(isVolatile);
3265 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3266 return SDOperand(E, 0);
3267 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3268 SVT, SV, SVOffset, Alignment, isVolatile);
3269 CSEMap.InsertNode(N, IP);
3270 AllNodes.push_back(N);
3271 return SDOperand(N, 0);
3275 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3276 SDOperand Offset, ISD::MemIndexedMode AM) {
3277 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3278 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3279 "Store is already a indexed store!");
3280 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3281 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3282 FoldingSetNodeID ID;
3283 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3285 ID.AddInteger(ST->isTruncatingStore());
3286 ID.AddInteger(ST->getMemoryVT().getRawBits());
3287 ID.AddInteger(ST->getAlignment());
3288 ID.AddInteger(ST->isVolatile());
3290 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3291 return SDOperand(E, 0);
3292 SDNode *N = new StoreSDNode(Ops, VTs, AM,
3293 ST->isTruncatingStore(), ST->getMemoryVT(),
3294 ST->getSrcValue(), ST->getSrcValueOffset(),
3295 ST->getAlignment(), ST->isVolatile());
3296 CSEMap.InsertNode(N, IP);
3297 AllNodes.push_back(N);
3298 return SDOperand(N, 0);
3301 SDOperand SelectionDAG::getVAArg(MVT VT,
3302 SDOperand Chain, SDOperand Ptr,
3304 SDOperand Ops[] = { Chain, Ptr, SV };
3305 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3308 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3309 const SDUse *Ops, unsigned NumOps) {
3311 case 0: return getNode(Opcode, VT);
3312 case 1: return getNode(Opcode, VT, Ops[0].getSDOperand());
3313 case 2: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3314 Ops[1].getSDOperand());
3315 case 3: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3316 Ops[1].getSDOperand(), Ops[2].getSDOperand());
3320 // Copy from an SDUse array into an SDOperand array for use with
3321 // the regular getNode logic.
3322 SmallVector<SDOperand, 8> NewOps;
3323 NewOps.reserve(NumOps);
3324 for (unsigned i = 0; i != NumOps; ++i)
3325 NewOps.push_back(Ops[i].getSDOperand());
3326 return getNode(Opcode, VT, Ops, NumOps);
3329 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3330 const SDOperand *Ops, unsigned NumOps) {
3332 case 0: return getNode(Opcode, VT);
3333 case 1: return getNode(Opcode, VT, Ops[0]);
3334 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3335 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3341 case ISD::SELECT_CC: {
3342 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3343 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3344 "LHS and RHS of condition must have same type!");
3345 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3346 "True and False arms of SelectCC must have same type!");
3347 assert(Ops[2].getValueType() == VT &&
3348 "select_cc node must be of same type as true and false value!");
3352 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3353 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3354 "LHS/RHS of comparison should match types!");
3361 SDVTList VTs = getVTList(VT);
3362 if (VT != MVT::Flag) {
3363 FoldingSetNodeID ID;
3364 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3366 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3367 return SDOperand(E, 0);
3368 N = new SDNode(Opcode, VTs, Ops, NumOps);
3369 CSEMap.InsertNode(N, IP);
3371 N = new SDNode(Opcode, VTs, Ops, NumOps);
3373 AllNodes.push_back(N);
3374 return SDOperand(N, 0);
3377 SDOperand SelectionDAG::getNode(unsigned Opcode,
3378 std::vector<MVT> &ResultTys,
3379 const SDOperand *Ops, unsigned NumOps) {
3380 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3384 SDOperand SelectionDAG::getNode(unsigned Opcode,
3385 const MVT *VTs, unsigned NumVTs,
3386 const SDOperand *Ops, unsigned NumOps) {
3388 return getNode(Opcode, VTs[0], Ops, NumOps);
3389 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3392 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3393 const SDOperand *Ops, unsigned NumOps) {
3394 if (VTList.NumVTs == 1)
3395 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3398 // FIXME: figure out how to safely handle things like
3399 // int foo(int x) { return 1 << (x & 255); }
3400 // int bar() { return foo(256); }
3402 case ISD::SRA_PARTS:
3403 case ISD::SRL_PARTS:
3404 case ISD::SHL_PARTS:
3405 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3406 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3407 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3408 else if (N3.getOpcode() == ISD::AND)
3409 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3410 // If the and is only masking out bits that cannot effect the shift,
3411 // eliminate the and.
3412 unsigned NumBits = VT.getSizeInBits()*2;
3413 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3414 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3420 // Memoize the node unless it returns a flag.
3422 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3423 FoldingSetNodeID ID;
3424 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3426 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3427 return SDOperand(E, 0);
3429 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3430 else if (NumOps == 2)
3431 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3432 else if (NumOps == 3)
3433 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3435 N = new SDNode(Opcode, VTList, Ops, NumOps);
3436 CSEMap.InsertNode(N, IP);
3439 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3440 else if (NumOps == 2)
3441 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3442 else if (NumOps == 3)
3443 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3445 N = new SDNode(Opcode, VTList, Ops, NumOps);
3447 AllNodes.push_back(N);
3448 return SDOperand(N, 0);
3451 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3452 return getNode(Opcode, VTList, 0, 0);
3455 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3457 SDOperand Ops[] = { N1 };
3458 return getNode(Opcode, VTList, Ops, 1);
3461 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3462 SDOperand N1, SDOperand N2) {
3463 SDOperand Ops[] = { N1, N2 };
3464 return getNode(Opcode, VTList, Ops, 2);
3467 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3468 SDOperand N1, SDOperand N2, SDOperand N3) {
3469 SDOperand Ops[] = { N1, N2, N3 };
3470 return getNode(Opcode, VTList, Ops, 3);
3473 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3474 SDOperand N1, SDOperand N2, SDOperand N3,
3476 SDOperand Ops[] = { N1, N2, N3, N4 };
3477 return getNode(Opcode, VTList, Ops, 4);
3480 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3481 SDOperand N1, SDOperand N2, SDOperand N3,
3482 SDOperand N4, SDOperand N5) {
3483 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3484 return getNode(Opcode, VTList, Ops, 5);
3487 SDVTList SelectionDAG::getVTList(MVT VT) {
3488 return makeVTList(SDNode::getValueTypeList(VT), 1);
3491 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3492 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3493 E = VTList.end(); I != E; ++I) {
3494 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3495 return makeVTList(&(*I)[0], 2);
3500 VTList.push_front(V);
3501 return makeVTList(&(*VTList.begin())[0], 2);
3503 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3505 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3506 E = VTList.end(); I != E; ++I) {
3507 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3509 return makeVTList(&(*I)[0], 3);
3515 VTList.push_front(V);
3516 return makeVTList(&(*VTList.begin())[0], 3);
3519 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3521 case 0: assert(0 && "Cannot have nodes without results!");
3522 case 1: return getVTList(VTs[0]);
3523 case 2: return getVTList(VTs[0], VTs[1]);
3524 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3528 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3529 E = VTList.end(); I != E; ++I) {
3530 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3532 bool NoMatch = false;
3533 for (unsigned i = 2; i != NumVTs; ++i)
3534 if (VTs[i] != (*I)[i]) {
3539 return makeVTList(&*I->begin(), NumVTs);
3542 VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3543 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3547 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3548 /// specified operands. If the resultant node already exists in the DAG,
3549 /// this does not modify the specified node, instead it returns the node that
3550 /// already exists. If the resultant node does not exist in the DAG, the
3551 /// input node is returned. As a degenerate case, if you specify the same
3552 /// input operands as the node already has, the input node is returned.
3553 SDOperand SelectionDAG::
3554 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3555 SDNode *N = InN.Val;
3556 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3558 // Check to see if there is no change.
3559 if (Op == N->getOperand(0)) return InN;
3561 // See if the modified node already exists.
3562 void *InsertPos = 0;
3563 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3564 return SDOperand(Existing, InN.ResNo);
3566 // Nope it doesn't. Remove the node from it's current place in the maps.
3568 RemoveNodeFromCSEMaps(N);
3570 // Now we update the operands.
3571 N->OperandList[0].getVal()->removeUser(0, N);
3572 N->OperandList[0] = Op;
3573 N->OperandList[0].setUser(N);
3574 Op.Val->addUser(0, N);
3576 // If this gets put into a CSE map, add it.
3577 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3581 SDOperand SelectionDAG::
3582 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3583 SDNode *N = InN.Val;
3584 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3586 // Check to see if there is no change.
3587 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3588 return InN; // No operands changed, just return the input node.
3590 // See if the modified node already exists.
3591 void *InsertPos = 0;
3592 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3593 return SDOperand(Existing, InN.ResNo);
3595 // Nope it doesn't. Remove the node from it's current place in the maps.
3597 RemoveNodeFromCSEMaps(N);
3599 // Now we update the operands.
3600 if (N->OperandList[0] != Op1) {
3601 N->OperandList[0].getVal()->removeUser(0, N);
3602 N->OperandList[0] = Op1;
3603 N->OperandList[0].setUser(N);
3604 Op1.Val->addUser(0, N);
3606 if (N->OperandList[1] != Op2) {
3607 N->OperandList[1].getVal()->removeUser(1, N);
3608 N->OperandList[1] = Op2;
3609 N->OperandList[1].setUser(N);
3610 Op2.Val->addUser(1, N);
3613 // If this gets put into a CSE map, add it.
3614 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3618 SDOperand SelectionDAG::
3619 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3620 SDOperand Ops[] = { Op1, Op2, Op3 };
3621 return UpdateNodeOperands(N, Ops, 3);
3624 SDOperand SelectionDAG::
3625 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3626 SDOperand Op3, SDOperand Op4) {
3627 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3628 return UpdateNodeOperands(N, Ops, 4);
3631 SDOperand SelectionDAG::
3632 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3633 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3634 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3635 return UpdateNodeOperands(N, Ops, 5);
3638 SDOperand SelectionDAG::
3639 UpdateNodeOperands(SDOperand InN, const SDOperand *Ops, unsigned NumOps) {
3640 SDNode *N = InN.Val;
3641 assert(N->getNumOperands() == NumOps &&
3642 "Update with wrong number of operands");
3644 // Check to see if there is no change.
3645 bool AnyChange = false;
3646 for (unsigned i = 0; i != NumOps; ++i) {
3647 if (Ops[i] != N->getOperand(i)) {
3653 // No operands changed, just return the input node.
3654 if (!AnyChange) return InN;
3656 // See if the modified node already exists.
3657 void *InsertPos = 0;
3658 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3659 return SDOperand(Existing, InN.ResNo);
3661 // Nope it doesn't. Remove the node from its current place in the maps.
3663 RemoveNodeFromCSEMaps(N);
3665 // Now we update the operands.
3666 for (unsigned i = 0; i != NumOps; ++i) {
3667 if (N->OperandList[i] != Ops[i]) {
3668 N->OperandList[i].getVal()->removeUser(i, N);
3669 N->OperandList[i] = Ops[i];
3670 N->OperandList[i].setUser(N);
3671 Ops[i].Val->addUser(i, N);
3675 // If this gets put into a CSE map, add it.
3676 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3680 /// MorphNodeTo - This frees the operands of the current node, resets the
3681 /// opcode, types, and operands to the specified value. This should only be
3682 /// used by the SelectionDAG class.
3683 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3684 const SDOperand *Ops, unsigned NumOps) {
3687 NumValues = L.NumVTs;
3689 // Clear the operands list, updating used nodes to remove this from their
3691 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3692 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3694 // If NumOps is larger than the # of operands we currently have, reallocate
3695 // the operand list.
3696 if (NumOps > NumOperands) {
3697 if (OperandsNeedDelete) {
3698 delete [] OperandList;
3700 OperandList = new SDUse[NumOps];
3701 OperandsNeedDelete = true;
3704 // Assign the new operands.
3705 NumOperands = NumOps;
3707 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3708 OperandList[i] = Ops[i];
3709 OperandList[i].setUser(this);
3710 SDNode *N = OperandList[i].getVal();
3711 N->addUser(i, this);
3716 /// SelectNodeTo - These are used for target selectors to *mutate* the
3717 /// specified node to have the specified return type, Target opcode, and
3718 /// operands. Note that target opcodes are stored as
3719 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3721 /// Note that SelectNodeTo returns the resultant node. If there is already a
3722 /// node of the specified opcode and operands, it returns that node instead of
3723 /// the current one.
3724 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3726 SDVTList VTs = getVTList(VT);
3727 return SelectNodeTo(N, TargetOpc, VTs, 0, 0);
3730 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3731 MVT VT, SDOperand Op1) {
3732 SDVTList VTs = getVTList(VT);
3733 SDOperand Ops[] = { Op1 };
3734 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3737 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3738 MVT VT, SDOperand Op1,
3740 SDVTList VTs = getVTList(VT);
3741 SDOperand Ops[] = { Op1, Op2 };
3742 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3745 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3746 MVT VT, SDOperand Op1,
3747 SDOperand Op2, SDOperand Op3) {
3748 SDVTList VTs = getVTList(VT);
3749 SDOperand Ops[] = { Op1, Op2, Op3 };
3750 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3753 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3754 MVT VT, const SDOperand *Ops,
3756 SDVTList VTs = getVTList(VT);
3757 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3760 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3761 MVT VT1, MVT VT2, const SDOperand *Ops,
3763 SDVTList VTs = getVTList(VT1, VT2);
3764 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3767 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3769 SDVTList VTs = getVTList(VT1, VT2);
3770 return SelectNodeTo(N, TargetOpc, VTs, (SDOperand *)0, 0);
3773 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3774 MVT VT1, MVT VT2, MVT VT3,
3775 const SDOperand *Ops, unsigned NumOps) {
3776 SDVTList VTs = getVTList(VT1, VT2, VT3);
3777 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3780 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3783 SDVTList VTs = getVTList(VT1, VT2);
3784 SDOperand Ops[] = { Op1 };
3785 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3788 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3790 SDOperand Op1, SDOperand Op2) {
3791 SDVTList VTs = getVTList(VT1, VT2);
3792 SDOperand Ops[] = { Op1, Op2 };
3793 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3796 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3798 SDOperand Op1, SDOperand Op2,
3800 SDVTList VTs = getVTList(VT1, VT2);
3801 SDOperand Ops[] = { Op1, Op2, Op3 };
3802 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3805 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3806 SDVTList VTs, const SDOperand *Ops,
3808 // If an identical node already exists, use it.
3809 FoldingSetNodeID ID;
3810 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3812 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3815 RemoveNodeFromCSEMaps(N);
3817 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3818 CSEMap.InsertNode(N, IP); // Memoize the new node.
3823 /// getTargetNode - These are used for target selectors to create a new node
3824 /// with specified return type(s), target opcode, and operands.
3826 /// Note that getTargetNode returns the resultant node. If there is already a
3827 /// node of the specified opcode and operands, it returns that node instead of
3828 /// the current one.
3829 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3830 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3832 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3833 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3835 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3836 SDOperand Op1, SDOperand Op2) {
3837 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3839 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3840 SDOperand Op1, SDOperand Op2,
3842 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3844 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3845 const SDOperand *Ops, unsigned NumOps) {
3846 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3848 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3849 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3851 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3853 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3854 MVT VT2, SDOperand Op1) {
3855 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3856 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3858 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3859 MVT VT2, SDOperand Op1,
3861 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3862 SDOperand Ops[] = { Op1, Op2 };
3863 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3865 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3866 MVT VT2, SDOperand Op1,
3867 SDOperand Op2, SDOperand Op3) {
3868 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3869 SDOperand Ops[] = { Op1, Op2, Op3 };
3870 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3872 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3873 const SDOperand *Ops, unsigned NumOps) {
3874 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3875 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3877 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3878 SDOperand Op1, SDOperand Op2) {
3879 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3880 SDOperand Ops[] = { Op1, Op2 };
3881 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3883 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3884 SDOperand Op1, SDOperand Op2,
3886 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3887 SDOperand Ops[] = { Op1, Op2, Op3 };
3888 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3890 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3891 const SDOperand *Ops, unsigned NumOps) {
3892 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3893 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3895 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3896 MVT VT2, MVT VT3, MVT VT4,
3897 const SDOperand *Ops, unsigned NumOps) {
3898 std::vector<MVT> VTList;
3899 VTList.push_back(VT1);
3900 VTList.push_back(VT2);
3901 VTList.push_back(VT3);
3902 VTList.push_back(VT4);
3903 const MVT *VTs = getNodeValueTypes(VTList);
3904 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3906 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3907 std::vector<MVT> &ResultTys,
3908 const SDOperand *Ops, unsigned NumOps) {
3909 const MVT *VTs = getNodeValueTypes(ResultTys);
3910 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3914 /// getNodeIfExists - Get the specified node if it's already available, or
3915 /// else return NULL.
3916 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3917 const SDOperand *Ops, unsigned NumOps) {
3918 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3919 FoldingSetNodeID ID;
3920 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3922 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3929 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3930 /// This can cause recursive merging of nodes in the DAG.
3932 /// This version assumes From has a single result value.
3934 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3935 DAGUpdateListener *UpdateListener) {
3936 SDNode *From = FromN.Val;
3937 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3938 "Cannot replace with this method!");
3939 assert(From != To.Val && "Cannot replace uses of with self");
3941 while (!From->use_empty()) {
3942 SDNode::use_iterator UI = From->use_begin();
3943 SDNode *U = UI->getUser();
3945 // This node is about to morph, remove its old self from the CSE maps.
3946 RemoveNodeFromCSEMaps(U);
3948 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3949 I != E; ++I, ++operandNum)
3950 if (I->getVal() == From) {
3951 From->removeUser(operandNum, U);
3954 To.Val->addUser(operandNum, U);
3957 // Now that we have modified U, add it back to the CSE maps. If it already
3958 // exists there, recursively merge the results together.
3959 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3960 ReplaceAllUsesWith(U, Existing, UpdateListener);
3961 // U is now dead. Inform the listener if it exists and delete it.
3963 UpdateListener->NodeDeleted(U, Existing);
3964 DeleteNodeNotInCSEMaps(U);
3966 // If the node doesn't already exist, we updated it. Inform a listener if
3969 UpdateListener->NodeUpdated(U);
3974 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3975 /// This can cause recursive merging of nodes in the DAG.
3977 /// This version assumes From/To have matching types and numbers of result
3980 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3981 DAGUpdateListener *UpdateListener) {
3982 assert(From != To && "Cannot replace uses of with self");
3983 assert(From->getNumValues() == To->getNumValues() &&
3984 "Cannot use this version of ReplaceAllUsesWith!");
3985 if (From->getNumValues() == 1) // If possible, use the faster version.
3986 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3989 while (!From->use_empty()) {
3990 SDNode::use_iterator UI = From->use_begin();
3991 SDNode *U = UI->getUser();
3993 // This node is about to morph, remove its old self from the CSE maps.
3994 RemoveNodeFromCSEMaps(U);
3996 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3997 I != E; ++I, ++operandNum)
3998 if (I->getVal() == From) {
3999 From->removeUser(operandNum, U);
4001 To->addUser(operandNum, U);
4004 // Now that we have modified U, add it back to the CSE maps. If it already
4005 // exists there, recursively merge the results together.
4006 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4007 ReplaceAllUsesWith(U, Existing, UpdateListener);
4008 // U is now dead. Inform the listener if it exists and delete it.
4010 UpdateListener->NodeDeleted(U, Existing);
4011 DeleteNodeNotInCSEMaps(U);
4013 // If the node doesn't already exist, we updated it. Inform a listener if
4016 UpdateListener->NodeUpdated(U);
4021 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4022 /// This can cause recursive merging of nodes in the DAG.
4024 /// This version can replace From with any result values. To must match the
4025 /// number and types of values returned by From.
4026 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4027 const SDOperand *To,
4028 DAGUpdateListener *UpdateListener) {
4029 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4030 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
4032 while (!From->use_empty()) {
4033 SDNode::use_iterator UI = From->use_begin();
4034 SDNode *U = UI->getUser();
4036 // This node is about to morph, remove its old self from the CSE maps.
4037 RemoveNodeFromCSEMaps(U);
4039 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4040 I != E; ++I, ++operandNum)
4041 if (I->getVal() == From) {
4042 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4043 From->removeUser(operandNum, U);
4046 ToOp.Val->addUser(operandNum, U);
4049 // Now that we have modified U, add it back to the CSE maps. If it already
4050 // exists there, recursively merge the results together.
4051 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4052 ReplaceAllUsesWith(U, Existing, UpdateListener);
4053 // U is now dead. Inform the listener if it exists and delete it.
4055 UpdateListener->NodeDeleted(U, Existing);
4056 DeleteNodeNotInCSEMaps(U);
4058 // If the node doesn't already exist, we updated it. Inform a listener if
4061 UpdateListener->NodeUpdated(U);
4067 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4068 /// any deleted nodes from the set passed into its constructor and recursively
4069 /// notifies another update listener if specified.
4070 class ChainedSetUpdaterListener :
4071 public SelectionDAG::DAGUpdateListener {
4072 SmallSetVector<SDNode*, 16> &Set;
4073 SelectionDAG::DAGUpdateListener *Chain;
4075 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4076 SelectionDAG::DAGUpdateListener *chain)
4077 : Set(set), Chain(chain) {}
4079 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4081 if (Chain) Chain->NodeDeleted(N, E);
4083 virtual void NodeUpdated(SDNode *N) {
4084 if (Chain) Chain->NodeUpdated(N);
4089 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4090 /// uses of other values produced by From.Val alone. The Deleted vector is
4091 /// handled the same way as for ReplaceAllUsesWith.
4092 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4093 DAGUpdateListener *UpdateListener){
4094 assert(From != To && "Cannot replace a value with itself");
4096 // Handle the simple, trivial, case efficiently.
4097 if (From.Val->getNumValues() == 1) {
4098 ReplaceAllUsesWith(From, To, UpdateListener);
4102 if (From.use_empty()) return;
4104 // Get all of the users of From.Val. We want these in a nice,
4105 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4106 SmallSetVector<SDNode*, 16> Users;
4107 for (SDNode::use_iterator UI = From.Val->use_begin(),
4108 E = From.Val->use_end(); UI != E; ++UI) {
4109 SDNode *User = UI->getUser();
4113 // When one of the recursive merges deletes nodes from the graph, we need to
4114 // make sure that UpdateListener is notified *and* that the node is removed
4115 // from Users if present. CSUL does this.
4116 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4118 while (!Users.empty()) {
4119 // We know that this user uses some value of From. If it is the right
4120 // value, update it.
4121 SDNode *User = Users.back();
4124 // Scan for an operand that matches From.
4125 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4126 for (; Op != E; ++Op)
4127 if (*Op == From) break;
4129 // If there are no matches, the user must use some other result of From.
4130 if (Op == E) continue;
4132 // Okay, we know this user needs to be updated. Remove its old self
4133 // from the CSE maps.
4134 RemoveNodeFromCSEMaps(User);
4136 // Update all operands that match "From" in case there are multiple uses.
4137 for (; Op != E; ++Op) {
4139 From.Val->removeUser(Op-User->op_begin(), User);
4142 To.Val->addUser(Op-User->op_begin(), User);
4146 // Now that we have modified User, add it back to the CSE maps. If it
4147 // already exists there, recursively merge the results together.
4148 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4150 if (UpdateListener) UpdateListener->NodeUpdated(User);
4151 continue; // Continue on to next user.
4154 // If there was already an existing matching node, use ReplaceAllUsesWith
4155 // to replace the dead one with the existing one. This can cause
4156 // recursive merging of other unrelated nodes down the line. The merging
4157 // can cause deletion of nodes that used the old value. To handle this, we
4158 // use CSUL to remove them from the Users set.
4159 ReplaceAllUsesWith(User, Existing, &CSUL);
4161 // User is now dead. Notify a listener if present.
4162 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4163 DeleteNodeNotInCSEMaps(User);
4167 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4168 /// their allnodes order. It returns the maximum id.
4169 unsigned SelectionDAG::AssignNodeIds() {
4171 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4178 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4179 /// based on their topological order. It returns the maximum id and a vector
4180 /// of the SDNodes* in assigned order by reference.
4181 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4182 unsigned DAGSize = AllNodes.size();
4183 std::vector<unsigned> InDegree(DAGSize);
4184 std::vector<SDNode*> Sources;
4186 // Use a two pass approach to avoid using a std::map which is slow.
4188 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4191 unsigned Degree = N->use_size();
4192 InDegree[N->getNodeId()] = Degree;
4194 Sources.push_back(N);
4198 while (!Sources.empty()) {
4199 SDNode *N = Sources.back();
4201 TopOrder.push_back(N);
4202 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4203 SDNode *P = I->getVal();
4204 unsigned Degree = --InDegree[P->getNodeId()];
4206 Sources.push_back(P);
4210 // Second pass, assign the actual topological order as node ids.
4212 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4214 (*TI)->setNodeId(Id++);
4221 //===----------------------------------------------------------------------===//
4223 //===----------------------------------------------------------------------===//
4225 // Out-of-line virtual method to give class a home.
4226 void SDNode::ANCHOR() {}
4227 void UnarySDNode::ANCHOR() {}
4228 void BinarySDNode::ANCHOR() {}
4229 void TernarySDNode::ANCHOR() {}
4230 void HandleSDNode::ANCHOR() {}
4231 void ConstantSDNode::ANCHOR() {}
4232 void ConstantFPSDNode::ANCHOR() {}
4233 void GlobalAddressSDNode::ANCHOR() {}
4234 void FrameIndexSDNode::ANCHOR() {}
4235 void JumpTableSDNode::ANCHOR() {}
4236 void ConstantPoolSDNode::ANCHOR() {}
4237 void BasicBlockSDNode::ANCHOR() {}
4238 void SrcValueSDNode::ANCHOR() {}
4239 void MemOperandSDNode::ANCHOR() {}
4240 void RegisterSDNode::ANCHOR() {}
4241 void DbgStopPointSDNode::ANCHOR() {}
4242 void LabelSDNode::ANCHOR() {}
4243 void ExternalSymbolSDNode::ANCHOR() {}
4244 void CondCodeSDNode::ANCHOR() {}
4245 void ARG_FLAGSSDNode::ANCHOR() {}
4246 void VTSDNode::ANCHOR() {}
4247 void MemSDNode::ANCHOR() {}
4248 void LoadSDNode::ANCHOR() {}
4249 void StoreSDNode::ANCHOR() {}
4250 void AtomicSDNode::ANCHOR() {}
4252 HandleSDNode::~HandleSDNode() {
4253 SDVTList VTs = { 0, 0 };
4254 MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0); // Drops operand uses.
4257 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4259 : SDNode(isa<GlobalVariable>(GA) &&
4260 cast<GlobalVariable>(GA)->isThreadLocal() ?
4262 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4264 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4265 getSDVTList(VT)), Offset(o) {
4266 TheGlobal = const_cast<GlobalValue*>(GA);
4269 /// getMemOperand - Return a MachineMemOperand object describing the memory
4270 /// reference performed by this atomic.
4271 MachineMemOperand AtomicSDNode::getMemOperand() const {
4272 int Size = (getValueType(0).getSizeInBits() + 7) >> 3;
4273 int Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4274 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4276 // Check if the atomic references a frame index
4277 const FrameIndexSDNode *FI =
4278 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4279 if (!getSrcValue() && FI)
4280 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4281 FI->getIndex(), Size, getAlignment());
4283 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4284 Size, getAlignment());
4287 /// getMemOperand - Return a MachineMemOperand object describing the memory
4288 /// reference performed by this load or store.
4289 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4290 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4292 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4293 MachineMemOperand::MOStore;
4294 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4296 // Check if the load references a frame index, and does not have
4298 const FrameIndexSDNode *FI =
4299 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4300 if (!getSrcValue() && FI)
4301 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4302 FI->getIndex(), Size, getAlignment());
4304 return MachineMemOperand(getSrcValue(), Flags,
4305 getSrcValueOffset(), Size, getAlignment());
4308 /// Profile - Gather unique data for the node.
4310 void SDNode::Profile(FoldingSetNodeID &ID) {
4311 AddNodeIDNode(ID, this);
4314 /// getValueTypeList - Return a pointer to the specified value type.
4316 const MVT *SDNode::getValueTypeList(MVT VT) {
4317 if (VT.isExtended()) {
4318 static std::set<MVT, MVT::compareRawBits> EVTs;
4319 return &(*EVTs.insert(VT).first);
4321 static MVT VTs[MVT::LAST_VALUETYPE];
4322 VTs[VT.getSimpleVT()] = VT;
4323 return &VTs[VT.getSimpleVT()];
4327 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4328 /// indicated value. This method ignores uses of other values defined by this
4330 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4331 assert(Value < getNumValues() && "Bad value!");
4333 // If there is only one value, this is easy.
4334 if (getNumValues() == 1)
4335 return use_size() == NUses;
4336 if (use_size() < NUses) return false;
4338 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4340 SmallPtrSet<SDNode*, 32> UsersHandled;
4342 // TODO: Only iterate over uses of a given value of the node
4343 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4344 if (*UI == TheValue) {
4351 // Found exactly the right number of uses?
4356 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4357 /// value. This method ignores uses of other values defined by this operation.
4358 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4359 assert(Value < getNumValues() && "Bad value!");
4361 if (use_empty()) return false;
4363 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4365 SmallPtrSet<SDNode*, 32> UsersHandled;
4367 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4368 SDNode *User = UI->getUser();
4369 if (User->getNumOperands() == 1 ||
4370 UsersHandled.insert(User)) // First time we've seen this?
4371 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4372 if (User->getOperand(i) == TheValue) {
4381 /// isOnlyUseOf - Return true if this node is the only use of N.
4383 bool SDNode::isOnlyUseOf(SDNode *N) const {
4385 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4386 SDNode *User = I->getUser();
4396 /// isOperand - Return true if this node is an operand of N.
4398 bool SDOperand::isOperandOf(SDNode *N) const {
4399 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4400 if (*this == N->getOperand(i))
4405 bool SDNode::isOperandOf(SDNode *N) const {
4406 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4407 if (this == N->OperandList[i].getVal())
4412 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4413 /// be a chain) reaches the specified operand without crossing any
4414 /// side-effecting instructions. In practice, this looks through token
4415 /// factors and non-volatile loads. In order to remain efficient, this only
4416 /// looks a couple of nodes in, it does not do an exhaustive search.
4417 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4418 unsigned Depth) const {
4419 if (*this == Dest) return true;
4421 // Don't search too deeply, we just want to be able to see through
4422 // TokenFactor's etc.
4423 if (Depth == 0) return false;
4425 // If this is a token factor, all inputs to the TF happen in parallel. If any
4426 // of the operands of the TF reach dest, then we can do the xform.
4427 if (getOpcode() == ISD::TokenFactor) {
4428 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4429 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4434 // Loads don't have side effects, look through them.
4435 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4436 if (!Ld->isVolatile())
4437 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4443 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4444 SmallPtrSet<SDNode *, 32> &Visited) {
4445 if (found || !Visited.insert(N))
4448 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4449 SDNode *Op = N->getOperand(i).Val;
4454 findPredecessor(Op, P, found, Visited);
4458 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4459 /// is either an operand of N or it can be reached by recursively traversing
4460 /// up the operands.
4461 /// NOTE: this is an expensive method. Use it carefully.
4462 bool SDNode::isPredecessorOf(SDNode *N) const {
4463 SmallPtrSet<SDNode *, 32> Visited;
4465 findPredecessor(N, this, found, Visited);
4469 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4470 assert(Num < NumOperands && "Invalid child # of SDNode!");
4471 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4474 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4475 switch (getOpcode()) {
4477 if (getOpcode() < ISD::BUILTIN_OP_END)
4478 return "<<Unknown DAG Node>>";
4481 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4482 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4483 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4485 TargetLowering &TLI = G->getTargetLoweringInfo();
4487 TLI.getTargetNodeName(getOpcode());
4488 if (Name) return Name;
4491 return "<<Unknown Target Node>>";
4494 case ISD::PREFETCH: return "Prefetch";
4495 case ISD::MEMBARRIER: return "MemBarrier";
4496 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4497 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4498 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4499 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4500 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4501 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4502 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4503 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4504 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4505 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4506 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4507 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4508 case ISD::PCMARKER: return "PCMarker";
4509 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4510 case ISD::SRCVALUE: return "SrcValue";
4511 case ISD::MEMOPERAND: return "MemOperand";
4512 case ISD::EntryToken: return "EntryToken";
4513 case ISD::TokenFactor: return "TokenFactor";
4514 case ISD::AssertSext: return "AssertSext";
4515 case ISD::AssertZext: return "AssertZext";
4517 case ISD::BasicBlock: return "BasicBlock";
4518 case ISD::ARG_FLAGS: return "ArgFlags";
4519 case ISD::VALUETYPE: return "ValueType";
4520 case ISD::Register: return "Register";
4522 case ISD::Constant: return "Constant";
4523 case ISD::ConstantFP: return "ConstantFP";
4524 case ISD::GlobalAddress: return "GlobalAddress";
4525 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4526 case ISD::FrameIndex: return "FrameIndex";
4527 case ISD::JumpTable: return "JumpTable";
4528 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4529 case ISD::RETURNADDR: return "RETURNADDR";
4530 case ISD::FRAMEADDR: return "FRAMEADDR";
4531 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4532 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4533 case ISD::EHSELECTION: return "EHSELECTION";
4534 case ISD::EH_RETURN: return "EH_RETURN";
4535 case ISD::ConstantPool: return "ConstantPool";
4536 case ISD::ExternalSymbol: return "ExternalSymbol";
4537 case ISD::INTRINSIC_WO_CHAIN: {
4538 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4539 return Intrinsic::getName((Intrinsic::ID)IID);
4541 case ISD::INTRINSIC_VOID:
4542 case ISD::INTRINSIC_W_CHAIN: {
4543 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4544 return Intrinsic::getName((Intrinsic::ID)IID);
4547 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4548 case ISD::TargetConstant: return "TargetConstant";
4549 case ISD::TargetConstantFP:return "TargetConstantFP";
4550 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4551 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4552 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4553 case ISD::TargetJumpTable: return "TargetJumpTable";
4554 case ISD::TargetConstantPool: return "TargetConstantPool";
4555 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4557 case ISD::CopyToReg: return "CopyToReg";
4558 case ISD::CopyFromReg: return "CopyFromReg";
4559 case ISD::UNDEF: return "undef";
4560 case ISD::MERGE_VALUES: return "merge_values";
4561 case ISD::INLINEASM: return "inlineasm";
4562 case ISD::DBG_LABEL: return "dbg_label";
4563 case ISD::EH_LABEL: return "eh_label";
4564 case ISD::DECLARE: return "declare";
4565 case ISD::HANDLENODE: return "handlenode";
4566 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4567 case ISD::CALL: return "call";
4570 case ISD::FABS: return "fabs";
4571 case ISD::FNEG: return "fneg";
4572 case ISD::FSQRT: return "fsqrt";
4573 case ISD::FSIN: return "fsin";
4574 case ISD::FCOS: return "fcos";
4575 case ISD::FPOWI: return "fpowi";
4576 case ISD::FPOW: return "fpow";
4579 case ISD::ADD: return "add";
4580 case ISD::SUB: return "sub";
4581 case ISD::MUL: return "mul";
4582 case ISD::MULHU: return "mulhu";
4583 case ISD::MULHS: return "mulhs";
4584 case ISD::SDIV: return "sdiv";
4585 case ISD::UDIV: return "udiv";
4586 case ISD::SREM: return "srem";
4587 case ISD::UREM: return "urem";
4588 case ISD::SMUL_LOHI: return "smul_lohi";
4589 case ISD::UMUL_LOHI: return "umul_lohi";
4590 case ISD::SDIVREM: return "sdivrem";
4591 case ISD::UDIVREM: return "divrem";
4592 case ISD::AND: return "and";
4593 case ISD::OR: return "or";
4594 case ISD::XOR: return "xor";
4595 case ISD::SHL: return "shl";
4596 case ISD::SRA: return "sra";
4597 case ISD::SRL: return "srl";
4598 case ISD::ROTL: return "rotl";
4599 case ISD::ROTR: return "rotr";
4600 case ISD::FADD: return "fadd";
4601 case ISD::FSUB: return "fsub";
4602 case ISD::FMUL: return "fmul";
4603 case ISD::FDIV: return "fdiv";
4604 case ISD::FREM: return "frem";
4605 case ISD::FCOPYSIGN: return "fcopysign";
4606 case ISD::FGETSIGN: return "fgetsign";
4608 case ISD::SETCC: return "setcc";
4609 case ISD::VSETCC: return "vsetcc";
4610 case ISD::SELECT: return "select";
4611 case ISD::SELECT_CC: return "select_cc";
4612 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4613 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4614 case ISD::CONCAT_VECTORS: return "concat_vectors";
4615 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4616 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4617 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4618 case ISD::CARRY_FALSE: return "carry_false";
4619 case ISD::ADDC: return "addc";
4620 case ISD::ADDE: return "adde";
4621 case ISD::SUBC: return "subc";
4622 case ISD::SUBE: return "sube";
4623 case ISD::SHL_PARTS: return "shl_parts";
4624 case ISD::SRA_PARTS: return "sra_parts";
4625 case ISD::SRL_PARTS: return "srl_parts";
4627 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4628 case ISD::INSERT_SUBREG: return "insert_subreg";
4630 // Conversion operators.
4631 case ISD::SIGN_EXTEND: return "sign_extend";
4632 case ISD::ZERO_EXTEND: return "zero_extend";
4633 case ISD::ANY_EXTEND: return "any_extend";
4634 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4635 case ISD::TRUNCATE: return "truncate";
4636 case ISD::FP_ROUND: return "fp_round";
4637 case ISD::FLT_ROUNDS_: return "flt_rounds";
4638 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4639 case ISD::FP_EXTEND: return "fp_extend";
4641 case ISD::SINT_TO_FP: return "sint_to_fp";
4642 case ISD::UINT_TO_FP: return "uint_to_fp";
4643 case ISD::FP_TO_SINT: return "fp_to_sint";
4644 case ISD::FP_TO_UINT: return "fp_to_uint";
4645 case ISD::BIT_CONVERT: return "bit_convert";
4647 // Control flow instructions
4648 case ISD::BR: return "br";
4649 case ISD::BRIND: return "brind";
4650 case ISD::BR_JT: return "br_jt";
4651 case ISD::BRCOND: return "brcond";
4652 case ISD::BR_CC: return "br_cc";
4653 case ISD::RET: return "ret";
4654 case ISD::CALLSEQ_START: return "callseq_start";
4655 case ISD::CALLSEQ_END: return "callseq_end";
4658 case ISD::LOAD: return "load";
4659 case ISD::STORE: return "store";
4660 case ISD::VAARG: return "vaarg";
4661 case ISD::VACOPY: return "vacopy";
4662 case ISD::VAEND: return "vaend";
4663 case ISD::VASTART: return "vastart";
4664 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4665 case ISD::EXTRACT_ELEMENT: return "extract_element";
4666 case ISD::BUILD_PAIR: return "build_pair";
4667 case ISD::STACKSAVE: return "stacksave";
4668 case ISD::STACKRESTORE: return "stackrestore";
4669 case ISD::TRAP: return "trap";
4672 case ISD::BSWAP: return "bswap";
4673 case ISD::CTPOP: return "ctpop";
4674 case ISD::CTTZ: return "cttz";
4675 case ISD::CTLZ: return "ctlz";
4678 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4679 case ISD::DEBUG_LOC: return "debug_loc";
4682 case ISD::TRAMPOLINE: return "trampoline";
4685 switch (cast<CondCodeSDNode>(this)->get()) {
4686 default: assert(0 && "Unknown setcc condition!");
4687 case ISD::SETOEQ: return "setoeq";
4688 case ISD::SETOGT: return "setogt";
4689 case ISD::SETOGE: return "setoge";
4690 case ISD::SETOLT: return "setolt";
4691 case ISD::SETOLE: return "setole";
4692 case ISD::SETONE: return "setone";
4694 case ISD::SETO: return "seto";
4695 case ISD::SETUO: return "setuo";
4696 case ISD::SETUEQ: return "setue";
4697 case ISD::SETUGT: return "setugt";
4698 case ISD::SETUGE: return "setuge";
4699 case ISD::SETULT: return "setult";
4700 case ISD::SETULE: return "setule";
4701 case ISD::SETUNE: return "setune";
4703 case ISD::SETEQ: return "seteq";
4704 case ISD::SETGT: return "setgt";
4705 case ISD::SETGE: return "setge";
4706 case ISD::SETLT: return "setlt";
4707 case ISD::SETLE: return "setle";
4708 case ISD::SETNE: return "setne";
4713 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4722 return "<post-inc>";
4724 return "<post-dec>";
4728 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4729 std::string S = "< ";
4743 if (getByValAlign())
4744 S += "byval-align:" + utostr(getByValAlign()) + " ";
4746 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4748 S += "byval-size:" + utostr(getByValSize()) + " ";
4752 void SDNode::dump() const { dump(0); }
4753 void SDNode::dump(const SelectionDAG *G) const {
4754 cerr << (void*)this << ": ";
4756 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4758 if (getValueType(i) == MVT::Other)
4761 cerr << getValueType(i).getMVTString();
4763 cerr << " = " << getOperationName(G);
4766 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4767 if (i) cerr << ", ";
4768 cerr << (void*)getOperand(i).Val;
4769 if (unsigned RN = getOperand(i).ResNo)
4773 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4774 SDNode *Mask = getOperand(2).Val;
4776 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4778 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4781 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4786 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4787 cerr << "<" << CSDN->getValue() << ">";
4788 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4789 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4790 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4791 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4792 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4794 cerr << "<APFloat(";
4795 CSDN->getValueAPF().convertToAPInt().dump();
4798 } else if (const GlobalAddressSDNode *GADN =
4799 dyn_cast<GlobalAddressSDNode>(this)) {
4800 int offset = GADN->getOffset();
4802 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4804 cerr << " + " << offset;
4806 cerr << " " << offset;
4807 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4808 cerr << "<" << FIDN->getIndex() << ">";
4809 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4810 cerr << "<" << JTDN->getIndex() << ">";
4811 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4812 int offset = CP->getOffset();
4813 if (CP->isMachineConstantPoolEntry())
4814 cerr << "<" << *CP->getMachineCPVal() << ">";
4816 cerr << "<" << *CP->getConstVal() << ">";
4818 cerr << " + " << offset;
4820 cerr << " " << offset;
4821 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4823 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4825 cerr << LBB->getName() << " ";
4826 cerr << (const void*)BBDN->getBasicBlock() << ">";
4827 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4828 if (G && R->getReg() &&
4829 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4830 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4832 cerr << " #" << R->getReg();
4834 } else if (const ExternalSymbolSDNode *ES =
4835 dyn_cast<ExternalSymbolSDNode>(this)) {
4836 cerr << "'" << ES->getSymbol() << "'";
4837 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4839 cerr << "<" << M->getValue() << ">";
4842 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4843 if (M->MO.getValue())
4844 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4846 cerr << "<null:" << M->MO.getOffset() << ">";
4847 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4848 cerr << N->getArgFlags().getArgFlagsString();
4849 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4850 cerr << ":" << N->getVT().getMVTString();
4852 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4853 const Value *SrcValue = LD->getSrcValue();
4854 int SrcOffset = LD->getSrcValueOffset();
4860 cerr << ":" << SrcOffset << ">";
4863 switch (LD->getExtensionType()) {
4864 default: doExt = false; break;
4866 cerr << " <anyext ";
4876 cerr << LD->getMemoryVT().getMVTString() << ">";
4878 const char *AM = getIndexedModeName(LD->getAddressingMode());
4881 if (LD->isVolatile())
4882 cerr << " <volatile>";
4883 cerr << " alignment=" << LD->getAlignment();
4884 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4885 const Value *SrcValue = ST->getSrcValue();
4886 int SrcOffset = ST->getSrcValueOffset();
4892 cerr << ":" << SrcOffset << ">";
4894 if (ST->isTruncatingStore())
4896 << ST->getMemoryVT().getMVTString() << ">";
4898 const char *AM = getIndexedModeName(ST->getAddressingMode());
4901 if (ST->isVolatile())
4902 cerr << " <volatile>";
4903 cerr << " alignment=" << ST->getAlignment();
4904 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4905 const Value *SrcValue = AT->getSrcValue();
4906 int SrcOffset = AT->getSrcValueOffset();
4912 cerr << ":" << SrcOffset << ">";
4913 if (AT->isVolatile())
4914 cerr << " <volatile>";
4915 cerr << " alignment=" << AT->getAlignment();
4919 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4920 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4921 if (N->getOperand(i).Val->hasOneUse())
4922 DumpNodes(N->getOperand(i).Val, indent+2, G);
4924 cerr << "\n" << std::string(indent+2, ' ')
4925 << (void*)N->getOperand(i).Val << ": <multiple use>";
4928 cerr << "\n" << std::string(indent, ' ');
4932 void SelectionDAG::dump() const {
4933 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4934 std::vector<const SDNode*> Nodes;
4935 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4939 std::sort(Nodes.begin(), Nodes.end());
4941 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4942 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4943 DumpNodes(Nodes[i], 2, this);
4946 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4951 const Type *ConstantPoolSDNode::getType() const {
4952 if (isMachineConstantPoolEntry())
4953 return Val.MachineCPVal->getType();
4954 return Val.ConstVal->getType();