1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/GlobalAlias.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/CallingConv.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/ADT/SetVector.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/StringExtras.h"
41 /// makeVTList - Return an instance of the SDVTList struct initialized with the
42 /// specified members.
43 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
44 SDVTList Res = {VTs, NumVTs};
48 static const fltSemantics *MVTToAPFloatSemantics(MVT::ValueType VT) {
50 default: assert(0 && "Unknown FP format");
51 case MVT::f32: return &APFloat::IEEEsingle;
52 case MVT::f64: return &APFloat::IEEEdouble;
53 case MVT::f80: return &APFloat::x87DoubleExtended;
54 case MVT::f128: return &APFloat::IEEEquad;
55 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
59 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
61 //===----------------------------------------------------------------------===//
62 // ConstantFPSDNode Class
63 //===----------------------------------------------------------------------===//
65 /// isExactlyValue - We don't rely on operator== working on double values, as
66 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
67 /// As such, this method can be used to do an exact bit-for-bit comparison of
68 /// two floating point values.
69 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
70 return Value.bitwiseIsEqual(V);
73 bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT,
75 assert(MVT::isFloatingPoint(VT) && "Can only convert between FP types");
77 // Anything can be extended to ppc long double.
78 if (VT == MVT::ppcf128)
81 // PPC long double cannot be shrunk to anything though.
82 if (&Val.getSemantics() == &APFloat::PPCDoubleDouble)
85 // convert modifies in place, so make a copy.
86 APFloat Val2 = APFloat(Val);
87 return Val2.convert(*MVTToAPFloatSemantics(VT),
88 APFloat::rmNearestTiesToEven) == APFloat::opOK;
91 //===----------------------------------------------------------------------===//
93 //===----------------------------------------------------------------------===//
95 /// isBuildVectorAllOnes - Return true if the specified node is a
96 /// BUILD_VECTOR where all of the elements are ~0 or undef.
97 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
98 // Look through a bit convert.
99 if (N->getOpcode() == ISD::BIT_CONVERT)
100 N = N->getOperand(0).Val;
102 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
104 unsigned i = 0, e = N->getNumOperands();
106 // Skip over all of the undef values.
107 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
110 // Do not accept an all-undef vector.
111 if (i == e) return false;
113 // Do not accept build_vectors that aren't all constants or which have non-~0
115 SDOperand NotZero = N->getOperand(i);
116 if (isa<ConstantSDNode>(NotZero)) {
117 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
119 } else if (isa<ConstantFPSDNode>(NotZero)) {
120 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
121 convertToAPInt().isAllOnesValue())
126 // Okay, we have at least one ~0 value, check to see if the rest match or are
128 for (++i; i != e; ++i)
129 if (N->getOperand(i) != NotZero &&
130 N->getOperand(i).getOpcode() != ISD::UNDEF)
136 /// isBuildVectorAllZeros - Return true if the specified node is a
137 /// BUILD_VECTOR where all of the elements are 0 or undef.
138 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
139 // Look through a bit convert.
140 if (N->getOpcode() == ISD::BIT_CONVERT)
141 N = N->getOperand(0).Val;
143 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
145 unsigned i = 0, e = N->getNumOperands();
147 // Skip over all of the undef values.
148 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
151 // Do not accept an all-undef vector.
152 if (i == e) return false;
154 // Do not accept build_vectors that aren't all constants or which have non-~0
156 SDOperand Zero = N->getOperand(i);
157 if (isa<ConstantSDNode>(Zero)) {
158 if (!cast<ConstantSDNode>(Zero)->isNullValue())
160 } else if (isa<ConstantFPSDNode>(Zero)) {
161 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
166 // Okay, we have at least one ~0 value, check to see if the rest match or are
168 for (++i; i != e; ++i)
169 if (N->getOperand(i) != Zero &&
170 N->getOperand(i).getOpcode() != ISD::UNDEF)
175 /// isScalarToVector - Return true if the specified node is a
176 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
177 /// element is not an undef.
178 bool ISD::isScalarToVector(const SDNode *N) {
179 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
182 if (N->getOpcode() != ISD::BUILD_VECTOR)
184 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
186 unsigned NumElems = N->getNumOperands();
187 for (unsigned i = 1; i < NumElems; ++i) {
188 SDOperand V = N->getOperand(i);
189 if (V.getOpcode() != ISD::UNDEF)
196 /// isDebugLabel - Return true if the specified node represents a debug
197 /// label (i.e. ISD::LABEL or TargetInstrInfo::LABEL node and third operand
199 bool ISD::isDebugLabel(const SDNode *N) {
201 if (N->getOpcode() == ISD::LABEL)
202 Zero = N->getOperand(2);
203 else if (N->isTargetOpcode() &&
204 N->getTargetOpcode() == TargetInstrInfo::LABEL)
205 // Chain moved to last operand.
206 Zero = N->getOperand(1);
209 return isa<ConstantSDNode>(Zero) && cast<ConstantSDNode>(Zero)->isNullValue();
212 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
213 /// when given the operation for (X op Y).
214 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
215 // To perform this operation, we just need to swap the L and G bits of the
217 unsigned OldL = (Operation >> 2) & 1;
218 unsigned OldG = (Operation >> 1) & 1;
219 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
220 (OldL << 1) | // New G bit
221 (OldG << 2)); // New L bit.
224 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
225 /// 'op' is a valid SetCC operation.
226 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
227 unsigned Operation = Op;
229 Operation ^= 7; // Flip L, G, E bits, but not U.
231 Operation ^= 15; // Flip all of the condition bits.
232 if (Operation > ISD::SETTRUE2)
233 Operation &= ~8; // Don't let N and U bits get set.
234 return ISD::CondCode(Operation);
238 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
239 /// signed operation and 2 if the result is an unsigned comparison. Return zero
240 /// if the operation does not depend on the sign of the input (setne and seteq).
241 static int isSignedOp(ISD::CondCode Opcode) {
243 default: assert(0 && "Illegal integer setcc operation!");
245 case ISD::SETNE: return 0;
249 case ISD::SETGE: return 1;
253 case ISD::SETUGE: return 2;
257 /// getSetCCOrOperation - Return the result of a logical OR between different
258 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
259 /// returns SETCC_INVALID if it is not possible to represent the resultant
261 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
263 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
264 // Cannot fold a signed integer setcc with an unsigned integer setcc.
265 return ISD::SETCC_INVALID;
267 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
269 // If the N and U bits get set then the resultant comparison DOES suddenly
270 // care about orderedness, and is true when ordered.
271 if (Op > ISD::SETTRUE2)
272 Op &= ~16; // Clear the U bit if the N bit is set.
274 // Canonicalize illegal integer setcc's.
275 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
278 return ISD::CondCode(Op);
281 /// getSetCCAndOperation - Return the result of a logical AND between different
282 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
283 /// function returns zero if it is not possible to represent the resultant
285 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
287 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
288 // Cannot fold a signed setcc with an unsigned setcc.
289 return ISD::SETCC_INVALID;
291 // Combine all of the condition bits.
292 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
294 // Canonicalize illegal integer setcc's.
298 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
299 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
300 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
301 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
308 const TargetMachine &SelectionDAG::getTarget() const {
309 return TLI.getTargetMachine();
312 //===----------------------------------------------------------------------===//
313 // SDNode Profile Support
314 //===----------------------------------------------------------------------===//
316 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
318 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
322 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
323 /// solely with their pointer.
324 void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
325 ID.AddPointer(VTList.VTs);
328 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
330 static void AddNodeIDOperands(FoldingSetNodeID &ID,
331 const SDOperand *Ops, unsigned NumOps) {
332 for (; NumOps; --NumOps, ++Ops) {
333 ID.AddPointer(Ops->Val);
334 ID.AddInteger(Ops->ResNo);
338 static void AddNodeIDNode(FoldingSetNodeID &ID,
339 unsigned short OpC, SDVTList VTList,
340 const SDOperand *OpList, unsigned N) {
341 AddNodeIDOpcode(ID, OpC);
342 AddNodeIDValueTypes(ID, VTList);
343 AddNodeIDOperands(ID, OpList, N);
346 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
348 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
349 AddNodeIDOpcode(ID, N->getOpcode());
350 // Add the return value info.
351 AddNodeIDValueTypes(ID, N->getVTList());
352 // Add the operand info.
353 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
355 // Handle SDNode leafs with special info.
356 switch (N->getOpcode()) {
357 default: break; // Normal nodes don't need extra info.
359 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
361 case ISD::TargetConstant:
363 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
365 case ISD::TargetConstantFP:
366 case ISD::ConstantFP: {
367 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
370 case ISD::TargetGlobalAddress:
371 case ISD::GlobalAddress:
372 case ISD::TargetGlobalTLSAddress:
373 case ISD::GlobalTLSAddress: {
374 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
375 ID.AddPointer(GA->getGlobal());
376 ID.AddInteger(GA->getOffset());
379 case ISD::BasicBlock:
380 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
383 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
386 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
388 case ISD::MEMOPERAND: {
389 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
390 ID.AddPointer(MO.getValue());
391 ID.AddInteger(MO.getFlags());
392 ID.AddInteger(MO.getOffset());
393 ID.AddInteger(MO.getSize());
394 ID.AddInteger(MO.getAlignment());
397 case ISD::FrameIndex:
398 case ISD::TargetFrameIndex:
399 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
402 case ISD::TargetJumpTable:
403 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
405 case ISD::ConstantPool:
406 case ISD::TargetConstantPool: {
407 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
408 ID.AddInteger(CP->getAlignment());
409 ID.AddInteger(CP->getOffset());
410 if (CP->isMachineConstantPoolEntry())
411 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
413 ID.AddPointer(CP->getConstVal());
417 LoadSDNode *LD = cast<LoadSDNode>(N);
418 ID.AddInteger(LD->getAddressingMode());
419 ID.AddInteger(LD->getExtensionType());
420 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
421 ID.AddInteger(LD->getAlignment());
422 ID.AddInteger(LD->isVolatile());
426 StoreSDNode *ST = cast<StoreSDNode>(N);
427 ID.AddInteger(ST->getAddressingMode());
428 ID.AddInteger(ST->isTruncatingStore());
429 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
430 ID.AddInteger(ST->getAlignment());
431 ID.AddInteger(ST->isVolatile());
437 //===----------------------------------------------------------------------===//
438 // SelectionDAG Class
439 //===----------------------------------------------------------------------===//
441 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
443 void SelectionDAG::RemoveDeadNodes() {
444 // Create a dummy node (which is not added to allnodes), that adds a reference
445 // to the root node, preventing it from being deleted.
446 HandleSDNode Dummy(getRoot());
448 SmallVector<SDNode*, 128> DeadNodes;
450 // Add all obviously-dead nodes to the DeadNodes worklist.
451 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
453 DeadNodes.push_back(I);
455 // Process the worklist, deleting the nodes and adding their uses to the
457 while (!DeadNodes.empty()) {
458 SDNode *N = DeadNodes.back();
459 DeadNodes.pop_back();
461 // Take the node out of the appropriate CSE map.
462 RemoveNodeFromCSEMaps(N);
464 // Next, brutally remove the operand list. This is safe to do, as there are
465 // no cycles in the graph.
466 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
467 SDNode *Operand = I->Val;
468 Operand->removeUser(std::distance(N->op_begin(), I), N);
470 // Now that we removed this operand, see if there are no uses of it left.
471 if (Operand->use_empty())
472 DeadNodes.push_back(Operand);
474 if (N->OperandsNeedDelete) {
475 delete[] N->OperandList;
480 // Finally, remove N itself.
484 // If the root changed (e.g. it was a dead load, update the root).
485 setRoot(Dummy.getValue());
488 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
489 SmallVector<SDNode*, 16> DeadNodes;
490 DeadNodes.push_back(N);
492 // Process the worklist, deleting the nodes and adding their uses to the
494 while (!DeadNodes.empty()) {
495 SDNode *N = DeadNodes.back();
496 DeadNodes.pop_back();
499 UpdateListener->NodeDeleted(N);
501 // Take the node out of the appropriate CSE map.
502 RemoveNodeFromCSEMaps(N);
504 // Next, brutally remove the operand list. This is safe to do, as there are
505 // no cycles in the graph.
506 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
507 SDNode *Operand = I->Val;
508 Operand->removeUser(std::distance(N->op_begin(), I), N);
510 // Now that we removed this operand, see if there are no uses of it left.
511 if (Operand->use_empty())
512 DeadNodes.push_back(Operand);
514 if (N->OperandsNeedDelete) {
515 delete[] N->OperandList;
520 // Finally, remove N itself.
525 void SelectionDAG::DeleteNode(SDNode *N) {
526 assert(N->use_empty() && "Cannot delete a node that is not dead!");
528 // First take this out of the appropriate CSE map.
529 RemoveNodeFromCSEMaps(N);
531 // Finally, remove uses due to operands of this node, remove from the
532 // AllNodes list, and delete the node.
533 DeleteNodeNotInCSEMaps(N);
536 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
538 // Remove it from the AllNodes list.
541 // Drop all of the operands and decrement used nodes use counts.
542 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
543 I->Val->removeUser(std::distance(N->op_begin(), I), N);
544 if (N->OperandsNeedDelete) {
545 delete[] N->OperandList;
553 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
554 /// correspond to it. This is useful when we're about to delete or repurpose
555 /// the node. We don't want future request for structurally identical nodes
556 /// to return N anymore.
557 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
559 switch (N->getOpcode()) {
560 case ISD::HANDLENODE: return; // noop.
562 Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
565 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
566 "Cond code doesn't exist!");
567 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
568 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
570 case ISD::ExternalSymbol:
571 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
573 case ISD::TargetExternalSymbol:
575 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
577 case ISD::VALUETYPE: {
578 MVT::ValueType VT = cast<VTSDNode>(N)->getVT();
579 if (MVT::isExtendedVT(VT)) {
580 Erased = ExtendedValueTypeNodes.erase(VT);
582 Erased = ValueTypeNodes[VT] != 0;
583 ValueTypeNodes[VT] = 0;
588 // Remove it from the CSE Map.
589 Erased = CSEMap.RemoveNode(N);
593 // Verify that the node was actually in one of the CSE maps, unless it has a
594 // flag result (which cannot be CSE'd) or is one of the special cases that are
595 // not subject to CSE.
596 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
597 !N->isTargetOpcode()) {
600 assert(0 && "Node is not in map!");
605 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
606 /// has been taken out and modified in some way. If the specified node already
607 /// exists in the CSE maps, do not modify the maps, but return the existing node
608 /// instead. If it doesn't exist, add it and return null.
610 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
611 assert(N->getNumOperands() && "This is a leaf node!");
612 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
613 return 0; // Never add these nodes.
615 // Check that remaining values produced are not flags.
616 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
617 if (N->getValueType(i) == MVT::Flag)
618 return 0; // Never CSE anything that produces a flag.
620 SDNode *New = CSEMap.GetOrInsertNode(N);
621 if (New != N) return New; // Node already existed.
625 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
626 /// were replaced with those specified. If this node is never memoized,
627 /// return null, otherwise return a pointer to the slot it would take. If a
628 /// node already exists with these operands, the slot will be non-null.
629 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
631 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
632 return 0; // Never add these nodes.
634 // Check that remaining values produced are not flags.
635 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
636 if (N->getValueType(i) == MVT::Flag)
637 return 0; // Never CSE anything that produces a flag.
639 SDOperand Ops[] = { Op };
641 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
642 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
645 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
646 /// were replaced with those specified. If this node is never memoized,
647 /// return null, otherwise return a pointer to the slot it would take. If a
648 /// node already exists with these operands, the slot will be non-null.
649 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
650 SDOperand Op1, SDOperand Op2,
652 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
653 return 0; // Never add these nodes.
655 // Check that remaining values produced are not flags.
656 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
657 if (N->getValueType(i) == MVT::Flag)
658 return 0; // Never CSE anything that produces a flag.
660 SDOperand Ops[] = { Op1, Op2 };
662 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
663 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
667 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
668 /// were replaced with those specified. If this node is never memoized,
669 /// return null, otherwise return a pointer to the slot it would take. If a
670 /// node already exists with these operands, the slot will be non-null.
671 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
672 const SDOperand *Ops,unsigned NumOps,
674 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
675 return 0; // Never add these nodes.
677 // Check that remaining values produced are not flags.
678 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
679 if (N->getValueType(i) == MVT::Flag)
680 return 0; // Never CSE anything that produces a flag.
683 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
685 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
686 ID.AddInteger(LD->getAddressingMode());
687 ID.AddInteger(LD->getExtensionType());
688 ID.AddInteger((unsigned int)(LD->getMemoryVT()));
689 ID.AddInteger(LD->getAlignment());
690 ID.AddInteger(LD->isVolatile());
691 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
692 ID.AddInteger(ST->getAddressingMode());
693 ID.AddInteger(ST->isTruncatingStore());
694 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
695 ID.AddInteger(ST->getAlignment());
696 ID.AddInteger(ST->isVolatile());
699 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
703 SelectionDAG::~SelectionDAG() {
704 while (!AllNodes.empty()) {
705 SDNode *N = AllNodes.begin();
706 N->SetNextInBucket(0);
707 if (N->OperandsNeedDelete) {
708 delete [] N->OperandList;
712 AllNodes.pop_front();
716 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
717 if (Op.getValueType() == VT) return Op;
718 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
719 MVT::getSizeInBits(VT));
720 return getNode(ISD::AND, Op.getValueType(), Op,
721 getConstant(Imm, Op.getValueType()));
724 SDOperand SelectionDAG::getString(const std::string &Val) {
725 StringSDNode *&N = StringNodes[Val];
727 N = new StringSDNode(Val);
728 AllNodes.push_back(N);
730 return SDOperand(N, 0);
733 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
734 MVT::ValueType EltVT =
735 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
737 return getConstant(APInt(MVT::getSizeInBits(EltVT), Val), VT, isT);
740 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT::ValueType VT, bool isT) {
741 assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
743 MVT::ValueType EltVT =
744 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
746 assert(Val.getBitWidth() == MVT::getSizeInBits(EltVT) &&
747 "APInt size does not match type size!");
749 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
751 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
755 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
756 if (!MVT::isVector(VT))
757 return SDOperand(N, 0);
759 N = new ConstantSDNode(isT, Val, EltVT);
760 CSEMap.InsertNode(N, IP);
761 AllNodes.push_back(N);
764 SDOperand Result(N, 0);
765 if (MVT::isVector(VT)) {
766 SmallVector<SDOperand, 8> Ops;
767 Ops.assign(MVT::getVectorNumElements(VT), Result);
768 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
773 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
774 return getConstant(Val, TLI.getPointerTy(), isTarget);
778 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
780 assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
782 MVT::ValueType EltVT =
783 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
785 // Do the map lookup using the actual bit pattern for the floating point
786 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
787 // we don't have issues with SNANs.
788 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
790 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
794 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
795 if (!MVT::isVector(VT))
796 return SDOperand(N, 0);
798 N = new ConstantFPSDNode(isTarget, V, EltVT);
799 CSEMap.InsertNode(N, IP);
800 AllNodes.push_back(N);
803 SDOperand Result(N, 0);
804 if (MVT::isVector(VT)) {
805 SmallVector<SDOperand, 8> Ops;
806 Ops.assign(MVT::getVectorNumElements(VT), Result);
807 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
812 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
814 MVT::ValueType EltVT =
815 MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
817 return getConstantFP(APFloat((float)Val), VT, isTarget);
819 return getConstantFP(APFloat(Val), VT, isTarget);
822 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
823 MVT::ValueType VT, int Offset,
827 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
829 // If GV is an alias then use the aliasee for determining thread-localness.
830 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
831 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
834 if (GVar && GVar->isThreadLocal())
835 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
837 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
840 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
842 ID.AddInteger(Offset);
844 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
845 return SDOperand(E, 0);
846 SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
847 CSEMap.InsertNode(N, IP);
848 AllNodes.push_back(N);
849 return SDOperand(N, 0);
852 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
854 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
856 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
859 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
860 return SDOperand(E, 0);
861 SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
862 CSEMap.InsertNode(N, IP);
863 AllNodes.push_back(N);
864 return SDOperand(N, 0);
867 SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
868 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
870 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
873 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
874 return SDOperand(E, 0);
875 SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
876 CSEMap.InsertNode(N, IP);
877 AllNodes.push_back(N);
878 return SDOperand(N, 0);
881 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
882 unsigned Alignment, int Offset,
884 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
886 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
887 ID.AddInteger(Alignment);
888 ID.AddInteger(Offset);
891 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
892 return SDOperand(E, 0);
893 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
894 CSEMap.InsertNode(N, IP);
895 AllNodes.push_back(N);
896 return SDOperand(N, 0);
900 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
902 unsigned Alignment, int Offset,
904 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
906 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
907 ID.AddInteger(Alignment);
908 ID.AddInteger(Offset);
909 C->AddSelectionDAGCSEId(ID);
911 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
912 return SDOperand(E, 0);
913 SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
914 CSEMap.InsertNode(N, IP);
915 AllNodes.push_back(N);
916 return SDOperand(N, 0);
920 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
922 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
925 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
926 return SDOperand(E, 0);
927 SDNode *N = new BasicBlockSDNode(MBB);
928 CSEMap.InsertNode(N, IP);
929 AllNodes.push_back(N);
930 return SDOperand(N, 0);
933 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
935 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
936 ID.AddInteger(Flags.getRawBits());
938 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
939 return SDOperand(E, 0);
940 SDNode *N = new ARG_FLAGSSDNode(Flags);
941 CSEMap.InsertNode(N, IP);
942 AllNodes.push_back(N);
943 return SDOperand(N, 0);
946 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
947 if (!MVT::isExtendedVT(VT) && (unsigned)VT >= ValueTypeNodes.size())
948 ValueTypeNodes.resize(VT+1);
950 SDNode *&N = MVT::isExtendedVT(VT) ?
951 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT];
953 if (N) return SDOperand(N, 0);
954 N = new VTSDNode(VT);
955 AllNodes.push_back(N);
956 return SDOperand(N, 0);
959 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
960 SDNode *&N = ExternalSymbols[Sym];
961 if (N) return SDOperand(N, 0);
962 N = new ExternalSymbolSDNode(false, Sym, VT);
963 AllNodes.push_back(N);
964 return SDOperand(N, 0);
967 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
969 SDNode *&N = TargetExternalSymbols[Sym];
970 if (N) return SDOperand(N, 0);
971 N = new ExternalSymbolSDNode(true, Sym, VT);
972 AllNodes.push_back(N);
973 return SDOperand(N, 0);
976 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
977 if ((unsigned)Cond >= CondCodeNodes.size())
978 CondCodeNodes.resize(Cond+1);
980 if (CondCodeNodes[Cond] == 0) {
981 CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
982 AllNodes.push_back(CondCodeNodes[Cond]);
984 return SDOperand(CondCodeNodes[Cond], 0);
987 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
989 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
990 ID.AddInteger(RegNo);
992 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
993 return SDOperand(E, 0);
994 SDNode *N = new RegisterSDNode(RegNo, VT);
995 CSEMap.InsertNode(N, IP);
996 AllNodes.push_back(N);
997 return SDOperand(N, 0);
1000 SDOperand SelectionDAG::getSrcValue(const Value *V) {
1001 assert((!V || isa<PointerType>(V->getType())) &&
1002 "SrcValue is not a pointer?");
1004 FoldingSetNodeID ID;
1005 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1009 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1010 return SDOperand(E, 0);
1012 SDNode *N = new SrcValueSDNode(V);
1013 CSEMap.InsertNode(N, IP);
1014 AllNodes.push_back(N);
1015 return SDOperand(N, 0);
1018 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1019 const Value *v = MO.getValue();
1020 assert((!v || isa<PointerType>(v->getType())) &&
1021 "SrcValue is not a pointer?");
1023 FoldingSetNodeID ID;
1024 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1026 ID.AddInteger(MO.getFlags());
1027 ID.AddInteger(MO.getOffset());
1028 ID.AddInteger(MO.getSize());
1029 ID.AddInteger(MO.getAlignment());
1032 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1033 return SDOperand(E, 0);
1035 SDNode *N = new MemOperandSDNode(MO);
1036 CSEMap.InsertNode(N, IP);
1037 AllNodes.push_back(N);
1038 return SDOperand(N, 0);
1041 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1042 /// specified value type.
1043 SDOperand SelectionDAG::CreateStackTemporary(MVT::ValueType VT) {
1044 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1045 unsigned ByteSize = MVT::getSizeInBits(VT)/8;
1046 const Type *Ty = MVT::getTypeForValueType(VT);
1047 unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
1048 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1049 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1053 SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
1054 SDOperand N2, ISD::CondCode Cond) {
1055 // These setcc operations always fold.
1059 case ISD::SETFALSE2: return getConstant(0, VT);
1061 case ISD::SETTRUE2: return getConstant(1, VT);
1073 assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
1077 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1078 const APInt &C2 = N2C->getAPIntValue();
1079 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1080 const APInt &C1 = N1C->getAPIntValue();
1083 default: assert(0 && "Unknown integer setcc!");
1084 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1085 case ISD::SETNE: return getConstant(C1 != C2, VT);
1086 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1087 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1088 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1089 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1090 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1091 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1092 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1093 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1097 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1098 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1099 // No compile time operations on this type yet.
1100 if (N1C->getValueType(0) == MVT::ppcf128)
1103 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1106 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1107 return getNode(ISD::UNDEF, VT);
1109 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1110 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1111 return getNode(ISD::UNDEF, VT);
1113 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1114 R==APFloat::cmpLessThan, VT);
1115 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1116 return getNode(ISD::UNDEF, VT);
1118 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1119 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1120 return getNode(ISD::UNDEF, VT);
1122 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1123 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1124 return getNode(ISD::UNDEF, VT);
1126 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1127 R==APFloat::cmpEqual, VT);
1128 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1129 return getNode(ISD::UNDEF, VT);
1131 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1132 R==APFloat::cmpEqual, VT);
1133 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1134 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1135 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1136 R==APFloat::cmpEqual, VT);
1137 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1138 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1139 R==APFloat::cmpLessThan, VT);
1140 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1141 R==APFloat::cmpUnordered, VT);
1142 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1143 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1146 // Ensure that the constant occurs on the RHS.
1147 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1151 // Could not fold it.
1155 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1156 /// use this predicate to simplify operations downstream.
1157 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1158 unsigned BitWidth = Op.getValueSizeInBits();
1159 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1162 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1163 /// this predicate to simplify operations downstream. Mask is known to be zero
1164 /// for bits that V cannot have.
1165 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask,
1166 unsigned Depth) const {
1167 APInt KnownZero, KnownOne;
1168 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1169 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1170 return (KnownZero & Mask) == Mask;
1173 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1174 /// known to be either zero or one and return them in the KnownZero/KnownOne
1175 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1177 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask,
1178 APInt &KnownZero, APInt &KnownOne,
1179 unsigned Depth) const {
1180 unsigned BitWidth = Mask.getBitWidth();
1181 assert(BitWidth == MVT::getSizeInBits(Op.getValueType()) &&
1182 "Mask size mismatches value type size!");
1184 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1185 if (Depth == 6 || Mask == 0)
1186 return; // Limit search depth.
1188 APInt KnownZero2, KnownOne2;
1190 switch (Op.getOpcode()) {
1192 // We know all of the bits for a constant!
1193 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1194 KnownZero = ~KnownOne & Mask;
1197 // If either the LHS or the RHS are Zero, the result is zero.
1198 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1199 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1200 KnownZero2, KnownOne2, Depth+1);
1201 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1202 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1204 // Output known-1 bits are only known if set in both the LHS & RHS.
1205 KnownOne &= KnownOne2;
1206 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1207 KnownZero |= KnownZero2;
1210 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1211 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1212 KnownZero2, KnownOne2, Depth+1);
1213 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1214 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1216 // Output known-0 bits are only known if clear in both the LHS & RHS.
1217 KnownZero &= KnownZero2;
1218 // Output known-1 are known to be set if set in either the LHS | RHS.
1219 KnownOne |= KnownOne2;
1222 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1223 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1224 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1225 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1227 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1228 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1229 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1230 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1231 KnownZero = KnownZeroOut;
1235 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1236 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1237 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1238 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1240 // Only known if known in both the LHS and RHS.
1241 KnownOne &= KnownOne2;
1242 KnownZero &= KnownZero2;
1244 case ISD::SELECT_CC:
1245 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1246 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1247 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1248 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1250 // Only known if known in both the LHS and RHS.
1251 KnownOne &= KnownOne2;
1252 KnownZero &= KnownZero2;
1255 // If we know the result of a setcc has the top bits zero, use this info.
1256 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1258 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1261 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1262 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1263 unsigned ShAmt = SA->getValue();
1265 // If the shift count is an invalid immediate, don't do anything.
1266 if (ShAmt >= BitWidth)
1269 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1270 KnownZero, KnownOne, Depth+1);
1271 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1272 KnownZero <<= ShAmt;
1274 // low bits known zero.
1275 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1279 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1280 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1281 unsigned ShAmt = SA->getValue();
1283 // If the shift count is an invalid immediate, don't do anything.
1284 if (ShAmt >= BitWidth)
1287 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1288 KnownZero, KnownOne, Depth+1);
1289 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1290 KnownZero = KnownZero.lshr(ShAmt);
1291 KnownOne = KnownOne.lshr(ShAmt);
1293 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1294 KnownZero |= HighBits; // High bits known zero.
1298 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1299 unsigned ShAmt = SA->getValue();
1301 // If the shift count is an invalid immediate, don't do anything.
1302 if (ShAmt >= BitWidth)
1305 APInt InDemandedMask = (Mask << ShAmt);
1306 // If any of the demanded bits are produced by the sign extension, we also
1307 // demand the input sign bit.
1308 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1309 if (HighBits.getBoolValue())
1310 InDemandedMask |= APInt::getSignBit(BitWidth);
1312 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1314 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1315 KnownZero = KnownZero.lshr(ShAmt);
1316 KnownOne = KnownOne.lshr(ShAmt);
1318 // Handle the sign bits.
1319 APInt SignBit = APInt::getSignBit(BitWidth);
1320 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1322 if (KnownZero.intersects(SignBit)) {
1323 KnownZero |= HighBits; // New bits are known zero.
1324 } else if (KnownOne.intersects(SignBit)) {
1325 KnownOne |= HighBits; // New bits are known one.
1329 case ISD::SIGN_EXTEND_INREG: {
1330 MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1331 unsigned EBits = MVT::getSizeInBits(EVT);
1333 // Sign extension. Compute the demanded bits in the result that are not
1334 // present in the input.
1335 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1337 APInt InSignBit = APInt::getSignBit(EBits);
1338 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1340 // If the sign extended bits are demanded, we know that the sign
1342 InSignBit.zext(BitWidth);
1343 if (NewBits.getBoolValue())
1344 InputDemandedBits |= InSignBit;
1346 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1347 KnownZero, KnownOne, Depth+1);
1348 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1350 // If the sign bit of the input is known set or clear, then we know the
1351 // top bits of the result.
1352 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1353 KnownZero |= NewBits;
1354 KnownOne &= ~NewBits;
1355 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1356 KnownOne |= NewBits;
1357 KnownZero &= ~NewBits;
1358 } else { // Input sign bit unknown
1359 KnownZero &= ~NewBits;
1360 KnownOne &= ~NewBits;
1367 unsigned LowBits = Log2_32(BitWidth)+1;
1368 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1369 KnownOne = APInt(BitWidth, 0);
1373 if (ISD::isZEXTLoad(Op.Val)) {
1374 LoadSDNode *LD = cast<LoadSDNode>(Op);
1375 MVT::ValueType VT = LD->getMemoryVT();
1376 unsigned MemBits = MVT::getSizeInBits(VT);
1377 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1381 case ISD::ZERO_EXTEND: {
1382 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1383 unsigned InBits = MVT::getSizeInBits(InVT);
1384 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1385 APInt InMask = Mask;
1386 InMask.trunc(InBits);
1387 KnownZero.trunc(InBits);
1388 KnownOne.trunc(InBits);
1389 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1390 KnownZero.zext(BitWidth);
1391 KnownOne.zext(BitWidth);
1392 KnownZero |= NewBits;
1395 case ISD::SIGN_EXTEND: {
1396 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1397 unsigned InBits = MVT::getSizeInBits(InVT);
1398 APInt InSignBit = APInt::getSignBit(InBits);
1399 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1400 APInt InMask = Mask;
1401 InMask.trunc(InBits);
1403 // If any of the sign extended bits are demanded, we know that the sign
1404 // bit is demanded. Temporarily set this bit in the mask for our callee.
1405 if (NewBits.getBoolValue())
1406 InMask |= InSignBit;
1408 KnownZero.trunc(InBits);
1409 KnownOne.trunc(InBits);
1410 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1412 // Note if the sign bit is known to be zero or one.
1413 bool SignBitKnownZero = KnownZero.isNegative();
1414 bool SignBitKnownOne = KnownOne.isNegative();
1415 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1416 "Sign bit can't be known to be both zero and one!");
1418 // If the sign bit wasn't actually demanded by our caller, we don't
1419 // want it set in the KnownZero and KnownOne result values. Reset the
1420 // mask and reapply it to the result values.
1422 InMask.trunc(InBits);
1423 KnownZero &= InMask;
1426 KnownZero.zext(BitWidth);
1427 KnownOne.zext(BitWidth);
1429 // If the sign bit is known zero or one, the top bits match.
1430 if (SignBitKnownZero)
1431 KnownZero |= NewBits;
1432 else if (SignBitKnownOne)
1433 KnownOne |= NewBits;
1436 case ISD::ANY_EXTEND: {
1437 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1438 unsigned InBits = MVT::getSizeInBits(InVT);
1439 APInt InMask = Mask;
1440 InMask.trunc(InBits);
1441 KnownZero.trunc(InBits);
1442 KnownOne.trunc(InBits);
1443 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1444 KnownZero.zext(BitWidth);
1445 KnownOne.zext(BitWidth);
1448 case ISD::TRUNCATE: {
1449 MVT::ValueType InVT = Op.getOperand(0).getValueType();
1450 unsigned InBits = MVT::getSizeInBits(InVT);
1451 APInt InMask = Mask;
1452 InMask.zext(InBits);
1453 KnownZero.zext(InBits);
1454 KnownOne.zext(InBits);
1455 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1456 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1457 KnownZero.trunc(BitWidth);
1458 KnownOne.trunc(BitWidth);
1461 case ISD::AssertZext: {
1462 MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1463 APInt InMask = APInt::getLowBitsSet(BitWidth, MVT::getSizeInBits(VT));
1464 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1466 KnownZero |= (~InMask) & Mask;
1470 // All bits are zero except the low bit.
1471 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1475 // If either the LHS or the RHS are Zero, the result is zero.
1476 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1477 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1478 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1479 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1481 // Output known-0 bits are known if clear or set in both the low clear bits
1482 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1483 // low 3 bits clear.
1484 unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(),
1485 KnownZero2.countTrailingOnes());
1487 KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1488 KnownOne = APInt(BitWidth, 0);
1492 ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1495 // We know that the top bits of C-X are clear if X contains less bits
1496 // than C (i.e. no wrap-around can happen). For example, 20-X is
1497 // positive if we can prove that X is >= 0 and < 16.
1498 if (CLHS->getAPIntValue().isNonNegative()) {
1499 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1500 // NLZ can't be BitWidth with no sign bit
1501 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1502 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
1504 // If all of the MaskV bits are known to be zero, then we know the output
1505 // top bits are zero, because we now know that the output is from [0-C].
1506 if ((KnownZero & MaskV) == MaskV) {
1507 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1508 // Top bits known zero.
1509 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1510 KnownOne = APInt(BitWidth, 0); // No one bits known.
1512 KnownZero = KnownOne = APInt(BitWidth, 0); // Otherwise, nothing known.
1518 // Allow the target to implement this method for its nodes.
1519 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1520 case ISD::INTRINSIC_WO_CHAIN:
1521 case ISD::INTRINSIC_W_CHAIN:
1522 case ISD::INTRINSIC_VOID:
1523 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1529 /// ComputeNumSignBits - Return the number of times the sign bit of the
1530 /// register is replicated into the other bits. We know that at least 1 bit
1531 /// is always equal to the sign bit (itself), but other cases can give us
1532 /// information. For example, immediately after an "SRA X, 2", we know that
1533 /// the top 3 bits are all equal to each other, so we return 3.
1534 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1535 MVT::ValueType VT = Op.getValueType();
1536 assert(MVT::isInteger(VT) && "Invalid VT!");
1537 unsigned VTBits = MVT::getSizeInBits(VT);
1541 return 1; // Limit search depth.
1543 switch (Op.getOpcode()) {
1545 case ISD::AssertSext:
1546 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1547 return VTBits-Tmp+1;
1548 case ISD::AssertZext:
1549 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1552 case ISD::Constant: {
1553 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1554 // If negative, return # leading ones.
1555 if (Val.isNegative())
1556 return Val.countLeadingOnes();
1558 // Return # leading zeros.
1559 return Val.countLeadingZeros();
1562 case ISD::SIGN_EXTEND:
1563 Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1564 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1566 case ISD::SIGN_EXTEND_INREG:
1567 // Max of the input and what this extends.
1568 Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1571 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1572 return std::max(Tmp, Tmp2);
1575 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1576 // SRA X, C -> adds C sign bits.
1577 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1578 Tmp += C->getValue();
1579 if (Tmp > VTBits) Tmp = VTBits;
1583 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1584 // shl destroys sign bits.
1585 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1586 if (C->getValue() >= VTBits || // Bad shift.
1587 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1588 return Tmp - C->getValue();
1593 case ISD::XOR: // NOT is handled here.
1594 // Logical binary ops preserve the number of sign bits.
1595 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1596 if (Tmp == 1) return 1; // Early out.
1597 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1598 return std::min(Tmp, Tmp2);
1601 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1602 if (Tmp == 1) return 1; // Early out.
1603 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1604 return std::min(Tmp, Tmp2);
1607 // If setcc returns 0/-1, all bits are sign bits.
1608 if (TLI.getSetCCResultContents() ==
1609 TargetLowering::ZeroOrNegativeOneSetCCResult)
1614 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1615 unsigned RotAmt = C->getValue() & (VTBits-1);
1617 // Handle rotate right by N like a rotate left by 32-N.
1618 if (Op.getOpcode() == ISD::ROTR)
1619 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1621 // If we aren't rotating out all of the known-in sign bits, return the
1622 // number that are left. This handles rotl(sext(x), 1) for example.
1623 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1624 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1628 // Add can have at most one carry bit. Thus we know that the output
1629 // is, at worst, one more bit than the inputs.
1630 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1631 if (Tmp == 1) return 1; // Early out.
1633 // Special case decrementing a value (ADD X, -1):
1634 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1635 if (CRHS->isAllOnesValue()) {
1636 APInt KnownZero, KnownOne;
1637 APInt Mask = APInt::getAllOnesValue(VTBits);
1638 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1640 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1642 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1645 // If we are subtracting one from a positive number, there is no carry
1646 // out of the result.
1647 if (KnownZero.isNegative())
1651 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1652 if (Tmp2 == 1) return 1;
1653 return std::min(Tmp, Tmp2)-1;
1657 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1658 if (Tmp2 == 1) return 1;
1661 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1662 if (CLHS->isNullValue()) {
1663 APInt KnownZero, KnownOne;
1664 APInt Mask = APInt::getAllOnesValue(VTBits);
1665 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1666 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1668 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1671 // If the input is known to be positive (the sign bit is known clear),
1672 // the output of the NEG has the same number of sign bits as the input.
1673 if (KnownZero.isNegative())
1676 // Otherwise, we treat this like a SUB.
1679 // Sub can have at most one carry bit. Thus we know that the output
1680 // is, at worst, one more bit than the inputs.
1681 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1682 if (Tmp == 1) return 1; // Early out.
1683 return std::min(Tmp, Tmp2)-1;
1686 // FIXME: it's tricky to do anything useful for this, but it is an important
1687 // case for targets like X86.
1691 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1692 if (Op.getOpcode() == ISD::LOAD) {
1693 LoadSDNode *LD = cast<LoadSDNode>(Op);
1694 unsigned ExtType = LD->getExtensionType();
1697 case ISD::SEXTLOAD: // '17' bits known
1698 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1699 return VTBits-Tmp+1;
1700 case ISD::ZEXTLOAD: // '16' bits known
1701 Tmp = MVT::getSizeInBits(LD->getMemoryVT());
1706 // Allow the target to implement this method for its nodes.
1707 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1708 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1709 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1710 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1711 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1712 if (NumBits > 1) return NumBits;
1715 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1716 // use this information.
1717 APInt KnownZero, KnownOne;
1718 APInt Mask = APInt::getAllOnesValue(VTBits);
1719 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1721 if (KnownZero.isNegative()) { // sign bit is 0
1723 } else if (KnownOne.isNegative()) { // sign bit is 1;
1730 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1731 // the number of identical bits in the top of the input value.
1733 Mask <<= Mask.getBitWidth()-VTBits;
1734 // Return # leading zeros. We use 'min' here in case Val was zero before
1735 // shifting. We don't want to return '64' as for an i32 "0".
1736 return std::min(VTBits, Mask.countLeadingZeros());
1740 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1741 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1742 if (!GA) return false;
1743 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1744 if (!GV) return false;
1745 MachineModuleInfo *MMI = getMachineModuleInfo();
1746 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1750 /// getNode - Gets or creates the specified node.
1752 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1753 FoldingSetNodeID ID;
1754 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1756 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1757 return SDOperand(E, 0);
1758 SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1759 CSEMap.InsertNode(N, IP);
1761 AllNodes.push_back(N);
1762 return SDOperand(N, 0);
1765 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1766 SDOperand Operand) {
1767 // Constant fold unary operations with an integer constant operand.
1768 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1769 const APInt &Val = C->getAPIntValue();
1770 unsigned BitWidth = MVT::getSizeInBits(VT);
1773 case ISD::SIGN_EXTEND:
1774 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1775 case ISD::ANY_EXTEND:
1776 case ISD::ZERO_EXTEND:
1778 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1779 case ISD::UINT_TO_FP:
1780 case ISD::SINT_TO_FP: {
1781 const uint64_t zero[] = {0, 0};
1782 // No compile time operations on this type.
1783 if (VT==MVT::ppcf128)
1785 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1786 (void)apf.convertFromAPInt(Val,
1787 Opcode==ISD::SINT_TO_FP,
1788 APFloat::rmNearestTiesToEven);
1789 return getConstantFP(apf, VT);
1791 case ISD::BIT_CONVERT:
1792 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1793 return getConstantFP(Val.bitsToFloat(), VT);
1794 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1795 return getConstantFP(Val.bitsToDouble(), VT);
1798 return getConstant(Val.byteSwap(), VT);
1800 return getConstant(Val.countPopulation(), VT);
1802 return getConstant(Val.countLeadingZeros(), VT);
1804 return getConstant(Val.countTrailingZeros(), VT);
1808 // Constant fold unary operations with a floating point constant operand.
1809 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1810 APFloat V = C->getValueAPF(); // make copy
1811 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1815 return getConstantFP(V, VT);
1818 return getConstantFP(V, VT);
1820 case ISD::FP_EXTEND:
1821 // This can return overflow, underflow, or inexact; we don't care.
1822 // FIXME need to be more flexible about rounding mode.
1823 (void)V.convert(*MVTToAPFloatSemantics(VT),
1824 APFloat::rmNearestTiesToEven);
1825 return getConstantFP(V, VT);
1826 case ISD::FP_TO_SINT:
1827 case ISD::FP_TO_UINT: {
1829 assert(integerPartWidth >= 64);
1830 // FIXME need to be more flexible about rounding mode.
1831 APFloat::opStatus s = V.convertToInteger(&x, 64U,
1832 Opcode==ISD::FP_TO_SINT,
1833 APFloat::rmTowardZero);
1834 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
1836 return getConstant(x, VT);
1838 case ISD::BIT_CONVERT:
1839 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1840 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1841 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1842 return getConstant(V.convertToAPInt().getZExtValue(), VT);
1848 unsigned OpOpcode = Operand.Val->getOpcode();
1850 case ISD::TokenFactor:
1851 return Operand; // Factor of one node? No factor.
1852 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1853 case ISD::FP_EXTEND:
1854 assert(MVT::isFloatingPoint(VT) &&
1855 MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1856 if (Operand.getValueType() == VT) return Operand; // noop conversion.
1857 if (Operand.getOpcode() == ISD::UNDEF)
1858 return getNode(ISD::UNDEF, VT);
1860 case ISD::SIGN_EXTEND:
1861 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1862 "Invalid SIGN_EXTEND!");
1863 if (Operand.getValueType() == VT) return Operand; // noop extension
1864 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1865 && "Invalid sext node, dst < src!");
1866 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1867 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1869 case ISD::ZERO_EXTEND:
1870 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1871 "Invalid ZERO_EXTEND!");
1872 if (Operand.getValueType() == VT) return Operand; // noop extension
1873 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1874 && "Invalid zext node, dst < src!");
1875 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
1876 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1878 case ISD::ANY_EXTEND:
1879 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1880 "Invalid ANY_EXTEND!");
1881 if (Operand.getValueType() == VT) return Operand; // noop extension
1882 assert(MVT::getSizeInBits(Operand.getValueType()) < MVT::getSizeInBits(VT)
1883 && "Invalid anyext node, dst < src!");
1884 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1885 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
1886 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1889 assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1890 "Invalid TRUNCATE!");
1891 if (Operand.getValueType() == VT) return Operand; // noop truncate
1892 assert(MVT::getSizeInBits(Operand.getValueType()) > MVT::getSizeInBits(VT)
1893 && "Invalid truncate node, src < dst!");
1894 if (OpOpcode == ISD::TRUNCATE)
1895 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1896 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1897 OpOpcode == ISD::ANY_EXTEND) {
1898 // If the source is smaller than the dest, we still need an extend.
1899 if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1900 < MVT::getSizeInBits(VT))
1901 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1902 else if (MVT::getSizeInBits(Operand.Val->getOperand(0).getValueType())
1903 > MVT::getSizeInBits(VT))
1904 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1906 return Operand.Val->getOperand(0);
1909 case ISD::BIT_CONVERT:
1910 // Basic sanity checking.
1911 assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1912 && "Cannot BIT_CONVERT between types of different sizes!");
1913 if (VT == Operand.getValueType()) return Operand; // noop conversion.
1914 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
1915 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1916 if (OpOpcode == ISD::UNDEF)
1917 return getNode(ISD::UNDEF, VT);
1919 case ISD::SCALAR_TO_VECTOR:
1920 assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1921 MVT::getVectorElementType(VT) == Operand.getValueType() &&
1922 "Illegal SCALAR_TO_VECTOR node!");
1923 if (OpOpcode == ISD::UNDEF)
1924 return getNode(ISD::UNDEF, VT);
1925 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
1926 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
1927 isa<ConstantSDNode>(Operand.getOperand(1)) &&
1928 Operand.getConstantOperandVal(1) == 0 &&
1929 Operand.getOperand(0).getValueType() == VT)
1930 return Operand.getOperand(0);
1933 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
1934 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1935 Operand.Val->getOperand(0));
1936 if (OpOpcode == ISD::FNEG) // --X -> X
1937 return Operand.Val->getOperand(0);
1940 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
1941 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1946 SDVTList VTs = getVTList(VT);
1947 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1948 FoldingSetNodeID ID;
1949 SDOperand Ops[1] = { Operand };
1950 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
1952 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1953 return SDOperand(E, 0);
1954 N = new UnarySDNode(Opcode, VTs, Operand);
1955 CSEMap.InsertNode(N, IP);
1957 N = new UnarySDNode(Opcode, VTs, Operand);
1959 AllNodes.push_back(N);
1960 return SDOperand(N, 0);
1965 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1966 SDOperand N1, SDOperand N2) {
1967 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1968 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1971 case ISD::TokenFactor:
1972 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1973 N2.getValueType() == MVT::Other && "Invalid token factor!");
1974 // Fold trivial token factors.
1975 if (N1.getOpcode() == ISD::EntryToken) return N2;
1976 if (N2.getOpcode() == ISD::EntryToken) return N1;
1979 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1980 N1.getValueType() == VT && "Binary operator types must match!");
1981 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
1982 // worth handling here.
1983 if (N2C && N2C->isNullValue())
1985 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
1990 assert(MVT::isInteger(VT) && N1.getValueType() == N2.getValueType() &&
1991 N1.getValueType() == VT && "Binary operator types must match!");
1992 // (X ^| 0) -> X. This commonly occurs when legalizing i64 values, so it's
1993 // worth handling here.
1994 if (N2C && N2C->isNullValue())
2001 assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
2013 assert(N1.getValueType() == N2.getValueType() &&
2014 N1.getValueType() == VT && "Binary operator types must match!");
2016 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2017 assert(N1.getValueType() == VT &&
2018 MVT::isFloatingPoint(N1.getValueType()) &&
2019 MVT::isFloatingPoint(N2.getValueType()) &&
2020 "Invalid FCOPYSIGN!");
2027 assert(VT == N1.getValueType() &&
2028 "Shift operators return type must be the same as their first arg");
2029 assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
2030 VT != MVT::i1 && "Shifts only work on integers");
2032 case ISD::FP_ROUND_INREG: {
2033 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2034 assert(VT == N1.getValueType() && "Not an inreg round!");
2035 assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
2036 "Cannot FP_ROUND_INREG integer types");
2037 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2038 "Not rounding down!");
2039 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2043 assert(MVT::isFloatingPoint(VT) &&
2044 MVT::isFloatingPoint(N1.getValueType()) &&
2045 MVT::getSizeInBits(VT) <= MVT::getSizeInBits(N1.getValueType()) &&
2046 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2047 if (N1.getValueType() == VT) return N1; // noop conversion.
2049 case ISD::AssertSext:
2050 case ISD::AssertZext: {
2051 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2052 assert(VT == N1.getValueType() && "Not an inreg extend!");
2053 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2054 "Cannot *_EXTEND_INREG FP types");
2055 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2057 if (VT == EVT) return N1; // noop assertion.
2060 case ISD::SIGN_EXTEND_INREG: {
2061 MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2062 assert(VT == N1.getValueType() && "Not an inreg extend!");
2063 assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
2064 "Cannot *_EXTEND_INREG FP types");
2065 assert(MVT::getSizeInBits(EVT) <= MVT::getSizeInBits(VT) &&
2067 if (EVT == VT) return N1; // Not actually extending
2070 APInt Val = N1C->getAPIntValue();
2071 unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
2072 Val <<= Val.getBitWidth()-FromBits;
2073 Val = Val.ashr(Val.getBitWidth()-FromBits);
2074 return getConstant(Val, VT);
2078 case ISD::EXTRACT_VECTOR_ELT:
2079 assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2081 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2082 if (N1.getOpcode() == ISD::UNDEF)
2083 return getNode(ISD::UNDEF, VT);
2085 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2086 // expanding copies of large vectors from registers.
2087 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2088 N1.getNumOperands() > 0) {
2090 MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2091 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2092 N1.getOperand(N2C->getValue() / Factor),
2093 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2096 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2097 // expanding large vector constants.
2098 if (N1.getOpcode() == ISD::BUILD_VECTOR)
2099 return N1.getOperand(N2C->getValue());
2101 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2102 // operations are lowered to scalars.
2103 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2104 if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2106 return N1.getOperand(1);
2108 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2111 case ISD::EXTRACT_ELEMENT:
2112 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2113 assert(!MVT::isVector(N1.getValueType()) &&
2114 MVT::isInteger(N1.getValueType()) &&
2115 !MVT::isVector(VT) && MVT::isInteger(VT) &&
2116 "EXTRACT_ELEMENT only applies to integers!");
2118 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2119 // 64-bit integers into 32-bit parts. Instead of building the extract of
2120 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2121 if (N1.getOpcode() == ISD::BUILD_PAIR)
2122 return N1.getOperand(N2C->getValue());
2124 // EXTRACT_ELEMENT of a constant int is also very common.
2125 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2126 unsigned ElementSize = MVT::getSizeInBits(VT);
2127 unsigned Shift = ElementSize * N2C->getValue();
2128 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2129 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2132 case ISD::EXTRACT_SUBVECTOR:
2133 if (N1.getValueType() == VT) // Trivial extraction.
2140 APInt C1 = N1C->getAPIntValue(), C2 = N2C->getAPIntValue();
2142 case ISD::ADD: return getConstant(C1 + C2, VT);
2143 case ISD::SUB: return getConstant(C1 - C2, VT);
2144 case ISD::MUL: return getConstant(C1 * C2, VT);
2146 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2149 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2152 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2155 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2157 case ISD::AND : return getConstant(C1 & C2, VT);
2158 case ISD::OR : return getConstant(C1 | C2, VT);
2159 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2160 case ISD::SHL : return getConstant(C1 << C2, VT);
2161 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2162 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2163 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2164 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2167 } else { // Cannonicalize constant to RHS if commutative
2168 if (isCommutativeBinOp(Opcode)) {
2169 std::swap(N1C, N2C);
2175 // Constant fold FP operations.
2176 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2177 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2179 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2180 // Cannonicalize constant to RHS if commutative
2181 std::swap(N1CFP, N2CFP);
2183 } else if (N2CFP && VT != MVT::ppcf128) {
2184 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2185 APFloat::opStatus s;
2188 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2189 if (s != APFloat::opInvalidOp)
2190 return getConstantFP(V1, VT);
2193 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2194 if (s!=APFloat::opInvalidOp)
2195 return getConstantFP(V1, VT);
2198 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2199 if (s!=APFloat::opInvalidOp)
2200 return getConstantFP(V1, VT);
2203 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2204 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2205 return getConstantFP(V1, VT);
2208 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2209 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2210 return getConstantFP(V1, VT);
2212 case ISD::FCOPYSIGN:
2214 return getConstantFP(V1, VT);
2220 // Canonicalize an UNDEF to the RHS, even over a constant.
2221 if (N1.getOpcode() == ISD::UNDEF) {
2222 if (isCommutativeBinOp(Opcode)) {
2226 case ISD::FP_ROUND_INREG:
2227 case ISD::SIGN_EXTEND_INREG:
2233 return N1; // fold op(undef, arg2) -> undef
2240 if (!MVT::isVector(VT))
2241 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2242 // For vectors, we can't easily build an all zero vector, just return
2249 // Fold a bunch of operators when the RHS is undef.
2250 if (N2.getOpcode() == ISD::UNDEF) {
2253 if (N1.getOpcode() == ISD::UNDEF)
2254 // Handle undef ^ undef -> 0 special case. This is a common
2256 return getConstant(0, VT);
2271 return N2; // fold op(arg1, undef) -> undef
2276 if (!MVT::isVector(VT))
2277 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2278 // For vectors, we can't easily build an all zero vector, just return
2282 if (!MVT::isVector(VT))
2283 return getConstant(MVT::getIntVTBitMask(VT), VT);
2284 // For vectors, we can't easily build an all one vector, just return
2292 // Memoize this node if possible.
2294 SDVTList VTs = getVTList(VT);
2295 if (VT != MVT::Flag) {
2296 SDOperand Ops[] = { N1, N2 };
2297 FoldingSetNodeID ID;
2298 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2300 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2301 return SDOperand(E, 0);
2302 N = new BinarySDNode(Opcode, VTs, N1, N2);
2303 CSEMap.InsertNode(N, IP);
2305 N = new BinarySDNode(Opcode, VTs, N1, N2);
2308 AllNodes.push_back(N);
2309 return SDOperand(N, 0);
2312 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2313 SDOperand N1, SDOperand N2, SDOperand N3) {
2314 // Perform various simplifications.
2315 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2316 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2319 // Use FoldSetCC to simplify SETCC's.
2320 SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2321 if (Simp.Val) return Simp;
2326 if (N1C->getValue())
2327 return N2; // select true, X, Y -> X
2329 return N3; // select false, X, Y -> Y
2332 if (N2 == N3) return N2; // select C, X, X -> X
2336 if (N2C->getValue()) // Unconditional branch
2337 return getNode(ISD::BR, MVT::Other, N1, N3);
2339 return N1; // Never-taken branch
2342 case ISD::VECTOR_SHUFFLE:
2343 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2344 MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2345 N3.getOpcode() == ISD::BUILD_VECTOR &&
2346 MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2347 "Illegal VECTOR_SHUFFLE node!");
2349 case ISD::BIT_CONVERT:
2350 // Fold bit_convert nodes from a type to themselves.
2351 if (N1.getValueType() == VT)
2356 // Memoize node if it doesn't produce a flag.
2358 SDVTList VTs = getVTList(VT);
2359 if (VT != MVT::Flag) {
2360 SDOperand Ops[] = { N1, N2, N3 };
2361 FoldingSetNodeID ID;
2362 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2364 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2365 return SDOperand(E, 0);
2366 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2367 CSEMap.InsertNode(N, IP);
2369 N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2371 AllNodes.push_back(N);
2372 return SDOperand(N, 0);
2375 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2376 SDOperand N1, SDOperand N2, SDOperand N3,
2378 SDOperand Ops[] = { N1, N2, N3, N4 };
2379 return getNode(Opcode, VT, Ops, 4);
2382 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2383 SDOperand N1, SDOperand N2, SDOperand N3,
2384 SDOperand N4, SDOperand N5) {
2385 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2386 return getNode(Opcode, VT, Ops, 5);
2389 /// getMemsetValue - Vectorized representation of the memset value
2391 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2392 SelectionDAG &DAG) {
2393 MVT::ValueType CurVT = VT;
2394 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2395 uint64_t Val = C->getValue() & 255;
2397 while (CurVT != MVT::i8) {
2398 Val = (Val << Shift) | Val;
2400 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2402 return DAG.getConstant(Val, VT);
2404 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2406 while (CurVT != MVT::i8) {
2408 DAG.getNode(ISD::OR, VT,
2409 DAG.getNode(ISD::SHL, VT, Value,
2410 DAG.getConstant(Shift, MVT::i8)), Value);
2412 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2419 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2420 /// used when a memcpy is turned into a memset when the source is a constant
2422 static SDOperand getMemsetStringVal(MVT::ValueType VT,
2424 const TargetLowering &TLI,
2425 std::string &Str, unsigned Offset) {
2427 unsigned MSB = MVT::getSizeInBits(VT) / 8;
2428 if (TLI.isLittleEndian())
2429 Offset = Offset + MSB - 1;
2430 for (unsigned i = 0; i != MSB; ++i) {
2431 Val = (Val << 8) | (unsigned char)Str[Offset];
2432 Offset += TLI.isLittleEndian() ? -1 : 1;
2434 return DAG.getConstant(Val, VT);
2437 /// getMemBasePlusOffset - Returns base and offset node for the
2438 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2439 SelectionDAG &DAG) {
2440 MVT::ValueType VT = Base.getValueType();
2441 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2444 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2445 /// to replace the memset / memcpy is below the threshold. It also returns the
2446 /// types of the sequence of memory ops to perform memset / memcpy.
2447 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2448 unsigned Limit, uint64_t Size,
2450 const TargetLowering &TLI) {
2453 if (TLI.allowsUnalignedMemoryAccesses()) {
2456 switch (Align & 7) {
2472 MVT::ValueType LVT = MVT::i64;
2473 while (!TLI.isTypeLegal(LVT))
2474 LVT = (MVT::ValueType)((unsigned)LVT - 1);
2475 assert(MVT::isInteger(LVT));
2480 unsigned NumMemOps = 0;
2482 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2483 while (VTSize > Size) {
2484 VT = (MVT::ValueType)((unsigned)VT - 1);
2487 assert(MVT::isInteger(VT));
2489 if (++NumMemOps > Limit)
2491 MemOps.push_back(VT);
2498 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2499 SDOperand Chain, SDOperand Dst,
2500 SDOperand Src, uint64_t Size,
2503 Value *DstSV, uint64_t DstOff,
2504 Value *SrcSV, uint64_t SrcOff) {
2505 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2507 // Expand memcpy to a series of store ops if the size operand falls below
2508 // a certain threshold.
2509 std::vector<MVT::ValueType> MemOps;
2510 uint64_t Limit = -1;
2512 Limit = TLI.getMaxStoresPerMemcpy();
2513 if (!MeetsMaxMemopRequirement(MemOps, Limit, Size, Align, TLI))
2516 SmallVector<SDOperand, 8> OutChains;
2518 unsigned NumMemOps = MemOps.size();
2519 unsigned SrcDelta = 0;
2520 GlobalAddressSDNode *G = NULL;
2522 bool CopyFromStr = false;
2524 if (Src.getOpcode() == ISD::GlobalAddress)
2525 G = cast<GlobalAddressSDNode>(Src);
2526 else if (Src.getOpcode() == ISD::ADD &&
2527 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2528 Src.getOperand(1).getOpcode() == ISD::Constant) {
2529 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2530 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2533 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2534 if (GV && GV->isConstant()) {
2535 Str = GV->getStringValue(false);
2543 for (unsigned i = 0; i < NumMemOps; i++) {
2544 MVT::ValueType VT = MemOps[i];
2545 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2546 SDOperand Value, Store;
2549 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2551 DAG.getStore(Chain, Value,
2552 getMemBasePlusOffset(Dst, DstOff, DAG),
2555 Value = DAG.getLoad(VT, Chain,
2556 getMemBasePlusOffset(Src, SrcOff, DAG),
2557 SrcSV, SrcOff, false, Align);
2559 DAG.getStore(Chain, Value,
2560 getMemBasePlusOffset(Dst, DstOff, DAG),
2561 DstSV, DstOff, false, Align);
2563 OutChains.push_back(Store);
2568 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2569 &OutChains[0], OutChains.size());
2572 static SDOperand getMemsetStores(SelectionDAG &DAG,
2573 SDOperand Chain, SDOperand Dst,
2574 SDOperand Src, uint64_t Size,
2576 Value *DstSV, uint64_t DstOff) {
2577 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2579 // Expand memset to a series of load/store ops if the size operand
2580 // falls below a certain threshold.
2581 std::vector<MVT::ValueType> MemOps;
2582 if (!MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2586 SmallVector<SDOperand, 8> OutChains;
2588 unsigned NumMemOps = MemOps.size();
2589 for (unsigned i = 0; i < NumMemOps; i++) {
2590 MVT::ValueType VT = MemOps[i];
2591 unsigned VTSize = MVT::getSizeInBits(VT) / 8;
2592 SDOperand Value = getMemsetValue(Src, VT, DAG);
2593 SDOperand Store = DAG.getStore(Chain, Value,
2594 getMemBasePlusOffset(Dst, DstOff, DAG),
2596 OutChains.push_back(Store);
2600 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2601 &OutChains[0], OutChains.size());
2604 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2605 SDOperand Src, SDOperand Size,
2606 unsigned Align, bool AlwaysInline,
2607 Value *DstSV, uint64_t DstOff,
2608 Value *SrcSV, uint64_t SrcOff) {
2610 // Check to see if we should lower the memcpy to loads and stores first.
2611 // For cases within the target-specified limits, this is the best choice.
2612 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2614 // Memcpy with size zero? Just return the original chain.
2615 if (ConstantSize->isNullValue())
2619 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2620 Align, false, DstSV, DstOff, SrcSV, SrcOff);
2625 // Then check to see if we should lower the memcpy with target-specific
2626 // code. If the target chooses to do this, this is the next best.
2628 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2630 DstSV, DstOff, SrcSV, SrcOff);
2634 // If we really need inline code and the target declined to provide it,
2635 // use a (potentially long) sequence of loads and stores.
2637 assert(ConstantSize && "AlwaysInline requires a constant size!");
2638 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2639 ConstantSize->getValue(), Align, true,
2640 DstSV, DstOff, SrcSV, SrcOff);
2643 // Emit a library call.
2644 TargetLowering::ArgListTy Args;
2645 TargetLowering::ArgListEntry Entry;
2646 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2647 Entry.Node = Dst; Args.push_back(Entry);
2648 Entry.Node = Src; Args.push_back(Entry);
2649 Entry.Node = Size; Args.push_back(Entry);
2650 std::pair<SDOperand,SDOperand> CallResult =
2651 TLI.LowerCallTo(Chain, Type::VoidTy,
2652 false, false, false, CallingConv::C, false,
2653 getExternalSymbol("memcpy", TLI.getPointerTy()),
2655 return CallResult.second;
2658 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2659 SDOperand Src, SDOperand Size,
2661 Value *DstSV, uint64_t DstOff,
2662 Value *SrcSV, uint64_t SrcOff) {
2664 // TODO: Optimize small memmove cases with simple loads and stores,
2665 // ensuring that all loads precede all stores. This can cause severe
2666 // register pressure, so targets should be careful with the size limit.
2668 // Then check to see if we should lower the memmove with target-specific
2669 // code. If the target chooses to do this, this is the next best.
2671 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2672 DstSV, DstOff, SrcSV, SrcOff);
2676 // Emit a library call.
2677 TargetLowering::ArgListTy Args;
2678 TargetLowering::ArgListEntry Entry;
2679 Entry.Ty = TLI.getTargetData()->getIntPtrType();
2680 Entry.Node = Dst; Args.push_back(Entry);
2681 Entry.Node = Src; Args.push_back(Entry);
2682 Entry.Node = Size; Args.push_back(Entry);
2683 std::pair<SDOperand,SDOperand> CallResult =
2684 TLI.LowerCallTo(Chain, Type::VoidTy,
2685 false, false, false, CallingConv::C, false,
2686 getExternalSymbol("memmove", TLI.getPointerTy()),
2688 return CallResult.second;
2691 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2692 SDOperand Src, SDOperand Size,
2694 Value *DstSV, uint64_t DstOff) {
2696 // Check to see if we should lower the memset to stores first.
2697 // For cases within the target-specified limits, this is the best choice.
2698 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2700 // Memset with size zero? Just return the original chain.
2701 if (ConstantSize->isNullValue())
2705 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
2711 // Then check to see if we should lower the memset with target-specific
2712 // code. If the target chooses to do this, this is the next best.
2714 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
2719 // Emit a library call.
2720 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
2721 TargetLowering::ArgListTy Args;
2722 TargetLowering::ArgListEntry Entry;
2723 Entry.Node = Dst; Entry.Ty = IntPtrTy;
2724 Args.push_back(Entry);
2725 // Extend or truncate the argument to be an i32 value for the call.
2726 if (Src.getValueType() > MVT::i32)
2727 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
2729 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
2730 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
2731 Args.push_back(Entry);
2732 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
2733 Args.push_back(Entry);
2734 std::pair<SDOperand,SDOperand> CallResult =
2735 TLI.LowerCallTo(Chain, Type::VoidTy,
2736 false, false, false, CallingConv::C, false,
2737 getExternalSymbol("memset", TLI.getPointerTy()),
2739 return CallResult.second;
2742 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
2743 SDOperand Ptr, SDOperand Cmp,
2744 SDOperand Swp, MVT::ValueType VT) {
2745 assert(Opcode == ISD::ATOMIC_LCS && "Invalid Atomic Op");
2746 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
2747 SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
2748 FoldingSetNodeID ID;
2749 SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
2750 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
2751 ID.AddInteger((unsigned int)VT);
2753 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2754 return SDOperand(E, 0);
2755 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, VT);
2756 CSEMap.InsertNode(N, IP);
2757 AllNodes.push_back(N);
2758 return SDOperand(N, 0);
2761 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain,
2762 SDOperand Ptr, SDOperand Val,
2763 MVT::ValueType VT) {
2764 assert((Opcode == ISD::ATOMIC_LAS || Opcode == ISD::ATOMIC_SWAP)
2765 && "Invalid Atomic Op");
2766 SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
2767 FoldingSetNodeID ID;
2768 SDOperand Ops[] = {Chain, Ptr, Val};
2769 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2770 ID.AddInteger((unsigned int)VT);
2772 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2773 return SDOperand(E, 0);
2774 SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, VT);
2775 CSEMap.InsertNode(N, IP);
2776 AllNodes.push_back(N);
2777 return SDOperand(N, 0);
2781 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
2782 MVT::ValueType VT, SDOperand Chain,
2783 SDOperand Ptr, SDOperand Offset,
2784 const Value *SV, int SVOffset, MVT::ValueType EVT,
2785 bool isVolatile, unsigned Alignment) {
2786 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2788 if (VT != MVT::iPTR) {
2789 Ty = MVT::getTypeForValueType(VT);
2791 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2792 assert(PT && "Value for load must be a pointer");
2793 Ty = PT->getElementType();
2795 assert(Ty && "Could not get type information for load");
2796 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2800 ExtType = ISD::NON_EXTLOAD;
2801 } else if (ExtType == ISD::NON_EXTLOAD) {
2802 assert(VT == EVT && "Non-extending load from different memory type!");
2805 if (MVT::isVector(VT))
2806 assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2808 assert(MVT::getSizeInBits(EVT) < MVT::getSizeInBits(VT) &&
2809 "Should only be an extending load, not truncating!");
2810 assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2811 "Cannot sign/zero extend a FP/Vector load!");
2812 assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2813 "Cannot convert from FP to Int or Int -> FP!");
2816 bool Indexed = AM != ISD::UNINDEXED;
2817 assert(Indexed || Offset.getOpcode() == ISD::UNDEF &&
2818 "Unindexed load with an offset!");
2820 SDVTList VTs = Indexed ?
2821 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
2822 SDOperand Ops[] = { Chain, Ptr, Offset };
2823 FoldingSetNodeID ID;
2824 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2826 ID.AddInteger(ExtType);
2827 ID.AddInteger((unsigned int)EVT);
2828 ID.AddInteger(Alignment);
2829 ID.AddInteger(isVolatile);
2831 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2832 return SDOperand(E, 0);
2833 SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
2834 Alignment, isVolatile);
2835 CSEMap.InsertNode(N, IP);
2836 AllNodes.push_back(N);
2837 return SDOperand(N, 0);
2840 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2841 SDOperand Chain, SDOperand Ptr,
2842 const Value *SV, int SVOffset,
2843 bool isVolatile, unsigned Alignment) {
2844 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2845 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
2846 SV, SVOffset, VT, isVolatile, Alignment);
2849 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2850 SDOperand Chain, SDOperand Ptr,
2852 int SVOffset, MVT::ValueType EVT,
2853 bool isVolatile, unsigned Alignment) {
2854 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2855 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
2856 SV, SVOffset, EVT, isVolatile, Alignment);
2860 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2861 SDOperand Offset, ISD::MemIndexedMode AM) {
2862 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2863 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2864 "Load is already a indexed load!");
2865 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
2866 LD->getChain(), Base, Offset, LD->getSrcValue(),
2867 LD->getSrcValueOffset(), LD->getMemoryVT(),
2868 LD->isVolatile(), LD->getAlignment());
2871 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2872 SDOperand Ptr, const Value *SV, int SVOffset,
2873 bool isVolatile, unsigned Alignment) {
2874 MVT::ValueType VT = Val.getValueType();
2876 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2878 if (VT != MVT::iPTR) {
2879 Ty = MVT::getTypeForValueType(VT);
2881 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2882 assert(PT && "Value for store must be a pointer");
2883 Ty = PT->getElementType();
2885 assert(Ty && "Could not get type information for store");
2886 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2888 SDVTList VTs = getVTList(MVT::Other);
2889 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2890 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2891 FoldingSetNodeID ID;
2892 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2893 ID.AddInteger(ISD::UNINDEXED);
2894 ID.AddInteger(false);
2895 ID.AddInteger((unsigned int)VT);
2896 ID.AddInteger(Alignment);
2897 ID.AddInteger(isVolatile);
2899 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2900 return SDOperand(E, 0);
2901 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
2902 VT, SV, SVOffset, Alignment, isVolatile);
2903 CSEMap.InsertNode(N, IP);
2904 AllNodes.push_back(N);
2905 return SDOperand(N, 0);
2908 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
2909 SDOperand Ptr, const Value *SV,
2910 int SVOffset, MVT::ValueType SVT,
2911 bool isVolatile, unsigned Alignment) {
2912 MVT::ValueType VT = Val.getValueType();
2915 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
2917 assert(MVT::getSizeInBits(VT) > MVT::getSizeInBits(SVT) &&
2918 "Not a truncation?");
2919 assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
2920 "Can't do FP-INT conversion!");
2922 if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2924 if (VT != MVT::iPTR) {
2925 Ty = MVT::getTypeForValueType(VT);
2927 const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2928 assert(PT && "Value for store must be a pointer");
2929 Ty = PT->getElementType();
2931 assert(Ty && "Could not get type information for store");
2932 Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2934 SDVTList VTs = getVTList(MVT::Other);
2935 SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2936 SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2937 FoldingSetNodeID ID;
2938 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2939 ID.AddInteger(ISD::UNINDEXED);
2941 ID.AddInteger((unsigned int)SVT);
2942 ID.AddInteger(Alignment);
2943 ID.AddInteger(isVolatile);
2945 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2946 return SDOperand(E, 0);
2947 SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
2948 SVT, SV, SVOffset, Alignment, isVolatile);
2949 CSEMap.InsertNode(N, IP);
2950 AllNodes.push_back(N);
2951 return SDOperand(N, 0);
2955 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
2956 SDOperand Offset, ISD::MemIndexedMode AM) {
2957 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
2958 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
2959 "Store is already a indexed store!");
2960 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
2961 SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
2962 FoldingSetNodeID ID;
2963 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2965 ID.AddInteger(ST->isTruncatingStore());
2966 ID.AddInteger((unsigned int)(ST->getMemoryVT()));
2967 ID.AddInteger(ST->getAlignment());
2968 ID.AddInteger(ST->isVolatile());
2970 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2971 return SDOperand(E, 0);
2972 SDNode *N = new StoreSDNode(Ops, VTs, AM,
2973 ST->isTruncatingStore(), ST->getMemoryVT(),
2974 ST->getSrcValue(), ST->getSrcValueOffset(),
2975 ST->getAlignment(), ST->isVolatile());
2976 CSEMap.InsertNode(N, IP);
2977 AllNodes.push_back(N);
2978 return SDOperand(N, 0);
2981 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
2982 SDOperand Chain, SDOperand Ptr,
2984 SDOperand Ops[] = { Chain, Ptr, SV };
2985 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
2988 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2989 const SDOperand *Ops, unsigned NumOps) {
2991 case 0: return getNode(Opcode, VT);
2992 case 1: return getNode(Opcode, VT, Ops[0]);
2993 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
2994 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3000 case ISD::SELECT_CC: {
3001 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3002 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3003 "LHS and RHS of condition must have same type!");
3004 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3005 "True and False arms of SelectCC must have same type!");
3006 assert(Ops[2].getValueType() == VT &&
3007 "select_cc node must be of same type as true and false value!");
3011 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3012 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3013 "LHS/RHS of comparison should match types!");
3020 SDVTList VTs = getVTList(VT);
3021 if (VT != MVT::Flag) {
3022 FoldingSetNodeID ID;
3023 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3025 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3026 return SDOperand(E, 0);
3027 N = new SDNode(Opcode, VTs, Ops, NumOps);
3028 CSEMap.InsertNode(N, IP);
3030 N = new SDNode(Opcode, VTs, Ops, NumOps);
3032 AllNodes.push_back(N);
3033 return SDOperand(N, 0);
3036 SDOperand SelectionDAG::getNode(unsigned Opcode,
3037 std::vector<MVT::ValueType> &ResultTys,
3038 const SDOperand *Ops, unsigned NumOps) {
3039 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3043 SDOperand SelectionDAG::getNode(unsigned Opcode,
3044 const MVT::ValueType *VTs, unsigned NumVTs,
3045 const SDOperand *Ops, unsigned NumOps) {
3047 return getNode(Opcode, VTs[0], Ops, NumOps);
3048 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3051 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3052 const SDOperand *Ops, unsigned NumOps) {
3053 if (VTList.NumVTs == 1)
3054 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3057 // FIXME: figure out how to safely handle things like
3058 // int foo(int x) { return 1 << (x & 255); }
3059 // int bar() { return foo(256); }
3061 case ISD::SRA_PARTS:
3062 case ISD::SRL_PARTS:
3063 case ISD::SHL_PARTS:
3064 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3065 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3066 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3067 else if (N3.getOpcode() == ISD::AND)
3068 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3069 // If the and is only masking out bits that cannot effect the shift,
3070 // eliminate the and.
3071 unsigned NumBits = MVT::getSizeInBits(VT)*2;
3072 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3073 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3079 // Memoize the node unless it returns a flag.
3081 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3082 FoldingSetNodeID ID;
3083 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3085 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3086 return SDOperand(E, 0);
3088 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3089 else if (NumOps == 2)
3090 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3091 else if (NumOps == 3)
3092 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3094 N = new SDNode(Opcode, VTList, Ops, NumOps);
3095 CSEMap.InsertNode(N, IP);
3098 N = new UnarySDNode(Opcode, VTList, Ops[0]);
3099 else if (NumOps == 2)
3100 N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3101 else if (NumOps == 3)
3102 N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3104 N = new SDNode(Opcode, VTList, Ops, NumOps);
3106 AllNodes.push_back(N);
3107 return SDOperand(N, 0);
3110 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3111 return getNode(Opcode, VTList, 0, 0);
3114 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3116 SDOperand Ops[] = { N1 };
3117 return getNode(Opcode, VTList, Ops, 1);
3120 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3121 SDOperand N1, SDOperand N2) {
3122 SDOperand Ops[] = { N1, N2 };
3123 return getNode(Opcode, VTList, Ops, 2);
3126 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3127 SDOperand N1, SDOperand N2, SDOperand N3) {
3128 SDOperand Ops[] = { N1, N2, N3 };
3129 return getNode(Opcode, VTList, Ops, 3);
3132 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3133 SDOperand N1, SDOperand N2, SDOperand N3,
3135 SDOperand Ops[] = { N1, N2, N3, N4 };
3136 return getNode(Opcode, VTList, Ops, 4);
3139 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3140 SDOperand N1, SDOperand N2, SDOperand N3,
3141 SDOperand N4, SDOperand N5) {
3142 SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3143 return getNode(Opcode, VTList, Ops, 5);
3146 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
3147 return makeVTList(SDNode::getValueTypeList(VT), 1);
3150 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
3151 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
3152 E = VTList.end(); I != E; ++I) {
3153 if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3154 return makeVTList(&(*I)[0], 2);
3156 std::vector<MVT::ValueType> V;
3159 VTList.push_front(V);
3160 return makeVTList(&(*VTList.begin())[0], 2);
3162 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
3163 MVT::ValueType VT3) {
3164 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
3165 E = VTList.end(); I != E; ++I) {
3166 if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3168 return makeVTList(&(*I)[0], 3);
3170 std::vector<MVT::ValueType> V;
3174 VTList.push_front(V);
3175 return makeVTList(&(*VTList.begin())[0], 3);
3178 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
3180 case 0: assert(0 && "Cannot have nodes without results!");
3181 case 1: return getVTList(VTs[0]);
3182 case 2: return getVTList(VTs[0], VTs[1]);
3183 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3187 for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
3188 E = VTList.end(); I != E; ++I) {
3189 if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3191 bool NoMatch = false;
3192 for (unsigned i = 2; i != NumVTs; ++i)
3193 if (VTs[i] != (*I)[i]) {
3198 return makeVTList(&*I->begin(), NumVTs);
3201 VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
3202 return makeVTList(&*VTList.begin()->begin(), NumVTs);
3206 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3207 /// specified operands. If the resultant node already exists in the DAG,
3208 /// this does not modify the specified node, instead it returns the node that
3209 /// already exists. If the resultant node does not exist in the DAG, the
3210 /// input node is returned. As a degenerate case, if you specify the same
3211 /// input operands as the node already has, the input node is returned.
3212 SDOperand SelectionDAG::
3213 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3214 SDNode *N = InN.Val;
3215 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3217 // Check to see if there is no change.
3218 if (Op == N->getOperand(0)) return InN;
3220 // See if the modified node already exists.
3221 void *InsertPos = 0;
3222 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3223 return SDOperand(Existing, InN.ResNo);
3225 // Nope it doesn't. Remove the node from it's current place in the maps.
3227 RemoveNodeFromCSEMaps(N);
3229 // Now we update the operands.
3230 N->OperandList[0].Val->removeUser(0, N);
3231 N->OperandList[0] = Op;
3232 N->OperandList[0].setUser(N);
3233 Op.Val->addUser(0, N);
3235 // If this gets put into a CSE map, add it.
3236 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3240 SDOperand SelectionDAG::
3241 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3242 SDNode *N = InN.Val;
3243 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3245 // Check to see if there is no change.
3246 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3247 return InN; // No operands changed, just return the input node.
3249 // See if the modified node already exists.
3250 void *InsertPos = 0;
3251 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3252 return SDOperand(Existing, InN.ResNo);
3254 // Nope it doesn't. Remove the node from it's current place in the maps.
3256 RemoveNodeFromCSEMaps(N);
3258 // Now we update the operands.
3259 if (N->OperandList[0] != Op1) {
3260 N->OperandList[0].Val->removeUser(0, N);
3261 N->OperandList[0] = Op1;
3262 N->OperandList[0].setUser(N);
3263 Op1.Val->addUser(0, N);
3265 if (N->OperandList[1] != Op2) {
3266 N->OperandList[1].Val->removeUser(1, N);
3267 N->OperandList[1] = Op2;
3268 N->OperandList[1].setUser(N);
3269 Op2.Val->addUser(1, N);
3272 // If this gets put into a CSE map, add it.
3273 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3277 SDOperand SelectionDAG::
3278 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3279 SDOperand Ops[] = { Op1, Op2, Op3 };
3280 return UpdateNodeOperands(N, Ops, 3);
3283 SDOperand SelectionDAG::
3284 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3285 SDOperand Op3, SDOperand Op4) {
3286 SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3287 return UpdateNodeOperands(N, Ops, 4);
3290 SDOperand SelectionDAG::
3291 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3292 SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3293 SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3294 return UpdateNodeOperands(N, Ops, 5);
3297 SDOperand SelectionDAG::
3298 UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
3299 SDNode *N = InN.Val;
3300 assert(N->getNumOperands() == NumOps &&
3301 "Update with wrong number of operands");
3303 // Check to see if there is no change.
3304 bool AnyChange = false;
3305 for (unsigned i = 0; i != NumOps; ++i) {
3306 if (Ops[i] != N->getOperand(i)) {
3312 // No operands changed, just return the input node.
3313 if (!AnyChange) return InN;
3315 // See if the modified node already exists.
3316 void *InsertPos = 0;
3317 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3318 return SDOperand(Existing, InN.ResNo);
3320 // Nope it doesn't. Remove the node from it's current place in the maps.
3322 RemoveNodeFromCSEMaps(N);
3324 // Now we update the operands.
3325 for (unsigned i = 0; i != NumOps; ++i) {
3326 if (N->OperandList[i] != Ops[i]) {
3327 N->OperandList[i].Val->removeUser(i, N);
3328 N->OperandList[i] = Ops[i];
3329 N->OperandList[i].setUser(N);
3330 Ops[i].Val->addUser(i, N);
3334 // If this gets put into a CSE map, add it.
3335 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3339 /// MorphNodeTo - This frees the operands of the current node, resets the
3340 /// opcode, types, and operands to the specified value. This should only be
3341 /// used by the SelectionDAG class.
3342 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3343 const SDOperand *Ops, unsigned NumOps) {
3346 NumValues = L.NumVTs;
3348 // Clear the operands list, updating used nodes to remove this from their
3350 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3351 I->Val->removeUser(std::distance(op_begin(), I), this);
3353 // If NumOps is larger than the # of operands we currently have, reallocate
3354 // the operand list.
3355 if (NumOps > NumOperands) {
3356 if (OperandsNeedDelete) {
3357 delete [] OperandList;
3359 OperandList = new SDOperand[NumOps];
3360 OperandsNeedDelete = true;
3363 // Assign the new operands.
3364 NumOperands = NumOps;
3366 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3367 OperandList[i] = Ops[i];
3368 OperandList[i].setUser(this);
3369 SDNode *N = OperandList[i].Val;
3370 N->addUser(i, this);
3375 /// SelectNodeTo - These are used for target selectors to *mutate* the
3376 /// specified node to have the specified return type, Target opcode, and
3377 /// operands. Note that target opcodes are stored as
3378 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3380 /// Note that SelectNodeTo returns the resultant node. If there is already a
3381 /// node of the specified opcode and operands, it returns that node instead of
3382 /// the current one.
3383 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3384 MVT::ValueType VT) {
3385 SDVTList VTs = getVTList(VT);
3386 FoldingSetNodeID ID;
3387 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
3389 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3392 RemoveNodeFromCSEMaps(N);
3394 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
3396 CSEMap.InsertNode(N, IP);
3400 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3401 MVT::ValueType VT, SDOperand Op1) {
3402 // If an identical node already exists, use it.
3403 SDVTList VTs = getVTList(VT);
3404 SDOperand Ops[] = { Op1 };
3406 FoldingSetNodeID ID;
3407 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3409 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3412 RemoveNodeFromCSEMaps(N);
3413 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3414 CSEMap.InsertNode(N, IP);
3418 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3419 MVT::ValueType VT, SDOperand Op1,
3421 // If an identical node already exists, use it.
3422 SDVTList VTs = getVTList(VT);
3423 SDOperand Ops[] = { Op1, Op2 };
3425 FoldingSetNodeID ID;
3426 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3428 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3431 RemoveNodeFromCSEMaps(N);
3433 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3435 CSEMap.InsertNode(N, IP); // Memoize the new node.
3439 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3440 MVT::ValueType VT, SDOperand Op1,
3441 SDOperand Op2, SDOperand Op3) {
3442 // If an identical node already exists, use it.
3443 SDVTList VTs = getVTList(VT);
3444 SDOperand Ops[] = { Op1, Op2, Op3 };
3445 FoldingSetNodeID ID;
3446 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3448 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3451 RemoveNodeFromCSEMaps(N);
3453 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3455 CSEMap.InsertNode(N, IP); // Memoize the new node.
3459 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3460 MVT::ValueType VT, const SDOperand *Ops,
3462 // If an identical node already exists, use it.
3463 SDVTList VTs = getVTList(VT);
3464 FoldingSetNodeID ID;
3465 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3467 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3470 RemoveNodeFromCSEMaps(N);
3471 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3473 CSEMap.InsertNode(N, IP); // Memoize the new node.
3477 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3478 MVT::ValueType VT1, MVT::ValueType VT2,
3479 SDOperand Op1, SDOperand Op2) {
3480 SDVTList VTs = getVTList(VT1, VT2);
3481 FoldingSetNodeID ID;
3482 SDOperand Ops[] = { Op1, Op2 };
3483 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3485 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3488 RemoveNodeFromCSEMaps(N);
3489 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3490 CSEMap.InsertNode(N, IP); // Memoize the new node.
3494 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3495 MVT::ValueType VT1, MVT::ValueType VT2,
3496 SDOperand Op1, SDOperand Op2,
3498 // If an identical node already exists, use it.
3499 SDVTList VTs = getVTList(VT1, VT2);
3500 SDOperand Ops[] = { Op1, Op2, Op3 };
3501 FoldingSetNodeID ID;
3502 AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3504 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3507 RemoveNodeFromCSEMaps(N);
3509 N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3510 CSEMap.InsertNode(N, IP); // Memoize the new node.
3515 /// getTargetNode - These are used for target selectors to create a new node
3516 /// with specified return type(s), target opcode, and operands.
3518 /// Note that getTargetNode returns the resultant node. If there is already a
3519 /// node of the specified opcode and operands, it returns that node instead of
3520 /// the current one.
3521 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
3522 return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3524 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3526 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3528 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3529 SDOperand Op1, SDOperand Op2) {
3530 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3532 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3533 SDOperand Op1, SDOperand Op2,
3535 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3537 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
3538 const SDOperand *Ops, unsigned NumOps) {
3539 return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3541 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3542 MVT::ValueType VT2) {
3543 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3545 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3547 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3548 MVT::ValueType VT2, SDOperand Op1) {
3549 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3550 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3552 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3553 MVT::ValueType VT2, SDOperand Op1,
3555 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3556 SDOperand Ops[] = { Op1, Op2 };
3557 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3559 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3560 MVT::ValueType VT2, SDOperand Op1,
3561 SDOperand Op2, SDOperand Op3) {
3562 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3563 SDOperand Ops[] = { Op1, Op2, Op3 };
3564 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3566 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3568 const SDOperand *Ops, unsigned NumOps) {
3569 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3570 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3572 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3573 MVT::ValueType VT2, MVT::ValueType VT3,
3574 SDOperand Op1, SDOperand Op2) {
3575 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3576 SDOperand Ops[] = { Op1, Op2 };
3577 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3579 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3580 MVT::ValueType VT2, MVT::ValueType VT3,
3581 SDOperand Op1, SDOperand Op2,
3583 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3584 SDOperand Ops[] = { Op1, Op2, Op3 };
3585 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3587 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3588 MVT::ValueType VT2, MVT::ValueType VT3,
3589 const SDOperand *Ops, unsigned NumOps) {
3590 const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3591 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3593 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3594 MVT::ValueType VT2, MVT::ValueType VT3,
3596 const SDOperand *Ops, unsigned NumOps) {
3597 std::vector<MVT::ValueType> VTList;
3598 VTList.push_back(VT1);
3599 VTList.push_back(VT2);
3600 VTList.push_back(VT3);
3601 VTList.push_back(VT4);
3602 const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3603 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3605 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3606 std::vector<MVT::ValueType> &ResultTys,
3607 const SDOperand *Ops, unsigned NumOps) {
3608 const MVT::ValueType *VTs = getNodeValueTypes(ResultTys);
3609 return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3613 /// getNodeIfExists - Get the specified node if it's already available, or
3614 /// else return NULL.
3615 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3616 const SDOperand *Ops, unsigned NumOps) {
3617 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3618 FoldingSetNodeID ID;
3619 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3621 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3628 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3629 /// This can cause recursive merging of nodes in the DAG.
3631 /// This version assumes From has a single result value.
3633 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3634 DAGUpdateListener *UpdateListener) {
3635 SDNode *From = FromN.Val;
3636 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
3637 "Cannot replace with this method!");
3638 assert(From != To.Val && "Cannot replace uses of with self");
3640 while (!From->use_empty()) {
3641 SDNode::use_iterator UI = From->use_begin();
3642 SDNode *U = UI->getUser();
3644 // This node is about to morph, remove its old self from the CSE maps.
3645 RemoveNodeFromCSEMaps(U);
3647 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3648 I != E; ++I, ++operandNum)
3649 if (I->Val == From) {
3650 From->removeUser(operandNum, U);
3653 To.Val->addUser(operandNum, U);
3656 // Now that we have modified U, add it back to the CSE maps. If it already
3657 // exists there, recursively merge the results together.
3658 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3659 ReplaceAllUsesWith(U, Existing, UpdateListener);
3660 // U is now dead. Inform the listener if it exists and delete it.
3662 UpdateListener->NodeDeleted(U);
3663 DeleteNodeNotInCSEMaps(U);
3665 // If the node doesn't already exist, we updated it. Inform a listener if
3668 UpdateListener->NodeUpdated(U);
3673 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3674 /// This can cause recursive merging of nodes in the DAG.
3676 /// This version assumes From/To have matching types and numbers of result
3679 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3680 DAGUpdateListener *UpdateListener) {
3681 assert(From != To && "Cannot replace uses of with self");
3682 assert(From->getNumValues() == To->getNumValues() &&
3683 "Cannot use this version of ReplaceAllUsesWith!");
3684 if (From->getNumValues() == 1) // If possible, use the faster version.
3685 return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3688 while (!From->use_empty()) {
3689 SDNode::use_iterator UI = From->use_begin();
3690 SDNode *U = UI->getUser();
3692 // This node is about to morph, remove its old self from the CSE maps.
3693 RemoveNodeFromCSEMaps(U);
3695 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3696 I != E; ++I, ++operandNum)
3697 if (I->Val == From) {
3698 From->removeUser(operandNum, U);
3700 To->addUser(operandNum, U);
3703 // Now that we have modified U, add it back to the CSE maps. If it already
3704 // exists there, recursively merge the results together.
3705 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3706 ReplaceAllUsesWith(U, Existing, UpdateListener);
3707 // U is now dead. Inform the listener if it exists and delete it.
3709 UpdateListener->NodeDeleted(U);
3710 DeleteNodeNotInCSEMaps(U);
3712 // If the node doesn't already exist, we updated it. Inform a listener if
3715 UpdateListener->NodeUpdated(U);
3720 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3721 /// This can cause recursive merging of nodes in the DAG.
3723 /// This version can replace From with any result values. To must match the
3724 /// number and types of values returned by From.
3725 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3726 const SDOperand *To,
3727 DAGUpdateListener *UpdateListener) {
3728 if (From->getNumValues() == 1) // Handle the simple case efficiently.
3729 return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
3731 while (!From->use_empty()) {
3732 SDNode::use_iterator UI = From->use_begin();
3733 SDNode *U = UI->getUser();
3735 // This node is about to morph, remove its old self from the CSE maps.
3736 RemoveNodeFromCSEMaps(U);
3738 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3739 I != E; ++I, ++operandNum)
3740 if (I->Val == From) {
3741 const SDOperand &ToOp = To[I->ResNo];
3742 From->removeUser(operandNum, U);
3745 ToOp.Val->addUser(operandNum, U);
3748 // Now that we have modified U, add it back to the CSE maps. If it already
3749 // exists there, recursively merge the results together.
3750 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3751 ReplaceAllUsesWith(U, Existing, UpdateListener);
3752 // U is now dead. Inform the listener if it exists and delete it.
3754 UpdateListener->NodeDeleted(U);
3755 DeleteNodeNotInCSEMaps(U);
3757 // If the node doesn't already exist, we updated it. Inform a listener if
3760 UpdateListener->NodeUpdated(U);
3766 /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
3767 /// any deleted nodes from the set passed into its constructor and recursively
3768 /// notifies another update listener if specified.
3769 class ChainedSetUpdaterListener :
3770 public SelectionDAG::DAGUpdateListener {
3771 SmallSetVector<SDNode*, 16> &Set;
3772 SelectionDAG::DAGUpdateListener *Chain;
3774 ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
3775 SelectionDAG::DAGUpdateListener *chain)
3776 : Set(set), Chain(chain) {}
3778 virtual void NodeDeleted(SDNode *N) {
3780 if (Chain) Chain->NodeDeleted(N);
3782 virtual void NodeUpdated(SDNode *N) {
3783 if (Chain) Chain->NodeUpdated(N);
3788 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3789 /// uses of other values produced by From.Val alone. The Deleted vector is
3790 /// handled the same way as for ReplaceAllUsesWith.
3791 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3792 DAGUpdateListener *UpdateListener){
3793 assert(From != To && "Cannot replace a value with itself");
3795 // Handle the simple, trivial, case efficiently.
3796 if (From.Val->getNumValues() == 1) {
3797 ReplaceAllUsesWith(From, To, UpdateListener);
3801 if (From.use_empty()) return;
3803 // Get all of the users of From.Val. We want these in a nice,
3804 // deterministically ordered and uniqued set, so we use a SmallSetVector.
3805 SmallSetVector<SDNode*, 16> Users;
3806 for (SDNode::use_iterator UI = From.Val->use_begin(),
3807 E = From.Val->use_end(); UI != E; ++UI) {
3808 SDNode *User = UI->getUser();
3809 if (!Users.count(User))
3813 // When one of the recursive merges deletes nodes from the graph, we need to
3814 // make sure that UpdateListener is notified *and* that the node is removed
3815 // from Users if present. CSUL does this.
3816 ChainedSetUpdaterListener CSUL(Users, UpdateListener);
3818 while (!Users.empty()) {
3819 // We know that this user uses some value of From. If it is the right
3820 // value, update it.
3821 SDNode *User = Users.back();
3824 // Scan for an operand that matches From.
3825 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
3826 for (; Op != E; ++Op)
3827 if (*Op == From) break;
3829 // If there are no matches, the user must use some other result of From.
3830 if (Op == E) continue;
3832 // Okay, we know this user needs to be updated. Remove its old self
3833 // from the CSE maps.
3834 RemoveNodeFromCSEMaps(User);
3836 // Update all operands that match "From" in case there are multiple uses.
3837 for (; Op != E; ++Op) {
3839 From.Val->removeUser(Op-User->op_begin(), User);
3842 To.Val->addUser(Op-User->op_begin(), User);
3846 // Now that we have modified User, add it back to the CSE maps. If it
3847 // already exists there, recursively merge the results together.
3848 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
3850 if (UpdateListener) UpdateListener->NodeUpdated(User);
3851 continue; // Continue on to next user.
3854 // If there was already an existing matching node, use ReplaceAllUsesWith
3855 // to replace the dead one with the existing one. This can cause
3856 // recursive merging of other unrelated nodes down the line. The merging
3857 // can cause deletion of nodes that used the old value. To handle this, we
3858 // use CSUL to remove them from the Users set.
3859 ReplaceAllUsesWith(User, Existing, &CSUL);
3861 // User is now dead. Notify a listener if present.
3862 if (UpdateListener) UpdateListener->NodeDeleted(User);
3863 DeleteNodeNotInCSEMaps(User);
3868 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3869 /// their allnodes order. It returns the maximum id.
3870 unsigned SelectionDAG::AssignNodeIds() {
3872 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3879 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
3880 /// based on their topological order. It returns the maximum id and a vector
3881 /// of the SDNodes* in assigned order by reference.
3882 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
3883 unsigned DAGSize = AllNodes.size();
3884 std::vector<unsigned> InDegree(DAGSize);
3885 std::vector<SDNode*> Sources;
3887 // Use a two pass approach to avoid using a std::map which is slow.
3889 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
3892 unsigned Degree = N->use_size();
3893 InDegree[N->getNodeId()] = Degree;
3895 Sources.push_back(N);
3899 while (!Sources.empty()) {
3900 SDNode *N = Sources.back();
3902 TopOrder.push_back(N);
3903 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
3905 unsigned Degree = --InDegree[P->getNodeId()];
3907 Sources.push_back(P);
3911 // Second pass, assign the actual topological order as node ids.
3913 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
3915 (*TI)->setNodeId(Id++);
3922 //===----------------------------------------------------------------------===//
3924 //===----------------------------------------------------------------------===//
3926 // Out-of-line virtual method to give class a home.
3927 void SDNode::ANCHOR() {}
3928 void UnarySDNode::ANCHOR() {}
3929 void BinarySDNode::ANCHOR() {}
3930 void TernarySDNode::ANCHOR() {}
3931 void HandleSDNode::ANCHOR() {}
3932 void StringSDNode::ANCHOR() {}
3933 void ConstantSDNode::ANCHOR() {}
3934 void ConstantFPSDNode::ANCHOR() {}
3935 void GlobalAddressSDNode::ANCHOR() {}
3936 void FrameIndexSDNode::ANCHOR() {}
3937 void JumpTableSDNode::ANCHOR() {}
3938 void ConstantPoolSDNode::ANCHOR() {}
3939 void BasicBlockSDNode::ANCHOR() {}
3940 void SrcValueSDNode::ANCHOR() {}
3941 void MemOperandSDNode::ANCHOR() {}
3942 void RegisterSDNode::ANCHOR() {}
3943 void ExternalSymbolSDNode::ANCHOR() {}
3944 void CondCodeSDNode::ANCHOR() {}
3945 void ARG_FLAGSSDNode::ANCHOR() {}
3946 void VTSDNode::ANCHOR() {}
3947 void LoadSDNode::ANCHOR() {}
3948 void StoreSDNode::ANCHOR() {}
3949 void AtomicSDNode::ANCHOR() {}
3951 HandleSDNode::~HandleSDNode() {
3952 SDVTList VTs = { 0, 0 };
3953 MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0); // Drops operand uses.
3956 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
3957 MVT::ValueType VT, int o)
3958 : SDNode(isa<GlobalVariable>(GA) &&
3959 cast<GlobalVariable>(GA)->isThreadLocal() ?
3961 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
3963 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
3964 getSDVTList(VT)), Offset(o) {
3965 TheGlobal = const_cast<GlobalValue*>(GA);
3968 /// getMemOperand - Return a MachineMemOperand object describing the memory
3969 /// reference performed by this load or store.
3970 MachineMemOperand LSBaseSDNode::getMemOperand() const {
3971 int Size = (MVT::getSizeInBits(getMemoryVT()) + 7) >> 3;
3973 getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
3974 MachineMemOperand::MOStore;
3975 if (IsVolatile) Flags |= MachineMemOperand::MOVolatile;
3977 // Check if the load references a frame index, and does not have
3979 const FrameIndexSDNode *FI =
3980 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
3981 if (!getSrcValue() && FI)
3982 return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
3983 FI->getIndex(), Size, Alignment);
3985 return MachineMemOperand(getSrcValue(), Flags,
3986 getSrcValueOffset(), Size, Alignment);
3989 /// Profile - Gather unique data for the node.
3991 void SDNode::Profile(FoldingSetNodeID &ID) {
3992 AddNodeIDNode(ID, this);
3995 /// getValueTypeList - Return a pointer to the specified value type.
3997 const MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
3998 if (MVT::isExtendedVT(VT)) {
3999 static std::set<MVT::ValueType> EVTs;
4000 return &(*EVTs.insert(VT).first);
4002 static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
4008 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4009 /// indicated value. This method ignores uses of other values defined by this
4011 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4012 assert(Value < getNumValues() && "Bad value!");
4014 // If there is only one value, this is easy.
4015 if (getNumValues() == 1)
4016 return use_size() == NUses;
4017 if (use_size() < NUses) return false;
4019 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4021 SmallPtrSet<SDNode*, 32> UsersHandled;
4023 // TODO: Only iterate over uses of a given value of the node
4024 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4025 if (*UI == TheValue) {
4032 // Found exactly the right number of uses?
4037 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4038 /// value. This method ignores uses of other values defined by this operation.
4039 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4040 assert(Value < getNumValues() && "Bad value!");
4042 if (use_empty()) return false;
4044 SDOperand TheValue(const_cast<SDNode *>(this), Value);
4046 SmallPtrSet<SDNode*, 32> UsersHandled;
4048 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4049 SDNode *User = UI->getUser();
4050 if (User->getNumOperands() == 1 ||
4051 UsersHandled.insert(User)) // First time we've seen this?
4052 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4053 if (User->getOperand(i) == TheValue) {
4062 /// isOnlyUseOf - Return true if this node is the only use of N.
4064 bool SDNode::isOnlyUseOf(SDNode *N) const {
4066 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4067 SDNode *User = I->getUser();
4077 /// isOperand - Return true if this node is an operand of N.
4079 bool SDOperandImpl::isOperandOf(SDNode *N) const {
4080 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4081 if (*this == N->getOperand(i))
4086 bool SDNode::isOperandOf(SDNode *N) const {
4087 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4088 if (this == N->OperandList[i].Val)
4093 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4094 /// be a chain) reaches the specified operand without crossing any
4095 /// side-effecting instructions. In practice, this looks through token
4096 /// factors and non-volatile loads. In order to remain efficient, this only
4097 /// looks a couple of nodes in, it does not do an exhaustive search.
4098 bool SDOperandImpl::reachesChainWithoutSideEffects(SDOperandImpl Dest,
4099 unsigned Depth) const {
4100 if (*this == Dest) return true;
4102 // Don't search too deeply, we just want to be able to see through
4103 // TokenFactor's etc.
4104 if (Depth == 0) return false;
4106 // If this is a token factor, all inputs to the TF happen in parallel. If any
4107 // of the operands of the TF reach dest, then we can do the xform.
4108 if (getOpcode() == ISD::TokenFactor) {
4109 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4110 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4115 // Loads don't have side effects, look through them.
4116 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4117 if (!Ld->isVolatile())
4118 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4124 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4125 SmallPtrSet<SDNode *, 32> &Visited) {
4126 if (found || !Visited.insert(N))
4129 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4130 SDNode *Op = N->getOperand(i).Val;
4135 findPredecessor(Op, P, found, Visited);
4139 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4140 /// is either an operand of N or it can be reached by recursively traversing
4141 /// up the operands.
4142 /// NOTE: this is an expensive method. Use it carefully.
4143 bool SDNode::isPredecessorOf(SDNode *N) const {
4144 SmallPtrSet<SDNode *, 32> Visited;
4146 findPredecessor(N, this, found, Visited);
4150 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4151 assert(Num < NumOperands && "Invalid child # of SDNode!");
4152 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4155 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4156 switch (getOpcode()) {
4158 if (getOpcode() < ISD::BUILTIN_OP_END)
4159 return "<<Unknown DAG Node>>";
4162 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4163 if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4164 return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4166 TargetLowering &TLI = G->getTargetLoweringInfo();
4168 TLI.getTargetNodeName(getOpcode());
4169 if (Name) return Name;
4172 return "<<Unknown Target Node>>";
4175 case ISD::PREFETCH: return "Prefetch";
4176 case ISD::MEMBARRIER: return "MemBarrier";
4177 case ISD::ATOMIC_LCS: return "AtomicLCS";
4178 case ISD::ATOMIC_LAS: return "AtomicLAS";
4179 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4180 case ISD::PCMARKER: return "PCMarker";
4181 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4182 case ISD::SRCVALUE: return "SrcValue";
4183 case ISD::MEMOPERAND: return "MemOperand";
4184 case ISD::EntryToken: return "EntryToken";
4185 case ISD::TokenFactor: return "TokenFactor";
4186 case ISD::AssertSext: return "AssertSext";
4187 case ISD::AssertZext: return "AssertZext";
4189 case ISD::STRING: return "String";
4190 case ISD::BasicBlock: return "BasicBlock";
4191 case ISD::ARG_FLAGS: return "ArgFlags";
4192 case ISD::VALUETYPE: return "ValueType";
4193 case ISD::Register: return "Register";
4195 case ISD::Constant: return "Constant";
4196 case ISD::ConstantFP: return "ConstantFP";
4197 case ISD::GlobalAddress: return "GlobalAddress";
4198 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4199 case ISD::FrameIndex: return "FrameIndex";
4200 case ISD::JumpTable: return "JumpTable";
4201 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4202 case ISD::RETURNADDR: return "RETURNADDR";
4203 case ISD::FRAMEADDR: return "FRAMEADDR";
4204 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4205 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4206 case ISD::EHSELECTION: return "EHSELECTION";
4207 case ISD::EH_RETURN: return "EH_RETURN";
4208 case ISD::ConstantPool: return "ConstantPool";
4209 case ISD::ExternalSymbol: return "ExternalSymbol";
4210 case ISD::INTRINSIC_WO_CHAIN: {
4211 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4212 return Intrinsic::getName((Intrinsic::ID)IID);
4214 case ISD::INTRINSIC_VOID:
4215 case ISD::INTRINSIC_W_CHAIN: {
4216 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4217 return Intrinsic::getName((Intrinsic::ID)IID);
4220 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4221 case ISD::TargetConstant: return "TargetConstant";
4222 case ISD::TargetConstantFP:return "TargetConstantFP";
4223 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4224 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4225 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4226 case ISD::TargetJumpTable: return "TargetJumpTable";
4227 case ISD::TargetConstantPool: return "TargetConstantPool";
4228 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4230 case ISD::CopyToReg: return "CopyToReg";
4231 case ISD::CopyFromReg: return "CopyFromReg";
4232 case ISD::UNDEF: return "undef";
4233 case ISD::MERGE_VALUES: return "merge_values";
4234 case ISD::INLINEASM: return "inlineasm";
4235 case ISD::LABEL: return "label";
4236 case ISD::DECLARE: return "declare";
4237 case ISD::HANDLENODE: return "handlenode";
4238 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4239 case ISD::CALL: return "call";
4242 case ISD::FABS: return "fabs";
4243 case ISD::FNEG: return "fneg";
4244 case ISD::FSQRT: return "fsqrt";
4245 case ISD::FSIN: return "fsin";
4246 case ISD::FCOS: return "fcos";
4247 case ISD::FPOWI: return "fpowi";
4248 case ISD::FPOW: return "fpow";
4251 case ISD::ADD: return "add";
4252 case ISD::SUB: return "sub";
4253 case ISD::MUL: return "mul";
4254 case ISD::MULHU: return "mulhu";
4255 case ISD::MULHS: return "mulhs";
4256 case ISD::SDIV: return "sdiv";
4257 case ISD::UDIV: return "udiv";
4258 case ISD::SREM: return "srem";
4259 case ISD::UREM: return "urem";
4260 case ISD::SMUL_LOHI: return "smul_lohi";
4261 case ISD::UMUL_LOHI: return "umul_lohi";
4262 case ISD::SDIVREM: return "sdivrem";
4263 case ISD::UDIVREM: return "divrem";
4264 case ISD::AND: return "and";
4265 case ISD::OR: return "or";
4266 case ISD::XOR: return "xor";
4267 case ISD::SHL: return "shl";
4268 case ISD::SRA: return "sra";
4269 case ISD::SRL: return "srl";
4270 case ISD::ROTL: return "rotl";
4271 case ISD::ROTR: return "rotr";
4272 case ISD::FADD: return "fadd";
4273 case ISD::FSUB: return "fsub";
4274 case ISD::FMUL: return "fmul";
4275 case ISD::FDIV: return "fdiv";
4276 case ISD::FREM: return "frem";
4277 case ISD::FCOPYSIGN: return "fcopysign";
4278 case ISD::FGETSIGN: return "fgetsign";
4280 case ISD::SETCC: return "setcc";
4281 case ISD::SELECT: return "select";
4282 case ISD::SELECT_CC: return "select_cc";
4283 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4284 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4285 case ISD::CONCAT_VECTORS: return "concat_vectors";
4286 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4287 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4288 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4289 case ISD::CARRY_FALSE: return "carry_false";
4290 case ISD::ADDC: return "addc";
4291 case ISD::ADDE: return "adde";
4292 case ISD::SUBC: return "subc";
4293 case ISD::SUBE: return "sube";
4294 case ISD::SHL_PARTS: return "shl_parts";
4295 case ISD::SRA_PARTS: return "sra_parts";
4296 case ISD::SRL_PARTS: return "srl_parts";
4298 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4299 case ISD::INSERT_SUBREG: return "insert_subreg";
4301 // Conversion operators.
4302 case ISD::SIGN_EXTEND: return "sign_extend";
4303 case ISD::ZERO_EXTEND: return "zero_extend";
4304 case ISD::ANY_EXTEND: return "any_extend";
4305 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4306 case ISD::TRUNCATE: return "truncate";
4307 case ISD::FP_ROUND: return "fp_round";
4308 case ISD::FLT_ROUNDS_: return "flt_rounds";
4309 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4310 case ISD::FP_EXTEND: return "fp_extend";
4312 case ISD::SINT_TO_FP: return "sint_to_fp";
4313 case ISD::UINT_TO_FP: return "uint_to_fp";
4314 case ISD::FP_TO_SINT: return "fp_to_sint";
4315 case ISD::FP_TO_UINT: return "fp_to_uint";
4316 case ISD::BIT_CONVERT: return "bit_convert";
4318 // Control flow instructions
4319 case ISD::BR: return "br";
4320 case ISD::BRIND: return "brind";
4321 case ISD::BR_JT: return "br_jt";
4322 case ISD::BRCOND: return "brcond";
4323 case ISD::BR_CC: return "br_cc";
4324 case ISD::RET: return "ret";
4325 case ISD::CALLSEQ_START: return "callseq_start";
4326 case ISD::CALLSEQ_END: return "callseq_end";
4329 case ISD::LOAD: return "load";
4330 case ISD::STORE: return "store";
4331 case ISD::VAARG: return "vaarg";
4332 case ISD::VACOPY: return "vacopy";
4333 case ISD::VAEND: return "vaend";
4334 case ISD::VASTART: return "vastart";
4335 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4336 case ISD::EXTRACT_ELEMENT: return "extract_element";
4337 case ISD::BUILD_PAIR: return "build_pair";
4338 case ISD::STACKSAVE: return "stacksave";
4339 case ISD::STACKRESTORE: return "stackrestore";
4340 case ISD::TRAP: return "trap";
4343 case ISD::BSWAP: return "bswap";
4344 case ISD::CTPOP: return "ctpop";
4345 case ISD::CTTZ: return "cttz";
4346 case ISD::CTLZ: return "ctlz";
4349 case ISD::LOCATION: return "location";
4350 case ISD::DEBUG_LOC: return "debug_loc";
4353 case ISD::TRAMPOLINE: return "trampoline";
4356 switch (cast<CondCodeSDNode>(this)->get()) {
4357 default: assert(0 && "Unknown setcc condition!");
4358 case ISD::SETOEQ: return "setoeq";
4359 case ISD::SETOGT: return "setogt";
4360 case ISD::SETOGE: return "setoge";
4361 case ISD::SETOLT: return "setolt";
4362 case ISD::SETOLE: return "setole";
4363 case ISD::SETONE: return "setone";
4365 case ISD::SETO: return "seto";
4366 case ISD::SETUO: return "setuo";
4367 case ISD::SETUEQ: return "setue";
4368 case ISD::SETUGT: return "setugt";
4369 case ISD::SETUGE: return "setuge";
4370 case ISD::SETULT: return "setult";
4371 case ISD::SETULE: return "setule";
4372 case ISD::SETUNE: return "setune";
4374 case ISD::SETEQ: return "seteq";
4375 case ISD::SETGT: return "setgt";
4376 case ISD::SETGE: return "setge";
4377 case ISD::SETLT: return "setlt";
4378 case ISD::SETLE: return "setle";
4379 case ISD::SETNE: return "setne";
4384 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4393 return "<post-inc>";
4395 return "<post-dec>";
4399 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4400 std::string S = "< ";
4414 if (getByValAlign())
4415 S += "byval-align:" + utostr(getByValAlign()) + " ";
4417 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4419 S += "byval-size:" + utostr(getByValSize()) + " ";
4423 void SDNode::dump() const { dump(0); }
4424 void SDNode::dump(const SelectionDAG *G) const {
4425 cerr << (void*)this << ": ";
4427 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4429 if (getValueType(i) == MVT::Other)
4432 cerr << MVT::getValueTypeString(getValueType(i));
4434 cerr << " = " << getOperationName(G);
4437 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4438 if (i) cerr << ", ";
4439 cerr << (void*)getOperand(i).Val;
4440 if (unsigned RN = getOperand(i).ResNo)
4444 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4445 SDNode *Mask = getOperand(2).Val;
4447 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4449 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4452 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4457 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4458 cerr << "<" << CSDN->getValue() << ">";
4459 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4460 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4461 cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4462 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4463 cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4465 cerr << "<APFloat(";
4466 CSDN->getValueAPF().convertToAPInt().dump();
4469 } else if (const GlobalAddressSDNode *GADN =
4470 dyn_cast<GlobalAddressSDNode>(this)) {
4471 int offset = GADN->getOffset();
4473 WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4475 cerr << " + " << offset;
4477 cerr << " " << offset;
4478 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4479 cerr << "<" << FIDN->getIndex() << ">";
4480 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4481 cerr << "<" << JTDN->getIndex() << ">";
4482 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4483 int offset = CP->getOffset();
4484 if (CP->isMachineConstantPoolEntry())
4485 cerr << "<" << *CP->getMachineCPVal() << ">";
4487 cerr << "<" << *CP->getConstVal() << ">";
4489 cerr << " + " << offset;
4491 cerr << " " << offset;
4492 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4494 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4496 cerr << LBB->getName() << " ";
4497 cerr << (const void*)BBDN->getBasicBlock() << ">";
4498 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4499 if (G && R->getReg() &&
4500 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4501 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4503 cerr << " #" << R->getReg();
4505 } else if (const ExternalSymbolSDNode *ES =
4506 dyn_cast<ExternalSymbolSDNode>(this)) {
4507 cerr << "'" << ES->getSymbol() << "'";
4508 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4510 cerr << "<" << M->getValue() << ">";
4513 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4514 if (M->MO.getValue())
4515 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4517 cerr << "<null:" << M->MO.getOffset() << ">";
4518 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4519 cerr << N->getArgFlags().getArgFlagsString();
4520 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4521 cerr << ":" << MVT::getValueTypeString(N->getVT());
4522 } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4523 const Value *SrcValue = LD->getSrcValue();
4524 int SrcOffset = LD->getSrcValueOffset();
4530 cerr << ":" << SrcOffset << ">";
4533 switch (LD->getExtensionType()) {
4534 default: doExt = false; break;
4536 cerr << " <anyext ";
4546 cerr << MVT::getValueTypeString(LD->getMemoryVT()) << ">";
4548 const char *AM = getIndexedModeName(LD->getAddressingMode());
4551 if (LD->isVolatile())
4552 cerr << " <volatile>";
4553 cerr << " alignment=" << LD->getAlignment();
4554 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4555 const Value *SrcValue = ST->getSrcValue();
4556 int SrcOffset = ST->getSrcValueOffset();
4562 cerr << ":" << SrcOffset << ">";
4564 if (ST->isTruncatingStore())
4566 << MVT::getValueTypeString(ST->getMemoryVT()) << ">";
4568 const char *AM = getIndexedModeName(ST->getAddressingMode());
4571 if (ST->isVolatile())
4572 cerr << " <volatile>";
4573 cerr << " alignment=" << ST->getAlignment();
4577 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4578 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4579 if (N->getOperand(i).Val->hasOneUse())
4580 DumpNodes(N->getOperand(i).Val, indent+2, G);
4582 cerr << "\n" << std::string(indent+2, ' ')
4583 << (void*)N->getOperand(i).Val << ": <multiple use>";
4586 cerr << "\n" << std::string(indent, ' ');
4590 void SelectionDAG::dump() const {
4591 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4592 std::vector<const SDNode*> Nodes;
4593 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4597 std::sort(Nodes.begin(), Nodes.end());
4599 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4600 if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4601 DumpNodes(Nodes[i], 2, this);
4604 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4609 const Type *ConstantPoolSDNode::getType() const {
4610 if (isMachineConstantPoolEntry())
4611 return Val.MachineCPVal->getType();
4612 return Val.ConstVal->getType();