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);
745 SelectionDAG::~SelectionDAG() {
746 while (!AllNodes.empty()) {
747 SDNode *N = AllNodes.begin();
748 N->SetNextInBucket(0);
749 if (N->OperandsNeedDelete) {
750 delete [] N->OperandList;
754 AllNodes.pop_front();
758 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
759 if (Op.getValueType() == VT) return Op;
760 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
762 return getNode(ISD::AND, Op.getValueType(), Op,
763 getConstant(Imm, Op.getValueType()));
766 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
767 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
768 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
771 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
772 assert(VT.isInteger() && "Cannot create FP integer constant!");
774 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
775 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
776 "APInt size does not match type size!");
778 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
780 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
784 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
786 return SDOperand(N, 0);
788 N = getAllocator().Allocate<ConstantSDNode>();
789 new (N) ConstantSDNode(isT, Val, EltVT);
790 CSEMap.InsertNode(N, IP);
791 AllNodes.push_back(N);
794 SDOperand Result(N, 0);
796 SmallVector<SDOperand, 8> Ops;
797 Ops.assign(VT.getVectorNumElements(), Result);
798 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
803 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
804 return getConstant(Val, TLI.getPointerTy(), isTarget);
808 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
809 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
812 VT.isVector() ? VT.getVectorElementType() : VT;
814 // Do the map lookup using the actual bit pattern for the floating point
815 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
816 // we don't have issues with SNANs.
817 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
819 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
823 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
825 return SDOperand(N, 0);
827 N = getAllocator().Allocate<ConstantFPSDNode>();
828 new (N) ConstantFPSDNode(isTarget, V, EltVT);
829 CSEMap.InsertNode(N, IP);
830 AllNodes.push_back(N);
833 SDOperand Result(N, 0);
835 SmallVector<SDOperand, 8> Ops;
836 Ops.assign(VT.getVectorNumElements(), Result);
837 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
842 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
844 VT.isVector() ? VT.getVectorElementType() : VT;
846 return getConstantFP(APFloat((float)Val), VT, isTarget);
848 return getConstantFP(APFloat(Val), VT, isTarget);
851 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
856 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
858 // If GV is an alias then use the aliasee for determining thread-localness.
859 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
860 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
863 if (GVar && GVar->isThreadLocal())
864 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
866 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
869 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
871 ID.AddInteger(Offset);
873 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
874 return SDOperand(E, 0);
875 SDNode *N = getAllocator().Allocate<GlobalAddressSDNode>();
876 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
877 CSEMap.InsertNode(N, IP);
878 AllNodes.push_back(N);
879 return SDOperand(N, 0);
882 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
883 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
885 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
888 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
889 return SDOperand(E, 0);
890 SDNode *N = getAllocator().Allocate<FrameIndexSDNode>();
891 new (N) FrameIndexSDNode(FI, VT, isTarget);
892 CSEMap.InsertNode(N, IP);
893 AllNodes.push_back(N);
894 return SDOperand(N, 0);
897 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
898 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
900 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
903 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
904 return SDOperand(E, 0);
905 SDNode *N = getAllocator().Allocate<JumpTableSDNode>();
906 new (N) JumpTableSDNode(JTI, VT, isTarget);
907 CSEMap.InsertNode(N, IP);
908 AllNodes.push_back(N);
909 return SDOperand(N, 0);
912 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
913 unsigned Alignment, int Offset,
915 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
917 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
918 ID.AddInteger(Alignment);
919 ID.AddInteger(Offset);
922 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
923 return SDOperand(E, 0);
924 SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
925 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
926 CSEMap.InsertNode(N, IP);
927 AllNodes.push_back(N);
928 return SDOperand(N, 0);
932 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
933 unsigned Alignment, int Offset,
935 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
937 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
938 ID.AddInteger(Alignment);
939 ID.AddInteger(Offset);
940 C->AddSelectionDAGCSEId(ID);
942 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
943 return SDOperand(E, 0);
944 SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
945 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
946 CSEMap.InsertNode(N, IP);
947 AllNodes.push_back(N);
948 return SDOperand(N, 0);
952 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
954 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
957 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
958 return SDOperand(E, 0);
959 SDNode *N = getAllocator().Allocate<BasicBlockSDNode>();
960 new (N) BasicBlockSDNode(MBB);
961 CSEMap.InsertNode(N, IP);
962 AllNodes.push_back(N);
963 return SDOperand(N, 0);
966 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
968 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
969 ID.AddInteger(Flags.getRawBits());
971 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
972 return SDOperand(E, 0);
973 SDNode *N = getAllocator().Allocate<ARG_FLAGSSDNode>();
974 new (N) ARG_FLAGSSDNode(Flags);
975 CSEMap.InsertNode(N, IP);
976 AllNodes.push_back(N);
977 return SDOperand(N, 0);
980 SDOperand SelectionDAG::getValueType(MVT VT) {
981 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
982 ValueTypeNodes.resize(VT.getSimpleVT()+1);
984 SDNode *&N = VT.isExtended() ?
985 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
987 if (N) return SDOperand(N, 0);
988 N = getAllocator().Allocate<VTSDNode>();
989 new (N) VTSDNode(VT);
990 AllNodes.push_back(N);
991 return SDOperand(N, 0);
994 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
995 SDNode *&N = ExternalSymbols[Sym];
996 if (N) return SDOperand(N, 0);
997 N = getAllocator().Allocate<ExternalSymbolSDNode>();
998 new (N) ExternalSymbolSDNode(false, Sym, VT);
999 AllNodes.push_back(N);
1000 return SDOperand(N, 0);
1003 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1004 SDNode *&N = TargetExternalSymbols[Sym];
1005 if (N) return SDOperand(N, 0);
1006 N = getAllocator().Allocate<ExternalSymbolSDNode>();
1007 new (N) ExternalSymbolSDNode(true, Sym, VT);
1008 AllNodes.push_back(N);
1009 return SDOperand(N, 0);
1012 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
1013 if ((unsigned)Cond >= CondCodeNodes.size())
1014 CondCodeNodes.resize(Cond+1);
1016 if (CondCodeNodes[Cond] == 0) {
1017 CondCodeSDNode *N = getAllocator().Allocate<CondCodeSDNode>();
1018 new (N) CondCodeSDNode(Cond);
1019 CondCodeNodes[Cond] = N;
1020 AllNodes.push_back(N);
1022 return SDOperand(CondCodeNodes[Cond], 0);
1025 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1026 FoldingSetNodeID ID;
1027 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1028 ID.AddInteger(RegNo);
1030 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1031 return SDOperand(E, 0);
1032 SDNode *N = getAllocator().Allocate<RegisterSDNode>();
1033 new (N) RegisterSDNode(RegNo, VT);
1034 CSEMap.InsertNode(N, IP);
1035 AllNodes.push_back(N);
1036 return SDOperand(N, 0);
1039 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
1040 unsigned Line, unsigned Col,
1041 const CompileUnitDesc *CU) {
1042 SDNode *N = getAllocator().Allocate<DbgStopPointSDNode>();
1043 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1044 AllNodes.push_back(N);
1045 return SDOperand(N, 0);
1048 SDOperand SelectionDAG::getLabel(unsigned Opcode,
1051 FoldingSetNodeID ID;
1052 SDOperand Ops[] = { Root };
1053 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1054 ID.AddInteger(LabelID);
1056 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1057 return SDOperand(E, 0);
1058 SDNode *N = getAllocator().Allocate<LabelSDNode>();
1059 new (N) LabelSDNode(Opcode, Root, LabelID);
1060 CSEMap.InsertNode(N, IP);
1061 AllNodes.push_back(N);
1062 return SDOperand(N, 0);
1065 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1066 assert((!V || isa<PointerType>(V->getType())) &&
1067 "SrcValue is not a pointer?");
1069 FoldingSetNodeID ID;
1070 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1074 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1075 return SDOperand(E, 0);
1077 SDNode *N = getAllocator().Allocate<SrcValueSDNode>();
1078 new (N) SrcValueSDNode(V);
1079 CSEMap.InsertNode(N, IP);
1080 AllNodes.push_back(N);
1081 return SDOperand(N, 0);
1084 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1085 const Value *v = MO.getValue();
1086 assert((!v || isa<PointerType>(v->getType())) &&
1087 "SrcValue is not a pointer?");
1089 FoldingSetNodeID ID;
1090 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1092 ID.AddInteger(MO.getFlags());
1093 ID.AddInteger(MO.getOffset());
1094 ID.AddInteger(MO.getSize());
1095 ID.AddInteger(MO.getAlignment());
1098 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1099 return SDOperand(E, 0);
1101 SDNode *N = getAllocator().Allocate<MemOperandSDNode>();
1102 new (N) MemOperandSDNode(MO);
1103 CSEMap.InsertNode(N, IP);
1104 AllNodes.push_back(N);
1105 return SDOperand(N, 0);
1108 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1109 /// specified value type.
1110 SDOperand SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1111 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1112 unsigned ByteSize = VT.getSizeInBits()/8;
1113 const Type *Ty = VT.getTypeForMVT();
1114 unsigned StackAlign =
1115 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1117 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1118 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1121 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1122 SDOperand N2, ISD::CondCode Cond) {
1123 // These setcc operations always fold.
1127 case ISD::SETFALSE2: return getConstant(0, VT);
1129 case ISD::SETTRUE2: return getConstant(1, VT);
1141 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1145 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1146 const APInt &C2 = N2C->getAPIntValue();
1147 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1148 const APInt &C1 = N1C->getAPIntValue();
1151 default: assert(0 && "Unknown integer setcc!");
1152 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1153 case ISD::SETNE: return getConstant(C1 != C2, VT);
1154 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1155 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1156 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1157 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1158 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1159 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1160 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1161 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1165 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1166 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1167 // No compile time operations on this type yet.
1168 if (N1C->getValueType(0) == MVT::ppcf128)
1171 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1174 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1175 return getNode(ISD::UNDEF, VT);
1177 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1178 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1179 return getNode(ISD::UNDEF, VT);
1181 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1182 R==APFloat::cmpLessThan, VT);
1183 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1184 return getNode(ISD::UNDEF, VT);
1186 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1187 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1188 return getNode(ISD::UNDEF, VT);
1190 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1191 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1192 return getNode(ISD::UNDEF, VT);
1194 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1195 R==APFloat::cmpEqual, VT);
1196 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1197 return getNode(ISD::UNDEF, VT);
1199 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1200 R==APFloat::cmpEqual, VT);
1201 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1202 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1203 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1204 R==APFloat::cmpEqual, VT);
1205 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1206 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1207 R==APFloat::cmpLessThan, VT);
1208 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1209 R==APFloat::cmpUnordered, VT);
1210 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1211 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1214 // Ensure that the constant occurs on the RHS.
1215 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1219 // Could not fold it.
1223 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1224 /// use this predicate to simplify operations downstream.
1225 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1226 unsigned BitWidth = Op.getValueSizeInBits();
1227 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1230 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1231 /// this predicate to simplify operations downstream. Mask is known to be zero
1232 /// for bits that V cannot have.
1233 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1234 unsigned Depth) const {
1235 APInt KnownZero, KnownOne;
1236 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1237 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1238 return (KnownZero & Mask) == Mask;
1241 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1242 /// known to be either zero or one and return them in the KnownZero/KnownOne
1243 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1245 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1246 APInt &KnownZero, APInt &KnownOne,
1247 unsigned Depth) const {
1248 unsigned BitWidth = Mask.getBitWidth();
1249 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1250 "Mask size mismatches value type size!");
1252 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1253 if (Depth == 6 || Mask == 0)
1254 return; // Limit search depth.
1256 APInt KnownZero2, KnownOne2;
1258 switch (Op.getOpcode()) {
1260 // We know all of the bits for a constant!
1261 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1262 KnownZero = ~KnownOne & Mask;
1265 // If either the LHS or the RHS are Zero, the result is zero.
1266 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1267 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1268 KnownZero2, KnownOne2, Depth+1);
1269 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1270 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1272 // Output known-1 bits are only known if set in both the LHS & RHS.
1273 KnownOne &= KnownOne2;
1274 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1275 KnownZero |= KnownZero2;
1278 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1279 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1280 KnownZero2, KnownOne2, Depth+1);
1281 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1282 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1284 // Output known-0 bits are only known if clear in both the LHS & RHS.
1285 KnownZero &= KnownZero2;
1286 // Output known-1 are known to be set if set in either the LHS | RHS.
1287 KnownOne |= KnownOne2;
1290 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1291 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1292 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1293 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1295 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1296 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1297 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1298 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1299 KnownZero = KnownZeroOut;
1303 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1304 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1305 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1306 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1307 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1309 // If low bits are zero in either operand, output low known-0 bits.
1310 // Also compute a conserative estimate for high known-0 bits.
1311 // More trickiness is possible, but this is sufficient for the
1312 // interesting case of alignment computation.
1314 unsigned TrailZ = KnownZero.countTrailingOnes() +
1315 KnownZero2.countTrailingOnes();
1316 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1317 KnownZero2.countLeadingOnes(),
1318 BitWidth) - BitWidth;
1320 TrailZ = std::min(TrailZ, BitWidth);
1321 LeadZ = std::min(LeadZ, BitWidth);
1322 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1323 APInt::getHighBitsSet(BitWidth, LeadZ);
1328 // For the purposes of computing leading zeros we can conservatively
1329 // treat a udiv as a logical right shift by the power of 2 known to
1330 // be less than the denominator.
1331 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1332 ComputeMaskedBits(Op.getOperand(0),
1333 AllOnes, KnownZero2, KnownOne2, Depth+1);
1334 unsigned LeadZ = KnownZero2.countLeadingOnes();
1338 ComputeMaskedBits(Op.getOperand(1),
1339 AllOnes, KnownZero2, KnownOne2, Depth+1);
1340 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1341 if (RHSUnknownLeadingOnes != BitWidth)
1342 LeadZ = std::min(BitWidth,
1343 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1345 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1349 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1350 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1351 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1352 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1354 // Only known if known in both the LHS and RHS.
1355 KnownOne &= KnownOne2;
1356 KnownZero &= KnownZero2;
1358 case ISD::SELECT_CC:
1359 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1360 ComputeMaskedBits(Op.getOperand(2), 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;
1369 // If we know the result of a setcc has the top bits zero, use this info.
1370 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1372 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1375 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1376 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1377 unsigned ShAmt = SA->getValue();
1379 // If the shift count is an invalid immediate, don't do anything.
1380 if (ShAmt >= BitWidth)
1383 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1384 KnownZero, KnownOne, Depth+1);
1385 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1386 KnownZero <<= ShAmt;
1388 // low bits known zero.
1389 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1393 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1394 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1395 unsigned ShAmt = SA->getValue();
1397 // If the shift count is an invalid immediate, don't do anything.
1398 if (ShAmt >= BitWidth)
1401 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1402 KnownZero, KnownOne, Depth+1);
1403 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1404 KnownZero = KnownZero.lshr(ShAmt);
1405 KnownOne = KnownOne.lshr(ShAmt);
1407 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1408 KnownZero |= HighBits; // High bits known zero.
1412 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1413 unsigned ShAmt = SA->getValue();
1415 // If the shift count is an invalid immediate, don't do anything.
1416 if (ShAmt >= BitWidth)
1419 APInt InDemandedMask = (Mask << ShAmt);
1420 // If any of the demanded bits are produced by the sign extension, we also
1421 // demand the input sign bit.
1422 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1423 if (HighBits.getBoolValue())
1424 InDemandedMask |= APInt::getSignBit(BitWidth);
1426 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1428 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1429 KnownZero = KnownZero.lshr(ShAmt);
1430 KnownOne = KnownOne.lshr(ShAmt);
1432 // Handle the sign bits.
1433 APInt SignBit = APInt::getSignBit(BitWidth);
1434 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1436 if (KnownZero.intersects(SignBit)) {
1437 KnownZero |= HighBits; // New bits are known zero.
1438 } else if (KnownOne.intersects(SignBit)) {
1439 KnownOne |= HighBits; // New bits are known one.
1443 case ISD::SIGN_EXTEND_INREG: {
1444 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1445 unsigned EBits = EVT.getSizeInBits();
1447 // Sign extension. Compute the demanded bits in the result that are not
1448 // present in the input.
1449 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1451 APInt InSignBit = APInt::getSignBit(EBits);
1452 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1454 // If the sign extended bits are demanded, we know that the sign
1456 InSignBit.zext(BitWidth);
1457 if (NewBits.getBoolValue())
1458 InputDemandedBits |= InSignBit;
1460 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1461 KnownZero, KnownOne, Depth+1);
1462 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1464 // If the sign bit of the input is known set or clear, then we know the
1465 // top bits of the result.
1466 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1467 KnownZero |= NewBits;
1468 KnownOne &= ~NewBits;
1469 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1470 KnownOne |= NewBits;
1471 KnownZero &= ~NewBits;
1472 } else { // Input sign bit unknown
1473 KnownZero &= ~NewBits;
1474 KnownOne &= ~NewBits;
1481 unsigned LowBits = Log2_32(BitWidth)+1;
1482 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1487 if (ISD::isZEXTLoad(Op.Val)) {
1488 LoadSDNode *LD = cast<LoadSDNode>(Op);
1489 MVT VT = LD->getMemoryVT();
1490 unsigned MemBits = VT.getSizeInBits();
1491 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1495 case ISD::ZERO_EXTEND: {
1496 MVT InVT = Op.getOperand(0).getValueType();
1497 unsigned InBits = InVT.getSizeInBits();
1498 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1499 APInt InMask = Mask;
1500 InMask.trunc(InBits);
1501 KnownZero.trunc(InBits);
1502 KnownOne.trunc(InBits);
1503 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1504 KnownZero.zext(BitWidth);
1505 KnownOne.zext(BitWidth);
1506 KnownZero |= NewBits;
1509 case ISD::SIGN_EXTEND: {
1510 MVT InVT = Op.getOperand(0).getValueType();
1511 unsigned InBits = InVT.getSizeInBits();
1512 APInt InSignBit = APInt::getSignBit(InBits);
1513 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1514 APInt InMask = Mask;
1515 InMask.trunc(InBits);
1517 // If any of the sign extended bits are demanded, we know that the sign
1518 // bit is demanded. Temporarily set this bit in the mask for our callee.
1519 if (NewBits.getBoolValue())
1520 InMask |= InSignBit;
1522 KnownZero.trunc(InBits);
1523 KnownOne.trunc(InBits);
1524 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1526 // Note if the sign bit is known to be zero or one.
1527 bool SignBitKnownZero = KnownZero.isNegative();
1528 bool SignBitKnownOne = KnownOne.isNegative();
1529 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1530 "Sign bit can't be known to be both zero and one!");
1532 // If the sign bit wasn't actually demanded by our caller, we don't
1533 // want it set in the KnownZero and KnownOne result values. Reset the
1534 // mask and reapply it to the result values.
1536 InMask.trunc(InBits);
1537 KnownZero &= InMask;
1540 KnownZero.zext(BitWidth);
1541 KnownOne.zext(BitWidth);
1543 // If the sign bit is known zero or one, the top bits match.
1544 if (SignBitKnownZero)
1545 KnownZero |= NewBits;
1546 else if (SignBitKnownOne)
1547 KnownOne |= NewBits;
1550 case ISD::ANY_EXTEND: {
1551 MVT InVT = Op.getOperand(0).getValueType();
1552 unsigned InBits = InVT.getSizeInBits();
1553 APInt InMask = Mask;
1554 InMask.trunc(InBits);
1555 KnownZero.trunc(InBits);
1556 KnownOne.trunc(InBits);
1557 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1558 KnownZero.zext(BitWidth);
1559 KnownOne.zext(BitWidth);
1562 case ISD::TRUNCATE: {
1563 MVT InVT = Op.getOperand(0).getValueType();
1564 unsigned InBits = InVT.getSizeInBits();
1565 APInt InMask = Mask;
1566 InMask.zext(InBits);
1567 KnownZero.zext(InBits);
1568 KnownOne.zext(InBits);
1569 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1570 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1571 KnownZero.trunc(BitWidth);
1572 KnownOne.trunc(BitWidth);
1575 case ISD::AssertZext: {
1576 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1577 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1578 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1580 KnownZero |= (~InMask) & Mask;
1584 // All bits are zero except the low bit.
1585 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1589 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1590 // We know that the top bits of C-X are clear if X contains less bits
1591 // than C (i.e. no wrap-around can happen). For example, 20-X is
1592 // positive if we can prove that X is >= 0 and < 16.
1593 if (CLHS->getAPIntValue().isNonNegative()) {
1594 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1595 // NLZ can't be BitWidth with no sign bit
1596 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1597 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1600 // If all of the MaskV bits are known to be zero, then we know the
1601 // output top bits are zero, because we now know that the output is
1603 if ((KnownZero2 & MaskV) == MaskV) {
1604 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1605 // Top bits known zero.
1606 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1613 // Output known-0 bits are known if clear or set in both the low clear bits
1614 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1615 // low 3 bits clear.
1616 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1617 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1618 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1619 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1621 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1622 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1623 KnownZeroOut = std::min(KnownZeroOut,
1624 KnownZero2.countTrailingOnes());
1626 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1630 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1631 const APInt &RA = Rem->getAPIntValue();
1632 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1633 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1634 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1635 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1637 // The sign of a remainder is equal to the sign of the first
1638 // operand (zero being positive).
1639 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1640 KnownZero2 |= ~LowBits;
1641 else if (KnownOne2[BitWidth-1])
1642 KnownOne2 |= ~LowBits;
1644 KnownZero |= KnownZero2 & Mask;
1645 KnownOne |= KnownOne2 & Mask;
1647 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1652 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1653 const APInt &RA = Rem->getAPIntValue();
1654 if (RA.isPowerOf2()) {
1655 APInt LowBits = (RA - 1);
1656 APInt Mask2 = LowBits & Mask;
1657 KnownZero |= ~LowBits & Mask;
1658 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1659 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1664 // Since the result is less than or equal to either operand, any leading
1665 // zero bits in either operand must also exist in the result.
1666 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1667 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1669 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1672 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1673 KnownZero2.countLeadingOnes());
1675 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1679 // Allow the target to implement this method for its nodes.
1680 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1681 case ISD::INTRINSIC_WO_CHAIN:
1682 case ISD::INTRINSIC_W_CHAIN:
1683 case ISD::INTRINSIC_VOID:
1684 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1690 /// ComputeNumSignBits - Return the number of times the sign bit of the
1691 /// register is replicated into the other bits. We know that at least 1 bit
1692 /// is always equal to the sign bit (itself), but other cases can give us
1693 /// information. For example, immediately after an "SRA X, 2", we know that
1694 /// the top 3 bits are all equal to each other, so we return 3.
1695 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1696 MVT VT = Op.getValueType();
1697 assert(VT.isInteger() && "Invalid VT!");
1698 unsigned VTBits = VT.getSizeInBits();
1700 unsigned FirstAnswer = 1;
1703 return 1; // Limit search depth.
1705 switch (Op.getOpcode()) {
1707 case ISD::AssertSext:
1708 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1709 return VTBits-Tmp+1;
1710 case ISD::AssertZext:
1711 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1714 case ISD::Constant: {
1715 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1716 // If negative, return # leading ones.
1717 if (Val.isNegative())
1718 return Val.countLeadingOnes();
1720 // Return # leading zeros.
1721 return Val.countLeadingZeros();
1724 case ISD::SIGN_EXTEND:
1725 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1726 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1728 case ISD::SIGN_EXTEND_INREG:
1729 // Max of the input and what this extends.
1730 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1733 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1734 return std::max(Tmp, Tmp2);
1737 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1738 // SRA X, C -> adds C sign bits.
1739 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1740 Tmp += C->getValue();
1741 if (Tmp > VTBits) Tmp = VTBits;
1745 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1746 // shl destroys sign bits.
1747 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1748 if (C->getValue() >= VTBits || // Bad shift.
1749 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1750 return Tmp - C->getValue();
1755 case ISD::XOR: // NOT is handled here.
1756 // Logical binary ops preserve the number of sign bits at the worst.
1757 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1759 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1760 FirstAnswer = std::min(Tmp, Tmp2);
1761 // We computed what we know about the sign bits as our first
1762 // answer. Now proceed to the generic code that uses
1763 // ComputeMaskedBits, and pick whichever answer is better.
1768 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1769 if (Tmp == 1) return 1; // Early out.
1770 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1771 return std::min(Tmp, Tmp2);
1774 // If setcc returns 0/-1, all bits are sign bits.
1775 if (TLI.getSetCCResultContents() ==
1776 TargetLowering::ZeroOrNegativeOneSetCCResult)
1781 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1782 unsigned RotAmt = C->getValue() & (VTBits-1);
1784 // Handle rotate right by N like a rotate left by 32-N.
1785 if (Op.getOpcode() == ISD::ROTR)
1786 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1788 // If we aren't rotating out all of the known-in sign bits, return the
1789 // number that are left. This handles rotl(sext(x), 1) for example.
1790 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1791 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1795 // Add can have at most one carry bit. Thus we know that the output
1796 // is, at worst, one more bit than the inputs.
1797 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1798 if (Tmp == 1) return 1; // Early out.
1800 // Special case decrementing a value (ADD X, -1):
1801 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1802 if (CRHS->isAllOnesValue()) {
1803 APInt KnownZero, KnownOne;
1804 APInt Mask = APInt::getAllOnesValue(VTBits);
1805 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1807 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1809 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1812 // If we are subtracting one from a positive number, there is no carry
1813 // out of the result.
1814 if (KnownZero.isNegative())
1818 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1819 if (Tmp2 == 1) return 1;
1820 return std::min(Tmp, Tmp2)-1;
1824 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1825 if (Tmp2 == 1) return 1;
1828 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1829 if (CLHS->isNullValue()) {
1830 APInt KnownZero, KnownOne;
1831 APInt Mask = APInt::getAllOnesValue(VTBits);
1832 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1833 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1835 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1838 // If the input is known to be positive (the sign bit is known clear),
1839 // the output of the NEG has the same number of sign bits as the input.
1840 if (KnownZero.isNegative())
1843 // Otherwise, we treat this like a SUB.
1846 // Sub can have at most one carry bit. Thus we know that the output
1847 // is, at worst, one more bit than the inputs.
1848 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1849 if (Tmp == 1) return 1; // Early out.
1850 return std::min(Tmp, Tmp2)-1;
1853 // FIXME: it's tricky to do anything useful for this, but it is an important
1854 // case for targets like X86.
1858 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1859 if (Op.getOpcode() == ISD::LOAD) {
1860 LoadSDNode *LD = cast<LoadSDNode>(Op);
1861 unsigned ExtType = LD->getExtensionType();
1864 case ISD::SEXTLOAD: // '17' bits known
1865 Tmp = LD->getMemoryVT().getSizeInBits();
1866 return VTBits-Tmp+1;
1867 case ISD::ZEXTLOAD: // '16' bits known
1868 Tmp = LD->getMemoryVT().getSizeInBits();
1873 // Allow the target to implement this method for its nodes.
1874 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1875 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1876 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1877 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1878 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1879 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1882 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1883 // use this information.
1884 APInt KnownZero, KnownOne;
1885 APInt Mask = APInt::getAllOnesValue(VTBits);
1886 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1888 if (KnownZero.isNegative()) { // sign bit is 0
1890 } else if (KnownOne.isNegative()) { // sign bit is 1;
1897 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1898 // the number of identical bits in the top of the input value.
1900 Mask <<= Mask.getBitWidth()-VTBits;
1901 // Return # leading zeros. We use 'min' here in case Val was zero before
1902 // shifting. We don't want to return '64' as for an i32 "0".
1903 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1907 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1908 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1909 if (!GA) return false;
1910 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1911 if (!GV) return false;
1912 MachineModuleInfo *MMI = getMachineModuleInfo();
1913 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1917 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1918 /// element of the result of the vector shuffle.
1919 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1920 MVT VT = N->getValueType(0);
1921 SDOperand PermMask = N->getOperand(2);
1922 SDOperand Idx = PermMask.getOperand(i);
1923 if (Idx.getOpcode() == ISD::UNDEF)
1924 return getNode(ISD::UNDEF, VT.getVectorElementType());
1925 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1926 unsigned NumElems = PermMask.getNumOperands();
1927 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1930 if (V.getOpcode() == ISD::BIT_CONVERT) {
1931 V = V.getOperand(0);
1932 if (V.getValueType().getVectorNumElements() != NumElems)
1935 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1936 return (Index == 0) ? V.getOperand(0)
1937 : getNode(ISD::UNDEF, VT.getVectorElementType());
1938 if (V.getOpcode() == ISD::BUILD_VECTOR)
1939 return V.getOperand(Index);
1940 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1941 return getShuffleScalarElt(V.Val, Index);
1946 /// getNode - Gets or creates the specified node.
1948 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1949 FoldingSetNodeID ID;
1950 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1952 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1953 return SDOperand(E, 0);
1954 SDNode *N = getAllocator().Allocate<SDNode>();
1955 new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
1956 CSEMap.InsertNode(N, IP);
1958 AllNodes.push_back(N);
1959 return SDOperand(N, 0);
1962 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1963 // Constant fold unary operations with an integer constant operand.
1964 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1965 const APInt &Val = C->getAPIntValue();
1966 unsigned BitWidth = VT.getSizeInBits();
1969 case ISD::SIGN_EXTEND:
1970 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1971 case ISD::ANY_EXTEND:
1972 case ISD::ZERO_EXTEND:
1974 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1975 case ISD::UINT_TO_FP:
1976 case ISD::SINT_TO_FP: {
1977 const uint64_t zero[] = {0, 0};
1978 // No compile time operations on this type.
1979 if (VT==MVT::ppcf128)
1981 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1982 (void)apf.convertFromAPInt(Val,
1983 Opcode==ISD::SINT_TO_FP,
1984 APFloat::rmNearestTiesToEven);
1985 return getConstantFP(apf, VT);
1987 case ISD::BIT_CONVERT:
1988 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1989 return getConstantFP(Val.bitsToFloat(), VT);
1990 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1991 return getConstantFP(Val.bitsToDouble(), VT);
1994 return getConstant(Val.byteSwap(), VT);
1996 return getConstant(Val.countPopulation(), VT);
1998 return getConstant(Val.countLeadingZeros(), VT);
2000 return getConstant(Val.countTrailingZeros(), VT);
2004 // Constant fold unary operations with a floating point constant operand.
2005 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
2006 APFloat V = C->getValueAPF(); // make copy
2007 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2011 return getConstantFP(V, VT);
2014 return getConstantFP(V, VT);
2016 case ISD::FP_EXTEND:
2017 // This can return overflow, underflow, or inexact; we don't care.
2018 // FIXME need to be more flexible about rounding mode.
2019 (void)V.convert(*MVTToAPFloatSemantics(VT),
2020 APFloat::rmNearestTiesToEven);
2021 return getConstantFP(V, VT);
2022 case ISD::FP_TO_SINT:
2023 case ISD::FP_TO_UINT: {
2025 assert(integerPartWidth >= 64);
2026 // FIXME need to be more flexible about rounding mode.
2027 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2028 Opcode==ISD::FP_TO_SINT,
2029 APFloat::rmTowardZero);
2030 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2032 return getConstant(x, VT);
2034 case ISD::BIT_CONVERT:
2035 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2036 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2037 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2038 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2044 unsigned OpOpcode = Operand.Val->getOpcode();
2046 case ISD::TokenFactor:
2047 return Operand; // Factor of one node? No need.
2048 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2049 case ISD::FP_EXTEND:
2050 assert(VT.isFloatingPoint() &&
2051 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2052 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2053 if (Operand.getOpcode() == ISD::UNDEF)
2054 return getNode(ISD::UNDEF, VT);
2056 case ISD::SIGN_EXTEND:
2057 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2058 "Invalid SIGN_EXTEND!");
2059 if (Operand.getValueType() == VT) return Operand; // noop extension
2060 assert(Operand.getValueType().bitsLT(VT)
2061 && "Invalid sext node, dst < src!");
2062 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2063 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2065 case ISD::ZERO_EXTEND:
2066 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2067 "Invalid ZERO_EXTEND!");
2068 if (Operand.getValueType() == VT) return Operand; // noop extension
2069 assert(Operand.getValueType().bitsLT(VT)
2070 && "Invalid zext node, dst < src!");
2071 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2072 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2074 case ISD::ANY_EXTEND:
2075 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2076 "Invalid ANY_EXTEND!");
2077 if (Operand.getValueType() == VT) return Operand; // noop extension
2078 assert(Operand.getValueType().bitsLT(VT)
2079 && "Invalid anyext node, dst < src!");
2080 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2081 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2082 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2085 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2086 "Invalid TRUNCATE!");
2087 if (Operand.getValueType() == VT) return Operand; // noop truncate
2088 assert(Operand.getValueType().bitsGT(VT)
2089 && "Invalid truncate node, src < dst!");
2090 if (OpOpcode == ISD::TRUNCATE)
2091 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2092 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2093 OpOpcode == ISD::ANY_EXTEND) {
2094 // If the source is smaller than the dest, we still need an extend.
2095 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2096 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2097 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2098 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2100 return Operand.Val->getOperand(0);
2103 case ISD::BIT_CONVERT:
2104 // Basic sanity checking.
2105 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2106 && "Cannot BIT_CONVERT between types of different sizes!");
2107 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2108 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2109 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2110 if (OpOpcode == ISD::UNDEF)
2111 return getNode(ISD::UNDEF, VT);
2113 case ISD::SCALAR_TO_VECTOR:
2114 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2115 VT.getVectorElementType() == Operand.getValueType() &&
2116 "Illegal SCALAR_TO_VECTOR node!");
2117 if (OpOpcode == ISD::UNDEF)
2118 return getNode(ISD::UNDEF, VT);
2119 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2120 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2121 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2122 Operand.getConstantOperandVal(1) == 0 &&
2123 Operand.getOperand(0).getValueType() == VT)
2124 return Operand.getOperand(0);
2127 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2128 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2129 Operand.Val->getOperand(0));
2130 if (OpOpcode == ISD::FNEG) // --X -> X
2131 return Operand.Val->getOperand(0);
2134 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2135 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2140 SDVTList VTs = getVTList(VT);
2141 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2142 FoldingSetNodeID ID;
2143 SDOperand Ops[1] = { Operand };
2144 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2146 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2147 return SDOperand(E, 0);
2148 N = getAllocator().Allocate<UnarySDNode>();
2149 new (N) UnarySDNode(Opcode, VTs, Operand);
2150 CSEMap.InsertNode(N, IP);
2152 N = getAllocator().Allocate<UnarySDNode>();
2153 new (N) UnarySDNode(Opcode, VTs, Operand);
2155 AllNodes.push_back(N);
2156 return SDOperand(N, 0);
2161 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2162 SDOperand N1, SDOperand N2) {
2163 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2164 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2167 case ISD::TokenFactor:
2168 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2169 N2.getValueType() == MVT::Other && "Invalid token factor!");
2170 // Fold trivial token factors.
2171 if (N1.getOpcode() == ISD::EntryToken) return N2;
2172 if (N2.getOpcode() == ISD::EntryToken) return N1;
2175 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2176 N1.getValueType() == VT && "Binary operator types must match!");
2177 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2178 // worth handling here.
2179 if (N2C && N2C->isNullValue())
2181 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2188 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2189 N1.getValueType() == VT && "Binary operator types must match!");
2190 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2191 // it's worth handling here.
2192 if (N2C && N2C->isNullValue())
2199 assert(VT.isInteger() && "This operator does not apply to FP types!");
2209 assert(N1.getValueType() == N2.getValueType() &&
2210 N1.getValueType() == VT && "Binary operator types must match!");
2212 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2213 assert(N1.getValueType() == VT &&
2214 N1.getValueType().isFloatingPoint() &&
2215 N2.getValueType().isFloatingPoint() &&
2216 "Invalid FCOPYSIGN!");
2223 assert(VT == N1.getValueType() &&
2224 "Shift operators return type must be the same as their first arg");
2225 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2226 "Shifts only work on integers");
2228 // Always fold shifts of i1 values so the code generator doesn't need to
2229 // handle them. Since we know the size of the shift has to be less than the
2230 // size of the value, the shift/rotate count is guaranteed to be zero.
2234 case ISD::FP_ROUND_INREG: {
2235 MVT EVT = cast<VTSDNode>(N2)->getVT();
2236 assert(VT == N1.getValueType() && "Not an inreg round!");
2237 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2238 "Cannot FP_ROUND_INREG integer types");
2239 assert(EVT.bitsLE(VT) && "Not rounding down!");
2240 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2244 assert(VT.isFloatingPoint() &&
2245 N1.getValueType().isFloatingPoint() &&
2246 VT.bitsLE(N1.getValueType()) &&
2247 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2248 if (N1.getValueType() == VT) return N1; // noop conversion.
2250 case ISD::AssertSext:
2251 case ISD::AssertZext: {
2252 MVT EVT = cast<VTSDNode>(N2)->getVT();
2253 assert(VT == N1.getValueType() && "Not an inreg extend!");
2254 assert(VT.isInteger() && EVT.isInteger() &&
2255 "Cannot *_EXTEND_INREG FP types");
2256 assert(EVT.bitsLE(VT) && "Not extending!");
2257 if (VT == EVT) return N1; // noop assertion.
2260 case ISD::SIGN_EXTEND_INREG: {
2261 MVT EVT = cast<VTSDNode>(N2)->getVT();
2262 assert(VT == N1.getValueType() && "Not an inreg extend!");
2263 assert(VT.isInteger() && EVT.isInteger() &&
2264 "Cannot *_EXTEND_INREG FP types");
2265 assert(EVT.bitsLE(VT) && "Not extending!");
2266 if (EVT == VT) return N1; // Not actually extending
2269 APInt Val = N1C->getAPIntValue();
2270 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2271 Val <<= Val.getBitWidth()-FromBits;
2272 Val = Val.ashr(Val.getBitWidth()-FromBits);
2273 return getConstant(Val, VT);
2277 case ISD::EXTRACT_VECTOR_ELT:
2278 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2280 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2281 if (N1.getOpcode() == ISD::UNDEF)
2282 return getNode(ISD::UNDEF, VT);
2284 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2285 // expanding copies of large vectors from registers.
2286 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2287 N1.getNumOperands() > 0) {
2289 N1.getOperand(0).getValueType().getVectorNumElements();
2290 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2291 N1.getOperand(N2C->getValue() / Factor),
2292 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2295 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2296 // expanding large vector constants.
2297 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2298 return N1.getOperand(N2C->getValue());
2300 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2301 // operations are lowered to scalars.
2302 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2303 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2305 return N1.getOperand(1);
2307 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2310 case ISD::EXTRACT_ELEMENT:
2311 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2312 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2313 (N1.getValueType().isInteger() == VT.isInteger()) &&
2314 "Wrong types for EXTRACT_ELEMENT!");
2316 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2317 // 64-bit integers into 32-bit parts. Instead of building the extract of
2318 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2319 if (N1.getOpcode() == ISD::BUILD_PAIR)
2320 return N1.getOperand(N2C->getValue());
2322 // EXTRACT_ELEMENT of a constant int is also very common.
2323 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2324 unsigned ElementSize = VT.getSizeInBits();
2325 unsigned Shift = ElementSize * N2C->getValue();
2326 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2327 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2330 case ISD::EXTRACT_SUBVECTOR:
2331 if (N1.getValueType() == VT) // Trivial extraction.
2338 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2340 case ISD::ADD: return getConstant(C1 + C2, VT);
2341 case ISD::SUB: return getConstant(C1 - C2, VT);
2342 case ISD::MUL: return getConstant(C1 * C2, VT);
2344 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2347 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2350 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2353 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2355 case ISD::AND : return getConstant(C1 & C2, VT);
2356 case ISD::OR : return getConstant(C1 | C2, VT);
2357 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2358 case ISD::SHL : return getConstant(C1 << C2, VT);
2359 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2360 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2361 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2362 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2365 } else { // Cannonicalize constant to RHS if commutative
2366 if (isCommutativeBinOp(Opcode)) {
2367 std::swap(N1C, N2C);
2373 // Constant fold FP operations.
2374 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2375 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2377 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2378 // Cannonicalize constant to RHS if commutative
2379 std::swap(N1CFP, N2CFP);
2381 } else if (N2CFP && VT != MVT::ppcf128) {
2382 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2383 APFloat::opStatus s;
2386 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2387 if (s != APFloat::opInvalidOp)
2388 return getConstantFP(V1, VT);
2391 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2392 if (s!=APFloat::opInvalidOp)
2393 return getConstantFP(V1, VT);
2396 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2397 if (s!=APFloat::opInvalidOp)
2398 return getConstantFP(V1, VT);
2401 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2402 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2403 return getConstantFP(V1, VT);
2406 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2407 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2408 return getConstantFP(V1, VT);
2410 case ISD::FCOPYSIGN:
2412 return getConstantFP(V1, VT);
2418 // Canonicalize an UNDEF to the RHS, even over a constant.
2419 if (N1.getOpcode() == ISD::UNDEF) {
2420 if (isCommutativeBinOp(Opcode)) {
2424 case ISD::FP_ROUND_INREG:
2425 case ISD::SIGN_EXTEND_INREG:
2431 return N1; // fold op(undef, arg2) -> undef
2439 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2440 // For vectors, we can't easily build an all zero vector, just return
2447 // Fold a bunch of operators when the RHS is undef.
2448 if (N2.getOpcode() == ISD::UNDEF) {
2451 if (N1.getOpcode() == ISD::UNDEF)
2452 // Handle undef ^ undef -> 0 special case. This is a common
2454 return getConstant(0, VT);
2469 return N2; // fold op(arg1, undef) -> undef
2475 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2476 // For vectors, we can't easily build an all zero vector, just return
2481 return getConstant(VT.getIntegerVTBitMask(), VT);
2482 // For vectors, we can't easily build an all one vector, just return
2490 // Memoize this node if possible.
2492 SDVTList VTs = getVTList(VT);
2493 if (VT != MVT::Flag) {
2494 SDOperand Ops[] = { N1, N2 };
2495 FoldingSetNodeID ID;
2496 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2498 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2499 return SDOperand(E, 0);
2500 N = getAllocator().Allocate<BinarySDNode>();
2501 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2502 CSEMap.InsertNode(N, IP);
2504 N = getAllocator().Allocate<BinarySDNode>();
2505 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2508 AllNodes.push_back(N);
2509 return SDOperand(N, 0);
2512 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2513 SDOperand N1, SDOperand N2, SDOperand N3) {
2514 // Perform various simplifications.
2515 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2516 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2519 // Use FoldSetCC to simplify SETCC's.
2520 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2521 if (Simp.Val) return Simp;
2526 if (N1C->getValue())
2527 return N2; // select true, X, Y -> X
2529 return N3; // select false, X, Y -> Y
2532 if (N2 == N3) return N2; // select C, X, X -> X
2536 if (N2C->getValue()) // Unconditional branch
2537 return getNode(ISD::BR, MVT::Other, N1, N3);
2539 return N1; // Never-taken branch
2542 case ISD::VECTOR_SHUFFLE:
2543 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2544 VT.isVector() && N3.getValueType().isVector() &&
2545 N3.getOpcode() == ISD::BUILD_VECTOR &&
2546 VT.getVectorNumElements() == N3.getNumOperands() &&
2547 "Illegal VECTOR_SHUFFLE node!");
2549 case ISD::BIT_CONVERT:
2550 // Fold bit_convert nodes from a type to themselves.
2551 if (N1.getValueType() == VT)
2556 // Memoize node if it doesn't produce a flag.
2558 SDVTList VTs = getVTList(VT);
2559 if (VT != MVT::Flag) {
2560 SDOperand Ops[] = { N1, N2, N3 };
2561 FoldingSetNodeID ID;
2562 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2564 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2565 return SDOperand(E, 0);
2566 N = getAllocator().Allocate<TernarySDNode>();
2567 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2568 CSEMap.InsertNode(N, IP);
2570 N = getAllocator().Allocate<TernarySDNode>();
2571 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2573 AllNodes.push_back(N);
2574 return SDOperand(N, 0);
2577 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2578 SDOperand N1, SDOperand N2, SDOperand N3,
2580 SDOperand Ops[] = { N1, N2, N3, N4 };
2581 return getNode(Opcode, VT, Ops, 4);
2584 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2585 SDOperand N1, SDOperand N2, SDOperand N3,
2586 SDOperand N4, SDOperand N5) {
2587 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2588 return getNode(Opcode, VT, Ops, 5);
2591 /// getMemsetValue - Vectorized representation of the memset value
2593 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2594 unsigned NumBits = VT.isVector() ?
2595 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2596 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2597 APInt Val = APInt(NumBits, C->getValue() & 255);
2599 for (unsigned i = NumBits; i > 8; i >>= 1) {
2600 Val = (Val << Shift) | Val;
2604 return DAG.getConstant(Val, VT);
2605 return DAG.getConstantFP(APFloat(Val), VT);
2608 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2610 for (unsigned i = NumBits; i > 8; i >>= 1) {
2611 Value = DAG.getNode(ISD::OR, VT,
2612 DAG.getNode(ISD::SHL, VT, Value,
2613 DAG.getConstant(Shift, MVT::i8)), Value);
2620 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2621 /// used when a memcpy is turned into a memset when the source is a constant
2623 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2624 const TargetLowering &TLI,
2625 std::string &Str, unsigned Offset) {
2626 // Handle vector with all elements zero.
2629 return DAG.getConstant(0, VT);
2630 unsigned NumElts = VT.getVectorNumElements();
2631 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2632 return DAG.getNode(ISD::BIT_CONVERT, VT,
2633 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2636 assert(!VT.isVector() && "Can't handle vector type here!");
2637 unsigned NumBits = VT.getSizeInBits();
2638 unsigned MSB = NumBits / 8;
2640 if (TLI.isLittleEndian())
2641 Offset = Offset + MSB - 1;
2642 for (unsigned i = 0; i != MSB; ++i) {
2643 Val = (Val << 8) | (unsigned char)Str[Offset];
2644 Offset += TLI.isLittleEndian() ? -1 : 1;
2646 return DAG.getConstant(Val, VT);
2649 /// getMemBasePlusOffset - Returns base and offset node for the
2651 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2652 SelectionDAG &DAG) {
2653 MVT VT = Base.getValueType();
2654 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2657 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2659 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2660 unsigned SrcDelta = 0;
2661 GlobalAddressSDNode *G = NULL;
2662 if (Src.getOpcode() == ISD::GlobalAddress)
2663 G = cast<GlobalAddressSDNode>(Src);
2664 else if (Src.getOpcode() == ISD::ADD &&
2665 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2666 Src.getOperand(1).getOpcode() == ISD::Constant) {
2667 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2668 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2673 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2674 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2680 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2681 /// to replace the memset / memcpy is below the threshold. It also returns the
2682 /// types of the sequence of memory ops to perform memset / memcpy.
2684 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2685 SDOperand Dst, SDOperand Src,
2686 unsigned Limit, uint64_t Size, unsigned &Align,
2687 std::string &Str, bool &isSrcStr,
2689 const TargetLowering &TLI) {
2690 isSrcStr = isMemSrcFromString(Src, Str);
2691 bool isSrcConst = isa<ConstantSDNode>(Src);
2692 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2693 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2694 if (VT != MVT::iAny) {
2695 unsigned NewAlign = (unsigned)
2696 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2697 // If source is a string constant, this will require an unaligned load.
2698 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2699 if (Dst.getOpcode() != ISD::FrameIndex) {
2700 // Can't change destination alignment. It requires a unaligned store.
2704 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2705 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2706 if (MFI->isFixedObjectIndex(FI)) {
2707 // Can't change destination alignment. It requires a unaligned store.
2711 // Give the stack frame object a larger alignment if needed.
2712 if (MFI->getObjectAlignment(FI) < NewAlign)
2713 MFI->setObjectAlignment(FI, NewAlign);
2720 if (VT == MVT::iAny) {
2724 switch (Align & 7) {
2725 case 0: VT = MVT::i64; break;
2726 case 4: VT = MVT::i32; break;
2727 case 2: VT = MVT::i16; break;
2728 default: VT = MVT::i8; break;
2733 while (!TLI.isTypeLegal(LVT))
2734 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2735 assert(LVT.isInteger());
2741 unsigned NumMemOps = 0;
2743 unsigned VTSize = VT.getSizeInBits() / 8;
2744 while (VTSize > Size) {
2745 // For now, only use non-vector load / store's for the left-over pieces.
2746 if (VT.isVector()) {
2748 while (!TLI.isTypeLegal(VT))
2749 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2750 VTSize = VT.getSizeInBits() / 8;
2752 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2757 if (++NumMemOps > Limit)
2759 MemOps.push_back(VT);
2766 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2767 SDOperand Chain, SDOperand Dst,
2768 SDOperand Src, uint64_t Size,
2769 unsigned Align, bool AlwaysInline,
2770 const Value *DstSV, uint64_t DstSVOff,
2771 const Value *SrcSV, uint64_t SrcSVOff){
2772 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2774 // Expand memcpy to a series of load and store ops if the size operand falls
2775 // below a certain threshold.
2776 std::vector<MVT> MemOps;
2777 uint64_t Limit = -1;
2779 Limit = TLI.getMaxStoresPerMemcpy();
2780 unsigned DstAlign = Align; // Destination alignment can change.
2783 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2784 Str, CopyFromStr, DAG, TLI))
2788 bool isZeroStr = CopyFromStr && Str.empty();
2789 SmallVector<SDOperand, 8> OutChains;
2790 unsigned NumMemOps = MemOps.size();
2791 uint64_t SrcOff = 0, DstOff = 0;
2792 for (unsigned i = 0; i < NumMemOps; i++) {
2794 unsigned VTSize = VT.getSizeInBits() / 8;
2795 SDOperand Value, Store;
2797 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2798 // It's unlikely a store of a vector immediate can be done in a single
2799 // instruction. It would require a load from a constantpool first.
2800 // We also handle store a vector with all zero's.
2801 // FIXME: Handle other cases where store of vector immediate is done in
2802 // a single instruction.
2803 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2804 Store = DAG.getStore(Chain, Value,
2805 getMemBasePlusOffset(Dst, DstOff, DAG),
2806 DstSV, DstSVOff + DstOff);
2808 Value = DAG.getLoad(VT, Chain,
2809 getMemBasePlusOffset(Src, SrcOff, DAG),
2810 SrcSV, SrcSVOff + SrcOff, false, Align);
2811 Store = DAG.getStore(Chain, Value,
2812 getMemBasePlusOffset(Dst, DstOff, DAG),
2813 DstSV, DstSVOff + DstOff, false, DstAlign);
2815 OutChains.push_back(Store);
2820 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2821 &OutChains[0], OutChains.size());
2824 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2825 SDOperand Chain, SDOperand Dst,
2826 SDOperand Src, uint64_t Size,
2827 unsigned Align, bool AlwaysInline,
2828 const Value *DstSV, uint64_t DstSVOff,
2829 const Value *SrcSV, uint64_t SrcSVOff){
2830 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2832 // Expand memmove to a series of load and store ops if the size operand falls
2833 // below a certain threshold.
2834 std::vector<MVT> MemOps;
2835 uint64_t Limit = -1;
2837 Limit = TLI.getMaxStoresPerMemmove();
2838 unsigned DstAlign = Align; // Destination alignment can change.
2841 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2842 Str, CopyFromStr, DAG, TLI))
2845 uint64_t SrcOff = 0, DstOff = 0;
2847 SmallVector<SDOperand, 8> LoadValues;
2848 SmallVector<SDOperand, 8> LoadChains;
2849 SmallVector<SDOperand, 8> OutChains;
2850 unsigned NumMemOps = MemOps.size();
2851 for (unsigned i = 0; i < NumMemOps; i++) {
2853 unsigned VTSize = VT.getSizeInBits() / 8;
2854 SDOperand Value, Store;
2856 Value = DAG.getLoad(VT, Chain,
2857 getMemBasePlusOffset(Src, SrcOff, DAG),
2858 SrcSV, SrcSVOff + SrcOff, false, Align);
2859 LoadValues.push_back(Value);
2860 LoadChains.push_back(Value.getValue(1));
2863 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2864 &LoadChains[0], LoadChains.size());
2866 for (unsigned i = 0; i < NumMemOps; i++) {
2868 unsigned VTSize = VT.getSizeInBits() / 8;
2869 SDOperand Value, Store;
2871 Store = DAG.getStore(Chain, LoadValues[i],
2872 getMemBasePlusOffset(Dst, DstOff, DAG),
2873 DstSV, DstSVOff + DstOff, false, DstAlign);
2874 OutChains.push_back(Store);
2878 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2879 &OutChains[0], OutChains.size());
2882 static SDOperand getMemsetStores(SelectionDAG &DAG,
2883 SDOperand Chain, SDOperand Dst,
2884 SDOperand Src, uint64_t Size,
2886 const Value *DstSV, uint64_t DstSVOff) {
2887 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2889 // Expand memset to a series of load/store ops if the size operand
2890 // falls below a certain threshold.
2891 std::vector<MVT> MemOps;
2894 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2895 Size, Align, Str, CopyFromStr, DAG, TLI))
2898 SmallVector<SDOperand, 8> OutChains;
2899 uint64_t DstOff = 0;
2901 unsigned NumMemOps = MemOps.size();
2902 for (unsigned i = 0; i < NumMemOps; i++) {
2904 unsigned VTSize = VT.getSizeInBits() / 8;
2905 SDOperand Value = getMemsetValue(Src, VT, DAG);
2906 SDOperand Store = DAG.getStore(Chain, Value,
2907 getMemBasePlusOffset(Dst, DstOff, DAG),
2908 DstSV, DstSVOff + DstOff);
2909 OutChains.push_back(Store);
2913 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2914 &OutChains[0], OutChains.size());
2917 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2918 SDOperand Src, SDOperand Size,
2919 unsigned Align, bool AlwaysInline,
2920 const Value *DstSV, uint64_t DstSVOff,
2921 const Value *SrcSV, uint64_t SrcSVOff) {
2923 // Check to see if we should lower the memcpy to loads and stores first.
2924 // For cases within the target-specified limits, this is the best choice.
2925 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2927 // Memcpy with size zero? Just return the original chain.
2928 if (ConstantSize->isNullValue())
2932 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2933 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2938 // Then check to see if we should lower the memcpy with target-specific
2939 // code. If the target chooses to do this, this is the next best.
2941 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2943 DstSV, DstSVOff, SrcSV, SrcSVOff);
2947 // If we really need inline code and the target declined to provide it,
2948 // use a (potentially long) sequence of loads and stores.
2950 assert(ConstantSize && "AlwaysInline requires a constant size!");
2951 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2952 ConstantSize->getValue(), Align, true,
2953 DstSV, DstSVOff, SrcSV, SrcSVOff);
2956 // Emit a library call.
2957 TargetLowering::ArgListTy Args;
2958 TargetLowering::ArgListEntry Entry;
2959 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2960 Entry.Node = Dst; Args.push_back(Entry);
2961 Entry.Node = Src; Args.push_back(Entry);
2962 Entry.Node = Size; Args.push_back(Entry);
2963 std::pair<SDOperand,SDOperand> CallResult =
2964 TLI.LowerCallTo(Chain, Type::VoidTy,
2965 false, false, false, CallingConv::C, false,
2966 getExternalSymbol("memcpy", TLI.getPointerTy()),
2968 return CallResult.second;
2971 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2972 SDOperand Src, SDOperand Size,
2974 const Value *DstSV, uint64_t DstSVOff,
2975 const Value *SrcSV, uint64_t SrcSVOff) {
2977 // Check to see if we should lower the memmove to loads and stores first.
2978 // For cases within the target-specified limits, this is the best choice.
2979 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2981 // Memmove with size zero? Just return the original chain.
2982 if (ConstantSize->isNullValue())
2986 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2987 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2992 // Then check to see if we should lower the memmove with target-specific
2993 // code. If the target chooses to do this, this is the next best.
2995 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2996 DstSV, DstSVOff, SrcSV, SrcSVOff);
3000 // Emit a library call.
3001 TargetLowering::ArgListTy Args;
3002 TargetLowering::ArgListEntry Entry;
3003 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3004 Entry.Node = Dst; Args.push_back(Entry);
3005 Entry.Node = Src; Args.push_back(Entry);
3006 Entry.Node = Size; Args.push_back(Entry);
3007 std::pair<SDOperand,SDOperand> CallResult =
3008 TLI.LowerCallTo(Chain, Type::VoidTy,
3009 false, false, false, CallingConv::C, false,
3010 getExternalSymbol("memmove", TLI.getPointerTy()),
3012 return CallResult.second;
3015 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
3016 SDOperand Src, SDOperand Size,
3018 const Value *DstSV, uint64_t DstSVOff) {
3020 // Check to see if we should lower the memset to stores first.
3021 // For cases within the target-specified limits, this is the best choice.
3022 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3024 // Memset with size zero? Just return the original chain.
3025 if (ConstantSize->isNullValue())
3029 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3035 // Then check to see if we should lower the memset with target-specific
3036 // code. If the target chooses to do this, this is the next best.
3038 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3043 // Emit a library call.
3044 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3045 TargetLowering::ArgListTy Args;
3046 TargetLowering::ArgListEntry Entry;
3047 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3048 Args.push_back(Entry);
3049 // Extend or truncate the argument to be an i32 value for the call.
3050 if (Src.getValueType().bitsGT(MVT::i32))
3051 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3053 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3054 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3055 Args.push_back(Entry);
3056 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3057 Args.push_back(Entry);
3058 std::pair<SDOperand,SDOperand> CallResult =
3059 TLI.LowerCallTo(Chain, Type::VoidTy,
3060 false, false, false, CallingConv::C, false,
3061 getExternalSymbol("memset", TLI.getPointerTy()),
3063 return CallResult.second;
3066 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3067 SDOperand Ptr, SDOperand Cmp,
3068 SDOperand Swp, const Value* PtrVal,
3069 unsigned Alignment) {
3070 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3071 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3072 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
3073 FoldingSetNodeID ID;
3074 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3075 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3077 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3078 return SDOperand(E, 0);
3079 SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3080 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3081 CSEMap.InsertNode(N, IP);
3082 AllNodes.push_back(N);
3083 return SDOperand(N, 0);
3086 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3087 SDOperand Ptr, SDOperand Val,
3088 const Value* PtrVal,
3089 unsigned Alignment) {
3090 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3091 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3092 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3093 || Opcode == ISD::ATOMIC_LOAD_NAND
3094 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3095 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3096 && "Invalid Atomic Op");
3097 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3098 FoldingSetNodeID ID;
3099 SDOperand Ops[] = {Chain, Ptr, Val};
3100 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3102 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3103 return SDOperand(E, 0);
3104 SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3105 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
3106 CSEMap.InsertNode(N, IP);
3107 AllNodes.push_back(N);
3108 return SDOperand(N, 0);
3111 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3112 /// Allowed to return something different (and simpler) if Simplify is true.
3113 SDOperand SelectionDAG::getMergeValues(const SDOperand *Ops, unsigned NumOps,
3115 if (Simplify && NumOps == 1)
3118 SmallVector<MVT, 4> VTs;
3119 VTs.reserve(NumOps);
3120 for (unsigned i = 0; i < NumOps; ++i)
3121 VTs.push_back(Ops[i].getValueType());
3122 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3126 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3127 MVT VT, SDOperand Chain,
3128 SDOperand Ptr, SDOperand Offset,
3129 const Value *SV, int SVOffset, MVT EVT,
3130 bool isVolatile, unsigned Alignment) {
3131 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3133 if (VT != MVT::iPTR) {
3134 Ty = VT.getTypeForMVT();
3136 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3137 assert(PT && "Value for load must be a pointer");
3138 Ty = PT->getElementType();
3140 assert(Ty && "Could not get type information for load");
3141 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3145 ExtType = ISD::NON_EXTLOAD;
3146 } else if (ExtType == ISD::NON_EXTLOAD) {
3147 assert(VT == EVT && "Non-extending load from different memory type!");
3151 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3153 assert(EVT.bitsLT(VT) &&
3154 "Should only be an extending load, not truncating!");
3155 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3156 "Cannot sign/zero extend a FP/Vector load!");
3157 assert(VT.isInteger() == EVT.isInteger() &&
3158 "Cannot convert from FP to Int or Int -> FP!");
3161 bool Indexed = AM != ISD::UNINDEXED;
3162 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3163 "Unindexed load with an offset!");
3165 SDVTList VTs = Indexed ?
3166 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3167 SDOperand Ops[] = { Chain, Ptr, Offset };
3168 FoldingSetNodeID ID;
3169 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3171 ID.AddInteger(ExtType);
3172 ID.AddInteger(EVT.getRawBits());
3173 ID.AddInteger(Alignment);
3174 ID.AddInteger(isVolatile);
3176 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3177 return SDOperand(E, 0);
3178 SDNode *N = getAllocator().Allocate<LoadSDNode>();
3179 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3180 Alignment, isVolatile);
3181 CSEMap.InsertNode(N, IP);
3182 AllNodes.push_back(N);
3183 return SDOperand(N, 0);
3186 SDOperand SelectionDAG::getLoad(MVT VT,
3187 SDOperand Chain, SDOperand Ptr,
3188 const Value *SV, int SVOffset,
3189 bool isVolatile, unsigned Alignment) {
3190 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3191 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3192 SV, SVOffset, VT, isVolatile, Alignment);
3195 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3196 SDOperand Chain, SDOperand Ptr,
3198 int SVOffset, MVT EVT,
3199 bool isVolatile, unsigned Alignment) {
3200 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3201 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3202 SV, SVOffset, EVT, isVolatile, Alignment);
3206 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3207 SDOperand Offset, ISD::MemIndexedMode AM) {
3208 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3209 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3210 "Load is already a indexed load!");
3211 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3212 LD->getChain(), Base, Offset, LD->getSrcValue(),
3213 LD->getSrcValueOffset(), LD->getMemoryVT(),
3214 LD->isVolatile(), LD->getAlignment());
3217 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3218 SDOperand Ptr, const Value *SV, int SVOffset,
3219 bool isVolatile, unsigned Alignment) {
3220 MVT VT = Val.getValueType();
3222 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3224 if (VT != MVT::iPTR) {
3225 Ty = VT.getTypeForMVT();
3227 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3228 assert(PT && "Value for store must be a pointer");
3229 Ty = PT->getElementType();
3231 assert(Ty && "Could not get type information for store");
3232 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3234 SDVTList VTs = getVTList(MVT::Other);
3235 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3236 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3237 FoldingSetNodeID ID;
3238 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3239 ID.AddInteger(ISD::UNINDEXED);
3240 ID.AddInteger(false);
3241 ID.AddInteger(VT.getRawBits());
3242 ID.AddInteger(Alignment);
3243 ID.AddInteger(isVolatile);
3245 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3246 return SDOperand(E, 0);
3247 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3248 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3249 VT, SV, SVOffset, Alignment, isVolatile);
3250 CSEMap.InsertNode(N, IP);
3251 AllNodes.push_back(N);
3252 return SDOperand(N, 0);
3255 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3256 SDOperand Ptr, const Value *SV,
3257 int SVOffset, MVT SVT,
3258 bool isVolatile, unsigned Alignment) {
3259 MVT VT = Val.getValueType();
3262 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3264 assert(VT.bitsGT(SVT) && "Not a truncation?");
3265 assert(VT.isInteger() == SVT.isInteger() &&
3266 "Can't do FP-INT conversion!");
3268 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3270 if (VT != MVT::iPTR) {
3271 Ty = VT.getTypeForMVT();
3273 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3274 assert(PT && "Value for store must be a pointer");
3275 Ty = PT->getElementType();
3277 assert(Ty && "Could not get type information for store");
3278 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3280 SDVTList VTs = getVTList(MVT::Other);
3281 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3282 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3283 FoldingSetNodeID ID;
3284 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3285 ID.AddInteger(ISD::UNINDEXED);
3287 ID.AddInteger(SVT.getRawBits());
3288 ID.AddInteger(Alignment);
3289 ID.AddInteger(isVolatile);
3291 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3292 return SDOperand(E, 0);
3293 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3294 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3295 SVT, SV, SVOffset, Alignment, isVolatile);
3296 CSEMap.InsertNode(N, IP);
3297 AllNodes.push_back(N);
3298 return SDOperand(N, 0);
3302 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3303 SDOperand Offset, ISD::MemIndexedMode AM) {
3304 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3305 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3306 "Store is already a indexed store!");
3307 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3308 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3309 FoldingSetNodeID ID;
3310 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3312 ID.AddInteger(ST->isTruncatingStore());
3313 ID.AddInteger(ST->getMemoryVT().getRawBits());
3314 ID.AddInteger(ST->getAlignment());
3315 ID.AddInteger(ST->isVolatile());
3317 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3318 return SDOperand(E, 0);
3319 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3320 new (N) StoreSDNode(Ops, VTs, AM,
3321 ST->isTruncatingStore(), ST->getMemoryVT(),
3322 ST->getSrcValue(), ST->getSrcValueOffset(),
3323 ST->getAlignment(), ST->isVolatile());
3324 CSEMap.InsertNode(N, IP);
3325 AllNodes.push_back(N);
3326 return SDOperand(N, 0);
3329 SDOperand SelectionDAG::getVAArg(MVT VT,
3330 SDOperand Chain, SDOperand Ptr,
3332 SDOperand Ops[] = { Chain, Ptr, SV };
3333 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3336 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3337 const SDUse *Ops, unsigned NumOps) {
3339 case 0: return getNode(Opcode, VT);
3340 case 1: return getNode(Opcode, VT, Ops[0].getSDOperand());
3341 case 2: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3342 Ops[1].getSDOperand());
3343 case 3: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3344 Ops[1].getSDOperand(), Ops[2].getSDOperand());
3348 // Copy from an SDUse array into an SDOperand array for use with
3349 // the regular getNode logic.
3350 SmallVector<SDOperand, 8> NewOps;
3351 NewOps.reserve(NumOps);
3352 for (unsigned i = 0; i != NumOps; ++i)
3353 NewOps.push_back(Ops[i].getSDOperand());
3354 return getNode(Opcode, VT, Ops, NumOps);
3357 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3358 const SDOperand *Ops, unsigned NumOps) {
3360 case 0: return getNode(Opcode, VT);
3361 case 1: return getNode(Opcode, VT, Ops[0]);
3362 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3363 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3369 case ISD::SELECT_CC: {
3370 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3371 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3372 "LHS and RHS of condition must have same type!");
3373 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3374 "True and False arms of SelectCC must have same type!");
3375 assert(Ops[2].getValueType() == VT &&
3376 "select_cc node must be of same type as true and false value!");
3380 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3381 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3382 "LHS/RHS of comparison should match types!");
3389 SDVTList VTs = getVTList(VT);
3390 if (VT != MVT::Flag) {
3391 FoldingSetNodeID ID;
3392 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3394 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3395 return SDOperand(E, 0);
3396 N = getAllocator().Allocate<SDNode>();
3397 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3398 CSEMap.InsertNode(N, IP);
3400 N = getAllocator().Allocate<SDNode>();
3401 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3403 AllNodes.push_back(N);
3404 return SDOperand(N, 0);
3407 SDOperand SelectionDAG::getNode(unsigned Opcode,
3408 std::vector<MVT> &ResultTys,
3409 const SDOperand *Ops, unsigned NumOps) {
3410 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3414 SDOperand SelectionDAG::getNode(unsigned Opcode,
3415 const MVT *VTs, unsigned NumVTs,
3416 const SDOperand *Ops, unsigned NumOps) {
3418 return getNode(Opcode, VTs[0], Ops, NumOps);
3419 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3422 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3423 const SDOperand *Ops, unsigned NumOps) {
3424 if (VTList.NumVTs == 1)
3425 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3428 // FIXME: figure out how to safely handle things like
3429 // int foo(int x) { return 1 << (x & 255); }
3430 // int bar() { return foo(256); }
3432 case ISD::SRA_PARTS:
3433 case ISD::SRL_PARTS:
3434 case ISD::SHL_PARTS:
3435 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3436 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3437 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3438 else if (N3.getOpcode() == ISD::AND)
3439 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3440 // If the and is only masking out bits that cannot effect the shift,
3441 // eliminate the and.
3442 unsigned NumBits = VT.getSizeInBits()*2;
3443 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3444 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3450 // Memoize the node unless it returns a flag.
3452 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3453 FoldingSetNodeID ID;
3454 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3456 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3457 return SDOperand(E, 0);
3459 N = getAllocator().Allocate<UnarySDNode>();
3460 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3461 } else if (NumOps == 2) {
3462 N = getAllocator().Allocate<BinarySDNode>();
3463 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3464 } else if (NumOps == 3) {
3465 N = getAllocator().Allocate<TernarySDNode>();
3466 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3468 N = getAllocator().Allocate<SDNode>();
3469 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3471 CSEMap.InsertNode(N, IP);
3474 N = getAllocator().Allocate<UnarySDNode>();
3475 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3476 } else if (NumOps == 2) {
3477 N = getAllocator().Allocate<BinarySDNode>();
3478 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3479 } else if (NumOps == 3) {
3480 N = getAllocator().Allocate<TernarySDNode>();
3481 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3483 N = getAllocator().Allocate<SDNode>();
3484 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3487 AllNodes.push_back(N);
3488 return SDOperand(N, 0);
3491 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3492 return getNode(Opcode, VTList, 0, 0);
3495 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3497 SDOperand Ops[] = { N1 };
3498 return getNode(Opcode, VTList, Ops, 1);
3501 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3502 SDOperand N1, SDOperand N2) {
3503 SDOperand Ops[] = { N1, N2 };
3504 return getNode(Opcode, VTList, Ops, 2);
3507 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3508 SDOperand N1, SDOperand N2, SDOperand N3) {
3509 SDOperand Ops[] = { N1, N2, N3 };
3510 return getNode(Opcode, VTList, Ops, 3);
3513 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3514 SDOperand N1, SDOperand N2, SDOperand N3,
3516 SDOperand Ops[] = { N1, N2, N3, N4 };
3517 return getNode(Opcode, VTList, Ops, 4);
3520 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3521 SDOperand N1, SDOperand N2, SDOperand N3,
3522 SDOperand N4, SDOperand N5) {
3523 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3524 return getNode(Opcode, VTList, Ops, 5);
3527 SDVTList SelectionDAG::getVTList(MVT VT) {
3528 return makeVTList(SDNode::getValueTypeList(VT), 1);
3531 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3532 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3533 E = VTList.end(); I != E; ++I) {
3534 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3535 return makeVTList(&(*I)[0], 2);
3540 VTList.push_front(V);
3541 return makeVTList(&(*VTList.begin())[0], 2);
3543 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3545 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3546 E = VTList.end(); I != E; ++I) {
3547 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3549 return makeVTList(&(*I)[0], 3);
3555 VTList.push_front(V);
3556 return makeVTList(&(*VTList.begin())[0], 3);
3559 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3561 case 0: assert(0 && "Cannot have nodes without results!");
3562 case 1: return getVTList(VTs[0]);
3563 case 2: return getVTList(VTs[0], VTs[1]);
3564 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3568 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3569 E = VTList.end(); I != E; ++I) {
3570 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3572 bool NoMatch = false;
3573 for (unsigned i = 2; i != NumVTs; ++i)
3574 if (VTs[i] != (*I)[i]) {
3579 return makeVTList(&*I->begin(), NumVTs);
3582 VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3583 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3587 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3588 /// specified operands. If the resultant node already exists in the DAG,
3589 /// this does not modify the specified node, instead it returns the node that
3590 /// already exists. If the resultant node does not exist in the DAG, the
3591 /// input node is returned. As a degenerate case, if you specify the same
3592 /// input operands as the node already has, the input node is returned.
3593 SDOperand SelectionDAG::
3594 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3595 SDNode *N = InN.Val;
3596 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3598 // Check to see if there is no change.
3599 if (Op == N->getOperand(0)) return InN;
3601 // See if the modified node already exists.
3602 void *InsertPos = 0;
3603 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3604 return SDOperand(Existing, InN.ResNo);
3606 // Nope it doesn't. Remove the node from it's current place in the maps.
3608 RemoveNodeFromCSEMaps(N);
3610 // Now we update the operands.
3611 N->OperandList[0].getVal()->removeUser(0, N);
3612 N->OperandList[0] = Op;
3613 N->OperandList[0].setUser(N);
3614 Op.Val->addUser(0, N);
3616 // If this gets put into a CSE map, add it.
3617 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3621 SDOperand SelectionDAG::
3622 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3623 SDNode *N = InN.Val;
3624 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3626 // Check to see if there is no change.
3627 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3628 return InN; // No operands changed, just return the input node.
3630 // See if the modified node already exists.
3631 void *InsertPos = 0;
3632 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3633 return SDOperand(Existing, InN.ResNo);
3635 // Nope it doesn't. Remove the node from it's current place in the maps.
3637 RemoveNodeFromCSEMaps(N);
3639 // Now we update the operands.
3640 if (N->OperandList[0] != Op1) {
3641 N->OperandList[0].getVal()->removeUser(0, N);
3642 N->OperandList[0] = Op1;
3643 N->OperandList[0].setUser(N);
3644 Op1.Val->addUser(0, N);
3646 if (N->OperandList[1] != Op2) {
3647 N->OperandList[1].getVal()->removeUser(1, N);
3648 N->OperandList[1] = Op2;
3649 N->OperandList[1].setUser(N);
3650 Op2.Val->addUser(1, N);
3653 // If this gets put into a CSE map, add it.
3654 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3658 SDOperand SelectionDAG::
3659 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3660 SDOperand Ops[] = { Op1, Op2, Op3 };
3661 return UpdateNodeOperands(N, Ops, 3);
3664 SDOperand SelectionDAG::
3665 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3666 SDOperand Op3, SDOperand Op4) {
3667 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3668 return UpdateNodeOperands(N, Ops, 4);
3671 SDOperand SelectionDAG::
3672 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3673 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3674 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3675 return UpdateNodeOperands(N, Ops, 5);
3678 SDOperand SelectionDAG::
3679 UpdateNodeOperands(SDOperand InN, const SDOperand *Ops, unsigned NumOps) {
3680 SDNode *N = InN.Val;
3681 assert(N->getNumOperands() == NumOps &&
3682 "Update with wrong number of operands");
3684 // Check to see if there is no change.
3685 bool AnyChange = false;
3686 for (unsigned i = 0; i != NumOps; ++i) {
3687 if (Ops[i] != N->getOperand(i)) {
3693 // No operands changed, just return the input node.
3694 if (!AnyChange) return InN;
3696 // See if the modified node already exists.
3697 void *InsertPos = 0;
3698 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3699 return SDOperand(Existing, InN.ResNo);
3701 // Nope it doesn't. Remove the node from its current place in the maps.
3703 RemoveNodeFromCSEMaps(N);
3705 // Now we update the operands.
3706 for (unsigned i = 0; i != NumOps; ++i) {
3707 if (N->OperandList[i] != Ops[i]) {
3708 N->OperandList[i].getVal()->removeUser(i, N);
3709 N->OperandList[i] = Ops[i];
3710 N->OperandList[i].setUser(N);
3711 Ops[i].Val->addUser(i, N);
3715 // If this gets put into a CSE map, add it.
3716 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3720 /// MorphNodeTo - This frees the operands of the current node, resets the
3721 /// opcode, types, and operands to the specified value. This should only be
3722 /// used by the SelectionDAG class.
3723 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3724 const SDOperand *Ops, unsigned NumOps,
3725 SmallVectorImpl<SDNode *> &DeadNodes) {
3728 NumValues = L.NumVTs;
3730 // Clear the operands list, updating used nodes to remove this from their
3731 // use list. Keep track of any operands that become dead as a result.
3732 SmallPtrSet<SDNode*, 16> DeadNodeSet;
3733 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
3734 SDNode *N = I->getVal();
3735 N->removeUser(std::distance(op_begin(), I), this);
3737 DeadNodeSet.insert(N);
3740 // If NumOps is larger than the # of operands we currently have, reallocate
3741 // the operand list.
3742 if (NumOps > NumOperands) {
3743 if (OperandsNeedDelete) {
3744 delete [] OperandList;
3746 OperandList = new SDUse[NumOps];
3747 OperandsNeedDelete = true;
3750 // Assign the new operands.
3751 NumOperands = NumOps;
3753 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3754 OperandList[i] = Ops[i];
3755 OperandList[i].setUser(this);
3756 SDNode *N = OperandList[i].getVal();
3757 N->addUser(i, this);
3759 DeadNodeSet.erase(N);
3762 // Clean up any nodes that are still dead after adding the uses for the
3764 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
3765 E = DeadNodeSet.end(); I != E; ++I)
3766 DeadNodes.push_back(*I);
3769 /// DropOperands - Release the operands and set this node to have
3770 /// zero operands. This should only be used by HandleSDNode to clear
3771 /// its operand list.
3772 void SDNode::DropOperands() {
3773 assert(NodeType == ISD::HANDLENODE &&
3774 "DropOperands is for HANDLENODE only!");
3776 // Unlike the code in MorphNodeTo that does this, we don't need to
3777 // watch for dead nodes here.
3778 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3779 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3784 /// SelectNodeTo - These are used for target selectors to *mutate* the
3785 /// specified node to have the specified return type, Target opcode, and
3786 /// operands. Note that target opcodes are stored as
3787 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3789 /// Note that SelectNodeTo returns the resultant node. If there is already a
3790 /// node of the specified opcode and operands, it returns that node instead of
3791 /// the current one.
3792 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3794 SDVTList VTs = getVTList(VT);
3795 return SelectNodeTo(N, TargetOpc, VTs, 0, 0);
3798 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3799 MVT VT, SDOperand Op1) {
3800 SDVTList VTs = getVTList(VT);
3801 SDOperand Ops[] = { Op1 };
3802 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3805 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3806 MVT VT, SDOperand Op1,
3808 SDVTList VTs = getVTList(VT);
3809 SDOperand Ops[] = { Op1, Op2 };
3810 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3813 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3814 MVT VT, SDOperand Op1,
3815 SDOperand Op2, SDOperand Op3) {
3816 SDVTList VTs = getVTList(VT);
3817 SDOperand Ops[] = { Op1, Op2, Op3 };
3818 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3821 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3822 MVT VT, const SDOperand *Ops,
3824 SDVTList VTs = getVTList(VT);
3825 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3828 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3829 MVT VT1, MVT VT2, const SDOperand *Ops,
3831 SDVTList VTs = getVTList(VT1, VT2);
3832 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3835 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3837 SDVTList VTs = getVTList(VT1, VT2);
3838 return SelectNodeTo(N, TargetOpc, VTs, (SDOperand *)0, 0);
3841 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3842 MVT VT1, MVT VT2, MVT VT3,
3843 const SDOperand *Ops, unsigned NumOps) {
3844 SDVTList VTs = getVTList(VT1, VT2, VT3);
3845 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3848 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3851 SDVTList VTs = getVTList(VT1, VT2);
3852 SDOperand Ops[] = { Op1 };
3853 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3856 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3858 SDOperand Op1, SDOperand Op2) {
3859 SDVTList VTs = getVTList(VT1, VT2);
3860 SDOperand Ops[] = { Op1, Op2 };
3861 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3864 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3866 SDOperand Op1, SDOperand Op2,
3868 SDVTList VTs = getVTList(VT1, VT2);
3869 SDOperand Ops[] = { Op1, Op2, Op3 };
3870 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3873 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3874 SDVTList VTs, const SDOperand *Ops,
3876 // If an identical node already exists, use it.
3877 FoldingSetNodeID ID;
3878 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3880 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3883 RemoveNodeFromCSEMaps(N);
3885 SmallVector<SDNode *, 16> DeadNodes;
3886 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps, DeadNodes);
3887 RemoveDeadNodes(DeadNodes);
3889 CSEMap.InsertNode(N, IP); // Memoize the new node.
3894 /// getTargetNode - These are used for target selectors to create a new node
3895 /// with specified return type(s), target opcode, and operands.
3897 /// Note that getTargetNode returns the resultant node. If there is already a
3898 /// node of the specified opcode and operands, it returns that node instead of
3899 /// the current one.
3900 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3901 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3903 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3904 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3906 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3907 SDOperand Op1, SDOperand Op2) {
3908 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3910 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3911 SDOperand Op1, SDOperand Op2,
3913 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3915 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3916 const SDOperand *Ops, unsigned NumOps) {
3917 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3919 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3920 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3922 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3924 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3925 MVT VT2, SDOperand Op1) {
3926 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3927 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3929 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3930 MVT VT2, SDOperand Op1,
3932 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3933 SDOperand Ops[] = { Op1, Op2 };
3934 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3936 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3937 MVT VT2, SDOperand Op1,
3938 SDOperand Op2, SDOperand Op3) {
3939 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3940 SDOperand Ops[] = { Op1, Op2, Op3 };
3941 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3943 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3944 const SDOperand *Ops, unsigned NumOps) {
3945 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3946 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3948 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3949 SDOperand Op1, SDOperand Op2) {
3950 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3951 SDOperand Ops[] = { Op1, Op2 };
3952 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3954 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3955 SDOperand Op1, SDOperand Op2,
3957 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3958 SDOperand Ops[] = { Op1, Op2, Op3 };
3959 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3961 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3962 const SDOperand *Ops, unsigned NumOps) {
3963 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3964 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3966 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3967 MVT VT2, MVT VT3, MVT VT4,
3968 const SDOperand *Ops, unsigned NumOps) {
3969 std::vector<MVT> VTList;
3970 VTList.push_back(VT1);
3971 VTList.push_back(VT2);
3972 VTList.push_back(VT3);
3973 VTList.push_back(VT4);
3974 const MVT *VTs = getNodeValueTypes(VTList);
3975 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3977 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3978 std::vector<MVT> &ResultTys,
3979 const SDOperand *Ops, unsigned NumOps) {
3980 const MVT *VTs = getNodeValueTypes(ResultTys);
3981 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3985 /// getNodeIfExists - Get the specified node if it's already available, or
3986 /// else return NULL.
3987 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3988 const SDOperand *Ops, unsigned NumOps) {
3989 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3990 FoldingSetNodeID ID;
3991 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3993 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4000 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4001 /// This can cause recursive merging of nodes in the DAG.
4003 /// This version assumes From has a single result value.
4005 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
4006 DAGUpdateListener *UpdateListener) {
4007 SDNode *From = FromN.Val;
4008 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
4009 "Cannot replace with this method!");
4010 assert(From != To.Val && "Cannot replace uses of with self");
4012 while (!From->use_empty()) {
4013 SDNode::use_iterator UI = From->use_begin();
4014 SDNode *U = UI->getUser();
4016 // This node is about to morph, remove its old self from the CSE maps.
4017 RemoveNodeFromCSEMaps(U);
4019 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4020 I != E; ++I, ++operandNum)
4021 if (I->getVal() == From) {
4022 From->removeUser(operandNum, U);
4025 To.Val->addUser(operandNum, U);
4028 // Now that we have modified U, add it back to the CSE maps. If it already
4029 // exists there, recursively merge the results together.
4030 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4031 ReplaceAllUsesWith(U, Existing, UpdateListener);
4032 // U is now dead. Inform the listener if it exists and delete it.
4034 UpdateListener->NodeDeleted(U, Existing);
4035 DeleteNodeNotInCSEMaps(U);
4037 // If the node doesn't already exist, we updated it. Inform a listener if
4040 UpdateListener->NodeUpdated(U);
4045 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4046 /// This can cause recursive merging of nodes in the DAG.
4048 /// This version assumes From/To have matching types and numbers of result
4051 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4052 DAGUpdateListener *UpdateListener) {
4053 assert(From != To && "Cannot replace uses of with self");
4054 assert(From->getNumValues() == To->getNumValues() &&
4055 "Cannot use this version of ReplaceAllUsesWith!");
4056 if (From->getNumValues() == 1) // If possible, use the faster version.
4057 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
4060 while (!From->use_empty()) {
4061 SDNode::use_iterator UI = From->use_begin();
4062 SDNode *U = UI->getUser();
4064 // This node is about to morph, remove its old self from the CSE maps.
4065 RemoveNodeFromCSEMaps(U);
4067 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4068 I != E; ++I, ++operandNum)
4069 if (I->getVal() == From) {
4070 From->removeUser(operandNum, U);
4072 To->addUser(operandNum, U);
4075 // Now that we have modified U, add it back to the CSE maps. If it already
4076 // exists there, recursively merge the results together.
4077 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4078 ReplaceAllUsesWith(U, Existing, UpdateListener);
4079 // U is now dead. Inform the listener if it exists and delete it.
4081 UpdateListener->NodeDeleted(U, Existing);
4082 DeleteNodeNotInCSEMaps(U);
4084 // If the node doesn't already exist, we updated it. Inform a listener if
4087 UpdateListener->NodeUpdated(U);
4092 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4093 /// This can cause recursive merging of nodes in the DAG.
4095 /// This version can replace From with any result values. To must match the
4096 /// number and types of values returned by From.
4097 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4098 const SDOperand *To,
4099 DAGUpdateListener *UpdateListener) {
4100 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4101 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
4103 while (!From->use_empty()) {
4104 SDNode::use_iterator UI = From->use_begin();
4105 SDNode *U = UI->getUser();
4107 // This node is about to morph, remove its old self from the CSE maps.
4108 RemoveNodeFromCSEMaps(U);
4110 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4111 I != E; ++I, ++operandNum)
4112 if (I->getVal() == From) {
4113 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4114 From->removeUser(operandNum, U);
4117 ToOp.Val->addUser(operandNum, U);
4120 // Now that we have modified U, add it back to the CSE maps. If it already
4121 // exists there, recursively merge the results together.
4122 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4123 ReplaceAllUsesWith(U, Existing, UpdateListener);
4124 // U is now dead. Inform the listener if it exists and delete it.
4126 UpdateListener->NodeDeleted(U, Existing);
4127 DeleteNodeNotInCSEMaps(U);
4129 // If the node doesn't already exist, we updated it. Inform a listener if
4132 UpdateListener->NodeUpdated(U);
4138 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4139 /// any deleted nodes from the set passed into its constructor and recursively
4140 /// notifies another update listener if specified.
4141 class ChainedSetUpdaterListener :
4142 public SelectionDAG::DAGUpdateListener {
4143 SmallSetVector<SDNode*, 16> &Set;
4144 SelectionDAG::DAGUpdateListener *Chain;
4146 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4147 SelectionDAG::DAGUpdateListener *chain)
4148 : Set(set), Chain(chain) {}
4150 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4152 if (Chain) Chain->NodeDeleted(N, E);
4154 virtual void NodeUpdated(SDNode *N) {
4155 if (Chain) Chain->NodeUpdated(N);
4160 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4161 /// uses of other values produced by From.Val alone. The Deleted vector is
4162 /// handled the same way as for ReplaceAllUsesWith.
4163 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4164 DAGUpdateListener *UpdateListener){
4165 assert(From != To && "Cannot replace a value with itself");
4167 // Handle the simple, trivial, case efficiently.
4168 if (From.Val->getNumValues() == 1) {
4169 ReplaceAllUsesWith(From, To, UpdateListener);
4173 if (From.use_empty()) return;
4175 // Get all of the users of From.Val. We want these in a nice,
4176 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4177 SmallSetVector<SDNode*, 16> Users;
4178 for (SDNode::use_iterator UI = From.Val->use_begin(),
4179 E = From.Val->use_end(); UI != E; ++UI) {
4180 SDNode *User = UI->getUser();
4184 // When one of the recursive merges deletes nodes from the graph, we need to
4185 // make sure that UpdateListener is notified *and* that the node is removed
4186 // from Users if present. CSUL does this.
4187 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4189 while (!Users.empty()) {
4190 // We know that this user uses some value of From. If it is the right
4191 // value, update it.
4192 SDNode *User = Users.back();
4195 // Scan for an operand that matches From.
4196 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4197 for (; Op != E; ++Op)
4198 if (*Op == From) break;
4200 // If there are no matches, the user must use some other result of From.
4201 if (Op == E) continue;
4203 // Okay, we know this user needs to be updated. Remove its old self
4204 // from the CSE maps.
4205 RemoveNodeFromCSEMaps(User);
4207 // Update all operands that match "From" in case there are multiple uses.
4208 for (; Op != E; ++Op) {
4210 From.Val->removeUser(Op-User->op_begin(), User);
4213 To.Val->addUser(Op-User->op_begin(), User);
4217 // Now that we have modified User, add it back to the CSE maps. If it
4218 // already exists there, recursively merge the results together.
4219 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4221 if (UpdateListener) UpdateListener->NodeUpdated(User);
4222 continue; // Continue on to next user.
4225 // If there was already an existing matching node, use ReplaceAllUsesWith
4226 // to replace the dead one with the existing one. This can cause
4227 // recursive merging of other unrelated nodes down the line. The merging
4228 // can cause deletion of nodes that used the old value. To handle this, we
4229 // use CSUL to remove them from the Users set.
4230 ReplaceAllUsesWith(User, Existing, &CSUL);
4232 // User is now dead. Notify a listener if present.
4233 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4234 DeleteNodeNotInCSEMaps(User);
4238 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4239 /// their allnodes order. It returns the maximum id.
4240 unsigned SelectionDAG::AssignNodeIds() {
4242 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4249 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4250 /// based on their topological order. It returns the maximum id and a vector
4251 /// of the SDNodes* in assigned order by reference.
4252 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4253 unsigned DAGSize = AllNodes.size();
4254 std::vector<unsigned> InDegree(DAGSize);
4255 std::vector<SDNode*> Sources;
4257 // Use a two pass approach to avoid using a std::map which is slow.
4259 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4262 unsigned Degree = N->use_size();
4263 InDegree[N->getNodeId()] = Degree;
4265 Sources.push_back(N);
4269 TopOrder.reserve(DAGSize);
4270 while (!Sources.empty()) {
4271 SDNode *N = Sources.back();
4273 TopOrder.push_back(N);
4274 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4275 SDNode *P = I->getVal();
4276 unsigned Degree = --InDegree[P->getNodeId()];
4278 Sources.push_back(P);
4282 // Second pass, assign the actual topological order as node ids.
4284 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4286 (*TI)->setNodeId(Id++);
4293 //===----------------------------------------------------------------------===//
4295 //===----------------------------------------------------------------------===//
4297 // Out-of-line virtual method to give class a home.
4298 void SDNode::ANCHOR() {}
4299 void UnarySDNode::ANCHOR() {}
4300 void BinarySDNode::ANCHOR() {}
4301 void TernarySDNode::ANCHOR() {}
4302 void HandleSDNode::ANCHOR() {}
4303 void ConstantSDNode::ANCHOR() {}
4304 void ConstantFPSDNode::ANCHOR() {}
4305 void GlobalAddressSDNode::ANCHOR() {}
4306 void FrameIndexSDNode::ANCHOR() {}
4307 void JumpTableSDNode::ANCHOR() {}
4308 void ConstantPoolSDNode::ANCHOR() {}
4309 void BasicBlockSDNode::ANCHOR() {}
4310 void SrcValueSDNode::ANCHOR() {}
4311 void MemOperandSDNode::ANCHOR() {}
4312 void RegisterSDNode::ANCHOR() {}
4313 void DbgStopPointSDNode::ANCHOR() {}
4314 void LabelSDNode::ANCHOR() {}
4315 void ExternalSymbolSDNode::ANCHOR() {}
4316 void CondCodeSDNode::ANCHOR() {}
4317 void ARG_FLAGSSDNode::ANCHOR() {}
4318 void VTSDNode::ANCHOR() {}
4319 void MemSDNode::ANCHOR() {}
4320 void LoadSDNode::ANCHOR() {}
4321 void StoreSDNode::ANCHOR() {}
4322 void AtomicSDNode::ANCHOR() {}
4324 HandleSDNode::~HandleSDNode() {
4328 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4330 : SDNode(isa<GlobalVariable>(GA) &&
4331 cast<GlobalVariable>(GA)->isThreadLocal() ?
4333 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4335 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4336 getSDVTList(VT)), Offset(o) {
4337 TheGlobal = const_cast<GlobalValue*>(GA);
4340 /// getMemOperand - Return a MachineMemOperand object describing the memory
4341 /// reference performed by this atomic.
4342 MachineMemOperand AtomicSDNode::getMemOperand() const {
4343 int Size = (getValueType(0).getSizeInBits() + 7) >> 3;
4344 int Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4345 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4347 // Check if the atomic references a frame index
4348 const FrameIndexSDNode *FI =
4349 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4350 if (!getSrcValue() && FI)
4351 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4352 FI->getIndex(), Size, getAlignment());
4354 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4355 Size, getAlignment());
4358 /// getMemOperand - Return a MachineMemOperand object describing the memory
4359 /// reference performed by this load or store.
4360 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4361 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4363 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4364 MachineMemOperand::MOStore;
4365 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4367 // Check if the load references a frame index, and does not have
4369 const FrameIndexSDNode *FI =
4370 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4371 if (!getSrcValue() && FI)
4372 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4373 FI->getIndex(), Size, getAlignment());
4375 return MachineMemOperand(getSrcValue(), Flags,
4376 getSrcValueOffset(), Size, getAlignment());
4379 /// Profile - Gather unique data for the node.
4381 void SDNode::Profile(FoldingSetNodeID &ID) {
4382 AddNodeIDNode(ID, this);
4385 /// getValueTypeList - Return a pointer to the specified value type.
4387 const MVT *SDNode::getValueTypeList(MVT VT) {
4388 if (VT.isExtended()) {
4389 static std::set<MVT, MVT::compareRawBits> EVTs;
4390 return &(*EVTs.insert(VT).first);
4392 static MVT VTs[MVT::LAST_VALUETYPE];
4393 VTs[VT.getSimpleVT()] = VT;
4394 return &VTs[VT.getSimpleVT()];
4398 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4399 /// indicated value. This method ignores uses of other values defined by this
4401 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4402 assert(Value < getNumValues() && "Bad value!");
4404 // If there is only one value, this is easy.
4405 if (getNumValues() == 1)
4406 return use_size() == NUses;
4407 if (use_size() < NUses) return false;
4409 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4411 SmallPtrSet<SDNode*, 32> UsersHandled;
4413 // TODO: Only iterate over uses of a given value of the node
4414 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4415 if (*UI == TheValue) {
4422 // Found exactly the right number of uses?
4427 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4428 /// value. This method ignores uses of other values defined by this operation.
4429 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4430 assert(Value < getNumValues() && "Bad value!");
4432 if (use_empty()) return false;
4434 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4436 SmallPtrSet<SDNode*, 32> UsersHandled;
4438 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4439 SDNode *User = UI->getUser();
4440 if (User->getNumOperands() == 1 ||
4441 UsersHandled.insert(User)) // First time we've seen this?
4442 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4443 if (User->getOperand(i) == TheValue) {
4452 /// isOnlyUseOf - Return true if this node is the only use of N.
4454 bool SDNode::isOnlyUseOf(SDNode *N) const {
4456 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4457 SDNode *User = I->getUser();
4467 /// isOperand - Return true if this node is an operand of N.
4469 bool SDOperand::isOperandOf(SDNode *N) const {
4470 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4471 if (*this == N->getOperand(i))
4476 bool SDNode::isOperandOf(SDNode *N) const {
4477 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4478 if (this == N->OperandList[i].getVal())
4483 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4484 /// be a chain) reaches the specified operand without crossing any
4485 /// side-effecting instructions. In practice, this looks through token
4486 /// factors and non-volatile loads. In order to remain efficient, this only
4487 /// looks a couple of nodes in, it does not do an exhaustive search.
4488 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4489 unsigned Depth) const {
4490 if (*this == Dest) return true;
4492 // Don't search too deeply, we just want to be able to see through
4493 // TokenFactor's etc.
4494 if (Depth == 0) return false;
4496 // If this is a token factor, all inputs to the TF happen in parallel. If any
4497 // of the operands of the TF reach dest, then we can do the xform.
4498 if (getOpcode() == ISD::TokenFactor) {
4499 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4500 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4505 // Loads don't have side effects, look through them.
4506 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4507 if (!Ld->isVolatile())
4508 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4514 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4515 SmallPtrSet<SDNode *, 32> &Visited) {
4516 if (found || !Visited.insert(N))
4519 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4520 SDNode *Op = N->getOperand(i).Val;
4525 findPredecessor(Op, P, found, Visited);
4529 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4530 /// is either an operand of N or it can be reached by recursively traversing
4531 /// up the operands.
4532 /// NOTE: this is an expensive method. Use it carefully.
4533 bool SDNode::isPredecessorOf(SDNode *N) const {
4534 SmallPtrSet<SDNode *, 32> Visited;
4536 findPredecessor(N, this, found, Visited);
4540 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4541 assert(Num < NumOperands && "Invalid child # of SDNode!");
4542 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4545 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4546 switch (getOpcode()) {
4548 if (getOpcode() < ISD::BUILTIN_OP_END)
4549 return "<<Unknown DAG Node>>";
4552 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4553 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4554 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4556 TargetLowering &TLI = G->getTargetLoweringInfo();
4558 TLI.getTargetNodeName(getOpcode());
4559 if (Name) return Name;
4562 return "<<Unknown Target Node>>";
4565 case ISD::PREFETCH: return "Prefetch";
4566 case ISD::MEMBARRIER: return "MemBarrier";
4567 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4568 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4569 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4570 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4571 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4572 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4573 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4574 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4575 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4576 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4577 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4578 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4579 case ISD::PCMARKER: return "PCMarker";
4580 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4581 case ISD::SRCVALUE: return "SrcValue";
4582 case ISD::MEMOPERAND: return "MemOperand";
4583 case ISD::EntryToken: return "EntryToken";
4584 case ISD::TokenFactor: return "TokenFactor";
4585 case ISD::AssertSext: return "AssertSext";
4586 case ISD::AssertZext: return "AssertZext";
4588 case ISD::BasicBlock: return "BasicBlock";
4589 case ISD::ARG_FLAGS: return "ArgFlags";
4590 case ISD::VALUETYPE: return "ValueType";
4591 case ISD::Register: return "Register";
4593 case ISD::Constant: return "Constant";
4594 case ISD::ConstantFP: return "ConstantFP";
4595 case ISD::GlobalAddress: return "GlobalAddress";
4596 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4597 case ISD::FrameIndex: return "FrameIndex";
4598 case ISD::JumpTable: return "JumpTable";
4599 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4600 case ISD::RETURNADDR: return "RETURNADDR";
4601 case ISD::FRAMEADDR: return "FRAMEADDR";
4602 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4603 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4604 case ISD::EHSELECTION: return "EHSELECTION";
4605 case ISD::EH_RETURN: return "EH_RETURN";
4606 case ISD::ConstantPool: return "ConstantPool";
4607 case ISD::ExternalSymbol: return "ExternalSymbol";
4608 case ISD::INTRINSIC_WO_CHAIN: {
4609 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4610 return Intrinsic::getName((Intrinsic::ID)IID);
4612 case ISD::INTRINSIC_VOID:
4613 case ISD::INTRINSIC_W_CHAIN: {
4614 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4615 return Intrinsic::getName((Intrinsic::ID)IID);
4618 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4619 case ISD::TargetConstant: return "TargetConstant";
4620 case ISD::TargetConstantFP:return "TargetConstantFP";
4621 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4622 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4623 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4624 case ISD::TargetJumpTable: return "TargetJumpTable";
4625 case ISD::TargetConstantPool: return "TargetConstantPool";
4626 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4628 case ISD::CopyToReg: return "CopyToReg";
4629 case ISD::CopyFromReg: return "CopyFromReg";
4630 case ISD::UNDEF: return "undef";
4631 case ISD::MERGE_VALUES: return "merge_values";
4632 case ISD::INLINEASM: return "inlineasm";
4633 case ISD::DBG_LABEL: return "dbg_label";
4634 case ISD::EH_LABEL: return "eh_label";
4635 case ISD::DECLARE: return "declare";
4636 case ISD::HANDLENODE: return "handlenode";
4637 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4638 case ISD::CALL: return "call";
4641 case ISD::FABS: return "fabs";
4642 case ISD::FNEG: return "fneg";
4643 case ISD::FSQRT: return "fsqrt";
4644 case ISD::FSIN: return "fsin";
4645 case ISD::FCOS: return "fcos";
4646 case ISD::FPOWI: return "fpowi";
4647 case ISD::FPOW: return "fpow";
4650 case ISD::ADD: return "add";
4651 case ISD::SUB: return "sub";
4652 case ISD::MUL: return "mul";
4653 case ISD::MULHU: return "mulhu";
4654 case ISD::MULHS: return "mulhs";
4655 case ISD::SDIV: return "sdiv";
4656 case ISD::UDIV: return "udiv";
4657 case ISD::SREM: return "srem";
4658 case ISD::UREM: return "urem";
4659 case ISD::SMUL_LOHI: return "smul_lohi";
4660 case ISD::UMUL_LOHI: return "umul_lohi";
4661 case ISD::SDIVREM: return "sdivrem";
4662 case ISD::UDIVREM: return "divrem";
4663 case ISD::AND: return "and";
4664 case ISD::OR: return "or";
4665 case ISD::XOR: return "xor";
4666 case ISD::SHL: return "shl";
4667 case ISD::SRA: return "sra";
4668 case ISD::SRL: return "srl";
4669 case ISD::ROTL: return "rotl";
4670 case ISD::ROTR: return "rotr";
4671 case ISD::FADD: return "fadd";
4672 case ISD::FSUB: return "fsub";
4673 case ISD::FMUL: return "fmul";
4674 case ISD::FDIV: return "fdiv";
4675 case ISD::FREM: return "frem";
4676 case ISD::FCOPYSIGN: return "fcopysign";
4677 case ISD::FGETSIGN: return "fgetsign";
4679 case ISD::SETCC: return "setcc";
4680 case ISD::VSETCC: return "vsetcc";
4681 case ISD::SELECT: return "select";
4682 case ISD::SELECT_CC: return "select_cc";
4683 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4684 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4685 case ISD::CONCAT_VECTORS: return "concat_vectors";
4686 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4687 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4688 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4689 case ISD::CARRY_FALSE: return "carry_false";
4690 case ISD::ADDC: return "addc";
4691 case ISD::ADDE: return "adde";
4692 case ISD::SUBC: return "subc";
4693 case ISD::SUBE: return "sube";
4694 case ISD::SHL_PARTS: return "shl_parts";
4695 case ISD::SRA_PARTS: return "sra_parts";
4696 case ISD::SRL_PARTS: return "srl_parts";
4698 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4699 case ISD::INSERT_SUBREG: return "insert_subreg";
4701 // Conversion operators.
4702 case ISD::SIGN_EXTEND: return "sign_extend";
4703 case ISD::ZERO_EXTEND: return "zero_extend";
4704 case ISD::ANY_EXTEND: return "any_extend";
4705 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4706 case ISD::TRUNCATE: return "truncate";
4707 case ISD::FP_ROUND: return "fp_round";
4708 case ISD::FLT_ROUNDS_: return "flt_rounds";
4709 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4710 case ISD::FP_EXTEND: return "fp_extend";
4712 case ISD::SINT_TO_FP: return "sint_to_fp";
4713 case ISD::UINT_TO_FP: return "uint_to_fp";
4714 case ISD::FP_TO_SINT: return "fp_to_sint";
4715 case ISD::FP_TO_UINT: return "fp_to_uint";
4716 case ISD::BIT_CONVERT: return "bit_convert";
4718 // Control flow instructions
4719 case ISD::BR: return "br";
4720 case ISD::BRIND: return "brind";
4721 case ISD::BR_JT: return "br_jt";
4722 case ISD::BRCOND: return "brcond";
4723 case ISD::BR_CC: return "br_cc";
4724 case ISD::RET: return "ret";
4725 case ISD::CALLSEQ_START: return "callseq_start";
4726 case ISD::CALLSEQ_END: return "callseq_end";
4729 case ISD::LOAD: return "load";
4730 case ISD::STORE: return "store";
4731 case ISD::VAARG: return "vaarg";
4732 case ISD::VACOPY: return "vacopy";
4733 case ISD::VAEND: return "vaend";
4734 case ISD::VASTART: return "vastart";
4735 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4736 case ISD::EXTRACT_ELEMENT: return "extract_element";
4737 case ISD::BUILD_PAIR: return "build_pair";
4738 case ISD::STACKSAVE: return "stacksave";
4739 case ISD::STACKRESTORE: return "stackrestore";
4740 case ISD::TRAP: return "trap";
4743 case ISD::BSWAP: return "bswap";
4744 case ISD::CTPOP: return "ctpop";
4745 case ISD::CTTZ: return "cttz";
4746 case ISD::CTLZ: return "ctlz";
4749 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4750 case ISD::DEBUG_LOC: return "debug_loc";
4753 case ISD::TRAMPOLINE: return "trampoline";
4756 switch (cast<CondCodeSDNode>(this)->get()) {
4757 default: assert(0 && "Unknown setcc condition!");
4758 case ISD::SETOEQ: return "setoeq";
4759 case ISD::SETOGT: return "setogt";
4760 case ISD::SETOGE: return "setoge";
4761 case ISD::SETOLT: return "setolt";
4762 case ISD::SETOLE: return "setole";
4763 case ISD::SETONE: return "setone";
4765 case ISD::SETO: return "seto";
4766 case ISD::SETUO: return "setuo";
4767 case ISD::SETUEQ: return "setue";
4768 case ISD::SETUGT: return "setugt";
4769 case ISD::SETUGE: return "setuge";
4770 case ISD::SETULT: return "setult";
4771 case ISD::SETULE: return "setule";
4772 case ISD::SETUNE: return "setune";
4774 case ISD::SETEQ: return "seteq";
4775 case ISD::SETGT: return "setgt";
4776 case ISD::SETGE: return "setge";
4777 case ISD::SETLT: return "setlt";
4778 case ISD::SETLE: return "setle";
4779 case ISD::SETNE: return "setne";
4784 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4793 return "<post-inc>";
4795 return "<post-dec>";
4799 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4800 std::string S = "< ";
4814 if (getByValAlign())
4815 S += "byval-align:" + utostr(getByValAlign()) + " ";
4817 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4819 S += "byval-size:" + utostr(getByValSize()) + " ";
4823 void SDNode::dump() const { dump(0); }
4824 void SDNode::dump(const SelectionDAG *G) const {
4825 cerr << (void*)this << ": ";
4827 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4829 if (getValueType(i) == MVT::Other)
4832 cerr << getValueType(i).getMVTString();
4834 cerr << " = " << getOperationName(G);
4837 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4838 if (i) cerr << ", ";
4839 cerr << (void*)getOperand(i).Val;
4840 if (unsigned RN = getOperand(i).ResNo)
4844 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4845 SDNode *Mask = getOperand(2).Val;
4847 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4849 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4852 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4857 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4858 cerr << "<" << CSDN->getValue() << ">";
4859 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4860 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4861 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4862 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4863 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4865 cerr << "<APFloat(";
4866 CSDN->getValueAPF().convertToAPInt().dump();
4869 } else if (const GlobalAddressSDNode *GADN =
4870 dyn_cast<GlobalAddressSDNode>(this)) {
4871 int offset = GADN->getOffset();
4873 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4875 cerr << " + " << offset;
4877 cerr << " " << offset;
4878 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4879 cerr << "<" << FIDN->getIndex() << ">";
4880 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4881 cerr << "<" << JTDN->getIndex() << ">";
4882 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4883 int offset = CP->getOffset();
4884 if (CP->isMachineConstantPoolEntry())
4885 cerr << "<" << *CP->getMachineCPVal() << ">";
4887 cerr << "<" << *CP->getConstVal() << ">";
4889 cerr << " + " << offset;
4891 cerr << " " << offset;
4892 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4894 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4896 cerr << LBB->getName() << " ";
4897 cerr << (const void*)BBDN->getBasicBlock() << ">";
4898 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4899 if (G && R->getReg() &&
4900 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4901 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4903 cerr << " #" << R->getReg();
4905 } else if (const ExternalSymbolSDNode *ES =
4906 dyn_cast<ExternalSymbolSDNode>(this)) {
4907 cerr << "'" << ES->getSymbol() << "'";
4908 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4910 cerr << "<" << M->getValue() << ">";
4913 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4914 if (M->MO.getValue())
4915 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4917 cerr << "<null:" << M->MO.getOffset() << ">";
4918 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4919 cerr << N->getArgFlags().getArgFlagsString();
4920 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4921 cerr << ":" << N->getVT().getMVTString();
4923 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4924 const Value *SrcValue = LD->getSrcValue();
4925 int SrcOffset = LD->getSrcValueOffset();
4931 cerr << ":" << SrcOffset << ">";
4934 switch (LD->getExtensionType()) {
4935 default: doExt = false; break;
4937 cerr << " <anyext ";
4947 cerr << LD->getMemoryVT().getMVTString() << ">";
4949 const char *AM = getIndexedModeName(LD->getAddressingMode());
4952 if (LD->isVolatile())
4953 cerr << " <volatile>";
4954 cerr << " alignment=" << LD->getAlignment();
4955 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4956 const Value *SrcValue = ST->getSrcValue();
4957 int SrcOffset = ST->getSrcValueOffset();
4963 cerr << ":" << SrcOffset << ">";
4965 if (ST->isTruncatingStore())
4967 << ST->getMemoryVT().getMVTString() << ">";
4969 const char *AM = getIndexedModeName(ST->getAddressingMode());
4972 if (ST->isVolatile())
4973 cerr << " <volatile>";
4974 cerr << " alignment=" << ST->getAlignment();
4975 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4976 const Value *SrcValue = AT->getSrcValue();
4977 int SrcOffset = AT->getSrcValueOffset();
4983 cerr << ":" << SrcOffset << ">";
4984 if (AT->isVolatile())
4985 cerr << " <volatile>";
4986 cerr << " alignment=" << AT->getAlignment();
4990 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4991 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4992 if (N->getOperand(i).Val->hasOneUse())
4993 DumpNodes(N->getOperand(i).Val, indent+2, G);
4995 cerr << "\n" << std::string(indent+2, ' ')
4996 << (void*)N->getOperand(i).Val << ": <multiple use>";
4999 cerr << "\n" << std::string(indent, ' ');
5003 void SelectionDAG::dump() const {
5004 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5005 std::vector<const SDNode*> Nodes;
5006 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5010 std::sort(Nodes.begin(), Nodes.end());
5012 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
5013 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
5014 DumpNodes(Nodes[i], 2, this);
5017 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
5022 const Type *ConstantPoolSDNode::getType() const {
5023 if (isMachineConstantPoolEntry())
5024 return Val.MachineCPVal->getType();
5025 return Val.ConstVal->getType();