1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/GlobalAlias.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/StringExtras.h"
42 /// makeVTList - Return an instance of the SDVTList struct initialized with the
43 /// specified members.
44 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
45 SDVTList Res = {VTs, NumVTs};
49 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
50 switch (VT.getSimpleVT()) {
51 default: assert(0 && "Unknown FP format");
52 case MVT::f32: return &APFloat::IEEEsingle;
53 case MVT::f64: return &APFloat::IEEEdouble;
54 case MVT::f80: return &APFloat::x87DoubleExtended;
55 case MVT::f128: return &APFloat::IEEEquad;
56 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
60 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
62 //===----------------------------------------------------------------------===//
63 // ConstantFPSDNode Class
64 //===----------------------------------------------------------------------===//
66 /// isExactlyValue - We don't rely on operator== working on double values, as
67 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
68 /// As such, this method can be used to do an exact bit-for-bit comparison of
69 /// two floating point values.
70 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
71 return Value.bitwiseIsEqual(V);
74 bool ConstantFPSDNode::isValueValidForType(MVT VT,
76 assert(VT.isFloatingPoint() && "Can only convert between FP types");
78 // PPC long double cannot be converted to any other type.
79 if (VT == MVT::ppcf128 ||
80 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
83 // convert modifies in place, so make a copy.
84 APFloat Val2 = APFloat(Val);
85 return Val2.convert(*MVTToAPFloatSemantics(VT),
86 APFloat::rmNearestTiesToEven) == APFloat::opOK;
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 /// isBuildVectorAllOnes - Return true if the specified node is a
94 /// BUILD_VECTOR where all of the elements are ~0 or undef.
95 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
96 // Look through a bit convert.
97 if (N->getOpcode() == ISD::BIT_CONVERT)
98 N = N->getOperand(0).Val;
100 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
102 unsigned i = 0, e = N->getNumOperands();
104 // Skip over all of the undef values.
105 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
108 // Do not accept an all-undef vector.
109 if (i == e) return false;
111 // Do not accept build_vectors that aren't all constants or which have non-~0
113 SDOperand NotZero = N->getOperand(i);
114 if (isa<ConstantSDNode>(NotZero)) {
115 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
117 } else if (isa<ConstantFPSDNode>(NotZero)) {
118 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
119 convertToAPInt().isAllOnesValue())
124 // Okay, we have at least one ~0 value, check to see if the rest match or are
126 for (++i; i != e; ++i)
127 if (N->getOperand(i) != NotZero &&
128 N->getOperand(i).getOpcode() != ISD::UNDEF)
134 /// isBuildVectorAllZeros - Return true if the specified node is a
135 /// BUILD_VECTOR where all of the elements are 0 or undef.
136 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
137 // Look through a bit convert.
138 if (N->getOpcode() == ISD::BIT_CONVERT)
139 N = N->getOperand(0).Val;
141 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
143 unsigned i = 0, e = N->getNumOperands();
145 // Skip over all of the undef values.
146 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
149 // Do not accept an all-undef vector.
150 if (i == e) return false;
152 // Do not accept build_vectors that aren't all constants or which have non-~0
154 SDOperand Zero = N->getOperand(i);
155 if (isa<ConstantSDNode>(Zero)) {
156 if (!cast<ConstantSDNode>(Zero)->isNullValue())
158 } else if (isa<ConstantFPSDNode>(Zero)) {
159 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
164 // Okay, we have at least one ~0 value, check to see if the rest match or are
166 for (++i; i != e; ++i)
167 if (N->getOperand(i) != Zero &&
168 N->getOperand(i).getOpcode() != ISD::UNDEF)
173 /// isScalarToVector - Return true if the specified node is a
174 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
175 /// element is not an undef.
176 bool ISD::isScalarToVector(const SDNode *N) {
177 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
180 if (N->getOpcode() != ISD::BUILD_VECTOR)
182 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
184 unsigned NumElems = N->getNumOperands();
185 for (unsigned i = 1; i < NumElems; ++i) {
186 SDOperand V = N->getOperand(i);
187 if (V.getOpcode() != ISD::UNDEF)
194 /// isDebugLabel - Return true if the specified node represents a debug
195 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
196 bool ISD::isDebugLabel(const SDNode *N) {
198 if (N->getOpcode() == ISD::DBG_LABEL)
200 if (N->isTargetOpcode() &&
201 N->getTargetOpcode() == TargetInstrInfo::DBG_LABEL)
206 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
207 /// when given the operation for (X op Y).
208 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
209 // To perform this operation, we just need to swap the L and G bits of the
211 unsigned OldL = (Operation >> 2) & 1;
212 unsigned OldG = (Operation >> 1) & 1;
213 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
214 (OldL << 1) | // New G bit
215 (OldG << 2)); // New L bit.
218 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
219 /// 'op' is a valid SetCC operation.
220 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
221 unsigned Operation = Op;
223 Operation ^= 7; // Flip L, G, E bits, but not U.
225 Operation ^= 15; // Flip all of the condition bits.
226 if (Operation > ISD::SETTRUE2)
227 Operation &= ~8; // Don't let N and U bits get set.
228 return ISD::CondCode(Operation);
232 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
233 /// signed operation and 2 if the result is an unsigned comparison. Return zero
234 /// if the operation does not depend on the sign of the input (setne and seteq).
235 static int isSignedOp(ISD::CondCode Opcode) {
237 default: assert(0 && "Illegal integer setcc operation!");
239 case ISD::SETNE: return 0;
243 case ISD::SETGE: return 1;
247 case ISD::SETUGE: return 2;
251 /// getSetCCOrOperation - Return the result of a logical OR between different
252 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
253 /// returns SETCC_INVALID if it is not possible to represent the resultant
255 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
257 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
258 // Cannot fold a signed integer setcc with an unsigned integer setcc.
259 return ISD::SETCC_INVALID;
261 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
263 // If the N and U bits get set then the resultant comparison DOES suddenly
264 // care about orderedness, and is true when ordered.
265 if (Op > ISD::SETTRUE2)
266 Op &= ~16; // Clear the U bit if the N bit is set.
268 // Canonicalize illegal integer setcc's.
269 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
272 return ISD::CondCode(Op);
275 /// getSetCCAndOperation - Return the result of a logical AND between different
276 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
277 /// function returns zero if it is not possible to represent the resultant
279 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
281 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
282 // Cannot fold a signed setcc with an unsigned setcc.
283 return ISD::SETCC_INVALID;
285 // Combine all of the condition bits.
286 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
288 // Canonicalize illegal integer setcc's.
292 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
293 case ISD::SETOEQ: // SETEQ & SETU[LG]E
294 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
295 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
296 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
303 const TargetMachine &SelectionDAG::getTarget() const {
304 return TLI.getTargetMachine();
307 //===----------------------------------------------------------------------===//
308 // SDNode Profile Support
309 //===----------------------------------------------------------------------===//
311 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
313 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
317 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
318 /// solely with their pointer.
319 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
320 ID.AddPointer(VTList.VTs);
323 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
325 static void AddNodeIDOperands(FoldingSetNodeID &ID,
326 const SDOperand *Ops, unsigned NumOps) {
327 for (; NumOps; --NumOps, ++Ops) {
328 ID.AddPointer(Ops->Val);
329 ID.AddInteger(Ops->ResNo);
333 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
335 static void AddNodeIDOperands(FoldingSetNodeID &ID,
336 const SDUse *Ops, unsigned NumOps) {
337 for (; NumOps; --NumOps, ++Ops) {
338 ID.AddPointer(Ops->getSDOperand().Val);
339 ID.AddInteger(Ops->getSDOperand().ResNo);
343 static void AddNodeIDNode(FoldingSetNodeID &ID,
344 unsigned short OpC, SDVTList VTList,
345 const SDOperand *OpList, unsigned N) {
346 AddNodeIDOpcode(ID, OpC);
347 AddNodeIDValueTypes(ID, VTList);
348 AddNodeIDOperands(ID, OpList, N);
352 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
354 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
355 AddNodeIDOpcode(ID, N->getOpcode());
356 // Add the return value info.
357 AddNodeIDValueTypes(ID, N->getVTList());
358 // Add the operand info.
359 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
361 // Handle SDNode leafs with special info.
362 switch (N->getOpcode()) {
363 default: break; // Normal nodes don't need extra info.
365 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
367 case ISD::TargetConstant:
369 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
371 case ISD::TargetConstantFP:
372 case ISD::ConstantFP: {
373 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
376 case ISD::TargetGlobalAddress:
377 case ISD::GlobalAddress:
378 case ISD::TargetGlobalTLSAddress:
379 case ISD::GlobalTLSAddress: {
380 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
381 ID.AddPointer(GA->getGlobal());
382 ID.AddInteger(GA->getOffset());
385 case ISD::BasicBlock:
386 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
389 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
391 case ISD::DBG_STOPPOINT: {
392 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
393 ID.AddInteger(DSP->getLine());
394 ID.AddInteger(DSP->getColumn());
395 ID.AddPointer(DSP->getCompileUnit());
400 ID.AddInteger(cast<LabelSDNode>(N)->getLabelID());
403 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
405 case ISD::MEMOPERAND: {
406 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
407 ID.AddPointer(MO.getValue());
408 ID.AddInteger(MO.getFlags());
409 ID.AddInteger(MO.getOffset());
410 ID.AddInteger(MO.getSize());
411 ID.AddInteger(MO.getAlignment());
414 case ISD::FrameIndex:
415 case ISD::TargetFrameIndex:
416 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
419 case ISD::TargetJumpTable:
420 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
422 case ISD::ConstantPool:
423 case ISD::TargetConstantPool: {
424 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
425 ID.AddInteger(CP->getAlignment());
426 ID.AddInteger(CP->getOffset());
427 if (CP->isMachineConstantPoolEntry())
428 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
430 ID.AddPointer(CP->getConstVal());
434 LoadSDNode *LD = cast<LoadSDNode>(N);
435 ID.AddInteger(LD->getAddressingMode());
436 ID.AddInteger(LD->getExtensionType());
437 ID.AddInteger(LD->getMemoryVT().getRawBits());
438 ID.AddInteger(LD->getAlignment());
439 ID.AddInteger(LD->isVolatile());
443 StoreSDNode *ST = cast<StoreSDNode>(N);
444 ID.AddInteger(ST->getAddressingMode());
445 ID.AddInteger(ST->isTruncatingStore());
446 ID.AddInteger(ST->getMemoryVT().getRawBits());
447 ID.AddInteger(ST->getAlignment());
448 ID.AddInteger(ST->isVolatile());
451 case ISD::ATOMIC_CMP_SWAP:
452 case ISD::ATOMIC_LOAD_ADD:
453 case ISD::ATOMIC_SWAP:
454 case ISD::ATOMIC_LOAD_SUB:
455 case ISD::ATOMIC_LOAD_AND:
456 case ISD::ATOMIC_LOAD_OR:
457 case ISD::ATOMIC_LOAD_XOR:
458 case ISD::ATOMIC_LOAD_NAND:
459 case ISD::ATOMIC_LOAD_MIN:
460 case ISD::ATOMIC_LOAD_MAX:
461 case ISD::ATOMIC_LOAD_UMIN:
462 case ISD::ATOMIC_LOAD_UMAX: {
463 AtomicSDNode *AT = cast<AtomicSDNode>(N);
464 ID.AddInteger(AT->getAlignment());
465 ID.AddInteger(AT->isVolatile());
468 } // end switch (N->getOpcode())
471 //===----------------------------------------------------------------------===//
472 // SelectionDAG Class
473 //===----------------------------------------------------------------------===//
475 inline alist_traits<SDNode, LargestSDNode>::AllocatorType &
476 SelectionDAG::getAllocator() {
477 return AllNodes.getTraits().Allocator;
480 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
482 void SelectionDAG::RemoveDeadNodes() {
483 // Create a dummy node (which is not added to allnodes), that adds a reference
484 // to the root node, preventing it from being deleted.
485 HandleSDNode Dummy(getRoot());
487 SmallVector<SDNode*, 128> DeadNodes;
489 // Add all obviously-dead nodes to the DeadNodes worklist.
490 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
492 DeadNodes.push_back(I);
494 RemoveDeadNodes(DeadNodes);
496 // If the root changed (e.g. it was a dead load, update the root).
497 setRoot(Dummy.getValue());
500 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
501 /// given list, and any nodes that become unreachable as a result.
502 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
503 DAGUpdateListener *UpdateListener) {
505 // Process the worklist, deleting the nodes and adding their uses to the
507 while (!DeadNodes.empty()) {
508 SDNode *N = DeadNodes.back();
509 DeadNodes.pop_back();
512 UpdateListener->NodeDeleted(N, 0);
514 // Take the node out of the appropriate CSE map.
515 RemoveNodeFromCSEMaps(N);
517 // Next, brutally remove the operand list. This is safe to do, as there are
518 // no cycles in the graph.
519 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
520 SDNode *Operand = I->getVal();
521 Operand->removeUser(std::distance(N->op_begin(), I), N);
523 // Now that we removed this operand, see if there are no uses of it left.
524 if (Operand->use_empty())
525 DeadNodes.push_back(Operand);
527 if (N->OperandsNeedDelete) {
528 delete[] N->OperandList;
533 // Finally, remove N itself.
538 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
539 SmallVector<SDNode*, 16> DeadNodes;
540 DeadNodes.push_back(N);
541 RemoveDeadNodes(DeadNodes, UpdateListener);
544 void SelectionDAG::DeleteNode(SDNode *N) {
545 assert(N->use_empty() && "Cannot delete a node that is not dead!");
547 // First take this out of the appropriate CSE map.
548 RemoveNodeFromCSEMaps(N);
550 // Finally, remove uses due to operands of this node, remove from the
551 // AllNodes list, and delete the node.
552 DeleteNodeNotInCSEMaps(N);
555 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
557 // Drop all of the operands and decrement used nodes use counts.
558 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
559 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
560 if (N->OperandsNeedDelete) {
561 delete[] N->OperandList;
569 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
570 /// correspond to it. This is useful when we're about to delete or repurpose
571 /// the node. We don't want future request for structurally identical nodes
572 /// to return N anymore.
573 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
575 switch (N->getOpcode()) {
576 case ISD::HANDLENODE: return; // noop.
578 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
579 "Cond code doesn't exist!");
580 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
581 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
583 case ISD::ExternalSymbol:
584 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
586 case ISD::TargetExternalSymbol:
588 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
590 case ISD::VALUETYPE: {
591 MVT VT = cast<VTSDNode>(N)->getVT();
592 if (VT.isExtended()) {
593 Erased = ExtendedValueTypeNodes.erase(VT);
595 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
596 ValueTypeNodes[VT.getSimpleVT()] = 0;
601 // Remove it from the CSE Map.
602 Erased = CSEMap.RemoveNode(N);
606 // Verify that the node was actually in one of the CSE maps, unless it has a
607 // flag result (which cannot be CSE'd) or is one of the special cases that are
608 // not subject to CSE.
609 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
610 !N->isTargetOpcode()) {
613 assert(0 && "Node is not in map!");
618 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
619 /// has been taken out and modified in some way. If the specified node already
620 /// exists in the CSE maps, do not modify the maps, but return the existing node
621 /// instead. If it doesn't exist, add it and return null.
623 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
624 assert(N->getNumOperands() && "This is a leaf node!");
625 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
626 return 0; // Never add these nodes.
628 // Check that remaining values produced are not flags.
629 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
630 if (N->getValueType(i) == MVT::Flag)
631 return 0; // Never CSE anything that produces a flag.
633 SDNode *New = CSEMap.GetOrInsertNode(N);
634 if (New != N) return New; // Node already existed.
638 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
639 /// were replaced with those specified. If this node is never memoized,
640 /// return null, otherwise return a pointer to the slot it would take. If a
641 /// node already exists with these operands, the slot will be non-null.
642 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
644 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
645 return 0; // Never add these nodes.
647 // Check that remaining values produced are not flags.
648 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
649 if (N->getValueType(i) == MVT::Flag)
650 return 0; // Never CSE anything that produces a flag.
652 SDOperand Ops[] = { Op };
654 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
655 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
658 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
659 /// were replaced with those specified. If this node is never memoized,
660 /// return null, otherwise return a pointer to the slot it would take. If a
661 /// node already exists with these operands, the slot will be non-null.
662 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
663 SDOperand Op1, SDOperand Op2,
665 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
666 return 0; // Never add these nodes.
668 // Check that remaining values produced are not flags.
669 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
670 if (N->getValueType(i) == MVT::Flag)
671 return 0; // Never CSE anything that produces a flag.
673 SDOperand Ops[] = { Op1, Op2 };
675 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
676 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
680 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
681 /// were replaced with those specified. If this node is never memoized,
682 /// return null, otherwise return a pointer to the slot it would take. If a
683 /// node already exists with these operands, the slot will be non-null.
684 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
685 const SDOperand *Ops,unsigned NumOps,
687 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
688 return 0; // Never add these nodes.
690 // Check that remaining values produced are not flags.
691 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
692 if (N->getValueType(i) == MVT::Flag)
693 return 0; // Never CSE anything that produces a flag.
696 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
698 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
699 ID.AddInteger(LD->getAddressingMode());
700 ID.AddInteger(LD->getExtensionType());
701 ID.AddInteger(LD->getMemoryVT().getRawBits());
702 ID.AddInteger(LD->getAlignment());
703 ID.AddInteger(LD->isVolatile());
704 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
705 ID.AddInteger(ST->getAddressingMode());
706 ID.AddInteger(ST->isTruncatingStore());
707 ID.AddInteger(ST->getMemoryVT().getRawBits());
708 ID.AddInteger(ST->getAlignment());
709 ID.AddInteger(ST->isVolatile());
712 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
716 SelectionDAG::~SelectionDAG() {
717 while (!AllNodes.empty()) {
718 SDNode *N = AllNodes.begin();
719 N->SetNextInBucket(0);
720 if (N->OperandsNeedDelete) {
721 delete [] N->OperandList;
725 AllNodes.pop_front();
729 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
730 if (Op.getValueType() == VT) return Op;
731 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
733 return getNode(ISD::AND, Op.getValueType(), Op,
734 getConstant(Imm, Op.getValueType()));
737 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
738 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
739 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
742 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
743 assert(VT.isInteger() && "Cannot create FP integer constant!");
745 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
746 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
747 "APInt size does not match type size!");
749 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
751 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
755 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
757 return SDOperand(N, 0);
759 N = getAllocator().Allocate<ConstantSDNode>();
760 new (N) ConstantSDNode(isT, Val, EltVT);
761 CSEMap.InsertNode(N, IP);
762 AllNodes.push_back(N);
765 SDOperand Result(N, 0);
767 SmallVector<SDOperand, 8> Ops;
768 Ops.assign(VT.getVectorNumElements(), Result);
769 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
774 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
775 return getConstant(Val, TLI.getPointerTy(), isTarget);
779 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
780 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
783 VT.isVector() ? VT.getVectorElementType() : VT;
785 // Do the map lookup using the actual bit pattern for the floating point
786 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
787 // we don't have issues with SNANs.
788 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
790 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
794 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
796 return SDOperand(N, 0);
798 N = getAllocator().Allocate<ConstantFPSDNode>();
799 new (N) ConstantFPSDNode(isTarget, V, EltVT);
800 CSEMap.InsertNode(N, IP);
801 AllNodes.push_back(N);
804 SDOperand Result(N, 0);
806 SmallVector<SDOperand, 8> Ops;
807 Ops.assign(VT.getVectorNumElements(), Result);
808 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
813 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
815 VT.isVector() ? VT.getVectorElementType() : VT;
817 return getConstantFP(APFloat((float)Val), VT, isTarget);
819 return getConstantFP(APFloat(Val), VT, isTarget);
822 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
827 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
829 // If GV is an alias then use the aliasee for determining thread-localness.
830 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
831 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
834 if (GVar && GVar->isThreadLocal())
835 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
837 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
840 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
842 ID.AddInteger(Offset);
844 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
845 return SDOperand(E, 0);
846 SDNode *N = getAllocator().Allocate<GlobalAddressSDNode>();
847 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
848 CSEMap.InsertNode(N, IP);
849 AllNodes.push_back(N);
850 return SDOperand(N, 0);
853 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
854 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
856 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
859 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
860 return SDOperand(E, 0);
861 SDNode *N = getAllocator().Allocate<FrameIndexSDNode>();
862 new (N) FrameIndexSDNode(FI, VT, isTarget);
863 CSEMap.InsertNode(N, IP);
864 AllNodes.push_back(N);
865 return SDOperand(N, 0);
868 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
869 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
871 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
874 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
875 return SDOperand(E, 0);
876 SDNode *N = getAllocator().Allocate<JumpTableSDNode>();
877 new (N) JumpTableSDNode(JTI, VT, isTarget);
878 CSEMap.InsertNode(N, IP);
879 AllNodes.push_back(N);
880 return SDOperand(N, 0);
883 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
884 unsigned Alignment, int Offset,
886 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
888 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
889 ID.AddInteger(Alignment);
890 ID.AddInteger(Offset);
893 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
894 return SDOperand(E, 0);
895 SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
896 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
897 CSEMap.InsertNode(N, IP);
898 AllNodes.push_back(N);
899 return SDOperand(N, 0);
903 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
904 unsigned Alignment, int Offset,
906 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
908 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
909 ID.AddInteger(Alignment);
910 ID.AddInteger(Offset);
911 C->AddSelectionDAGCSEId(ID);
913 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
914 return SDOperand(E, 0);
915 SDNode *N = getAllocator().Allocate<ConstantPoolSDNode>();
916 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
917 CSEMap.InsertNode(N, IP);
918 AllNodes.push_back(N);
919 return SDOperand(N, 0);
923 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
925 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
928 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
929 return SDOperand(E, 0);
930 SDNode *N = getAllocator().Allocate<BasicBlockSDNode>();
931 new (N) BasicBlockSDNode(MBB);
932 CSEMap.InsertNode(N, IP);
933 AllNodes.push_back(N);
934 return SDOperand(N, 0);
937 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
939 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
940 ID.AddInteger(Flags.getRawBits());
942 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
943 return SDOperand(E, 0);
944 SDNode *N = getAllocator().Allocate<ARG_FLAGSSDNode>();
945 new (N) ARG_FLAGSSDNode(Flags);
946 CSEMap.InsertNode(N, IP);
947 AllNodes.push_back(N);
948 return SDOperand(N, 0);
951 SDOperand SelectionDAG::getValueType(MVT VT) {
952 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
953 ValueTypeNodes.resize(VT.getSimpleVT()+1);
955 SDNode *&N = VT.isExtended() ?
956 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
958 if (N) return SDOperand(N, 0);
959 N = getAllocator().Allocate<VTSDNode>();
960 new (N) VTSDNode(VT);
961 AllNodes.push_back(N);
962 return SDOperand(N, 0);
965 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
966 SDNode *&N = ExternalSymbols[Sym];
967 if (N) return SDOperand(N, 0);
968 N = getAllocator().Allocate<ExternalSymbolSDNode>();
969 new (N) ExternalSymbolSDNode(false, Sym, VT);
970 AllNodes.push_back(N);
971 return SDOperand(N, 0);
974 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
975 SDNode *&N = TargetExternalSymbols[Sym];
976 if (N) return SDOperand(N, 0);
977 N = getAllocator().Allocate<ExternalSymbolSDNode>();
978 new (N) ExternalSymbolSDNode(true, Sym, VT);
979 AllNodes.push_back(N);
980 return SDOperand(N, 0);
983 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
984 if ((unsigned)Cond >= CondCodeNodes.size())
985 CondCodeNodes.resize(Cond+1);
987 if (CondCodeNodes[Cond] == 0) {
988 CondCodeSDNode *N = getAllocator().Allocate<CondCodeSDNode>();
989 new (N) CondCodeSDNode(Cond);
990 CondCodeNodes[Cond] = N;
991 AllNodes.push_back(N);
993 return SDOperand(CondCodeNodes[Cond], 0);
996 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
998 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
999 ID.AddInteger(RegNo);
1001 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1002 return SDOperand(E, 0);
1003 SDNode *N = getAllocator().Allocate<RegisterSDNode>();
1004 new (N) RegisterSDNode(RegNo, VT);
1005 CSEMap.InsertNode(N, IP);
1006 AllNodes.push_back(N);
1007 return SDOperand(N, 0);
1010 SDOperand SelectionDAG::getDbgStopPoint(SDOperand Root,
1011 unsigned Line, unsigned Col,
1012 const CompileUnitDesc *CU) {
1013 FoldingSetNodeID ID;
1014 SDOperand Ops[] = { Root };
1015 AddNodeIDNode(ID, ISD::DBG_STOPPOINT, getVTList(MVT::Other), &Ops[0], 1);
1016 ID.AddInteger(Line);
1020 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1021 return SDOperand(E, 0);
1022 SDNode *N = getAllocator().Allocate<DbgStopPointSDNode>();
1023 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1024 CSEMap.InsertNode(N, IP);
1025 AllNodes.push_back(N);
1026 return SDOperand(N, 0);
1029 SDOperand SelectionDAG::getLabel(unsigned Opcode,
1032 FoldingSetNodeID ID;
1033 SDOperand Ops[] = { Root };
1034 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1035 ID.AddInteger(LabelID);
1037 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1038 return SDOperand(E, 0);
1039 SDNode *N = getAllocator().Allocate<LabelSDNode>();
1040 new (N) LabelSDNode(Opcode, Root, LabelID);
1041 CSEMap.InsertNode(N, IP);
1042 AllNodes.push_back(N);
1043 return SDOperand(N, 0);
1046 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1047 assert((!V || isa<PointerType>(V->getType())) &&
1048 "SrcValue is not a pointer?");
1050 FoldingSetNodeID ID;
1051 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1055 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1056 return SDOperand(E, 0);
1058 SDNode *N = getAllocator().Allocate<SrcValueSDNode>();
1059 new (N) SrcValueSDNode(V);
1060 CSEMap.InsertNode(N, IP);
1061 AllNodes.push_back(N);
1062 return SDOperand(N, 0);
1065 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1066 const Value *v = MO.getValue();
1067 assert((!v || isa<PointerType>(v->getType())) &&
1068 "SrcValue is not a pointer?");
1070 FoldingSetNodeID ID;
1071 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1073 ID.AddInteger(MO.getFlags());
1074 ID.AddInteger(MO.getOffset());
1075 ID.AddInteger(MO.getSize());
1076 ID.AddInteger(MO.getAlignment());
1079 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1080 return SDOperand(E, 0);
1082 SDNode *N = getAllocator().Allocate<MemOperandSDNode>();
1083 new (N) MemOperandSDNode(MO);
1084 CSEMap.InsertNode(N, IP);
1085 AllNodes.push_back(N);
1086 return SDOperand(N, 0);
1089 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1090 /// specified value type.
1091 SDOperand SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1092 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1093 unsigned ByteSize = VT.getSizeInBits()/8;
1094 const Type *Ty = VT.getTypeForMVT();
1095 unsigned StackAlign =
1096 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1098 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1099 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1102 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1103 SDOperand N2, ISD::CondCode Cond) {
1104 // These setcc operations always fold.
1108 case ISD::SETFALSE2: return getConstant(0, VT);
1110 case ISD::SETTRUE2: return getConstant(1, VT);
1122 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1126 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1127 const APInt &C2 = N2C->getAPIntValue();
1128 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1129 const APInt &C1 = N1C->getAPIntValue();
1132 default: assert(0 && "Unknown integer setcc!");
1133 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1134 case ISD::SETNE: return getConstant(C1 != C2, VT);
1135 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1136 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1137 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1138 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1139 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1140 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1141 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1142 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1146 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1147 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1148 // No compile time operations on this type yet.
1149 if (N1C->getValueType(0) == MVT::ppcf128)
1152 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1155 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1156 return getNode(ISD::UNDEF, VT);
1158 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1159 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1160 return getNode(ISD::UNDEF, VT);
1162 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1163 R==APFloat::cmpLessThan, VT);
1164 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1165 return getNode(ISD::UNDEF, VT);
1167 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1168 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1169 return getNode(ISD::UNDEF, VT);
1171 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1172 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1173 return getNode(ISD::UNDEF, VT);
1175 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1176 R==APFloat::cmpEqual, VT);
1177 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1178 return getNode(ISD::UNDEF, VT);
1180 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1181 R==APFloat::cmpEqual, VT);
1182 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1183 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1184 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1185 R==APFloat::cmpEqual, VT);
1186 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1187 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1188 R==APFloat::cmpLessThan, VT);
1189 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1190 R==APFloat::cmpUnordered, VT);
1191 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1192 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1195 // Ensure that the constant occurs on the RHS.
1196 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1200 // Could not fold it.
1204 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1205 /// use this predicate to simplify operations downstream.
1206 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1207 unsigned BitWidth = Op.getValueSizeInBits();
1208 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1211 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1212 /// this predicate to simplify operations downstream. Mask is known to be zero
1213 /// for bits that V cannot have.
1214 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1215 unsigned Depth) const {
1216 APInt KnownZero, KnownOne;
1217 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1218 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1219 return (KnownZero & Mask) == Mask;
1222 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1223 /// known to be either zero or one and return them in the KnownZero/KnownOne
1224 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1226 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1227 APInt &KnownZero, APInt &KnownOne,
1228 unsigned Depth) const {
1229 unsigned BitWidth = Mask.getBitWidth();
1230 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1231 "Mask size mismatches value type size!");
1233 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1234 if (Depth == 6 || Mask == 0)
1235 return; // Limit search depth.
1237 APInt KnownZero2, KnownOne2;
1239 switch (Op.getOpcode()) {
1241 // We know all of the bits for a constant!
1242 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1243 KnownZero = ~KnownOne & Mask;
1246 // If either the LHS or the RHS are Zero, the result is zero.
1247 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1248 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1249 KnownZero2, KnownOne2, Depth+1);
1250 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1251 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1253 // Output known-1 bits are only known if set in both the LHS & RHS.
1254 KnownOne &= KnownOne2;
1255 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1256 KnownZero |= KnownZero2;
1259 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1260 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1261 KnownZero2, KnownOne2, Depth+1);
1262 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1263 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1265 // Output known-0 bits are only known if clear in both the LHS & RHS.
1266 KnownZero &= KnownZero2;
1267 // Output known-1 are known to be set if set in either the LHS | RHS.
1268 KnownOne |= KnownOne2;
1271 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1272 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1273 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1274 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1276 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1277 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1278 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1279 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1280 KnownZero = KnownZeroOut;
1284 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1285 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1286 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1287 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1288 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1290 // If low bits are zero in either operand, output low known-0 bits.
1291 // Also compute a conserative estimate for high known-0 bits.
1292 // More trickiness is possible, but this is sufficient for the
1293 // interesting case of alignment computation.
1295 unsigned TrailZ = KnownZero.countTrailingOnes() +
1296 KnownZero2.countTrailingOnes();
1297 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1298 KnownZero2.countLeadingOnes(),
1299 BitWidth) - BitWidth;
1301 TrailZ = std::min(TrailZ, BitWidth);
1302 LeadZ = std::min(LeadZ, BitWidth);
1303 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1304 APInt::getHighBitsSet(BitWidth, LeadZ);
1309 // For the purposes of computing leading zeros we can conservatively
1310 // treat a udiv as a logical right shift by the power of 2 known to
1311 // be less than the denominator.
1312 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1313 ComputeMaskedBits(Op.getOperand(0),
1314 AllOnes, KnownZero2, KnownOne2, Depth+1);
1315 unsigned LeadZ = KnownZero2.countLeadingOnes();
1319 ComputeMaskedBits(Op.getOperand(1),
1320 AllOnes, KnownZero2, KnownOne2, Depth+1);
1321 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1322 if (RHSUnknownLeadingOnes != BitWidth)
1323 LeadZ = std::min(BitWidth,
1324 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1326 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1330 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1331 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1332 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1333 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1335 // Only known if known in both the LHS and RHS.
1336 KnownOne &= KnownOne2;
1337 KnownZero &= KnownZero2;
1339 case ISD::SELECT_CC:
1340 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1341 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1342 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1343 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1345 // Only known if known in both the LHS and RHS.
1346 KnownOne &= KnownOne2;
1347 KnownZero &= KnownZero2;
1350 // If we know the result of a setcc has the top bits zero, use this info.
1351 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1353 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1356 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1357 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1358 unsigned ShAmt = SA->getValue();
1360 // If the shift count is an invalid immediate, don't do anything.
1361 if (ShAmt >= BitWidth)
1364 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1365 KnownZero, KnownOne, Depth+1);
1366 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1367 KnownZero <<= ShAmt;
1369 // low bits known zero.
1370 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1374 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1375 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1376 unsigned ShAmt = SA->getValue();
1378 // If the shift count is an invalid immediate, don't do anything.
1379 if (ShAmt >= BitWidth)
1382 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1383 KnownZero, KnownOne, Depth+1);
1384 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1385 KnownZero = KnownZero.lshr(ShAmt);
1386 KnownOne = KnownOne.lshr(ShAmt);
1388 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1389 KnownZero |= HighBits; // High bits known zero.
1393 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1394 unsigned ShAmt = SA->getValue();
1396 // If the shift count is an invalid immediate, don't do anything.
1397 if (ShAmt >= BitWidth)
1400 APInt InDemandedMask = (Mask << ShAmt);
1401 // If any of the demanded bits are produced by the sign extension, we also
1402 // demand the input sign bit.
1403 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1404 if (HighBits.getBoolValue())
1405 InDemandedMask |= APInt::getSignBit(BitWidth);
1407 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1409 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1410 KnownZero = KnownZero.lshr(ShAmt);
1411 KnownOne = KnownOne.lshr(ShAmt);
1413 // Handle the sign bits.
1414 APInt SignBit = APInt::getSignBit(BitWidth);
1415 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1417 if (KnownZero.intersects(SignBit)) {
1418 KnownZero |= HighBits; // New bits are known zero.
1419 } else if (KnownOne.intersects(SignBit)) {
1420 KnownOne |= HighBits; // New bits are known one.
1424 case ISD::SIGN_EXTEND_INREG: {
1425 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1426 unsigned EBits = EVT.getSizeInBits();
1428 // Sign extension. Compute the demanded bits in the result that are not
1429 // present in the input.
1430 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1432 APInt InSignBit = APInt::getSignBit(EBits);
1433 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1435 // If the sign extended bits are demanded, we know that the sign
1437 InSignBit.zext(BitWidth);
1438 if (NewBits.getBoolValue())
1439 InputDemandedBits |= InSignBit;
1441 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1442 KnownZero, KnownOne, Depth+1);
1443 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1445 // If the sign bit of the input is known set or clear, then we know the
1446 // top bits of the result.
1447 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1448 KnownZero |= NewBits;
1449 KnownOne &= ~NewBits;
1450 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1451 KnownOne |= NewBits;
1452 KnownZero &= ~NewBits;
1453 } else { // Input sign bit unknown
1454 KnownZero &= ~NewBits;
1455 KnownOne &= ~NewBits;
1462 unsigned LowBits = Log2_32(BitWidth)+1;
1463 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1468 if (ISD::isZEXTLoad(Op.Val)) {
1469 LoadSDNode *LD = cast<LoadSDNode>(Op);
1470 MVT VT = LD->getMemoryVT();
1471 unsigned MemBits = VT.getSizeInBits();
1472 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1476 case ISD::ZERO_EXTEND: {
1477 MVT InVT = Op.getOperand(0).getValueType();
1478 unsigned InBits = InVT.getSizeInBits();
1479 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1480 APInt InMask = Mask;
1481 InMask.trunc(InBits);
1482 KnownZero.trunc(InBits);
1483 KnownOne.trunc(InBits);
1484 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1485 KnownZero.zext(BitWidth);
1486 KnownOne.zext(BitWidth);
1487 KnownZero |= NewBits;
1490 case ISD::SIGN_EXTEND: {
1491 MVT InVT = Op.getOperand(0).getValueType();
1492 unsigned InBits = InVT.getSizeInBits();
1493 APInt InSignBit = APInt::getSignBit(InBits);
1494 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1495 APInt InMask = Mask;
1496 InMask.trunc(InBits);
1498 // If any of the sign extended bits are demanded, we know that the sign
1499 // bit is demanded. Temporarily set this bit in the mask for our callee.
1500 if (NewBits.getBoolValue())
1501 InMask |= InSignBit;
1503 KnownZero.trunc(InBits);
1504 KnownOne.trunc(InBits);
1505 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1507 // Note if the sign bit is known to be zero or one.
1508 bool SignBitKnownZero = KnownZero.isNegative();
1509 bool SignBitKnownOne = KnownOne.isNegative();
1510 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1511 "Sign bit can't be known to be both zero and one!");
1513 // If the sign bit wasn't actually demanded by our caller, we don't
1514 // want it set in the KnownZero and KnownOne result values. Reset the
1515 // mask and reapply it to the result values.
1517 InMask.trunc(InBits);
1518 KnownZero &= InMask;
1521 KnownZero.zext(BitWidth);
1522 KnownOne.zext(BitWidth);
1524 // If the sign bit is known zero or one, the top bits match.
1525 if (SignBitKnownZero)
1526 KnownZero |= NewBits;
1527 else if (SignBitKnownOne)
1528 KnownOne |= NewBits;
1531 case ISD::ANY_EXTEND: {
1532 MVT InVT = Op.getOperand(0).getValueType();
1533 unsigned InBits = InVT.getSizeInBits();
1534 APInt InMask = Mask;
1535 InMask.trunc(InBits);
1536 KnownZero.trunc(InBits);
1537 KnownOne.trunc(InBits);
1538 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1539 KnownZero.zext(BitWidth);
1540 KnownOne.zext(BitWidth);
1543 case ISD::TRUNCATE: {
1544 MVT InVT = Op.getOperand(0).getValueType();
1545 unsigned InBits = InVT.getSizeInBits();
1546 APInt InMask = Mask;
1547 InMask.zext(InBits);
1548 KnownZero.zext(InBits);
1549 KnownOne.zext(InBits);
1550 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1551 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1552 KnownZero.trunc(BitWidth);
1553 KnownOne.trunc(BitWidth);
1556 case ISD::AssertZext: {
1557 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1558 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1559 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1561 KnownZero |= (~InMask) & Mask;
1565 // All bits are zero except the low bit.
1566 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1570 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1571 // We know that the top bits of C-X are clear if X contains less bits
1572 // than C (i.e. no wrap-around can happen). For example, 20-X is
1573 // positive if we can prove that X is >= 0 and < 16.
1574 if (CLHS->getAPIntValue().isNonNegative()) {
1575 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1576 // NLZ can't be BitWidth with no sign bit
1577 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1578 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1581 // If all of the MaskV bits are known to be zero, then we know the
1582 // output top bits are zero, because we now know that the output is
1584 if ((KnownZero2 & MaskV) == MaskV) {
1585 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1586 // Top bits known zero.
1587 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1594 // Output known-0 bits are known if clear or set in both the low clear bits
1595 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1596 // low 3 bits clear.
1597 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1598 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1599 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1600 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1602 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1603 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1604 KnownZeroOut = std::min(KnownZeroOut,
1605 KnownZero2.countTrailingOnes());
1607 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1611 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1612 const APInt &RA = Rem->getAPIntValue();
1613 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1614 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1615 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1616 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1618 // The sign of a remainder is equal to the sign of the first
1619 // operand (zero being positive).
1620 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1621 KnownZero2 |= ~LowBits;
1622 else if (KnownOne2[BitWidth-1])
1623 KnownOne2 |= ~LowBits;
1625 KnownZero |= KnownZero2 & Mask;
1626 KnownOne |= KnownOne2 & Mask;
1628 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1633 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1634 const APInt &RA = Rem->getAPIntValue();
1635 if (RA.isPowerOf2()) {
1636 APInt LowBits = (RA - 1);
1637 APInt Mask2 = LowBits & Mask;
1638 KnownZero |= ~LowBits & Mask;
1639 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1640 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1645 // Since the result is less than or equal to either operand, any leading
1646 // zero bits in either operand must also exist in the result.
1647 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1648 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1650 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1653 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1654 KnownZero2.countLeadingOnes());
1656 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1660 // Allow the target to implement this method for its nodes.
1661 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1662 case ISD::INTRINSIC_WO_CHAIN:
1663 case ISD::INTRINSIC_W_CHAIN:
1664 case ISD::INTRINSIC_VOID:
1665 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1671 /// ComputeNumSignBits - Return the number of times the sign bit of the
1672 /// register is replicated into the other bits. We know that at least 1 bit
1673 /// is always equal to the sign bit (itself), but other cases can give us
1674 /// information. For example, immediately after an "SRA X, 2", we know that
1675 /// the top 3 bits are all equal to each other, so we return 3.
1676 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1677 MVT VT = Op.getValueType();
1678 assert(VT.isInteger() && "Invalid VT!");
1679 unsigned VTBits = VT.getSizeInBits();
1681 unsigned FirstAnswer = 1;
1684 return 1; // Limit search depth.
1686 switch (Op.getOpcode()) {
1688 case ISD::AssertSext:
1689 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1690 return VTBits-Tmp+1;
1691 case ISD::AssertZext:
1692 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1695 case ISD::Constant: {
1696 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1697 // If negative, return # leading ones.
1698 if (Val.isNegative())
1699 return Val.countLeadingOnes();
1701 // Return # leading zeros.
1702 return Val.countLeadingZeros();
1705 case ISD::SIGN_EXTEND:
1706 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1707 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1709 case ISD::SIGN_EXTEND_INREG:
1710 // Max of the input and what this extends.
1711 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1714 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1715 return std::max(Tmp, Tmp2);
1718 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1719 // SRA X, C -> adds C sign bits.
1720 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1721 Tmp += C->getValue();
1722 if (Tmp > VTBits) Tmp = VTBits;
1726 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1727 // shl destroys sign bits.
1728 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1729 if (C->getValue() >= VTBits || // Bad shift.
1730 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1731 return Tmp - C->getValue();
1736 case ISD::XOR: // NOT is handled here.
1737 // Logical binary ops preserve the number of sign bits at the worst.
1738 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1740 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1741 FirstAnswer = std::min(Tmp, Tmp2);
1742 // We computed what we know about the sign bits as our first
1743 // answer. Now proceed to the generic code that uses
1744 // ComputeMaskedBits, and pick whichever answer is better.
1749 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1750 if (Tmp == 1) return 1; // Early out.
1751 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1752 return std::min(Tmp, Tmp2);
1755 // If setcc returns 0/-1, all bits are sign bits.
1756 if (TLI.getSetCCResultContents() ==
1757 TargetLowering::ZeroOrNegativeOneSetCCResult)
1762 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1763 unsigned RotAmt = C->getValue() & (VTBits-1);
1765 // Handle rotate right by N like a rotate left by 32-N.
1766 if (Op.getOpcode() == ISD::ROTR)
1767 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1769 // If we aren't rotating out all of the known-in sign bits, return the
1770 // number that are left. This handles rotl(sext(x), 1) for example.
1771 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1772 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1776 // Add can have at most one carry bit. Thus we know that the output
1777 // is, at worst, one more bit than the inputs.
1778 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1779 if (Tmp == 1) return 1; // Early out.
1781 // Special case decrementing a value (ADD X, -1):
1782 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1783 if (CRHS->isAllOnesValue()) {
1784 APInt KnownZero, KnownOne;
1785 APInt Mask = APInt::getAllOnesValue(VTBits);
1786 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1788 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1790 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1793 // If we are subtracting one from a positive number, there is no carry
1794 // out of the result.
1795 if (KnownZero.isNegative())
1799 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1800 if (Tmp2 == 1) return 1;
1801 return std::min(Tmp, Tmp2)-1;
1805 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1806 if (Tmp2 == 1) return 1;
1809 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1810 if (CLHS->isNullValue()) {
1811 APInt KnownZero, KnownOne;
1812 APInt Mask = APInt::getAllOnesValue(VTBits);
1813 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1814 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1816 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1819 // If the input is known to be positive (the sign bit is known clear),
1820 // the output of the NEG has the same number of sign bits as the input.
1821 if (KnownZero.isNegative())
1824 // Otherwise, we treat this like a SUB.
1827 // Sub can have at most one carry bit. Thus we know that the output
1828 // is, at worst, one more bit than the inputs.
1829 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1830 if (Tmp == 1) return 1; // Early out.
1831 return std::min(Tmp, Tmp2)-1;
1834 // FIXME: it's tricky to do anything useful for this, but it is an important
1835 // case for targets like X86.
1839 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1840 if (Op.getOpcode() == ISD::LOAD) {
1841 LoadSDNode *LD = cast<LoadSDNode>(Op);
1842 unsigned ExtType = LD->getExtensionType();
1845 case ISD::SEXTLOAD: // '17' bits known
1846 Tmp = LD->getMemoryVT().getSizeInBits();
1847 return VTBits-Tmp+1;
1848 case ISD::ZEXTLOAD: // '16' bits known
1849 Tmp = LD->getMemoryVT().getSizeInBits();
1854 // Allow the target to implement this method for its nodes.
1855 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1856 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1857 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1858 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1859 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1860 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1863 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1864 // use this information.
1865 APInt KnownZero, KnownOne;
1866 APInt Mask = APInt::getAllOnesValue(VTBits);
1867 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1869 if (KnownZero.isNegative()) { // sign bit is 0
1871 } else if (KnownOne.isNegative()) { // sign bit is 1;
1878 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1879 // the number of identical bits in the top of the input value.
1881 Mask <<= Mask.getBitWidth()-VTBits;
1882 // Return # leading zeros. We use 'min' here in case Val was zero before
1883 // shifting. We don't want to return '64' as for an i32 "0".
1884 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1888 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1889 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1890 if (!GA) return false;
1891 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1892 if (!GV) return false;
1893 MachineModuleInfo *MMI = getMachineModuleInfo();
1894 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1898 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1899 /// element of the result of the vector shuffle.
1900 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1901 MVT VT = N->getValueType(0);
1902 SDOperand PermMask = N->getOperand(2);
1903 SDOperand Idx = PermMask.getOperand(i);
1904 if (Idx.getOpcode() == ISD::UNDEF)
1905 return getNode(ISD::UNDEF, VT.getVectorElementType());
1906 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1907 unsigned NumElems = PermMask.getNumOperands();
1908 SDOperand V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1911 if (V.getOpcode() == ISD::BIT_CONVERT) {
1912 V = V.getOperand(0);
1913 if (V.getValueType().getVectorNumElements() != NumElems)
1916 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1917 return (Index == 0) ? V.getOperand(0)
1918 : getNode(ISD::UNDEF, VT.getVectorElementType());
1919 if (V.getOpcode() == ISD::BUILD_VECTOR)
1920 return V.getOperand(Index);
1921 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1922 return getShuffleScalarElt(V.Val, Index);
1927 /// getNode - Gets or creates the specified node.
1929 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1930 FoldingSetNodeID ID;
1931 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1933 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1934 return SDOperand(E, 0);
1935 SDNode *N = getAllocator().Allocate<SDNode>();
1936 new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
1937 CSEMap.InsertNode(N, IP);
1939 AllNodes.push_back(N);
1940 return SDOperand(N, 0);
1943 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1944 // Constant fold unary operations with an integer constant operand.
1945 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1946 const APInt &Val = C->getAPIntValue();
1947 unsigned BitWidth = VT.getSizeInBits();
1950 case ISD::SIGN_EXTEND:
1951 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1952 case ISD::ANY_EXTEND:
1953 case ISD::ZERO_EXTEND:
1955 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1956 case ISD::UINT_TO_FP:
1957 case ISD::SINT_TO_FP: {
1958 const uint64_t zero[] = {0, 0};
1959 // No compile time operations on this type.
1960 if (VT==MVT::ppcf128)
1962 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1963 (void)apf.convertFromAPInt(Val,
1964 Opcode==ISD::SINT_TO_FP,
1965 APFloat::rmNearestTiesToEven);
1966 return getConstantFP(apf, VT);
1968 case ISD::BIT_CONVERT:
1969 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1970 return getConstantFP(Val.bitsToFloat(), VT);
1971 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1972 return getConstantFP(Val.bitsToDouble(), VT);
1975 return getConstant(Val.byteSwap(), VT);
1977 return getConstant(Val.countPopulation(), VT);
1979 return getConstant(Val.countLeadingZeros(), VT);
1981 return getConstant(Val.countTrailingZeros(), VT);
1985 // Constant fold unary operations with a floating point constant operand.
1986 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1987 APFloat V = C->getValueAPF(); // make copy
1988 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1992 return getConstantFP(V, VT);
1995 return getConstantFP(V, VT);
1997 case ISD::FP_EXTEND:
1998 // This can return overflow, underflow, or inexact; we don't care.
1999 // FIXME need to be more flexible about rounding mode.
2000 (void)V.convert(*MVTToAPFloatSemantics(VT),
2001 APFloat::rmNearestTiesToEven);
2002 return getConstantFP(V, VT);
2003 case ISD::FP_TO_SINT:
2004 case ISD::FP_TO_UINT: {
2006 assert(integerPartWidth >= 64);
2007 // FIXME need to be more flexible about rounding mode.
2008 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2009 Opcode==ISD::FP_TO_SINT,
2010 APFloat::rmTowardZero);
2011 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2013 return getConstant(x, VT);
2015 case ISD::BIT_CONVERT:
2016 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2017 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2018 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2019 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2025 unsigned OpOpcode = Operand.Val->getOpcode();
2027 case ISD::TokenFactor:
2028 return Operand; // Factor of one node? No need.
2029 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2030 case ISD::FP_EXTEND:
2031 assert(VT.isFloatingPoint() &&
2032 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2033 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2034 if (Operand.getOpcode() == ISD::UNDEF)
2035 return getNode(ISD::UNDEF, VT);
2037 case ISD::SIGN_EXTEND:
2038 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2039 "Invalid SIGN_EXTEND!");
2040 if (Operand.getValueType() == VT) return Operand; // noop extension
2041 assert(Operand.getValueType().bitsLT(VT)
2042 && "Invalid sext node, dst < src!");
2043 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2044 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2046 case ISD::ZERO_EXTEND:
2047 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2048 "Invalid ZERO_EXTEND!");
2049 if (Operand.getValueType() == VT) return Operand; // noop extension
2050 assert(Operand.getValueType().bitsLT(VT)
2051 && "Invalid zext node, dst < src!");
2052 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2053 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2055 case ISD::ANY_EXTEND:
2056 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2057 "Invalid ANY_EXTEND!");
2058 if (Operand.getValueType() == VT) return Operand; // noop extension
2059 assert(Operand.getValueType().bitsLT(VT)
2060 && "Invalid anyext node, dst < src!");
2061 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2062 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2063 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2066 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2067 "Invalid TRUNCATE!");
2068 if (Operand.getValueType() == VT) return Operand; // noop truncate
2069 assert(Operand.getValueType().bitsGT(VT)
2070 && "Invalid truncate node, src < dst!");
2071 if (OpOpcode == ISD::TRUNCATE)
2072 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2073 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2074 OpOpcode == ISD::ANY_EXTEND) {
2075 // If the source is smaller than the dest, we still need an extend.
2076 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2077 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2078 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2079 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2081 return Operand.Val->getOperand(0);
2084 case ISD::BIT_CONVERT:
2085 // Basic sanity checking.
2086 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2087 && "Cannot BIT_CONVERT between types of different sizes!");
2088 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2089 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2090 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2091 if (OpOpcode == ISD::UNDEF)
2092 return getNode(ISD::UNDEF, VT);
2094 case ISD::SCALAR_TO_VECTOR:
2095 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2096 VT.getVectorElementType() == Operand.getValueType() &&
2097 "Illegal SCALAR_TO_VECTOR node!");
2098 if (OpOpcode == ISD::UNDEF)
2099 return getNode(ISD::UNDEF, VT);
2100 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2101 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2102 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2103 Operand.getConstantOperandVal(1) == 0 &&
2104 Operand.getOperand(0).getValueType() == VT)
2105 return Operand.getOperand(0);
2108 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2109 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2110 Operand.Val->getOperand(0));
2111 if (OpOpcode == ISD::FNEG) // --X -> X
2112 return Operand.Val->getOperand(0);
2115 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2116 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2121 SDVTList VTs = getVTList(VT);
2122 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2123 FoldingSetNodeID ID;
2124 SDOperand Ops[1] = { Operand };
2125 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2127 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2128 return SDOperand(E, 0);
2129 N = getAllocator().Allocate<UnarySDNode>();
2130 new (N) UnarySDNode(Opcode, VTs, Operand);
2131 CSEMap.InsertNode(N, IP);
2133 N = getAllocator().Allocate<UnarySDNode>();
2134 new (N) UnarySDNode(Opcode, VTs, Operand);
2136 AllNodes.push_back(N);
2137 return SDOperand(N, 0);
2142 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2143 SDOperand N1, SDOperand N2) {
2144 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2145 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2148 case ISD::TokenFactor:
2149 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2150 N2.getValueType() == MVT::Other && "Invalid token factor!");
2151 // Fold trivial token factors.
2152 if (N1.getOpcode() == ISD::EntryToken) return N2;
2153 if (N2.getOpcode() == ISD::EntryToken) return N1;
2156 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2157 N1.getValueType() == VT && "Binary operator types must match!");
2158 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2159 // worth handling here.
2160 if (N2C && N2C->isNullValue())
2162 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2169 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2170 N1.getValueType() == VT && "Binary operator types must match!");
2171 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2172 // it's worth handling here.
2173 if (N2C && N2C->isNullValue())
2180 assert(VT.isInteger() && "This operator does not apply to FP types!");
2190 assert(N1.getValueType() == N2.getValueType() &&
2191 N1.getValueType() == VT && "Binary operator types must match!");
2193 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2194 assert(N1.getValueType() == VT &&
2195 N1.getValueType().isFloatingPoint() &&
2196 N2.getValueType().isFloatingPoint() &&
2197 "Invalid FCOPYSIGN!");
2204 assert(VT == N1.getValueType() &&
2205 "Shift operators return type must be the same as their first arg");
2206 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2207 "Shifts only work on integers");
2209 // Always fold shifts of i1 values so the code generator doesn't need to
2210 // handle them. Since we know the size of the shift has to be less than the
2211 // size of the value, the shift/rotate count is guaranteed to be zero.
2215 case ISD::FP_ROUND_INREG: {
2216 MVT EVT = cast<VTSDNode>(N2)->getVT();
2217 assert(VT == N1.getValueType() && "Not an inreg round!");
2218 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2219 "Cannot FP_ROUND_INREG integer types");
2220 assert(EVT.bitsLE(VT) && "Not rounding down!");
2221 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2225 assert(VT.isFloatingPoint() &&
2226 N1.getValueType().isFloatingPoint() &&
2227 VT.bitsLE(N1.getValueType()) &&
2228 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2229 if (N1.getValueType() == VT) return N1; // noop conversion.
2231 case ISD::AssertSext:
2232 case ISD::AssertZext: {
2233 MVT EVT = cast<VTSDNode>(N2)->getVT();
2234 assert(VT == N1.getValueType() && "Not an inreg extend!");
2235 assert(VT.isInteger() && EVT.isInteger() &&
2236 "Cannot *_EXTEND_INREG FP types");
2237 assert(EVT.bitsLE(VT) && "Not extending!");
2238 if (VT == EVT) return N1; // noop assertion.
2241 case ISD::SIGN_EXTEND_INREG: {
2242 MVT EVT = cast<VTSDNode>(N2)->getVT();
2243 assert(VT == N1.getValueType() && "Not an inreg extend!");
2244 assert(VT.isInteger() && EVT.isInteger() &&
2245 "Cannot *_EXTEND_INREG FP types");
2246 assert(EVT.bitsLE(VT) && "Not extending!");
2247 if (EVT == VT) return N1; // Not actually extending
2250 APInt Val = N1C->getAPIntValue();
2251 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2252 Val <<= Val.getBitWidth()-FromBits;
2253 Val = Val.ashr(Val.getBitWidth()-FromBits);
2254 return getConstant(Val, VT);
2258 case ISD::EXTRACT_VECTOR_ELT:
2259 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2261 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2262 if (N1.getOpcode() == ISD::UNDEF)
2263 return getNode(ISD::UNDEF, VT);
2265 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2266 // expanding copies of large vectors from registers.
2267 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2268 N1.getNumOperands() > 0) {
2270 N1.getOperand(0).getValueType().getVectorNumElements();
2271 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2272 N1.getOperand(N2C->getValue() / Factor),
2273 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2276 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2277 // expanding large vector constants.
2278 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2279 return N1.getOperand(N2C->getValue());
2281 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2282 // operations are lowered to scalars.
2283 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2284 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2286 return N1.getOperand(1);
2288 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2291 case ISD::EXTRACT_ELEMENT:
2292 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2293 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2294 (N1.getValueType().isInteger() == VT.isInteger()) &&
2295 "Wrong types for EXTRACT_ELEMENT!");
2297 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2298 // 64-bit integers into 32-bit parts. Instead of building the extract of
2299 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2300 if (N1.getOpcode() == ISD::BUILD_PAIR)
2301 return N1.getOperand(N2C->getValue());
2303 // EXTRACT_ELEMENT of a constant int is also very common.
2304 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2305 unsigned ElementSize = VT.getSizeInBits();
2306 unsigned Shift = ElementSize * N2C->getValue();
2307 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2308 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2311 case ISD::EXTRACT_SUBVECTOR:
2312 if (N1.getValueType() == VT) // Trivial extraction.
2319 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2321 case ISD::ADD: return getConstant(C1 + C2, VT);
2322 case ISD::SUB: return getConstant(C1 - C2, VT);
2323 case ISD::MUL: return getConstant(C1 * C2, VT);
2325 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2328 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2331 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2334 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2336 case ISD::AND : return getConstant(C1 & C2, VT);
2337 case ISD::OR : return getConstant(C1 | C2, VT);
2338 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2339 case ISD::SHL : return getConstant(C1 << C2, VT);
2340 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2341 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2342 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2343 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2346 } else { // Cannonicalize constant to RHS if commutative
2347 if (isCommutativeBinOp(Opcode)) {
2348 std::swap(N1C, N2C);
2354 // Constant fold FP operations.
2355 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2356 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2358 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2359 // Cannonicalize constant to RHS if commutative
2360 std::swap(N1CFP, N2CFP);
2362 } else if (N2CFP && VT != MVT::ppcf128) {
2363 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2364 APFloat::opStatus s;
2367 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2368 if (s != APFloat::opInvalidOp)
2369 return getConstantFP(V1, VT);
2372 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2373 if (s!=APFloat::opInvalidOp)
2374 return getConstantFP(V1, VT);
2377 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2378 if (s!=APFloat::opInvalidOp)
2379 return getConstantFP(V1, VT);
2382 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2383 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2384 return getConstantFP(V1, VT);
2387 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2388 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2389 return getConstantFP(V1, VT);
2391 case ISD::FCOPYSIGN:
2393 return getConstantFP(V1, VT);
2399 // Canonicalize an UNDEF to the RHS, even over a constant.
2400 if (N1.getOpcode() == ISD::UNDEF) {
2401 if (isCommutativeBinOp(Opcode)) {
2405 case ISD::FP_ROUND_INREG:
2406 case ISD::SIGN_EXTEND_INREG:
2412 return N1; // fold op(undef, arg2) -> undef
2420 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2421 // For vectors, we can't easily build an all zero vector, just return
2428 // Fold a bunch of operators when the RHS is undef.
2429 if (N2.getOpcode() == ISD::UNDEF) {
2432 if (N1.getOpcode() == ISD::UNDEF)
2433 // Handle undef ^ undef -> 0 special case. This is a common
2435 return getConstant(0, VT);
2450 return N2; // fold op(arg1, undef) -> undef
2456 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2457 // For vectors, we can't easily build an all zero vector, just return
2462 return getConstant(VT.getIntegerVTBitMask(), VT);
2463 // For vectors, we can't easily build an all one vector, just return
2471 // Memoize this node if possible.
2473 SDVTList VTs = getVTList(VT);
2474 if (VT != MVT::Flag) {
2475 SDOperand Ops[] = { N1, N2 };
2476 FoldingSetNodeID ID;
2477 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2479 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2480 return SDOperand(E, 0);
2481 N = getAllocator().Allocate<BinarySDNode>();
2482 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2483 CSEMap.InsertNode(N, IP);
2485 N = getAllocator().Allocate<BinarySDNode>();
2486 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2489 AllNodes.push_back(N);
2490 return SDOperand(N, 0);
2493 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2494 SDOperand N1, SDOperand N2, SDOperand N3) {
2495 // Perform various simplifications.
2496 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2497 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2500 // Use FoldSetCC to simplify SETCC's.
2501 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2502 if (Simp.Val) return Simp;
2507 if (N1C->getValue())
2508 return N2; // select true, X, Y -> X
2510 return N3; // select false, X, Y -> Y
2513 if (N2 == N3) return N2; // select C, X, X -> X
2517 if (N2C->getValue()) // Unconditional branch
2518 return getNode(ISD::BR, MVT::Other, N1, N3);
2520 return N1; // Never-taken branch
2523 case ISD::VECTOR_SHUFFLE:
2524 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2525 VT.isVector() && N3.getValueType().isVector() &&
2526 N3.getOpcode() == ISD::BUILD_VECTOR &&
2527 VT.getVectorNumElements() == N3.getNumOperands() &&
2528 "Illegal VECTOR_SHUFFLE node!");
2530 case ISD::BIT_CONVERT:
2531 // Fold bit_convert nodes from a type to themselves.
2532 if (N1.getValueType() == VT)
2537 // Memoize node if it doesn't produce a flag.
2539 SDVTList VTs = getVTList(VT);
2540 if (VT != MVT::Flag) {
2541 SDOperand Ops[] = { N1, N2, N3 };
2542 FoldingSetNodeID ID;
2543 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2545 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2546 return SDOperand(E, 0);
2547 N = getAllocator().Allocate<TernarySDNode>();
2548 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2549 CSEMap.InsertNode(N, IP);
2551 N = getAllocator().Allocate<TernarySDNode>();
2552 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2554 AllNodes.push_back(N);
2555 return SDOperand(N, 0);
2558 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2559 SDOperand N1, SDOperand N2, SDOperand N3,
2561 SDOperand Ops[] = { N1, N2, N3, N4 };
2562 return getNode(Opcode, VT, Ops, 4);
2565 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2566 SDOperand N1, SDOperand N2, SDOperand N3,
2567 SDOperand N4, SDOperand N5) {
2568 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2569 return getNode(Opcode, VT, Ops, 5);
2572 /// getMemsetValue - Vectorized representation of the memset value
2574 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2575 unsigned NumBits = VT.isVector() ?
2576 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2577 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2578 APInt Val = APInt(NumBits, C->getValue() & 255);
2580 for (unsigned i = NumBits; i > 8; i >>= 1) {
2581 Val = (Val << Shift) | Val;
2585 return DAG.getConstant(Val, VT);
2586 return DAG.getConstantFP(APFloat(Val), VT);
2589 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2591 for (unsigned i = NumBits; i > 8; i >>= 1) {
2592 Value = DAG.getNode(ISD::OR, VT,
2593 DAG.getNode(ISD::SHL, VT, Value,
2594 DAG.getConstant(Shift, MVT::i8)), Value);
2601 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2602 /// used when a memcpy is turned into a memset when the source is a constant
2604 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2605 const TargetLowering &TLI,
2606 std::string &Str, unsigned Offset) {
2607 // Handle vector with all elements zero.
2610 return DAG.getConstant(0, VT);
2611 unsigned NumElts = VT.getVectorNumElements();
2612 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2613 return DAG.getNode(ISD::BIT_CONVERT, VT,
2614 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2617 assert(!VT.isVector() && "Can't handle vector type here!");
2618 unsigned NumBits = VT.getSizeInBits();
2619 unsigned MSB = NumBits / 8;
2621 if (TLI.isLittleEndian())
2622 Offset = Offset + MSB - 1;
2623 for (unsigned i = 0; i != MSB; ++i) {
2624 Val = (Val << 8) | (unsigned char)Str[Offset];
2625 Offset += TLI.isLittleEndian() ? -1 : 1;
2627 return DAG.getConstant(Val, VT);
2630 /// getMemBasePlusOffset - Returns base and offset node for the
2632 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2633 SelectionDAG &DAG) {
2634 MVT VT = Base.getValueType();
2635 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2638 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2640 static bool isMemSrcFromString(SDOperand Src, std::string &Str) {
2641 unsigned SrcDelta = 0;
2642 GlobalAddressSDNode *G = NULL;
2643 if (Src.getOpcode() == ISD::GlobalAddress)
2644 G = cast<GlobalAddressSDNode>(Src);
2645 else if (Src.getOpcode() == ISD::ADD &&
2646 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2647 Src.getOperand(1).getOpcode() == ISD::Constant) {
2648 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2649 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2654 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2655 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2661 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2662 /// to replace the memset / memcpy is below the threshold. It also returns the
2663 /// types of the sequence of memory ops to perform memset / memcpy.
2665 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2666 SDOperand Dst, SDOperand Src,
2667 unsigned Limit, uint64_t Size, unsigned &Align,
2668 std::string &Str, bool &isSrcStr,
2670 const TargetLowering &TLI) {
2671 isSrcStr = isMemSrcFromString(Src, Str);
2672 bool isSrcConst = isa<ConstantSDNode>(Src);
2673 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2674 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2675 if (VT != MVT::iAny) {
2676 unsigned NewAlign = (unsigned)
2677 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2678 // If source is a string constant, this will require an unaligned load.
2679 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2680 if (Dst.getOpcode() != ISD::FrameIndex) {
2681 // Can't change destination alignment. It requires a unaligned store.
2685 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2686 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2687 if (MFI->isFixedObjectIndex(FI)) {
2688 // Can't change destination alignment. It requires a unaligned store.
2692 // Give the stack frame object a larger alignment if needed.
2693 if (MFI->getObjectAlignment(FI) < NewAlign)
2694 MFI->setObjectAlignment(FI, NewAlign);
2701 if (VT == MVT::iAny) {
2705 switch (Align & 7) {
2706 case 0: VT = MVT::i64; break;
2707 case 4: VT = MVT::i32; break;
2708 case 2: VT = MVT::i16; break;
2709 default: VT = MVT::i8; break;
2714 while (!TLI.isTypeLegal(LVT))
2715 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2716 assert(LVT.isInteger());
2722 unsigned NumMemOps = 0;
2724 unsigned VTSize = VT.getSizeInBits() / 8;
2725 while (VTSize > Size) {
2726 // For now, only use non-vector load / store's for the left-over pieces.
2727 if (VT.isVector()) {
2729 while (!TLI.isTypeLegal(VT))
2730 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2731 VTSize = VT.getSizeInBits() / 8;
2733 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2738 if (++NumMemOps > Limit)
2740 MemOps.push_back(VT);
2747 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2748 SDOperand Chain, SDOperand Dst,
2749 SDOperand Src, uint64_t Size,
2750 unsigned Align, bool AlwaysInline,
2751 const Value *DstSV, uint64_t DstSVOff,
2752 const Value *SrcSV, uint64_t SrcSVOff){
2753 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2755 // Expand memcpy to a series of load and store ops if the size operand falls
2756 // below a certain threshold.
2757 std::vector<MVT> MemOps;
2758 uint64_t Limit = -1;
2760 Limit = TLI.getMaxStoresPerMemcpy();
2761 unsigned DstAlign = Align; // Destination alignment can change.
2764 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2765 Str, CopyFromStr, DAG, TLI))
2769 bool isZeroStr = CopyFromStr && Str.empty();
2770 SmallVector<SDOperand, 8> OutChains;
2771 unsigned NumMemOps = MemOps.size();
2772 uint64_t SrcOff = 0, DstOff = 0;
2773 for (unsigned i = 0; i < NumMemOps; i++) {
2775 unsigned VTSize = VT.getSizeInBits() / 8;
2776 SDOperand Value, Store;
2778 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2779 // It's unlikely a store of a vector immediate can be done in a single
2780 // instruction. It would require a load from a constantpool first.
2781 // We also handle store a vector with all zero's.
2782 // FIXME: Handle other cases where store of vector immediate is done in
2783 // a single instruction.
2784 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2785 Store = DAG.getStore(Chain, Value,
2786 getMemBasePlusOffset(Dst, DstOff, DAG),
2787 DstSV, DstSVOff + DstOff);
2789 Value = DAG.getLoad(VT, Chain,
2790 getMemBasePlusOffset(Src, SrcOff, DAG),
2791 SrcSV, SrcSVOff + SrcOff, false, Align);
2792 Store = DAG.getStore(Chain, Value,
2793 getMemBasePlusOffset(Dst, DstOff, DAG),
2794 DstSV, DstSVOff + DstOff, false, DstAlign);
2796 OutChains.push_back(Store);
2801 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2802 &OutChains[0], OutChains.size());
2805 static SDOperand getMemmoveLoadsAndStores(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 memmove 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.getMaxStoresPerMemmove();
2819 unsigned DstAlign = Align; // Destination alignment can change.
2822 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2823 Str, CopyFromStr, DAG, TLI))
2826 uint64_t SrcOff = 0, DstOff = 0;
2828 SmallVector<SDOperand, 8> LoadValues;
2829 SmallVector<SDOperand, 8> LoadChains;
2830 SmallVector<SDOperand, 8> OutChains;
2831 unsigned NumMemOps = MemOps.size();
2832 for (unsigned i = 0; i < NumMemOps; i++) {
2834 unsigned VTSize = VT.getSizeInBits() / 8;
2835 SDOperand Value, Store;
2837 Value = DAG.getLoad(VT, Chain,
2838 getMemBasePlusOffset(Src, SrcOff, DAG),
2839 SrcSV, SrcSVOff + SrcOff, false, Align);
2840 LoadValues.push_back(Value);
2841 LoadChains.push_back(Value.getValue(1));
2844 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2845 &LoadChains[0], LoadChains.size());
2847 for (unsigned i = 0; i < NumMemOps; i++) {
2849 unsigned VTSize = VT.getSizeInBits() / 8;
2850 SDOperand Value, Store;
2852 Store = DAG.getStore(Chain, LoadValues[i],
2853 getMemBasePlusOffset(Dst, DstOff, DAG),
2854 DstSV, DstSVOff + DstOff, false, DstAlign);
2855 OutChains.push_back(Store);
2859 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2860 &OutChains[0], OutChains.size());
2863 static SDOperand getMemsetStores(SelectionDAG &DAG,
2864 SDOperand Chain, SDOperand Dst,
2865 SDOperand Src, uint64_t Size,
2867 const Value *DstSV, uint64_t DstSVOff) {
2868 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2870 // Expand memset to a series of load/store ops if the size operand
2871 // falls below a certain threshold.
2872 std::vector<MVT> MemOps;
2875 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2876 Size, Align, Str, CopyFromStr, DAG, TLI))
2879 SmallVector<SDOperand, 8> OutChains;
2880 uint64_t DstOff = 0;
2882 unsigned NumMemOps = MemOps.size();
2883 for (unsigned i = 0; i < NumMemOps; i++) {
2885 unsigned VTSize = VT.getSizeInBits() / 8;
2886 SDOperand Value = getMemsetValue(Src, VT, DAG);
2887 SDOperand Store = DAG.getStore(Chain, Value,
2888 getMemBasePlusOffset(Dst, DstOff, DAG),
2889 DstSV, DstSVOff + DstOff);
2890 OutChains.push_back(Store);
2894 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2895 &OutChains[0], OutChains.size());
2898 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2899 SDOperand Src, SDOperand Size,
2900 unsigned Align, bool AlwaysInline,
2901 const Value *DstSV, uint64_t DstSVOff,
2902 const Value *SrcSV, uint64_t SrcSVOff) {
2904 // Check to see if we should lower the memcpy to loads and stores first.
2905 // For cases within the target-specified limits, this is the best choice.
2906 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2908 // Memcpy with size zero? Just return the original chain.
2909 if (ConstantSize->isNullValue())
2913 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2914 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2919 // Then check to see if we should lower the memcpy with target-specific
2920 // code. If the target chooses to do this, this is the next best.
2922 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2924 DstSV, DstSVOff, SrcSV, SrcSVOff);
2928 // If we really need inline code and the target declined to provide it,
2929 // use a (potentially long) sequence of loads and stores.
2931 assert(ConstantSize && "AlwaysInline requires a constant size!");
2932 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2933 ConstantSize->getValue(), Align, true,
2934 DstSV, DstSVOff, SrcSV, SrcSVOff);
2937 // Emit a library call.
2938 TargetLowering::ArgListTy Args;
2939 TargetLowering::ArgListEntry Entry;
2940 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2941 Entry.Node = Dst; Args.push_back(Entry);
2942 Entry.Node = Src; Args.push_back(Entry);
2943 Entry.Node = Size; Args.push_back(Entry);
2944 std::pair<SDOperand,SDOperand> CallResult =
2945 TLI.LowerCallTo(Chain, Type::VoidTy,
2946 false, false, false, CallingConv::C, false,
2947 getExternalSymbol("memcpy", TLI.getPointerTy()),
2949 return CallResult.second;
2952 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2953 SDOperand Src, SDOperand Size,
2955 const Value *DstSV, uint64_t DstSVOff,
2956 const Value *SrcSV, uint64_t SrcSVOff) {
2958 // Check to see if we should lower the memmove to loads and stores first.
2959 // For cases within the target-specified limits, this is the best choice.
2960 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2962 // Memmove with size zero? Just return the original chain.
2963 if (ConstantSize->isNullValue())
2967 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2968 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2973 // Then check to see if we should lower the memmove with target-specific
2974 // code. If the target chooses to do this, this is the next best.
2976 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2977 DstSV, DstSVOff, SrcSV, SrcSVOff);
2981 // Emit a library call.
2982 TargetLowering::ArgListTy Args;
2983 TargetLowering::ArgListEntry Entry;
2984 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2985 Entry.Node = Dst; Args.push_back(Entry);
2986 Entry.Node = Src; Args.push_back(Entry);
2987 Entry.Node = Size; Args.push_back(Entry);
2988 std::pair<SDOperand,SDOperand> CallResult =
2989 TLI.LowerCallTo(Chain, Type::VoidTy,
2990 false, false, false, CallingConv::C, false,
2991 getExternalSymbol("memmove", TLI.getPointerTy()),
2993 return CallResult.second;
2996 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2997 SDOperand Src, SDOperand Size,
2999 const Value *DstSV, uint64_t DstSVOff) {
3001 // Check to see if we should lower the memset to stores first.
3002 // For cases within the target-specified limits, this is the best choice.
3003 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3005 // Memset with size zero? Just return the original chain.
3006 if (ConstantSize->isNullValue())
3010 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3016 // Then check to see if we should lower the memset with target-specific
3017 // code. If the target chooses to do this, this is the next best.
3019 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3024 // Emit a library call.
3025 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3026 TargetLowering::ArgListTy Args;
3027 TargetLowering::ArgListEntry Entry;
3028 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3029 Args.push_back(Entry);
3030 // Extend or truncate the argument to be an i32 value for the call.
3031 if (Src.getValueType().bitsGT(MVT::i32))
3032 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3034 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3035 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3036 Args.push_back(Entry);
3037 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3038 Args.push_back(Entry);
3039 std::pair<SDOperand,SDOperand> CallResult =
3040 TLI.LowerCallTo(Chain, Type::VoidTy,
3041 false, false, false, CallingConv::C, false,
3042 getExternalSymbol("memset", TLI.getPointerTy()),
3044 return CallResult.second;
3047 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3048 SDOperand Ptr, SDOperand Cmp,
3049 SDOperand Swp, const Value* PtrVal,
3050 unsigned Alignment) {
3051 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3052 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3053 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
3054 FoldingSetNodeID ID;
3055 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
3056 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3058 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3059 return SDOperand(E, 0);
3060 SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3061 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3062 CSEMap.InsertNode(N, IP);
3063 AllNodes.push_back(N);
3064 return SDOperand(N, 0);
3067 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
3068 SDOperand Ptr, SDOperand Val,
3069 const Value* PtrVal,
3070 unsigned Alignment) {
3071 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3072 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3073 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3074 || Opcode == ISD::ATOMIC_LOAD_NAND
3075 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3076 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3077 && "Invalid Atomic Op");
3078 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3079 FoldingSetNodeID ID;
3080 SDOperand Ops[] = {Chain, Ptr, Val};
3081 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3083 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3084 return SDOperand(E, 0);
3085 SDNode* N = getAllocator().Allocate<AtomicSDNode>();
3086 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
3087 CSEMap.InsertNode(N, IP);
3088 AllNodes.push_back(N);
3089 return SDOperand(N, 0);
3092 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3093 /// Allowed to return something different (and simpler) if Simplify is true.
3094 SDOperand SelectionDAG::getMergeValues(const SDOperand *Ops, unsigned NumOps,
3096 if (Simplify && NumOps == 1)
3099 SmallVector<MVT, 4> VTs;
3100 VTs.reserve(NumOps);
3101 for (unsigned i = 0; i < NumOps; ++i)
3102 VTs.push_back(Ops[i].getValueType());
3103 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3107 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3108 MVT VT, SDOperand Chain,
3109 SDOperand Ptr, SDOperand Offset,
3110 const Value *SV, int SVOffset, MVT EVT,
3111 bool isVolatile, unsigned Alignment) {
3112 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3114 if (VT != MVT::iPTR) {
3115 Ty = VT.getTypeForMVT();
3117 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3118 assert(PT && "Value for load must be a pointer");
3119 Ty = PT->getElementType();
3121 assert(Ty && "Could not get type information for load");
3122 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3126 ExtType = ISD::NON_EXTLOAD;
3127 } else if (ExtType == ISD::NON_EXTLOAD) {
3128 assert(VT == EVT && "Non-extending load from different memory type!");
3132 assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3134 assert(EVT.bitsLT(VT) &&
3135 "Should only be an extending load, not truncating!");
3136 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3137 "Cannot sign/zero extend a FP/Vector load!");
3138 assert(VT.isInteger() == EVT.isInteger() &&
3139 "Cannot convert from FP to Int or Int -> FP!");
3142 bool Indexed = AM != ISD::UNINDEXED;
3143 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3144 "Unindexed load with an offset!");
3146 SDVTList VTs = Indexed ?
3147 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3148 SDOperand Ops[] = { Chain, Ptr, Offset };
3149 FoldingSetNodeID ID;
3150 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3152 ID.AddInteger(ExtType);
3153 ID.AddInteger(EVT.getRawBits());
3154 ID.AddInteger(Alignment);
3155 ID.AddInteger(isVolatile);
3157 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3158 return SDOperand(E, 0);
3159 SDNode *N = getAllocator().Allocate<LoadSDNode>();
3160 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3161 Alignment, isVolatile);
3162 CSEMap.InsertNode(N, IP);
3163 AllNodes.push_back(N);
3164 return SDOperand(N, 0);
3167 SDOperand SelectionDAG::getLoad(MVT VT,
3168 SDOperand Chain, SDOperand Ptr,
3169 const Value *SV, int SVOffset,
3170 bool isVolatile, unsigned Alignment) {
3171 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3172 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3173 SV, SVOffset, VT, isVolatile, Alignment);
3176 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3177 SDOperand Chain, SDOperand Ptr,
3179 int SVOffset, MVT EVT,
3180 bool isVolatile, unsigned Alignment) {
3181 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3182 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3183 SV, SVOffset, EVT, isVolatile, Alignment);
3187 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3188 SDOperand Offset, ISD::MemIndexedMode AM) {
3189 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3190 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3191 "Load is already a indexed load!");
3192 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3193 LD->getChain(), Base, Offset, LD->getSrcValue(),
3194 LD->getSrcValueOffset(), LD->getMemoryVT(),
3195 LD->isVolatile(), LD->getAlignment());
3198 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3199 SDOperand Ptr, const Value *SV, int SVOffset,
3200 bool isVolatile, unsigned Alignment) {
3201 MVT VT = Val.getValueType();
3203 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3205 if (VT != MVT::iPTR) {
3206 Ty = VT.getTypeForMVT();
3208 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3209 assert(PT && "Value for store must be a pointer");
3210 Ty = PT->getElementType();
3212 assert(Ty && "Could not get type information for store");
3213 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3215 SDVTList VTs = getVTList(MVT::Other);
3216 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3217 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3218 FoldingSetNodeID ID;
3219 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3220 ID.AddInteger(ISD::UNINDEXED);
3221 ID.AddInteger(false);
3222 ID.AddInteger(VT.getRawBits());
3223 ID.AddInteger(Alignment);
3224 ID.AddInteger(isVolatile);
3226 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3227 return SDOperand(E, 0);
3228 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3229 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3230 VT, SV, SVOffset, Alignment, isVolatile);
3231 CSEMap.InsertNode(N, IP);
3232 AllNodes.push_back(N);
3233 return SDOperand(N, 0);
3236 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3237 SDOperand Ptr, const Value *SV,
3238 int SVOffset, MVT SVT,
3239 bool isVolatile, unsigned Alignment) {
3240 MVT VT = Val.getValueType();
3243 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3245 assert(VT.bitsGT(SVT) && "Not a truncation?");
3246 assert(VT.isInteger() == SVT.isInteger() &&
3247 "Can't do FP-INT conversion!");
3249 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3251 if (VT != MVT::iPTR) {
3252 Ty = VT.getTypeForMVT();
3254 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3255 assert(PT && "Value for store must be a pointer");
3256 Ty = PT->getElementType();
3258 assert(Ty && "Could not get type information for store");
3259 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3261 SDVTList VTs = getVTList(MVT::Other);
3262 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3263 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3264 FoldingSetNodeID ID;
3265 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3266 ID.AddInteger(ISD::UNINDEXED);
3268 ID.AddInteger(SVT.getRawBits());
3269 ID.AddInteger(Alignment);
3270 ID.AddInteger(isVolatile);
3272 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3273 return SDOperand(E, 0);
3274 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3275 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3276 SVT, SV, SVOffset, Alignment, isVolatile);
3277 CSEMap.InsertNode(N, IP);
3278 AllNodes.push_back(N);
3279 return SDOperand(N, 0);
3283 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3284 SDOperand Offset, ISD::MemIndexedMode AM) {
3285 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3286 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3287 "Store is already a indexed store!");
3288 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3289 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3290 FoldingSetNodeID ID;
3291 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3293 ID.AddInteger(ST->isTruncatingStore());
3294 ID.AddInteger(ST->getMemoryVT().getRawBits());
3295 ID.AddInteger(ST->getAlignment());
3296 ID.AddInteger(ST->isVolatile());
3298 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3299 return SDOperand(E, 0);
3300 SDNode *N = getAllocator().Allocate<StoreSDNode>();
3301 new (N) StoreSDNode(Ops, VTs, AM,
3302 ST->isTruncatingStore(), ST->getMemoryVT(),
3303 ST->getSrcValue(), ST->getSrcValueOffset(),
3304 ST->getAlignment(), ST->isVolatile());
3305 CSEMap.InsertNode(N, IP);
3306 AllNodes.push_back(N);
3307 return SDOperand(N, 0);
3310 SDOperand SelectionDAG::getVAArg(MVT VT,
3311 SDOperand Chain, SDOperand Ptr,
3313 SDOperand Ops[] = { Chain, Ptr, SV };
3314 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3317 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3318 const SDUse *Ops, unsigned NumOps) {
3320 case 0: return getNode(Opcode, VT);
3321 case 1: return getNode(Opcode, VT, Ops[0].getSDOperand());
3322 case 2: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3323 Ops[1].getSDOperand());
3324 case 3: return getNode(Opcode, VT, Ops[0].getSDOperand(),
3325 Ops[1].getSDOperand(), Ops[2].getSDOperand());
3329 // Copy from an SDUse array into an SDOperand array for use with
3330 // the regular getNode logic.
3331 SmallVector<SDOperand, 8> NewOps;
3332 NewOps.reserve(NumOps);
3333 for (unsigned i = 0; i != NumOps; ++i)
3334 NewOps.push_back(Ops[i].getSDOperand());
3335 return getNode(Opcode, VT, Ops, NumOps);
3338 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3339 const SDOperand *Ops, unsigned NumOps) {
3341 case 0: return getNode(Opcode, VT);
3342 case 1: return getNode(Opcode, VT, Ops[0]);
3343 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3344 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3350 case ISD::SELECT_CC: {
3351 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3352 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3353 "LHS and RHS of condition must have same type!");
3354 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3355 "True and False arms of SelectCC must have same type!");
3356 assert(Ops[2].getValueType() == VT &&
3357 "select_cc node must be of same type as true and false value!");
3361 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3362 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3363 "LHS/RHS of comparison should match types!");
3370 SDVTList VTs = getVTList(VT);
3371 if (VT != MVT::Flag) {
3372 FoldingSetNodeID ID;
3373 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3375 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3376 return SDOperand(E, 0);
3377 N = getAllocator().Allocate<SDNode>();
3378 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3379 CSEMap.InsertNode(N, IP);
3381 N = getAllocator().Allocate<SDNode>();
3382 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3384 AllNodes.push_back(N);
3385 return SDOperand(N, 0);
3388 SDOperand SelectionDAG::getNode(unsigned Opcode,
3389 std::vector<MVT> &ResultTys,
3390 const SDOperand *Ops, unsigned NumOps) {
3391 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3395 SDOperand SelectionDAG::getNode(unsigned Opcode,
3396 const MVT *VTs, unsigned NumVTs,
3397 const SDOperand *Ops, unsigned NumOps) {
3399 return getNode(Opcode, VTs[0], Ops, NumOps);
3400 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3403 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3404 const SDOperand *Ops, unsigned NumOps) {
3405 if (VTList.NumVTs == 1)
3406 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3409 // FIXME: figure out how to safely handle things like
3410 // int foo(int x) { return 1 << (x & 255); }
3411 // int bar() { return foo(256); }
3413 case ISD::SRA_PARTS:
3414 case ISD::SRL_PARTS:
3415 case ISD::SHL_PARTS:
3416 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3417 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3418 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3419 else if (N3.getOpcode() == ISD::AND)
3420 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3421 // If the and is only masking out bits that cannot effect the shift,
3422 // eliminate the and.
3423 unsigned NumBits = VT.getSizeInBits()*2;
3424 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3425 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3431 // Memoize the node unless it returns a flag.
3433 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3434 FoldingSetNodeID ID;
3435 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3437 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3438 return SDOperand(E, 0);
3440 N = getAllocator().Allocate<UnarySDNode>();
3441 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3442 } else if (NumOps == 2) {
3443 N = getAllocator().Allocate<BinarySDNode>();
3444 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3445 } else if (NumOps == 3) {
3446 N = getAllocator().Allocate<TernarySDNode>();
3447 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3449 N = getAllocator().Allocate<SDNode>();
3450 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3452 CSEMap.InsertNode(N, IP);
3455 N = getAllocator().Allocate<UnarySDNode>();
3456 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3457 } else if (NumOps == 2) {
3458 N = getAllocator().Allocate<BinarySDNode>();
3459 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3460 } else if (NumOps == 3) {
3461 N = getAllocator().Allocate<TernarySDNode>();
3462 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3464 N = getAllocator().Allocate<SDNode>();
3465 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3468 AllNodes.push_back(N);
3469 return SDOperand(N, 0);
3472 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3473 return getNode(Opcode, VTList, 0, 0);
3476 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3478 SDOperand Ops[] = { N1 };
3479 return getNode(Opcode, VTList, Ops, 1);
3482 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3483 SDOperand N1, SDOperand N2) {
3484 SDOperand Ops[] = { N1, N2 };
3485 return getNode(Opcode, VTList, Ops, 2);
3488 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3489 SDOperand N1, SDOperand N2, SDOperand N3) {
3490 SDOperand Ops[] = { N1, N2, N3 };
3491 return getNode(Opcode, VTList, Ops, 3);
3494 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3495 SDOperand N1, SDOperand N2, SDOperand N3,
3497 SDOperand Ops[] = { N1, N2, N3, N4 };
3498 return getNode(Opcode, VTList, Ops, 4);
3501 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3502 SDOperand N1, SDOperand N2, SDOperand N3,
3503 SDOperand N4, SDOperand N5) {
3504 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3505 return getNode(Opcode, VTList, Ops, 5);
3508 SDVTList SelectionDAG::getVTList(MVT VT) {
3509 return makeVTList(SDNode::getValueTypeList(VT), 1);
3512 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3513 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3514 E = VTList.end(); I != E; ++I) {
3515 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3516 return makeVTList(&(*I)[0], 2);
3521 VTList.push_front(V);
3522 return makeVTList(&(*VTList.begin())[0], 2);
3524 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3526 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3527 E = VTList.end(); I != E; ++I) {
3528 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3530 return makeVTList(&(*I)[0], 3);
3536 VTList.push_front(V);
3537 return makeVTList(&(*VTList.begin())[0], 3);
3540 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3542 case 0: assert(0 && "Cannot have nodes without results!");
3543 case 1: return getVTList(VTs[0]);
3544 case 2: return getVTList(VTs[0], VTs[1]);
3545 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3549 for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3550 E = VTList.end(); I != E; ++I) {
3551 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3553 bool NoMatch = false;
3554 for (unsigned i = 2; i != NumVTs; ++i)
3555 if (VTs[i] != (*I)[i]) {
3560 return makeVTList(&*I->begin(), NumVTs);
3563 VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3564 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3568 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3569 /// specified operands. If the resultant node already exists in the DAG,
3570 /// this does not modify the specified node, instead it returns the node that
3571 /// already exists. If the resultant node does not exist in the DAG, the
3572 /// input node is returned. As a degenerate case, if you specify the same
3573 /// input operands as the node already has, the input node is returned.
3574 SDOperand SelectionDAG::
3575 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3576 SDNode *N = InN.Val;
3577 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3579 // Check to see if there is no change.
3580 if (Op == N->getOperand(0)) return InN;
3582 // See if the modified node already exists.
3583 void *InsertPos = 0;
3584 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3585 return SDOperand(Existing, InN.ResNo);
3587 // Nope it doesn't. Remove the node from it's current place in the maps.
3589 RemoveNodeFromCSEMaps(N);
3591 // Now we update the operands.
3592 N->OperandList[0].getVal()->removeUser(0, N);
3593 N->OperandList[0] = Op;
3594 N->OperandList[0].setUser(N);
3595 Op.Val->addUser(0, N);
3597 // If this gets put into a CSE map, add it.
3598 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3602 SDOperand SelectionDAG::
3603 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3604 SDNode *N = InN.Val;
3605 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3607 // Check to see if there is no change.
3608 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3609 return InN; // No operands changed, just return the input node.
3611 // See if the modified node already exists.
3612 void *InsertPos = 0;
3613 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3614 return SDOperand(Existing, InN.ResNo);
3616 // Nope it doesn't. Remove the node from it's current place in the maps.
3618 RemoveNodeFromCSEMaps(N);
3620 // Now we update the operands.
3621 if (N->OperandList[0] != Op1) {
3622 N->OperandList[0].getVal()->removeUser(0, N);
3623 N->OperandList[0] = Op1;
3624 N->OperandList[0].setUser(N);
3625 Op1.Val->addUser(0, N);
3627 if (N->OperandList[1] != Op2) {
3628 N->OperandList[1].getVal()->removeUser(1, N);
3629 N->OperandList[1] = Op2;
3630 N->OperandList[1].setUser(N);
3631 Op2.Val->addUser(1, N);
3634 // If this gets put into a CSE map, add it.
3635 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3639 SDOperand SelectionDAG::
3640 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3641 SDOperand Ops[] = { Op1, Op2, Op3 };
3642 return UpdateNodeOperands(N, Ops, 3);
3645 SDOperand SelectionDAG::
3646 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3647 SDOperand Op3, SDOperand Op4) {
3648 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3649 return UpdateNodeOperands(N, Ops, 4);
3652 SDOperand SelectionDAG::
3653 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3654 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3655 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3656 return UpdateNodeOperands(N, Ops, 5);
3659 SDOperand SelectionDAG::
3660 UpdateNodeOperands(SDOperand InN, const SDOperand *Ops, unsigned NumOps) {
3661 SDNode *N = InN.Val;
3662 assert(N->getNumOperands() == NumOps &&
3663 "Update with wrong number of operands");
3665 // Check to see if there is no change.
3666 bool AnyChange = false;
3667 for (unsigned i = 0; i != NumOps; ++i) {
3668 if (Ops[i] != N->getOperand(i)) {
3674 // No operands changed, just return the input node.
3675 if (!AnyChange) return InN;
3677 // See if the modified node already exists.
3678 void *InsertPos = 0;
3679 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3680 return SDOperand(Existing, InN.ResNo);
3682 // Nope it doesn't. Remove the node from its current place in the maps.
3684 RemoveNodeFromCSEMaps(N);
3686 // Now we update the operands.
3687 for (unsigned i = 0; i != NumOps; ++i) {
3688 if (N->OperandList[i] != Ops[i]) {
3689 N->OperandList[i].getVal()->removeUser(i, N);
3690 N->OperandList[i] = Ops[i];
3691 N->OperandList[i].setUser(N);
3692 Ops[i].Val->addUser(i, N);
3696 // If this gets put into a CSE map, add it.
3697 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3701 /// MorphNodeTo - This frees the operands of the current node, resets the
3702 /// opcode, types, and operands to the specified value. This should only be
3703 /// used by the SelectionDAG class.
3704 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3705 const SDOperand *Ops, unsigned NumOps,
3706 SmallVectorImpl<SDNode *> &DeadNodes) {
3709 NumValues = L.NumVTs;
3711 // Clear the operands list, updating used nodes to remove this from their
3712 // use list. Keep track of any operands that become dead as a result.
3713 SmallPtrSet<SDNode*, 16> DeadNodeSet;
3714 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I) {
3715 SDNode *N = I->getVal();
3716 N->removeUser(std::distance(op_begin(), I), this);
3718 DeadNodeSet.insert(N);
3721 // If NumOps is larger than the # of operands we currently have, reallocate
3722 // the operand list.
3723 if (NumOps > NumOperands) {
3724 if (OperandsNeedDelete) {
3725 delete [] OperandList;
3727 OperandList = new SDUse[NumOps];
3728 OperandsNeedDelete = true;
3731 // Assign the new operands.
3732 NumOperands = NumOps;
3734 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3735 OperandList[i] = Ops[i];
3736 OperandList[i].setUser(this);
3737 SDNode *N = OperandList[i].getVal();
3738 N->addUser(i, this);
3740 DeadNodeSet.erase(N);
3743 // Clean up any nodes that are still dead after adding the uses for the
3745 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
3746 E = DeadNodeSet.end(); I != E; ++I)
3747 DeadNodes.push_back(*I);
3750 /// DropOperands - Release the operands and set this node to have
3751 /// zero operands. This should only be used by HandleSDNode to clear
3752 /// its operand list.
3753 void SDNode::DropOperands() {
3754 assert(NodeType == ISD::HANDLENODE &&
3755 "DropOperands is for HANDLENODE only!");
3757 // Unlike the code in MorphNodeTo that does this, we don't need to
3758 // watch for dead nodes here.
3759 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3760 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3765 /// SelectNodeTo - These are used for target selectors to *mutate* the
3766 /// specified node to have the specified return type, Target opcode, and
3767 /// operands. Note that target opcodes are stored as
3768 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3770 /// Note that SelectNodeTo returns the resultant node. If there is already a
3771 /// node of the specified opcode and operands, it returns that node instead of
3772 /// the current one.
3773 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3775 SDVTList VTs = getVTList(VT);
3776 return SelectNodeTo(N, TargetOpc, VTs, 0, 0);
3779 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3780 MVT VT, SDOperand Op1) {
3781 SDVTList VTs = getVTList(VT);
3782 SDOperand Ops[] = { Op1 };
3783 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3786 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3787 MVT VT, SDOperand Op1,
3789 SDVTList VTs = getVTList(VT);
3790 SDOperand Ops[] = { Op1, Op2 };
3791 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3794 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3795 MVT VT, SDOperand Op1,
3796 SDOperand Op2, SDOperand Op3) {
3797 SDVTList VTs = getVTList(VT);
3798 SDOperand Ops[] = { Op1, Op2, Op3 };
3799 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3802 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3803 MVT VT, const SDOperand *Ops,
3805 SDVTList VTs = getVTList(VT);
3806 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3809 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3810 MVT VT1, MVT VT2, const SDOperand *Ops,
3812 SDVTList VTs = getVTList(VT1, VT2);
3813 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3816 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3818 SDVTList VTs = getVTList(VT1, VT2);
3819 return SelectNodeTo(N, TargetOpc, VTs, (SDOperand *)0, 0);
3822 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3823 MVT VT1, MVT VT2, MVT VT3,
3824 const SDOperand *Ops, unsigned NumOps) {
3825 SDVTList VTs = getVTList(VT1, VT2, VT3);
3826 return SelectNodeTo(N, TargetOpc, VTs, Ops, NumOps);
3829 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3832 SDVTList VTs = getVTList(VT1, VT2);
3833 SDOperand Ops[] = { Op1 };
3834 return SelectNodeTo(N, TargetOpc, VTs, Ops, 1);
3837 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3839 SDOperand Op1, SDOperand Op2) {
3840 SDVTList VTs = getVTList(VT1, VT2);
3841 SDOperand Ops[] = { Op1, Op2 };
3842 return SelectNodeTo(N, TargetOpc, VTs, Ops, 2);
3845 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3847 SDOperand Op1, SDOperand Op2,
3849 SDVTList VTs = getVTList(VT1, VT2);
3850 SDOperand Ops[] = { Op1, Op2, Op3 };
3851 return SelectNodeTo(N, TargetOpc, VTs, Ops, 3);
3854 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3855 SDVTList VTs, const SDOperand *Ops,
3857 // If an identical node already exists, use it.
3858 FoldingSetNodeID ID;
3859 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3861 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3864 RemoveNodeFromCSEMaps(N);
3866 SmallVector<SDNode *, 16> DeadNodes;
3867 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps, DeadNodes);
3868 RemoveDeadNodes(DeadNodes);
3870 CSEMap.InsertNode(N, IP); // Memoize the new node.
3875 /// getTargetNode - These are used for target selectors to create a new node
3876 /// with specified return type(s), target opcode, and operands.
3878 /// Note that getTargetNode returns the resultant node. If there is already a
3879 /// node of the specified opcode and operands, it returns that node instead of
3880 /// the current one.
3881 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3882 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3884 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3885 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3887 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3888 SDOperand Op1, SDOperand Op2) {
3889 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3891 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3892 SDOperand Op1, SDOperand Op2,
3894 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3896 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3897 const SDOperand *Ops, unsigned NumOps) {
3898 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3900 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3901 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3903 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3905 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3906 MVT VT2, SDOperand Op1) {
3907 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3908 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3910 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3911 MVT VT2, SDOperand Op1,
3913 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3914 SDOperand Ops[] = { Op1, Op2 };
3915 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3917 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3918 MVT VT2, SDOperand Op1,
3919 SDOperand Op2, SDOperand Op3) {
3920 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3921 SDOperand Ops[] = { Op1, Op2, Op3 };
3922 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3924 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3925 const SDOperand *Ops, unsigned NumOps) {
3926 const MVT *VTs = getNodeValueTypes(VT1, VT2);
3927 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3929 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3930 SDOperand Op1, SDOperand Op2) {
3931 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3932 SDOperand Ops[] = { Op1, Op2 };
3933 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3935 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3936 SDOperand Op1, SDOperand Op2,
3938 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3939 SDOperand Ops[] = { Op1, Op2, Op3 };
3940 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3942 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3943 const SDOperand *Ops, unsigned NumOps) {
3944 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3945 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3947 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3948 MVT VT2, MVT VT3, MVT VT4,
3949 const SDOperand *Ops, unsigned NumOps) {
3950 std::vector<MVT> VTList;
3951 VTList.push_back(VT1);
3952 VTList.push_back(VT2);
3953 VTList.push_back(VT3);
3954 VTList.push_back(VT4);
3955 const MVT *VTs = getNodeValueTypes(VTList);
3956 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3958 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3959 std::vector<MVT> &ResultTys,
3960 const SDOperand *Ops, unsigned NumOps) {
3961 const MVT *VTs = getNodeValueTypes(ResultTys);
3962 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3966 /// getNodeIfExists - Get the specified node if it's already available, or
3967 /// else return NULL.
3968 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3969 const SDOperand *Ops, unsigned NumOps) {
3970 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3971 FoldingSetNodeID ID;
3972 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3974 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3981 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3982 /// This can cause recursive merging of nodes in the DAG.
3984 /// This version assumes From has a single result value.
3986 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3987 DAGUpdateListener *UpdateListener) {
3988 SDNode *From = FromN.Val;
3989 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3990 "Cannot replace with this method!");
3991 assert(From != To.Val && "Cannot replace uses of with self");
3993 while (!From->use_empty()) {
3994 SDNode::use_iterator UI = From->use_begin();
3995 SDNode *U = UI->getUser();
3997 // This node is about to morph, remove its old self from the CSE maps.
3998 RemoveNodeFromCSEMaps(U);
4000 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4001 I != E; ++I, ++operandNum)
4002 if (I->getVal() == From) {
4003 From->removeUser(operandNum, U);
4006 To.Val->addUser(operandNum, U);
4009 // Now that we have modified U, add it back to the CSE maps. If it already
4010 // exists there, recursively merge the results together.
4011 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4012 ReplaceAllUsesWith(U, Existing, UpdateListener);
4013 // U is now dead. Inform the listener if it exists and delete it.
4015 UpdateListener->NodeDeleted(U, Existing);
4016 DeleteNodeNotInCSEMaps(U);
4018 // If the node doesn't already exist, we updated it. Inform a listener if
4021 UpdateListener->NodeUpdated(U);
4026 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4027 /// This can cause recursive merging of nodes in the DAG.
4029 /// This version assumes From/To have matching types and numbers of result
4032 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4033 DAGUpdateListener *UpdateListener) {
4034 assert(From != To && "Cannot replace uses of with self");
4035 assert(From->getNumValues() == To->getNumValues() &&
4036 "Cannot use this version of ReplaceAllUsesWith!");
4037 if (From->getNumValues() == 1) // If possible, use the faster version.
4038 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
4041 while (!From->use_empty()) {
4042 SDNode::use_iterator UI = From->use_begin();
4043 SDNode *U = UI->getUser();
4045 // This node is about to morph, remove its old self from the CSE maps.
4046 RemoveNodeFromCSEMaps(U);
4048 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4049 I != E; ++I, ++operandNum)
4050 if (I->getVal() == From) {
4051 From->removeUser(operandNum, U);
4053 To->addUser(operandNum, U);
4056 // Now that we have modified U, add it back to the CSE maps. If it already
4057 // exists there, recursively merge the results together.
4058 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4059 ReplaceAllUsesWith(U, Existing, UpdateListener);
4060 // U is now dead. Inform the listener if it exists and delete it.
4062 UpdateListener->NodeDeleted(U, Existing);
4063 DeleteNodeNotInCSEMaps(U);
4065 // If the node doesn't already exist, we updated it. Inform a listener if
4068 UpdateListener->NodeUpdated(U);
4073 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4074 /// This can cause recursive merging of nodes in the DAG.
4076 /// This version can replace From with any result values. To must match the
4077 /// number and types of values returned by From.
4078 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4079 const SDOperand *To,
4080 DAGUpdateListener *UpdateListener) {
4081 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4082 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
4084 while (!From->use_empty()) {
4085 SDNode::use_iterator UI = From->use_begin();
4086 SDNode *U = UI->getUser();
4088 // This node is about to morph, remove its old self from the CSE maps.
4089 RemoveNodeFromCSEMaps(U);
4091 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4092 I != E; ++I, ++operandNum)
4093 if (I->getVal() == From) {
4094 const SDOperand &ToOp = To[I->getSDOperand().ResNo];
4095 From->removeUser(operandNum, U);
4098 ToOp.Val->addUser(operandNum, U);
4101 // Now that we have modified U, add it back to the CSE maps. If it already
4102 // exists there, recursively merge the results together.
4103 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4104 ReplaceAllUsesWith(U, Existing, UpdateListener);
4105 // U is now dead. Inform the listener if it exists and delete it.
4107 UpdateListener->NodeDeleted(U, Existing);
4108 DeleteNodeNotInCSEMaps(U);
4110 // If the node doesn't already exist, we updated it. Inform a listener if
4113 UpdateListener->NodeUpdated(U);
4119 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
4120 /// any deleted nodes from the set passed into its constructor and recursively
4121 /// notifies another update listener if specified.
4122 class ChainedSetUpdaterListener :
4123 public SelectionDAG::DAGUpdateListener {
4124 SmallSetVector<SDNode*, 16> &Set;
4125 SelectionDAG::DAGUpdateListener *Chain;
4127 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4128 SelectionDAG::DAGUpdateListener *chain)
4129 : Set(set), Chain(chain) {}
4131 virtual void NodeDeleted(SDNode *N, SDNode *E) {
4133 if (Chain) Chain->NodeDeleted(N, E);
4135 virtual void NodeUpdated(SDNode *N) {
4136 if (Chain) Chain->NodeUpdated(N);
4141 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4142 /// uses of other values produced by From.Val alone. The Deleted vector is
4143 /// handled the same way as for ReplaceAllUsesWith.
4144 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4145 DAGUpdateListener *UpdateListener){
4146 assert(From != To && "Cannot replace a value with itself");
4148 // Handle the simple, trivial, case efficiently.
4149 if (From.Val->getNumValues() == 1) {
4150 ReplaceAllUsesWith(From, To, UpdateListener);
4154 if (From.use_empty()) return;
4156 // Get all of the users of From.Val. We want these in a nice,
4157 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4158 SmallSetVector<SDNode*, 16> Users;
4159 for (SDNode::use_iterator UI = From.Val->use_begin(),
4160 E = From.Val->use_end(); UI != E; ++UI) {
4161 SDNode *User = UI->getUser();
4165 // When one of the recursive merges deletes nodes from the graph, we need to
4166 // make sure that UpdateListener is notified *and* that the node is removed
4167 // from Users if present. CSUL does this.
4168 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4170 while (!Users.empty()) {
4171 // We know that this user uses some value of From. If it is the right
4172 // value, update it.
4173 SDNode *User = Users.back();
4176 // Scan for an operand that matches From.
4177 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4178 for (; Op != E; ++Op)
4179 if (*Op == From) break;
4181 // If there are no matches, the user must use some other result of From.
4182 if (Op == E) continue;
4184 // Okay, we know this user needs to be updated. Remove its old self
4185 // from the CSE maps.
4186 RemoveNodeFromCSEMaps(User);
4188 // Update all operands that match "From" in case there are multiple uses.
4189 for (; Op != E; ++Op) {
4191 From.Val->removeUser(Op-User->op_begin(), User);
4194 To.Val->addUser(Op-User->op_begin(), User);
4198 // Now that we have modified User, add it back to the CSE maps. If it
4199 // already exists there, recursively merge the results together.
4200 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4202 if (UpdateListener) UpdateListener->NodeUpdated(User);
4203 continue; // Continue on to next user.
4206 // If there was already an existing matching node, use ReplaceAllUsesWith
4207 // to replace the dead one with the existing one. This can cause
4208 // recursive merging of other unrelated nodes down the line. The merging
4209 // can cause deletion of nodes that used the old value. To handle this, we
4210 // use CSUL to remove them from the Users set.
4211 ReplaceAllUsesWith(User, Existing, &CSUL);
4213 // User is now dead. Notify a listener if present.
4214 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4215 DeleteNodeNotInCSEMaps(User);
4219 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4220 /// their allnodes order. It returns the maximum id.
4221 unsigned SelectionDAG::AssignNodeIds() {
4223 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4230 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4231 /// based on their topological order. It returns the maximum id and a vector
4232 /// of the SDNodes* in assigned order by reference.
4233 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4234 unsigned DAGSize = AllNodes.size();
4235 std::vector<unsigned> InDegree(DAGSize);
4236 std::vector<SDNode*> Sources;
4238 // Use a two pass approach to avoid using a std::map which is slow.
4240 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4243 unsigned Degree = N->use_size();
4244 InDegree[N->getNodeId()] = Degree;
4246 Sources.push_back(N);
4250 TopOrder.reserve(DAGSize);
4251 while (!Sources.empty()) {
4252 SDNode *N = Sources.back();
4254 TopOrder.push_back(N);
4255 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4256 SDNode *P = I->getVal();
4257 unsigned Degree = --InDegree[P->getNodeId()];
4259 Sources.push_back(P);
4263 // Second pass, assign the actual topological order as node ids.
4265 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4267 (*TI)->setNodeId(Id++);
4274 //===----------------------------------------------------------------------===//
4276 //===----------------------------------------------------------------------===//
4278 // Out-of-line virtual method to give class a home.
4279 void SDNode::ANCHOR() {}
4280 void UnarySDNode::ANCHOR() {}
4281 void BinarySDNode::ANCHOR() {}
4282 void TernarySDNode::ANCHOR() {}
4283 void HandleSDNode::ANCHOR() {}
4284 void ConstantSDNode::ANCHOR() {}
4285 void ConstantFPSDNode::ANCHOR() {}
4286 void GlobalAddressSDNode::ANCHOR() {}
4287 void FrameIndexSDNode::ANCHOR() {}
4288 void JumpTableSDNode::ANCHOR() {}
4289 void ConstantPoolSDNode::ANCHOR() {}
4290 void BasicBlockSDNode::ANCHOR() {}
4291 void SrcValueSDNode::ANCHOR() {}
4292 void MemOperandSDNode::ANCHOR() {}
4293 void RegisterSDNode::ANCHOR() {}
4294 void DbgStopPointSDNode::ANCHOR() {}
4295 void LabelSDNode::ANCHOR() {}
4296 void ExternalSymbolSDNode::ANCHOR() {}
4297 void CondCodeSDNode::ANCHOR() {}
4298 void ARG_FLAGSSDNode::ANCHOR() {}
4299 void VTSDNode::ANCHOR() {}
4300 void MemSDNode::ANCHOR() {}
4301 void LoadSDNode::ANCHOR() {}
4302 void StoreSDNode::ANCHOR() {}
4303 void AtomicSDNode::ANCHOR() {}
4305 HandleSDNode::~HandleSDNode() {
4309 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4311 : SDNode(isa<GlobalVariable>(GA) &&
4312 cast<GlobalVariable>(GA)->isThreadLocal() ?
4314 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4316 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4317 getSDVTList(VT)), Offset(o) {
4318 TheGlobal = const_cast<GlobalValue*>(GA);
4321 /// getMemOperand - Return a MachineMemOperand object describing the memory
4322 /// reference performed by this atomic.
4323 MachineMemOperand AtomicSDNode::getMemOperand() const {
4324 int Size = (getValueType(0).getSizeInBits() + 7) >> 3;
4325 int Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4326 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4328 // Check if the atomic references a frame index
4329 const FrameIndexSDNode *FI =
4330 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4331 if (!getSrcValue() && FI)
4332 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4333 FI->getIndex(), Size, getAlignment());
4335 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4336 Size, getAlignment());
4339 /// getMemOperand - Return a MachineMemOperand object describing the memory
4340 /// reference performed by this load or store.
4341 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4342 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4344 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4345 MachineMemOperand::MOStore;
4346 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4348 // Check if the load references a frame index, and does not have
4350 const FrameIndexSDNode *FI =
4351 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4352 if (!getSrcValue() && FI)
4353 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4354 FI->getIndex(), Size, getAlignment());
4356 return MachineMemOperand(getSrcValue(), Flags,
4357 getSrcValueOffset(), Size, getAlignment());
4360 /// Profile - Gather unique data for the node.
4362 void SDNode::Profile(FoldingSetNodeID &ID) {
4363 AddNodeIDNode(ID, this);
4366 /// getValueTypeList - Return a pointer to the specified value type.
4368 const MVT *SDNode::getValueTypeList(MVT VT) {
4369 if (VT.isExtended()) {
4370 static std::set<MVT, MVT::compareRawBits> EVTs;
4371 return &(*EVTs.insert(VT).first);
4373 static MVT VTs[MVT::LAST_VALUETYPE];
4374 VTs[VT.getSimpleVT()] = VT;
4375 return &VTs[VT.getSimpleVT()];
4379 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4380 /// indicated value. This method ignores uses of other values defined by this
4382 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4383 assert(Value < getNumValues() && "Bad value!");
4385 // If there is only one value, this is easy.
4386 if (getNumValues() == 1)
4387 return use_size() == NUses;
4388 if (use_size() < NUses) return false;
4390 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4392 SmallPtrSet<SDNode*, 32> UsersHandled;
4394 // TODO: Only iterate over uses of a given value of the node
4395 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4396 if (*UI == TheValue) {
4403 // Found exactly the right number of uses?
4408 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4409 /// value. This method ignores uses of other values defined by this operation.
4410 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4411 assert(Value < getNumValues() && "Bad value!");
4413 if (use_empty()) return false;
4415 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4417 SmallPtrSet<SDNode*, 32> UsersHandled;
4419 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4420 SDNode *User = UI->getUser();
4421 if (User->getNumOperands() == 1 ||
4422 UsersHandled.insert(User)) // First time we've seen this?
4423 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4424 if (User->getOperand(i) == TheValue) {
4433 /// isOnlyUseOf - Return true if this node is the only use of N.
4435 bool SDNode::isOnlyUseOf(SDNode *N) const {
4437 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4438 SDNode *User = I->getUser();
4448 /// isOperand - Return true if this node is an operand of N.
4450 bool SDOperand::isOperandOf(SDNode *N) const {
4451 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4452 if (*this == N->getOperand(i))
4457 bool SDNode::isOperandOf(SDNode *N) const {
4458 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4459 if (this == N->OperandList[i].getVal())
4464 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4465 /// be a chain) reaches the specified operand without crossing any
4466 /// side-effecting instructions. In practice, this looks through token
4467 /// factors and non-volatile loads. In order to remain efficient, this only
4468 /// looks a couple of nodes in, it does not do an exhaustive search.
4469 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
4470 unsigned Depth) const {
4471 if (*this == Dest) return true;
4473 // Don't search too deeply, we just want to be able to see through
4474 // TokenFactor's etc.
4475 if (Depth == 0) return false;
4477 // If this is a token factor, all inputs to the TF happen in parallel. If any
4478 // of the operands of the TF reach dest, then we can do the xform.
4479 if (getOpcode() == ISD::TokenFactor) {
4480 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4481 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4486 // Loads don't have side effects, look through them.
4487 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4488 if (!Ld->isVolatile())
4489 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4495 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4496 SmallPtrSet<SDNode *, 32> &Visited) {
4497 if (found || !Visited.insert(N))
4500 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4501 SDNode *Op = N->getOperand(i).Val;
4506 findPredecessor(Op, P, found, Visited);
4510 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4511 /// is either an operand of N or it can be reached by recursively traversing
4512 /// up the operands.
4513 /// NOTE: this is an expensive method. Use it carefully.
4514 bool SDNode::isPredecessorOf(SDNode *N) const {
4515 SmallPtrSet<SDNode *, 32> Visited;
4517 findPredecessor(N, this, found, Visited);
4521 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4522 assert(Num < NumOperands && "Invalid child # of SDNode!");
4523 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4526 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4527 switch (getOpcode()) {
4529 if (getOpcode() < ISD::BUILTIN_OP_END)
4530 return "<<Unknown DAG Node>>";
4533 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4534 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4535 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4537 TargetLowering &TLI = G->getTargetLoweringInfo();
4539 TLI.getTargetNodeName(getOpcode());
4540 if (Name) return Name;
4543 return "<<Unknown Target Node>>";
4546 case ISD::PREFETCH: return "Prefetch";
4547 case ISD::MEMBARRIER: return "MemBarrier";
4548 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4549 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4550 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4551 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4552 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4553 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4554 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4555 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4556 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4557 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4558 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4559 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4560 case ISD::PCMARKER: return "PCMarker";
4561 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4562 case ISD::SRCVALUE: return "SrcValue";
4563 case ISD::MEMOPERAND: return "MemOperand";
4564 case ISD::EntryToken: return "EntryToken";
4565 case ISD::TokenFactor: return "TokenFactor";
4566 case ISD::AssertSext: return "AssertSext";
4567 case ISD::AssertZext: return "AssertZext";
4569 case ISD::BasicBlock: return "BasicBlock";
4570 case ISD::ARG_FLAGS: return "ArgFlags";
4571 case ISD::VALUETYPE: return "ValueType";
4572 case ISD::Register: return "Register";
4574 case ISD::Constant: return "Constant";
4575 case ISD::ConstantFP: return "ConstantFP";
4576 case ISD::GlobalAddress: return "GlobalAddress";
4577 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4578 case ISD::FrameIndex: return "FrameIndex";
4579 case ISD::JumpTable: return "JumpTable";
4580 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4581 case ISD::RETURNADDR: return "RETURNADDR";
4582 case ISD::FRAMEADDR: return "FRAMEADDR";
4583 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4584 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4585 case ISD::EHSELECTION: return "EHSELECTION";
4586 case ISD::EH_RETURN: return "EH_RETURN";
4587 case ISD::ConstantPool: return "ConstantPool";
4588 case ISD::ExternalSymbol: return "ExternalSymbol";
4589 case ISD::INTRINSIC_WO_CHAIN: {
4590 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4591 return Intrinsic::getName((Intrinsic::ID)IID);
4593 case ISD::INTRINSIC_VOID:
4594 case ISD::INTRINSIC_W_CHAIN: {
4595 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4596 return Intrinsic::getName((Intrinsic::ID)IID);
4599 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4600 case ISD::TargetConstant: return "TargetConstant";
4601 case ISD::TargetConstantFP:return "TargetConstantFP";
4602 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4603 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4604 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4605 case ISD::TargetJumpTable: return "TargetJumpTable";
4606 case ISD::TargetConstantPool: return "TargetConstantPool";
4607 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4609 case ISD::CopyToReg: return "CopyToReg";
4610 case ISD::CopyFromReg: return "CopyFromReg";
4611 case ISD::UNDEF: return "undef";
4612 case ISD::MERGE_VALUES: return "merge_values";
4613 case ISD::INLINEASM: return "inlineasm";
4614 case ISD::DBG_LABEL: return "dbg_label";
4615 case ISD::EH_LABEL: return "eh_label";
4616 case ISD::DECLARE: return "declare";
4617 case ISD::HANDLENODE: return "handlenode";
4618 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4619 case ISD::CALL: return "call";
4622 case ISD::FABS: return "fabs";
4623 case ISD::FNEG: return "fneg";
4624 case ISD::FSQRT: return "fsqrt";
4625 case ISD::FSIN: return "fsin";
4626 case ISD::FCOS: return "fcos";
4627 case ISD::FPOWI: return "fpowi";
4628 case ISD::FPOW: return "fpow";
4631 case ISD::ADD: return "add";
4632 case ISD::SUB: return "sub";
4633 case ISD::MUL: return "mul";
4634 case ISD::MULHU: return "mulhu";
4635 case ISD::MULHS: return "mulhs";
4636 case ISD::SDIV: return "sdiv";
4637 case ISD::UDIV: return "udiv";
4638 case ISD::SREM: return "srem";
4639 case ISD::UREM: return "urem";
4640 case ISD::SMUL_LOHI: return "smul_lohi";
4641 case ISD::UMUL_LOHI: return "umul_lohi";
4642 case ISD::SDIVREM: return "sdivrem";
4643 case ISD::UDIVREM: return "divrem";
4644 case ISD::AND: return "and";
4645 case ISD::OR: return "or";
4646 case ISD::XOR: return "xor";
4647 case ISD::SHL: return "shl";
4648 case ISD::SRA: return "sra";
4649 case ISD::SRL: return "srl";
4650 case ISD::ROTL: return "rotl";
4651 case ISD::ROTR: return "rotr";
4652 case ISD::FADD: return "fadd";
4653 case ISD::FSUB: return "fsub";
4654 case ISD::FMUL: return "fmul";
4655 case ISD::FDIV: return "fdiv";
4656 case ISD::FREM: return "frem";
4657 case ISD::FCOPYSIGN: return "fcopysign";
4658 case ISD::FGETSIGN: return "fgetsign";
4660 case ISD::SETCC: return "setcc";
4661 case ISD::VSETCC: return "vsetcc";
4662 case ISD::SELECT: return "select";
4663 case ISD::SELECT_CC: return "select_cc";
4664 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4665 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4666 case ISD::CONCAT_VECTORS: return "concat_vectors";
4667 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4668 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4669 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4670 case ISD::CARRY_FALSE: return "carry_false";
4671 case ISD::ADDC: return "addc";
4672 case ISD::ADDE: return "adde";
4673 case ISD::SUBC: return "subc";
4674 case ISD::SUBE: return "sube";
4675 case ISD::SHL_PARTS: return "shl_parts";
4676 case ISD::SRA_PARTS: return "sra_parts";
4677 case ISD::SRL_PARTS: return "srl_parts";
4679 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4680 case ISD::INSERT_SUBREG: return "insert_subreg";
4682 // Conversion operators.
4683 case ISD::SIGN_EXTEND: return "sign_extend";
4684 case ISD::ZERO_EXTEND: return "zero_extend";
4685 case ISD::ANY_EXTEND: return "any_extend";
4686 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4687 case ISD::TRUNCATE: return "truncate";
4688 case ISD::FP_ROUND: return "fp_round";
4689 case ISD::FLT_ROUNDS_: return "flt_rounds";
4690 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4691 case ISD::FP_EXTEND: return "fp_extend";
4693 case ISD::SINT_TO_FP: return "sint_to_fp";
4694 case ISD::UINT_TO_FP: return "uint_to_fp";
4695 case ISD::FP_TO_SINT: return "fp_to_sint";
4696 case ISD::FP_TO_UINT: return "fp_to_uint";
4697 case ISD::BIT_CONVERT: return "bit_convert";
4699 // Control flow instructions
4700 case ISD::BR: return "br";
4701 case ISD::BRIND: return "brind";
4702 case ISD::BR_JT: return "br_jt";
4703 case ISD::BRCOND: return "brcond";
4704 case ISD::BR_CC: return "br_cc";
4705 case ISD::RET: return "ret";
4706 case ISD::CALLSEQ_START: return "callseq_start";
4707 case ISD::CALLSEQ_END: return "callseq_end";
4710 case ISD::LOAD: return "load";
4711 case ISD::STORE: return "store";
4712 case ISD::VAARG: return "vaarg";
4713 case ISD::VACOPY: return "vacopy";
4714 case ISD::VAEND: return "vaend";
4715 case ISD::VASTART: return "vastart";
4716 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4717 case ISD::EXTRACT_ELEMENT: return "extract_element";
4718 case ISD::BUILD_PAIR: return "build_pair";
4719 case ISD::STACKSAVE: return "stacksave";
4720 case ISD::STACKRESTORE: return "stackrestore";
4721 case ISD::TRAP: return "trap";
4724 case ISD::BSWAP: return "bswap";
4725 case ISD::CTPOP: return "ctpop";
4726 case ISD::CTTZ: return "cttz";
4727 case ISD::CTLZ: return "ctlz";
4730 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4731 case ISD::DEBUG_LOC: return "debug_loc";
4734 case ISD::TRAMPOLINE: return "trampoline";
4737 switch (cast<CondCodeSDNode>(this)->get()) {
4738 default: assert(0 && "Unknown setcc condition!");
4739 case ISD::SETOEQ: return "setoeq";
4740 case ISD::SETOGT: return "setogt";
4741 case ISD::SETOGE: return "setoge";
4742 case ISD::SETOLT: return "setolt";
4743 case ISD::SETOLE: return "setole";
4744 case ISD::SETONE: return "setone";
4746 case ISD::SETO: return "seto";
4747 case ISD::SETUO: return "setuo";
4748 case ISD::SETUEQ: return "setue";
4749 case ISD::SETUGT: return "setugt";
4750 case ISD::SETUGE: return "setuge";
4751 case ISD::SETULT: return "setult";
4752 case ISD::SETULE: return "setule";
4753 case ISD::SETUNE: return "setune";
4755 case ISD::SETEQ: return "seteq";
4756 case ISD::SETGT: return "setgt";
4757 case ISD::SETGE: return "setge";
4758 case ISD::SETLT: return "setlt";
4759 case ISD::SETLE: return "setle";
4760 case ISD::SETNE: return "setne";
4765 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4774 return "<post-inc>";
4776 return "<post-dec>";
4780 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4781 std::string S = "< ";
4795 if (getByValAlign())
4796 S += "byval-align:" + utostr(getByValAlign()) + " ";
4798 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4800 S += "byval-size:" + utostr(getByValSize()) + " ";
4804 void SDNode::dump() const { dump(0); }
4805 void SDNode::dump(const SelectionDAG *G) const {
4806 cerr << (void*)this << ": ";
4808 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4810 if (getValueType(i) == MVT::Other)
4813 cerr << getValueType(i).getMVTString();
4815 cerr << " = " << getOperationName(G);
4818 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4819 if (i) cerr << ", ";
4820 cerr << (void*)getOperand(i).Val;
4821 if (unsigned RN = getOperand(i).ResNo)
4825 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4826 SDNode *Mask = getOperand(2).Val;
4828 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4830 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4833 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4838 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4839 cerr << "<" << CSDN->getValue() << ">";
4840 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4841 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4842 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4843 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4844 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4846 cerr << "<APFloat(";
4847 CSDN->getValueAPF().convertToAPInt().dump();
4850 } else if (const GlobalAddressSDNode *GADN =
4851 dyn_cast<GlobalAddressSDNode>(this)) {
4852 int offset = GADN->getOffset();
4854 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4856 cerr << " + " << offset;
4858 cerr << " " << offset;
4859 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4860 cerr << "<" << FIDN->getIndex() << ">";
4861 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4862 cerr << "<" << JTDN->getIndex() << ">";
4863 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4864 int offset = CP->getOffset();
4865 if (CP->isMachineConstantPoolEntry())
4866 cerr << "<" << *CP->getMachineCPVal() << ">";
4868 cerr << "<" << *CP->getConstVal() << ">";
4870 cerr << " + " << offset;
4872 cerr << " " << offset;
4873 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4875 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4877 cerr << LBB->getName() << " ";
4878 cerr << (const void*)BBDN->getBasicBlock() << ">";
4879 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4880 if (G && R->getReg() &&
4881 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4882 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4884 cerr << " #" << R->getReg();
4886 } else if (const ExternalSymbolSDNode *ES =
4887 dyn_cast<ExternalSymbolSDNode>(this)) {
4888 cerr << "'" << ES->getSymbol() << "'";
4889 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4891 cerr << "<" << M->getValue() << ">";
4894 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4895 if (M->MO.getValue())
4896 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4898 cerr << "<null:" << M->MO.getOffset() << ">";
4899 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4900 cerr << N->getArgFlags().getArgFlagsString();
4901 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4902 cerr << ":" << N->getVT().getMVTString();
4904 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4905 const Value *SrcValue = LD->getSrcValue();
4906 int SrcOffset = LD->getSrcValueOffset();
4912 cerr << ":" << SrcOffset << ">";
4915 switch (LD->getExtensionType()) {
4916 default: doExt = false; break;
4918 cerr << " <anyext ";
4928 cerr << LD->getMemoryVT().getMVTString() << ">";
4930 const char *AM = getIndexedModeName(LD->getAddressingMode());
4933 if (LD->isVolatile())
4934 cerr << " <volatile>";
4935 cerr << " alignment=" << LD->getAlignment();
4936 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4937 const Value *SrcValue = ST->getSrcValue();
4938 int SrcOffset = ST->getSrcValueOffset();
4944 cerr << ":" << SrcOffset << ">";
4946 if (ST->isTruncatingStore())
4948 << ST->getMemoryVT().getMVTString() << ">";
4950 const char *AM = getIndexedModeName(ST->getAddressingMode());
4953 if (ST->isVolatile())
4954 cerr << " <volatile>";
4955 cerr << " alignment=" << ST->getAlignment();
4956 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
4957 const Value *SrcValue = AT->getSrcValue();
4958 int SrcOffset = AT->getSrcValueOffset();
4964 cerr << ":" << SrcOffset << ">";
4965 if (AT->isVolatile())
4966 cerr << " <volatile>";
4967 cerr << " alignment=" << AT->getAlignment();
4971 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4972 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4973 if (N->getOperand(i).Val->hasOneUse())
4974 DumpNodes(N->getOperand(i).Val, indent+2, G);
4976 cerr << "\n" << std::string(indent+2, ' ')
4977 << (void*)N->getOperand(i).Val << ": <multiple use>";
4980 cerr << "\n" << std::string(indent, ' ');
4984 void SelectionDAG::dump() const {
4985 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4986 std::vector<const SDNode*> Nodes;
4987 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4991 std::sort(Nodes.begin(), Nodes.end());
4993 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4994 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4995 DumpNodes(Nodes[i], 2, this);
4998 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
5003 const Type *ConstantPoolSDNode::getType() const {
5004 if (isMachineConstantPoolEntry())
5005 return Val.MachineCPVal->getType();
5006 return Val.ConstVal->getType();