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->isMachineOpcode() &&
201 N->getMachineOpcode() == 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(1, N);
536 RemoveDeadNodes(DeadNodes, UpdateListener);
539 void SelectionDAG::DeleteNode(SDNode *N) {
540 assert(N->use_empty() && "Cannot delete a node that is not dead!");
542 // First take this out of the appropriate CSE map.
543 RemoveNodeFromCSEMaps(N);
545 // Finally, remove uses due to operands of this node, remove from the
546 // AllNodes list, and delete the node.
547 DeleteNodeNotInCSEMaps(N);
550 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
552 // Drop all of the operands and decrement used nodes use counts.
553 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
554 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
555 if (N->OperandsNeedDelete) {
556 delete[] N->OperandList;
564 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
565 /// correspond to it. This is useful when we're about to delete or repurpose
566 /// the node. We don't want future request for structurally identical nodes
567 /// to return N anymore.
568 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
570 switch (N->getOpcode()) {
571 case ISD::HANDLENODE: return; // noop.
573 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
574 "Cond code doesn't exist!");
575 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
576 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
578 case ISD::ExternalSymbol:
579 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
581 case ISD::TargetExternalSymbol:
583 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
585 case ISD::VALUETYPE: {
586 MVT VT = cast<VTSDNode>(N)->getVT();
587 if (VT.isExtended()) {
588 Erased = ExtendedValueTypeNodes.erase(VT);
590 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
591 ValueTypeNodes[VT.getSimpleVT()] = 0;
596 // Remove it from the CSE Map.
597 Erased = CSEMap.RemoveNode(N);
601 // Verify that the node was actually in one of the CSE maps, unless it has a
602 // flag result (which cannot be CSE'd) or is one of the special cases that are
603 // not subject to CSE.
604 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
605 !N->isTargetOpcode() &&
606 N->getOpcode() != ISD::DBG_LABEL &&
607 N->getOpcode() != ISD::DBG_STOPPOINT &&
608 N->getOpcode() != ISD::EH_LABEL &&
609 N->getOpcode() != ISD::DECLARE) {
612 assert(0 && "Node is not in map!");
617 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
618 /// has been taken out and modified in some way. If the specified node already
619 /// exists in the CSE maps, do not modify the maps, but return the existing node
620 /// instead. If it doesn't exist, add it and return null.
622 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
623 assert(N->getNumOperands() && "This is a leaf node!");
625 if (N->getValueType(0) == MVT::Flag)
626 return 0; // Never CSE anything that produces a flag.
628 switch (N->getOpcode()) {
630 case ISD::HANDLENODE:
632 case ISD::DBG_STOPPOINT:
635 return 0; // Never add these nodes.
638 // Check that remaining values produced are not flags.
639 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
640 if (N->getValueType(i) == MVT::Flag)
641 return 0; // Never CSE anything that produces a flag.
643 SDNode *New = CSEMap.GetOrInsertNode(N);
644 if (New != N) return New; // Node already existed.
648 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
649 /// were replaced with those specified. If this node is never memoized,
650 /// return null, otherwise return a pointer to the slot it would take. If a
651 /// node already exists with these operands, the slot will be non-null.
652 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
654 if (N->getValueType(0) == MVT::Flag)
655 return 0; // Never CSE anything that produces a flag.
657 switch (N->getOpcode()) {
659 case ISD::HANDLENODE:
661 case ISD::DBG_STOPPOINT:
663 return 0; // Never add these nodes.
666 // Check that remaining values produced are not flags.
667 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
668 if (N->getValueType(i) == MVT::Flag)
669 return 0; // Never CSE anything that produces a flag.
671 SDOperand Ops[] = { Op };
673 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
674 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
677 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
678 /// were replaced with those specified. If this node is never memoized,
679 /// return null, otherwise return a pointer to the slot it would take. If a
680 /// node already exists with these operands, the slot will be non-null.
681 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
682 SDOperand Op1, SDOperand Op2,
684 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
686 // Check that remaining values produced are not flags.
687 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
688 if (N->getValueType(i) == MVT::Flag)
689 return 0; // Never CSE anything that produces a flag.
691 SDOperand Ops[] = { Op1, Op2 };
693 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
694 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
698 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
699 /// were replaced with those specified. If this node is never memoized,
700 /// return null, otherwise return a pointer to the slot it would take. If a
701 /// node already exists with these operands, the slot will be non-null.
702 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
703 const SDOperand *Ops,unsigned NumOps,
705 if (N->getValueType(0) == MVT::Flag)
706 return 0; // Never CSE anything that produces a flag.
708 switch (N->getOpcode()) {
710 case ISD::HANDLENODE:
712 case ISD::DBG_STOPPOINT:
715 return 0; // Never add these nodes.
718 // Check that remaining values produced are not flags.
719 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
720 if (N->getValueType(i) == MVT::Flag)
721 return 0; // Never CSE anything that produces a flag.
724 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
726 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
727 ID.AddInteger(LD->getAddressingMode());
728 ID.AddInteger(LD->getExtensionType());
729 ID.AddInteger(LD->getMemoryVT().getRawBits());
730 ID.AddInteger(LD->getAlignment());
731 ID.AddInteger(LD->isVolatile());
732 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
733 ID.AddInteger(ST->getAddressingMode());
734 ID.AddInteger(ST->isTruncatingStore());
735 ID.AddInteger(ST->getMemoryVT().getRawBits());
736 ID.AddInteger(ST->getAlignment());
737 ID.AddInteger(ST->isVolatile());
740 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
743 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
744 void SelectionDAG::VerifyNode(SDNode *N) {
745 switch (N->getOpcode()) {
748 case ISD::BUILD_VECTOR: {
749 assert(N->getNumValues() == 1 && "Too many results for BUILD_VECTOR!");
750 assert(N->getValueType(0).isVector() && "Wrong BUILD_VECTOR return type!");
751 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
752 "Wrong number of BUILD_VECTOR operands!");
753 MVT EltVT = N->getValueType(0).getVectorElementType();
754 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
755 assert(I->getSDOperand().getValueType() == EltVT &&
756 "Wrong BUILD_VECTOR operand type!");
762 /// getMVTAlignment - Compute the default alignment value for the
765 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
766 const Type *Ty = VT == MVT::iPTR ?
767 PointerType::get(Type::Int8Ty, 0) :
770 return TLI.getTargetData()->getABITypeAlignment(Ty);
773 SelectionDAG::~SelectionDAG() {
774 while (!AllNodes.empty()) {
775 SDNode *N = AllNodes.begin();
776 N->SetNextInBucket(0);
777 if (N->OperandsNeedDelete) {
778 delete [] N->OperandList;
782 AllNodes.pop_front();
786 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
787 if (Op.getValueType() == VT) return Op;
788 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
790 return getNode(ISD::AND, Op.getValueType(), Op,
791 getConstant(Imm, Op.getValueType()));
794 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
795 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
796 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
799 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
800 assert(VT.isInteger() && "Cannot create FP integer constant!");
802 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
803 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
804 "APInt size does not match type size!");
806 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
808 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
812 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
814 return SDOperand(N, 0);
816 N = getAllocator().Allocate<ConstantSDNode>();
817 new (N) ConstantSDNode(isT, Val, EltVT);
818 CSEMap.InsertNode(N, IP);
819 AllNodes.push_back(N);
822 SDOperand Result(N, 0);
824 SmallVector<SDOperand, 8> Ops;
825 Ops.assign(VT.getVectorNumElements(), Result);
826 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
831 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
832 return getConstant(Val, TLI.getPointerTy(), isTarget);
836 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
837 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
840 VT.isVector() ? VT.getVectorElementType() : VT;
842 // Do the map lookup using the actual bit pattern for the floating point
843 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
844 // we don't have issues with SNANs.
845 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
847 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
851 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
853 return SDOperand(N, 0);
855 N = getAllocator().Allocate<ConstantFPSDNode>();
856 new (N) ConstantFPSDNode(isTarget, V, EltVT);
857 CSEMap.InsertNode(N, IP);
858 AllNodes.push_back(N);
861 SDOperand Result(N, 0);
863 SmallVector<SDOperand, 8> Ops;
864 Ops.assign(VT.getVectorNumElements(), Result);
865 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
870 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
872 VT.isVector() ? VT.getVectorElementType() : VT;
874 return getConstantFP(APFloat((float)Val), VT, isTarget);
876 return getConstantFP(APFloat(Val), VT, isTarget);
879 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
884 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
886 // If GV is an alias then use the aliasee for determining thread-localness.
887 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
888 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
891 if (GVar && GVar->isThreadLocal())
892 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
894 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
897 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
899 ID.AddInteger(Offset);
901 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
902 return SDOperand(E, 0);
903 SDNode *N = getAllocator().Allocate<GlobalAddressSDNode>();
904 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
905 CSEMap.InsertNode(N, IP);
906 AllNodes.push_back(N);
907 return SDOperand(N, 0);
910 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
911 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
913 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
916 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
917 return SDOperand(E, 0);
918 SDNode *N = getAllocator().Allocate<FrameIndexSDNode>();
919 new (N) FrameIndexSDNode(FI, VT, isTarget);
920 CSEMap.InsertNode(N, IP);
921 AllNodes.push_back(N);
922 return SDOperand(N, 0);
925 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
926 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
928 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
931 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
932 return SDOperand(E, 0);
933 SDNode *N = getAllocator().Allocate<JumpTableSDNode>();
934 new (N) JumpTableSDNode(JTI, VT, isTarget);
935 CSEMap.InsertNode(N, IP);
936 AllNodes.push_back(N);
937 return SDOperand(N, 0);
940 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
941 unsigned Alignment, int Offset,
943 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
945 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
946 ID.AddInteger(Alignment);
947 ID.AddInteger(Offset);
950 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
951 return SDOperand(E, 0);
952 SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
953 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
954 CSEMap.InsertNode(N, IP);
955 AllNodes.push_back(N);
956 return SDOperand(N, 0);
960 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
961 unsigned Alignment, int Offset,
963 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
965 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
966 ID.AddInteger(Alignment);
967 ID.AddInteger(Offset);
968 C->AddSelectionDAGCSEId(ID);
970 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
971 return SDOperand(E, 0);
972 SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
973 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
974 CSEMap.InsertNode(N, IP);
975 AllNodes.push_back(N);
976 return SDOperand(N, 0);
980 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
982 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
985 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
986 return SDOperand(E, 0);
987 SDNode *N = getAllocator().Allocate<BasicBlockSDNode>();
988 new (N) BasicBlockSDNode(MBB);
989 CSEMap.InsertNode(N, IP);
990 AllNodes.push_back(N);
991 return SDOperand(N, 0);
994 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
996 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
997 ID.AddInteger(Flags.getRawBits());
999 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1000 return SDOperand(E, 0);
1001 SDNode *N = getAllocator().Allocate<ARG_FLAGSSDNode>();
1002 new (N) ARG_FLAGSSDNode(Flags);
1003 CSEMap.InsertNode(N, IP);
1004 AllNodes.push_back(N);
1005 return SDOperand(N, 0);
1008 SDOperand SelectionDAG::getValueType(MVT VT) {
1009 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1010 ValueTypeNodes.resize(VT.getSimpleVT()+1);
1012 SDNode *&N = VT.isExtended() ?
1013 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1015 if (N) return SDOperand(N, 0);
1016 N = getAllocator().Allocate<VTSDNode>();
1017 new (N) VTSDNode(VT);
1018 AllNodes.push_back(N);
1019 return SDOperand(N, 0);
1022 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1023 SDNode *&N = ExternalSymbols[Sym];
1024 if (N) return SDOperand(N, 0);
1025 N = getAllocator().Allocate<ExternalSymbolSDNode>();
1026 new (N) ExternalSymbolSDNode(false, Sym, VT);
1027 AllNodes.push_back(N);
1028 return SDOperand(N, 0);
1031 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1032 SDNode *&N = TargetExternalSymbols[Sym];
1033 if (N) return SDOperand(N, 0);
1034 N = getAllocator().Allocate<ExternalSymbolSDNode>();
1035 new (N) ExternalSymbolSDNode(true, Sym, VT);
1036 AllNodes.push_back(N);
1037 return SDOperand(N, 0);
1040 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
1041 if ((unsigned)Cond >= CondCodeNodes.size())
1042 CondCodeNodes.resize(Cond+1);
1044 if (CondCodeNodes[Cond] == 0) {
1045 CondCodeSDNode *N = getAllocator().Allocate<CondCodeSDNode>();
1046 new (N) CondCodeSDNode(Cond);
1047 CondCodeNodes[Cond] = N;
1048 AllNodes.push_back(N);
1050 return SDOperand(CondCodeNodes[Cond], 0);
1053 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1054 FoldingSetNodeID ID;
1055 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1056 ID.AddInteger(RegNo);
1058 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1059 return SDOperand(E, 0);
1060 SDNode *N = getAllocator().Allocate<RegisterSDNode>();
1061 new (N) RegisterSDNode(RegNo, VT);
1062 CSEMap.InsertNode(N, IP);
1063 AllNodes.push_back(N);
1064 return SDOperand(N, 0);
1067 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
1068 unsigned Line, unsigned Col,
1069 const CompileUnitDesc *CU) {
1070 SDNode *N = getAllocator().Allocate<DbgStopPointSDNode>();
1071 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1072 AllNodes.push_back(N);
1073 return SDOperand(N, 0);
1076 SDOperand SelectionDAG::getLabel(unsigned Opcode,
1079 FoldingSetNodeID ID;
1080 SDOperand Ops[] = { Root };
1081 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1082 ID.AddInteger(LabelID);
1084 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1085 return SDOperand(E, 0);
1086 SDNode *N = getAllocator().Allocate<LabelSDNode>();
1087 new (N) LabelSDNode(Opcode, Root, LabelID);
1088 CSEMap.InsertNode(N, IP);
1089 AllNodes.push_back(N);
1090 return SDOperand(N, 0);
1093 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1094 assert((!V || isa<PointerType>(V->getType())) &&
1095 "SrcValue is not a pointer?");
1097 FoldingSetNodeID ID;
1098 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1102 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1103 return SDOperand(E, 0);
1105 SDNode *N = getAllocator().Allocate<SrcValueSDNode>();
1106 new (N) SrcValueSDNode(V);
1107 CSEMap.InsertNode(N, IP);
1108 AllNodes.push_back(N);
1109 return SDOperand(N, 0);
1112 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1113 const Value *v = MO.getValue();
1114 assert((!v || isa<PointerType>(v->getType())) &&
1115 "SrcValue is not a pointer?");
1117 FoldingSetNodeID ID;
1118 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1120 ID.AddInteger(MO.getFlags());
1121 ID.AddInteger(MO.getOffset());
1122 ID.AddInteger(MO.getSize());
1123 ID.AddInteger(MO.getAlignment());
1126 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1127 return SDOperand(E, 0);
1129 SDNode *N = getAllocator().Allocate<MemOperandSDNode>();
1130 new (N) MemOperandSDNode(MO);
1131 CSEMap.InsertNode(N, IP);
1132 AllNodes.push_back(N);
1133 return SDOperand(N, 0);
1136 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1137 /// specified value type.
1138 SDOperand SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1139 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1140 unsigned ByteSize = VT.getSizeInBits()/8;
1141 const Type *Ty = VT.getTypeForMVT();
1142 unsigned StackAlign =
1143 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1145 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1146 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1149 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1150 SDOperand N2, ISD::CondCode Cond) {
1151 // These setcc operations always fold.
1155 case ISD::SETFALSE2: return getConstant(0, VT);
1157 case ISD::SETTRUE2: return getConstant(1, VT);
1169 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1173 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1174 const APInt &C2 = N2C->getAPIntValue();
1175 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1176 const APInt &C1 = N1C->getAPIntValue();
1179 default: assert(0 && "Unknown integer setcc!");
1180 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1181 case ISD::SETNE: return getConstant(C1 != C2, VT);
1182 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1183 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1184 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1185 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1186 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1187 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1188 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1189 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1193 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1194 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1195 // No compile time operations on this type yet.
1196 if (N1C->getValueType(0) == MVT::ppcf128)
1199 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1202 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1203 return getNode(ISD::UNDEF, VT);
1205 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1206 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1207 return getNode(ISD::UNDEF, VT);
1209 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1210 R==APFloat::cmpLessThan, VT);
1211 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1212 return getNode(ISD::UNDEF, VT);
1214 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1215 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1216 return getNode(ISD::UNDEF, VT);
1218 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1219 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1220 return getNode(ISD::UNDEF, VT);
1222 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1223 R==APFloat::cmpEqual, VT);
1224 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1225 return getNode(ISD::UNDEF, VT);
1227 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1228 R==APFloat::cmpEqual, VT);
1229 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1230 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1231 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1232 R==APFloat::cmpEqual, VT);
1233 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1234 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1235 R==APFloat::cmpLessThan, VT);
1236 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1237 R==APFloat::cmpUnordered, VT);
1238 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1239 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1242 // Ensure that the constant occurs on the RHS.
1243 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1247 // Could not fold it.
1251 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1252 /// use this predicate to simplify operations downstream.
1253 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1254 unsigned BitWidth = Op.getValueSizeInBits();
1255 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1258 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1259 /// this predicate to simplify operations downstream. Mask is known to be zero
1260 /// for bits that V cannot have.
1261 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1262 unsigned Depth) const {
1263 APInt KnownZero, KnownOne;
1264 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1265 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1266 return (KnownZero & Mask) == Mask;
1269 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1270 /// known to be either zero or one and return them in the KnownZero/KnownOne
1271 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1273 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1274 APInt &KnownZero, APInt &KnownOne,
1275 unsigned Depth) const {
1276 unsigned BitWidth = Mask.getBitWidth();
1277 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1278 "Mask size mismatches value type size!");
1280 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1281 if (Depth == 6 || Mask == 0)
1282 return; // Limit search depth.
1284 APInt KnownZero2, KnownOne2;
1286 switch (Op.getOpcode()) {
1288 // We know all of the bits for a constant!
1289 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1290 KnownZero = ~KnownOne & Mask;
1293 // If either the LHS or the RHS are Zero, the result is zero.
1294 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1295 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1296 KnownZero2, KnownOne2, Depth+1);
1297 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1298 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1300 // Output known-1 bits are only known if set in both the LHS & RHS.
1301 KnownOne &= KnownOne2;
1302 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1303 KnownZero |= KnownZero2;
1306 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1307 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1308 KnownZero2, KnownOne2, Depth+1);
1309 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1310 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1312 // Output known-0 bits are only known if clear in both the LHS & RHS.
1313 KnownZero &= KnownZero2;
1314 // Output known-1 are known to be set if set in either the LHS | RHS.
1315 KnownOne |= KnownOne2;
1318 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1319 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1320 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1321 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1323 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1324 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1325 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1326 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1327 KnownZero = KnownZeroOut;
1331 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1332 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1333 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1334 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1335 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1337 // If low bits are zero in either operand, output low known-0 bits.
1338 // Also compute a conserative estimate for high known-0 bits.
1339 // More trickiness is possible, but this is sufficient for the
1340 // interesting case of alignment computation.
1342 unsigned TrailZ = KnownZero.countTrailingOnes() +
1343 KnownZero2.countTrailingOnes();
1344 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1345 KnownZero2.countLeadingOnes(),
1346 BitWidth) - BitWidth;
1348 TrailZ = std::min(TrailZ, BitWidth);
1349 LeadZ = std::min(LeadZ, BitWidth);
1350 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1351 APInt::getHighBitsSet(BitWidth, LeadZ);
1356 // For the purposes of computing leading zeros we can conservatively
1357 // treat a udiv as a logical right shift by the power of 2 known to
1358 // be less than the denominator.
1359 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1360 ComputeMaskedBits(Op.getOperand(0),
1361 AllOnes, KnownZero2, KnownOne2, Depth+1);
1362 unsigned LeadZ = KnownZero2.countLeadingOnes();
1366 ComputeMaskedBits(Op.getOperand(1),
1367 AllOnes, KnownZero2, KnownOne2, Depth+1);
1368 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1369 if (RHSUnknownLeadingOnes != BitWidth)
1370 LeadZ = std::min(BitWidth,
1371 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1373 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1377 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1378 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1379 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1380 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1382 // Only known if known in both the LHS and RHS.
1383 KnownOne &= KnownOne2;
1384 KnownZero &= KnownZero2;
1386 case ISD::SELECT_CC:
1387 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1388 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1389 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1390 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1392 // Only known if known in both the LHS and RHS.
1393 KnownOne &= KnownOne2;
1394 KnownZero &= KnownZero2;
1397 // If we know the result of a setcc has the top bits zero, use this info.
1398 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1400 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1403 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1404 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1405 unsigned ShAmt = SA->getValue();
1407 // If the shift count is an invalid immediate, don't do anything.
1408 if (ShAmt >= BitWidth)
1411 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1412 KnownZero, KnownOne, Depth+1);
1413 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1414 KnownZero <<= ShAmt;
1416 // low bits known zero.
1417 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1421 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1422 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1423 unsigned ShAmt = SA->getValue();
1425 // If the shift count is an invalid immediate, don't do anything.
1426 if (ShAmt >= BitWidth)
1429 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1430 KnownZero, KnownOne, Depth+1);
1431 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1432 KnownZero = KnownZero.lshr(ShAmt);
1433 KnownOne = KnownOne.lshr(ShAmt);
1435 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1436 KnownZero |= HighBits; // High bits known zero.
1440 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1441 unsigned ShAmt = SA->getValue();
1443 // If the shift count is an invalid immediate, don't do anything.
1444 if (ShAmt >= BitWidth)
1447 APInt InDemandedMask = (Mask << ShAmt);
1448 // If any of the demanded bits are produced by the sign extension, we also
1449 // demand the input sign bit.
1450 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1451 if (HighBits.getBoolValue())
1452 InDemandedMask |= APInt::getSignBit(BitWidth);
1454 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1456 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1457 KnownZero = KnownZero.lshr(ShAmt);
1458 KnownOne = KnownOne.lshr(ShAmt);
1460 // Handle the sign bits.
1461 APInt SignBit = APInt::getSignBit(BitWidth);
1462 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1464 if (KnownZero.intersects(SignBit)) {
1465 KnownZero |= HighBits; // New bits are known zero.
1466 } else if (KnownOne.intersects(SignBit)) {
1467 KnownOne |= HighBits; // New bits are known one.
1471 case ISD::SIGN_EXTEND_INREG: {
1472 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1473 unsigned EBits = EVT.getSizeInBits();
1475 // Sign extension. Compute the demanded bits in the result that are not
1476 // present in the input.
1477 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1479 APInt InSignBit = APInt::getSignBit(EBits);
1480 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1482 // If the sign extended bits are demanded, we know that the sign
1484 InSignBit.zext(BitWidth);
1485 if (NewBits.getBoolValue())
1486 InputDemandedBits |= InSignBit;
1488 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1489 KnownZero, KnownOne, Depth+1);
1490 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1492 // If the sign bit of the input is known set or clear, then we know the
1493 // top bits of the result.
1494 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1495 KnownZero |= NewBits;
1496 KnownOne &= ~NewBits;
1497 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1498 KnownOne |= NewBits;
1499 KnownZero &= ~NewBits;
1500 } else { // Input sign bit unknown
1501 KnownZero &= ~NewBits;
1502 KnownOne &= ~NewBits;
1509 unsigned LowBits = Log2_32(BitWidth)+1;
1510 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1515 if (ISD::isZEXTLoad(Op.Val)) {
1516 LoadSDNode *LD = cast<LoadSDNode>(Op);
1517 MVT VT = LD->getMemoryVT();
1518 unsigned MemBits = VT.getSizeInBits();
1519 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1523 case ISD::ZERO_EXTEND: {
1524 MVT InVT = Op.getOperand(0).getValueType();
1525 unsigned InBits = InVT.getSizeInBits();
1526 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1527 APInt InMask = Mask;
1528 InMask.trunc(InBits);
1529 KnownZero.trunc(InBits);
1530 KnownOne.trunc(InBits);
1531 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1532 KnownZero.zext(BitWidth);
1533 KnownOne.zext(BitWidth);
1534 KnownZero |= NewBits;
1537 case ISD::SIGN_EXTEND: {
1538 MVT InVT = Op.getOperand(0).getValueType();
1539 unsigned InBits = InVT.getSizeInBits();
1540 APInt InSignBit = APInt::getSignBit(InBits);
1541 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1542 APInt InMask = Mask;
1543 InMask.trunc(InBits);
1545 // If any of the sign extended bits are demanded, we know that the sign
1546 // bit is demanded. Temporarily set this bit in the mask for our callee.
1547 if (NewBits.getBoolValue())
1548 InMask |= InSignBit;
1550 KnownZero.trunc(InBits);
1551 KnownOne.trunc(InBits);
1552 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1554 // Note if the sign bit is known to be zero or one.
1555 bool SignBitKnownZero = KnownZero.isNegative();
1556 bool SignBitKnownOne = KnownOne.isNegative();
1557 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1558 "Sign bit can't be known to be both zero and one!");
1560 // If the sign bit wasn't actually demanded by our caller, we don't
1561 // want it set in the KnownZero and KnownOne result values. Reset the
1562 // mask and reapply it to the result values.
1564 InMask.trunc(InBits);
1565 KnownZero &= InMask;
1568 KnownZero.zext(BitWidth);
1569 KnownOne.zext(BitWidth);
1571 // If the sign bit is known zero or one, the top bits match.
1572 if (SignBitKnownZero)
1573 KnownZero |= NewBits;
1574 else if (SignBitKnownOne)
1575 KnownOne |= NewBits;
1578 case ISD::ANY_EXTEND: {
1579 MVT InVT = Op.getOperand(0).getValueType();
1580 unsigned InBits = InVT.getSizeInBits();
1581 APInt InMask = Mask;
1582 InMask.trunc(InBits);
1583 KnownZero.trunc(InBits);
1584 KnownOne.trunc(InBits);
1585 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1586 KnownZero.zext(BitWidth);
1587 KnownOne.zext(BitWidth);
1590 case ISD::TRUNCATE: {
1591 MVT InVT = Op.getOperand(0).getValueType();
1592 unsigned InBits = InVT.getSizeInBits();
1593 APInt InMask = Mask;
1594 InMask.zext(InBits);
1595 KnownZero.zext(InBits);
1596 KnownOne.zext(InBits);
1597 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1598 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1599 KnownZero.trunc(BitWidth);
1600 KnownOne.trunc(BitWidth);
1603 case ISD::AssertZext: {
1604 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1605 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1606 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1608 KnownZero |= (~InMask) & Mask;
1612 // All bits are zero except the low bit.
1613 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1617 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1618 // We know that the top bits of C-X are clear if X contains less bits
1619 // than C (i.e. no wrap-around can happen). For example, 20-X is
1620 // positive if we can prove that X is >= 0 and < 16.
1621 if (CLHS->getAPIntValue().isNonNegative()) {
1622 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1623 // NLZ can't be BitWidth with no sign bit
1624 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1625 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1628 // If all of the MaskV bits are known to be zero, then we know the
1629 // output top bits are zero, because we now know that the output is
1631 if ((KnownZero2 & MaskV) == MaskV) {
1632 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1633 // Top bits known zero.
1634 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1641 // Output known-0 bits are known if clear or set in both the low clear bits
1642 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1643 // low 3 bits clear.
1644 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1645 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1646 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1647 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1649 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1650 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1651 KnownZeroOut = std::min(KnownZeroOut,
1652 KnownZero2.countTrailingOnes());
1654 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1658 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1659 const APInt &RA = Rem->getAPIntValue();
1660 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1661 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1662 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1663 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1665 // The sign of a remainder is equal to the sign of the first
1666 // operand (zero being positive).
1667 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1668 KnownZero2 |= ~LowBits;
1669 else if (KnownOne2[BitWidth-1])
1670 KnownOne2 |= ~LowBits;
1672 KnownZero |= KnownZero2 & Mask;
1673 KnownOne |= KnownOne2 & Mask;
1675 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1680 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1681 const APInt &RA = Rem->getAPIntValue();
1682 if (RA.isPowerOf2()) {
1683 APInt LowBits = (RA - 1);
1684 APInt Mask2 = LowBits & Mask;
1685 KnownZero |= ~LowBits & Mask;
1686 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1687 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1692 // Since the result is less than or equal to either operand, any leading
1693 // zero bits in either operand must also exist in the result.
1694 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1695 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1697 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1700 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1701 KnownZero2.countLeadingOnes());
1703 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1707 // Allow the target to implement this method for its nodes.
1708 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1709 case ISD::INTRINSIC_WO_CHAIN:
1710 case ISD::INTRINSIC_W_CHAIN:
1711 case ISD::INTRINSIC_VOID:
1712 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1718 /// ComputeNumSignBits - Return the number of times the sign bit of the
1719 /// register is replicated into the other bits. We know that at least 1 bit
1720 /// is always equal to the sign bit (itself), but other cases can give us
1721 /// information. For example, immediately after an "SRA X, 2", we know that
1722 /// the top 3 bits are all equal to each other, so we return 3.
1723 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1724 MVT VT = Op.getValueType();
1725 assert(VT.isInteger() && "Invalid VT!");
1726 unsigned VTBits = VT.getSizeInBits();
1728 unsigned FirstAnswer = 1;
1731 return 1; // Limit search depth.
1733 switch (Op.getOpcode()) {
1735 case ISD::AssertSext:
1736 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1737 return VTBits-Tmp+1;
1738 case ISD::AssertZext:
1739 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1742 case ISD::Constant: {
1743 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1744 // If negative, return # leading ones.
1745 if (Val.isNegative())
1746 return Val.countLeadingOnes();
1748 // Return # leading zeros.
1749 return Val.countLeadingZeros();
1752 case ISD::SIGN_EXTEND:
1753 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1754 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1756 case ISD::SIGN_EXTEND_INREG:
1757 // Max of the input and what this extends.
1758 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1761 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1762 return std::max(Tmp, Tmp2);
1765 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1766 // SRA X, C -> adds C sign bits.
1767 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1768 Tmp += C->getValue();
1769 if (Tmp > VTBits) Tmp = VTBits;
1773 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1774 // shl destroys sign bits.
1775 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1776 if (C->getValue() >= VTBits || // Bad shift.
1777 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1778 return Tmp - C->getValue();
1783 case ISD::XOR: // NOT is handled here.
1784 // Logical binary ops preserve the number of sign bits at the worst.
1785 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1787 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1788 FirstAnswer = std::min(Tmp, Tmp2);
1789 // We computed what we know about the sign bits as our first
1790 // answer. Now proceed to the generic code that uses
1791 // ComputeMaskedBits, and pick whichever answer is better.
1796 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1797 if (Tmp == 1) return 1; // Early out.
1798 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1799 return std::min(Tmp, Tmp2);
1802 // If setcc returns 0/-1, all bits are sign bits.
1803 if (TLI.getSetCCResultContents() ==
1804 TargetLowering::ZeroOrNegativeOneSetCCResult)
1809 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1810 unsigned RotAmt = C->getValue() & (VTBits-1);
1812 // Handle rotate right by N like a rotate left by 32-N.
1813 if (Op.getOpcode() == ISD::ROTR)
1814 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1816 // If we aren't rotating out all of the known-in sign bits, return the
1817 // number that are left. This handles rotl(sext(x), 1) for example.
1818 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1819 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1823 // Add can have at most one carry bit. Thus we know that the output
1824 // is, at worst, one more bit than the inputs.
1825 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1826 if (Tmp == 1) return 1; // Early out.
1828 // Special case decrementing a value (ADD X, -1):
1829 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1830 if (CRHS->isAllOnesValue()) {
1831 APInt KnownZero, KnownOne;
1832 APInt Mask = APInt::getAllOnesValue(VTBits);
1833 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1835 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1837 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1840 // If we are subtracting one from a positive number, there is no carry
1841 // out of the result.
1842 if (KnownZero.isNegative())
1846 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1847 if (Tmp2 == 1) return 1;
1848 return std::min(Tmp, Tmp2)-1;
1852 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1853 if (Tmp2 == 1) return 1;
1856 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1857 if (CLHS->isNullValue()) {
1858 APInt KnownZero, KnownOne;
1859 APInt Mask = APInt::getAllOnesValue(VTBits);
1860 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1861 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1863 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1866 // If the input is known to be positive (the sign bit is known clear),
1867 // the output of the NEG has the same number of sign bits as the input.
1868 if (KnownZero.isNegative())
1871 // Otherwise, we treat this like a SUB.
1874 // Sub can have at most one carry bit. Thus we know that the output
1875 // is, at worst, one more bit than the inputs.
1876 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1877 if (Tmp == 1) return 1; // Early out.
1878 return std::min(Tmp, Tmp2)-1;
1881 // FIXME: it's tricky to do anything useful for this, but it is an important
1882 // case for targets like X86.
1886 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1887 if (Op.getOpcode() == ISD::LOAD) {
1888 LoadSDNode *LD = cast<LoadSDNode>(Op);
1889 unsigned ExtType = LD->getExtensionType();
1892 case ISD::SEXTLOAD: // '17' bits known
1893 Tmp = LD->getMemoryVT().getSizeInBits();
1894 return VTBits-Tmp+1;
1895 case ISD::ZEXTLOAD: // '16' bits known
1896 Tmp = LD->getMemoryVT().getSizeInBits();
1901 // Allow the target to implement this method for its nodes.
1902 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1903 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1904 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1905 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1906 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1907 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1910 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1911 // use this information.
1912 APInt KnownZero, KnownOne;
1913 APInt Mask = APInt::getAllOnesValue(VTBits);
1914 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1916 if (KnownZero.isNegative()) { // sign bit is 0
1918 } else if (KnownOne.isNegative()) { // sign bit is 1;
1925 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1926 // the number of identical bits in the top of the input value.
1928 Mask <<= Mask.getBitWidth()-VTBits;
1929 // Return # leading zeros. We use 'min' here in case Val was zero before
1930 // shifting. We don't want to return '64' as for an i32 "0".
1931 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1935 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1936 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1937 if (!GA) return false;
1938 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1939 if (!GV) return false;
1940 MachineModuleInfo *MMI = getMachineModuleInfo();
1941 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1945 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1946 /// element of the result of the vector shuffle.
1947 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1948 MVT VT = N->getValueType(0);
1949 SDOperand PermMask = N->getOperand(2);
1950 SDOperand Idx = PermMask.getOperand(i);
1951 if (Idx.getOpcode() == ISD::UNDEF)
1952 return getNode(ISD::UNDEF, VT.getVectorElementType());
1953 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1954 unsigned NumElems = PermMask.getNumOperands();
1955 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1958 if (V.getOpcode() == ISD::BIT_CONVERT) {
1959 V = V.getOperand(0);
1960 if (V.getValueType().getVectorNumElements() != NumElems)
1963 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1964 return (Index == 0) ? V.getOperand(0)
1965 : getNode(ISD::UNDEF, VT.getVectorElementType());
1966 if (V.getOpcode() == ISD::BUILD_VECTOR)
1967 return V.getOperand(Index);
1968 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1969 return getShuffleScalarElt(V.Val, Index);
1974 /// getNode - Gets or creates the specified node.
1976 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1977 FoldingSetNodeID ID;
1978 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1980 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1981 return SDOperand(E, 0);
1982 SDNode *N = getAllocator().Allocate<SDNode>();
1983 new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
1984 CSEMap.InsertNode(N, IP);
1986 AllNodes.push_back(N);
1990 return SDOperand(N, 0);
1993 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1994 // Constant fold unary operations with an integer constant operand.
1995 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1996 const APInt &Val = C->getAPIntValue();
1997 unsigned BitWidth = VT.getSizeInBits();
2000 case ISD::SIGN_EXTEND:
2001 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
2002 case ISD::ANY_EXTEND:
2003 case ISD::ZERO_EXTEND:
2005 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
2006 case ISD::UINT_TO_FP:
2007 case ISD::SINT_TO_FP: {
2008 const uint64_t zero[] = {0, 0};
2009 // No compile time operations on this type.
2010 if (VT==MVT::ppcf128)
2012 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
2013 (void)apf.convertFromAPInt(Val,
2014 Opcode==ISD::SINT_TO_FP,
2015 APFloat::rmNearestTiesToEven);
2016 return getConstantFP(apf, VT);
2018 case ISD::BIT_CONVERT:
2019 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2020 return getConstantFP(Val.bitsToFloat(), VT);
2021 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2022 return getConstantFP(Val.bitsToDouble(), VT);
2025 return getConstant(Val.byteSwap(), VT);
2027 return getConstant(Val.countPopulation(), VT);
2029 return getConstant(Val.countLeadingZeros(), VT);
2031 return getConstant(Val.countTrailingZeros(), VT);
2035 // Constant fold unary operations with a floating point constant operand.
2036 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
2037 APFloat V = C->getValueAPF(); // make copy
2038 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2042 return getConstantFP(V, VT);
2045 return getConstantFP(V, VT);
2047 case ISD::FP_EXTEND:
2048 // This can return overflow, underflow, or inexact; we don't care.
2049 // FIXME need to be more flexible about rounding mode.
2050 (void)V.convert(*MVTToAPFloatSemantics(VT),
2051 APFloat::rmNearestTiesToEven);
2052 return getConstantFP(V, VT);
2053 case ISD::FP_TO_SINT:
2054 case ISD::FP_TO_UINT: {
2056 assert(integerPartWidth >= 64);
2057 // FIXME need to be more flexible about rounding mode.
2058 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2059 Opcode==ISD::FP_TO_SINT,
2060 APFloat::rmTowardZero);
2061 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2063 return getConstant(x, VT);
2065 case ISD::BIT_CONVERT:
2066 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2067 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2068 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2069 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2075 unsigned OpOpcode = Operand.Val->getOpcode();
2077 case ISD::TokenFactor:
2078 return Operand; // Factor of one node? No need.
2079 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2080 case ISD::FP_EXTEND:
2081 assert(VT.isFloatingPoint() &&
2082 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2083 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2084 if (Operand.getOpcode() == ISD::UNDEF)
2085 return getNode(ISD::UNDEF, VT);
2087 case ISD::SIGN_EXTEND:
2088 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2089 "Invalid SIGN_EXTEND!");
2090 if (Operand.getValueType() == VT) return Operand; // noop extension
2091 assert(Operand.getValueType().bitsLT(VT)
2092 && "Invalid sext node, dst < src!");
2093 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2094 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2096 case ISD::ZERO_EXTEND:
2097 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2098 "Invalid ZERO_EXTEND!");
2099 if (Operand.getValueType() == VT) return Operand; // noop extension
2100 assert(Operand.getValueType().bitsLT(VT)
2101 && "Invalid zext node, dst < src!");
2102 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2103 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2105 case ISD::ANY_EXTEND:
2106 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2107 "Invalid ANY_EXTEND!");
2108 if (Operand.getValueType() == VT) return Operand; // noop extension
2109 assert(Operand.getValueType().bitsLT(VT)
2110 && "Invalid anyext node, dst < src!");
2111 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2112 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2113 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2116 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2117 "Invalid TRUNCATE!");
2118 if (Operand.getValueType() == VT) return Operand; // noop truncate
2119 assert(Operand.getValueType().bitsGT(VT)
2120 && "Invalid truncate node, src < dst!");
2121 if (OpOpcode == ISD::TRUNCATE)
2122 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2123 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2124 OpOpcode == ISD::ANY_EXTEND) {
2125 // If the source is smaller than the dest, we still need an extend.
2126 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2127 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2128 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2129 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2131 return Operand.Val->getOperand(0);
2134 case ISD::BIT_CONVERT:
2135 // Basic sanity checking.
2136 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2137 && "Cannot BIT_CONVERT between types of different sizes!");
2138 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2139 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2140 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2141 if (OpOpcode == ISD::UNDEF)
2142 return getNode(ISD::UNDEF, VT);
2144 case ISD::SCALAR_TO_VECTOR:
2145 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2146 VT.getVectorElementType() == Operand.getValueType() &&
2147 "Illegal SCALAR_TO_VECTOR node!");
2148 if (OpOpcode == ISD::UNDEF)
2149 return getNode(ISD::UNDEF, VT);
2150 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2151 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2152 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2153 Operand.getConstantOperandVal(1) == 0 &&
2154 Operand.getOperand(0).getValueType() == VT)
2155 return Operand.getOperand(0);
2158 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2159 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2160 Operand.Val->getOperand(0));
2161 if (OpOpcode == ISD::FNEG) // --X -> X
2162 return Operand.Val->getOperand(0);
2165 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2166 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2171 SDVTList VTs = getVTList(VT);
2172 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2173 FoldingSetNodeID ID;
2174 SDOperand Ops[1] = { Operand };
2175 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2177 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2178 return SDOperand(E, 0);
2179 N = getAllocator().Allocate<UnarySDNode>();
2180 new (N) UnarySDNode(Opcode, VTs, Operand);
2181 CSEMap.InsertNode(N, IP);
2183 N = getAllocator().Allocate<UnarySDNode>();
2184 new (N) UnarySDNode(Opcode, VTs, Operand);
2187 AllNodes.push_back(N);
2191 return SDOperand(N, 0);
2194 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2195 SDOperand N1, SDOperand N2) {
2196 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2197 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2200 case ISD::TokenFactor:
2201 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2202 N2.getValueType() == MVT::Other && "Invalid token factor!");
2203 // Fold trivial token factors.
2204 if (N1.getOpcode() == ISD::EntryToken) return N2;
2205 if (N2.getOpcode() == ISD::EntryToken) return N1;
2208 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2209 N1.getValueType() == VT && "Binary operator types must match!");
2210 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2211 // worth handling here.
2212 if (N2C && N2C->isNullValue())
2214 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2221 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2222 N1.getValueType() == VT && "Binary operator types must match!");
2223 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2224 // it's worth handling here.
2225 if (N2C && N2C->isNullValue())
2232 assert(VT.isInteger() && "This operator does not apply to FP types!");
2242 assert(N1.getValueType() == N2.getValueType() &&
2243 N1.getValueType() == VT && "Binary operator types must match!");
2245 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2246 assert(N1.getValueType() == VT &&
2247 N1.getValueType().isFloatingPoint() &&
2248 N2.getValueType().isFloatingPoint() &&
2249 "Invalid FCOPYSIGN!");
2256 assert(VT == N1.getValueType() &&
2257 "Shift operators return type must be the same as their first arg");
2258 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2259 "Shifts only work on integers");
2261 // Always fold shifts of i1 values so the code generator doesn't need to
2262 // handle them. Since we know the size of the shift has to be less than the
2263 // size of the value, the shift/rotate count is guaranteed to be zero.
2267 case ISD::FP_ROUND_INREG: {
2268 MVT EVT = cast<VTSDNode>(N2)->getVT();
2269 assert(VT == N1.getValueType() && "Not an inreg round!");
2270 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2271 "Cannot FP_ROUND_INREG integer types");
2272 assert(EVT.bitsLE(VT) && "Not rounding down!");
2273 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2277 assert(VT.isFloatingPoint() &&
2278 N1.getValueType().isFloatingPoint() &&
2279 VT.bitsLE(N1.getValueType()) &&
2280 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2281 if (N1.getValueType() == VT) return N1; // noop conversion.
2283 case ISD::AssertSext:
2284 case ISD::AssertZext: {
2285 MVT EVT = cast<VTSDNode>(N2)->getVT();
2286 assert(VT == N1.getValueType() && "Not an inreg extend!");
2287 assert(VT.isInteger() && EVT.isInteger() &&
2288 "Cannot *_EXTEND_INREG FP types");
2289 assert(EVT.bitsLE(VT) && "Not extending!");
2290 if (VT == EVT) return N1; // noop assertion.
2293 case ISD::SIGN_EXTEND_INREG: {
2294 MVT EVT = cast<VTSDNode>(N2)->getVT();
2295 assert(VT == N1.getValueType() && "Not an inreg extend!");
2296 assert(VT.isInteger() && EVT.isInteger() &&
2297 "Cannot *_EXTEND_INREG FP types");
2298 assert(EVT.bitsLE(VT) && "Not extending!");
2299 if (EVT == VT) return N1; // Not actually extending
2302 APInt Val = N1C->getAPIntValue();
2303 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2304 Val <<= Val.getBitWidth()-FromBits;
2305 Val = Val.ashr(Val.getBitWidth()-FromBits);
2306 return getConstant(Val, VT);
2310 case ISD::EXTRACT_VECTOR_ELT:
2311 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2313 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2314 if (N1.getOpcode() == ISD::UNDEF)
2315 return getNode(ISD::UNDEF, VT);
2317 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2318 // expanding copies of large vectors from registers.
2319 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2320 N1.getNumOperands() > 0) {
2322 N1.getOperand(0).getValueType().getVectorNumElements();
2323 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2324 N1.getOperand(N2C->getValue() / Factor),
2325 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2328 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2329 // expanding large vector constants.
2330 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2331 return N1.getOperand(N2C->getValue());
2333 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2334 // operations are lowered to scalars.
2335 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2336 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2338 return N1.getOperand(1);
2340 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2343 case ISD::EXTRACT_ELEMENT:
2344 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2345 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2346 (N1.getValueType().isInteger() == VT.isInteger()) &&
2347 "Wrong types for EXTRACT_ELEMENT!");
2349 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2350 // 64-bit integers into 32-bit parts. Instead of building the extract of
2351 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2352 if (N1.getOpcode() == ISD::BUILD_PAIR)
2353 return N1.getOperand(N2C->getValue());
2355 // EXTRACT_ELEMENT of a constant int is also very common.
2356 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2357 unsigned ElementSize = VT.getSizeInBits();
2358 unsigned Shift = ElementSize * N2C->getValue();
2359 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2360 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2363 case ISD::EXTRACT_SUBVECTOR:
2364 if (N1.getValueType() == VT) // Trivial extraction.
2371 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2373 case ISD::ADD: return getConstant(C1 + C2, VT);
2374 case ISD::SUB: return getConstant(C1 - C2, VT);
2375 case ISD::MUL: return getConstant(C1 * C2, VT);
2377 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2380 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2383 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2386 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2388 case ISD::AND : return getConstant(C1 & C2, VT);
2389 case ISD::OR : return getConstant(C1 | C2, VT);
2390 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2391 case ISD::SHL : return getConstant(C1 << C2, VT);
2392 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2393 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2394 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2395 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2398 } else { // Cannonicalize constant to RHS if commutative
2399 if (isCommutativeBinOp(Opcode)) {
2400 std::swap(N1C, N2C);
2406 // Constant fold FP operations.
2407 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2408 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2410 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2411 // Cannonicalize constant to RHS if commutative
2412 std::swap(N1CFP, N2CFP);
2414 } else if (N2CFP && VT != MVT::ppcf128) {
2415 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2416 APFloat::opStatus s;
2419 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2420 if (s != APFloat::opInvalidOp)
2421 return getConstantFP(V1, VT);
2424 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2425 if (s!=APFloat::opInvalidOp)
2426 return getConstantFP(V1, VT);
2429 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2430 if (s!=APFloat::opInvalidOp)
2431 return getConstantFP(V1, VT);
2434 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2435 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2436 return getConstantFP(V1, VT);
2439 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2440 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2441 return getConstantFP(V1, VT);
2443 case ISD::FCOPYSIGN:
2445 return getConstantFP(V1, VT);
2451 // Canonicalize an UNDEF to the RHS, even over a constant.
2452 if (N1.getOpcode() == ISD::UNDEF) {
2453 if (isCommutativeBinOp(Opcode)) {
2457 case ISD::FP_ROUND_INREG:
2458 case ISD::SIGN_EXTEND_INREG:
2464 return N1; // fold op(undef, arg2) -> undef
2472 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2473 // For vectors, we can't easily build an all zero vector, just return
2480 // Fold a bunch of operators when the RHS is undef.
2481 if (N2.getOpcode() == ISD::UNDEF) {
2484 if (N1.getOpcode() == ISD::UNDEF)
2485 // Handle undef ^ undef -> 0 special case. This is a common
2487 return getConstant(0, VT);
2502 return N2; // fold op(arg1, undef) -> undef
2508 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2509 // For vectors, we can't easily build an all zero vector, just return
2514 return getConstant(VT.getIntegerVTBitMask(), VT);
2515 // For vectors, we can't easily build an all one vector, just return
2523 // Memoize this node if possible.
2525 SDVTList VTs = getVTList(VT);
2526 if (VT != MVT::Flag) {
2527 SDOperand Ops[] = { N1, N2 };
2528 FoldingSetNodeID ID;
2529 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2531 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2532 return SDOperand(E, 0);
2533 N = getAllocator().Allocate<BinarySDNode>();
2534 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2535 CSEMap.InsertNode(N, IP);
2537 N = getAllocator().Allocate<BinarySDNode>();
2538 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2541 AllNodes.push_back(N);
2545 return SDOperand(N, 0);
2548 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2549 SDOperand N1, SDOperand N2, SDOperand N3) {
2550 // Perform various simplifications.
2551 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2552 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2555 // Use FoldSetCC to simplify SETCC's.
2556 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2557 if (Simp.Val) return Simp;
2562 if (N1C->getValue())
2563 return N2; // select true, X, Y -> X
2565 return N3; // select false, X, Y -> Y
2568 if (N2 == N3) return N2; // select C, X, X -> X
2572 if (N2C->getValue()) // Unconditional branch
2573 return getNode(ISD::BR, MVT::Other, N1, N3);
2575 return N1; // Never-taken branch
2578 case ISD::VECTOR_SHUFFLE:
2579 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2580 VT.isVector() && N3.getValueType().isVector() &&
2581 N3.getOpcode() == ISD::BUILD_VECTOR &&
2582 VT.getVectorNumElements() == N3.getNumOperands() &&
2583 "Illegal VECTOR_SHUFFLE node!");
2585 case ISD::BIT_CONVERT:
2586 // Fold bit_convert nodes from a type to themselves.
2587 if (N1.getValueType() == VT)
2592 // Memoize node if it doesn't produce a flag.
2594 SDVTList VTs = getVTList(VT);
2595 if (VT != MVT::Flag) {
2596 SDOperand Ops[] = { N1, N2, N3 };
2597 FoldingSetNodeID ID;
2598 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2600 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2601 return SDOperand(E, 0);
2602 N = getAllocator().Allocate<TernarySDNode>();
2603 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2604 CSEMap.InsertNode(N, IP);
2606 N = getAllocator().Allocate<TernarySDNode>();
2607 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2609 AllNodes.push_back(N);
2613 return SDOperand(N, 0);
2616 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2617 SDOperand N1, SDOperand N2, SDOperand N3,
2619 SDOperand Ops[] = { N1, N2, N3, N4 };
2620 return getNode(Opcode, VT, Ops, 4);
2623 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2624 SDOperand N1, SDOperand N2, SDOperand N3,
2625 SDOperand N4, SDOperand N5) {
2626 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2627 return getNode(Opcode, VT, Ops, 5);
2630 /// getMemsetValue - Vectorized representation of the memset value
2632 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2633 unsigned NumBits = VT.isVector() ?
2634 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2635 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2636 APInt Val = APInt(NumBits, C->getValue() & 255);
2638 for (unsigned i = NumBits; i > 8; i >>= 1) {
2639 Val = (Val << Shift) | Val;
2643 return DAG.getConstant(Val, VT);
2644 return DAG.getConstantFP(APFloat(Val), VT);
2647 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2649 for (unsigned i = NumBits; i > 8; i >>= 1) {
2650 Value = DAG.getNode(ISD::OR, VT,
2651 DAG.getNode(ISD::SHL, VT, Value,
2652 DAG.getConstant(Shift, MVT::i8)), Value);
2659 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2660 /// used when a memcpy is turned into a memset when the source is a constant
2662 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2663 const TargetLowering &TLI,
2664 std::string &Str, unsigned Offset) {
2665 // Handle vector with all elements zero.
2668 return DAG.getConstant(0, VT);
2669 unsigned NumElts = VT.getVectorNumElements();
2670 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2671 return DAG.getNode(ISD::BIT_CONVERT, VT,
2672 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2675 assert(!VT.isVector() && "Can't handle vector type here!");
2676 unsigned NumBits = VT.getSizeInBits();
2677 unsigned MSB = NumBits / 8;
2679 if (TLI.isLittleEndian())
2680 Offset = Offset + MSB - 1;
2681 for (unsigned i = 0; i != MSB; ++i) {
2682 Val = (Val << 8) | (unsigned char)Str[Offset];
2683 Offset += TLI.isLittleEndian() ? -1 : 1;
2685 return DAG.getConstant(Val, VT);
2688 /// getMemBasePlusOffset - Returns base and offset node for the
2690 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2691 SelectionDAG &DAG) {
2692 MVT VT = Base.getValueType();
2693 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2696 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2698 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2699 unsigned SrcDelta = 0;
2700 GlobalAddressSDNode *G = NULL;
2701 if (Src.getOpcode() == ISD::GlobalAddress)
2702 G = cast<GlobalAddressSDNode>(Src);
2703 else if (Src.getOpcode() == ISD::ADD &&
2704 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2705 Src.getOperand(1).getOpcode() == ISD::Constant) {
2706 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2707 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2712 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2713 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2719 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2720 /// to replace the memset / memcpy is below the threshold. It also returns the
2721 /// types of the sequence of memory ops to perform memset / memcpy.
2723 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2724 SDOperand Dst, SDOperand Src,
2725 unsigned Limit, uint64_t Size, unsigned &Align,
2726 std::string &Str, bool &isSrcStr,
2728 const TargetLowering &TLI) {
2729 isSrcStr = isMemSrcFromString(Src, Str);
2730 bool isSrcConst = isa<ConstantSDNode>(Src);
2731 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2732 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2733 if (VT != MVT::iAny) {
2734 unsigned NewAlign = (unsigned)
2735 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2736 // If source is a string constant, this will require an unaligned load.
2737 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2738 if (Dst.getOpcode() != ISD::FrameIndex) {
2739 // Can't change destination alignment. It requires a unaligned store.
2743 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2744 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2745 if (MFI->isFixedObjectIndex(FI)) {
2746 // Can't change destination alignment. It requires a unaligned store.
2750 // Give the stack frame object a larger alignment if needed.
2751 if (MFI->getObjectAlignment(FI) < NewAlign)
2752 MFI->setObjectAlignment(FI, NewAlign);
2759 if (VT == MVT::iAny) {
2763 switch (Align & 7) {
2764 case 0: VT = MVT::i64; break;
2765 case 4: VT = MVT::i32; break;
2766 case 2: VT = MVT::i16; break;
2767 default: VT = MVT::i8; break;
2772 while (!TLI.isTypeLegal(LVT))
2773 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2774 assert(LVT.isInteger());
2780 unsigned NumMemOps = 0;
2782 unsigned VTSize = VT.getSizeInBits() / 8;
2783 while (VTSize > Size) {
2784 // For now, only use non-vector load / store's for the left-over pieces.
2785 if (VT.isVector()) {
2787 while (!TLI.isTypeLegal(VT))
2788 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2789 VTSize = VT.getSizeInBits() / 8;
2791 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2796 if (++NumMemOps > Limit)
2798 MemOps.push_back(VT);
2805 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2806 SDOperand Chain, SDOperand Dst,
2807 SDOperand Src, uint64_t Size,
2808 unsigned Align, bool AlwaysInline,
2809 const Value *DstSV, uint64_t DstSVOff,
2810 const Value *SrcSV, uint64_t SrcSVOff){
2811 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2813 // Expand memcpy to a series of load and store ops if the size operand falls
2814 // below a certain threshold.
2815 std::vector<MVT> MemOps;
2816 uint64_t Limit = -1;
2818 Limit = TLI.getMaxStoresPerMemcpy();
2819 unsigned DstAlign = Align; // Destination alignment can change.
2822 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2823 Str, CopyFromStr, DAG, TLI))
2827 bool isZeroStr = CopyFromStr && Str.empty();
2828 SmallVector<SDOperand, 8> OutChains;
2829 unsigned NumMemOps = MemOps.size();
2830 uint64_t SrcOff = 0, DstOff = 0;
2831 for (unsigned i = 0; i < NumMemOps; i++) {
2833 unsigned VTSize = VT.getSizeInBits() / 8;
2834 SDOperand Value, Store;
2836 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2837 // It's unlikely a store of a vector immediate can be done in a single
2838 // instruction. It would require a load from a constantpool first.
2839 // We also handle store a vector with all zero's.
2840 // FIXME: Handle other cases where store of vector immediate is done in
2841 // a single instruction.
2842 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2843 Store = DAG.getStore(Chain, Value,
2844 getMemBasePlusOffset(Dst, DstOff, DAG),
2845 DstSV, DstSVOff + DstOff, false, DstAlign);
2847 Value = DAG.getLoad(VT, Chain,
2848 getMemBasePlusOffset(Src, SrcOff, DAG),
2849 SrcSV, SrcSVOff + SrcOff, false, Align);
2850 Store = DAG.getStore(Chain, Value,
2851 getMemBasePlusOffset(Dst, DstOff, DAG),
2852 DstSV, DstSVOff + DstOff, false, DstAlign);
2854 OutChains.push_back(Store);
2859 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2860 &OutChains[0], OutChains.size());
2863 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2864 SDOperand Chain, SDOperand Dst,
2865 SDOperand Src, uint64_t Size,
2866 unsigned Align, bool AlwaysInline,
2867 const Value *DstSV, uint64_t DstSVOff,
2868 const Value *SrcSV, uint64_t SrcSVOff){
2869 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2871 // Expand memmove to a series of load and store ops if the size operand falls
2872 // below a certain threshold.
2873 std::vector<MVT> MemOps;
2874 uint64_t Limit = -1;
2876 Limit = TLI.getMaxStoresPerMemmove();
2877 unsigned DstAlign = Align; // Destination alignment can change.
2880 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2881 Str, CopyFromStr, DAG, TLI))
2884 uint64_t SrcOff = 0, DstOff = 0;
2886 SmallVector<SDOperand, 8> LoadValues;
2887 SmallVector<SDOperand, 8> LoadChains;
2888 SmallVector<SDOperand, 8> OutChains;
2889 unsigned NumMemOps = MemOps.size();
2890 for (unsigned i = 0; i < NumMemOps; i++) {
2892 unsigned VTSize = VT.getSizeInBits() / 8;
2893 SDOperand Value, Store;
2895 Value = DAG.getLoad(VT, Chain,
2896 getMemBasePlusOffset(Src, SrcOff, DAG),
2897 SrcSV, SrcSVOff + SrcOff, false, Align);
2898 LoadValues.push_back(Value);
2899 LoadChains.push_back(Value.getValue(1));
2902 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2903 &LoadChains[0], LoadChains.size());
2905 for (unsigned i = 0; i < NumMemOps; i++) {
2907 unsigned VTSize = VT.getSizeInBits() / 8;
2908 SDOperand Value, Store;
2910 Store = DAG.getStore(Chain, LoadValues[i],
2911 getMemBasePlusOffset(Dst, DstOff, DAG),
2912 DstSV, DstSVOff + DstOff, false, DstAlign);
2913 OutChains.push_back(Store);
2917 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2918 &OutChains[0], OutChains.size());
2921 static SDOperand getMemsetStores(SelectionDAG &DAG,
2922 SDOperand Chain, SDOperand Dst,
2923 SDOperand Src, uint64_t Size,
2925 const Value *DstSV, uint64_t DstSVOff) {
2926 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2928 // Expand memset to a series of load/store ops if the size operand
2929 // falls below a certain threshold.
2930 std::vector<MVT> MemOps;
2933 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2934 Size, Align, Str, CopyFromStr, DAG, TLI))
2937 SmallVector<SDOperand, 8> OutChains;
2938 uint64_t DstOff = 0;
2940 unsigned NumMemOps = MemOps.size();
2941 for (unsigned i = 0; i < NumMemOps; i++) {
2943 unsigned VTSize = VT.getSizeInBits() / 8;
2944 SDOperand Value = getMemsetValue(Src, VT, DAG);
2945 SDOperand Store = DAG.getStore(Chain, Value,
2946 getMemBasePlusOffset(Dst, DstOff, DAG),
2947 DstSV, DstSVOff + DstOff);
2948 OutChains.push_back(Store);
2952 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2953 &OutChains[0], OutChains.size());
2956 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2957 SDOperand Src, SDOperand Size,
2958 unsigned Align, bool AlwaysInline,
2959 const Value *DstSV, uint64_t DstSVOff,
2960 const Value *SrcSV, uint64_t SrcSVOff) {
2962 // Check to see if we should lower the memcpy to loads and stores first.
2963 // For cases within the target-specified limits, this is the best choice.
2964 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2966 // Memcpy with size zero? Just return the original chain.
2967 if (ConstantSize->isNullValue())
2971 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2972 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2977 // Then check to see if we should lower the memcpy with target-specific
2978 // code. If the target chooses to do this, this is the next best.
2980 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2982 DstSV, DstSVOff, SrcSV, SrcSVOff);
2986 // If we really need inline code and the target declined to provide it,
2987 // use a (potentially long) sequence of loads and stores.
2989 assert(ConstantSize && "AlwaysInline requires a constant size!");
2990 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2991 ConstantSize->getValue(), Align, true,
2992 DstSV, DstSVOff, SrcSV, SrcSVOff);
2995 // Emit a library call.
2996 TargetLowering::ArgListTy Args;
2997 TargetLowering::ArgListEntry Entry;
2998 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2999 Entry.Node = Dst; Args.push_back(Entry);
3000 Entry.Node = Src; Args.push_back(Entry);
3001 Entry.Node = Size; Args.push_back(Entry);
3002 std::pair<SDOperand,SDOperand> CallResult =
3003 TLI.LowerCallTo(Chain, Type::VoidTy,
3004 false, false, false, CallingConv::C, false,
3005 getExternalSymbol("memcpy", TLI.getPointerTy()),
3007 return CallResult.second;
3010 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
3011 SDOperand Src, SDOperand Size,
3013 const Value *DstSV, uint64_t DstSVOff,
3014 const Value *SrcSV, uint64_t SrcSVOff) {
3016 // Check to see if we should lower the memmove to loads and stores first.
3017 // For cases within the target-specified limits, this is the best choice.
3018 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3020 // Memmove with size zero? Just return the original chain.
3021 if (ConstantSize->isNullValue())
3025 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
3026 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3031 // Then check to see if we should lower the memmove with target-specific
3032 // code. If the target chooses to do this, this is the next best.
3034 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
3035 DstSV, DstSVOff, SrcSV, SrcSVOff);
3039 // Emit a library call.
3040 TargetLowering::ArgListTy Args;
3041 TargetLowering::ArgListEntry Entry;
3042 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3043 Entry.Node = Dst; Args.push_back(Entry);
3044 Entry.Node = Src; Args.push_back(Entry);
3045 Entry.Node = Size; Args.push_back(Entry);
3046 std::pair<SDOperand,SDOperand> CallResult =
3047 TLI.LowerCallTo(Chain, Type::VoidTy,
3048 false, false, false, CallingConv::C, false,
3049 getExternalSymbol("memmove", TLI.getPointerTy()),
3051 return CallResult.second;
3054 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
3055 SDOperand Src, SDOperand Size,
3057 const Value *DstSV, uint64_t DstSVOff) {
3059 // Check to see if we should lower the memset to stores first.
3060 // For cases within the target-specified limits, this is the best choice.
3061 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3063 // Memset with size zero? Just return the original chain.
3064 if (ConstantSize->isNullValue())
3068 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3074 // Then check to see if we should lower the memset with target-specific
3075 // code. If the target chooses to do this, this is the next best.
3077 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3082 // Emit a library call.
3083 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3084 TargetLowering::ArgListTy Args;
3085 TargetLowering::ArgListEntry Entry;
3086 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3087 Args.push_back(Entry);
3088 // Extend or truncate the argument to be an i32 value for the call.
3089 if (Src.getValueType().bitsGT(MVT::i32))
3090 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3092 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3093 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3094 Args.push_back(Entry);
3095 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3096 Args.push_back(Entry);
3097 std::pair<SDOperand,SDOperand> CallResult =
3098 TLI.LowerCallTo(Chain, Type::VoidTy,
3099 false, false, false, CallingConv::C, false,
3100 getExternalSymbol("memset", TLI.getPointerTy()),
3102 return CallResult.second;
3105 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3106 SDOperand Ptr, SDOperand Cmp,
3107 SDOperand Swp, const Value* PtrVal,
3108 unsigned Alignment) {
3109 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3110 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3112 MVT VT = Cmp.getValueType();
3114 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3115 Alignment = getMVTAlignment(VT);
3117 SDVTList VTs = getVTList(VT, MVT::Other);
3118 FoldingSetNodeID ID;
3119 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3120 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3122 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3123 return SDOperand(E, 0);
3124 SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3125 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3126 CSEMap.InsertNode(N, IP);
3127 AllNodes.push_back(N);
3128 return SDOperand(N, 0);
3131 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3132 SDOperand Ptr, SDOperand Val,
3133 const Value* PtrVal,
3134 unsigned Alignment) {
3135 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3136 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3137 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3138 || Opcode == ISD::ATOMIC_LOAD_NAND
3139 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3140 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3141 && "Invalid Atomic Op");
3143 MVT VT = Val.getValueType();
3145 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3146 Alignment = getMVTAlignment(VT);
3148 SDVTList VTs = getVTList(VT, MVT::Other);
3149 FoldingSetNodeID ID;
3150 SDOperand Ops[] = {Chain, Ptr, Val};
3151 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3153 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3154 return SDOperand(E, 0);
3155 SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3156 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
3157 CSEMap.InsertNode(N, IP);
3158 AllNodes.push_back(N);
3159 return SDOperand(N, 0);
3162 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3163 /// Allowed to return something different (and simpler) if Simplify is true.
3164 SDOperand SelectionDAG::getMergeValues(const SDOperand *Ops, unsigned NumOps,
3166 if (Simplify && NumOps == 1)
3169 SmallVector<MVT, 4> VTs;
3170 VTs.reserve(NumOps);
3171 for (unsigned i = 0; i < NumOps; ++i)
3172 VTs.push_back(Ops[i].getValueType());
3173 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3177 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3178 MVT VT, SDOperand Chain,
3179 SDOperand Ptr, SDOperand Offset,
3180 const Value *SV, int SVOffset, MVT EVT,
3181 bool isVolatile, unsigned Alignment) {
3182 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3183 Alignment = getMVTAlignment(VT);
3186 ExtType = ISD::NON_EXTLOAD;
3187 } else if (ExtType == ISD::NON_EXTLOAD) {
3188 assert(VT == EVT && "Non-extending load from different memory type!");
3192 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3194 assert(EVT.bitsLT(VT) &&
3195 "Should only be an extending load, not truncating!");
3196 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3197 "Cannot sign/zero extend a FP/Vector load!");
3198 assert(VT.isInteger() == EVT.isInteger() &&
3199 "Cannot convert from FP to Int or Int -> FP!");
3202 bool Indexed = AM != ISD::UNINDEXED;
3203 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3204 "Unindexed load with an offset!");
3206 SDVTList VTs = Indexed ?
3207 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3208 SDOperand Ops[] = { Chain, Ptr, Offset };
3209 FoldingSetNodeID ID;
3210 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3212 ID.AddInteger(ExtType);
3213 ID.AddInteger(EVT.getRawBits());
3214 ID.AddInteger(Alignment);
3215 ID.AddInteger(isVolatile);
3217 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3218 return SDOperand(E, 0);
3219 SDNode *N = getAllocator().Allocate<LoadSDNode>();
3220 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3221 Alignment, isVolatile);
3222 CSEMap.InsertNode(N, IP);
3223 AllNodes.push_back(N);
3224 return SDOperand(N, 0);
3227 SDOperand SelectionDAG::getLoad(MVT VT,
3228 SDOperand Chain, SDOperand Ptr,
3229 const Value *SV, int SVOffset,
3230 bool isVolatile, unsigned Alignment) {
3231 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3232 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3233 SV, SVOffset, VT, isVolatile, Alignment);
3236 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3237 SDOperand Chain, SDOperand Ptr,
3239 int SVOffset, MVT EVT,
3240 bool isVolatile, unsigned Alignment) {
3241 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3242 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3243 SV, SVOffset, EVT, isVolatile, Alignment);
3247 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3248 SDOperand Offset, ISD::MemIndexedMode AM) {
3249 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3250 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3251 "Load is already a indexed load!");
3252 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3253 LD->getChain(), Base, Offset, LD->getSrcValue(),
3254 LD->getSrcValueOffset(), LD->getMemoryVT(),
3255 LD->isVolatile(), LD->getAlignment());
3258 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3259 SDOperand Ptr, const Value *SV, int SVOffset,
3260 bool isVolatile, unsigned Alignment) {
3261 MVT VT = Val.getValueType();
3263 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3264 Alignment = getMVTAlignment(VT);
3266 SDVTList VTs = getVTList(MVT::Other);
3267 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3268 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3269 FoldingSetNodeID ID;
3270 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3271 ID.AddInteger(ISD::UNINDEXED);
3272 ID.AddInteger(false);
3273 ID.AddInteger(VT.getRawBits());
3274 ID.AddInteger(Alignment);
3275 ID.AddInteger(isVolatile);
3277 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3278 return SDOperand(E, 0);
3279 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3280 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3281 VT, SV, SVOffset, Alignment, isVolatile);
3282 CSEMap.InsertNode(N, IP);
3283 AllNodes.push_back(N);
3284 return SDOperand(N, 0);
3287 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3288 SDOperand Ptr, const Value *SV,
3289 int SVOffset, MVT SVT,
3290 bool isVolatile, unsigned Alignment) {
3291 MVT VT = Val.getValueType();
3294 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3296 assert(VT.bitsGT(SVT) && "Not a truncation?");
3297 assert(VT.isInteger() == SVT.isInteger() &&
3298 "Can't do FP-INT conversion!");
3300 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3301 Alignment = getMVTAlignment(VT);
3303 SDVTList VTs = getVTList(MVT::Other);
3304 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3305 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3306 FoldingSetNodeID ID;
3307 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3308 ID.AddInteger(ISD::UNINDEXED);
3310 ID.AddInteger(SVT.getRawBits());
3311 ID.AddInteger(Alignment);
3312 ID.AddInteger(isVolatile);
3314 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3315 return SDOperand(E, 0);
3316 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3317 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3318 SVT, SV, SVOffset, Alignment, isVolatile);
3319 CSEMap.InsertNode(N, IP);
3320 AllNodes.push_back(N);
3321 return SDOperand(N, 0);
3325 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3326 SDOperand Offset, ISD::MemIndexedMode AM) {
3327 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3328 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3329 "Store is already a indexed store!");
3330 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3331 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3332 FoldingSetNodeID ID;
3333 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3335 ID.AddInteger(ST->isTruncatingStore());
3336 ID.AddInteger(ST->getMemoryVT().getRawBits());
3337 ID.AddInteger(ST->getAlignment());
3338 ID.AddInteger(ST->isVolatile());
3340 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3341 return SDOperand(E, 0);
3342 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3343 new (N) StoreSDNode(Ops, VTs, AM,
3344 ST->isTruncatingStore(), ST->getMemoryVT(),
3345 ST->getSrcValue(), ST->getSrcValueOffset(),
3346 ST->getAlignment(), ST->isVolatile());
3347 CSEMap.InsertNode(N, IP);
3348 AllNodes.push_back(N);
3349 return SDOperand(N, 0);
3352 SDOperand SelectionDAG::getVAArg(MVT VT,
3353 SDOperand Chain, SDOperand Ptr,
3355 SDOperand Ops[] = { Chain, Ptr, SV };
3356 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3359 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3360 const SDUse *Ops, unsigned NumOps) {
3362 case 0: return getNode(Opcode, VT);
3363 case 1: return getNode(Opcode, VT, Ops[0].getSDOperand());
3364 case 2: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3365 Ops[1].getSDOperand());
3366 case 3: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3367 Ops[1].getSDOperand(), Ops[2].getSDOperand());
3371 // Copy from an SDUse array into an SDOperand array for use with
3372 // the regular getNode logic.
3373 SmallVector<SDOperand, 8> NewOps;
3374 NewOps.reserve(NumOps);
3375 for (unsigned i = 0; i != NumOps; ++i)
3376 NewOps.push_back(Ops[i].getSDOperand());
3377 return getNode(Opcode, VT, Ops, NumOps);
3380 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3381 const SDOperand *Ops, unsigned NumOps) {
3383 case 0: return getNode(Opcode, VT);
3384 case 1: return getNode(Opcode, VT, Ops[0]);
3385 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3386 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3392 case ISD::SELECT_CC: {
3393 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3394 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3395 "LHS and RHS of condition must have same type!");
3396 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3397 "True and False arms of SelectCC must have same type!");
3398 assert(Ops[2].getValueType() == VT &&
3399 "select_cc node must be of same type as true and false value!");
3403 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3404 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3405 "LHS/RHS of comparison should match types!");
3412 SDVTList VTs = getVTList(VT);
3413 if (VT != MVT::Flag) {
3414 FoldingSetNodeID ID;
3415 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3417 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3418 return SDOperand(E, 0);
3419 N = getAllocator().Allocate<SDNode>();
3420 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3421 CSEMap.InsertNode(N, IP);
3423 N = getAllocator().Allocate<SDNode>();
3424 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3426 AllNodes.push_back(N);
3430 return SDOperand(N, 0);
3433 SDOperand SelectionDAG::getNode(unsigned Opcode,
3434 const std::vector<MVT> &ResultTys,
3435 const SDOperand *Ops, unsigned NumOps) {
3436 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3440 SDOperand SelectionDAG::getNode(unsigned Opcode,
3441 const MVT *VTs, unsigned NumVTs,
3442 const SDOperand *Ops, unsigned NumOps) {
3444 return getNode(Opcode, VTs[0], Ops, NumOps);
3445 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3448 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3449 const SDOperand *Ops, unsigned NumOps) {
3450 if (VTList.NumVTs == 1)
3451 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3454 // FIXME: figure out how to safely handle things like
3455 // int foo(int x) { return 1 << (x & 255); }
3456 // int bar() { return foo(256); }
3458 case ISD::SRA_PARTS:
3459 case ISD::SRL_PARTS:
3460 case ISD::SHL_PARTS:
3461 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3462 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3463 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3464 else if (N3.getOpcode() == ISD::AND)
3465 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3466 // If the and is only masking out bits that cannot effect the shift,
3467 // eliminate the and.
3468 unsigned NumBits = VT.getSizeInBits()*2;
3469 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3470 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3476 // Memoize the node unless it returns a flag.
3478 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3479 FoldingSetNodeID ID;
3480 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3482 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3483 return SDOperand(E, 0);
3485 N = getAllocator().Allocate<UnarySDNode>();
3486 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3487 } else if (NumOps == 2) {
3488 N = getAllocator().Allocate<BinarySDNode>();
3489 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3490 } else if (NumOps == 3) {
3491 N = getAllocator().Allocate<TernarySDNode>();
3492 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3494 N = getAllocator().Allocate<SDNode>();
3495 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3497 CSEMap.InsertNode(N, IP);
3500 N = getAllocator().Allocate<UnarySDNode>();
3501 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3502 } else if (NumOps == 2) {
3503 N = getAllocator().Allocate<BinarySDNode>();
3504 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3505 } else if (NumOps == 3) {
3506 N = getAllocator().Allocate<TernarySDNode>();
3507 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3509 N = getAllocator().Allocate<SDNode>();
3510 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3513 AllNodes.push_back(N);
3517 return SDOperand(N, 0);
3520 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3521 return getNode(Opcode, VTList, 0, 0);
3524 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3526 SDOperand Ops[] = { N1 };
3527 return getNode(Opcode, VTList, Ops, 1);
3530 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3531 SDOperand N1, SDOperand N2) {
3532 SDOperand Ops[] = { N1, N2 };
3533 return getNode(Opcode, VTList, Ops, 2);
3536 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3537 SDOperand N1, SDOperand N2, SDOperand N3) {
3538 SDOperand Ops[] = { N1, N2, N3 };
3539 return getNode(Opcode, VTList, Ops, 3);
3542 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3543 SDOperand N1, SDOperand N2, SDOperand N3,
3545 SDOperand Ops[] = { N1, N2, N3, N4 };
3546 return getNode(Opcode, VTList, Ops, 4);
3549 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3550 SDOperand N1, SDOperand N2, SDOperand N3,
3551 SDOperand N4, SDOperand N5) {
3552 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3553 return getNode(Opcode, VTList, Ops, 5);
3556 SDVTList SelectionDAG::getVTList(MVT VT) {
3557 return makeVTList(SDNode::getValueTypeList(VT), 1);
3560 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3561 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3562 E = VTList.rend(); I != E; ++I)
3563 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
3566 MVT *Array = Allocator.Allocate<MVT>(2);
3569 SDVTList Result = makeVTList(Array, 2);
3570 VTList.push_back(Result);
3574 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
3575 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3576 E = VTList.rend(); I != E; ++I)
3577 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
3581 MVT *Array = Allocator.Allocate<MVT>(3);
3585 SDVTList Result = makeVTList(Array, 3);
3586 VTList.push_back(Result);
3590 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3592 case 0: assert(0 && "Cannot have nodes without results!");
3593 case 1: return getVTList(VTs[0]);
3594 case 2: return getVTList(VTs[0], VTs[1]);
3595 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3599 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3600 E = VTList.rend(); I != E; ++I) {
3601 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
3604 bool NoMatch = false;
3605 for (unsigned i = 2; i != NumVTs; ++i)
3606 if (VTs[i] != I->VTs[i]) {
3614 MVT *Array = Allocator.Allocate<MVT>(NumVTs);
3615 std::copy(VTs, VTs+NumVTs, Array);
3616 SDVTList Result = makeVTList(Array, NumVTs);
3617 VTList.push_back(Result);
3622 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3623 /// specified operands. If the resultant node already exists in the DAG,
3624 /// this does not modify the specified node, instead it returns the node that
3625 /// already exists. If the resultant node does not exist in the DAG, the
3626 /// input node is returned. As a degenerate case, if you specify the same
3627 /// input operands as the node already has, the input node is returned.
3628 SDOperand SelectionDAG::
3629 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3630 SDNode *N = InN.Val;
3631 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3633 // Check to see if there is no change.
3634 if (Op == N->getOperand(0)) return InN;
3636 // See if the modified node already exists.
3637 void *InsertPos = 0;
3638 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3639 return SDOperand(Existing, InN.ResNo);
3641 // Nope it doesn't. Remove the node from its current place in the maps.
3643 RemoveNodeFromCSEMaps(N);
3645 // Now we update the operands.
3646 N->OperandList[0].getVal()->removeUser(0, N);
3647 N->OperandList[0] = Op;
3648 N->OperandList[0].setUser(N);
3649 Op.Val->addUser(0, N);
3651 // If this gets put into a CSE map, add it.
3652 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3656 SDOperand SelectionDAG::
3657 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3658 SDNode *N = InN.Val;
3659 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3661 // Check to see if there is no change.
3662 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3663 return InN; // No operands changed, just return the input node.
3665 // See if the modified node already exists.
3666 void *InsertPos = 0;
3667 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3668 return SDOperand(Existing, InN.ResNo);
3670 // Nope it doesn't. Remove the node from its current place in the maps.
3672 RemoveNodeFromCSEMaps(N);
3674 // Now we update the operands.
3675 if (N->OperandList[0] != Op1) {
3676 N->OperandList[0].getVal()->removeUser(0, N);
3677 N->OperandList[0] = Op1;
3678 N->OperandList[0].setUser(N);
3679 Op1.Val->addUser(0, N);
3681 if (N->OperandList[1] != Op2) {
3682 N->OperandList[1].getVal()->removeUser(1, N);
3683 N->OperandList[1] = Op2;
3684 N->OperandList[1].setUser(N);
3685 Op2.Val->addUser(1, N);
3688 // If this gets put into a CSE map, add it.
3689 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3693 SDOperand SelectionDAG::
3694 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3695 SDOperand Ops[] = { Op1, Op2, Op3 };
3696 return UpdateNodeOperands(N, Ops, 3);
3699 SDOperand SelectionDAG::
3700 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3701 SDOperand Op3, SDOperand Op4) {
3702 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3703 return UpdateNodeOperands(N, Ops, 4);
3706 SDOperand SelectionDAG::
3707 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3708 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3709 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3710 return UpdateNodeOperands(N, Ops, 5);
3713 SDOperand SelectionDAG::
3714 UpdateNodeOperands(SDOperand InN, const SDOperand *Ops, unsigned NumOps) {
3715 SDNode *N = InN.Val;
3716 assert(N->getNumOperands() == NumOps &&
3717 "Update with wrong number of operands");
3719 // Check to see if there is no change.
3720 bool AnyChange = false;
3721 for (unsigned i = 0; i != NumOps; ++i) {
3722 if (Ops[i] != N->getOperand(i)) {
3728 // No operands changed, just return the input node.
3729 if (!AnyChange) return InN;
3731 // See if the modified node already exists.
3732 void *InsertPos = 0;
3733 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3734 return SDOperand(Existing, InN.ResNo);
3736 // Nope it doesn't. Remove the node from its current place in the maps.
3738 RemoveNodeFromCSEMaps(N);
3740 // Now we update the operands.
3741 for (unsigned i = 0; i != NumOps; ++i) {
3742 if (N->OperandList[i] != Ops[i]) {
3743 N->OperandList[i].getVal()->removeUser(i, N);
3744 N->OperandList[i] = Ops[i];
3745 N->OperandList[i].setUser(N);
3746 Ops[i].Val->addUser(i, N);
3750 // If this gets put into a CSE map, add it.
3751 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3755 /// DropOperands - Release the operands and set this node to have
3757 void SDNode::DropOperands() {
3758 // Unlike the code in MorphNodeTo that does this, we don't need to
3759 // watch for dead nodes here.
3760 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3761 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3766 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
3769 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3771 SDVTList VTs = getVTList(VT);
3772 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
3775 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3776 MVT VT, SDOperand Op1) {
3777 SDVTList VTs = getVTList(VT);
3778 SDOperand Ops[] = { Op1 };
3779 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
3782 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3783 MVT VT, SDOperand Op1,
3785 SDVTList VTs = getVTList(VT);
3786 SDOperand Ops[] = { Op1, Op2 };
3787 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
3790 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3791 MVT VT, SDOperand Op1,
3792 SDOperand Op2, SDOperand Op3) {
3793 SDVTList VTs = getVTList(VT);
3794 SDOperand Ops[] = { Op1, Op2, Op3 };
3795 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
3798 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3799 MVT VT, const SDOperand *Ops,
3801 SDVTList VTs = getVTList(VT);
3802 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3805 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3806 MVT VT1, MVT VT2, const SDOperand *Ops,
3808 SDVTList VTs = getVTList(VT1, VT2);
3809 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3812 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3814 SDVTList VTs = getVTList(VT1, VT2);
3815 return SelectNodeTo(N, MachineOpc, VTs, (SDOperand *)0, 0);
3818 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3819 MVT VT1, MVT VT2, MVT VT3,
3820 const SDOperand *Ops, unsigned NumOps) {
3821 SDVTList VTs = getVTList(VT1, VT2, VT3);
3822 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3825 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3828 SDVTList VTs = getVTList(VT1, VT2);
3829 SDOperand Ops[] = { Op1 };
3830 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
3833 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3835 SDOperand Op1, SDOperand Op2) {
3836 SDVTList VTs = getVTList(VT1, VT2);
3837 SDOperand Ops[] = { Op1, Op2 };
3838 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
3841 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3843 SDOperand Op1, SDOperand Op2,
3845 SDVTList VTs = getVTList(VT1, VT2);
3846 SDOperand Ops[] = { Op1, Op2, Op3 };
3847 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
3850 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3851 SDVTList VTs, const SDOperand *Ops,
3853 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
3856 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3858 SDVTList VTs = getVTList(VT);
3859 return MorphNodeTo(N, Opc, VTs, 0, 0);
3862 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3863 MVT VT, SDOperand Op1) {
3864 SDVTList VTs = getVTList(VT);
3865 SDOperand Ops[] = { Op1 };
3866 return MorphNodeTo(N, Opc, VTs, Ops, 1);
3869 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3870 MVT VT, SDOperand Op1,
3872 SDVTList VTs = getVTList(VT);
3873 SDOperand Ops[] = { Op1, Op2 };
3874 return MorphNodeTo(N, Opc, VTs, Ops, 2);
3877 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3878 MVT VT, SDOperand Op1,
3879 SDOperand Op2, SDOperand Op3) {
3880 SDVTList VTs = getVTList(VT);
3881 SDOperand Ops[] = { Op1, Op2, Op3 };
3882 return MorphNodeTo(N, Opc, VTs, Ops, 3);
3885 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3886 MVT VT, const SDOperand *Ops,
3888 SDVTList VTs = getVTList(VT);
3889 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3892 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3893 MVT VT1, MVT VT2, const SDOperand *Ops,
3895 SDVTList VTs = getVTList(VT1, VT2);
3896 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3899 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3901 SDVTList VTs = getVTList(VT1, VT2);
3902 return MorphNodeTo(N, Opc, VTs, (SDOperand *)0, 0);
3905 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3906 MVT VT1, MVT VT2, MVT VT3,
3907 const SDOperand *Ops, unsigned NumOps) {
3908 SDVTList VTs = getVTList(VT1, VT2, VT3);
3909 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3912 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3915 SDVTList VTs = getVTList(VT1, VT2);
3916 SDOperand Ops[] = { Op1 };
3917 return MorphNodeTo(N, Opc, VTs, Ops, 1);
3920 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3922 SDOperand Op1, SDOperand Op2) {
3923 SDVTList VTs = getVTList(VT1, VT2);
3924 SDOperand Ops[] = { Op1, Op2 };
3925 return MorphNodeTo(N, Opc, VTs, Ops, 2);
3928 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3930 SDOperand Op1, SDOperand Op2,
3932 SDVTList VTs = getVTList(VT1, VT2);
3933 SDOperand Ops[] = { Op1, Op2, Op3 };
3934 return MorphNodeTo(N, Opc, VTs, Ops, 3);
3937 /// MorphNodeTo - These *mutate* the specified node to have the specified
3938 /// return type, opcode, and operands.
3940 /// Note that MorphNodeTo returns the resultant node. If there is already a
3941 /// node of the specified opcode and operands, it returns that node instead of
3942 /// the current one.
3944 /// Using MorphNodeTo is faster than creating a new node and swapping it in
3945 /// with ReplaceAllUsesWith both because it often avoids allocating a new
3946 /// node, and because it doesn't require CSE recalulation for any of
3947 /// the node's users.
3949 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3950 SDVTList VTs, const SDOperand *Ops,
3952 // If an identical node already exists, use it.
3954 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
3955 FoldingSetNodeID ID;
3956 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
3957 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3961 RemoveNodeFromCSEMaps(N);
3963 // Start the morphing.
3965 N->ValueList = VTs.VTs;
3966 N->NumValues = VTs.NumVTs;
3968 // Clear the operands list, updating used nodes to remove this from their
3969 // use list. Keep track of any operands that become dead as a result.
3970 SmallPtrSet<SDNode*, 16> DeadNodeSet;
3971 for (SDNode::op_iterator B = N->op_begin(), I = B, E = N->op_end();
3973 SDNode *Used = I->getVal();
3974 Used->removeUser(std::distance(B, I), N);
3975 if (Used->use_empty())
3976 DeadNodeSet.insert(Used);
3979 // If NumOps is larger than the # of operands we currently have, reallocate
3980 // the operand list.
3981 if (NumOps > N->NumOperands) {
3982 if (N->OperandsNeedDelete)
3983 delete[] N->OperandList;
3984 if (N->isMachineOpcode()) {
3985 // We're creating a final node that will live unmorphed for the
3986 // remainder of this SelectionDAG's duration, so we can allocate the
3987 // operands directly out of the pool with no recycling metadata.
3988 N->OperandList = Allocator.Allocate<SDUse>(NumOps);
3989 N->OperandsNeedDelete = false;
3991 N->OperandList = new SDUse[NumOps];
3992 N->OperandsNeedDelete = true;
3996 // Assign the new operands.
3997 N->NumOperands = NumOps;
3998 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3999 N->OperandList[i] = Ops[i];
4000 N->OperandList[i].setUser(N);
4001 SDNode *ToUse = N->OperandList[i].getVal();
4002 ToUse->addUser(i, N);
4003 DeadNodeSet.erase(ToUse);
4006 // Delete any nodes that are still dead after adding the uses for the
4008 SmallVector<SDNode *, 16> DeadNodes;
4009 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4010 E = DeadNodeSet.end(); I != E; ++I)
4011 if ((*I)->use_empty())
4012 DeadNodes.push_back(*I);
4013 RemoveDeadNodes(DeadNodes);
4016 CSEMap.InsertNode(N, IP); // Memoize the new node.
4021 /// getTargetNode - These are used for target selectors to create a new node
4022 /// with specified return type(s), target opcode, and operands.
4024 /// Note that getTargetNode returns the resultant node. If there is already a
4025 /// node of the specified opcode and operands, it returns that node instead of
4026 /// the current one.
4027 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
4028 return getNode(~Opcode, VT).Val;
4030 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
4031 return getNode(~Opcode, VT, Op1).Val;
4033 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4034 SDOperand Op1, SDOperand Op2) {
4035 return getNode(~Opcode, VT, Op1, Op2).Val;
4037 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4038 SDOperand Op1, SDOperand Op2,
4040 return getNode(~Opcode, VT, Op1, Op2, Op3).Val;
4042 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4043 const SDOperand *Ops, unsigned NumOps) {
4044 return getNode(~Opcode, VT, Ops, NumOps).Val;
4046 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
4047 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4049 return getNode(~Opcode, VTs, 2, &Op, 0).Val;
4051 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4052 MVT VT2, SDOperand Op1) {
4053 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4054 return getNode(~Opcode, VTs, 2, &Op1, 1).Val;
4056 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4057 MVT VT2, SDOperand Op1,
4059 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4060 SDOperand Ops[] = { Op1, Op2 };
4061 return getNode(~Opcode, VTs, 2, Ops, 2).Val;
4063 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4064 MVT VT2, SDOperand Op1,
4065 SDOperand Op2, SDOperand Op3) {
4066 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4067 SDOperand Ops[] = { Op1, Op2, Op3 };
4068 return getNode(~Opcode, VTs, 2, Ops, 3).Val;
4070 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
4071 const SDOperand *Ops, unsigned NumOps) {
4072 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4073 return getNode(~Opcode, VTs, 2, Ops, NumOps).Val;
4075 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4076 SDOperand Op1, SDOperand Op2) {
4077 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4078 SDOperand Ops[] = { Op1, Op2 };
4079 return getNode(~Opcode, VTs, 3, Ops, 2).Val;
4081 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4082 SDOperand Op1, SDOperand Op2,
4084 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4085 SDOperand Ops[] = { Op1, Op2, Op3 };
4086 return getNode(~Opcode, VTs, 3, Ops, 3).Val;
4088 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4089 const SDOperand *Ops, unsigned NumOps) {
4090 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4091 return getNode(~Opcode, VTs, 3, Ops, NumOps).Val;
4093 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4094 MVT VT2, MVT VT3, MVT VT4,
4095 const SDOperand *Ops, unsigned NumOps) {
4096 std::vector<MVT> VTList;
4097 VTList.push_back(VT1);
4098 VTList.push_back(VT2);
4099 VTList.push_back(VT3);
4100 VTList.push_back(VT4);
4101 const MVT *VTs = getNodeValueTypes(VTList);
4102 return getNode(~Opcode, VTs, 4, Ops, NumOps).Val;
4104 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
4105 const std::vector<MVT> &ResultTys,
4106 const SDOperand *Ops, unsigned NumOps) {
4107 const MVT *VTs = getNodeValueTypes(ResultTys);
4108 return getNode(~Opcode, VTs, ResultTys.size(),
4112 /// getNodeIfExists - Get the specified node if it's already available, or
4113 /// else return NULL.
4114 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4115 const SDOperand *Ops, unsigned NumOps) {
4116 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4117 FoldingSetNodeID ID;
4118 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4120 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4127 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4128 /// This can cause recursive merging of nodes in the DAG.
4130 /// This version assumes From has a single result value.
4132 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
4133 DAGUpdateListener *UpdateListener) {
4134 SDNode *From = FromN.Val;
4135 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
4136 "Cannot replace with this method!");
4137 assert(From != To.Val && "Cannot replace uses of with self");
4139 while (!From->use_empty()) {
4140 SDNode::use_iterator UI = From->use_begin();
4141 SDNode *U = UI->getUser();
4143 // This node is about to morph, remove its old self from the CSE maps.
4144 RemoveNodeFromCSEMaps(U);
4146 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4147 I != E; ++I, ++operandNum)
4148 if (I->getVal() == From) {
4149 From->removeUser(operandNum, U);
4152 To.Val->addUser(operandNum, U);
4155 // Now that we have modified U, add it back to the CSE maps. If it already
4156 // exists there, recursively merge the results together.
4157 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4158 ReplaceAllUsesWith(U, Existing, UpdateListener);
4159 // U is now dead. Inform the listener if it exists and delete it.
4161 UpdateListener->NodeDeleted(U, Existing);
4162 DeleteNodeNotInCSEMaps(U);
4164 // If the node doesn't already exist, we updated it. Inform a listener if
4167 UpdateListener->NodeUpdated(U);
4172 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4173 /// This can cause recursive merging of nodes in the DAG.
4175 /// This version assumes From/To have matching types and numbers of result
4178 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4179 DAGUpdateListener *UpdateListener) {
4180 assert(From->getVTList().VTs == To->getVTList().VTs &&
4181 From->getNumValues() == To->getNumValues() &&
4182 "Cannot use this version of ReplaceAllUsesWith!");
4184 // Handle the trivial case.
4188 while (!From->use_empty()) {
4189 SDNode::use_iterator UI = From->use_begin();
4190 SDNode *U = UI->getUser();
4192 // This node is about to morph, remove its old self from the CSE maps.
4193 RemoveNodeFromCSEMaps(U);
4195 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4196 I != E; ++I, ++operandNum)
4197 if (I->getVal() == From) {
4198 From->removeUser(operandNum, U);
4200 To->addUser(operandNum, U);
4203 // Now that we have modified U, add it back to the CSE maps. If it already
4204 // exists there, recursively merge the results together.
4205 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4206 ReplaceAllUsesWith(U, Existing, UpdateListener);
4207 // U is now dead. Inform the listener if it exists and delete it.
4209 UpdateListener->NodeDeleted(U, Existing);
4210 DeleteNodeNotInCSEMaps(U);
4212 // If the node doesn't already exist, we updated it. Inform a listener if
4215 UpdateListener->NodeUpdated(U);
4220 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4221 /// This can cause recursive merging of nodes in the DAG.
4223 /// This version can replace From with any result values. To must match the
4224 /// number and types of values returned by From.
4225 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4226 const SDOperand *To,
4227 DAGUpdateListener *UpdateListener) {
4228 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4229 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
4231 while (!From->use_empty()) {
4232 SDNode::use_iterator UI = From->use_begin();
4233 SDNode *U = UI->getUser();
4235 // This node is about to morph, remove its old self from the CSE maps.
4236 RemoveNodeFromCSEMaps(U);
4238 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4239 I != E; ++I, ++operandNum)
4240 if (I->getVal() == From) {
4241 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4242 From->removeUser(operandNum, U);
4245 ToOp.Val->addUser(operandNum, U);
4248 // Now that we have modified U, add it back to the CSE maps. If it already
4249 // exists there, recursively merge the results together.
4250 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4251 ReplaceAllUsesWith(U, Existing, UpdateListener);
4252 // U is now dead. Inform the listener if it exists and delete it.
4254 UpdateListener->NodeDeleted(U, Existing);
4255 DeleteNodeNotInCSEMaps(U);
4257 // If the node doesn't already exist, we updated it. Inform a listener if
4260 UpdateListener->NodeUpdated(U);
4265 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4266 /// uses of other values produced by From.Val alone. The Deleted vector is
4267 /// handled the same way as for ReplaceAllUsesWith.
4268 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4269 DAGUpdateListener *UpdateListener){
4270 // Handle the really simple, really trivial case efficiently.
4271 if (From == To) return;
4273 // Handle the simple, trivial, case efficiently.
4274 if (From.Val->getNumValues() == 1) {
4275 ReplaceAllUsesWith(From, To, UpdateListener);
4279 if (From.use_empty()) return;
4281 // Get all of the users of From.Val. We want these in a nice,
4282 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4283 SmallSetVector<SDNode*, 16> Users;
4284 for (SDNode::use_iterator UI = From.Val->use_begin(),
4285 E = From.Val->use_end(); UI != E; ++UI) {
4286 SDNode *User = UI->getUser();
4290 while (!Users.empty()) {
4291 // We know that this user uses some value of From. If it is the right
4292 // value, update it.
4293 SDNode *User = Users.back();
4296 // Scan for an operand that matches From.
4297 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4298 for (; Op != E; ++Op)
4299 if (*Op == From) break;
4301 // If there are no matches, the user must use some other result of From.
4302 if (Op == E) continue;
4304 // Okay, we know this user needs to be updated. Remove its old self
4305 // from the CSE maps.
4306 RemoveNodeFromCSEMaps(User);
4308 // Update all operands that match "From" in case there are multiple uses.
4309 for (; Op != E; ++Op) {
4311 From.Val->removeUser(Op-User->op_begin(), User);
4314 To.Val->addUser(Op-User->op_begin(), User);
4318 // Now that we have modified User, add it back to the CSE maps. If it
4319 // already exists there, recursively merge the results together.
4320 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4322 if (UpdateListener) UpdateListener->NodeUpdated(User);
4323 continue; // Continue on to next user.
4326 // If there was already an existing matching node, use ReplaceAllUsesWith
4327 // to replace the dead one with the existing one. This can cause
4328 // recursive merging of other unrelated nodes down the line.
4329 ReplaceAllUsesWith(User, Existing, UpdateListener);
4331 // User is now dead. Notify a listener if present.
4332 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4333 DeleteNodeNotInCSEMaps(User);
4337 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
4338 /// uses of other values produced by From.Val alone. The same value may
4339 /// appear in both the From and To list. The Deleted vector is
4340 /// handled the same way as for ReplaceAllUsesWith.
4341 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDOperand *From,
4342 const SDOperand *To,
4344 DAGUpdateListener *UpdateListener){
4345 // Handle the simple, trivial case efficiently.
4347 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
4349 SmallVector<std::pair<SDNode *, unsigned>, 16> Users;
4350 for (unsigned i = 0; i != Num; ++i)
4351 for (SDNode::use_iterator UI = From[i].Val->use_begin(),
4352 E = From[i].Val->use_end(); UI != E; ++UI)
4353 Users.push_back(std::make_pair(UI->getUser(), i));
4355 while (!Users.empty()) {
4356 // We know that this user uses some value of From. If it is the right
4357 // value, update it.
4358 SDNode *User = Users.back().first;
4359 unsigned i = Users.back().second;
4362 // Scan for an operand that matches From.
4363 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4364 for (; Op != E; ++Op)
4365 if (*Op == From[i]) break;
4367 // If there are no matches, the user must use some other result of From.
4368 if (Op == E) continue;
4370 // Okay, we know this user needs to be updated. Remove its old self
4371 // from the CSE maps.
4372 RemoveNodeFromCSEMaps(User);
4374 // Update all operands that match "From" in case there are multiple uses.
4375 for (; Op != E; ++Op) {
4376 if (*Op == From[i]) {
4377 From[i].Val->removeUser(Op-User->op_begin(), User);
4380 To[i].Val->addUser(Op-User->op_begin(), User);
4384 // Now that we have modified User, add it back to the CSE maps. If it
4385 // already exists there, recursively merge the results together.
4386 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4388 if (UpdateListener) UpdateListener->NodeUpdated(User);
4389 continue; // Continue on to next user.
4392 // If there was already an existing matching node, use ReplaceAllUsesWith
4393 // to replace the dead one with the existing one. This can cause
4394 // recursive merging of other unrelated nodes down the line.
4395 ReplaceAllUsesWith(User, Existing, UpdateListener);
4397 // User is now dead. Notify a listener if present.
4398 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4399 DeleteNodeNotInCSEMaps(User);
4403 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4404 /// based on their topological order. It returns the maximum id and a vector
4405 /// of the SDNodes* in assigned order by reference.
4406 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4407 unsigned DAGSize = AllNodes.size();
4408 std::vector<unsigned> InDegree(DAGSize);
4409 std::vector<SDNode*> Sources;
4411 // Use a two pass approach to avoid using a std::map which is slow.
4413 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4416 unsigned Degree = N->use_size();
4417 InDegree[N->getNodeId()] = Degree;
4419 Sources.push_back(N);
4423 TopOrder.reserve(DAGSize);
4424 while (!Sources.empty()) {
4425 SDNode *N = Sources.back();
4427 TopOrder.push_back(N);
4428 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4429 SDNode *P = I->getVal();
4430 unsigned Degree = --InDegree[P->getNodeId()];
4432 Sources.push_back(P);
4436 // Second pass, assign the actual topological order as node ids.
4438 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4440 (*TI)->setNodeId(Id++);
4447 //===----------------------------------------------------------------------===//
4449 //===----------------------------------------------------------------------===//
4451 // Out-of-line virtual method to give class a home.
4452 void SDNode::ANCHOR() {}
4453 void UnarySDNode::ANCHOR() {}
4454 void BinarySDNode::ANCHOR() {}
4455 void TernarySDNode::ANCHOR() {}
4456 void HandleSDNode::ANCHOR() {}
4457 void ConstantSDNode::ANCHOR() {}
4458 void ConstantFPSDNode::ANCHOR() {}
4459 void GlobalAddressSDNode::ANCHOR() {}
4460 void FrameIndexSDNode::ANCHOR() {}
4461 void JumpTableSDNode::ANCHOR() {}
4462 void ConstantPoolSDNode::ANCHOR() {}
4463 void BasicBlockSDNode::ANCHOR() {}
4464 void SrcValueSDNode::ANCHOR() {}
4465 void MemOperandSDNode::ANCHOR() {}
4466 void RegisterSDNode::ANCHOR() {}
4467 void DbgStopPointSDNode::ANCHOR() {}
4468 void LabelSDNode::ANCHOR() {}
4469 void ExternalSymbolSDNode::ANCHOR() {}
4470 void CondCodeSDNode::ANCHOR() {}
4471 void ARG_FLAGSSDNode::ANCHOR() {}
4472 void VTSDNode::ANCHOR() {}
4473 void MemSDNode::ANCHOR() {}
4474 void LoadSDNode::ANCHOR() {}
4475 void StoreSDNode::ANCHOR() {}
4476 void AtomicSDNode::ANCHOR() {}
4478 HandleSDNode::~HandleSDNode() {
4482 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4484 : SDNode(isa<GlobalVariable>(GA) &&
4485 cast<GlobalVariable>(GA)->isThreadLocal() ?
4487 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4489 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4490 getSDVTList(VT)), Offset(o) {
4491 TheGlobal = const_cast<GlobalValue*>(GA);
4494 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
4495 const Value *srcValue, int SVO,
4496 unsigned alignment, bool vol)
4497 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
4498 Flags(vol | ((Log2_32(alignment) + 1) << 1)) {
4500 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4501 assert(getAlignment() == alignment && "Alignment representation error!");
4502 assert(isVolatile() == vol && "Volatile representation error!");
4505 /// getMemOperand - Return a MachineMemOperand object describing the memory
4506 /// reference performed by this memory reference.
4507 MachineMemOperand MemSDNode::getMemOperand() const {
4509 if (isa<LoadSDNode>(this))
4510 Flags = MachineMemOperand::MOLoad;
4511 else if (isa<StoreSDNode>(this))
4512 Flags = MachineMemOperand::MOStore;
4514 assert(isa<AtomicSDNode>(this) && "Unknown MemSDNode opcode!");
4515 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4518 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4519 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4521 // Check if the memory reference references a frame index
4522 const FrameIndexSDNode *FI =
4523 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4524 if (!getSrcValue() && FI)
4525 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
4526 Flags, 0, Size, getAlignment());
4528 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4529 Size, getAlignment());
4532 /// Profile - Gather unique data for the node.
4534 void SDNode::Profile(FoldingSetNodeID &ID) {
4535 AddNodeIDNode(ID, this);
4538 /// getValueTypeList - Return a pointer to the specified value type.
4540 const MVT *SDNode::getValueTypeList(MVT VT) {
4541 if (VT.isExtended()) {
4542 static std::set<MVT, MVT::compareRawBits> EVTs;
4543 return &(*EVTs.insert(VT).first);
4545 static MVT VTs[MVT::LAST_VALUETYPE];
4546 VTs[VT.getSimpleVT()] = VT;
4547 return &VTs[VT.getSimpleVT()];
4551 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4552 /// indicated value. This method ignores uses of other values defined by this
4554 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4555 assert(Value < getNumValues() && "Bad value!");
4557 // TODO: Only iterate over uses of a given value of the node
4558 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4559 if (UI->getSDOperand().ResNo == Value) {
4566 // Found exactly the right number of uses?
4571 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4572 /// value. This method ignores uses of other values defined by this operation.
4573 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4574 assert(Value < getNumValues() && "Bad value!");
4576 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
4577 if (UI->getSDOperand().ResNo == Value)
4584 /// isOnlyUserOf - Return true if this node is the only use of N.
4586 bool SDNode::isOnlyUserOf(SDNode *N) const {
4588 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4589 SDNode *User = I->getUser();
4599 /// isOperand - Return true if this node is an operand of N.
4601 bool SDOperand::isOperandOf(SDNode *N) const {
4602 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4603 if (*this == N->getOperand(i))
4608 bool SDNode::isOperandOf(SDNode *N) const {
4609 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4610 if (this == N->OperandList[i].getVal())
4615 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4616 /// be a chain) reaches the specified operand without crossing any
4617 /// side-effecting instructions. In practice, this looks through token
4618 /// factors and non-volatile loads. In order to remain efficient, this only
4619 /// looks a couple of nodes in, it does not do an exhaustive search.
4620 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4621 unsigned Depth) const {
4622 if (*this == Dest) return true;
4624 // Don't search too deeply, we just want to be able to see through
4625 // TokenFactor's etc.
4626 if (Depth == 0) return false;
4628 // If this is a token factor, all inputs to the TF happen in parallel. If any
4629 // of the operands of the TF reach dest, then we can do the xform.
4630 if (getOpcode() == ISD::TokenFactor) {
4631 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4632 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4637 // Loads don't have side effects, look through them.
4638 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4639 if (!Ld->isVolatile())
4640 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4646 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4647 SmallPtrSet<SDNode *, 32> &Visited) {
4648 if (found || !Visited.insert(N))
4651 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4652 SDNode *Op = N->getOperand(i).Val;
4657 findPredecessor(Op, P, found, Visited);
4661 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4662 /// is either an operand of N or it can be reached by recursively traversing
4663 /// up the operands.
4664 /// NOTE: this is an expensive method. Use it carefully.
4665 bool SDNode::isPredecessorOf(SDNode *N) const {
4666 SmallPtrSet<SDNode *, 32> Visited;
4668 findPredecessor(N, this, found, Visited);
4672 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4673 assert(Num < NumOperands && "Invalid child # of SDNode!");
4674 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4677 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4678 switch (getOpcode()) {
4680 if (getOpcode() < ISD::BUILTIN_OP_END)
4681 return "<<Unknown DAG Node>>";
4682 if (isMachineOpcode()) {
4684 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4685 if (getMachineOpcode() < TII->getNumOpcodes())
4686 return TII->get(getMachineOpcode()).getName();
4687 return "<<Unknown Machine Node>>";
4690 TargetLowering &TLI = G->getTargetLoweringInfo();
4691 const char *Name = TLI.getTargetNodeName(getOpcode());
4692 if (Name) return Name;
4693 return "<<Unknown Target Node>>";
4695 return "<<Unknown Node>>";
4698 case ISD::DELETED_NODE:
4699 return "<<Deleted Node!>>";
4701 case ISD::PREFETCH: return "Prefetch";
4702 case ISD::MEMBARRIER: return "MemBarrier";
4703 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4704 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4705 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4706 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4707 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4708 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4709 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4710 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4711 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4712 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4713 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4714 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4715 case ISD::PCMARKER: return "PCMarker";
4716 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4717 case ISD::SRCVALUE: return "SrcValue";
4718 case ISD::MEMOPERAND: return "MemOperand";
4719 case ISD::EntryToken: return "EntryToken";
4720 case ISD::TokenFactor: return "TokenFactor";
4721 case ISD::AssertSext: return "AssertSext";
4722 case ISD::AssertZext: return "AssertZext";
4724 case ISD::BasicBlock: return "BasicBlock";
4725 case ISD::ARG_FLAGS: return "ArgFlags";
4726 case ISD::VALUETYPE: return "ValueType";
4727 case ISD::Register: return "Register";
4729 case ISD::Constant: return "Constant";
4730 case ISD::ConstantFP: return "ConstantFP";
4731 case ISD::GlobalAddress: return "GlobalAddress";
4732 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4733 case ISD::FrameIndex: return "FrameIndex";
4734 case ISD::JumpTable: return "JumpTable";
4735 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4736 case ISD::RETURNADDR: return "RETURNADDR";
4737 case ISD::FRAMEADDR: return "FRAMEADDR";
4738 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4739 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4740 case ISD::EHSELECTION: return "EHSELECTION";
4741 case ISD::EH_RETURN: return "EH_RETURN";
4742 case ISD::ConstantPool: return "ConstantPool";
4743 case ISD::ExternalSymbol: return "ExternalSymbol";
4744 case ISD::INTRINSIC_WO_CHAIN: {
4745 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4746 return Intrinsic::getName((Intrinsic::ID)IID);
4748 case ISD::INTRINSIC_VOID:
4749 case ISD::INTRINSIC_W_CHAIN: {
4750 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4751 return Intrinsic::getName((Intrinsic::ID)IID);
4754 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4755 case ISD::TargetConstant: return "TargetConstant";
4756 case ISD::TargetConstantFP:return "TargetConstantFP";
4757 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4758 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4759 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4760 case ISD::TargetJumpTable: return "TargetJumpTable";
4761 case ISD::TargetConstantPool: return "TargetConstantPool";
4762 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4764 case ISD::CopyToReg: return "CopyToReg";
4765 case ISD::CopyFromReg: return "CopyFromReg";
4766 case ISD::UNDEF: return "undef";
4767 case ISD::MERGE_VALUES: return "merge_values";
4768 case ISD::INLINEASM: return "inlineasm";
4769 case ISD::DBG_LABEL: return "dbg_label";
4770 case ISD::EH_LABEL: return "eh_label";
4771 case ISD::DECLARE: return "declare";
4772 case ISD::HANDLENODE: return "handlenode";
4773 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4774 case ISD::CALL: return "call";
4777 case ISD::FABS: return "fabs";
4778 case ISD::FNEG: return "fneg";
4779 case ISD::FSQRT: return "fsqrt";
4780 case ISD::FSIN: return "fsin";
4781 case ISD::FCOS: return "fcos";
4782 case ISD::FPOWI: return "fpowi";
4783 case ISD::FPOW: return "fpow";
4786 case ISD::ADD: return "add";
4787 case ISD::SUB: return "sub";
4788 case ISD::MUL: return "mul";
4789 case ISD::MULHU: return "mulhu";
4790 case ISD::MULHS: return "mulhs";
4791 case ISD::SDIV: return "sdiv";
4792 case ISD::UDIV: return "udiv";
4793 case ISD::SREM: return "srem";
4794 case ISD::UREM: return "urem";
4795 case ISD::SMUL_LOHI: return "smul_lohi";
4796 case ISD::UMUL_LOHI: return "umul_lohi";
4797 case ISD::SDIVREM: return "sdivrem";
4798 case ISD::UDIVREM: return "divrem";
4799 case ISD::AND: return "and";
4800 case ISD::OR: return "or";
4801 case ISD::XOR: return "xor";
4802 case ISD::SHL: return "shl";
4803 case ISD::SRA: return "sra";
4804 case ISD::SRL: return "srl";
4805 case ISD::ROTL: return "rotl";
4806 case ISD::ROTR: return "rotr";
4807 case ISD::FADD: return "fadd";
4808 case ISD::FSUB: return "fsub";
4809 case ISD::FMUL: return "fmul";
4810 case ISD::FDIV: return "fdiv";
4811 case ISD::FREM: return "frem";
4812 case ISD::FCOPYSIGN: return "fcopysign";
4813 case ISD::FGETSIGN: return "fgetsign";
4815 case ISD::SETCC: return "setcc";
4816 case ISD::VSETCC: return "vsetcc";
4817 case ISD::SELECT: return "select";
4818 case ISD::SELECT_CC: return "select_cc";
4819 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4820 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4821 case ISD::CONCAT_VECTORS: return "concat_vectors";
4822 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4823 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4824 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4825 case ISD::CARRY_FALSE: return "carry_false";
4826 case ISD::ADDC: return "addc";
4827 case ISD::ADDE: return "adde";
4828 case ISD::SUBC: return "subc";
4829 case ISD::SUBE: return "sube";
4830 case ISD::SHL_PARTS: return "shl_parts";
4831 case ISD::SRA_PARTS: return "sra_parts";
4832 case ISD::SRL_PARTS: return "srl_parts";
4834 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4835 case ISD::INSERT_SUBREG: return "insert_subreg";
4837 // Conversion operators.
4838 case ISD::SIGN_EXTEND: return "sign_extend";
4839 case ISD::ZERO_EXTEND: return "zero_extend";
4840 case ISD::ANY_EXTEND: return "any_extend";
4841 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4842 case ISD::TRUNCATE: return "truncate";
4843 case ISD::FP_ROUND: return "fp_round";
4844 case ISD::FLT_ROUNDS_: return "flt_rounds";
4845 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4846 case ISD::FP_EXTEND: return "fp_extend";
4848 case ISD::SINT_TO_FP: return "sint_to_fp";
4849 case ISD::UINT_TO_FP: return "uint_to_fp";
4850 case ISD::FP_TO_SINT: return "fp_to_sint";
4851 case ISD::FP_TO_UINT: return "fp_to_uint";
4852 case ISD::BIT_CONVERT: return "bit_convert";
4854 // Control flow instructions
4855 case ISD::BR: return "br";
4856 case ISD::BRIND: return "brind";
4857 case ISD::BR_JT: return "br_jt";
4858 case ISD::BRCOND: return "brcond";
4859 case ISD::BR_CC: return "br_cc";
4860 case ISD::RET: return "ret";
4861 case ISD::CALLSEQ_START: return "callseq_start";
4862 case ISD::CALLSEQ_END: return "callseq_end";
4865 case ISD::LOAD: return "load";
4866 case ISD::STORE: return "store";
4867 case ISD::VAARG: return "vaarg";
4868 case ISD::VACOPY: return "vacopy";
4869 case ISD::VAEND: return "vaend";
4870 case ISD::VASTART: return "vastart";
4871 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4872 case ISD::EXTRACT_ELEMENT: return "extract_element";
4873 case ISD::BUILD_PAIR: return "build_pair";
4874 case ISD::STACKSAVE: return "stacksave";
4875 case ISD::STACKRESTORE: return "stackrestore";
4876 case ISD::TRAP: return "trap";
4879 case ISD::BSWAP: return "bswap";
4880 case ISD::CTPOP: return "ctpop";
4881 case ISD::CTTZ: return "cttz";
4882 case ISD::CTLZ: return "ctlz";
4885 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4886 case ISD::DEBUG_LOC: return "debug_loc";
4889 case ISD::TRAMPOLINE: return "trampoline";
4892 switch (cast<CondCodeSDNode>(this)->get()) {
4893 default: assert(0 && "Unknown setcc condition!");
4894 case ISD::SETOEQ: return "setoeq";
4895 case ISD::SETOGT: return "setogt";
4896 case ISD::SETOGE: return "setoge";
4897 case ISD::SETOLT: return "setolt";
4898 case ISD::SETOLE: return "setole";
4899 case ISD::SETONE: return "setone";
4901 case ISD::SETO: return "seto";
4902 case ISD::SETUO: return "setuo";
4903 case ISD::SETUEQ: return "setue";
4904 case ISD::SETUGT: return "setugt";
4905 case ISD::SETUGE: return "setuge";
4906 case ISD::SETULT: return "setult";
4907 case ISD::SETULE: return "setule";
4908 case ISD::SETUNE: return "setune";
4910 case ISD::SETEQ: return "seteq";
4911 case ISD::SETGT: return "setgt";
4912 case ISD::SETGE: return "setge";
4913 case ISD::SETLT: return "setlt";
4914 case ISD::SETLE: return "setle";
4915 case ISD::SETNE: return "setne";
4920 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4929 return "<post-inc>";
4931 return "<post-dec>";
4935 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4936 std::string S = "< ";
4950 if (getByValAlign())
4951 S += "byval-align:" + utostr(getByValAlign()) + " ";
4953 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4955 S += "byval-size:" + utostr(getByValSize()) + " ";
4959 void SDNode::dump() const { dump(0); }
4960 void SDNode::dump(const SelectionDAG *G) const {
4961 cerr << (void*)this << ": ";
4963 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4965 if (getValueType(i) == MVT::Other)
4968 cerr << getValueType(i).getMVTString();
4970 cerr << " = " << getOperationName(G);
4973 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4974 if (i) cerr << ", ";
4975 cerr << (void*)getOperand(i).Val;
4976 if (unsigned RN = getOperand(i).ResNo)
4980 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4981 SDNode *Mask = getOperand(2).Val;
4983 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4985 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4988 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4993 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4994 cerr << "<" << CSDN->getAPIntValue().toStringUnsigned() << ">";
4995 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4996 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4997 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4998 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4999 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
5001 cerr << "<APFloat(";
5002 CSDN->getValueAPF().convertToAPInt().dump();
5005 } else if (const GlobalAddressSDNode *GADN =
5006 dyn_cast<GlobalAddressSDNode>(this)) {
5007 int offset = GADN->getOffset();
5009 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
5011 cerr << " + " << offset;
5013 cerr << " " << offset;
5014 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5015 cerr << "<" << FIDN->getIndex() << ">";
5016 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5017 cerr << "<" << JTDN->getIndex() << ">";
5018 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5019 int offset = CP->getOffset();
5020 if (CP->isMachineConstantPoolEntry())
5021 cerr << "<" << *CP->getMachineCPVal() << ">";
5023 cerr << "<" << *CP->getConstVal() << ">";
5025 cerr << " + " << offset;
5027 cerr << " " << offset;
5028 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5030 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5032 cerr << LBB->getName() << " ";
5033 cerr << (const void*)BBDN->getBasicBlock() << ">";
5034 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5035 if (G && R->getReg() &&
5036 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5037 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5039 cerr << " #" << R->getReg();
5041 } else if (const ExternalSymbolSDNode *ES =
5042 dyn_cast<ExternalSymbolSDNode>(this)) {
5043 cerr << "'" << ES->getSymbol() << "'";
5044 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5046 cerr << "<" << M->getValue() << ">";
5049 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5050 if (M->MO.getValue())
5051 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5053 cerr << "<null:" << M->MO.getOffset() << ">";
5054 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5055 cerr << N->getArgFlags().getArgFlagsString();
5056 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5057 cerr << ":" << N->getVT().getMVTString();
5059 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5060 const Value *SrcValue = LD->getSrcValue();
5061 int SrcOffset = LD->getSrcValueOffset();
5067 cerr << ":" << SrcOffset << ">";
5070 switch (LD->getExtensionType()) {
5071 default: doExt = false; break;
5073 cerr << " <anyext ";
5083 cerr << LD->getMemoryVT().getMVTString() << ">";
5085 const char *AM = getIndexedModeName(LD->getAddressingMode());
5088 if (LD->isVolatile())
5089 cerr << " <volatile>";
5090 cerr << " alignment=" << LD->getAlignment();
5091 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5092 const Value *SrcValue = ST->getSrcValue();
5093 int SrcOffset = ST->getSrcValueOffset();
5099 cerr << ":" << SrcOffset << ">";
5101 if (ST->isTruncatingStore())
5103 << ST->getMemoryVT().getMVTString() << ">";
5105 const char *AM = getIndexedModeName(ST->getAddressingMode());
5108 if (ST->isVolatile())
5109 cerr << " <volatile>";
5110 cerr << " alignment=" << ST->getAlignment();
5111 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5112 const Value *SrcValue = AT->getSrcValue();
5113 int SrcOffset = AT->getSrcValueOffset();
5119 cerr << ":" << SrcOffset << ">";
5120 if (AT->isVolatile())
5121 cerr << " <volatile>";
5122 cerr << " alignment=" << AT->getAlignment();
5126 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5127 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5128 if (N->getOperand(i).Val->hasOneUse())
5129 DumpNodes(N->getOperand(i).Val, indent+2, G);
5131 cerr << "\n" << std::string(indent+2, ' ')
5132 << (void*)N->getOperand(i).Val << ": <multiple use>";
5135 cerr << "\n" << std::string(indent, ' ');
5139 void SelectionDAG::dump() const {
5140 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5142 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5144 const SDNode *N = I;
5145 if (!N->hasOneUse() && N != getRoot().Val)
5146 DumpNodes(N, 2, this);
5149 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
5154 const Type *ConstantPoolSDNode::getType() const {
5155 if (isMachineConstantPoolEntry())
5156 return Val.MachineCPVal->getType();
5157 return Val.ConstVal->getType();