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 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/Constants.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringExtras.h"
39 /// makeVTList - Return an instance of the SDVTList struct initialized with the
40 /// specified members.
41 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
42 SDVTList Res = {VTs, NumVTs};
46 //===----------------------------------------------------------------------===//
47 // ConstantFPSDNode Class
48 //===----------------------------------------------------------------------===//
50 /// isExactlyValue - We don't rely on operator== working on double values, as
51 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
52 /// As such, this method can be used to do an exact bit-for-bit comparison of
53 /// two floating point values.
54 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
55 return Value.bitwiseIsEqual(V);
58 bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT,
60 // convert modifies in place, so make a copy.
61 APFloat Val2 = APFloat(Val);
64 return false; // These can't be represented as floating point!
66 // FIXME rounding mode needs to be more flexible
68 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
69 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
72 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
73 &Val2.getSemantics() == &APFloat::IEEEdouble ||
74 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
76 // TODO: Figure out how to test if we can use a shorter type instead!
84 //===----------------------------------------------------------------------===//
86 //===----------------------------------------------------------------------===//
88 /// isBuildVectorAllOnes - Return true if the specified node is a
89 /// BUILD_VECTOR where all of the elements are ~0 or undef.
90 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
91 // Look through a bit convert.
92 if (N->getOpcode() == ISD::BIT_CONVERT)
93 N = N->getOperand(0).Val;
95 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
97 unsigned i = 0, e = N->getNumOperands();
99 // Skip over all of the undef values.
100 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
103 // Do not accept an all-undef vector.
104 if (i == e) return false;
106 // Do not accept build_vectors that aren't all constants or which have non-~0
108 SDOperand NotZero = N->getOperand(i);
109 if (isa<ConstantSDNode>(NotZero)) {
110 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
112 } else if (isa<ConstantFPSDNode>(NotZero)) {
113 MVT::ValueType VT = NotZero.getValueType();
115 if (((cast<ConstantFPSDNode>(NotZero)->getValueAPF().
116 convertToAPInt().getZExtValue())) != (uint64_t)-1)
119 if ((uint32_t)cast<ConstantFPSDNode>(NotZero)->
120 getValueAPF().convertToAPInt().getZExtValue() !=
127 // Okay, we have at least one ~0 value, check to see if the rest match or are
129 for (++i; i != e; ++i)
130 if (N->getOperand(i) != NotZero &&
131 N->getOperand(i).getOpcode() != ISD::UNDEF)
137 /// isBuildVectorAllZeros - Return true if the specified node is a
138 /// BUILD_VECTOR where all of the elements are 0 or undef.
139 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
140 // Look through a bit convert.
141 if (N->getOpcode() == ISD::BIT_CONVERT)
142 N = N->getOperand(0).Val;
144 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
146 unsigned i = 0, e = N->getNumOperands();
148 // Skip over all of the undef values.
149 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
152 // Do not accept an all-undef vector.
153 if (i == e) return false;
155 // Do not accept build_vectors that aren't all constants or which have non-~0
157 SDOperand Zero = N->getOperand(i);
158 if (isa<ConstantSDNode>(Zero)) {
159 if (!cast<ConstantSDNode>(Zero)->isNullValue())
161 } else if (isa<ConstantFPSDNode>(Zero)) {
162 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
167 // Okay, we have at least one ~0 value, check to see if the rest match or are
169 for (++i; i != e; ++i)
170 if (N->getOperand(i) != Zero &&
171 N->getOperand(i).getOpcode() != ISD::UNDEF)
176 /// isDebugLabel - Return true if the specified node represents a debug
177 /// label (i.e. ISD::LABEL or TargetInstrInfo::LANEL node and third operand
179 bool ISD::isDebugLabel(const SDNode *N) {
181 if (N->getOpcode() == ISD::LABEL)
182 Zero = N->getOperand(2);
183 else if (N->isTargetOpcode() &&
184 N->getTargetOpcode() == TargetInstrInfo::LABEL)
185 // Chain moved to last operand.
186 Zero = N->getOperand(1);
189 return isa<ConstantSDNode>(Zero) && cast<ConstantSDNode>(Zero)->isNullValue();
192 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
193 /// when given the operation for (X op Y).
194 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
195 // To perform this operation, we just need to swap the L and G bits of the
197 unsigned OldL = (Operation >> 2) & 1;
198 unsigned OldG = (Operation >> 1) & 1;
199 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
200 (OldL << 1) | // New G bit
201 (OldG << 2)); // New L bit.
204 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
205 /// 'op' is a valid SetCC operation.
206 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
207 unsigned Operation = Op;
209 Operation ^= 7; // Flip L, G, E bits, but not U.
211 Operation ^= 15; // Flip all of the condition bits.
212 if (Operation > ISD::SETTRUE2)
213 Operation &= ~8; // Don't let N and U bits get set.
214 return ISD::CondCode(Operation);
218 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
219 /// signed operation and 2 if the result is an unsigned comparison. Return zero
220 /// if the operation does not depend on the sign of the input (setne and seteq).
221 static int isSignedOp(ISD::CondCode Opcode) {
223 default: assert(0 && "Illegal integer setcc operation!");
225 case ISD::SETNE: return 0;
229 case ISD::SETGE: return 1;
233 case ISD::SETUGE: return 2;
237 /// getSetCCOrOperation - Return the result of a logical OR between different
238 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
239 /// returns SETCC_INVALID if it is not possible to represent the resultant
241 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
243 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
244 // Cannot fold a signed integer setcc with an unsigned integer setcc.
245 return ISD::SETCC_INVALID;
247 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
249 // If the N and U bits get set then the resultant comparison DOES suddenly
250 // care about orderedness, and is true when ordered.
251 if (Op > ISD::SETTRUE2)
252 Op &= ~16; // Clear the U bit if the N bit is set.
254 // Canonicalize illegal integer setcc's.
255 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
258 return ISD::CondCode(Op);
261 /// getSetCCAndOperation - Return the result of a logical AND between different
262 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
263 /// function returns zero if it is not possible to represent the resultant
265 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
267 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
268 // Cannot fold a signed setcc with an unsigned setcc.
269 return ISD::SETCC_INVALID;
271 // Combine all of the condition bits.
272 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
274 // Canonicalize illegal integer setcc's.
278 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
279 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
280 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
281 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
288 const TargetMachine &SelectionDAG::getTarget() const {
289 return TLI.getTargetMachine();
292 //===----------------------------------------------------------------------===//
293 // SDNode Profile Support
294 //===----------------------------------------------------------------------===//
296 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
298 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
302 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
303 /// solely with their pointer.
304 void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
305 ID.AddPointer(VTList.VTs);
308 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
310 static void AddNodeIDOperands(FoldingSetNodeID &ID,
311 const SDOperand *Ops, unsigned NumOps) {
312 for (; NumOps; --NumOps, ++Ops) {
313 ID.AddPointer(Ops->Val);
314 ID.AddInteger(Ops->ResNo);
318 static void AddNodeIDNode(FoldingSetNodeID &ID,
319 unsigned short OpC, SDVTList VTList,
320 const SDOperand *OpList, unsigned N) {
321 AddNodeIDOpcode(ID, OpC);
322 AddNodeIDValueTypes(ID, VTList);
323 AddNodeIDOperands(ID, OpList, N);
326 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
328 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
329 AddNodeIDOpcode(ID, N->getOpcode());
330 // Add the return value info.
331 AddNodeIDValueTypes(ID, N->getVTList());
332 // Add the operand info.
333 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
335 // Handle SDNode leafs with special info.
336 switch (N->getOpcode()) {
337 default: break; // Normal nodes don't need extra info.
338 case ISD::TargetConstant:
340 ID.AddInteger(cast<ConstantSDNode>(N)->getValue());
342 case ISD::TargetConstantFP:
343 case ISD::ConstantFP: {
344 ID.AddAPFloat(cast<ConstantFPSDNode>(N)->getValueAPF());
347 case ISD::TargetGlobalAddress:
348 case ISD::GlobalAddress:
349 case ISD::TargetGlobalTLSAddress:
350 case ISD::GlobalTLSAddress: {
351 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
352 ID.AddPointer(GA->getGlobal());
353 ID.AddInteger(GA->getOffset());
356 case ISD::BasicBlock:
357 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
360 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
363 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
365 case ISD::MEMOPERAND: {
366 const MemOperand &MO = cast<MemOperandSDNode>(N)->MO;
367 ID.AddPointer(MO.getValue());
368 ID.AddInteger(MO.getFlags());
369 ID.AddInteger(MO.getOffset());
370 ID.AddInteger(MO.getSize());
371 ID.AddInteger(MO.getAlignment());
374 case ISD::FrameIndex:
375 case ISD::TargetFrameIndex:
376 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
379 case ISD::TargetJumpTable:
380 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
382 case ISD::ConstantPool:
383 case ISD::TargetConstantPool: {
384 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
385 ID.AddInteger(CP->getAlignment());
386 ID.AddInteger(CP->getOffset());
387 if (CP->isMachineConstantPoolEntry())
388 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
390 ID.AddPointer(CP->getConstVal());
394 LoadSDNode *LD = cast<LoadSDNode>(N);
395 ID.AddInteger(LD->getAddressingMode());
396 ID.AddInteger(LD->getExtensionType());
397 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
398 ID.AddInteger(LD->getAlignment());
399 ID.AddInteger(LD->isVolatile());
403 StoreSDNode *ST = cast<StoreSDNode>(N);
404 ID.AddInteger(ST->getAddressingMode());
405 ID.AddInteger(ST->isTruncatingStore());
406 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
407 ID.AddInteger(ST->getAlignment());
408 ID.AddInteger(ST->isVolatile());
414 //===----------------------------------------------------------------------===//
415 // SelectionDAG Class
416 //===----------------------------------------------------------------------===//
418 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
420 void SelectionDAG::RemoveDeadNodes() {
421 // Create a dummy node (which is not added to allnodes), that adds a reference
422 // to the root node, preventing it from being deleted.
423 HandleSDNode Dummy(getRoot());
425 SmallVector<SDNode*, 128> DeadNodes;
427 // Add all obviously-dead nodes to the DeadNodes worklist.
428 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
430 DeadNodes.push_back(I);
432 // Process the worklist, deleting the nodes and adding their uses to the
434 while (!DeadNodes.empty()) {
435 SDNode *N = DeadNodes.back();
436 DeadNodes.pop_back();
438 // Take the node out of the appropriate CSE map.
439 RemoveNodeFromCSEMaps(N);
441 // Next, brutally remove the operand list. This is safe to do, as there are
442 // no cycles in the graph.
443 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
444 SDNode *Operand = I->Val;
445 Operand->removeUser(N);
447 // Now that we removed this operand, see if there are no uses of it left.
448 if (Operand->use_empty())
449 DeadNodes.push_back(Operand);
451 if (N->OperandsNeedDelete)
452 delete[] N->OperandList;
456 // Finally, remove N itself.
460 // If the root changed (e.g. it was a dead load, update the root).
461 setRoot(Dummy.getValue());
464 void SelectionDAG::RemoveDeadNode(SDNode *N, std::vector<SDNode*> &Deleted) {
465 SmallVector<SDNode*, 16> DeadNodes;
466 DeadNodes.push_back(N);
468 // Process the worklist, deleting the nodes and adding their uses to the
470 while (!DeadNodes.empty()) {
471 SDNode *N = DeadNodes.back();
472 DeadNodes.pop_back();
474 // Take the node out of the appropriate CSE map.
475 RemoveNodeFromCSEMaps(N);
477 // Next, brutally remove the operand list. This is safe to do, as there are
478 // no cycles in the graph.
479 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
480 SDNode *Operand = I->Val;
481 Operand->removeUser(N);
483 // Now that we removed this operand, see if there are no uses of it left.
484 if (Operand->use_empty())
485 DeadNodes.push_back(Operand);
487 if (N->OperandsNeedDelete)
488 delete[] N->OperandList;
492 // Finally, remove N itself.
493 Deleted.push_back(N);
498 void SelectionDAG::DeleteNode(SDNode *N) {
499 assert(N->use_empty() && "Cannot delete a node that is not dead!");
501 // First take this out of the appropriate CSE map.
502 RemoveNodeFromCSEMaps(N);
504 // Finally, remove uses due to operands of this node, remove from the
505 // AllNodes list, and delete the node.
506 DeleteNodeNotInCSEMaps(N);
509 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
511 // Remove it from the AllNodes list.
514 // Drop all of the operands and decrement used nodes use counts.
515 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
516 I->Val->removeUser(N);
517 if (N->OperandsNeedDelete)
518 delete[] N->OperandList;
525 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
526 /// correspond to it. This is useful when we're about to delete or repurpose
527 /// the node. We don't want future request for structurally identical nodes
528 /// to return N anymore.
529 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
531 switch (N->getOpcode()) {
532 case ISD::HANDLENODE: return; // noop.
534 Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
537 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
538 "Cond code doesn't exist!");
539 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
540 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
542 case ISD::ExternalSymbol:
543 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
545 case ISD::TargetExternalSymbol:
547 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
549 case ISD::VALUETYPE: {
550 MVT::ValueType VT = cast<VTSDNode>(N)->getVT();
551 if (MVT::isExtendedVT(VT)) {
552 Erased = ExtendedValueTypeNodes.erase(VT);
554 Erased = ValueTypeNodes[VT] != 0;
555 ValueTypeNodes[VT] = 0;
560 // Remove it from the CSE Map.
561 Erased = CSEMap.RemoveNode(N);
565 // Verify that the node was actually in one of the CSE maps, unless it has a
566 // flag result (which cannot be CSE'd) or is one of the special cases that are
567 // not subject to CSE.
568 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
569 !N->isTargetOpcode()) {
572 assert(0 && "Node is not in map!");
577 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
578 /// has been taken out and modified in some way. If the specified node already
579 /// exists in the CSE maps, do not modify the maps, but return the existing node
580 /// instead. If it doesn't exist, add it and return null.
582 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
583 assert(N->getNumOperands() && "This is a leaf node!");
584 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
585 return 0; // Never add these nodes.
587 // Check that remaining values produced are not flags.
588 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
589 if (N->getValueType(i) == MVT::Flag)
590 return 0; // Never CSE anything that produces a flag.
592 SDNode *New = CSEMap.GetOrInsertNode(N);
593 if (New != N) return New; // Node already existed.
597 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
598 /// were replaced with those specified. If this node is never memoized,
599 /// return null, otherwise return a pointer to the slot it would take. If a
600 /// node already exists with these operands, the slot will be non-null.
601 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
603 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
604 return 0; // Never add these nodes.
606 // Check that remaining values produced are not flags.
607 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
608 if (N->getValueType(i) == MVT::Flag)
609 return 0; // Never CSE anything that produces a flag.
611 SDOperand Ops[] = { Op };
613 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
614 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
617 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
618 /// were replaced with those specified. If this node is never memoized,
619 /// return null, otherwise return a pointer to the slot it would take. If a
620 /// node already exists with these operands, the slot will be non-null.
621 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
622 SDOperand Op1, SDOperand Op2,
624 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
625 return 0; // Never add these nodes.
627 // Check that remaining values produced are not flags.
628 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
629 if (N->getValueType(i) == MVT::Flag)
630 return 0; // Never CSE anything that produces a flag.
632 SDOperand Ops[] = { Op1, Op2 };
634 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
635 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
639 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
640 /// were replaced with those specified. If this node is never memoized,
641 /// return null, otherwise return a pointer to the slot it would take. If a
642 /// node already exists with these operands, the slot will be non-null.
643 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
644 const SDOperand *Ops,unsigned NumOps,
646 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
647 return 0; // Never add these nodes.
649 // Check that remaining values produced are not flags.
650 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
651 if (N->getValueType(i) == MVT::Flag)
652 return 0; // Never CSE anything that produces a flag.
655 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
657 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
658 ID.AddInteger(LD->getAddressingMode());
659 ID.AddInteger(LD->getExtensionType());
660 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
661 ID.AddInteger(LD->getAlignment());
662 ID.AddInteger(LD->isVolatile());
663 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
664 ID.AddInteger(ST->getAddressingMode());
665 ID.AddInteger(ST->isTruncatingStore());
666 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
667 ID.AddInteger(ST->getAlignment());
668 ID.AddInteger(ST->isVolatile());
671 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
675 SelectionDAG::~SelectionDAG() {
676 while (!AllNodes.empty()) {
677 SDNode *N = AllNodes.begin();
678 N->SetNextInBucket(0);
679 if (N->OperandsNeedDelete)
680 delete [] N->OperandList;
683 AllNodes.pop_front();
687 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
688 if (Op.getValueType() == VT) return Op;
689 int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
690 return getNode(ISD::AND, Op.getValueType(), Op,
691 getConstant(Imm, Op.getValueType()));
694 SDOperand SelectionDAG::getString(const std::string &Val) {
695 StringSDNode *&N = StringNodes[Val];
697 N = new StringSDNode(Val);
698 AllNodes.push_back(N);
700 return SDOperand(N, 0);
703 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
704 assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
706 MVT::ValueType EltVT =
707 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
709 // Mask out any bits that are not valid for this constant.
710 Val &= MVT::getIntVTBitMask(EltVT);
712 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
714 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
718 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
719 if (!MVT::isVector(VT))
720 return SDOperand(N, 0);
722 N = new ConstantSDNode(isT, Val, EltVT);
723 CSEMap.InsertNode(N, IP);
724 AllNodes.push_back(N);
727 SDOperand Result(N, 0);
728 if (MVT::isVector(VT)) {
729 SmallVector<SDOperand, 8> Ops;
730 Ops.assign(MVT::getVectorNumElements(VT), Result);
731 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
736 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
737 return getConstant(Val, TLI.getPointerTy(), isTarget);
741 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
743 assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
745 MVT::ValueType EltVT =
746 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
748 // Do the map lookup using the actual bit pattern for the floating point
749 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
750 // we don't have issues with SNANs.
751 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
753 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
757 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
758 if (!MVT::isVector(VT))
759 return SDOperand(N, 0);
761 N = new ConstantFPSDNode(isTarget, V, EltVT);
762 CSEMap.InsertNode(N, IP);
763 AllNodes.push_back(N);
766 SDOperand Result(N, 0);
767 if (MVT::isVector(VT)) {
768 SmallVector<SDOperand, 8> Ops;
769 Ops.assign(MVT::getVectorNumElements(VT), Result);
770 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
775 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
777 MVT::ValueType EltVT =
778 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
780 return getConstantFP(APFloat((float)Val), VT, isTarget);
782 return getConstantFP(APFloat(Val), VT, isTarget);
785 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
786 MVT::ValueType VT, int Offset,
788 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
790 if (GVar && GVar->isThreadLocal())
791 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
793 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
795 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
797 ID.AddInteger(Offset);
799 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
800 return SDOperand(E, 0);
801 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
802 CSEMap.InsertNode(N, IP);
803 AllNodes.push_back(N);
804 return SDOperand(N, 0);
807 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
809 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
811 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
814 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
815 return SDOperand(E, 0);
816 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
817 CSEMap.InsertNode(N, IP);
818 AllNodes.push_back(N);
819 return SDOperand(N, 0);
822 SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
823 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
825 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
828 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
829 return SDOperand(E, 0);
830 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
831 CSEMap.InsertNode(N, IP);
832 AllNodes.push_back(N);
833 return SDOperand(N, 0);
836 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
837 unsigned Alignment, int Offset,
839 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
841 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
842 ID.AddInteger(Alignment);
843 ID.AddInteger(Offset);
846 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
847 return SDOperand(E, 0);
848 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
849 CSEMap.InsertNode(N, IP);
850 AllNodes.push_back(N);
851 return SDOperand(N, 0);
855 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
857 unsigned Alignment, int Offset,
859 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
861 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
862 ID.AddInteger(Alignment);
863 ID.AddInteger(Offset);
864 C->AddSelectionDAGCSEId(ID);
866 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
867 return SDOperand(E, 0);
868 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
869 CSEMap.InsertNode(N, IP);
870 AllNodes.push_back(N);
871 return SDOperand(N, 0);
875 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
877 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
880 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
881 return SDOperand(E, 0);
882 SDNode *N = new BasicBlockSDNode(MBB);
883 CSEMap.InsertNode(N, IP);
884 AllNodes.push_back(N);
885 return SDOperand(N, 0);
888 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
889 if (!MVT::isExtendedVT(VT) && (unsigned)VT >= ValueTypeNodes.size())
890 ValueTypeNodes.resize(VT+1);
892 SDNode *&N = MVT::isExtendedVT(VT) ?
893 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT];
895 if (N) return SDOperand(N, 0);
896 N = new VTSDNode(VT);
897 AllNodes.push_back(N);
898 return SDOperand(N, 0);
901 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
902 SDNode *&N = ExternalSymbols[Sym];
903 if (N) return SDOperand(N, 0);
904 N = new ExternalSymbolSDNode(false, Sym, VT);
905 AllNodes.push_back(N);
906 return SDOperand(N, 0);
909 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
911 SDNode *&N = TargetExternalSymbols[Sym];
912 if (N) return SDOperand(N, 0);
913 N = new ExternalSymbolSDNode(true, Sym, VT);
914 AllNodes.push_back(N);
915 return SDOperand(N, 0);
918 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
919 if ((unsigned)Cond >= CondCodeNodes.size())
920 CondCodeNodes.resize(Cond+1);
922 if (CondCodeNodes[Cond] == 0) {
923 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
924 AllNodes.push_back(CondCodeNodes[Cond]);
926 return SDOperand(CondCodeNodes[Cond], 0);
929 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
931 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
932 ID.AddInteger(RegNo);
934 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
935 return SDOperand(E, 0);
936 SDNode *N = new RegisterSDNode(RegNo, VT);
937 CSEMap.InsertNode(N, IP);
938 AllNodes.push_back(N);
939 return SDOperand(N, 0);
942 SDOperand SelectionDAG::getSrcValue(const Value *V) {
943 assert((!V || isa<PointerType>(V->getType())) &&
944 "SrcValue is not a pointer?");
947 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
951 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
952 return SDOperand(E, 0);
954 SDNode *N = new SrcValueSDNode(V);
955 CSEMap.InsertNode(N, IP);
956 AllNodes.push_back(N);
957 return SDOperand(N, 0);
960 SDOperand SelectionDAG::getMemOperand(const MemOperand &MO) {
961 const Value *v = MO.getValue();
962 assert((!v || isa<PointerType>(v->getType())) &&
963 "SrcValue is not a pointer?");
966 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
968 ID.AddInteger(MO.getFlags());
969 ID.AddInteger(MO.getOffset());
970 ID.AddInteger(MO.getSize());
971 ID.AddInteger(MO.getAlignment());
974 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
975 return SDOperand(E, 0);
977 SDNode *N = new MemOperandSDNode(MO);
978 CSEMap.InsertNode(N, IP);
979 AllNodes.push_back(N);
980 return SDOperand(N, 0);
983 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
984 /// specified value type.
985 SDOperand SelectionDAG::CreateStackTemporary(MVT::ValueType VT) {
986 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
987 unsigned ByteSize = MVT::getSizeInBits(VT)/8;
988 const Type *Ty = MVT::getTypeForValueType(VT);
989 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
990 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
991 return getFrameIndex(FrameIdx, TLI.getPointerTy());
995 SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
996 SDOperand N2, ISD::CondCode Cond) {
997 // These setcc operations always fold.
1001 case ISD::SETFALSE2: return getConstant(0, VT);
1003 case ISD::SETTRUE2: return getConstant(1, VT);
1015 assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
1019 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1020 uint64_t C2 = N2C->getValue();
1021 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1022 uint64_t C1 = N1C->getValue();
1024 // Sign extend the operands if required
1025 if (ISD::isSignedIntSetCC(Cond)) {
1026 C1 = N1C->getSignExtended();
1027 C2 = N2C->getSignExtended();
1031 default: assert(0 && "Unknown integer setcc!");
1032 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1033 case ISD::SETNE: return getConstant(C1 != C2, VT);
1034 case ISD::SETULT: return getConstant(C1 < C2, VT);
1035 case ISD::SETUGT: return getConstant(C1 > C2, VT);
1036 case ISD::SETULE: return getConstant(C1 <= C2, VT);
1037 case ISD::SETUGE: return getConstant(C1 >= C2, VT);
1038 case ISD::SETLT: return getConstant((int64_t)C1 < (int64_t)C2, VT);
1039 case ISD::SETGT: return getConstant((int64_t)C1 > (int64_t)C2, VT);
1040 case ISD::SETLE: return getConstant((int64_t)C1 <= (int64_t)C2, VT);
1041 case ISD::SETGE: return getConstant((int64_t)C1 >= (int64_t)C2, VT);
1045 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
1046 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1047 // No compile time operations on this type yet.
1048 if (N1C->getValueType(0) == MVT::ppcf128)
1051 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1054 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1055 return getNode(ISD::UNDEF, VT);
1057 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1058 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1059 return getNode(ISD::UNDEF, VT);
1061 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1062 R==APFloat::cmpLessThan, VT);
1063 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1064 return getNode(ISD::UNDEF, VT);
1066 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1067 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1068 return getNode(ISD::UNDEF, VT);
1070 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1071 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1072 return getNode(ISD::UNDEF, VT);
1074 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1075 R==APFloat::cmpEqual, VT);
1076 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1077 return getNode(ISD::UNDEF, VT);
1079 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1080 R==APFloat::cmpEqual, VT);
1081 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1082 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1083 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1084 R==APFloat::cmpEqual, VT);
1085 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1086 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1087 R==APFloat::cmpLessThan, VT);
1088 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1089 R==APFloat::cmpUnordered, VT);
1090 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1091 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1094 // Ensure that the constant occurs on the RHS.
1095 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1098 // Could not fold it.
1102 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1103 /// this predicate to simplify operations downstream. Mask is known to be zero
1104 /// for bits that V cannot have.
1105 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, uint64_t Mask,
1106 unsigned Depth) const {
1107 // The masks are not wide enough to represent this type! Should use APInt.
1108 if (Op.getValueType() == MVT::i128)
1111 uint64_t KnownZero, KnownOne;
1112 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1113 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1114 return (KnownZero & Mask) == Mask;
1117 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1118 /// known to be either zero or one and return them in the KnownZero/KnownOne
1119 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1121 void SelectionDAG::ComputeMaskedBits(SDOperand Op, uint64_t Mask,
1122 uint64_t &KnownZero, uint64_t &KnownOne,
1123 unsigned Depth) const {
1124 KnownZero = KnownOne = 0; // Don't know anything.
1125 if (Depth == 6 || Mask == 0)
1126 return; // Limit search depth.
1128 // The masks are not wide enough to represent this type! Should use APInt.
1129 if (Op.getValueType() == MVT::i128)
1132 uint64_t KnownZero2, KnownOne2;
1134 switch (Op.getOpcode()) {
1136 // We know all of the bits for a constant!
1137 KnownOne = cast<ConstantSDNode>(Op)->getValue() & Mask;
1138 KnownZero = ~KnownOne & Mask;
1141 // If either the LHS or the RHS are Zero, the result is zero.
1142 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1144 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1145 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1146 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1148 // Output known-1 bits are only known if set in both the LHS & RHS.
1149 KnownOne &= KnownOne2;
1150 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1151 KnownZero |= KnownZero2;
1154 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1156 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1157 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1158 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1160 // Output known-0 bits are only known if clear in both the LHS & RHS.
1161 KnownZero &= KnownZero2;
1162 // Output known-1 are known to be set if set in either the LHS | RHS.
1163 KnownOne |= KnownOne2;
1166 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1167 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1168 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1169 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1171 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1172 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1173 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1174 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1175 KnownZero = KnownZeroOut;
1179 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1180 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1181 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1182 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1184 // Only known if known in both the LHS and RHS.
1185 KnownOne &= KnownOne2;
1186 KnownZero &= KnownZero2;
1188 case ISD::SELECT_CC:
1189 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1190 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1191 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1192 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1194 // Only known if known in both the LHS and RHS.
1195 KnownOne &= KnownOne2;
1196 KnownZero &= KnownZero2;
1199 // If we know the result of a setcc has the top bits zero, use this info.
1200 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
1201 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
1204 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1205 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1206 ComputeMaskedBits(Op.getOperand(0), Mask >> SA->getValue(),
1207 KnownZero, KnownOne, Depth+1);
1208 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1209 KnownZero <<= SA->getValue();
1210 KnownOne <<= SA->getValue();
1211 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1215 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1216 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1217 MVT::ValueType VT = Op.getValueType();
1218 unsigned ShAmt = SA->getValue();
1220 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1221 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt) & TypeMask,
1222 KnownZero, KnownOne, Depth+1);
1223 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1224 KnownZero &= TypeMask;
1225 KnownOne &= TypeMask;
1226 KnownZero >>= ShAmt;
1229 uint64_t HighBits = (1ULL << ShAmt)-1;
1230 HighBits <<= MVT::getSizeInBits(VT)-ShAmt;
1231 KnownZero |= HighBits; // High bits known zero.
1235 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1236 MVT::ValueType VT = Op.getValueType();
1237 unsigned ShAmt = SA->getValue();
1239 // Compute the new bits that are at the top now.
1240 uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1242 uint64_t InDemandedMask = (Mask << ShAmt) & TypeMask;
1243 // If any of the demanded bits are produced by the sign extension, we also
1244 // demand the input sign bit.
1245 uint64_t HighBits = (1ULL << ShAmt)-1;
1246 HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
1247 if (HighBits & Mask)
1248 InDemandedMask |= MVT::getIntVTSignBit(VT);
1250 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1252 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1253 KnownZero &= TypeMask;
1254 KnownOne &= TypeMask;
1255 KnownZero >>= ShAmt;
1258 // Handle the sign bits.
1259 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1260 SignBit >>= ShAmt; // Adjust to where it is now in the mask.
1262 if (KnownZero & SignBit) {
1263 KnownZero |= HighBits; // New bits are known zero.
1264 } else if (KnownOne & SignBit) {
1265 KnownOne |= HighBits; // New bits are known one.
1269 case ISD::SIGN_EXTEND_INREG: {
1270 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1272 // Sign extension. Compute the demanded bits in the result that are not
1273 // present in the input.
1274 uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & Mask;
1276 uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
1277 int64_t InputDemandedBits = Mask & MVT::getIntVTBitMask(EVT);
1279 // If the sign extended bits are demanded, we know that the sign
1282 InputDemandedBits |= InSignBit;
1284 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1285 KnownZero, KnownOne, Depth+1);
1286 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1288 // If the sign bit of the input is known set or clear, then we know the
1289 // top bits of the result.
1290 if (KnownZero & InSignBit) { // Input sign bit known clear
1291 KnownZero |= NewBits;
1292 KnownOne &= ~NewBits;
1293 } else if (KnownOne & InSignBit) { // Input sign bit known set
1294 KnownOne |= NewBits;
1295 KnownZero &= ~NewBits;
1296 } else { // Input sign bit unknown
1297 KnownZero &= ~NewBits;
1298 KnownOne &= ~NewBits;
1305 MVT::ValueType VT = Op.getValueType();
1306 unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
1307 KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
1312 if (ISD::isZEXTLoad(Op.Val)) {
1313 LoadSDNode *LD = cast<LoadSDNode>(Op);
1314 MVT::ValueType VT = LD->getMemoryVT();
1315 KnownZero |= ~MVT::getIntVTBitMask(VT) & Mask;
1319 case ISD::ZERO_EXTEND: {
1320 uint64_t InMask = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
1321 uint64_t NewBits = (~InMask) & Mask;
1322 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1324 KnownZero |= NewBits & Mask;
1325 KnownOne &= ~NewBits;
1328 case ISD::SIGN_EXTEND: {
1329 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1330 unsigned InBits = MVT::getSizeInBits(InVT);
1331 uint64_t InMask = MVT::getIntVTBitMask(InVT);
1332 uint64_t InSignBit = 1ULL << (InBits-1);
1333 uint64_t NewBits = (~InMask) & Mask;
1334 uint64_t InDemandedBits = Mask & InMask;
1336 // If any of the sign extended bits are demanded, we know that the sign
1339 InDemandedBits |= InSignBit;
1341 ComputeMaskedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1343 // If the sign bit is known zero or one, the top bits match.
1344 if (KnownZero & InSignBit) {
1345 KnownZero |= NewBits;
1346 KnownOne &= ~NewBits;
1347 } else if (KnownOne & InSignBit) {
1348 KnownOne |= NewBits;
1349 KnownZero &= ~NewBits;
1350 } else { // Otherwise, top bits aren't known.
1351 KnownOne &= ~NewBits;
1352 KnownZero &= ~NewBits;
1356 case ISD::ANY_EXTEND: {
1357 MVT::ValueType VT = Op.getOperand(0).getValueType();
1358 ComputeMaskedBits(Op.getOperand(0), Mask & MVT::getIntVTBitMask(VT),
1359 KnownZero, KnownOne, Depth+1);
1362 case ISD::TRUNCATE: {
1363 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1364 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1365 uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
1366 KnownZero &= OutMask;
1367 KnownOne &= OutMask;
1370 case ISD::AssertZext: {
1371 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1372 uint64_t InMask = MVT::getIntVTBitMask(VT);
1373 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1375 KnownZero |= (~InMask) & Mask;
1379 // All bits are zero except the low bit.
1380 KnownZero = MVT::getIntVTBitMask(Op.getValueType()) ^ 1;
1384 // If either the LHS or the RHS are Zero, the result is zero.
1385 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1386 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1387 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1388 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1390 // Output known-0 bits are known if clear or set in both the low clear bits
1391 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1392 // low 3 bits clear.
1393 uint64_t KnownZeroOut = std::min(CountTrailingZeros_64(~KnownZero),
1394 CountTrailingZeros_64(~KnownZero2));
1396 KnownZero = (1ULL << KnownZeroOut) - 1;
1401 ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1404 // We know that the top bits of C-X are clear if X contains less bits
1405 // than C (i.e. no wrap-around can happen). For example, 20-X is
1406 // positive if we can prove that X is >= 0 and < 16.
1407 MVT::ValueType VT = CLHS->getValueType(0);
1408 if ((CLHS->getValue() & MVT::getIntVTSignBit(VT)) == 0) { // sign bit clear
1409 unsigned NLZ = CountLeadingZeros_64(CLHS->getValue()+1);
1410 uint64_t MaskV = (1ULL << (63-NLZ))-1; // NLZ can't be 64 with no sign bit
1411 MaskV = ~MaskV & MVT::getIntVTBitMask(VT);
1412 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
1414 // If all of the MaskV bits are known to be zero, then we know the output
1415 // top bits are zero, because we now know that the output is from [0-C].
1416 if ((KnownZero & MaskV) == MaskV) {
1417 unsigned NLZ2 = CountLeadingZeros_64(CLHS->getValue());
1418 KnownZero = ~((1ULL << (64-NLZ2))-1) & Mask; // Top bits known zero.
1419 KnownOne = 0; // No one bits known.
1421 KnownZero = KnownOne = 0; // Otherwise, nothing known.
1427 // Allow the target to implement this method for its nodes.
1428 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1429 case ISD::INTRINSIC_WO_CHAIN:
1430 case ISD::INTRINSIC_W_CHAIN:
1431 case ISD::INTRINSIC_VOID:
1432 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1438 /// ComputeNumSignBits - Return the number of times the sign bit of the
1439 /// register is replicated into the other bits. We know that at least 1 bit
1440 /// is always equal to the sign bit (itself), but other cases can give us
1441 /// information. For example, immediately after an "SRA X, 2", we know that
1442 /// the top 3 bits are all equal to each other, so we return 3.
1443 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1444 MVT::ValueType VT = Op.getValueType();
1445 assert(MVT::isInteger(VT) && "Invalid VT!");
1446 unsigned VTBits = MVT::getSizeInBits(VT);
1450 return 1; // Limit search depth.
1452 switch (Op.getOpcode()) {
1454 case ISD::AssertSext:
1455 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1456 return VTBits-Tmp+1;
1457 case ISD::AssertZext:
1458 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1461 case ISD::Constant: {
1462 uint64_t Val = cast<ConstantSDNode>(Op)->getValue();
1463 // If negative, invert the bits, then look at it.
1464 if (Val & MVT::getIntVTSignBit(VT))
1467 // Shift the bits so they are the leading bits in the int64_t.
1470 // Return # leading zeros. We use 'min' here in case Val was zero before
1471 // shifting. We don't want to return '64' as for an i32 "0".
1472 return std::min(VTBits, CountLeadingZeros_64(Val));
1475 case ISD::SIGN_EXTEND:
1476 Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1477 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1479 case ISD::SIGN_EXTEND_INREG:
1480 // Max of the input and what this extends.
1481 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1484 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1485 return std::max(Tmp, Tmp2);
1488 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1489 // SRA X, C -> adds C sign bits.
1490 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1491 Tmp += C->getValue();
1492 if (Tmp > VTBits) Tmp = VTBits;
1496 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1497 // shl destroys sign bits.
1498 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1499 if (C->getValue() >= VTBits || // Bad shift.
1500 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1501 return Tmp - C->getValue();
1506 case ISD::XOR: // NOT is handled here.
1507 // Logical binary ops preserve the number of sign bits.
1508 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1509 if (Tmp == 1) return 1; // Early out.
1510 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1511 return std::min(Tmp, Tmp2);
1514 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1515 if (Tmp == 1) return 1; // Early out.
1516 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1517 return std::min(Tmp, Tmp2);
1520 // If setcc returns 0/-1, all bits are sign bits.
1521 if (TLI.getSetCCResultContents() ==
1522 TargetLowering::ZeroOrNegativeOneSetCCResult)
1527 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1528 unsigned RotAmt = C->getValue() & (VTBits-1);
1530 // Handle rotate right by N like a rotate left by 32-N.
1531 if (Op.getOpcode() == ISD::ROTR)
1532 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1534 // If we aren't rotating out all of the known-in sign bits, return the
1535 // number that are left. This handles rotl(sext(x), 1) for example.
1536 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1537 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1541 // Add can have at most one carry bit. Thus we know that the output
1542 // is, at worst, one more bit than the inputs.
1543 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1544 if (Tmp == 1) return 1; // Early out.
1546 // Special case decrementing a value (ADD X, -1):
1547 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1548 if (CRHS->isAllOnesValue()) {
1549 uint64_t KnownZero, KnownOne;
1550 uint64_t Mask = MVT::getIntVTBitMask(VT);
1551 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1553 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1555 if ((KnownZero|1) == Mask)
1558 // If we are subtracting one from a positive number, there is no carry
1559 // out of the result.
1560 if (KnownZero & MVT::getIntVTSignBit(VT))
1564 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1565 if (Tmp2 == 1) return 1;
1566 return std::min(Tmp, Tmp2)-1;
1570 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1571 if (Tmp2 == 1) return 1;
1574 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1575 if (CLHS->getValue() == 0) {
1576 uint64_t KnownZero, KnownOne;
1577 uint64_t Mask = MVT::getIntVTBitMask(VT);
1578 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1579 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1581 if ((KnownZero|1) == Mask)
1584 // If the input is known to be positive (the sign bit is known clear),
1585 // the output of the NEG has the same number of sign bits as the input.
1586 if (KnownZero & MVT::getIntVTSignBit(VT))
1589 // Otherwise, we treat this like a SUB.
1592 // Sub can have at most one carry bit. Thus we know that the output
1593 // is, at worst, one more bit than the inputs.
1594 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1595 if (Tmp == 1) return 1; // Early out.
1596 return std::min(Tmp, Tmp2)-1;
1599 // FIXME: it's tricky to do anything useful for this, but it is an important
1600 // case for targets like X86.
1604 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1605 if (Op.getOpcode() == ISD::LOAD) {
1606 LoadSDNode *LD = cast<LoadSDNode>(Op);
1607 unsigned ExtType = LD->getExtensionType();
1610 case ISD::SEXTLOAD: // '17' bits known
1611 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1612 return VTBits-Tmp+1;
1613 case ISD::ZEXTLOAD: // '16' bits known
1614 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1619 // Allow the target to implement this method for its nodes.
1620 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1621 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1622 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1623 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1624 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1625 if (NumBits > 1) return NumBits;
1628 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1629 // use this information.
1630 uint64_t KnownZero, KnownOne;
1631 uint64_t Mask = MVT::getIntVTBitMask(VT);
1632 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1634 uint64_t SignBit = MVT::getIntVTSignBit(VT);
1635 if (KnownZero & SignBit) { // SignBit is 0
1637 } else if (KnownOne & SignBit) { // SignBit is 1;
1644 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1645 // the number of identical bits in the top of the input value.
1648 // Return # leading zeros. We use 'min' here in case Val was zero before
1649 // shifting. We don't want to return '64' as for an i32 "0".
1650 return std::min(VTBits, CountLeadingZeros_64(Mask));
1654 /// getNode - Gets or creates the specified node.
1656 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1657 FoldingSetNodeID ID;
1658 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1660 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1661 return SDOperand(E, 0);
1662 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1663 CSEMap.InsertNode(N, IP);
1665 AllNodes.push_back(N);
1666 return SDOperand(N, 0);
1669 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1670 SDOperand Operand) {
1672 // Constant fold unary operations with an integer constant operand.
1673 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1674 uint64_t Val = C->getValue();
1677 case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
1678 case ISD::ANY_EXTEND:
1679 case ISD::ZERO_EXTEND: return getConstant(Val, VT);
1680 case ISD::TRUNCATE: return getConstant(Val, VT);
1681 case ISD::UINT_TO_FP:
1682 case ISD::SINT_TO_FP: {
1683 const uint64_t zero[] = {0, 0};
1684 // No compile time operations on this type.
1685 if (VT==MVT::ppcf128)
1687 APFloat apf = APFloat(APInt(MVT::getSizeInBits(VT), 2, zero));
1688 (void)apf.convertFromZeroExtendedInteger(&Val,
1689 MVT::getSizeInBits(Operand.getValueType()),
1690 Opcode==ISD::SINT_TO_FP,
1691 APFloat::rmNearestTiesToEven);
1692 return getConstantFP(apf, VT);
1694 case ISD::BIT_CONVERT:
1695 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1696 return getConstantFP(BitsToFloat(Val), VT);
1697 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1698 return getConstantFP(BitsToDouble(Val), VT);
1702 default: assert(0 && "Invalid bswap!"); break;
1703 case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
1704 case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
1705 case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
1710 default: assert(0 && "Invalid ctpop!"); break;
1711 case MVT::i1: return getConstant(Val != 0, VT);
1713 Tmp1 = (unsigned)Val & 0xFF;
1714 return getConstant(CountPopulation_32(Tmp1), VT);
1716 Tmp1 = (unsigned)Val & 0xFFFF;
1717 return getConstant(CountPopulation_32(Tmp1), VT);
1719 return getConstant(CountPopulation_32((unsigned)Val), VT);
1721 return getConstant(CountPopulation_64(Val), VT);
1725 default: assert(0 && "Invalid ctlz!"); break;
1726 case MVT::i1: return getConstant(Val == 0, VT);
1728 Tmp1 = (unsigned)Val & 0xFF;
1729 return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
1731 Tmp1 = (unsigned)Val & 0xFFFF;
1732 return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
1734 return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
1736 return getConstant(CountLeadingZeros_64(Val), VT);
1740 default: assert(0 && "Invalid cttz!"); break;
1741 case MVT::i1: return getConstant(Val == 0, VT);
1743 Tmp1 = (unsigned)Val | 0x100;
1744 return getConstant(CountTrailingZeros_32(Tmp1), VT);
1746 Tmp1 = (unsigned)Val | 0x10000;
1747 return getConstant(CountTrailingZeros_32(Tmp1), VT);
1749 return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
1751 return getConstant(CountTrailingZeros_64(Val), VT);
1756 // Constant fold unary operations with a floating point constant operand.
1757 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1758 APFloat V = C->getValueAPF(); // make copy
1759 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1763 return getConstantFP(V, VT);
1766 return getConstantFP(V, VT);
1768 case ISD::FP_EXTEND:
1769 // This can return overflow, underflow, or inexact; we don't care.
1770 // FIXME need to be more flexible about rounding mode.
1771 (void) V.convert(VT==MVT::f32 ? APFloat::IEEEsingle :
1772 VT==MVT::f64 ? APFloat::IEEEdouble :
1773 VT==MVT::f80 ? APFloat::x87DoubleExtended :
1774 VT==MVT::f128 ? APFloat::IEEEquad :
1776 APFloat::rmNearestTiesToEven);
1777 return getConstantFP(V, VT);
1778 case ISD::FP_TO_SINT:
1779 case ISD::FP_TO_UINT: {
1781 assert(integerPartWidth >= 64);
1782 // FIXME need to be more flexible about rounding mode.
1783 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1784 Opcode==ISD::FP_TO_SINT,
1785 APFloat::rmTowardZero);
1786 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
1788 return getConstant(x, VT);
1790 case ISD::BIT_CONVERT:
1791 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1792 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1793 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1794 return getConstant(V.convertToAPInt().getZExtValue(), VT);
1800 unsigned OpOpcode = Operand.Val->getOpcode();
1802 case ISD::TokenFactor:
1803 return Operand; // Factor of one node? No factor.
1804 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1805 case ISD::FP_EXTEND:
1806 assert(MVT::isFloatingPoint(VT) &&
1807 MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1808 if (Operand.getValueType() == VT) return Operand; // noop conversion.
1810 case ISD::SIGN_EXTEND:
1811 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1812 "Invalid SIGN_EXTEND!");
1813 if (Operand.getValueType() == VT) return Operand; // noop extension
1814 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1815 && "Invalid sext node, dst < src!");
1816 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1817 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1819 case ISD::ZERO_EXTEND:
1820 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1821 "Invalid ZERO_EXTEND!");
1822 if (Operand.getValueType() == VT) return Operand; // noop extension
1823 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1824 && "Invalid zext node, dst < src!");
1825 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
1826 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1828 case ISD::ANY_EXTEND:
1829 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1830 "Invalid ANY_EXTEND!");
1831 if (Operand.getValueType() == VT) return Operand; // noop extension
1832 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1833 && "Invalid anyext node, dst < src!");
1834 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1835 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
1836 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1839 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1840 "Invalid TRUNCATE!");
1841 if (Operand.getValueType() == VT) return Operand; // noop truncate
1842 assert(MVT::getSizeInBits(Operand.getValueType()) > MVT::getSizeInBits(VT)
1843 && "Invalid truncate node, src < dst!");
1844 if (OpOpcode == ISD::TRUNCATE)
1845 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1846 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1847 OpOpcode == ISD::ANY_EXTEND) {
1848 // If the source is smaller than the dest, we still need an extend.
1849 if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1850 < MVT::getSizeInBits(VT))
1851 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1852 else if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1853 > MVT::getSizeInBits(VT))
1854 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1856 return Operand.Val->getOperand(0);
1859 case ISD::BIT_CONVERT:
1860 // Basic sanity checking.
1861 assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1862 && "Cannot BIT_CONVERT between types of different sizes!");
1863 if (VT == Operand.getValueType()) return Operand; // noop conversion.
1864 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
1865 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1866 if (OpOpcode == ISD::UNDEF)
1867 return getNode(ISD::UNDEF, VT);
1869 case ISD::SCALAR_TO_VECTOR:
1870 assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1871 MVT::getVectorElementType(VT) == Operand.getValueType() &&
1872 "Illegal SCALAR_TO_VECTOR node!");
1875 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
1876 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1877 Operand.Val->getOperand(0));
1878 if (OpOpcode == ISD::FNEG) // --X -> X
1879 return Operand.Val->getOperand(0);
1882 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
1883 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1888 SDVTList VTs = getVTList(VT);
1889 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1890 FoldingSetNodeID ID;
1891 SDOperand Ops[1] = { Operand };
1892 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
1894 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1895 return SDOperand(E, 0);
1896 N = new UnarySDNode(Opcode, VTs, Operand);
1897 CSEMap.InsertNode(N, IP);
1899 N = new UnarySDNode(Opcode, VTs, Operand);
1901 AllNodes.push_back(N);
1902 return SDOperand(N, 0);
1907 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1908 SDOperand N1, SDOperand N2) {
1909 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1910 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1913 case ISD::TokenFactor:
1914 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1915 N2.getValueType() == MVT::Other && "Invalid token factor!");
1916 // Fold trivial token factors.
1917 if (N1.getOpcode() == ISD::EntryToken) return N2;
1918 if (N2.getOpcode() == ISD::EntryToken) return N1;
1921 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1922 N1.getValueType() == VT && "Binary operator types must match!");
1923 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
1924 // worth handling here.
1925 if (N2C && N2C->getValue() == 0)
1927 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
1932 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1933 N1.getValueType() == VT && "Binary operator types must match!");
1934 // (X ^| 0) -> X. This commonly occurs when legalizing i64 values, so it's
1935 // worth handling here.
1936 if (N2C && N2C->getValue() == 0)
1943 assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1955 assert(N1.getValueType() == N2.getValueType() &&
1956 N1.getValueType() == VT && "Binary operator types must match!");
1958 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
1959 assert(N1.getValueType() == VT &&
1960 MVT::isFloatingPoint(N1.getValueType()) &&
1961 MVT::isFloatingPoint(N2.getValueType()) &&
1962 "Invalid FCOPYSIGN!");
1969 assert(VT == N1.getValueType() &&
1970 "Shift operators return type must be the same as their first arg");
1971 assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1972 VT != MVT::i1 && "Shifts only work on integers");
1974 case ISD::FP_ROUND_INREG: {
1975 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1976 assert(VT == N1.getValueType() && "Not an inreg round!");
1977 assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1978 "Cannot FP_ROUND_INREG integer types");
1979 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
1980 "Not rounding down!");
1981 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
1985 assert(MVT::isFloatingPoint(VT) &&
1986 MVT::isFloatingPoint(N1.getValueType()) &&
1987 MVT::getSizeInBits(VT) <= MVT::getSizeInBits(N1.getValueType()) &&
1988 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
1989 if (N1.getValueType() == VT) return N1; // noop conversion.
1991 case ISD::AssertSext:
1992 case ISD::AssertZext: {
1993 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1994 assert(VT == N1.getValueType() && "Not an inreg extend!");
1995 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1996 "Cannot *_EXTEND_INREG FP types");
1997 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2001 case ISD::SIGN_EXTEND_INREG: {
2002 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2003 assert(VT == N1.getValueType() && "Not an inreg extend!");
2004 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2005 "Cannot *_EXTEND_INREG FP types");
2006 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2008 if (EVT == VT) return N1; // Not actually extending
2011 int64_t Val = N1C->getValue();
2012 unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
2013 Val <<= 64-FromBits;
2014 Val >>= 64-FromBits;
2015 return getConstant(Val, VT);
2019 case ISD::EXTRACT_VECTOR_ELT:
2020 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2022 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2023 // expanding copies of large vectors from registers.
2024 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2025 N1.getNumOperands() > 0) {
2027 MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2028 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2029 N1.getOperand(N2C->getValue() / Factor),
2030 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2033 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2034 // expanding large vector constants.
2035 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2036 return N1.getOperand(N2C->getValue());
2038 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2039 // operations are lowered to scalars.
2040 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2041 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2043 return N1.getOperand(1);
2045 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2048 case ISD::EXTRACT_ELEMENT:
2049 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2051 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2052 // 64-bit integers into 32-bit parts. Instead of building the extract of
2053 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2054 if (N1.getOpcode() == ISD::BUILD_PAIR)
2055 return N1.getOperand(N2C->getValue());
2057 // EXTRACT_ELEMENT of a constant int is also very common.
2058 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2059 unsigned Shift = MVT::getSizeInBits(VT) * N2C->getValue();
2060 return getConstant(C->getValue() >> Shift, VT);
2067 uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
2069 case ISD::ADD: return getConstant(C1 + C2, VT);
2070 case ISD::SUB: return getConstant(C1 - C2, VT);
2071 case ISD::MUL: return getConstant(C1 * C2, VT);
2073 if (C2) return getConstant(C1 / C2, VT);
2076 if (C2) return getConstant(C1 % C2, VT);
2079 if (C2) return getConstant(N1C->getSignExtended() /
2080 N2C->getSignExtended(), VT);
2083 if (C2) return getConstant(N1C->getSignExtended() %
2084 N2C->getSignExtended(), VT);
2086 case ISD::AND : return getConstant(C1 & C2, VT);
2087 case ISD::OR : return getConstant(C1 | C2, VT);
2088 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2089 case ISD::SHL : return getConstant(C1 << C2, VT);
2090 case ISD::SRL : return getConstant(C1 >> C2, VT);
2091 case ISD::SRA : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
2093 return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
2096 return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)),
2100 } else { // Cannonicalize constant to RHS if commutative
2101 if (isCommutativeBinOp(Opcode)) {
2102 std::swap(N1C, N2C);
2108 // Constant fold FP operations.
2109 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2110 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2112 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2113 // Cannonicalize constant to RHS if commutative
2114 std::swap(N1CFP, N2CFP);
2116 } else if (N2CFP && VT != MVT::ppcf128) {
2117 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2118 APFloat::opStatus s;
2121 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2122 if (s != APFloat::opInvalidOp)
2123 return getConstantFP(V1, VT);
2126 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2127 if (s!=APFloat::opInvalidOp)
2128 return getConstantFP(V1, VT);
2131 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2132 if (s!=APFloat::opInvalidOp)
2133 return getConstantFP(V1, VT);
2136 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2137 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2138 return getConstantFP(V1, VT);
2141 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2142 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2143 return getConstantFP(V1, VT);
2145 case ISD::FCOPYSIGN:
2147 return getConstantFP(V1, VT);
2153 // Canonicalize an UNDEF to the RHS, even over a constant.
2154 if (N1.getOpcode() == ISD::UNDEF) {
2155 if (isCommutativeBinOp(Opcode)) {
2159 case ISD::FP_ROUND_INREG:
2160 case ISD::SIGN_EXTEND_INREG:
2166 return N1; // fold op(undef, arg2) -> undef
2173 if (!MVT::isVector(VT))
2174 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2175 // For vectors, we can't easily build an all zero vector, just return
2182 // Fold a bunch of operators when the RHS is undef.
2183 if (N2.getOpcode() == ISD::UNDEF) {
2199 return N2; // fold op(arg1, undef) -> undef
2204 if (!MVT::isVector(VT))
2205 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2206 // For vectors, we can't easily build an all zero vector, just return
2210 if (!MVT::isVector(VT))
2211 return getConstant(MVT::getIntVTBitMask(VT), VT);
2212 // For vectors, we can't easily build an all one vector, just return
2220 // Memoize this node if possible.
2222 SDVTList VTs = getVTList(VT);
2223 if (VT != MVT::Flag) {
2224 SDOperand Ops[] = { N1, N2 };
2225 FoldingSetNodeID ID;
2226 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2228 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2229 return SDOperand(E, 0);
2230 N = new BinarySDNode(Opcode, VTs, N1, N2);
2231 CSEMap.InsertNode(N, IP);
2233 N = new BinarySDNode(Opcode, VTs, N1, N2);
2236 AllNodes.push_back(N);
2237 return SDOperand(N, 0);
2240 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2241 SDOperand N1, SDOperand N2, SDOperand N3) {
2242 // Perform various simplifications.
2243 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2244 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2247 // Use FoldSetCC to simplify SETCC's.
2248 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2249 if (Simp.Val) return Simp;
2254 if (N1C->getValue())
2255 return N2; // select true, X, Y -> X
2257 return N3; // select false, X, Y -> Y
2259 if (N2 == N3) return N2; // select C, X, X -> X
2263 if (N2C->getValue()) // Unconditional branch
2264 return getNode(ISD::BR, MVT::Other, N1, N3);
2266 return N1; // Never-taken branch
2268 case ISD::VECTOR_SHUFFLE:
2269 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2270 MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2271 N3.getOpcode() == ISD::BUILD_VECTOR &&
2272 MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2273 "Illegal VECTOR_SHUFFLE node!");
2275 case ISD::BIT_CONVERT:
2276 // Fold bit_convert nodes from a type to themselves.
2277 if (N1.getValueType() == VT)
2282 // Memoize node if it doesn't produce a flag.
2284 SDVTList VTs = getVTList(VT);
2285 if (VT != MVT::Flag) {
2286 SDOperand Ops[] = { N1, N2, N3 };
2287 FoldingSetNodeID ID;
2288 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2290 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2291 return SDOperand(E, 0);
2292 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2293 CSEMap.InsertNode(N, IP);
2295 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2297 AllNodes.push_back(N);
2298 return SDOperand(N, 0);
2301 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2302 SDOperand N1, SDOperand N2, SDOperand N3,
2304 SDOperand Ops[] = { N1, N2, N3, N4 };
2305 return getNode(Opcode, VT, Ops, 4);
2308 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2309 SDOperand N1, SDOperand N2, SDOperand N3,
2310 SDOperand N4, SDOperand N5) {
2311 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2312 return getNode(Opcode, VT, Ops, 5);
2315 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dest,
2316 SDOperand Src, SDOperand Size,
2318 SDOperand AlwaysInline) {
2319 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2320 return getNode(ISD::MEMCPY, MVT::Other, Ops, 6);
2323 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dest,
2324 SDOperand Src, SDOperand Size,
2326 SDOperand AlwaysInline) {
2327 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2328 return getNode(ISD::MEMMOVE, MVT::Other, Ops, 6);
2331 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dest,
2332 SDOperand Src, SDOperand Size,
2334 SDOperand AlwaysInline) {
2335 SDOperand Ops[] = { Chain, Dest, Src, Size, Align, AlwaysInline };
2336 return getNode(ISD::MEMSET, MVT::Other, Ops, 6);
2339 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2340 SDOperand Chain, SDOperand Ptr,
2341 const Value *SV, int SVOffset,
2342 bool isVolatile, unsigned Alignment) {
2343 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2345 if (VT != MVT::iPTR) {
2346 Ty = MVT::getTypeForValueType(VT);
2348 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2349 assert(PT && "Value for load must be a pointer");
2350 Ty = PT->getElementType();
2352 assert(Ty && "Could not get type information for load");
2353 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2355 SDVTList VTs = getVTList(VT, MVT::Other);
2356 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2357 SDOperand Ops[] = { Chain, Ptr, Undef };
2358 FoldingSetNodeID ID;
2359 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2360 ID.AddInteger(ISD::UNINDEXED);
2361 ID.AddInteger(ISD::NON_EXTLOAD);
2362 ID.AddInteger((unsigned int)VT);
2363 ID.AddInteger(Alignment);
2364 ID.AddInteger(isVolatile);
2366 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2367 return SDOperand(E, 0);
2368 SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED,
2369 ISD::NON_EXTLOAD, VT, SV, SVOffset, Alignment,
2371 CSEMap.InsertNode(N, IP);
2372 AllNodes.push_back(N);
2373 return SDOperand(N, 0);
2376 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2377 SDOperand Chain, SDOperand Ptr,
2379 int SVOffset, MVT::ValueType EVT,
2380 bool isVolatile, unsigned Alignment) {
2381 // If they are asking for an extending load from/to the same thing, return a
2384 return getLoad(VT, Chain, Ptr, SV, SVOffset, isVolatile, Alignment);
2386 if (MVT::isVector(VT))
2387 assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2389 assert(MVT::getSizeInBits(EVT) < MVT::getSizeInBits(VT) &&
2390 "Should only be an extending load, not truncating!");
2391 assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2392 "Cannot sign/zero extend a FP/Vector load!");
2393 assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2394 "Cannot convert from FP to Int or Int -> FP!");
2396 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2398 if (VT != MVT::iPTR) {
2399 Ty = MVT::getTypeForValueType(VT);
2401 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2402 assert(PT && "Value for load must be a pointer");
2403 Ty = PT->getElementType();
2405 assert(Ty && "Could not get type information for load");
2406 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2408 SDVTList VTs = getVTList(VT, MVT::Other);
2409 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2410 SDOperand Ops[] = { Chain, Ptr, Undef };
2411 FoldingSetNodeID ID;
2412 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2413 ID.AddInteger(ISD::UNINDEXED);
2414 ID.AddInteger(ExtType);
2415 ID.AddInteger((unsigned int)EVT);
2416 ID.AddInteger(Alignment);
2417 ID.AddInteger(isVolatile);
2419 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2420 return SDOperand(E, 0);
2421 SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED, ExtType, EVT,
2422 SV, SVOffset, Alignment, isVolatile);
2423 CSEMap.InsertNode(N, IP);
2424 AllNodes.push_back(N);
2425 return SDOperand(N, 0);
2429 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2430 SDOperand Offset, ISD::MemIndexedMode AM) {
2431 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2432 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2433 "Load is already a indexed load!");
2434 MVT::ValueType VT = OrigLoad.getValueType();
2435 SDVTList VTs = getVTList(VT, Base.getValueType(), MVT::Other);
2436 SDOperand Ops[] = { LD->getChain(), Base, Offset };
2437 FoldingSetNodeID ID;
2438 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2440 ID.AddInteger(LD->getExtensionType());
2441 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
2442 ID.AddInteger(LD->getAlignment());
2443 ID.AddInteger(LD->isVolatile());
2445 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2446 return SDOperand(E, 0);
2447 SDNode *N = new LoadSDNode(Ops, VTs, AM,
2448 LD->getExtensionType(), LD->getMemoryVT(),
2449 LD->getSrcValue(), LD->getSrcValueOffset(),
2450 LD->getAlignment(), LD->isVolatile());
2451 CSEMap.InsertNode(N, IP);
2452 AllNodes.push_back(N);
2453 return SDOperand(N, 0);
2456 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2457 SDOperand Ptr, const Value *SV, int SVOffset,
2458 bool isVolatile, unsigned Alignment) {
2459 MVT::ValueType VT = Val.getValueType();
2461 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2463 if (VT != MVT::iPTR) {
2464 Ty = MVT::getTypeForValueType(VT);
2466 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2467 assert(PT && "Value for store must be a pointer");
2468 Ty = PT->getElementType();
2470 assert(Ty && "Could not get type information for store");
2471 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2473 SDVTList VTs = getVTList(MVT::Other);
2474 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2475 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2476 FoldingSetNodeID ID;
2477 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2478 ID.AddInteger(ISD::UNINDEXED);
2479 ID.AddInteger(false);
2480 ID.AddInteger((unsigned int)VT);
2481 ID.AddInteger(Alignment);
2482 ID.AddInteger(isVolatile);
2484 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2485 return SDOperand(E, 0);
2486 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
2487 VT, SV, SVOffset, Alignment, isVolatile);
2488 CSEMap.InsertNode(N, IP);
2489 AllNodes.push_back(N);
2490 return SDOperand(N, 0);
2493 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
2494 SDOperand Ptr, const Value *SV,
2495 int SVOffset, MVT::ValueType SVT,
2496 bool isVolatile, unsigned Alignment) {
2497 MVT::ValueType VT = Val.getValueType();
2500 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
2502 assert(MVT::getSizeInBits(VT) > MVT::getSizeInBits(SVT) &&
2503 "Not a truncation?");
2504 assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
2505 "Can't do FP-INT conversion!");
2507 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2509 if (VT != MVT::iPTR) {
2510 Ty = MVT::getTypeForValueType(VT);
2512 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2513 assert(PT && "Value for store must be a pointer");
2514 Ty = PT->getElementType();
2516 assert(Ty && "Could not get type information for store");
2517 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2519 SDVTList VTs = getVTList(MVT::Other);
2520 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2521 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2522 FoldingSetNodeID ID;
2523 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2524 ID.AddInteger(ISD::UNINDEXED);
2526 ID.AddInteger((unsigned int)SVT);
2527 ID.AddInteger(Alignment);
2528 ID.AddInteger(isVolatile);
2530 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2531 return SDOperand(E, 0);
2532 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
2533 SVT, SV, SVOffset, Alignment, isVolatile);
2534 CSEMap.InsertNode(N, IP);
2535 AllNodes.push_back(N);
2536 return SDOperand(N, 0);
2540 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
2541 SDOperand Offset, ISD::MemIndexedMode AM) {
2542 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
2543 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
2544 "Store is already a indexed store!");
2545 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
2546 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
2547 FoldingSetNodeID ID;
2548 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2550 ID.AddInteger(ST->isTruncatingStore());
2551 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
2552 ID.AddInteger(ST->getAlignment());
2553 ID.AddInteger(ST->isVolatile());
2555 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2556 return SDOperand(E, 0);
2557 SDNode *N = new StoreSDNode(Ops, VTs, AM,
2558 ST->isTruncatingStore(), ST->getMemoryVT(),
2559 ST->getSrcValue(), ST->getSrcValueOffset(),
2560 ST->getAlignment(), ST->isVolatile());
2561 CSEMap.InsertNode(N, IP);
2562 AllNodes.push_back(N);
2563 return SDOperand(N, 0);
2566 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
2567 SDOperand Chain, SDOperand Ptr,
2569 SDOperand Ops[] = { Chain, Ptr, SV };
2570 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
2573 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2574 const SDOperand *Ops, unsigned NumOps) {
2576 case 0: return getNode(Opcode, VT);
2577 case 1: return getNode(Opcode, VT, Ops[0]);
2578 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
2579 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
2585 case ISD::SELECT_CC: {
2586 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
2587 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
2588 "LHS and RHS of condition must have same type!");
2589 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2590 "True and False arms of SelectCC must have same type!");
2591 assert(Ops[2].getValueType() == VT &&
2592 "select_cc node must be of same type as true and false value!");
2596 assert(NumOps == 5 && "BR_CC takes 5 operands!");
2597 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2598 "LHS/RHS of comparison should match types!");
2605 SDVTList VTs = getVTList(VT);
2606 if (VT != MVT::Flag) {
2607 FoldingSetNodeID ID;
2608 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
2610 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2611 return SDOperand(E, 0);
2612 N = new SDNode(Opcode, VTs, Ops, NumOps);
2613 CSEMap.InsertNode(N, IP);
2615 N = new SDNode(Opcode, VTs, Ops, NumOps);
2617 AllNodes.push_back(N);
2618 return SDOperand(N, 0);
2621 SDOperand SelectionDAG::getNode(unsigned Opcode,
2622 std::vector<MVT::ValueType> &ResultTys,
2623 const SDOperand *Ops, unsigned NumOps) {
2624 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
2628 SDOperand SelectionDAG::getNode(unsigned Opcode,
2629 const MVT::ValueType *VTs, unsigned NumVTs,
2630 const SDOperand *Ops, unsigned NumOps) {
2632 return getNode(Opcode, VTs[0], Ops, NumOps);
2633 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
2636 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2637 const SDOperand *Ops, unsigned NumOps) {
2638 if (VTList.NumVTs == 1)
2639 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
2642 // FIXME: figure out how to safely handle things like
2643 // int foo(int x) { return 1 << (x & 255); }
2644 // int bar() { return foo(256); }
2646 case ISD::SRA_PARTS:
2647 case ISD::SRL_PARTS:
2648 case ISD::SHL_PARTS:
2649 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2650 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
2651 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2652 else if (N3.getOpcode() == ISD::AND)
2653 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
2654 // If the and is only masking out bits that cannot effect the shift,
2655 // eliminate the and.
2656 unsigned NumBits = MVT::getSizeInBits(VT)*2;
2657 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2658 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2664 // Memoize the node unless it returns a flag.
2666 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
2667 FoldingSetNodeID ID;
2668 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
2670 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2671 return SDOperand(E, 0);
2673 N = new UnarySDNode(Opcode, VTList, Ops[0]);
2674 else if (NumOps == 2)
2675 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2676 else if (NumOps == 3)
2677 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2679 N = new SDNode(Opcode, VTList, Ops, NumOps);
2680 CSEMap.InsertNode(N, IP);
2683 N = new UnarySDNode(Opcode, VTList, Ops[0]);
2684 else if (NumOps == 2)
2685 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2686 else if (NumOps == 3)
2687 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2689 N = new SDNode(Opcode, VTList, Ops, NumOps);
2691 AllNodes.push_back(N);
2692 return SDOperand(N, 0);
2695 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
2696 return getNode(Opcode, VTList, 0, 0);
2699 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2701 SDOperand Ops[] = { N1 };
2702 return getNode(Opcode, VTList, Ops, 1);
2705 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2706 SDOperand N1, SDOperand N2) {
2707 SDOperand Ops[] = { N1, N2 };
2708 return getNode(Opcode, VTList, Ops, 2);
2711 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2712 SDOperand N1, SDOperand N2, SDOperand N3) {
2713 SDOperand Ops[] = { N1, N2, N3 };
2714 return getNode(Opcode, VTList, Ops, 3);
2717 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2718 SDOperand N1, SDOperand N2, SDOperand N3,
2720 SDOperand Ops[] = { N1, N2, N3, N4 };
2721 return getNode(Opcode, VTList, Ops, 4);
2724 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2725 SDOperand N1, SDOperand N2, SDOperand N3,
2726 SDOperand N4, SDOperand N5) {
2727 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2728 return getNode(Opcode, VTList, Ops, 5);
2731 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
2732 return makeVTList(SDNode::getValueTypeList(VT), 1);
2735 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
2736 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2737 E = VTList.end(); I != E; ++I) {
2738 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
2739 return makeVTList(&(*I)[0], 2);
2741 std::vector<MVT::ValueType> V;
2744 VTList.push_front(V);
2745 return makeVTList(&(*VTList.begin())[0], 2);
2747 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
2748 MVT::ValueType VT3) {
2749 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2750 E = VTList.end(); I != E; ++I) {
2751 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
2753 return makeVTList(&(*I)[0], 3);
2755 std::vector<MVT::ValueType> V;
2759 VTList.push_front(V);
2760 return makeVTList(&(*VTList.begin())[0], 3);
2763 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
2765 case 0: assert(0 && "Cannot have nodes without results!");
2766 case 1: return getVTList(VTs[0]);
2767 case 2: return getVTList(VTs[0], VTs[1]);
2768 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
2772 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2773 E = VTList.end(); I != E; ++I) {
2774 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
2776 bool NoMatch = false;
2777 for (unsigned i = 2; i != NumVTs; ++i)
2778 if (VTs[i] != (*I)[i]) {
2783 return makeVTList(&*I->begin(), NumVTs);
2786 VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
2787 return makeVTList(&*VTList.begin()->begin(), NumVTs);
2791 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
2792 /// specified operands. If the resultant node already exists in the DAG,
2793 /// this does not modify the specified node, instead it returns the node that
2794 /// already exists. If the resultant node does not exist in the DAG, the
2795 /// input node is returned. As a degenerate case, if you specify the same
2796 /// input operands as the node already has, the input node is returned.
2797 SDOperand SelectionDAG::
2798 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
2799 SDNode *N = InN.Val;
2800 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
2802 // Check to see if there is no change.
2803 if (Op == N->getOperand(0)) return InN;
2805 // See if the modified node already exists.
2806 void *InsertPos = 0;
2807 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
2808 return SDOperand(Existing, InN.ResNo);
2810 // Nope it doesn't. Remove the node from it's current place in the maps.
2812 RemoveNodeFromCSEMaps(N);
2814 // Now we update the operands.
2815 N->OperandList[0].Val->removeUser(N);
2817 N->OperandList[0] = Op;
2819 // If this gets put into a CSE map, add it.
2820 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2824 SDOperand SelectionDAG::
2825 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
2826 SDNode *N = InN.Val;
2827 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
2829 // Check to see if there is no change.
2830 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
2831 return InN; // No operands changed, just return the input node.
2833 // See if the modified node already exists.
2834 void *InsertPos = 0;
2835 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
2836 return SDOperand(Existing, InN.ResNo);
2838 // Nope it doesn't. Remove the node from it's current place in the maps.
2840 RemoveNodeFromCSEMaps(N);
2842 // Now we update the operands.
2843 if (N->OperandList[0] != Op1) {
2844 N->OperandList[0].Val->removeUser(N);
2845 Op1.Val->addUser(N);
2846 N->OperandList[0] = Op1;
2848 if (N->OperandList[1] != Op2) {
2849 N->OperandList[1].Val->removeUser(N);
2850 Op2.Val->addUser(N);
2851 N->OperandList[1] = Op2;
2854 // If this gets put into a CSE map, add it.
2855 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2859 SDOperand SelectionDAG::
2860 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2861 SDOperand Ops[] = { Op1, Op2, Op3 };
2862 return UpdateNodeOperands(N, Ops, 3);
2865 SDOperand SelectionDAG::
2866 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2867 SDOperand Op3, SDOperand Op4) {
2868 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
2869 return UpdateNodeOperands(N, Ops, 4);
2872 SDOperand SelectionDAG::
2873 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2874 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2875 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
2876 return UpdateNodeOperands(N, Ops, 5);
2880 SDOperand SelectionDAG::
2881 UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
2882 SDNode *N = InN.Val;
2883 assert(N->getNumOperands() == NumOps &&
2884 "Update with wrong number of operands");
2886 // Check to see if there is no change.
2887 bool AnyChange = false;
2888 for (unsigned i = 0; i != NumOps; ++i) {
2889 if (Ops[i] != N->getOperand(i)) {
2895 // No operands changed, just return the input node.
2896 if (!AnyChange) return InN;
2898 // See if the modified node already exists.
2899 void *InsertPos = 0;
2900 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
2901 return SDOperand(Existing, InN.ResNo);
2903 // Nope it doesn't. Remove the node from it's current place in the maps.
2905 RemoveNodeFromCSEMaps(N);
2907 // Now we update the operands.
2908 for (unsigned i = 0; i != NumOps; ++i) {
2909 if (N->OperandList[i] != Ops[i]) {
2910 N->OperandList[i].Val->removeUser(N);
2911 Ops[i].Val->addUser(N);
2912 N->OperandList[i] = Ops[i];
2916 // If this gets put into a CSE map, add it.
2917 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2922 /// MorphNodeTo - This frees the operands of the current node, resets the
2923 /// opcode, types, and operands to the specified value. This should only be
2924 /// used by the SelectionDAG class.
2925 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
2926 const SDOperand *Ops, unsigned NumOps) {
2929 NumValues = L.NumVTs;
2931 // Clear the operands list, updating used nodes to remove this from their
2933 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2934 I->Val->removeUser(this);
2936 // If NumOps is larger than the # of operands we currently have, reallocate
2937 // the operand list.
2938 if (NumOps > NumOperands) {
2939 if (OperandsNeedDelete)
2940 delete [] OperandList;
2941 OperandList = new SDOperand[NumOps];
2942 OperandsNeedDelete = true;
2945 // Assign the new operands.
2946 NumOperands = NumOps;
2948 for (unsigned i = 0, e = NumOps; i != e; ++i) {
2949 OperandList[i] = Ops[i];
2950 SDNode *N = OperandList[i].Val;
2951 N->Uses.push_back(this);
2955 /// SelectNodeTo - These are used for target selectors to *mutate* the
2956 /// specified node to have the specified return type, Target opcode, and
2957 /// operands. Note that target opcodes are stored as
2958 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
2960 /// Note that SelectNodeTo returns the resultant node. If there is already a
2961 /// node of the specified opcode and operands, it returns that node instead of
2962 /// the current one.
2963 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2964 MVT::ValueType VT) {
2965 SDVTList VTs = getVTList(VT);
2966 FoldingSetNodeID ID;
2967 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2969 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2972 RemoveNodeFromCSEMaps(N);
2974 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2976 CSEMap.InsertNode(N, IP);
2980 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2981 MVT::ValueType VT, SDOperand Op1) {
2982 // If an identical node already exists, use it.
2983 SDVTList VTs = getVTList(VT);
2984 SDOperand Ops[] = { Op1 };
2986 FoldingSetNodeID ID;
2987 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2989 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2992 RemoveNodeFromCSEMaps(N);
2993 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2994 CSEMap.InsertNode(N, IP);
2998 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2999 MVT::ValueType VT, SDOperand Op1,
3001 // If an identical node already exists, use it.
3002 SDVTList VTs = getVTList(VT);
3003 SDOperand Ops[] = { Op1, Op2 };
3005 FoldingSetNodeID ID;
3006 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3008 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3011 RemoveNodeFromCSEMaps(N);
3013 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3015 CSEMap.InsertNode(N, IP); // Memoize the new node.
3019 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3020 MVT::ValueType VT, SDOperand Op1,
3021 SDOperand Op2, SDOperand Op3) {
3022 // If an identical node already exists, use it.
3023 SDVTList VTs = getVTList(VT);
3024 SDOperand Ops[] = { Op1, Op2, Op3 };
3025 FoldingSetNodeID ID;
3026 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3028 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3031 RemoveNodeFromCSEMaps(N);
3033 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3035 CSEMap.InsertNode(N, IP); // Memoize the new node.
3039 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3040 MVT::ValueType VT, const SDOperand *Ops,
3042 // If an identical node already exists, use it.
3043 SDVTList VTs = getVTList(VT);
3044 FoldingSetNodeID ID;
3045 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3047 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3050 RemoveNodeFromCSEMaps(N);
3051 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3053 CSEMap.InsertNode(N, IP); // Memoize the new node.
3057 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3058 MVT::ValueType VT1, MVT::ValueType VT2,
3059 SDOperand Op1, SDOperand Op2) {
3060 SDVTList VTs = getVTList(VT1, VT2);
3061 FoldingSetNodeID ID;
3062 SDOperand Ops[] = { Op1, Op2 };
3063 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3065 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3068 RemoveNodeFromCSEMaps(N);
3069 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3070 CSEMap.InsertNode(N, IP); // Memoize the new node.
3074 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3075 MVT::ValueType VT1, MVT::ValueType VT2,
3076 SDOperand Op1, SDOperand Op2,
3078 // If an identical node already exists, use it.
3079 SDVTList VTs = getVTList(VT1, VT2);
3080 SDOperand Ops[] = { Op1, Op2, Op3 };
3081 FoldingSetNodeID ID;
3082 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3084 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3087 RemoveNodeFromCSEMaps(N);
3089 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3090 CSEMap.InsertNode(N, IP); // Memoize the new node.
3095 /// getTargetNode - These are used for target selectors to create a new node
3096 /// with specified return type(s), target opcode, and operands.
3098 /// Note that getTargetNode returns the resultant node. If there is already a
3099 /// node of the specified opcode and operands, it returns that node instead of
3100 /// the current one.
3101 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
3102 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3104 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3106 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3108 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3109 SDOperand Op1, SDOperand Op2) {
3110 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3112 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3113 SDOperand Op1, SDOperand Op2,
3115 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3117 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3118 const SDOperand *Ops, unsigned NumOps) {
3119 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3121 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3122 MVT::ValueType VT2) {
3123 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3125 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3127 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3128 MVT::ValueType VT2, SDOperand Op1) {
3129 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3130 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3132 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3133 MVT::ValueType VT2, SDOperand Op1,
3135 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3136 SDOperand Ops[] = { Op1, Op2 };
3137 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3139 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3140 MVT::ValueType VT2, SDOperand Op1,
3141 SDOperand Op2, SDOperand Op3) {
3142 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3143 SDOperand Ops[] = { Op1, Op2, Op3 };
3144 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3146 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3148 const SDOperand *Ops, unsigned NumOps) {
3149 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3150 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3152 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3153 MVT::ValueType VT2, MVT::ValueType VT3,
3154 SDOperand Op1, SDOperand Op2) {
3155 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3156 SDOperand Ops[] = { Op1, Op2 };
3157 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3159 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3160 MVT::ValueType VT2, MVT::ValueType VT3,
3161 SDOperand Op1, SDOperand Op2,
3163 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3164 SDOperand Ops[] = { Op1, Op2, Op3 };
3165 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3167 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3168 MVT::ValueType VT2, MVT::ValueType VT3,
3169 const SDOperand *Ops, unsigned NumOps) {
3170 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3171 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3173 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3174 MVT::ValueType VT2, MVT::ValueType VT3,
3176 const SDOperand *Ops, unsigned NumOps) {
3177 std::vector<MVT::ValueType> VTList;
3178 VTList.push_back(VT1);
3179 VTList.push_back(VT2);
3180 VTList.push_back(VT3);
3181 VTList.push_back(VT4);
3182 const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3183 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3185 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3186 std::vector<MVT::ValueType> &ResultTys,
3187 const SDOperand *Ops, unsigned NumOps) {
3188 const MVT::ValueType *VTs = getNodeValueTypes(ResultTys);
3189 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3193 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3194 /// This can cause recursive merging of nodes in the DAG.
3196 /// This version assumes From/To have a single result value.
3198 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
3199 std::vector<SDNode*> *Deleted) {
3200 SDNode *From = FromN.Val, *To = ToN.Val;
3201 assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
3202 "Cannot replace with this method!");
3203 assert(From != To && "Cannot replace uses of with self");
3205 while (!From->use_empty()) {
3206 // Process users until they are all gone.
3207 SDNode *U = *From->use_begin();
3209 // This node is about to morph, remove its old self from the CSE maps.
3210 RemoveNodeFromCSEMaps(U);
3212 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3214 if (I->Val == From) {
3215 From->removeUser(U);
3220 // Now that we have modified U, add it back to the CSE maps. If it already
3221 // exists there, recursively merge the results together.
3222 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3223 ReplaceAllUsesWith(U, Existing, Deleted);
3225 if (Deleted) Deleted->push_back(U);
3226 DeleteNodeNotInCSEMaps(U);
3231 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3232 /// This can cause recursive merging of nodes in the DAG.
3234 /// This version assumes From/To have matching types and numbers of result
3237 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3238 std::vector<SDNode*> *Deleted) {
3239 assert(From != To && "Cannot replace uses of with self");
3240 assert(From->getNumValues() == To->getNumValues() &&
3241 "Cannot use this version of ReplaceAllUsesWith!");
3242 if (From->getNumValues() == 1) { // If possible, use the faster version.
3243 ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
3247 while (!From->use_empty()) {
3248 // Process users until they are all gone.
3249 SDNode *U = *From->use_begin();
3251 // This node is about to morph, remove its old self from the CSE maps.
3252 RemoveNodeFromCSEMaps(U);
3254 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3256 if (I->Val == From) {
3257 From->removeUser(U);
3262 // Now that we have modified U, add it back to the CSE maps. If it already
3263 // exists there, recursively merge the results together.
3264 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3265 ReplaceAllUsesWith(U, Existing, Deleted);
3267 if (Deleted) Deleted->push_back(U);
3268 DeleteNodeNotInCSEMaps(U);
3273 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3274 /// This can cause recursive merging of nodes in the DAG.
3276 /// This version can replace From with any result values. To must match the
3277 /// number and types of values returned by From.
3278 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3279 const SDOperand *To,
3280 std::vector<SDNode*> *Deleted) {
3281 if (From->getNumValues() == 1 && To[0].Val->getNumValues() == 1) {
3282 // Degenerate case handled above.
3283 ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
3287 while (!From->use_empty()) {
3288 // Process users until they are all gone.
3289 SDNode *U = *From->use_begin();
3291 // This node is about to morph, remove its old self from the CSE maps.
3292 RemoveNodeFromCSEMaps(U);
3294 for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3296 if (I->Val == From) {
3297 const SDOperand &ToOp = To[I->ResNo];
3298 From->removeUser(U);
3300 ToOp.Val->addUser(U);
3303 // Now that we have modified U, add it back to the CSE maps. If it already
3304 // exists there, recursively merge the results together.
3305 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3306 ReplaceAllUsesWith(U, Existing, Deleted);
3308 if (Deleted) Deleted->push_back(U);
3309 DeleteNodeNotInCSEMaps(U);
3314 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3315 /// uses of other values produced by From.Val alone. The Deleted vector is
3316 /// handled the same was as for ReplaceAllUsesWith.
3317 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3318 std::vector<SDNode*> *Deleted) {
3319 assert(From != To && "Cannot replace a value with itself");
3320 // Handle the simple, trivial, case efficiently.
3321 if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
3322 ReplaceAllUsesWith(From, To, Deleted);
3326 // Get all of the users of From.Val. We want these in a nice,
3327 // deterministically ordered and uniqued set, so we use a SmallSetVector.
3328 SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
3330 std::vector<SDNode*> LocalDeletionVector;
3332 // Pick a deletion vector to use. If the user specified one, use theirs,
3333 // otherwise use a local one.
3334 std::vector<SDNode*> *DeleteVector = Deleted ? Deleted : &LocalDeletionVector;
3335 while (!Users.empty()) {
3336 // We know that this user uses some value of From. If it is the right
3337 // value, update it.
3338 SDNode *User = Users.back();
3341 // Scan for an operand that matches From.
3342 SDOperand *Op = User->OperandList, *E = User->OperandList+User->NumOperands;
3343 for (; Op != E; ++Op)
3344 if (*Op == From) break;
3346 // If there are no matches, the user must use some other result of From.
3347 if (Op == E) continue;
3349 // Okay, we know this user needs to be updated. Remove its old self
3350 // from the CSE maps.
3351 RemoveNodeFromCSEMaps(User);
3353 // Update all operands that match "From".
3354 for (; Op != E; ++Op) {
3356 From.Val->removeUser(User);
3358 To.Val->addUser(User);
3362 // Now that we have modified User, add it back to the CSE maps. If it
3363 // already exists there, recursively merge the results together.
3364 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
3365 if (!Existing) continue; // Continue on to next user.
3367 // If there was already an existing matching node, use ReplaceAllUsesWith
3368 // to replace the dead one with the existing one. However, this can cause
3369 // recursive merging of other unrelated nodes down the line. The merging
3370 // can cause deletion of nodes that used the old value. In this case,
3371 // we have to be certain to remove them from the Users set.
3372 unsigned NumDeleted = DeleteVector->size();
3373 ReplaceAllUsesWith(User, Existing, DeleteVector);
3375 // User is now dead.
3376 DeleteVector->push_back(User);
3377 DeleteNodeNotInCSEMaps(User);
3379 // We have to be careful here, because ReplaceAllUsesWith could have
3380 // deleted a user of From, which means there may be dangling pointers
3381 // in the "Users" setvector. Scan over the deleted node pointers and
3382 // remove them from the setvector.
3383 for (unsigned i = NumDeleted, e = DeleteVector->size(); i != e; ++i)
3384 Users.remove((*DeleteVector)[i]);
3386 // If the user doesn't need the set of deleted elements, don't retain them
3387 // to the next loop iteration.
3389 LocalDeletionVector.clear();
3394 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3395 /// their allnodes order. It returns the maximum id.
3396 unsigned SelectionDAG::AssignNodeIds() {
3398 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3405 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
3406 /// based on their topological order. It returns the maximum id and a vector
3407 /// of the SDNodes* in assigned order by reference.
3408 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
3409 unsigned DAGSize = AllNodes.size();
3410 std::vector<unsigned> InDegree(DAGSize);
3411 std::vector<SDNode*> Sources;
3413 // Use a two pass approach to avoid using a std::map which is slow.
3415 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
3418 unsigned Degree = N->use_size();
3419 InDegree[N->getNodeId()] = Degree;
3421 Sources.push_back(N);
3425 while (!Sources.empty()) {
3426 SDNode *N = Sources.back();
3428 TopOrder.push_back(N);
3429 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
3431 unsigned Degree = --InDegree[P->getNodeId()];
3433 Sources.push_back(P);
3437 // Second pass, assign the actual topological order as node ids.
3439 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
3441 (*TI)->setNodeId(Id++);
3448 //===----------------------------------------------------------------------===//
3450 //===----------------------------------------------------------------------===//
3452 // Out-of-line virtual method to give class a home.
3453 void SDNode::ANCHOR() {}
3454 void UnarySDNode::ANCHOR() {}
3455 void BinarySDNode::ANCHOR() {}
3456 void TernarySDNode::ANCHOR() {}
3457 void HandleSDNode::ANCHOR() {}
3458 void StringSDNode::ANCHOR() {}
3459 void ConstantSDNode::ANCHOR() {}
3460 void ConstantFPSDNode::ANCHOR() {}
3461 void GlobalAddressSDNode::ANCHOR() {}
3462 void FrameIndexSDNode::ANCHOR() {}
3463 void JumpTableSDNode::ANCHOR() {}
3464 void ConstantPoolSDNode::ANCHOR() {}
3465 void BasicBlockSDNode::ANCHOR() {}
3466 void SrcValueSDNode::ANCHOR() {}
3467 void MemOperandSDNode::ANCHOR() {}
3468 void RegisterSDNode::ANCHOR() {}
3469 void ExternalSymbolSDNode::ANCHOR() {}
3470 void CondCodeSDNode::ANCHOR() {}
3471 void VTSDNode::ANCHOR() {}
3472 void LoadSDNode::ANCHOR() {}
3473 void StoreSDNode::ANCHOR() {}
3475 HandleSDNode::~HandleSDNode() {
3476 SDVTList VTs = { 0, 0 };
3477 MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0); // Drops operand uses.
3480 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
3481 MVT::ValueType VT, int o)
3482 : SDNode(isa<GlobalVariable>(GA) &&
3483 cast<GlobalVariable>(GA)->isThreadLocal() ?
3485 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
3487 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
3488 getSDVTList(VT)), Offset(o) {
3489 TheGlobal = const_cast<GlobalValue*>(GA);
3492 /// getMemOperand - Return a MemOperand object describing the memory
3493 /// reference performed by this load or store.
3494 MemOperand LSBaseSDNode::getMemOperand() const {
3495 int Size = (MVT::getSizeInBits(getMemoryVT()) + 7) >> 3;
3497 getOpcode() == ISD::LOAD ? MemOperand::MOLoad : MemOperand::MOStore;
3498 if (IsVolatile) Flags |= MemOperand::MOVolatile;
3500 // Check if the load references a frame index, and does not have
3502 const FrameIndexSDNode *FI =
3503 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
3504 if (!getSrcValue() && FI)
3505 return MemOperand(&PseudoSourceValue::FPRel, Flags,
3506 FI->getIndex(), Size, Alignment);
3508 return MemOperand(getSrcValue(), Flags,
3509 getSrcValueOffset(), Size, Alignment);
3512 /// Profile - Gather unique data for the node.
3514 void SDNode::Profile(FoldingSetNodeID &ID) {
3515 AddNodeIDNode(ID, this);
3518 /// getValueTypeList - Return a pointer to the specified value type.
3520 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
3521 if (MVT::isExtendedVT(VT)) {
3522 static std::set<MVT::ValueType> EVTs;
3523 return (MVT::ValueType *)&(*EVTs.insert(VT).first);
3525 static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
3531 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
3532 /// indicated value. This method ignores uses of other values defined by this
3534 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
3535 assert(Value < getNumValues() && "Bad value!");
3537 // If there is only one value, this is easy.
3538 if (getNumValues() == 1)
3539 return use_size() == NUses;
3540 if (use_size() < NUses) return false;
3542 SDOperand TheValue(const_cast<SDNode *>(this), Value);
3544 SmallPtrSet<SDNode*, 32> UsersHandled;
3546 for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3548 if (User->getNumOperands() == 1 ||
3549 UsersHandled.insert(User)) // First time we've seen this?
3550 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3551 if (User->getOperand(i) == TheValue) {
3553 return false; // too many uses
3558 // Found exactly the right number of uses?
3563 /// hasAnyUseOfValue - Return true if there are any use of the indicated
3564 /// value. This method ignores uses of other values defined by this operation.
3565 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
3566 assert(Value < getNumValues() && "Bad value!");
3568 if (use_empty()) return false;
3570 SDOperand TheValue(const_cast<SDNode *>(this), Value);
3572 SmallPtrSet<SDNode*, 32> UsersHandled;
3574 for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3576 if (User->getNumOperands() == 1 ||
3577 UsersHandled.insert(User)) // First time we've seen this?
3578 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3579 if (User->getOperand(i) == TheValue) {
3588 /// isOnlyUse - Return true if this node is the only use of N.
3590 bool SDNode::isOnlyUse(SDNode *N) const {
3592 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
3603 /// isOperand - Return true if this node is an operand of N.
3605 bool SDOperand::isOperand(SDNode *N) const {
3606 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3607 if (*this == N->getOperand(i))
3612 bool SDNode::isOperand(SDNode *N) const {
3613 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
3614 if (this == N->OperandList[i].Val)
3619 /// reachesChainWithoutSideEffects - Return true if this operand (which must
3620 /// be a chain) reaches the specified operand without crossing any
3621 /// side-effecting instructions. In practice, this looks through token
3622 /// factors and non-volatile loads. In order to remain efficient, this only
3623 /// looks a couple of nodes in, it does not do an exhaustive search.
3624 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest,
3625 unsigned Depth) const {
3626 if (*this == Dest) return true;
3628 // Don't search too deeply, we just want to be able to see through
3629 // TokenFactor's etc.
3630 if (Depth == 0) return false;
3632 // If this is a token factor, all inputs to the TF happen in parallel. If any
3633 // of the operands of the TF reach dest, then we can do the xform.
3634 if (getOpcode() == ISD::TokenFactor) {
3635 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3636 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
3641 // Loads don't have side effects, look through them.
3642 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
3643 if (!Ld->isVolatile())
3644 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
3650 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
3651 SmallPtrSet<SDNode *, 32> &Visited) {
3652 if (found || !Visited.insert(N))
3655 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
3656 SDNode *Op = N->getOperand(i).Val;
3661 findPredecessor(Op, P, found, Visited);
3665 /// isPredecessor - Return true if this node is a predecessor of N. This node
3666 /// is either an operand of N or it can be reached by recursively traversing
3667 /// up the operands.
3668 /// NOTE: this is an expensive method. Use it carefully.
3669 bool SDNode::isPredecessor(SDNode *N) const {
3670 SmallPtrSet<SDNode *, 32> Visited;
3672 findPredecessor(N, this, found, Visited);
3676 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
3677 assert(Num < NumOperands && "Invalid child # of SDNode!");
3678 return cast<ConstantSDNode>(OperandList[Num])->getValue();
3681 std::string SDNode::getOperationName(const SelectionDAG *G) const {
3682 switch (getOpcode()) {
3684 if (getOpcode() < ISD::BUILTIN_OP_END)
3685 return "<<Unknown DAG Node>>";
3688 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
3689 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
3690 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
3692 TargetLowering &TLI = G->getTargetLoweringInfo();
3694 TLI.getTargetNodeName(getOpcode());
3695 if (Name) return Name;
3698 return "<<Unknown Target Node>>";
3701 case ISD::PCMARKER: return "PCMarker";
3702 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
3703 case ISD::SRCVALUE: return "SrcValue";
3704 case ISD::MEMOPERAND: return "MemOperand";
3705 case ISD::EntryToken: return "EntryToken";
3706 case ISD::TokenFactor: return "TokenFactor";
3707 case ISD::AssertSext: return "AssertSext";
3708 case ISD::AssertZext: return "AssertZext";
3710 case ISD::STRING: return "String";
3711 case ISD::BasicBlock: return "BasicBlock";
3712 case ISD::VALUETYPE: return "ValueType";
3713 case ISD::Register: return "Register";
3715 case ISD::Constant: return "Constant";
3716 case ISD::ConstantFP: return "ConstantFP";
3717 case ISD::GlobalAddress: return "GlobalAddress";
3718 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
3719 case ISD::FrameIndex: return "FrameIndex";
3720 case ISD::JumpTable: return "JumpTable";
3721 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
3722 case ISD::RETURNADDR: return "RETURNADDR";
3723 case ISD::FRAMEADDR: return "FRAMEADDR";
3724 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
3725 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
3726 case ISD::EHSELECTION: return "EHSELECTION";
3727 case ISD::EH_RETURN: return "EH_RETURN";
3728 case ISD::ConstantPool: return "ConstantPool";
3729 case ISD::ExternalSymbol: return "ExternalSymbol";
3730 case ISD::INTRINSIC_WO_CHAIN: {
3731 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
3732 return Intrinsic::getName((Intrinsic::ID)IID);
3734 case ISD::INTRINSIC_VOID:
3735 case ISD::INTRINSIC_W_CHAIN: {
3736 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
3737 return Intrinsic::getName((Intrinsic::ID)IID);
3740 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
3741 case ISD::TargetConstant: return "TargetConstant";
3742 case ISD::TargetConstantFP:return "TargetConstantFP";
3743 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
3744 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
3745 case ISD::TargetFrameIndex: return "TargetFrameIndex";
3746 case ISD::TargetJumpTable: return "TargetJumpTable";
3747 case ISD::TargetConstantPool: return "TargetConstantPool";
3748 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
3750 case ISD::CopyToReg: return "CopyToReg";
3751 case ISD::CopyFromReg: return "CopyFromReg";
3752 case ISD::UNDEF: return "undef";
3753 case ISD::MERGE_VALUES: return "merge_values";
3754 case ISD::INLINEASM: return "inlineasm";
3755 case ISD::LABEL: return "label";
3756 case ISD::HANDLENODE: return "handlenode";
3757 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
3758 case ISD::CALL: return "call";
3761 case ISD::FABS: return "fabs";
3762 case ISD::FNEG: return "fneg";
3763 case ISD::FSQRT: return "fsqrt";
3764 case ISD::FSIN: return "fsin";
3765 case ISD::FCOS: return "fcos";
3766 case ISD::FPOWI: return "fpowi";
3767 case ISD::FPOW: return "fpow";
3770 case ISD::ADD: return "add";
3771 case ISD::SUB: return "sub";
3772 case ISD::MUL: return "mul";
3773 case ISD::MULHU: return "mulhu";
3774 case ISD::MULHS: return "mulhs";
3775 case ISD::SDIV: return "sdiv";
3776 case ISD::UDIV: return "udiv";
3777 case ISD::SREM: return "srem";
3778 case ISD::UREM: return "urem";
3779 case ISD::SMUL_LOHI: return "smul_lohi";
3780 case ISD::UMUL_LOHI: return "umul_lohi";
3781 case ISD::SDIVREM: return "sdivrem";
3782 case ISD::UDIVREM: return "divrem";
3783 case ISD::AND: return "and";
3784 case ISD::OR: return "or";
3785 case ISD::XOR: return "xor";
3786 case ISD::SHL: return "shl";
3787 case ISD::SRA: return "sra";
3788 case ISD::SRL: return "srl";
3789 case ISD::ROTL: return "rotl";
3790 case ISD::ROTR: return "rotr";
3791 case ISD::FADD: return "fadd";
3792 case ISD::FSUB: return "fsub";
3793 case ISD::FMUL: return "fmul";
3794 case ISD::FDIV: return "fdiv";
3795 case ISD::FREM: return "frem";
3796 case ISD::FCOPYSIGN: return "fcopysign";
3797 case ISD::FGETSIGN: return "fgetsign";
3799 case ISD::SETCC: return "setcc";
3800 case ISD::SELECT: return "select";
3801 case ISD::SELECT_CC: return "select_cc";
3802 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
3803 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
3804 case ISD::CONCAT_VECTORS: return "concat_vectors";
3805 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
3806 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
3807 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
3808 case ISD::CARRY_FALSE: return "carry_false";
3809 case ISD::ADDC: return "addc";
3810 case ISD::ADDE: return "adde";
3811 case ISD::SUBC: return "subc";
3812 case ISD::SUBE: return "sube";
3813 case ISD::SHL_PARTS: return "shl_parts";
3814 case ISD::SRA_PARTS: return "sra_parts";
3815 case ISD::SRL_PARTS: return "srl_parts";
3817 case ISD::EXTRACT_SUBREG: return "extract_subreg";
3818 case ISD::INSERT_SUBREG: return "insert_subreg";
3820 // Conversion operators.
3821 case ISD::SIGN_EXTEND: return "sign_extend";
3822 case ISD::ZERO_EXTEND: return "zero_extend";
3823 case ISD::ANY_EXTEND: return "any_extend";
3824 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
3825 case ISD::TRUNCATE: return "truncate";
3826 case ISD::FP_ROUND: return "fp_round";
3827 case ISD::FLT_ROUNDS_: return "flt_rounds";
3828 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
3829 case ISD::FP_EXTEND: return "fp_extend";
3831 case ISD::SINT_TO_FP: return "sint_to_fp";
3832 case ISD::UINT_TO_FP: return "uint_to_fp";
3833 case ISD::FP_TO_SINT: return "fp_to_sint";
3834 case ISD::FP_TO_UINT: return "fp_to_uint";
3835 case ISD::BIT_CONVERT: return "bit_convert";
3837 // Control flow instructions
3838 case ISD::BR: return "br";
3839 case ISD::BRIND: return "brind";
3840 case ISD::BR_JT: return "br_jt";
3841 case ISD::BRCOND: return "brcond";
3842 case ISD::BR_CC: return "br_cc";
3843 case ISD::RET: return "ret";
3844 case ISD::CALLSEQ_START: return "callseq_start";
3845 case ISD::CALLSEQ_END: return "callseq_end";
3848 case ISD::LOAD: return "load";
3849 case ISD::STORE: return "store";
3850 case ISD::VAARG: return "vaarg";
3851 case ISD::VACOPY: return "vacopy";
3852 case ISD::VAEND: return "vaend";
3853 case ISD::VASTART: return "vastart";
3854 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
3855 case ISD::EXTRACT_ELEMENT: return "extract_element";
3856 case ISD::BUILD_PAIR: return "build_pair";
3857 case ISD::STACKSAVE: return "stacksave";
3858 case ISD::STACKRESTORE: return "stackrestore";
3859 case ISD::TRAP: return "trap";
3861 // Block memory operations.
3862 case ISD::MEMSET: return "memset";
3863 case ISD::MEMCPY: return "memcpy";
3864 case ISD::MEMMOVE: return "memmove";
3867 case ISD::BSWAP: return "bswap";
3868 case ISD::CTPOP: return "ctpop";
3869 case ISD::CTTZ: return "cttz";
3870 case ISD::CTLZ: return "ctlz";
3873 case ISD::LOCATION: return "location";
3874 case ISD::DEBUG_LOC: return "debug_loc";
3877 case ISD::TRAMPOLINE: return "trampoline";
3880 switch (cast<CondCodeSDNode>(this)->get()) {
3881 default: assert(0 && "Unknown setcc condition!");
3882 case ISD::SETOEQ: return "setoeq";
3883 case ISD::SETOGT: return "setogt";
3884 case ISD::SETOGE: return "setoge";
3885 case ISD::SETOLT: return "setolt";
3886 case ISD::SETOLE: return "setole";
3887 case ISD::SETONE: return "setone";
3889 case ISD::SETO: return "seto";
3890 case ISD::SETUO: return "setuo";
3891 case ISD::SETUEQ: return "setue";
3892 case ISD::SETUGT: return "setugt";
3893 case ISD::SETUGE: return "setuge";
3894 case ISD::SETULT: return "setult";
3895 case ISD::SETULE: return "setule";
3896 case ISD::SETUNE: return "setune";
3898 case ISD::SETEQ: return "seteq";
3899 case ISD::SETGT: return "setgt";
3900 case ISD::SETGE: return "setge";
3901 case ISD::SETLT: return "setlt";
3902 case ISD::SETLE: return "setle";
3903 case ISD::SETNE: return "setne";
3908 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
3917 return "<post-inc>";
3919 return "<post-dec>";
3923 void SDNode::dump() const { dump(0); }
3924 void SDNode::dump(const SelectionDAG *G) const {
3925 cerr << (void*)this << ": ";
3927 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
3929 if (getValueType(i) == MVT::Other)
3932 cerr << MVT::getValueTypeString(getValueType(i));
3934 cerr << " = " << getOperationName(G);
3937 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3938 if (i) cerr << ", ";
3939 cerr << (void*)getOperand(i).Val;
3940 if (unsigned RN = getOperand(i).ResNo)
3944 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
3945 SDNode *Mask = getOperand(2).Val;
3947 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
3949 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
3952 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
3957 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
3958 cerr << "<" << CSDN->getValue() << ">";
3959 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
3960 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
3961 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
3962 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
3963 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
3965 cerr << "<APFloat(";
3966 CSDN->getValueAPF().convertToAPInt().dump();
3969 } else if (const GlobalAddressSDNode *GADN =
3970 dyn_cast<GlobalAddressSDNode>(this)) {
3971 int offset = GADN->getOffset();
3973 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
3975 cerr << " + " << offset;
3977 cerr << " " << offset;
3978 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
3979 cerr << "<" << FIDN->getIndex() << ">";
3980 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
3981 cerr << "<" << JTDN->getIndex() << ">";
3982 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
3983 int offset = CP->getOffset();
3984 if (CP->isMachineConstantPoolEntry())
3985 cerr << "<" << *CP->getMachineCPVal() << ">";
3987 cerr << "<" << *CP->getConstVal() << ">";
3989 cerr << " + " << offset;
3991 cerr << " " << offset;
3992 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
3994 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
3996 cerr << LBB->getName() << " ";
3997 cerr << (const void*)BBDN->getBasicBlock() << ">";
3998 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
3999 if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
4000 cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
4002 cerr << " #" << R->getReg();
4004 } else if (const ExternalSymbolSDNode *ES =
4005 dyn_cast<ExternalSymbolSDNode>(this)) {
4006 cerr << "'" << ES->getSymbol() << "'";
4007 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4009 cerr << "<" << M->getValue() << ">";
4012 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4013 if (M->MO.getValue())
4014 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4016 cerr << "<null:" << M->MO.getOffset() << ">";
4017 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4018 cerr << ":" << MVT::getValueTypeString(N->getVT());
4019 } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4020 const Value *SrcValue = LD->getSrcValue();
4021 int SrcOffset = LD->getSrcValueOffset();
4027 cerr << ":" << SrcOffset << ">";
4030 switch (LD->getExtensionType()) {
4031 default: doExt = false; break;
4033 cerr << " <anyext ";
4043 cerr << MVT::getValueTypeString(LD->getMemoryVT()) << ">";
4045 const char *AM = getIndexedModeName(LD->getAddressingMode());
4048 if (LD->isVolatile())
4049 cerr << " <volatile>";
4050 cerr << " alignment=" << LD->getAlignment();
4051 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4052 const Value *SrcValue = ST->getSrcValue();
4053 int SrcOffset = ST->getSrcValueOffset();
4059 cerr << ":" << SrcOffset << ">";
4061 if (ST->isTruncatingStore())
4063 << MVT::getValueTypeString(ST->getMemoryVT()) << ">";
4065 const char *AM = getIndexedModeName(ST->getAddressingMode());
4068 if (ST->isVolatile())
4069 cerr << " <volatile>";
4070 cerr << " alignment=" << ST->getAlignment();
4074 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4075 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4076 if (N->getOperand(i).Val->hasOneUse())
4077 DumpNodes(N->getOperand(i).Val, indent+2, G);
4079 cerr << "\n" << std::string(indent+2, ' ')
4080 << (void*)N->getOperand(i).Val << ": <multiple use>";
4083 cerr << "\n" << std::string(indent, ' ');
4087 void SelectionDAG::dump() const {
4088 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4089 std::vector<const SDNode*> Nodes;
4090 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4094 std::sort(Nodes.begin(), Nodes.end());
4096 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4097 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4098 DumpNodes(Nodes[i], 2, this);
4101 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4106 const Type *ConstantPoolSDNode::getType() const {
4107 if (isMachineConstantPoolEntry())
4108 return Val.MachineCPVal->getType();
4109 return Val.ConstVal->getType();