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());
399 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
401 case ISD::MEMOPERAND: {
402 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
403 ID.AddPointer(MO.getValue());
404 ID.AddInteger(MO.getFlags());
405 ID.AddInteger(MO.getOffset());
406 ID.AddInteger(MO.getSize());
407 ID.AddInteger(MO.getAlignment());
410 case ISD::FrameIndex:
411 case ISD::TargetFrameIndex:
412 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
415 case ISD::TargetJumpTable:
416 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
418 case ISD::ConstantPool:
419 case ISD::TargetConstantPool: {
420 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
421 ID.AddInteger(CP->getAlignment());
422 ID.AddInteger(CP->getOffset());
423 if (CP->isMachineConstantPoolEntry())
424 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
426 ID.AddPointer(CP->getConstVal());
430 LoadSDNode *LD = cast<LoadSDNode>(N);
431 ID.AddInteger(LD->getAddressingMode());
432 ID.AddInteger(LD->getExtensionType());
433 ID.AddInteger(LD->getMemoryVT().getRawBits());
434 ID.AddInteger(LD->getAlignment());
435 ID.AddInteger(LD->isVolatile());
439 StoreSDNode *ST = cast<StoreSDNode>(N);
440 ID.AddInteger(ST->getAddressingMode());
441 ID.AddInteger(ST->isTruncatingStore());
442 ID.AddInteger(ST->getMemoryVT().getRawBits());
443 ID.AddInteger(ST->getAlignment());
444 ID.AddInteger(ST->isVolatile());
447 case ISD::ATOMIC_CMP_SWAP:
448 case ISD::ATOMIC_LOAD_ADD:
449 case ISD::ATOMIC_SWAP:
450 case ISD::ATOMIC_LOAD_SUB:
451 case ISD::ATOMIC_LOAD_AND:
452 case ISD::ATOMIC_LOAD_OR:
453 case ISD::ATOMIC_LOAD_XOR:
454 case ISD::ATOMIC_LOAD_NAND:
455 case ISD::ATOMIC_LOAD_MIN:
456 case ISD::ATOMIC_LOAD_MAX:
457 case ISD::ATOMIC_LOAD_UMIN:
458 case ISD::ATOMIC_LOAD_UMAX: {
459 AtomicSDNode *AT = cast<AtomicSDNode>(N);
460 ID.AddInteger(AT->getAlignment());
461 ID.AddInteger(AT->isVolatile());
464 } // end switch (N->getOpcode())
467 //===----------------------------------------------------------------------===//
468 // SelectionDAG Class
469 //===----------------------------------------------------------------------===//
471 inline alist_traits<SDNode, LargestSDNode>::AllocatorType &
472 SelectionDAG::getAllocator() {
473 return AllNodes.getTraits().Allocator;
476 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
478 void SelectionDAG::RemoveDeadNodes() {
479 // Create a dummy node (which is not added to allnodes), that adds a reference
480 // to the root node, preventing it from being deleted.
481 HandleSDNode Dummy(getRoot());
483 SmallVector<SDNode*, 128> DeadNodes;
485 // Add all obviously-dead nodes to the DeadNodes worklist.
486 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
488 DeadNodes.push_back(I);
490 RemoveDeadNodes(DeadNodes);
492 // If the root changed (e.g. it was a dead load, update the root).
493 setRoot(Dummy.getValue());
496 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
497 /// given list, and any nodes that become unreachable as a result.
498 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
499 DAGUpdateListener *UpdateListener) {
501 // Process the worklist, deleting the nodes and adding their uses to the
503 while (!DeadNodes.empty()) {
504 SDNode *N = DeadNodes.back();
505 DeadNodes.pop_back();
508 UpdateListener->NodeDeleted(N, 0);
510 // Take the node out of the appropriate CSE map.
511 RemoveNodeFromCSEMaps(N);
513 // Next, brutally remove the operand list. This is safe to do, as there are
514 // no cycles in the graph.
515 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
516 SDNode *Operand = I->getVal();
517 Operand->removeUser(std::distance(N->op_begin(), I), N);
519 // Now that we removed this operand, see if there are no uses of it left.
520 if (Operand->use_empty())
521 DeadNodes.push_back(Operand);
523 if (N->OperandsNeedDelete) {
524 delete[] N->OperandList;
529 // Finally, remove N itself.
534 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
535 SmallVector<SDNode*, 16> DeadNodes;
536 DeadNodes.push_back(N);
537 RemoveDeadNodes(DeadNodes, UpdateListener);
540 void SelectionDAG::DeleteNode(SDNode *N) {
541 assert(N->use_empty() && "Cannot delete a node that is not dead!");
543 // First take this out of the appropriate CSE map.
544 RemoveNodeFromCSEMaps(N);
546 // Finally, remove uses due to operands of this node, remove from the
547 // AllNodes list, and delete the node.
548 DeleteNodeNotInCSEMaps(N);
551 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
553 // Drop all of the operands and decrement used nodes use counts.
554 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
555 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
556 if (N->OperandsNeedDelete) {
557 delete[] N->OperandList;
565 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
566 /// correspond to it. This is useful when we're about to delete or repurpose
567 /// the node. We don't want future request for structurally identical nodes
568 /// to return N anymore.
569 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
571 switch (N->getOpcode()) {
572 case ISD::HANDLENODE: return; // noop.
574 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
575 "Cond code doesn't exist!");
576 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
577 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
579 case ISD::ExternalSymbol:
580 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
582 case ISD::TargetExternalSymbol:
584 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
586 case ISD::VALUETYPE: {
587 MVT VT = cast<VTSDNode>(N)->getVT();
588 if (VT.isExtended()) {
589 Erased = ExtendedValueTypeNodes.erase(VT);
591 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
592 ValueTypeNodes[VT.getSimpleVT()] = 0;
597 // Remove it from the CSE Map.
598 Erased = CSEMap.RemoveNode(N);
602 // Verify that the node was actually in one of the CSE maps, unless it has a
603 // flag result (which cannot be CSE'd) or is one of the special cases that are
604 // not subject to CSE.
605 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
606 !N->isTargetOpcode() &&
607 N->getOpcode() != ISD::DBG_LABEL &&
608 N->getOpcode() != ISD::DBG_STOPPOINT &&
609 N->getOpcode() != ISD::EH_LABEL &&
610 N->getOpcode() != ISD::DECLARE) {
613 assert(0 && "Node is not in map!");
618 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
619 /// has been taken out and modified in some way. If the specified node already
620 /// exists in the CSE maps, do not modify the maps, but return the existing node
621 /// instead. If it doesn't exist, add it and return null.
623 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
624 assert(N->getNumOperands() && "This is a leaf node!");
626 if (N->getValueType(0) == MVT::Flag)
627 return 0; // Never CSE anything that produces a flag.
629 switch (N->getOpcode()) {
631 case ISD::HANDLENODE:
633 case ISD::DBG_STOPPOINT:
636 return 0; // Never add these nodes.
639 // Check that remaining values produced are not flags.
640 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
641 if (N->getValueType(i) == MVT::Flag)
642 return 0; // Never CSE anything that produces a flag.
644 SDNode *New = CSEMap.GetOrInsertNode(N);
645 if (New != N) return New; // Node already existed.
649 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
650 /// were replaced with those specified. If this node is never memoized,
651 /// return null, otherwise return a pointer to the slot it would take. If a
652 /// node already exists with these operands, the slot will be non-null.
653 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
655 if (N->getValueType(0) == MVT::Flag)
656 return 0; // Never CSE anything that produces a flag.
658 switch (N->getOpcode()) {
660 case ISD::HANDLENODE:
662 case ISD::DBG_STOPPOINT:
664 return 0; // Never add these nodes.
667 // Check that remaining values produced are not flags.
668 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
669 if (N->getValueType(i) == MVT::Flag)
670 return 0; // Never CSE anything that produces a flag.
672 SDOperand Ops[] = { Op };
674 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
675 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
678 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
679 /// were replaced with those specified. If this node is never memoized,
680 /// return null, otherwise return a pointer to the slot it would take. If a
681 /// node already exists with these operands, the slot will be non-null.
682 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
683 SDOperand Op1, SDOperand Op2,
685 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
687 // Check that remaining values produced are not flags.
688 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
689 if (N->getValueType(i) == MVT::Flag)
690 return 0; // Never CSE anything that produces a flag.
692 SDOperand Ops[] = { Op1, Op2 };
694 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
695 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
699 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
700 /// were replaced with those specified. If this node is never memoized,
701 /// return null, otherwise return a pointer to the slot it would take. If a
702 /// node already exists with these operands, the slot will be non-null.
703 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
704 const SDOperand *Ops,unsigned NumOps,
706 if (N->getValueType(0) == MVT::Flag)
707 return 0; // Never CSE anything that produces a flag.
709 switch (N->getOpcode()) {
711 case ISD::HANDLENODE:
713 case ISD::DBG_STOPPOINT:
716 return 0; // Never add these nodes.
719 // Check that remaining values produced are not flags.
720 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
721 if (N->getValueType(i) == MVT::Flag)
722 return 0; // Never CSE anything that produces a flag.
725 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
727 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
728 ID.AddInteger(LD->getAddressingMode());
729 ID.AddInteger(LD->getExtensionType());
730 ID.AddInteger(LD->getMemoryVT().getRawBits());
731 ID.AddInteger(LD->getAlignment());
732 ID.AddInteger(LD->isVolatile());
733 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
734 ID.AddInteger(ST->getAddressingMode());
735 ID.AddInteger(ST->isTruncatingStore());
736 ID.AddInteger(ST->getMemoryVT().getRawBits());
737 ID.AddInteger(ST->getAlignment());
738 ID.AddInteger(ST->isVolatile());
741 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
744 /// getMVTAlignment - Compute the default alignment value for the
747 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
748 const Type *Ty = VT == MVT::iPTR ?
749 PointerType::get(Type::Int8Ty, 0) :
752 return TLI.getTargetData()->getABITypeAlignment(Ty);
755 SelectionDAG::~SelectionDAG() {
756 while (!AllNodes.empty()) {
757 SDNode *N = AllNodes.begin();
758 N->SetNextInBucket(0);
759 if (N->OperandsNeedDelete) {
760 delete [] N->OperandList;
764 AllNodes.pop_front();
768 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
769 if (Op.getValueType() == VT) return Op;
770 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
772 return getNode(ISD::AND, Op.getValueType(), Op,
773 getConstant(Imm, Op.getValueType()));
776 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
777 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
778 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
781 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
782 assert(VT.isInteger() && "Cannot create FP integer constant!");
784 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
785 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
786 "APInt size does not match type size!");
788 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
790 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
794 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
796 return SDOperand(N, 0);
798 N = getAllocator().Allocate<ConstantSDNode>();
799 new (N) ConstantSDNode(isT, Val, EltVT);
800 CSEMap.InsertNode(N, IP);
801 AllNodes.push_back(N);
804 SDOperand Result(N, 0);
806 SmallVector<SDOperand, 8> Ops;
807 Ops.assign(VT.getVectorNumElements(), Result);
808 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
813 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
814 return getConstant(Val, TLI.getPointerTy(), isTarget);
818 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
819 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
822 VT.isVector() ? VT.getVectorElementType() : VT;
824 // Do the map lookup using the actual bit pattern for the floating point
825 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
826 // we don't have issues with SNANs.
827 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
829 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
833 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
835 return SDOperand(N, 0);
837 N = getAllocator().Allocate<ConstantFPSDNode>();
838 new (N) ConstantFPSDNode(isTarget, V, EltVT);
839 CSEMap.InsertNode(N, IP);
840 AllNodes.push_back(N);
843 SDOperand Result(N, 0);
845 SmallVector<SDOperand, 8> Ops;
846 Ops.assign(VT.getVectorNumElements(), Result);
847 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
852 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
854 VT.isVector() ? VT.getVectorElementType() : VT;
856 return getConstantFP(APFloat((float)Val), VT, isTarget);
858 return getConstantFP(APFloat(Val), VT, isTarget);
861 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
866 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
868 // If GV is an alias then use the aliasee for determining thread-localness.
869 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
870 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
873 if (GVar && GVar->isThreadLocal())
874 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
876 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
879 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
881 ID.AddInteger(Offset);
883 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
884 return SDOperand(E, 0);
885 SDNode *N = getAllocator().Allocate<GlobalAddressSDNode>();
886 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
887 CSEMap.InsertNode(N, IP);
888 AllNodes.push_back(N);
889 return SDOperand(N, 0);
892 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
893 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
895 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
898 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
899 return SDOperand(E, 0);
900 SDNode *N = getAllocator().Allocate<FrameIndexSDNode>();
901 new (N) FrameIndexSDNode(FI, VT, isTarget);
902 CSEMap.InsertNode(N, IP);
903 AllNodes.push_back(N);
904 return SDOperand(N, 0);
907 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
908 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
910 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
913 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
914 return SDOperand(E, 0);
915 SDNode *N = getAllocator().Allocate<JumpTableSDNode>();
916 new (N) JumpTableSDNode(JTI, VT, isTarget);
917 CSEMap.InsertNode(N, IP);
918 AllNodes.push_back(N);
919 return SDOperand(N, 0);
922 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
923 unsigned Alignment, int Offset,
925 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
927 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
928 ID.AddInteger(Alignment);
929 ID.AddInteger(Offset);
932 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
933 return SDOperand(E, 0);
934 SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
935 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
936 CSEMap.InsertNode(N, IP);
937 AllNodes.push_back(N);
938 return SDOperand(N, 0);
942 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
943 unsigned Alignment, int Offset,
945 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
947 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
948 ID.AddInteger(Alignment);
949 ID.AddInteger(Offset);
950 C->AddSelectionDAGCSEId(ID);
952 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
953 return SDOperand(E, 0);
954 SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
955 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
956 CSEMap.InsertNode(N, IP);
957 AllNodes.push_back(N);
958 return SDOperand(N, 0);
962 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
964 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
967 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
968 return SDOperand(E, 0);
969 SDNode *N = getAllocator().Allocate<BasicBlockSDNode>();
970 new (N) BasicBlockSDNode(MBB);
971 CSEMap.InsertNode(N, IP);
972 AllNodes.push_back(N);
973 return SDOperand(N, 0);
976 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
978 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
979 ID.AddInteger(Flags.getRawBits());
981 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
982 return SDOperand(E, 0);
983 SDNode *N = getAllocator().Allocate<ARG_FLAGSSDNode>();
984 new (N) ARG_FLAGSSDNode(Flags);
985 CSEMap.InsertNode(N, IP);
986 AllNodes.push_back(N);
987 return SDOperand(N, 0);
990 SDOperand SelectionDAG::getValueType(MVT VT) {
991 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
992 ValueTypeNodes.resize(VT.getSimpleVT()+1);
994 SDNode *&N = VT.isExtended() ?
995 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
997 if (N) return SDOperand(N, 0);
998 N = getAllocator().Allocate<VTSDNode>();
999 new (N) VTSDNode(VT);
1000 AllNodes.push_back(N);
1001 return SDOperand(N, 0);
1004 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1005 SDNode *&N = ExternalSymbols[Sym];
1006 if (N) return SDOperand(N, 0);
1007 N = getAllocator().Allocate<ExternalSymbolSDNode>();
1008 new (N) ExternalSymbolSDNode(false, Sym, VT);
1009 AllNodes.push_back(N);
1010 return SDOperand(N, 0);
1013 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1014 SDNode *&N = TargetExternalSymbols[Sym];
1015 if (N) return SDOperand(N, 0);
1016 N = getAllocator().Allocate<ExternalSymbolSDNode>();
1017 new (N) ExternalSymbolSDNode(true, Sym, VT);
1018 AllNodes.push_back(N);
1019 return SDOperand(N, 0);
1022 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
1023 if ((unsigned)Cond >= CondCodeNodes.size())
1024 CondCodeNodes.resize(Cond+1);
1026 if (CondCodeNodes[Cond] == 0) {
1027 CondCodeSDNode *N = getAllocator().Allocate<CondCodeSDNode>();
1028 new (N) CondCodeSDNode(Cond);
1029 CondCodeNodes[Cond] = N;
1030 AllNodes.push_back(N);
1032 return SDOperand(CondCodeNodes[Cond], 0);
1035 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1036 FoldingSetNodeID ID;
1037 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1038 ID.AddInteger(RegNo);
1040 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1041 return SDOperand(E, 0);
1042 SDNode *N = getAllocator().Allocate<RegisterSDNode>();
1043 new (N) RegisterSDNode(RegNo, VT);
1044 CSEMap.InsertNode(N, IP);
1045 AllNodes.push_back(N);
1046 return SDOperand(N, 0);
1049 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
1050 unsigned Line, unsigned Col,
1051 const CompileUnitDesc *CU) {
1052 SDNode *N = getAllocator().Allocate<DbgStopPointSDNode>();
1053 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1054 AllNodes.push_back(N);
1055 return SDOperand(N, 0);
1058 SDOperand SelectionDAG::getLabel(unsigned Opcode,
1061 FoldingSetNodeID ID;
1062 SDOperand Ops[] = { Root };
1063 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1064 ID.AddInteger(LabelID);
1066 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1067 return SDOperand(E, 0);
1068 SDNode *N = getAllocator().Allocate<LabelSDNode>();
1069 new (N) LabelSDNode(Opcode, Root, LabelID);
1070 CSEMap.InsertNode(N, IP);
1071 AllNodes.push_back(N);
1072 return SDOperand(N, 0);
1075 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1076 assert((!V || isa<PointerType>(V->getType())) &&
1077 "SrcValue is not a pointer?");
1079 FoldingSetNodeID ID;
1080 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1084 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1085 return SDOperand(E, 0);
1087 SDNode *N = getAllocator().Allocate<SrcValueSDNode>();
1088 new (N) SrcValueSDNode(V);
1089 CSEMap.InsertNode(N, IP);
1090 AllNodes.push_back(N);
1091 return SDOperand(N, 0);
1094 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1095 const Value *v = MO.getValue();
1096 assert((!v || isa<PointerType>(v->getType())) &&
1097 "SrcValue is not a pointer?");
1099 FoldingSetNodeID ID;
1100 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1102 ID.AddInteger(MO.getFlags());
1103 ID.AddInteger(MO.getOffset());
1104 ID.AddInteger(MO.getSize());
1105 ID.AddInteger(MO.getAlignment());
1108 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1109 return SDOperand(E, 0);
1111 SDNode *N = getAllocator().Allocate<MemOperandSDNode>();
1112 new (N) MemOperandSDNode(MO);
1113 CSEMap.InsertNode(N, IP);
1114 AllNodes.push_back(N);
1115 return SDOperand(N, 0);
1118 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1119 /// specified value type.
1120 SDOperand SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1121 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1122 unsigned ByteSize = VT.getSizeInBits()/8;
1123 const Type *Ty = VT.getTypeForMVT();
1124 unsigned StackAlign =
1125 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1127 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1128 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1131 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1132 SDOperand N2, ISD::CondCode Cond) {
1133 // These setcc operations always fold.
1137 case ISD::SETFALSE2: return getConstant(0, VT);
1139 case ISD::SETTRUE2: return getConstant(1, VT);
1151 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1155 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1156 const APInt &C2 = N2C->getAPIntValue();
1157 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1158 const APInt &C1 = N1C->getAPIntValue();
1161 default: assert(0 && "Unknown integer setcc!");
1162 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1163 case ISD::SETNE: return getConstant(C1 != C2, VT);
1164 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1165 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1166 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1167 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1168 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1169 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1170 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1171 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1175 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1176 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1177 // No compile time operations on this type yet.
1178 if (N1C->getValueType(0) == MVT::ppcf128)
1181 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1184 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1185 return getNode(ISD::UNDEF, VT);
1187 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1188 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1189 return getNode(ISD::UNDEF, VT);
1191 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1192 R==APFloat::cmpLessThan, VT);
1193 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1194 return getNode(ISD::UNDEF, VT);
1196 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1197 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1198 return getNode(ISD::UNDEF, VT);
1200 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1201 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1202 return getNode(ISD::UNDEF, VT);
1204 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1205 R==APFloat::cmpEqual, VT);
1206 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1207 return getNode(ISD::UNDEF, VT);
1209 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1210 R==APFloat::cmpEqual, VT);
1211 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1212 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1213 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1214 R==APFloat::cmpEqual, VT);
1215 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1216 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1217 R==APFloat::cmpLessThan, VT);
1218 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1219 R==APFloat::cmpUnordered, VT);
1220 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1221 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1224 // Ensure that the constant occurs on the RHS.
1225 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1229 // Could not fold it.
1233 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1234 /// use this predicate to simplify operations downstream.
1235 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1236 unsigned BitWidth = Op.getValueSizeInBits();
1237 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1240 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1241 /// this predicate to simplify operations downstream. Mask is known to be zero
1242 /// for bits that V cannot have.
1243 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1244 unsigned Depth) const {
1245 APInt KnownZero, KnownOne;
1246 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1247 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1248 return (KnownZero & Mask) == Mask;
1251 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1252 /// known to be either zero or one and return them in the KnownZero/KnownOne
1253 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1255 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1256 APInt &KnownZero, APInt &KnownOne,
1257 unsigned Depth) const {
1258 unsigned BitWidth = Mask.getBitWidth();
1259 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1260 "Mask size mismatches value type size!");
1262 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1263 if (Depth == 6 || Mask == 0)
1264 return; // Limit search depth.
1266 APInt KnownZero2, KnownOne2;
1268 switch (Op.getOpcode()) {
1270 // We know all of the bits for a constant!
1271 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1272 KnownZero = ~KnownOne & Mask;
1275 // If either the LHS or the RHS are Zero, the result is zero.
1276 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1277 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1278 KnownZero2, KnownOne2, Depth+1);
1279 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1280 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1282 // Output known-1 bits are only known if set in both the LHS & RHS.
1283 KnownOne &= KnownOne2;
1284 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1285 KnownZero |= KnownZero2;
1288 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1289 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1290 KnownZero2, KnownOne2, Depth+1);
1291 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1292 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1294 // Output known-0 bits are only known if clear in both the LHS & RHS.
1295 KnownZero &= KnownZero2;
1296 // Output known-1 are known to be set if set in either the LHS | RHS.
1297 KnownOne |= KnownOne2;
1300 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1301 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1302 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1303 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1305 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1306 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1307 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1308 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1309 KnownZero = KnownZeroOut;
1313 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1314 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1315 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1316 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1317 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1319 // If low bits are zero in either operand, output low known-0 bits.
1320 // Also compute a conserative estimate for high known-0 bits.
1321 // More trickiness is possible, but this is sufficient for the
1322 // interesting case of alignment computation.
1324 unsigned TrailZ = KnownZero.countTrailingOnes() +
1325 KnownZero2.countTrailingOnes();
1326 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1327 KnownZero2.countLeadingOnes(),
1328 BitWidth) - BitWidth;
1330 TrailZ = std::min(TrailZ, BitWidth);
1331 LeadZ = std::min(LeadZ, BitWidth);
1332 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1333 APInt::getHighBitsSet(BitWidth, LeadZ);
1338 // For the purposes of computing leading zeros we can conservatively
1339 // treat a udiv as a logical right shift by the power of 2 known to
1340 // be less than the denominator.
1341 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1342 ComputeMaskedBits(Op.getOperand(0),
1343 AllOnes, KnownZero2, KnownOne2, Depth+1);
1344 unsigned LeadZ = KnownZero2.countLeadingOnes();
1348 ComputeMaskedBits(Op.getOperand(1),
1349 AllOnes, KnownZero2, KnownOne2, Depth+1);
1350 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1351 if (RHSUnknownLeadingOnes != BitWidth)
1352 LeadZ = std::min(BitWidth,
1353 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1355 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1359 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1360 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1361 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1362 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1364 // Only known if known in both the LHS and RHS.
1365 KnownOne &= KnownOne2;
1366 KnownZero &= KnownZero2;
1368 case ISD::SELECT_CC:
1369 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1370 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1371 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1372 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1374 // Only known if known in both the LHS and RHS.
1375 KnownOne &= KnownOne2;
1376 KnownZero &= KnownZero2;
1379 // If we know the result of a setcc has the top bits zero, use this info.
1380 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1382 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1385 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1386 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1387 unsigned ShAmt = SA->getValue();
1389 // If the shift count is an invalid immediate, don't do anything.
1390 if (ShAmt >= BitWidth)
1393 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1394 KnownZero, KnownOne, Depth+1);
1395 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1396 KnownZero <<= ShAmt;
1398 // low bits known zero.
1399 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1403 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1404 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1405 unsigned ShAmt = SA->getValue();
1407 // If the shift count is an invalid immediate, don't do anything.
1408 if (ShAmt >= BitWidth)
1411 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1412 KnownZero, KnownOne, Depth+1);
1413 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1414 KnownZero = KnownZero.lshr(ShAmt);
1415 KnownOne = KnownOne.lshr(ShAmt);
1417 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1418 KnownZero |= HighBits; // High bits known zero.
1422 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1423 unsigned ShAmt = SA->getValue();
1425 // If the shift count is an invalid immediate, don't do anything.
1426 if (ShAmt >= BitWidth)
1429 APInt InDemandedMask = (Mask << ShAmt);
1430 // If any of the demanded bits are produced by the sign extension, we also
1431 // demand the input sign bit.
1432 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1433 if (HighBits.getBoolValue())
1434 InDemandedMask |= APInt::getSignBit(BitWidth);
1436 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1438 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1439 KnownZero = KnownZero.lshr(ShAmt);
1440 KnownOne = KnownOne.lshr(ShAmt);
1442 // Handle the sign bits.
1443 APInt SignBit = APInt::getSignBit(BitWidth);
1444 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1446 if (KnownZero.intersects(SignBit)) {
1447 KnownZero |= HighBits; // New bits are known zero.
1448 } else if (KnownOne.intersects(SignBit)) {
1449 KnownOne |= HighBits; // New bits are known one.
1453 case ISD::SIGN_EXTEND_INREG: {
1454 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1455 unsigned EBits = EVT.getSizeInBits();
1457 // Sign extension. Compute the demanded bits in the result that are not
1458 // present in the input.
1459 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1461 APInt InSignBit = APInt::getSignBit(EBits);
1462 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1464 // If the sign extended bits are demanded, we know that the sign
1466 InSignBit.zext(BitWidth);
1467 if (NewBits.getBoolValue())
1468 InputDemandedBits |= InSignBit;
1470 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1471 KnownZero, KnownOne, Depth+1);
1472 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1474 // If the sign bit of the input is known set or clear, then we know the
1475 // top bits of the result.
1476 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1477 KnownZero |= NewBits;
1478 KnownOne &= ~NewBits;
1479 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1480 KnownOne |= NewBits;
1481 KnownZero &= ~NewBits;
1482 } else { // Input sign bit unknown
1483 KnownZero &= ~NewBits;
1484 KnownOne &= ~NewBits;
1491 unsigned LowBits = Log2_32(BitWidth)+1;
1492 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1497 if (ISD::isZEXTLoad(Op.Val)) {
1498 LoadSDNode *LD = cast<LoadSDNode>(Op);
1499 MVT VT = LD->getMemoryVT();
1500 unsigned MemBits = VT.getSizeInBits();
1501 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1505 case ISD::ZERO_EXTEND: {
1506 MVT InVT = Op.getOperand(0).getValueType();
1507 unsigned InBits = InVT.getSizeInBits();
1508 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1509 APInt InMask = Mask;
1510 InMask.trunc(InBits);
1511 KnownZero.trunc(InBits);
1512 KnownOne.trunc(InBits);
1513 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1514 KnownZero.zext(BitWidth);
1515 KnownOne.zext(BitWidth);
1516 KnownZero |= NewBits;
1519 case ISD::SIGN_EXTEND: {
1520 MVT InVT = Op.getOperand(0).getValueType();
1521 unsigned InBits = InVT.getSizeInBits();
1522 APInt InSignBit = APInt::getSignBit(InBits);
1523 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1524 APInt InMask = Mask;
1525 InMask.trunc(InBits);
1527 // If any of the sign extended bits are demanded, we know that the sign
1528 // bit is demanded. Temporarily set this bit in the mask for our callee.
1529 if (NewBits.getBoolValue())
1530 InMask |= InSignBit;
1532 KnownZero.trunc(InBits);
1533 KnownOne.trunc(InBits);
1534 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1536 // Note if the sign bit is known to be zero or one.
1537 bool SignBitKnownZero = KnownZero.isNegative();
1538 bool SignBitKnownOne = KnownOne.isNegative();
1539 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1540 "Sign bit can't be known to be both zero and one!");
1542 // If the sign bit wasn't actually demanded by our caller, we don't
1543 // want it set in the KnownZero and KnownOne result values. Reset the
1544 // mask and reapply it to the result values.
1546 InMask.trunc(InBits);
1547 KnownZero &= InMask;
1550 KnownZero.zext(BitWidth);
1551 KnownOne.zext(BitWidth);
1553 // If the sign bit is known zero or one, the top bits match.
1554 if (SignBitKnownZero)
1555 KnownZero |= NewBits;
1556 else if (SignBitKnownOne)
1557 KnownOne |= NewBits;
1560 case ISD::ANY_EXTEND: {
1561 MVT InVT = Op.getOperand(0).getValueType();
1562 unsigned InBits = InVT.getSizeInBits();
1563 APInt InMask = Mask;
1564 InMask.trunc(InBits);
1565 KnownZero.trunc(InBits);
1566 KnownOne.trunc(InBits);
1567 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1568 KnownZero.zext(BitWidth);
1569 KnownOne.zext(BitWidth);
1572 case ISD::TRUNCATE: {
1573 MVT InVT = Op.getOperand(0).getValueType();
1574 unsigned InBits = InVT.getSizeInBits();
1575 APInt InMask = Mask;
1576 InMask.zext(InBits);
1577 KnownZero.zext(InBits);
1578 KnownOne.zext(InBits);
1579 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1580 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1581 KnownZero.trunc(BitWidth);
1582 KnownOne.trunc(BitWidth);
1585 case ISD::AssertZext: {
1586 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1587 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1588 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1590 KnownZero |= (~InMask) & Mask;
1594 // All bits are zero except the low bit.
1595 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1599 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1600 // We know that the top bits of C-X are clear if X contains less bits
1601 // than C (i.e. no wrap-around can happen). For example, 20-X is
1602 // positive if we can prove that X is >= 0 and < 16.
1603 if (CLHS->getAPIntValue().isNonNegative()) {
1604 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1605 // NLZ can't be BitWidth with no sign bit
1606 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1607 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1610 // If all of the MaskV bits are known to be zero, then we know the
1611 // output top bits are zero, because we now know that the output is
1613 if ((KnownZero2 & MaskV) == MaskV) {
1614 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1615 // Top bits known zero.
1616 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1623 // Output known-0 bits are known if clear or set in both the low clear bits
1624 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1625 // low 3 bits clear.
1626 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1627 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1628 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1629 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1631 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1632 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1633 KnownZeroOut = std::min(KnownZeroOut,
1634 KnownZero2.countTrailingOnes());
1636 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1640 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1641 const APInt &RA = Rem->getAPIntValue();
1642 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1643 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1644 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1645 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1647 // The sign of a remainder is equal to the sign of the first
1648 // operand (zero being positive).
1649 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1650 KnownZero2 |= ~LowBits;
1651 else if (KnownOne2[BitWidth-1])
1652 KnownOne2 |= ~LowBits;
1654 KnownZero |= KnownZero2 & Mask;
1655 KnownOne |= KnownOne2 & Mask;
1657 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1662 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1663 const APInt &RA = Rem->getAPIntValue();
1664 if (RA.isPowerOf2()) {
1665 APInt LowBits = (RA - 1);
1666 APInt Mask2 = LowBits & Mask;
1667 KnownZero |= ~LowBits & Mask;
1668 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1669 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1674 // Since the result is less than or equal to either operand, any leading
1675 // zero bits in either operand must also exist in the result.
1676 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1677 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1679 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1682 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1683 KnownZero2.countLeadingOnes());
1685 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1689 // Allow the target to implement this method for its nodes.
1690 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1691 case ISD::INTRINSIC_WO_CHAIN:
1692 case ISD::INTRINSIC_W_CHAIN:
1693 case ISD::INTRINSIC_VOID:
1694 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1700 /// ComputeNumSignBits - Return the number of times the sign bit of the
1701 /// register is replicated into the other bits. We know that at least 1 bit
1702 /// is always equal to the sign bit (itself), but other cases can give us
1703 /// information. For example, immediately after an "SRA X, 2", we know that
1704 /// the top 3 bits are all equal to each other, so we return 3.
1705 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1706 MVT VT = Op.getValueType();
1707 assert(VT.isInteger() && "Invalid VT!");
1708 unsigned VTBits = VT.getSizeInBits();
1710 unsigned FirstAnswer = 1;
1713 return 1; // Limit search depth.
1715 switch (Op.getOpcode()) {
1717 case ISD::AssertSext:
1718 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1719 return VTBits-Tmp+1;
1720 case ISD::AssertZext:
1721 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1724 case ISD::Constant: {
1725 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1726 // If negative, return # leading ones.
1727 if (Val.isNegative())
1728 return Val.countLeadingOnes();
1730 // Return # leading zeros.
1731 return Val.countLeadingZeros();
1734 case ISD::SIGN_EXTEND:
1735 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1736 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1738 case ISD::SIGN_EXTEND_INREG:
1739 // Max of the input and what this extends.
1740 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1743 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1744 return std::max(Tmp, Tmp2);
1747 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1748 // SRA X, C -> adds C sign bits.
1749 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1750 Tmp += C->getValue();
1751 if (Tmp > VTBits) Tmp = VTBits;
1755 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1756 // shl destroys sign bits.
1757 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1758 if (C->getValue() >= VTBits || // Bad shift.
1759 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1760 return Tmp - C->getValue();
1765 case ISD::XOR: // NOT is handled here.
1766 // Logical binary ops preserve the number of sign bits at the worst.
1767 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1769 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1770 FirstAnswer = std::min(Tmp, Tmp2);
1771 // We computed what we know about the sign bits as our first
1772 // answer. Now proceed to the generic code that uses
1773 // ComputeMaskedBits, and pick whichever answer is better.
1778 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1779 if (Tmp == 1) return 1; // Early out.
1780 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1781 return std::min(Tmp, Tmp2);
1784 // If setcc returns 0/-1, all bits are sign bits.
1785 if (TLI.getSetCCResultContents() ==
1786 TargetLowering::ZeroOrNegativeOneSetCCResult)
1791 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1792 unsigned RotAmt = C->getValue() & (VTBits-1);
1794 // Handle rotate right by N like a rotate left by 32-N.
1795 if (Op.getOpcode() == ISD::ROTR)
1796 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1798 // If we aren't rotating out all of the known-in sign bits, return the
1799 // number that are left. This handles rotl(sext(x), 1) for example.
1800 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1801 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1805 // Add can have at most one carry bit. Thus we know that the output
1806 // is, at worst, one more bit than the inputs.
1807 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1808 if (Tmp == 1) return 1; // Early out.
1810 // Special case decrementing a value (ADD X, -1):
1811 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1812 if (CRHS->isAllOnesValue()) {
1813 APInt KnownZero, KnownOne;
1814 APInt Mask = APInt::getAllOnesValue(VTBits);
1815 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1817 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1819 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1822 // If we are subtracting one from a positive number, there is no carry
1823 // out of the result.
1824 if (KnownZero.isNegative())
1828 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1829 if (Tmp2 == 1) return 1;
1830 return std::min(Tmp, Tmp2)-1;
1834 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1835 if (Tmp2 == 1) return 1;
1838 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1839 if (CLHS->isNullValue()) {
1840 APInt KnownZero, KnownOne;
1841 APInt Mask = APInt::getAllOnesValue(VTBits);
1842 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1843 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1845 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1848 // If the input is known to be positive (the sign bit is known clear),
1849 // the output of the NEG has the same number of sign bits as the input.
1850 if (KnownZero.isNegative())
1853 // Otherwise, we treat this like a SUB.
1856 // Sub can have at most one carry bit. Thus we know that the output
1857 // is, at worst, one more bit than the inputs.
1858 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1859 if (Tmp == 1) return 1; // Early out.
1860 return std::min(Tmp, Tmp2)-1;
1863 // FIXME: it's tricky to do anything useful for this, but it is an important
1864 // case for targets like X86.
1868 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1869 if (Op.getOpcode() == ISD::LOAD) {
1870 LoadSDNode *LD = cast<LoadSDNode>(Op);
1871 unsigned ExtType = LD->getExtensionType();
1874 case ISD::SEXTLOAD: // '17' bits known
1875 Tmp = LD->getMemoryVT().getSizeInBits();
1876 return VTBits-Tmp+1;
1877 case ISD::ZEXTLOAD: // '16' bits known
1878 Tmp = LD->getMemoryVT().getSizeInBits();
1883 // Allow the target to implement this method for its nodes.
1884 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1885 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1886 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1887 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1888 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1889 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1892 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1893 // use this information.
1894 APInt KnownZero, KnownOne;
1895 APInt Mask = APInt::getAllOnesValue(VTBits);
1896 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1898 if (KnownZero.isNegative()) { // sign bit is 0
1900 } else if (KnownOne.isNegative()) { // sign bit is 1;
1907 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1908 // the number of identical bits in the top of the input value.
1910 Mask <<= Mask.getBitWidth()-VTBits;
1911 // Return # leading zeros. We use 'min' here in case Val was zero before
1912 // shifting. We don't want to return '64' as for an i32 "0".
1913 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1917 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1918 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1919 if (!GA) return false;
1920 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1921 if (!GV) return false;
1922 MachineModuleInfo *MMI = getMachineModuleInfo();
1923 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1927 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1928 /// element of the result of the vector shuffle.
1929 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1930 MVT VT = N->getValueType(0);
1931 SDOperand PermMask = N->getOperand(2);
1932 SDOperand Idx = PermMask.getOperand(i);
1933 if (Idx.getOpcode() == ISD::UNDEF)
1934 return getNode(ISD::UNDEF, VT.getVectorElementType());
1935 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1936 unsigned NumElems = PermMask.getNumOperands();
1937 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1940 if (V.getOpcode() == ISD::BIT_CONVERT) {
1941 V = V.getOperand(0);
1942 if (V.getValueType().getVectorNumElements() != NumElems)
1945 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1946 return (Index == 0) ? V.getOperand(0)
1947 : getNode(ISD::UNDEF, VT.getVectorElementType());
1948 if (V.getOpcode() == ISD::BUILD_VECTOR)
1949 return V.getOperand(Index);
1950 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1951 return getShuffleScalarElt(V.Val, Index);
1956 /// getNode - Gets or creates the specified node.
1958 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1959 FoldingSetNodeID ID;
1960 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1962 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1963 return SDOperand(E, 0);
1964 SDNode *N = getAllocator().Allocate<SDNode>();
1965 new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
1966 CSEMap.InsertNode(N, IP);
1968 AllNodes.push_back(N);
1969 return SDOperand(N, 0);
1972 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1973 // Constant fold unary operations with an integer constant operand.
1974 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1975 const APInt &Val = C->getAPIntValue();
1976 unsigned BitWidth = VT.getSizeInBits();
1979 case ISD::SIGN_EXTEND:
1980 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1981 case ISD::ANY_EXTEND:
1982 case ISD::ZERO_EXTEND:
1984 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1985 case ISD::UINT_TO_FP:
1986 case ISD::SINT_TO_FP: {
1987 const uint64_t zero[] = {0, 0};
1988 // No compile time operations on this type.
1989 if (VT==MVT::ppcf128)
1991 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1992 (void)apf.convertFromAPInt(Val,
1993 Opcode==ISD::SINT_TO_FP,
1994 APFloat::rmNearestTiesToEven);
1995 return getConstantFP(apf, VT);
1997 case ISD::BIT_CONVERT:
1998 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1999 return getConstantFP(Val.bitsToFloat(), VT);
2000 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2001 return getConstantFP(Val.bitsToDouble(), VT);
2004 return getConstant(Val.byteSwap(), VT);
2006 return getConstant(Val.countPopulation(), VT);
2008 return getConstant(Val.countLeadingZeros(), VT);
2010 return getConstant(Val.countTrailingZeros(), VT);
2014 // Constant fold unary operations with a floating point constant operand.
2015 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
2016 APFloat V = C->getValueAPF(); // make copy
2017 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2021 return getConstantFP(V, VT);
2024 return getConstantFP(V, VT);
2026 case ISD::FP_EXTEND:
2027 // This can return overflow, underflow, or inexact; we don't care.
2028 // FIXME need to be more flexible about rounding mode.
2029 (void)V.convert(*MVTToAPFloatSemantics(VT),
2030 APFloat::rmNearestTiesToEven);
2031 return getConstantFP(V, VT);
2032 case ISD::FP_TO_SINT:
2033 case ISD::FP_TO_UINT: {
2035 assert(integerPartWidth >= 64);
2036 // FIXME need to be more flexible about rounding mode.
2037 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2038 Opcode==ISD::FP_TO_SINT,
2039 APFloat::rmTowardZero);
2040 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2042 return getConstant(x, VT);
2044 case ISD::BIT_CONVERT:
2045 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2046 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2047 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2048 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2054 unsigned OpOpcode = Operand.Val->getOpcode();
2056 case ISD::TokenFactor:
2057 return Operand; // Factor of one node? No need.
2058 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2059 case ISD::FP_EXTEND:
2060 assert(VT.isFloatingPoint() &&
2061 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2062 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2063 if (Operand.getOpcode() == ISD::UNDEF)
2064 return getNode(ISD::UNDEF, VT);
2066 case ISD::SIGN_EXTEND:
2067 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2068 "Invalid SIGN_EXTEND!");
2069 if (Operand.getValueType() == VT) return Operand; // noop extension
2070 assert(Operand.getValueType().bitsLT(VT)
2071 && "Invalid sext node, dst < src!");
2072 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2073 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2075 case ISD::ZERO_EXTEND:
2076 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2077 "Invalid ZERO_EXTEND!");
2078 if (Operand.getValueType() == VT) return Operand; // noop extension
2079 assert(Operand.getValueType().bitsLT(VT)
2080 && "Invalid zext node, dst < src!");
2081 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2082 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2084 case ISD::ANY_EXTEND:
2085 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2086 "Invalid ANY_EXTEND!");
2087 if (Operand.getValueType() == VT) return Operand; // noop extension
2088 assert(Operand.getValueType().bitsLT(VT)
2089 && "Invalid anyext node, dst < src!");
2090 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2091 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2092 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2095 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2096 "Invalid TRUNCATE!");
2097 if (Operand.getValueType() == VT) return Operand; // noop truncate
2098 assert(Operand.getValueType().bitsGT(VT)
2099 && "Invalid truncate node, src < dst!");
2100 if (OpOpcode == ISD::TRUNCATE)
2101 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2102 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2103 OpOpcode == ISD::ANY_EXTEND) {
2104 // If the source is smaller than the dest, we still need an extend.
2105 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2106 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2107 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2108 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2110 return Operand.Val->getOperand(0);
2113 case ISD::BIT_CONVERT:
2114 // Basic sanity checking.
2115 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2116 && "Cannot BIT_CONVERT between types of different sizes!");
2117 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2118 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2119 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2120 if (OpOpcode == ISD::UNDEF)
2121 return getNode(ISD::UNDEF, VT);
2123 case ISD::SCALAR_TO_VECTOR:
2124 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2125 VT.getVectorElementType() == Operand.getValueType() &&
2126 "Illegal SCALAR_TO_VECTOR node!");
2127 if (OpOpcode == ISD::UNDEF)
2128 return getNode(ISD::UNDEF, VT);
2129 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2130 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2131 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2132 Operand.getConstantOperandVal(1) == 0 &&
2133 Operand.getOperand(0).getValueType() == VT)
2134 return Operand.getOperand(0);
2137 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2138 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2139 Operand.Val->getOperand(0));
2140 if (OpOpcode == ISD::FNEG) // --X -> X
2141 return Operand.Val->getOperand(0);
2144 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2145 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2150 SDVTList VTs = getVTList(VT);
2151 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2152 FoldingSetNodeID ID;
2153 SDOperand Ops[1] = { Operand };
2154 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2156 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2157 return SDOperand(E, 0);
2158 N = getAllocator().Allocate<UnarySDNode>();
2159 new (N) UnarySDNode(Opcode, VTs, Operand);
2160 CSEMap.InsertNode(N, IP);
2162 N = getAllocator().Allocate<UnarySDNode>();
2163 new (N) UnarySDNode(Opcode, VTs, Operand);
2165 AllNodes.push_back(N);
2166 return SDOperand(N, 0);
2171 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2172 SDOperand N1, SDOperand N2) {
2173 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2174 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2177 case ISD::TokenFactor:
2178 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2179 N2.getValueType() == MVT::Other && "Invalid token factor!");
2180 // Fold trivial token factors.
2181 if (N1.getOpcode() == ISD::EntryToken) return N2;
2182 if (N2.getOpcode() == ISD::EntryToken) return N1;
2185 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2186 N1.getValueType() == VT && "Binary operator types must match!");
2187 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2188 // worth handling here.
2189 if (N2C && N2C->isNullValue())
2191 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2198 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2199 N1.getValueType() == VT && "Binary operator types must match!");
2200 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2201 // it's worth handling here.
2202 if (N2C && N2C->isNullValue())
2209 assert(VT.isInteger() && "This operator does not apply to FP types!");
2219 assert(N1.getValueType() == N2.getValueType() &&
2220 N1.getValueType() == VT && "Binary operator types must match!");
2222 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2223 assert(N1.getValueType() == VT &&
2224 N1.getValueType().isFloatingPoint() &&
2225 N2.getValueType().isFloatingPoint() &&
2226 "Invalid FCOPYSIGN!");
2233 assert(VT == N1.getValueType() &&
2234 "Shift operators return type must be the same as their first arg");
2235 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2236 "Shifts only work on integers");
2238 // Always fold shifts of i1 values so the code generator doesn't need to
2239 // handle them. Since we know the size of the shift has to be less than the
2240 // size of the value, the shift/rotate count is guaranteed to be zero.
2244 case ISD::FP_ROUND_INREG: {
2245 MVT EVT = cast<VTSDNode>(N2)->getVT();
2246 assert(VT == N1.getValueType() && "Not an inreg round!");
2247 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2248 "Cannot FP_ROUND_INREG integer types");
2249 assert(EVT.bitsLE(VT) && "Not rounding down!");
2250 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2254 assert(VT.isFloatingPoint() &&
2255 N1.getValueType().isFloatingPoint() &&
2256 VT.bitsLE(N1.getValueType()) &&
2257 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2258 if (N1.getValueType() == VT) return N1; // noop conversion.
2260 case ISD::AssertSext:
2261 case ISD::AssertZext: {
2262 MVT EVT = cast<VTSDNode>(N2)->getVT();
2263 assert(VT == N1.getValueType() && "Not an inreg extend!");
2264 assert(VT.isInteger() && EVT.isInteger() &&
2265 "Cannot *_EXTEND_INREG FP types");
2266 assert(EVT.bitsLE(VT) && "Not extending!");
2267 if (VT == EVT) return N1; // noop assertion.
2270 case ISD::SIGN_EXTEND_INREG: {
2271 MVT EVT = cast<VTSDNode>(N2)->getVT();
2272 assert(VT == N1.getValueType() && "Not an inreg extend!");
2273 assert(VT.isInteger() && EVT.isInteger() &&
2274 "Cannot *_EXTEND_INREG FP types");
2275 assert(EVT.bitsLE(VT) && "Not extending!");
2276 if (EVT == VT) return N1; // Not actually extending
2279 APInt Val = N1C->getAPIntValue();
2280 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2281 Val <<= Val.getBitWidth()-FromBits;
2282 Val = Val.ashr(Val.getBitWidth()-FromBits);
2283 return getConstant(Val, VT);
2287 case ISD::EXTRACT_VECTOR_ELT:
2288 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2290 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2291 if (N1.getOpcode() == ISD::UNDEF)
2292 return getNode(ISD::UNDEF, VT);
2294 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2295 // expanding copies of large vectors from registers.
2296 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2297 N1.getNumOperands() > 0) {
2299 N1.getOperand(0).getValueType().getVectorNumElements();
2300 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2301 N1.getOperand(N2C->getValue() / Factor),
2302 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2305 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2306 // expanding large vector constants.
2307 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2308 return N1.getOperand(N2C->getValue());
2310 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2311 // operations are lowered to scalars.
2312 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2313 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2315 return N1.getOperand(1);
2317 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2320 case ISD::EXTRACT_ELEMENT:
2321 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2322 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2323 (N1.getValueType().isInteger() == VT.isInteger()) &&
2324 "Wrong types for EXTRACT_ELEMENT!");
2326 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2327 // 64-bit integers into 32-bit parts. Instead of building the extract of
2328 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2329 if (N1.getOpcode() == ISD::BUILD_PAIR)
2330 return N1.getOperand(N2C->getValue());
2332 // EXTRACT_ELEMENT of a constant int is also very common.
2333 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2334 unsigned ElementSize = VT.getSizeInBits();
2335 unsigned Shift = ElementSize * N2C->getValue();
2336 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2337 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2340 case ISD::EXTRACT_SUBVECTOR:
2341 if (N1.getValueType() == VT) // Trivial extraction.
2348 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2350 case ISD::ADD: return getConstant(C1 + C2, VT);
2351 case ISD::SUB: return getConstant(C1 - C2, VT);
2352 case ISD::MUL: return getConstant(C1 * C2, VT);
2354 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2357 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2360 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2363 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2365 case ISD::AND : return getConstant(C1 & C2, VT);
2366 case ISD::OR : return getConstant(C1 | C2, VT);
2367 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2368 case ISD::SHL : return getConstant(C1 << C2, VT);
2369 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2370 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2371 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2372 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2375 } else { // Cannonicalize constant to RHS if commutative
2376 if (isCommutativeBinOp(Opcode)) {
2377 std::swap(N1C, N2C);
2383 // Constant fold FP operations.
2384 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2385 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2387 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2388 // Cannonicalize constant to RHS if commutative
2389 std::swap(N1CFP, N2CFP);
2391 } else if (N2CFP && VT != MVT::ppcf128) {
2392 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2393 APFloat::opStatus s;
2396 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2397 if (s != APFloat::opInvalidOp)
2398 return getConstantFP(V1, VT);
2401 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2402 if (s!=APFloat::opInvalidOp)
2403 return getConstantFP(V1, VT);
2406 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2407 if (s!=APFloat::opInvalidOp)
2408 return getConstantFP(V1, VT);
2411 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2412 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2413 return getConstantFP(V1, VT);
2416 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2417 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2418 return getConstantFP(V1, VT);
2420 case ISD::FCOPYSIGN:
2422 return getConstantFP(V1, VT);
2428 // Canonicalize an UNDEF to the RHS, even over a constant.
2429 if (N1.getOpcode() == ISD::UNDEF) {
2430 if (isCommutativeBinOp(Opcode)) {
2434 case ISD::FP_ROUND_INREG:
2435 case ISD::SIGN_EXTEND_INREG:
2441 return N1; // fold op(undef, arg2) -> undef
2449 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2450 // For vectors, we can't easily build an all zero vector, just return
2457 // Fold a bunch of operators when the RHS is undef.
2458 if (N2.getOpcode() == ISD::UNDEF) {
2461 if (N1.getOpcode() == ISD::UNDEF)
2462 // Handle undef ^ undef -> 0 special case. This is a common
2464 return getConstant(0, VT);
2479 return N2; // fold op(arg1, undef) -> undef
2485 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2486 // For vectors, we can't easily build an all zero vector, just return
2491 return getConstant(VT.getIntegerVTBitMask(), VT);
2492 // For vectors, we can't easily build an all one vector, just return
2500 // Memoize this node if possible.
2502 SDVTList VTs = getVTList(VT);
2503 if (VT != MVT::Flag) {
2504 SDOperand Ops[] = { N1, N2 };
2505 FoldingSetNodeID ID;
2506 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2508 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2509 return SDOperand(E, 0);
2510 N = getAllocator().Allocate<BinarySDNode>();
2511 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2512 CSEMap.InsertNode(N, IP);
2514 N = getAllocator().Allocate<BinarySDNode>();
2515 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2518 AllNodes.push_back(N);
2519 return SDOperand(N, 0);
2522 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2523 SDOperand N1, SDOperand N2, SDOperand N3) {
2524 // Perform various simplifications.
2525 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2526 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2529 // Use FoldSetCC to simplify SETCC's.
2530 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2531 if (Simp.Val) return Simp;
2536 if (N1C->getValue())
2537 return N2; // select true, X, Y -> X
2539 return N3; // select false, X, Y -> Y
2542 if (N2 == N3) return N2; // select C, X, X -> X
2546 if (N2C->getValue()) // Unconditional branch
2547 return getNode(ISD::BR, MVT::Other, N1, N3);
2549 return N1; // Never-taken branch
2552 case ISD::VECTOR_SHUFFLE:
2553 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2554 VT.isVector() && N3.getValueType().isVector() &&
2555 N3.getOpcode() == ISD::BUILD_VECTOR &&
2556 VT.getVectorNumElements() == N3.getNumOperands() &&
2557 "Illegal VECTOR_SHUFFLE node!");
2559 case ISD::BIT_CONVERT:
2560 // Fold bit_convert nodes from a type to themselves.
2561 if (N1.getValueType() == VT)
2566 // Memoize node if it doesn't produce a flag.
2568 SDVTList VTs = getVTList(VT);
2569 if (VT != MVT::Flag) {
2570 SDOperand Ops[] = { N1, N2, N3 };
2571 FoldingSetNodeID ID;
2572 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2574 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2575 return SDOperand(E, 0);
2576 N = getAllocator().Allocate<TernarySDNode>();
2577 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2578 CSEMap.InsertNode(N, IP);
2580 N = getAllocator().Allocate<TernarySDNode>();
2581 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2583 AllNodes.push_back(N);
2584 return SDOperand(N, 0);
2587 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2588 SDOperand N1, SDOperand N2, SDOperand N3,
2590 SDOperand Ops[] = { N1, N2, N3, N4 };
2591 return getNode(Opcode, VT, Ops, 4);
2594 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2595 SDOperand N1, SDOperand N2, SDOperand N3,
2596 SDOperand N4, SDOperand N5) {
2597 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2598 return getNode(Opcode, VT, Ops, 5);
2601 /// getMemsetValue - Vectorized representation of the memset value
2603 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2604 unsigned NumBits = VT.isVector() ?
2605 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2606 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2607 APInt Val = APInt(NumBits, C->getValue() & 255);
2609 for (unsigned i = NumBits; i > 8; i >>= 1) {
2610 Val = (Val << Shift) | Val;
2614 return DAG.getConstant(Val, VT);
2615 return DAG.getConstantFP(APFloat(Val), VT);
2618 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2620 for (unsigned i = NumBits; i > 8; i >>= 1) {
2621 Value = DAG.getNode(ISD::OR, VT,
2622 DAG.getNode(ISD::SHL, VT, Value,
2623 DAG.getConstant(Shift, MVT::i8)), Value);
2630 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2631 /// used when a memcpy is turned into a memset when the source is a constant
2633 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2634 const TargetLowering &TLI,
2635 std::string &Str, unsigned Offset) {
2636 // Handle vector with all elements zero.
2639 return DAG.getConstant(0, VT);
2640 unsigned NumElts = VT.getVectorNumElements();
2641 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2642 return DAG.getNode(ISD::BIT_CONVERT, VT,
2643 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2646 assert(!VT.isVector() && "Can't handle vector type here!");
2647 unsigned NumBits = VT.getSizeInBits();
2648 unsigned MSB = NumBits / 8;
2650 if (TLI.isLittleEndian())
2651 Offset = Offset + MSB - 1;
2652 for (unsigned i = 0; i != MSB; ++i) {
2653 Val = (Val << 8) | (unsigned char)Str[Offset];
2654 Offset += TLI.isLittleEndian() ? -1 : 1;
2656 return DAG.getConstant(Val, VT);
2659 /// getMemBasePlusOffset - Returns base and offset node for the
2661 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2662 SelectionDAG &DAG) {
2663 MVT VT = Base.getValueType();
2664 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2667 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2669 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2670 unsigned SrcDelta = 0;
2671 GlobalAddressSDNode *G = NULL;
2672 if (Src.getOpcode() == ISD::GlobalAddress)
2673 G = cast<GlobalAddressSDNode>(Src);
2674 else if (Src.getOpcode() == ISD::ADD &&
2675 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2676 Src.getOperand(1).getOpcode() == ISD::Constant) {
2677 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2678 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2683 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2684 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2690 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2691 /// to replace the memset / memcpy is below the threshold. It also returns the
2692 /// types of the sequence of memory ops to perform memset / memcpy.
2694 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2695 SDOperand Dst, SDOperand Src,
2696 unsigned Limit, uint64_t Size, unsigned &Align,
2697 std::string &Str, bool &isSrcStr,
2699 const TargetLowering &TLI) {
2700 isSrcStr = isMemSrcFromString(Src, Str);
2701 bool isSrcConst = isa<ConstantSDNode>(Src);
2702 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2703 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2704 if (VT != MVT::iAny) {
2705 unsigned NewAlign = (unsigned)
2706 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2707 // If source is a string constant, this will require an unaligned load.
2708 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2709 if (Dst.getOpcode() != ISD::FrameIndex) {
2710 // Can't change destination alignment. It requires a unaligned store.
2714 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2715 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2716 if (MFI->isFixedObjectIndex(FI)) {
2717 // Can't change destination alignment. It requires a unaligned store.
2721 // Give the stack frame object a larger alignment if needed.
2722 if (MFI->getObjectAlignment(FI) < NewAlign)
2723 MFI->setObjectAlignment(FI, NewAlign);
2730 if (VT == MVT::iAny) {
2734 switch (Align & 7) {
2735 case 0: VT = MVT::i64; break;
2736 case 4: VT = MVT::i32; break;
2737 case 2: VT = MVT::i16; break;
2738 default: VT = MVT::i8; break;
2743 while (!TLI.isTypeLegal(LVT))
2744 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2745 assert(LVT.isInteger());
2751 unsigned NumMemOps = 0;
2753 unsigned VTSize = VT.getSizeInBits() / 8;
2754 while (VTSize > Size) {
2755 // For now, only use non-vector load / store's for the left-over pieces.
2756 if (VT.isVector()) {
2758 while (!TLI.isTypeLegal(VT))
2759 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2760 VTSize = VT.getSizeInBits() / 8;
2762 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2767 if (++NumMemOps > Limit)
2769 MemOps.push_back(VT);
2776 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2777 SDOperand Chain, SDOperand Dst,
2778 SDOperand Src, uint64_t Size,
2779 unsigned Align, bool AlwaysInline,
2780 const Value *DstSV, uint64_t DstSVOff,
2781 const Value *SrcSV, uint64_t SrcSVOff){
2782 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2784 // Expand memcpy to a series of load and store ops if the size operand falls
2785 // below a certain threshold.
2786 std::vector<MVT> MemOps;
2787 uint64_t Limit = -1;
2789 Limit = TLI.getMaxStoresPerMemcpy();
2790 unsigned DstAlign = Align; // Destination alignment can change.
2793 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2794 Str, CopyFromStr, DAG, TLI))
2798 bool isZeroStr = CopyFromStr && Str.empty();
2799 SmallVector<SDOperand, 8> OutChains;
2800 unsigned NumMemOps = MemOps.size();
2801 uint64_t SrcOff = 0, DstOff = 0;
2802 for (unsigned i = 0; i < NumMemOps; i++) {
2804 unsigned VTSize = VT.getSizeInBits() / 8;
2805 SDOperand Value, Store;
2807 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2808 // It's unlikely a store of a vector immediate can be done in a single
2809 // instruction. It would require a load from a constantpool first.
2810 // We also handle store a vector with all zero's.
2811 // FIXME: Handle other cases where store of vector immediate is done in
2812 // a single instruction.
2813 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2814 Store = DAG.getStore(Chain, Value,
2815 getMemBasePlusOffset(Dst, DstOff, DAG),
2816 DstSV, DstSVOff + DstOff, false, DstAlign);
2818 Value = DAG.getLoad(VT, Chain,
2819 getMemBasePlusOffset(Src, SrcOff, DAG),
2820 SrcSV, SrcSVOff + SrcOff, false, Align);
2821 Store = DAG.getStore(Chain, Value,
2822 getMemBasePlusOffset(Dst, DstOff, DAG),
2823 DstSV, DstSVOff + DstOff, false, DstAlign);
2825 OutChains.push_back(Store);
2830 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2831 &OutChains[0], OutChains.size());
2834 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2835 SDOperand Chain, SDOperand Dst,
2836 SDOperand Src, uint64_t Size,
2837 unsigned Align, bool AlwaysInline,
2838 const Value *DstSV, uint64_t DstSVOff,
2839 const Value *SrcSV, uint64_t SrcSVOff){
2840 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2842 // Expand memmove to a series of load and store ops if the size operand falls
2843 // below a certain threshold.
2844 std::vector<MVT> MemOps;
2845 uint64_t Limit = -1;
2847 Limit = TLI.getMaxStoresPerMemmove();
2848 unsigned DstAlign = Align; // Destination alignment can change.
2851 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2852 Str, CopyFromStr, DAG, TLI))
2855 uint64_t SrcOff = 0, DstOff = 0;
2857 SmallVector<SDOperand, 8> LoadValues;
2858 SmallVector<SDOperand, 8> LoadChains;
2859 SmallVector<SDOperand, 8> OutChains;
2860 unsigned NumMemOps = MemOps.size();
2861 for (unsigned i = 0; i < NumMemOps; i++) {
2863 unsigned VTSize = VT.getSizeInBits() / 8;
2864 SDOperand Value, Store;
2866 Value = DAG.getLoad(VT, Chain,
2867 getMemBasePlusOffset(Src, SrcOff, DAG),
2868 SrcSV, SrcSVOff + SrcOff, false, Align);
2869 LoadValues.push_back(Value);
2870 LoadChains.push_back(Value.getValue(1));
2873 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2874 &LoadChains[0], LoadChains.size());
2876 for (unsigned i = 0; i < NumMemOps; i++) {
2878 unsigned VTSize = VT.getSizeInBits() / 8;
2879 SDOperand Value, Store;
2881 Store = DAG.getStore(Chain, LoadValues[i],
2882 getMemBasePlusOffset(Dst, DstOff, DAG),
2883 DstSV, DstSVOff + DstOff, false, DstAlign);
2884 OutChains.push_back(Store);
2888 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2889 &OutChains[0], OutChains.size());
2892 static SDOperand getMemsetStores(SelectionDAG &DAG,
2893 SDOperand Chain, SDOperand Dst,
2894 SDOperand Src, uint64_t Size,
2896 const Value *DstSV, uint64_t DstSVOff) {
2897 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2899 // Expand memset to a series of load/store ops if the size operand
2900 // falls below a certain threshold.
2901 std::vector<MVT> MemOps;
2904 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2905 Size, Align, Str, CopyFromStr, DAG, TLI))
2908 SmallVector<SDOperand, 8> OutChains;
2909 uint64_t DstOff = 0;
2911 unsigned NumMemOps = MemOps.size();
2912 for (unsigned i = 0; i < NumMemOps; i++) {
2914 unsigned VTSize = VT.getSizeInBits() / 8;
2915 SDOperand Value = getMemsetValue(Src, VT, DAG);
2916 SDOperand Store = DAG.getStore(Chain, Value,
2917 getMemBasePlusOffset(Dst, DstOff, DAG),
2918 DstSV, DstSVOff + DstOff);
2919 OutChains.push_back(Store);
2923 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2924 &OutChains[0], OutChains.size());
2927 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2928 SDOperand Src, SDOperand Size,
2929 unsigned Align, bool AlwaysInline,
2930 const Value *DstSV, uint64_t DstSVOff,
2931 const Value *SrcSV, uint64_t SrcSVOff) {
2933 // Check to see if we should lower the memcpy to loads and stores first.
2934 // For cases within the target-specified limits, this is the best choice.
2935 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2937 // Memcpy with size zero? Just return the original chain.
2938 if (ConstantSize->isNullValue())
2942 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2943 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2948 // Then check to see if we should lower the memcpy with target-specific
2949 // code. If the target chooses to do this, this is the next best.
2951 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2953 DstSV, DstSVOff, SrcSV, SrcSVOff);
2957 // If we really need inline code and the target declined to provide it,
2958 // use a (potentially long) sequence of loads and stores.
2960 assert(ConstantSize && "AlwaysInline requires a constant size!");
2961 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2962 ConstantSize->getValue(), Align, true,
2963 DstSV, DstSVOff, SrcSV, SrcSVOff);
2966 // Emit a library call.
2967 TargetLowering::ArgListTy Args;
2968 TargetLowering::ArgListEntry Entry;
2969 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2970 Entry.Node = Dst; Args.push_back(Entry);
2971 Entry.Node = Src; Args.push_back(Entry);
2972 Entry.Node = Size; Args.push_back(Entry);
2973 std::pair<SDOperand,SDOperand> CallResult =
2974 TLI.LowerCallTo(Chain, Type::VoidTy,
2975 false, false, false, CallingConv::C, false,
2976 getExternalSymbol("memcpy", TLI.getPointerTy()),
2978 return CallResult.second;
2981 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2982 SDOperand Src, SDOperand Size,
2984 const Value *DstSV, uint64_t DstSVOff,
2985 const Value *SrcSV, uint64_t SrcSVOff) {
2987 // Check to see if we should lower the memmove to loads and stores first.
2988 // For cases within the target-specified limits, this is the best choice.
2989 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2991 // Memmove with size zero? Just return the original chain.
2992 if (ConstantSize->isNullValue())
2996 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2997 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3002 // Then check to see if we should lower the memmove with target-specific
3003 // code. If the target chooses to do this, this is the next best.
3005 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
3006 DstSV, DstSVOff, SrcSV, SrcSVOff);
3010 // Emit a library call.
3011 TargetLowering::ArgListTy Args;
3012 TargetLowering::ArgListEntry Entry;
3013 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3014 Entry.Node = Dst; Args.push_back(Entry);
3015 Entry.Node = Src; Args.push_back(Entry);
3016 Entry.Node = Size; Args.push_back(Entry);
3017 std::pair<SDOperand,SDOperand> CallResult =
3018 TLI.LowerCallTo(Chain, Type::VoidTy,
3019 false, false, false, CallingConv::C, false,
3020 getExternalSymbol("memmove", TLI.getPointerTy()),
3022 return CallResult.second;
3025 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
3026 SDOperand Src, SDOperand Size,
3028 const Value *DstSV, uint64_t DstSVOff) {
3030 // Check to see if we should lower the memset to stores first.
3031 // For cases within the target-specified limits, this is the best choice.
3032 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3034 // Memset with size zero? Just return the original chain.
3035 if (ConstantSize->isNullValue())
3039 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3045 // Then check to see if we should lower the memset with target-specific
3046 // code. If the target chooses to do this, this is the next best.
3048 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3053 // Emit a library call.
3054 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3055 TargetLowering::ArgListTy Args;
3056 TargetLowering::ArgListEntry Entry;
3057 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3058 Args.push_back(Entry);
3059 // Extend or truncate the argument to be an i32 value for the call.
3060 if (Src.getValueType().bitsGT(MVT::i32))
3061 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3063 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3064 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3065 Args.push_back(Entry);
3066 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3067 Args.push_back(Entry);
3068 std::pair<SDOperand,SDOperand> CallResult =
3069 TLI.LowerCallTo(Chain, Type::VoidTy,
3070 false, false, false, CallingConv::C, false,
3071 getExternalSymbol("memset", TLI.getPointerTy()),
3073 return CallResult.second;
3076 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3077 SDOperand Ptr, SDOperand Cmp,
3078 SDOperand Swp, const Value* PtrVal,
3079 unsigned Alignment) {
3080 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3081 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3083 MVT VT = Cmp.getValueType();
3085 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3086 Alignment = getMVTAlignment(VT);
3088 SDVTList VTs = getVTList(VT, MVT::Other);
3089 FoldingSetNodeID ID;
3090 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3091 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3093 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3094 return SDOperand(E, 0);
3095 SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3096 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3097 CSEMap.InsertNode(N, IP);
3098 AllNodes.push_back(N);
3099 return SDOperand(N, 0);
3102 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3103 SDOperand Ptr, SDOperand Val,
3104 const Value* PtrVal,
3105 unsigned Alignment) {
3106 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3107 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3108 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3109 || Opcode == ISD::ATOMIC_LOAD_NAND
3110 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3111 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3112 && "Invalid Atomic Op");
3114 MVT VT = Val.getValueType();
3116 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3117 Alignment = getMVTAlignment(VT);
3119 SDVTList VTs = getVTList(VT, MVT::Other);
3120 FoldingSetNodeID ID;
3121 SDOperand Ops[] = {Chain, Ptr, Val};
3122 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3124 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3125 return SDOperand(E, 0);
3126 SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3127 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
3128 CSEMap.InsertNode(N, IP);
3129 AllNodes.push_back(N);
3130 return SDOperand(N, 0);
3133 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3134 /// Allowed to return something different (and simpler) if Simplify is true.
3135 SDOperand SelectionDAG::getMergeValues(const SDOperand *Ops, unsigned NumOps,
3137 if (Simplify && NumOps == 1)
3140 SmallVector<MVT, 4> VTs;
3141 VTs.reserve(NumOps);
3142 for (unsigned i = 0; i < NumOps; ++i)
3143 VTs.push_back(Ops[i].getValueType());
3144 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3148 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3149 MVT VT, SDOperand Chain,
3150 SDOperand Ptr, SDOperand Offset,
3151 const Value *SV, int SVOffset, MVT EVT,
3152 bool isVolatile, unsigned Alignment) {
3153 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3154 Alignment = getMVTAlignment(VT);
3157 ExtType = ISD::NON_EXTLOAD;
3158 } else if (ExtType == ISD::NON_EXTLOAD) {
3159 assert(VT == EVT && "Non-extending load from different memory type!");
3163 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3165 assert(EVT.bitsLT(VT) &&
3166 "Should only be an extending load, not truncating!");
3167 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3168 "Cannot sign/zero extend a FP/Vector load!");
3169 assert(VT.isInteger() == EVT.isInteger() &&
3170 "Cannot convert from FP to Int or Int -> FP!");
3173 bool Indexed = AM != ISD::UNINDEXED;
3174 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3175 "Unindexed load with an offset!");
3177 SDVTList VTs = Indexed ?
3178 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3179 SDOperand Ops[] = { Chain, Ptr, Offset };
3180 FoldingSetNodeID ID;
3181 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3183 ID.AddInteger(ExtType);
3184 ID.AddInteger(EVT.getRawBits());
3185 ID.AddInteger(Alignment);
3186 ID.AddInteger(isVolatile);
3188 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3189 return SDOperand(E, 0);
3190 SDNode *N = getAllocator().Allocate<LoadSDNode>();
3191 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3192 Alignment, isVolatile);
3193 CSEMap.InsertNode(N, IP);
3194 AllNodes.push_back(N);
3195 return SDOperand(N, 0);
3198 SDOperand SelectionDAG::getLoad(MVT VT,
3199 SDOperand Chain, SDOperand Ptr,
3200 const Value *SV, int SVOffset,
3201 bool isVolatile, unsigned Alignment) {
3202 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3203 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3204 SV, SVOffset, VT, isVolatile, Alignment);
3207 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3208 SDOperand Chain, SDOperand Ptr,
3210 int SVOffset, MVT EVT,
3211 bool isVolatile, unsigned Alignment) {
3212 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3213 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3214 SV, SVOffset, EVT, isVolatile, Alignment);
3218 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3219 SDOperand Offset, ISD::MemIndexedMode AM) {
3220 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3221 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3222 "Load is already a indexed load!");
3223 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3224 LD->getChain(), Base, Offset, LD->getSrcValue(),
3225 LD->getSrcValueOffset(), LD->getMemoryVT(),
3226 LD->isVolatile(), LD->getAlignment());
3229 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3230 SDOperand Ptr, const Value *SV, int SVOffset,
3231 bool isVolatile, unsigned Alignment) {
3232 MVT VT = Val.getValueType();
3234 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3235 Alignment = getMVTAlignment(VT);
3237 SDVTList VTs = getVTList(MVT::Other);
3238 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3239 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3240 FoldingSetNodeID ID;
3241 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3242 ID.AddInteger(ISD::UNINDEXED);
3243 ID.AddInteger(false);
3244 ID.AddInteger(VT.getRawBits());
3245 ID.AddInteger(Alignment);
3246 ID.AddInteger(isVolatile);
3248 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3249 return SDOperand(E, 0);
3250 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3251 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3252 VT, SV, SVOffset, Alignment, isVolatile);
3253 CSEMap.InsertNode(N, IP);
3254 AllNodes.push_back(N);
3255 return SDOperand(N, 0);
3258 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3259 SDOperand Ptr, const Value *SV,
3260 int SVOffset, MVT SVT,
3261 bool isVolatile, unsigned Alignment) {
3262 MVT VT = Val.getValueType();
3265 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3267 assert(VT.bitsGT(SVT) && "Not a truncation?");
3268 assert(VT.isInteger() == SVT.isInteger() &&
3269 "Can't do FP-INT conversion!");
3271 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3272 Alignment = getMVTAlignment(VT);
3274 SDVTList VTs = getVTList(MVT::Other);
3275 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3276 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3277 FoldingSetNodeID ID;
3278 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3279 ID.AddInteger(ISD::UNINDEXED);
3281 ID.AddInteger(SVT.getRawBits());
3282 ID.AddInteger(Alignment);
3283 ID.AddInteger(isVolatile);
3285 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3286 return SDOperand(E, 0);
3287 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3288 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3289 SVT, SV, SVOffset, Alignment, isVolatile);
3290 CSEMap.InsertNode(N, IP);
3291 AllNodes.push_back(N);
3292 return SDOperand(N, 0);
3296 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3297 SDOperand Offset, ISD::MemIndexedMode AM) {
3298 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3299 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3300 "Store is already a indexed store!");
3301 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3302 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3303 FoldingSetNodeID ID;
3304 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3306 ID.AddInteger(ST->isTruncatingStore());
3307 ID.AddInteger(ST->getMemoryVT().getRawBits());
3308 ID.AddInteger(ST->getAlignment());
3309 ID.AddInteger(ST->isVolatile());
3311 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3312 return SDOperand(E, 0);
3313 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3314 new (N) StoreSDNode(Ops, VTs, AM,
3315 ST->isTruncatingStore(), ST->getMemoryVT(),
3316 ST->getSrcValue(), ST->getSrcValueOffset(),
3317 ST->getAlignment(), ST->isVolatile());
3318 CSEMap.InsertNode(N, IP);
3319 AllNodes.push_back(N);
3320 return SDOperand(N, 0);
3323 SDOperand SelectionDAG::getVAArg(MVT VT,
3324 SDOperand Chain, SDOperand Ptr,
3326 SDOperand Ops[] = { Chain, Ptr, SV };
3327 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3330 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3331 const SDUse *Ops, unsigned NumOps) {
3333 case 0: return getNode(Opcode, VT);
3334 case 1: return getNode(Opcode, VT, Ops[0].getSDOperand());
3335 case 2: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3336 Ops[1].getSDOperand());
3337 case 3: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3338 Ops[1].getSDOperand(), Ops[2].getSDOperand());
3342 // Copy from an SDUse array into an SDOperand array for use with
3343 // the regular getNode logic.
3344 SmallVector<SDOperand, 8> NewOps;
3345 NewOps.reserve(NumOps);
3346 for (unsigned i = 0; i != NumOps; ++i)
3347 NewOps.push_back(Ops[i].getSDOperand());
3348 return getNode(Opcode, VT, Ops, NumOps);
3351 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3352 const SDOperand *Ops, unsigned NumOps) {
3354 case 0: return getNode(Opcode, VT);
3355 case 1: return getNode(Opcode, VT, Ops[0]);
3356 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3357 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3363 case ISD::SELECT_CC: {
3364 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3365 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3366 "LHS and RHS of condition must have same type!");
3367 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3368 "True and False arms of SelectCC must have same type!");
3369 assert(Ops[2].getValueType() == VT &&
3370 "select_cc node must be of same type as true and false value!");
3374 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3375 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3376 "LHS/RHS of comparison should match types!");
3383 SDVTList VTs = getVTList(VT);
3384 if (VT != MVT::Flag) {
3385 FoldingSetNodeID ID;
3386 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3388 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3389 return SDOperand(E, 0);
3390 N = getAllocator().Allocate<SDNode>();
3391 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3392 CSEMap.InsertNode(N, IP);
3394 N = getAllocator().Allocate<SDNode>();
3395 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3397 AllNodes.push_back(N);
3398 return SDOperand(N, 0);
3401 SDOperand SelectionDAG::getNode(unsigned Opcode,
3402 const std::vector<MVT> &ResultTys,
3403 const SDOperand *Ops, unsigned NumOps) {
3404 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3408 SDOperand SelectionDAG::getNode(unsigned Opcode,
3409 const MVT *VTs, unsigned NumVTs,
3410 const SDOperand *Ops, unsigned NumOps) {
3412 return getNode(Opcode, VTs[0], Ops, NumOps);
3413 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3416 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3417 const SDOperand *Ops, unsigned NumOps) {
3418 if (VTList.NumVTs == 1)
3419 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3422 // FIXME: figure out how to safely handle things like
3423 // int foo(int x) { return 1 << (x & 255); }
3424 // int bar() { return foo(256); }
3426 case ISD::SRA_PARTS:
3427 case ISD::SRL_PARTS:
3428 case ISD::SHL_PARTS:
3429 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3430 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3431 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3432 else if (N3.getOpcode() == ISD::AND)
3433 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3434 // If the and is only masking out bits that cannot effect the shift,
3435 // eliminate the and.
3436 unsigned NumBits = VT.getSizeInBits()*2;
3437 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3438 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3444 // Memoize the node unless it returns a flag.
3446 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3447 FoldingSetNodeID ID;
3448 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3450 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3451 return SDOperand(E, 0);
3453 N = getAllocator().Allocate<UnarySDNode>();
3454 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3455 } else if (NumOps == 2) {
3456 N = getAllocator().Allocate<BinarySDNode>();
3457 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3458 } else if (NumOps == 3) {
3459 N = getAllocator().Allocate<TernarySDNode>();
3460 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3462 N = getAllocator().Allocate<SDNode>();
3463 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3465 CSEMap.InsertNode(N, IP);
3468 N = getAllocator().Allocate<UnarySDNode>();
3469 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3470 } else if (NumOps == 2) {
3471 N = getAllocator().Allocate<BinarySDNode>();
3472 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3473 } else if (NumOps == 3) {
3474 N = getAllocator().Allocate<TernarySDNode>();
3475 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3477 N = getAllocator().Allocate<SDNode>();
3478 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3481 AllNodes.push_back(N);
3482 return SDOperand(N, 0);
3485 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3486 return getNode(Opcode, VTList, 0, 0);
3489 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3491 SDOperand Ops[] = { N1 };
3492 return getNode(Opcode, VTList, Ops, 1);
3495 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3496 SDOperand N1, SDOperand N2) {
3497 SDOperand Ops[] = { N1, N2 };
3498 return getNode(Opcode, VTList, Ops, 2);
3501 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3502 SDOperand N1, SDOperand N2, SDOperand N3) {
3503 SDOperand Ops[] = { N1, N2, N3 };
3504 return getNode(Opcode, VTList, Ops, 3);
3507 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3508 SDOperand N1, SDOperand N2, SDOperand N3,
3510 SDOperand Ops[] = { N1, N2, N3, N4 };
3511 return getNode(Opcode, VTList, Ops, 4);
3514 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3515 SDOperand N1, SDOperand N2, SDOperand N3,
3516 SDOperand N4, SDOperand N5) {
3517 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3518 return getNode(Opcode, VTList, Ops, 5);
3521 SDVTList SelectionDAG::getVTList(MVT VT) {
3522 return makeVTList(SDNode::getValueTypeList(VT), 1);
3525 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3526 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3527 E = VTList.end(); I != E; ++I) {
3528 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3529 return makeVTList(&(*I)[0], 2);
3534 VTList.push_front(V);
3535 return makeVTList(&(*VTList.begin())[0], 2);
3537 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3539 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3540 E = VTList.end(); I != E; ++I) {
3541 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3543 return makeVTList(&(*I)[0], 3);
3549 VTList.push_front(V);
3550 return makeVTList(&(*VTList.begin())[0], 3);
3553 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3555 case 0: assert(0 && "Cannot have nodes without results!");
3556 case 1: return getVTList(VTs[0]);
3557 case 2: return getVTList(VTs[0], VTs[1]);
3558 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3562 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3563 E = VTList.end(); I != E; ++I) {
3564 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3566 bool NoMatch = false;
3567 for (unsigned i = 2; i != NumVTs; ++i)
3568 if (VTs[i] != (*I)[i]) {
3573 return makeVTList(&*I->begin(), NumVTs);
3576 VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3577 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3581 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3582 /// specified operands. If the resultant node already exists in the DAG,
3583 /// this does not modify the specified node, instead it returns the node that
3584 /// already exists. If the resultant node does not exist in the DAG, the
3585 /// input node is returned. As a degenerate case, if you specify the same
3586 /// input operands as the node already has, the input node is returned.
3587 SDOperand SelectionDAG::
3588 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3589 SDNode *N = InN.Val;
3590 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3592 // Check to see if there is no change.
3593 if (Op == N->getOperand(0)) return InN;
3595 // See if the modified node already exists.
3596 void *InsertPos = 0;
3597 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3598 return SDOperand(Existing, InN.ResNo);
3600 // Nope it doesn't. Remove the node from it's current place in the maps.
3602 RemoveNodeFromCSEMaps(N);
3604 // Now we update the operands.
3605 N->OperandList[0].getVal()->removeUser(0, N);
3606 N->OperandList[0] = Op;
3607 N->OperandList[0].setUser(N);
3608 Op.Val->addUser(0, N);
3610 // If this gets put into a CSE map, add it.
3611 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3615 SDOperand SelectionDAG::
3616 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3617 SDNode *N = InN.Val;
3618 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3620 // Check to see if there is no change.
3621 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3622 return InN; // No operands changed, just return the input node.
3624 // See if the modified node already exists.
3625 void *InsertPos = 0;
3626 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3627 return SDOperand(Existing, InN.ResNo);
3629 // Nope it doesn't. Remove the node from it's current place in the maps.
3631 RemoveNodeFromCSEMaps(N);
3633 // Now we update the operands.
3634 if (N->OperandList[0] != Op1) {
3635 N->OperandList[0].getVal()->removeUser(0, N);
3636 N->OperandList[0] = Op1;
3637 N->OperandList[0].setUser(N);
3638 Op1.Val->addUser(0, N);
3640 if (N->OperandList[1] != Op2) {
3641 N->OperandList[1].getVal()->removeUser(1, N);
3642 N->OperandList[1] = Op2;
3643 N->OperandList[1].setUser(N);
3644 Op2.Val->addUser(1, N);
3647 // If this gets put into a CSE map, add it.
3648 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3652 SDOperand SelectionDAG::
3653 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3654 SDOperand Ops[] = { Op1, Op2, Op3 };
3655 return UpdateNodeOperands(N, Ops, 3);
3658 SDOperand SelectionDAG::
3659 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3660 SDOperand Op3, SDOperand Op4) {
3661 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3662 return UpdateNodeOperands(N, Ops, 4);
3665 SDOperand SelectionDAG::
3666 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3667 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3668 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3669 return UpdateNodeOperands(N, Ops, 5);
3672 SDOperand SelectionDAG::
3673 UpdateNodeOperands(SDOperand InN, const SDOperand *Ops, unsigned NumOps) {
3674 SDNode *N = InN.Val;
3675 assert(N->getNumOperands() == NumOps &&
3676 "Update with wrong number of operands");
3678 // Check to see if there is no change.
3679 bool AnyChange = false;
3680 for (unsigned i = 0; i != NumOps; ++i) {
3681 if (Ops[i] != N->getOperand(i)) {
3687 // No operands changed, just return the input node.
3688 if (!AnyChange) return InN;
3690 // See if the modified node already exists.
3691 void *InsertPos = 0;
3692 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3693 return SDOperand(Existing, InN.ResNo);
3695 // Nope it doesn't. Remove the node from its current place in the maps.
3697 RemoveNodeFromCSEMaps(N);
3699 // Now we update the operands.
3700 for (unsigned i = 0; i != NumOps; ++i) {
3701 if (N->OperandList[i] != Ops[i]) {
3702 N->OperandList[i].getVal()->removeUser(i, N);
3703 N->OperandList[i] = Ops[i];
3704 N->OperandList[i].setUser(N);
3705 Ops[i].Val->addUser(i, N);
3709 // If this gets put into a CSE map, add it.
3710 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3714 /// MorphNodeTo - This frees the operands of the current node, resets the
3715 /// opcode, types, and operands to the specified value. This should only be
3716 /// used by the SelectionDAG class.
3717 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3718 const SDOperand *Ops, unsigned NumOps,
3719 SmallVectorImpl<SDNode *> &DeadNodes) {
3722 NumValues = L.NumVTs;
3724 // Clear the operands list, updating used nodes to remove this from their
3725 // use list. Keep track of any operands that become dead as a result.
3726 SmallPtrSet<SDNode*, 16> DeadNodeSet;
3727 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
3728 SDNode *N = I->getVal();
3729 N->removeUser(std::distance(op_begin(), I), this);
3731 DeadNodeSet.insert(N);
3734 // If NumOps is larger than the # of operands we currently have, reallocate
3735 // the operand list.
3736 if (NumOps > NumOperands) {
3737 if (OperandsNeedDelete) {
3738 delete [] OperandList;
3740 OperandList = new SDUse[NumOps];
3741 OperandsNeedDelete = true;
3744 // Assign the new operands.
3745 NumOperands = NumOps;
3747 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3748 OperandList[i] = Ops[i];
3749 OperandList[i].setUser(this);
3750 SDNode *N = OperandList[i].getVal();
3751 N->addUser(i, this);
3752 DeadNodeSet.erase(N);
3755 // Clean up any nodes that are still dead after adding the uses for the
3757 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
3758 E = DeadNodeSet.end(); I != E; ++I)
3759 DeadNodes.push_back(*I);
3762 /// DropOperands - Release the operands and set this node to have
3763 /// zero operands. This should only be used by HandleSDNode to clear
3764 /// its operand list.
3765 void SDNode::DropOperands() {
3766 assert(NodeType == ISD::HANDLENODE &&
3767 "DropOperands is for HANDLENODE only!");
3769 // Unlike the code in MorphNodeTo that does this, we don't need to
3770 // watch for dead nodes here.
3771 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3772 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3777 /// SelectNodeTo - These are used for target selectors to *mutate* the
3778 /// specified node to have the specified return type, Target opcode, and
3779 /// operands. Note that target opcodes are stored as
3780 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3782 /// Note that SelectNodeTo returns the resultant node. If there is already a
3783 /// node of the specified opcode and operands, it returns that node instead of
3784 /// the current one.
3785 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3787 SDVTList VTs = getVTList(VT);
3788 return SelectNodeTo(N, TargetOpc, VTs, 0, 0);
3791 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3792 MVT VT, SDOperand Op1) {
3793 SDVTList VTs = getVTList(VT);
3794 SDOperand Ops[] = { Op1 };
3795 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3798 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3799 MVT VT, SDOperand Op1,
3801 SDVTList VTs = getVTList(VT);
3802 SDOperand Ops[] = { Op1, Op2 };
3803 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3806 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3807 MVT VT, SDOperand Op1,
3808 SDOperand Op2, SDOperand Op3) {
3809 SDVTList VTs = getVTList(VT);
3810 SDOperand Ops[] = { Op1, Op2, Op3 };
3811 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3814 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3815 MVT VT, const SDOperand *Ops,
3817 SDVTList VTs = getVTList(VT);
3818 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3821 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3822 MVT VT1, MVT VT2, const SDOperand *Ops,
3824 SDVTList VTs = getVTList(VT1, VT2);
3825 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3828 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3830 SDVTList VTs = getVTList(VT1, VT2);
3831 return SelectNodeTo(N, TargetOpc, VTs, (SDOperand *)0, 0);
3834 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3835 MVT VT1, MVT VT2, MVT VT3,
3836 const SDOperand *Ops, unsigned NumOps) {
3837 SDVTList VTs = getVTList(VT1, VT2, VT3);
3838 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3841 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3844 SDVTList VTs = getVTList(VT1, VT2);
3845 SDOperand Ops[] = { Op1 };
3846 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3849 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3851 SDOperand Op1, SDOperand Op2) {
3852 SDVTList VTs = getVTList(VT1, VT2);
3853 SDOperand Ops[] = { Op1, Op2 };
3854 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3857 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3859 SDOperand Op1, SDOperand Op2,
3861 SDVTList VTs = getVTList(VT1, VT2);
3862 SDOperand Ops[] = { Op1, Op2, Op3 };
3863 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3866 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3867 SDVTList VTs, const SDOperand *Ops,
3869 // If an identical node already exists, use it.
3870 FoldingSetNodeID ID;
3871 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3873 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3876 RemoveNodeFromCSEMaps(N);
3878 SmallVector<SDNode *, 16> DeadNodes;
3879 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps, DeadNodes);
3880 RemoveDeadNodes(DeadNodes);
3882 CSEMap.InsertNode(N, IP); // Memoize the new node.
3887 /// getTargetNode - These are used for target selectors to create a new node
3888 /// with specified return type(s), target opcode, and operands.
3890 /// Note that getTargetNode returns the resultant node. If there is already a
3891 /// node of the specified opcode and operands, it returns that node instead of
3892 /// the current one.
3893 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3894 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3896 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3897 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3899 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3900 SDOperand Op1, SDOperand Op2) {
3901 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3903 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3904 SDOperand Op1, SDOperand Op2,
3906 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3908 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3909 const SDOperand *Ops, unsigned NumOps) {
3910 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3912 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3913 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3915 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3917 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3918 MVT VT2, SDOperand Op1) {
3919 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3920 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3922 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3923 MVT VT2, SDOperand Op1,
3925 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3926 SDOperand Ops[] = { Op1, Op2 };
3927 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3929 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3930 MVT VT2, SDOperand Op1,
3931 SDOperand Op2, SDOperand Op3) {
3932 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3933 SDOperand Ops[] = { Op1, Op2, Op3 };
3934 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3936 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3937 const SDOperand *Ops, unsigned NumOps) {
3938 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3939 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3941 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3942 SDOperand Op1, SDOperand Op2) {
3943 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3944 SDOperand Ops[] = { Op1, Op2 };
3945 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3947 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3948 SDOperand Op1, SDOperand Op2,
3950 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3951 SDOperand Ops[] = { Op1, Op2, Op3 };
3952 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3954 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3955 const SDOperand *Ops, unsigned NumOps) {
3956 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3957 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3959 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3960 MVT VT2, MVT VT3, MVT VT4,
3961 const SDOperand *Ops, unsigned NumOps) {
3962 std::vector<MVT> VTList;
3963 VTList.push_back(VT1);
3964 VTList.push_back(VT2);
3965 VTList.push_back(VT3);
3966 VTList.push_back(VT4);
3967 const MVT *VTs = getNodeValueTypes(VTList);
3968 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3970 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3971 const std::vector<MVT> &ResultTys,
3972 const SDOperand *Ops, unsigned NumOps) {
3973 const MVT *VTs = getNodeValueTypes(ResultTys);
3974 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3978 /// getNodeIfExists - Get the specified node if it's already available, or
3979 /// else return NULL.
3980 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3981 const SDOperand *Ops, unsigned NumOps) {
3982 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3983 FoldingSetNodeID ID;
3984 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3986 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3993 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3994 /// This can cause recursive merging of nodes in the DAG.
3996 /// This version assumes From has a single result value.
3998 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3999 DAGUpdateListener *UpdateListener) {
4000 SDNode *From = FromN.Val;
4001 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
4002 "Cannot replace with this method!");
4003 assert(From != To.Val && "Cannot replace uses of with self");
4005 while (!From->use_empty()) {
4006 SDNode::use_iterator UI = From->use_begin();
4007 SDNode *U = UI->getUser();
4009 // This node is about to morph, remove its old self from the CSE maps.
4010 RemoveNodeFromCSEMaps(U);
4012 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4013 I != E; ++I, ++operandNum)
4014 if (I->getVal() == From) {
4015 From->removeUser(operandNum, U);
4018 To.Val->addUser(operandNum, U);
4021 // Now that we have modified U, add it back to the CSE maps. If it already
4022 // exists there, recursively merge the results together.
4023 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4024 ReplaceAllUsesWith(U, Existing, UpdateListener);
4025 // U is now dead. Inform the listener if it exists and delete it.
4027 UpdateListener->NodeDeleted(U, Existing);
4028 DeleteNodeNotInCSEMaps(U);
4030 // If the node doesn't already exist, we updated it. Inform a listener if
4033 UpdateListener->NodeUpdated(U);
4038 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4039 /// This can cause recursive merging of nodes in the DAG.
4041 /// This version assumes From/To have matching types and numbers of result
4044 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4045 DAGUpdateListener *UpdateListener) {
4046 assert(From != To && "Cannot replace uses of with self");
4047 assert(From->getNumValues() == To->getNumValues() &&
4048 "Cannot use this version of ReplaceAllUsesWith!");
4049 if (From->getNumValues() == 1) // If possible, use the faster version.
4050 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
4053 while (!From->use_empty()) {
4054 SDNode::use_iterator UI = From->use_begin();
4055 SDNode *U = UI->getUser();
4057 // This node is about to morph, remove its old self from the CSE maps.
4058 RemoveNodeFromCSEMaps(U);
4060 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4061 I != E; ++I, ++operandNum)
4062 if (I->getVal() == From) {
4063 From->removeUser(operandNum, U);
4065 To->addUser(operandNum, U);
4068 // Now that we have modified U, add it back to the CSE maps. If it already
4069 // exists there, recursively merge the results together.
4070 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4071 ReplaceAllUsesWith(U, Existing, UpdateListener);
4072 // U is now dead. Inform the listener if it exists and delete it.
4074 UpdateListener->NodeDeleted(U, Existing);
4075 DeleteNodeNotInCSEMaps(U);
4077 // If the node doesn't already exist, we updated it. Inform a listener if
4080 UpdateListener->NodeUpdated(U);
4085 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4086 /// This can cause recursive merging of nodes in the DAG.
4088 /// This version can replace From with any result values. To must match the
4089 /// number and types of values returned by From.
4090 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4091 const SDOperand *To,
4092 DAGUpdateListener *UpdateListener) {
4093 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4094 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
4096 while (!From->use_empty()) {
4097 SDNode::use_iterator UI = From->use_begin();
4098 SDNode *U = UI->getUser();
4100 // This node is about to morph, remove its old self from the CSE maps.
4101 RemoveNodeFromCSEMaps(U);
4103 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4104 I != E; ++I, ++operandNum)
4105 if (I->getVal() == From) {
4106 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4107 From->removeUser(operandNum, U);
4110 ToOp.Val->addUser(operandNum, U);
4113 // Now that we have modified U, add it back to the CSE maps. If it already
4114 // exists there, recursively merge the results together.
4115 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4116 ReplaceAllUsesWith(U, Existing, UpdateListener);
4117 // U is now dead. Inform the listener if it exists and delete it.
4119 UpdateListener->NodeDeleted(U, Existing);
4120 DeleteNodeNotInCSEMaps(U);
4122 // If the node doesn't already exist, we updated it. Inform a listener if
4125 UpdateListener->NodeUpdated(U);
4131 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4132 /// any deleted nodes from the set passed into its constructor and recursively
4133 /// notifies another update listener if specified.
4134 class ChainedSetUpdaterListener :
4135 public SelectionDAG::DAGUpdateListener {
4136 SmallSetVector<SDNode*, 16> &Set;
4137 SelectionDAG::DAGUpdateListener *Chain;
4139 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4140 SelectionDAG::DAGUpdateListener *chain)
4141 : Set(set), Chain(chain) {}
4143 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4145 if (Chain) Chain->NodeDeleted(N, E);
4147 virtual void NodeUpdated(SDNode *N) {
4148 if (Chain) Chain->NodeUpdated(N);
4153 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4154 /// uses of other values produced by From.Val alone. The Deleted vector is
4155 /// handled the same way as for ReplaceAllUsesWith.
4156 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4157 DAGUpdateListener *UpdateListener){
4158 assert(From != To && "Cannot replace a value with itself");
4160 // Handle the simple, trivial, case efficiently.
4161 if (From.Val->getNumValues() == 1) {
4162 ReplaceAllUsesWith(From, To, UpdateListener);
4166 if (From.use_empty()) return;
4168 // Get all of the users of From.Val. We want these in a nice,
4169 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4170 SmallSetVector<SDNode*, 16> Users;
4171 for (SDNode::use_iterator UI = From.Val->use_begin(),
4172 E = From.Val->use_end(); UI != E; ++UI) {
4173 SDNode *User = UI->getUser();
4177 // When one of the recursive merges deletes nodes from the graph, we need to
4178 // make sure that UpdateListener is notified *and* that the node is removed
4179 // from Users if present. CSUL does this.
4180 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4182 while (!Users.empty()) {
4183 // We know that this user uses some value of From. If it is the right
4184 // value, update it.
4185 SDNode *User = Users.back();
4188 // Scan for an operand that matches From.
4189 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4190 for (; Op != E; ++Op)
4191 if (*Op == From) break;
4193 // If there are no matches, the user must use some other result of From.
4194 if (Op == E) continue;
4196 // Okay, we know this user needs to be updated. Remove its old self
4197 // from the CSE maps.
4198 RemoveNodeFromCSEMaps(User);
4200 // Update all operands that match "From" in case there are multiple uses.
4201 for (; Op != E; ++Op) {
4203 From.Val->removeUser(Op-User->op_begin(), User);
4206 To.Val->addUser(Op-User->op_begin(), User);
4210 // Now that we have modified User, add it back to the CSE maps. If it
4211 // already exists there, recursively merge the results together.
4212 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4214 if (UpdateListener) UpdateListener->NodeUpdated(User);
4215 continue; // Continue on to next user.
4218 // If there was already an existing matching node, use ReplaceAllUsesWith
4219 // to replace the dead one with the existing one. This can cause
4220 // recursive merging of other unrelated nodes down the line. The merging
4221 // can cause deletion of nodes that used the old value. To handle this, we
4222 // use CSUL to remove them from the Users set.
4223 ReplaceAllUsesWith(User, Existing, &CSUL);
4225 // User is now dead. Notify a listener if present.
4226 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4227 DeleteNodeNotInCSEMaps(User);
4231 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4232 /// their allnodes order. It returns the maximum id.
4233 unsigned SelectionDAG::AssignNodeIds() {
4235 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4242 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4243 /// based on their topological order. It returns the maximum id and a vector
4244 /// of the SDNodes* in assigned order by reference.
4245 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4246 unsigned DAGSize = AllNodes.size();
4247 std::vector<unsigned> InDegree(DAGSize);
4248 std::vector<SDNode*> Sources;
4250 // Use a two pass approach to avoid using a std::map which is slow.
4252 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4255 unsigned Degree = N->use_size();
4256 InDegree[N->getNodeId()] = Degree;
4258 Sources.push_back(N);
4262 TopOrder.reserve(DAGSize);
4263 while (!Sources.empty()) {
4264 SDNode *N = Sources.back();
4266 TopOrder.push_back(N);
4267 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4268 SDNode *P = I->getVal();
4269 unsigned Degree = --InDegree[P->getNodeId()];
4271 Sources.push_back(P);
4275 // Second pass, assign the actual topological order as node ids.
4277 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4279 (*TI)->setNodeId(Id++);
4286 //===----------------------------------------------------------------------===//
4288 //===----------------------------------------------------------------------===//
4290 // Out-of-line virtual method to give class a home.
4291 void SDNode::ANCHOR() {}
4292 void UnarySDNode::ANCHOR() {}
4293 void BinarySDNode::ANCHOR() {}
4294 void TernarySDNode::ANCHOR() {}
4295 void HandleSDNode::ANCHOR() {}
4296 void ConstantSDNode::ANCHOR() {}
4297 void ConstantFPSDNode::ANCHOR() {}
4298 void GlobalAddressSDNode::ANCHOR() {}
4299 void FrameIndexSDNode::ANCHOR() {}
4300 void JumpTableSDNode::ANCHOR() {}
4301 void ConstantPoolSDNode::ANCHOR() {}
4302 void BasicBlockSDNode::ANCHOR() {}
4303 void SrcValueSDNode::ANCHOR() {}
4304 void MemOperandSDNode::ANCHOR() {}
4305 void RegisterSDNode::ANCHOR() {}
4306 void DbgStopPointSDNode::ANCHOR() {}
4307 void LabelSDNode::ANCHOR() {}
4308 void ExternalSymbolSDNode::ANCHOR() {}
4309 void CondCodeSDNode::ANCHOR() {}
4310 void ARG_FLAGSSDNode::ANCHOR() {}
4311 void VTSDNode::ANCHOR() {}
4312 void MemSDNode::ANCHOR() {}
4313 void LoadSDNode::ANCHOR() {}
4314 void StoreSDNode::ANCHOR() {}
4315 void AtomicSDNode::ANCHOR() {}
4317 HandleSDNode::~HandleSDNode() {
4321 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4323 : SDNode(isa<GlobalVariable>(GA) &&
4324 cast<GlobalVariable>(GA)->isThreadLocal() ?
4326 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4328 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4329 getSDVTList(VT)), Offset(o) {
4330 TheGlobal = const_cast<GlobalValue*>(GA);
4333 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
4334 const Value *srcValue, int SVO,
4335 unsigned alignment, bool vol)
4336 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
4337 Flags(vol | ((Log2_32(alignment) + 1) << 1)) {
4339 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4340 assert(getAlignment() == alignment && "Alignment representation error!");
4341 assert(isVolatile() == vol && "Volatile representation error!");
4344 /// getMemOperand - Return a MachineMemOperand object describing the memory
4345 /// reference performed by this memory reference.
4346 MachineMemOperand MemSDNode::getMemOperand() const {
4348 if (isa<LoadSDNode>(this))
4349 Flags = MachineMemOperand::MOLoad;
4350 else if (isa<StoreSDNode>(this))
4351 Flags = MachineMemOperand::MOStore;
4353 assert(isa<AtomicSDNode>(this) && "Unknown MemSDNode opcode!");
4354 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4357 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4358 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4360 // Check if the memory reference references a frame index
4361 const FrameIndexSDNode *FI =
4362 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4363 if (!getSrcValue() && FI)
4364 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4365 FI->getIndex(), Size, getAlignment());
4367 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4368 Size, getAlignment());
4371 /// Profile - Gather unique data for the node.
4373 void SDNode::Profile(FoldingSetNodeID &ID) {
4374 AddNodeIDNode(ID, this);
4377 /// getValueTypeList - Return a pointer to the specified value type.
4379 const MVT *SDNode::getValueTypeList(MVT VT) {
4380 if (VT.isExtended()) {
4381 static std::set<MVT, MVT::compareRawBits> EVTs;
4382 return &(*EVTs.insert(VT).first);
4384 static MVT VTs[MVT::LAST_VALUETYPE];
4385 VTs[VT.getSimpleVT()] = VT;
4386 return &VTs[VT.getSimpleVT()];
4390 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4391 /// indicated value. This method ignores uses of other values defined by this
4393 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4394 assert(Value < getNumValues() && "Bad value!");
4396 // TODO: Only iterate over uses of a given value of the node
4397 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4398 if (UI->getSDOperand().ResNo == Value) {
4405 // Found exactly the right number of uses?
4410 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4411 /// value. This method ignores uses of other values defined by this operation.
4412 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4413 assert(Value < getNumValues() && "Bad value!");
4415 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
4416 if (UI->getSDOperand().ResNo == Value)
4423 /// isOnlyUseOf - Return true if this node is the only use of N.
4425 bool SDNode::isOnlyUseOf(SDNode *N) const {
4427 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4428 SDNode *User = I->getUser();
4438 /// isOperand - Return true if this node is an operand of N.
4440 bool SDOperand::isOperandOf(SDNode *N) const {
4441 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4442 if (*this == N->getOperand(i))
4447 bool SDNode::isOperandOf(SDNode *N) const {
4448 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4449 if (this == N->OperandList[i].getVal())
4454 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4455 /// be a chain) reaches the specified operand without crossing any
4456 /// side-effecting instructions. In practice, this looks through token
4457 /// factors and non-volatile loads. In order to remain efficient, this only
4458 /// looks a couple of nodes in, it does not do an exhaustive search.
4459 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4460 unsigned Depth) const {
4461 if (*this == Dest) return true;
4463 // Don't search too deeply, we just want to be able to see through
4464 // TokenFactor's etc.
4465 if (Depth == 0) return false;
4467 // If this is a token factor, all inputs to the TF happen in parallel. If any
4468 // of the operands of the TF reach dest, then we can do the xform.
4469 if (getOpcode() == ISD::TokenFactor) {
4470 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4471 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4476 // Loads don't have side effects, look through them.
4477 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4478 if (!Ld->isVolatile())
4479 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4485 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4486 SmallPtrSet<SDNode *, 32> &Visited) {
4487 if (found || !Visited.insert(N))
4490 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4491 SDNode *Op = N->getOperand(i).Val;
4496 findPredecessor(Op, P, found, Visited);
4500 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4501 /// is either an operand of N or it can be reached by recursively traversing
4502 /// up the operands.
4503 /// NOTE: this is an expensive method. Use it carefully.
4504 bool SDNode::isPredecessorOf(SDNode *N) const {
4505 SmallPtrSet<SDNode *, 32> Visited;
4507 findPredecessor(N, this, found, Visited);
4511 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4512 assert(Num < NumOperands && "Invalid child # of SDNode!");
4513 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4516 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4517 switch (getOpcode()) {
4519 if (getOpcode() < ISD::BUILTIN_OP_END)
4520 return "<<Unknown DAG Node>>";
4523 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4524 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4525 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4527 TargetLowering &TLI = G->getTargetLoweringInfo();
4529 TLI.getTargetNodeName(getOpcode());
4530 if (Name) return Name;
4533 return "<<Unknown Target Node>>";
4536 case ISD::PREFETCH: return "Prefetch";
4537 case ISD::MEMBARRIER: return "MemBarrier";
4538 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4539 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4540 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4541 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4542 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4543 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4544 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4545 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4546 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4547 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4548 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4549 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4550 case ISD::PCMARKER: return "PCMarker";
4551 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4552 case ISD::SRCVALUE: return "SrcValue";
4553 case ISD::MEMOPERAND: return "MemOperand";
4554 case ISD::EntryToken: return "EntryToken";
4555 case ISD::TokenFactor: return "TokenFactor";
4556 case ISD::AssertSext: return "AssertSext";
4557 case ISD::AssertZext: return "AssertZext";
4559 case ISD::BasicBlock: return "BasicBlock";
4560 case ISD::ARG_FLAGS: return "ArgFlags";
4561 case ISD::VALUETYPE: return "ValueType";
4562 case ISD::Register: return "Register";
4564 case ISD::Constant: return "Constant";
4565 case ISD::ConstantFP: return "ConstantFP";
4566 case ISD::GlobalAddress: return "GlobalAddress";
4567 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4568 case ISD::FrameIndex: return "FrameIndex";
4569 case ISD::JumpTable: return "JumpTable";
4570 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4571 case ISD::RETURNADDR: return "RETURNADDR";
4572 case ISD::FRAMEADDR: return "FRAMEADDR";
4573 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4574 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4575 case ISD::EHSELECTION: return "EHSELECTION";
4576 case ISD::EH_RETURN: return "EH_RETURN";
4577 case ISD::ConstantPool: return "ConstantPool";
4578 case ISD::ExternalSymbol: return "ExternalSymbol";
4579 case ISD::INTRINSIC_WO_CHAIN: {
4580 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4581 return Intrinsic::getName((Intrinsic::ID)IID);
4583 case ISD::INTRINSIC_VOID:
4584 case ISD::INTRINSIC_W_CHAIN: {
4585 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4586 return Intrinsic::getName((Intrinsic::ID)IID);
4589 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4590 case ISD::TargetConstant: return "TargetConstant";
4591 case ISD::TargetConstantFP:return "TargetConstantFP";
4592 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4593 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4594 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4595 case ISD::TargetJumpTable: return "TargetJumpTable";
4596 case ISD::TargetConstantPool: return "TargetConstantPool";
4597 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4599 case ISD::CopyToReg: return "CopyToReg";
4600 case ISD::CopyFromReg: return "CopyFromReg";
4601 case ISD::UNDEF: return "undef";
4602 case ISD::MERGE_VALUES: return "merge_values";
4603 case ISD::INLINEASM: return "inlineasm";
4604 case ISD::DBG_LABEL: return "dbg_label";
4605 case ISD::EH_LABEL: return "eh_label";
4606 case ISD::DECLARE: return "declare";
4607 case ISD::HANDLENODE: return "handlenode";
4608 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4609 case ISD::CALL: return "call";
4612 case ISD::FABS: return "fabs";
4613 case ISD::FNEG: return "fneg";
4614 case ISD::FSQRT: return "fsqrt";
4615 case ISD::FSIN: return "fsin";
4616 case ISD::FCOS: return "fcos";
4617 case ISD::FPOWI: return "fpowi";
4618 case ISD::FPOW: return "fpow";
4621 case ISD::ADD: return "add";
4622 case ISD::SUB: return "sub";
4623 case ISD::MUL: return "mul";
4624 case ISD::MULHU: return "mulhu";
4625 case ISD::MULHS: return "mulhs";
4626 case ISD::SDIV: return "sdiv";
4627 case ISD::UDIV: return "udiv";
4628 case ISD::SREM: return "srem";
4629 case ISD::UREM: return "urem";
4630 case ISD::SMUL_LOHI: return "smul_lohi";
4631 case ISD::UMUL_LOHI: return "umul_lohi";
4632 case ISD::SDIVREM: return "sdivrem";
4633 case ISD::UDIVREM: return "divrem";
4634 case ISD::AND: return "and";
4635 case ISD::OR: return "or";
4636 case ISD::XOR: return "xor";
4637 case ISD::SHL: return "shl";
4638 case ISD::SRA: return "sra";
4639 case ISD::SRL: return "srl";
4640 case ISD::ROTL: return "rotl";
4641 case ISD::ROTR: return "rotr";
4642 case ISD::FADD: return "fadd";
4643 case ISD::FSUB: return "fsub";
4644 case ISD::FMUL: return "fmul";
4645 case ISD::FDIV: return "fdiv";
4646 case ISD::FREM: return "frem";
4647 case ISD::FCOPYSIGN: return "fcopysign";
4648 case ISD::FGETSIGN: return "fgetsign";
4650 case ISD::SETCC: return "setcc";
4651 case ISD::VSETCC: return "vsetcc";
4652 case ISD::SELECT: return "select";
4653 case ISD::SELECT_CC: return "select_cc";
4654 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4655 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4656 case ISD::CONCAT_VECTORS: return "concat_vectors";
4657 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4658 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4659 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4660 case ISD::CARRY_FALSE: return "carry_false";
4661 case ISD::ADDC: return "addc";
4662 case ISD::ADDE: return "adde";
4663 case ISD::SUBC: return "subc";
4664 case ISD::SUBE: return "sube";
4665 case ISD::SHL_PARTS: return "shl_parts";
4666 case ISD::SRA_PARTS: return "sra_parts";
4667 case ISD::SRL_PARTS: return "srl_parts";
4669 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4670 case ISD::INSERT_SUBREG: return "insert_subreg";
4672 // Conversion operators.
4673 case ISD::SIGN_EXTEND: return "sign_extend";
4674 case ISD::ZERO_EXTEND: return "zero_extend";
4675 case ISD::ANY_EXTEND: return "any_extend";
4676 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4677 case ISD::TRUNCATE: return "truncate";
4678 case ISD::FP_ROUND: return "fp_round";
4679 case ISD::FLT_ROUNDS_: return "flt_rounds";
4680 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4681 case ISD::FP_EXTEND: return "fp_extend";
4683 case ISD::SINT_TO_FP: return "sint_to_fp";
4684 case ISD::UINT_TO_FP: return "uint_to_fp";
4685 case ISD::FP_TO_SINT: return "fp_to_sint";
4686 case ISD::FP_TO_UINT: return "fp_to_uint";
4687 case ISD::BIT_CONVERT: return "bit_convert";
4689 // Control flow instructions
4690 case ISD::BR: return "br";
4691 case ISD::BRIND: return "brind";
4692 case ISD::BR_JT: return "br_jt";
4693 case ISD::BRCOND: return "brcond";
4694 case ISD::BR_CC: return "br_cc";
4695 case ISD::RET: return "ret";
4696 case ISD::CALLSEQ_START: return "callseq_start";
4697 case ISD::CALLSEQ_END: return "callseq_end";
4700 case ISD::LOAD: return "load";
4701 case ISD::STORE: return "store";
4702 case ISD::VAARG: return "vaarg";
4703 case ISD::VACOPY: return "vacopy";
4704 case ISD::VAEND: return "vaend";
4705 case ISD::VASTART: return "vastart";
4706 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4707 case ISD::EXTRACT_ELEMENT: return "extract_element";
4708 case ISD::BUILD_PAIR: return "build_pair";
4709 case ISD::STACKSAVE: return "stacksave";
4710 case ISD::STACKRESTORE: return "stackrestore";
4711 case ISD::TRAP: return "trap";
4714 case ISD::BSWAP: return "bswap";
4715 case ISD::CTPOP: return "ctpop";
4716 case ISD::CTTZ: return "cttz";
4717 case ISD::CTLZ: return "ctlz";
4720 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4721 case ISD::DEBUG_LOC: return "debug_loc";
4724 case ISD::TRAMPOLINE: return "trampoline";
4727 switch (cast<CondCodeSDNode>(this)->get()) {
4728 default: assert(0 && "Unknown setcc condition!");
4729 case ISD::SETOEQ: return "setoeq";
4730 case ISD::SETOGT: return "setogt";
4731 case ISD::SETOGE: return "setoge";
4732 case ISD::SETOLT: return "setolt";
4733 case ISD::SETOLE: return "setole";
4734 case ISD::SETONE: return "setone";
4736 case ISD::SETO: return "seto";
4737 case ISD::SETUO: return "setuo";
4738 case ISD::SETUEQ: return "setue";
4739 case ISD::SETUGT: return "setugt";
4740 case ISD::SETUGE: return "setuge";
4741 case ISD::SETULT: return "setult";
4742 case ISD::SETULE: return "setule";
4743 case ISD::SETUNE: return "setune";
4745 case ISD::SETEQ: return "seteq";
4746 case ISD::SETGT: return "setgt";
4747 case ISD::SETGE: return "setge";
4748 case ISD::SETLT: return "setlt";
4749 case ISD::SETLE: return "setle";
4750 case ISD::SETNE: return "setne";
4755 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4764 return "<post-inc>";
4766 return "<post-dec>";
4770 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4771 std::string S = "< ";
4785 if (getByValAlign())
4786 S += "byval-align:" + utostr(getByValAlign()) + " ";
4788 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4790 S += "byval-size:" + utostr(getByValSize()) + " ";
4794 void SDNode::dump() const { dump(0); }
4795 void SDNode::dump(const SelectionDAG *G) const {
4796 cerr << (void*)this << ": ";
4798 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4800 if (getValueType(i) == MVT::Other)
4803 cerr << getValueType(i).getMVTString();
4805 cerr << " = " << getOperationName(G);
4808 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4809 if (i) cerr << ", ";
4810 cerr << (void*)getOperand(i).Val;
4811 if (unsigned RN = getOperand(i).ResNo)
4815 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4816 SDNode *Mask = getOperand(2).Val;
4818 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4820 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4823 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4828 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4829 cerr << "<" << CSDN->getAPIntValue().toStringUnsigned() << ">";
4830 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4831 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4832 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4833 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4834 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4836 cerr << "<APFloat(";
4837 CSDN->getValueAPF().convertToAPInt().dump();
4840 } else if (const GlobalAddressSDNode *GADN =
4841 dyn_cast<GlobalAddressSDNode>(this)) {
4842 int offset = GADN->getOffset();
4844 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4846 cerr << " + " << offset;
4848 cerr << " " << offset;
4849 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4850 cerr << "<" << FIDN->getIndex() << ">";
4851 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4852 cerr << "<" << JTDN->getIndex() << ">";
4853 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4854 int offset = CP->getOffset();
4855 if (CP->isMachineConstantPoolEntry())
4856 cerr << "<" << *CP->getMachineCPVal() << ">";
4858 cerr << "<" << *CP->getConstVal() << ">";
4860 cerr << " + " << offset;
4862 cerr << " " << offset;
4863 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4865 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4867 cerr << LBB->getName() << " ";
4868 cerr << (const void*)BBDN->getBasicBlock() << ">";
4869 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4870 if (G && R->getReg() &&
4871 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4872 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4874 cerr << " #" << R->getReg();
4876 } else if (const ExternalSymbolSDNode *ES =
4877 dyn_cast<ExternalSymbolSDNode>(this)) {
4878 cerr << "'" << ES->getSymbol() << "'";
4879 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4881 cerr << "<" << M->getValue() << ">";
4884 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4885 if (M->MO.getValue())
4886 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4888 cerr << "<null:" << M->MO.getOffset() << ">";
4889 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4890 cerr << N->getArgFlags().getArgFlagsString();
4891 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4892 cerr << ":" << N->getVT().getMVTString();
4894 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4895 const Value *SrcValue = LD->getSrcValue();
4896 int SrcOffset = LD->getSrcValueOffset();
4902 cerr << ":" << SrcOffset << ">";
4905 switch (LD->getExtensionType()) {
4906 default: doExt = false; break;
4908 cerr << " <anyext ";
4918 cerr << LD->getMemoryVT().getMVTString() << ">";
4920 const char *AM = getIndexedModeName(LD->getAddressingMode());
4923 if (LD->isVolatile())
4924 cerr << " <volatile>";
4925 cerr << " alignment=" << LD->getAlignment();
4926 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4927 const Value *SrcValue = ST->getSrcValue();
4928 int SrcOffset = ST->getSrcValueOffset();
4934 cerr << ":" << SrcOffset << ">";
4936 if (ST->isTruncatingStore())
4938 << ST->getMemoryVT().getMVTString() << ">";
4940 const char *AM = getIndexedModeName(ST->getAddressingMode());
4943 if (ST->isVolatile())
4944 cerr << " <volatile>";
4945 cerr << " alignment=" << ST->getAlignment();
4946 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4947 const Value *SrcValue = AT->getSrcValue();
4948 int SrcOffset = AT->getSrcValueOffset();
4954 cerr << ":" << SrcOffset << ">";
4955 if (AT->isVolatile())
4956 cerr << " <volatile>";
4957 cerr << " alignment=" << AT->getAlignment();
4961 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4962 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4963 if (N->getOperand(i).Val->hasOneUse())
4964 DumpNodes(N->getOperand(i).Val, indent+2, G);
4966 cerr << "\n" << std::string(indent+2, ' ')
4967 << (void*)N->getOperand(i).Val << ": <multiple use>";
4970 cerr << "\n" << std::string(indent, ' ');
4974 void SelectionDAG::dump() const {
4975 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4976 std::vector<const SDNode*> Nodes;
4977 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4981 std::sort(Nodes.begin(), Nodes.end());
4983 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4984 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4985 DumpNodes(Nodes[i], 2, this);
4988 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4993 const Type *ConstantPoolSDNode::getType() const {
4994 if (isMachineConstantPoolEntry())
4995 return Val.MachineCPVal->getType();
4996 return Val.ConstVal->getType();