1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAG class.
12 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/GlobalAlias.h"
17 #include "llvm/GlobalVariable.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/StringExtras.h"
42 /// makeVTList - Return an instance of the SDVTList struct initialized with the
43 /// specified members.
44 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
45 SDVTList Res = {VTs, NumVTs};
49 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
50 switch (VT.getSimpleVT()) {
51 default: assert(0 && "Unknown FP format");
52 case MVT::f32: return &APFloat::IEEEsingle;
53 case MVT::f64: return &APFloat::IEEEdouble;
54 case MVT::f80: return &APFloat::x87DoubleExtended;
55 case MVT::f128: return &APFloat::IEEEquad;
56 case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
60 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
62 //===----------------------------------------------------------------------===//
63 // ConstantFPSDNode Class
64 //===----------------------------------------------------------------------===//
66 /// isExactlyValue - We don't rely on operator== working on double values, as
67 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
68 /// As such, this method can be used to do an exact bit-for-bit comparison of
69 /// two floating point values.
70 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
71 return Value.bitwiseIsEqual(V);
74 bool ConstantFPSDNode::isValueValidForType(MVT VT,
76 assert(VT.isFloatingPoint() && "Can only convert between FP types");
78 // PPC long double cannot be converted to any other type.
79 if (VT == MVT::ppcf128 ||
80 &Val.getSemantics() == &APFloat::PPCDoubleDouble)
83 // convert modifies in place, so make a copy.
84 APFloat Val2 = APFloat(Val);
85 return Val2.convert(*MVTToAPFloatSemantics(VT),
86 APFloat::rmNearestTiesToEven) == APFloat::opOK;
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 /// isBuildVectorAllOnes - Return true if the specified node is a
94 /// BUILD_VECTOR where all of the elements are ~0 or undef.
95 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
96 // Look through a bit convert.
97 if (N->getOpcode() == ISD::BIT_CONVERT)
98 N = N->getOperand(0).Val;
100 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
102 unsigned i = 0, e = N->getNumOperands();
104 // Skip over all of the undef values.
105 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
108 // Do not accept an all-undef vector.
109 if (i == e) return false;
111 // Do not accept build_vectors that aren't all constants or which have non-~0
113 SDValue NotZero = N->getOperand(i);
114 if (isa<ConstantSDNode>(NotZero)) {
115 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
117 } else if (isa<ConstantFPSDNode>(NotZero)) {
118 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
119 convertToAPInt().isAllOnesValue())
124 // Okay, we have at least one ~0 value, check to see if the rest match or are
126 for (++i; i != e; ++i)
127 if (N->getOperand(i) != NotZero &&
128 N->getOperand(i).getOpcode() != ISD::UNDEF)
134 /// isBuildVectorAllZeros - Return true if the specified node is a
135 /// BUILD_VECTOR where all of the elements are 0 or undef.
136 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
137 // Look through a bit convert.
138 if (N->getOpcode() == ISD::BIT_CONVERT)
139 N = N->getOperand(0).Val;
141 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
143 unsigned i = 0, e = N->getNumOperands();
145 // Skip over all of the undef values.
146 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
149 // Do not accept an all-undef vector.
150 if (i == e) return false;
152 // Do not accept build_vectors that aren't all constants or which have non-~0
154 SDValue Zero = N->getOperand(i);
155 if (isa<ConstantSDNode>(Zero)) {
156 if (!cast<ConstantSDNode>(Zero)->isNullValue())
158 } else if (isa<ConstantFPSDNode>(Zero)) {
159 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
164 // Okay, we have at least one ~0 value, check to see if the rest match or are
166 for (++i; i != e; ++i)
167 if (N->getOperand(i) != Zero &&
168 N->getOperand(i).getOpcode() != ISD::UNDEF)
173 /// isScalarToVector - Return true if the specified node is a
174 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
175 /// element is not an undef.
176 bool ISD::isScalarToVector(const SDNode *N) {
177 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
180 if (N->getOpcode() != ISD::BUILD_VECTOR)
182 if (N->getOperand(0).getOpcode() == ISD::UNDEF)
184 unsigned NumElems = N->getNumOperands();
185 for (unsigned i = 1; i < NumElems; ++i) {
186 SDValue V = N->getOperand(i);
187 if (V.getOpcode() != ISD::UNDEF)
194 /// isDebugLabel - Return true if the specified node represents a debug
195 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
196 bool ISD::isDebugLabel(const SDNode *N) {
198 if (N->getOpcode() == ISD::DBG_LABEL)
200 if (N->isMachineOpcode() &&
201 N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
206 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
207 /// when given the operation for (X op Y).
208 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
209 // To perform this operation, we just need to swap the L and G bits of the
211 unsigned OldL = (Operation >> 2) & 1;
212 unsigned OldG = (Operation >> 1) & 1;
213 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
214 (OldL << 1) | // New G bit
215 (OldG << 2)); // New L bit.
218 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
219 /// 'op' is a valid SetCC operation.
220 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
221 unsigned Operation = Op;
223 Operation ^= 7; // Flip L, G, E bits, but not U.
225 Operation ^= 15; // Flip all of the condition bits.
226 if (Operation > ISD::SETTRUE2)
227 Operation &= ~8; // Don't let N and U bits get set.
228 return ISD::CondCode(Operation);
232 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
233 /// signed operation and 2 if the result is an unsigned comparison. Return zero
234 /// if the operation does not depend on the sign of the input (setne and seteq).
235 static int isSignedOp(ISD::CondCode Opcode) {
237 default: assert(0 && "Illegal integer setcc operation!");
239 case ISD::SETNE: return 0;
243 case ISD::SETGE: return 1;
247 case ISD::SETUGE: return 2;
251 /// getSetCCOrOperation - Return the result of a logical OR between different
252 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
253 /// returns SETCC_INVALID if it is not possible to represent the resultant
255 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
257 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
258 // Cannot fold a signed integer setcc with an unsigned integer setcc.
259 return ISD::SETCC_INVALID;
261 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
263 // If the N and U bits get set then the resultant comparison DOES suddenly
264 // care about orderedness, and is true when ordered.
265 if (Op > ISD::SETTRUE2)
266 Op &= ~16; // Clear the U bit if the N bit is set.
268 // Canonicalize illegal integer setcc's.
269 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
272 return ISD::CondCode(Op);
275 /// getSetCCAndOperation - Return the result of a logical AND between different
276 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
277 /// function returns zero if it is not possible to represent the resultant
279 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
281 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
282 // Cannot fold a signed setcc with an unsigned setcc.
283 return ISD::SETCC_INVALID;
285 // Combine all of the condition bits.
286 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
288 // Canonicalize illegal integer setcc's.
292 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
293 case ISD::SETOEQ: // SETEQ & SETU[LG]E
294 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
295 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
296 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
303 const TargetMachine &SelectionDAG::getTarget() const {
304 return TLI.getTargetMachine();
307 //===----------------------------------------------------------------------===//
308 // SDNode Profile Support
309 //===----------------------------------------------------------------------===//
311 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
313 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
317 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
318 /// solely with their pointer.
319 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
320 ID.AddPointer(VTList.VTs);
323 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
325 static void AddNodeIDOperands(FoldingSetNodeID &ID,
326 const SDValue *Ops, unsigned NumOps) {
327 for (; NumOps; --NumOps, ++Ops) {
328 ID.AddPointer(Ops->Val);
329 ID.AddInteger(Ops->ResNo);
333 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
335 static void AddNodeIDOperands(FoldingSetNodeID &ID,
336 const SDUse *Ops, unsigned NumOps) {
337 for (; NumOps; --NumOps, ++Ops) {
338 ID.AddPointer(Ops->getVal());
339 ID.AddInteger(Ops->getSDValue().ResNo);
343 static void AddNodeIDNode(FoldingSetNodeID &ID,
344 unsigned short OpC, SDVTList VTList,
345 const SDValue *OpList, unsigned N) {
346 AddNodeIDOpcode(ID, OpC);
347 AddNodeIDValueTypes(ID, VTList);
348 AddNodeIDOperands(ID, OpList, N);
352 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
354 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
355 AddNodeIDOpcode(ID, N->getOpcode());
356 // Add the return value info.
357 AddNodeIDValueTypes(ID, N->getVTList());
358 // Add the operand info.
359 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
361 // Handle SDNode leafs with special info.
362 switch (N->getOpcode()) {
363 default: break; // Normal nodes don't need extra info.
365 ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
367 case ISD::TargetConstant:
369 ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
371 case ISD::TargetConstantFP:
372 case ISD::ConstantFP: {
373 ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
376 case ISD::TargetGlobalAddress:
377 case ISD::GlobalAddress:
378 case ISD::TargetGlobalTLSAddress:
379 case ISD::GlobalTLSAddress: {
380 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
381 ID.AddPointer(GA->getGlobal());
382 ID.AddInteger(GA->getOffset());
385 case ISD::BasicBlock:
386 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
389 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
391 case ISD::DBG_STOPPOINT: {
392 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
393 ID.AddInteger(DSP->getLine());
394 ID.AddInteger(DSP->getColumn());
395 ID.AddPointer(DSP->getCompileUnit());
399 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
401 case ISD::MEMOPERAND: {
402 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
406 case ISD::FrameIndex:
407 case ISD::TargetFrameIndex:
408 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
411 case ISD::TargetJumpTable:
412 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
414 case ISD::ConstantPool:
415 case ISD::TargetConstantPool: {
416 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
417 ID.AddInteger(CP->getAlignment());
418 ID.AddInteger(CP->getOffset());
419 if (CP->isMachineConstantPoolEntry())
420 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
422 ID.AddPointer(CP->getConstVal());
426 const LoadSDNode *LD = cast<LoadSDNode>(N);
427 ID.AddInteger(LD->getAddressingMode());
428 ID.AddInteger(LD->getExtensionType());
429 ID.AddInteger(LD->getMemoryVT().getRawBits());
430 ID.AddInteger(LD->getRawFlags());
434 const StoreSDNode *ST = cast<StoreSDNode>(N);
435 ID.AddInteger(ST->getAddressingMode());
436 ID.AddInteger(ST->isTruncatingStore());
437 ID.AddInteger(ST->getMemoryVT().getRawBits());
438 ID.AddInteger(ST->getRawFlags());
441 case ISD::ATOMIC_CMP_SWAP:
442 case ISD::ATOMIC_LOAD_ADD:
443 case ISD::ATOMIC_SWAP:
444 case ISD::ATOMIC_LOAD_SUB:
445 case ISD::ATOMIC_LOAD_AND:
446 case ISD::ATOMIC_LOAD_OR:
447 case ISD::ATOMIC_LOAD_XOR:
448 case ISD::ATOMIC_LOAD_NAND:
449 case ISD::ATOMIC_LOAD_MIN:
450 case ISD::ATOMIC_LOAD_MAX:
451 case ISD::ATOMIC_LOAD_UMIN:
452 case ISD::ATOMIC_LOAD_UMAX: {
453 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
454 ID.AddInteger(AT->getRawFlags());
457 } // end switch (N->getOpcode())
460 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
461 /// the CSE map that carries both alignment and volatility information.
463 static unsigned encodeMemSDNodeFlags(bool isVolatile, unsigned Alignment) {
464 return isVolatile | ((Log2_32(Alignment) + 1) << 1);
467 //===----------------------------------------------------------------------===//
468 // SelectionDAG Class
469 //===----------------------------------------------------------------------===//
471 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
473 void SelectionDAG::RemoveDeadNodes() {
474 // Create a dummy node (which is not added to allnodes), that adds a reference
475 // to the root node, preventing it from being deleted.
476 HandleSDNode Dummy(getRoot());
478 SmallVector<SDNode*, 128> DeadNodes;
480 // Add all obviously-dead nodes to the DeadNodes worklist.
481 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
483 DeadNodes.push_back(I);
485 RemoveDeadNodes(DeadNodes);
487 // If the root changed (e.g. it was a dead load, update the root).
488 setRoot(Dummy.getValue());
491 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
492 /// given list, and any nodes that become unreachable as a result.
493 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
494 DAGUpdateListener *UpdateListener) {
496 // Process the worklist, deleting the nodes and adding their uses to the
498 while (!DeadNodes.empty()) {
499 SDNode *N = DeadNodes.back();
500 DeadNodes.pop_back();
503 UpdateListener->NodeDeleted(N, 0);
505 // Take the node out of the appropriate CSE map.
506 RemoveNodeFromCSEMaps(N);
508 // Next, brutally remove the operand list. This is safe to do, as there are
509 // no cycles in the graph.
510 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
511 SDNode *Operand = I->getVal();
512 Operand->removeUser(std::distance(N->op_begin(), I), N);
514 // Now that we removed this operand, see if there are no uses of it left.
515 if (Operand->use_empty())
516 DeadNodes.push_back(Operand);
518 if (N->OperandsNeedDelete) {
519 delete[] N->OperandList;
524 // Finally, remove N itself.
529 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
530 SmallVector<SDNode*, 16> DeadNodes(1, N);
531 RemoveDeadNodes(DeadNodes, UpdateListener);
534 void SelectionDAG::DeleteNode(SDNode *N) {
535 assert(N->use_empty() && "Cannot delete a node that is not dead!");
537 // First take this out of the appropriate CSE map.
538 RemoveNodeFromCSEMaps(N);
540 // Finally, remove uses due to operands of this node, remove from the
541 // AllNodes list, and delete the node.
542 DeleteNodeNotInCSEMaps(N);
545 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
547 // Drop all of the operands and decrement used nodes use counts.
548 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
549 I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
550 if (N->OperandsNeedDelete) {
551 delete[] N->OperandList;
559 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
560 /// correspond to it. This is useful when we're about to delete or repurpose
561 /// the node. We don't want future request for structurally identical nodes
562 /// to return N anymore.
563 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
565 switch (N->getOpcode()) {
566 case ISD::HANDLENODE: return; // noop.
568 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
569 "Cond code doesn't exist!");
570 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
571 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
573 case ISD::ExternalSymbol:
574 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
576 case ISD::TargetExternalSymbol:
578 TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
580 case ISD::VALUETYPE: {
581 MVT VT = cast<VTSDNode>(N)->getVT();
582 if (VT.isExtended()) {
583 Erased = ExtendedValueTypeNodes.erase(VT);
585 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
586 ValueTypeNodes[VT.getSimpleVT()] = 0;
591 // Remove it from the CSE Map.
592 Erased = CSEMap.RemoveNode(N);
596 // Verify that the node was actually in one of the CSE maps, unless it has a
597 // flag result (which cannot be CSE'd) or is one of the special cases that are
598 // not subject to CSE.
599 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
600 !N->isTargetOpcode() &&
601 N->getOpcode() != ISD::DBG_LABEL &&
602 N->getOpcode() != ISD::DBG_STOPPOINT &&
603 N->getOpcode() != ISD::EH_LABEL &&
604 N->getOpcode() != ISD::DECLARE) {
607 assert(0 && "Node is not in map!");
612 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps. It
613 /// has been taken out and modified in some way. If the specified node already
614 /// exists in the CSE maps, do not modify the maps, but return the existing node
615 /// instead. If it doesn't exist, add it and return null.
617 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
618 assert(N->getNumOperands() && "This is a leaf node!");
620 if (N->getValueType(0) == MVT::Flag)
621 return 0; // Never CSE anything that produces a flag.
623 switch (N->getOpcode()) {
625 case ISD::HANDLENODE:
627 case ISD::DBG_STOPPOINT:
630 return 0; // Never add these nodes.
633 // Check that remaining values produced are not flags.
634 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
635 if (N->getValueType(i) == MVT::Flag)
636 return 0; // Never CSE anything that produces a flag.
638 SDNode *New = CSEMap.GetOrInsertNode(N);
639 if (New != N) return New; // Node already existed.
643 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
644 /// were replaced with those specified. If this node is never memoized,
645 /// return null, otherwise return a pointer to the slot it would take. If a
646 /// node already exists with these operands, the slot will be non-null.
647 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
649 if (N->getValueType(0) == MVT::Flag)
650 return 0; // Never CSE anything that produces a flag.
652 switch (N->getOpcode()) {
654 case ISD::HANDLENODE:
656 case ISD::DBG_STOPPOINT:
658 return 0; // Never add these nodes.
661 // Check that remaining values produced are not flags.
662 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
663 if (N->getValueType(i) == MVT::Flag)
664 return 0; // Never CSE anything that produces a flag.
666 SDValue Ops[] = { Op };
668 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
669 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
672 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
673 /// were replaced with those specified. If this node is never memoized,
674 /// return null, otherwise return a pointer to the slot it would take. If a
675 /// node already exists with these operands, the slot will be non-null.
676 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
677 SDValue Op1, SDValue Op2,
679 if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
681 // Check that remaining values produced are not flags.
682 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
683 if (N->getValueType(i) == MVT::Flag)
684 return 0; // Never CSE anything that produces a flag.
686 SDValue Ops[] = { Op1, Op2 };
688 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
689 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
693 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
694 /// were replaced with those specified. If this node is never memoized,
695 /// return null, otherwise return a pointer to the slot it would take. If a
696 /// node already exists with these operands, the slot will be non-null.
697 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
698 const SDValue *Ops,unsigned NumOps,
700 if (N->getValueType(0) == MVT::Flag)
701 return 0; // Never CSE anything that produces a flag.
703 switch (N->getOpcode()) {
705 case ISD::HANDLENODE:
707 case ISD::DBG_STOPPOINT:
710 return 0; // Never add these nodes.
713 // Check that remaining values produced are not flags.
714 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
715 if (N->getValueType(i) == MVT::Flag)
716 return 0; // Never CSE anything that produces a flag.
719 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
721 if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
722 ID.AddInteger(LD->getAddressingMode());
723 ID.AddInteger(LD->getExtensionType());
724 ID.AddInteger(LD->getMemoryVT().getRawBits());
725 ID.AddInteger(LD->getRawFlags());
726 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
727 ID.AddInteger(ST->getAddressingMode());
728 ID.AddInteger(ST->isTruncatingStore());
729 ID.AddInteger(ST->getMemoryVT().getRawBits());
730 ID.AddInteger(ST->getRawFlags());
733 return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
736 /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
737 void SelectionDAG::VerifyNode(SDNode *N) {
738 switch (N->getOpcode()) {
741 case ISD::BUILD_VECTOR: {
742 assert(N->getNumValues() == 1 && "Too many results for BUILD_VECTOR!");
743 assert(N->getValueType(0).isVector() && "Wrong BUILD_VECTOR return type!");
744 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
745 "Wrong number of BUILD_VECTOR operands!");
746 MVT EltVT = N->getValueType(0).getVectorElementType();
747 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
748 assert(I->getSDValue().getValueType() == EltVT &&
749 "Wrong BUILD_VECTOR operand type!");
755 /// getMVTAlignment - Compute the default alignment value for the
758 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
759 const Type *Ty = VT == MVT::iPTR ?
760 PointerType::get(Type::Int8Ty, 0) :
763 return TLI.getTargetData()->getABITypeAlignment(Ty);
766 SelectionDAG::~SelectionDAG() {
767 while (!AllNodes.empty()) {
768 SDNode *N = AllNodes.remove(AllNodes.begin());
769 N->SetNextInBucket(0);
770 if (N->OperandsNeedDelete) {
771 delete [] N->OperandList;
778 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
779 if (Op.getValueType() == VT) return Op;
780 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
782 return getNode(ISD::AND, Op.getValueType(), Op,
783 getConstant(Imm, Op.getValueType()));
786 SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
787 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
788 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
791 SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
792 assert(VT.isInteger() && "Cannot create FP integer constant!");
794 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
795 assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
796 "APInt size does not match type size!");
798 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
800 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
804 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
806 return SDValue(N, 0);
808 N = NodeAllocator.Allocate<ConstantSDNode>();
809 new (N) ConstantSDNode(isT, Val, EltVT);
810 CSEMap.InsertNode(N, IP);
811 AllNodes.push_back(N);
814 SDValue Result(N, 0);
816 SmallVector<SDValue, 8> Ops;
817 Ops.assign(VT.getVectorNumElements(), Result);
818 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
823 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
824 return getConstant(Val, TLI.getPointerTy(), isTarget);
828 SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
829 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
832 VT.isVector() ? VT.getVectorElementType() : VT;
834 // Do the map lookup using the actual bit pattern for the floating point
835 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
836 // we don't have issues with SNANs.
837 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
839 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
843 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
845 return SDValue(N, 0);
847 N = NodeAllocator.Allocate<ConstantFPSDNode>();
848 new (N) ConstantFPSDNode(isTarget, V, EltVT);
849 CSEMap.InsertNode(N, IP);
850 AllNodes.push_back(N);
853 SDValue Result(N, 0);
855 SmallVector<SDValue, 8> Ops;
856 Ops.assign(VT.getVectorNumElements(), Result);
857 Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
862 SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
864 VT.isVector() ? VT.getVectorElementType() : VT;
866 return getConstantFP(APFloat((float)Val), VT, isTarget);
868 return getConstantFP(APFloat(Val), VT, isTarget);
871 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
876 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
878 // If GV is an alias then use the aliasee for determining thread-localness.
879 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
880 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
883 if (GVar && GVar->isThreadLocal())
884 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
886 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
889 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
891 ID.AddInteger(Offset);
893 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
894 return SDValue(E, 0);
895 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
896 new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
897 CSEMap.InsertNode(N, IP);
898 AllNodes.push_back(N);
899 return SDValue(N, 0);
902 SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
903 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
905 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
908 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
909 return SDValue(E, 0);
910 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
911 new (N) FrameIndexSDNode(FI, VT, isTarget);
912 CSEMap.InsertNode(N, IP);
913 AllNodes.push_back(N);
914 return SDValue(N, 0);
917 SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
918 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
920 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
923 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
924 return SDValue(E, 0);
925 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
926 new (N) JumpTableSDNode(JTI, VT, isTarget);
927 CSEMap.InsertNode(N, IP);
928 AllNodes.push_back(N);
929 return SDValue(N, 0);
932 SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
933 unsigned Alignment, int Offset,
935 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
937 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
938 ID.AddInteger(Alignment);
939 ID.AddInteger(Offset);
942 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
943 return SDValue(E, 0);
944 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
945 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
946 CSEMap.InsertNode(N, IP);
947 AllNodes.push_back(N);
948 return SDValue(N, 0);
952 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
953 unsigned Alignment, int Offset,
955 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
957 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
958 ID.AddInteger(Alignment);
959 ID.AddInteger(Offset);
960 C->AddSelectionDAGCSEId(ID);
962 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
963 return SDValue(E, 0);
964 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
965 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
966 CSEMap.InsertNode(N, IP);
967 AllNodes.push_back(N);
968 return SDValue(N, 0);
972 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
974 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
977 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
978 return SDValue(E, 0);
979 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
980 new (N) BasicBlockSDNode(MBB);
981 CSEMap.InsertNode(N, IP);
982 AllNodes.push_back(N);
983 return SDValue(N, 0);
986 SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
988 AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
989 ID.AddInteger(Flags.getRawBits());
991 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
992 return SDValue(E, 0);
993 SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
994 new (N) ARG_FLAGSSDNode(Flags);
995 CSEMap.InsertNode(N, IP);
996 AllNodes.push_back(N);
997 return SDValue(N, 0);
1000 SDValue SelectionDAG::getValueType(MVT VT) {
1001 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
1002 ValueTypeNodes.resize(VT.getSimpleVT()+1);
1004 SDNode *&N = VT.isExtended() ?
1005 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
1007 if (N) return SDValue(N, 0);
1008 N = NodeAllocator.Allocate<VTSDNode>();
1009 new (N) VTSDNode(VT);
1010 AllNodes.push_back(N);
1011 return SDValue(N, 0);
1014 SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
1015 SDNode *&N = ExternalSymbols[Sym];
1016 if (N) return SDValue(N, 0);
1017 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1018 new (N) ExternalSymbolSDNode(false, Sym, VT);
1019 AllNodes.push_back(N);
1020 return SDValue(N, 0);
1023 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
1024 SDNode *&N = TargetExternalSymbols[Sym];
1025 if (N) return SDValue(N, 0);
1026 N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
1027 new (N) ExternalSymbolSDNode(true, Sym, VT);
1028 AllNodes.push_back(N);
1029 return SDValue(N, 0);
1032 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1033 if ((unsigned)Cond >= CondCodeNodes.size())
1034 CondCodeNodes.resize(Cond+1);
1036 if (CondCodeNodes[Cond] == 0) {
1037 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
1038 new (N) CondCodeSDNode(Cond);
1039 CondCodeNodes[Cond] = N;
1040 AllNodes.push_back(N);
1042 return SDValue(CondCodeNodes[Cond], 0);
1045 SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
1046 FoldingSetNodeID ID;
1047 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
1048 ID.AddInteger(RegNo);
1050 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1051 return SDValue(E, 0);
1052 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
1053 new (N) RegisterSDNode(RegNo, VT);
1054 CSEMap.InsertNode(N, IP);
1055 AllNodes.push_back(N);
1056 return SDValue(N, 0);
1059 SDValue SelectionDAG::getDbgStopPoint(SDValue Root,
1060 unsigned Line, unsigned Col,
1061 const CompileUnitDesc *CU) {
1062 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
1063 new (N) DbgStopPointSDNode(Root, Line, Col, CU);
1064 AllNodes.push_back(N);
1065 return SDValue(N, 0);
1068 SDValue SelectionDAG::getLabel(unsigned Opcode,
1071 FoldingSetNodeID ID;
1072 SDValue Ops[] = { Root };
1073 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
1074 ID.AddInteger(LabelID);
1076 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1077 return SDValue(E, 0);
1078 SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
1079 new (N) LabelSDNode(Opcode, Root, LabelID);
1080 CSEMap.InsertNode(N, IP);
1081 AllNodes.push_back(N);
1082 return SDValue(N, 0);
1085 SDValue SelectionDAG::getSrcValue(const Value *V) {
1086 assert((!V || isa<PointerType>(V->getType())) &&
1087 "SrcValue is not a pointer?");
1089 FoldingSetNodeID ID;
1090 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
1094 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1095 return SDValue(E, 0);
1097 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
1098 new (N) SrcValueSDNode(V);
1099 CSEMap.InsertNode(N, IP);
1100 AllNodes.push_back(N);
1101 return SDValue(N, 0);
1104 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1105 const Value *v = MO.getValue();
1106 assert((!v || isa<PointerType>(v->getType())) &&
1107 "SrcValue is not a pointer?");
1109 FoldingSetNodeID ID;
1110 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
1114 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1115 return SDValue(E, 0);
1117 SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
1118 new (N) MemOperandSDNode(MO);
1119 CSEMap.InsertNode(N, IP);
1120 AllNodes.push_back(N);
1121 return SDValue(N, 0);
1124 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1125 /// specified value type.
1126 SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
1127 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1128 unsigned ByteSize = VT.getSizeInBits()/8;
1129 const Type *Ty = VT.getTypeForMVT();
1130 unsigned StackAlign =
1131 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
1133 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1134 return getFrameIndex(FrameIdx, TLI.getPointerTy());
1137 SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
1138 SDValue N2, ISD::CondCode Cond) {
1139 // These setcc operations always fold.
1143 case ISD::SETFALSE2: return getConstant(0, VT);
1145 case ISD::SETTRUE2: return getConstant(1, VT);
1157 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1161 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1162 const APInt &C2 = N2C->getAPIntValue();
1163 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1164 const APInt &C1 = N1C->getAPIntValue();
1167 default: assert(0 && "Unknown integer setcc!");
1168 case ISD::SETEQ: return getConstant(C1 == C2, VT);
1169 case ISD::SETNE: return getConstant(C1 != C2, VT);
1170 case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1171 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1172 case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1173 case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1174 case ISD::SETLT: return getConstant(C1.slt(C2), VT);
1175 case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
1176 case ISD::SETLE: return getConstant(C1.sle(C2), VT);
1177 case ISD::SETGE: return getConstant(C1.sge(C2), VT);
1181 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1182 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1183 // No compile time operations on this type yet.
1184 if (N1C->getValueType(0) == MVT::ppcf128)
1187 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1190 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
1191 return getNode(ISD::UNDEF, VT);
1193 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1194 case ISD::SETNE: if (R==APFloat::cmpUnordered)
1195 return getNode(ISD::UNDEF, VT);
1197 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1198 R==APFloat::cmpLessThan, VT);
1199 case ISD::SETLT: if (R==APFloat::cmpUnordered)
1200 return getNode(ISD::UNDEF, VT);
1202 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1203 case ISD::SETGT: if (R==APFloat::cmpUnordered)
1204 return getNode(ISD::UNDEF, VT);
1206 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1207 case ISD::SETLE: if (R==APFloat::cmpUnordered)
1208 return getNode(ISD::UNDEF, VT);
1210 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1211 R==APFloat::cmpEqual, VT);
1212 case ISD::SETGE: if (R==APFloat::cmpUnordered)
1213 return getNode(ISD::UNDEF, VT);
1215 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1216 R==APFloat::cmpEqual, VT);
1217 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
1218 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
1219 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1220 R==APFloat::cmpEqual, VT);
1221 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1222 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1223 R==APFloat::cmpLessThan, VT);
1224 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1225 R==APFloat::cmpUnordered, VT);
1226 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1227 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1230 // Ensure that the constant occurs on the RHS.
1231 return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1235 // Could not fold it.
1239 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
1240 /// use this predicate to simplify operations downstream.
1241 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
1242 unsigned BitWidth = Op.getValueSizeInBits();
1243 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1246 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1247 /// this predicate to simplify operations downstream. Mask is known to be zero
1248 /// for bits that V cannot have.
1249 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
1250 unsigned Depth) const {
1251 APInt KnownZero, KnownOne;
1252 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1253 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1254 return (KnownZero & Mask) == Mask;
1257 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1258 /// known to be either zero or one and return them in the KnownZero/KnownOne
1259 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
1261 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
1262 APInt &KnownZero, APInt &KnownOne,
1263 unsigned Depth) const {
1264 unsigned BitWidth = Mask.getBitWidth();
1265 assert(BitWidth == Op.getValueType().getSizeInBits() &&
1266 "Mask size mismatches value type size!");
1268 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
1269 if (Depth == 6 || Mask == 0)
1270 return; // Limit search depth.
1272 APInt KnownZero2, KnownOne2;
1274 switch (Op.getOpcode()) {
1276 // We know all of the bits for a constant!
1277 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1278 KnownZero = ~KnownOne & Mask;
1281 // If either the LHS or the RHS are Zero, the result is zero.
1282 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1283 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1284 KnownZero2, KnownOne2, Depth+1);
1285 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1286 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1288 // Output known-1 bits are only known if set in both the LHS & RHS.
1289 KnownOne &= KnownOne2;
1290 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1291 KnownZero |= KnownZero2;
1294 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1295 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1296 KnownZero2, KnownOne2, Depth+1);
1297 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1298 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1300 // Output known-0 bits are only known if clear in both the LHS & RHS.
1301 KnownZero &= KnownZero2;
1302 // Output known-1 are known to be set if set in either the LHS | RHS.
1303 KnownOne |= KnownOne2;
1306 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1307 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1308 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1309 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1311 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1312 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1313 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1314 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1315 KnownZero = KnownZeroOut;
1319 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1320 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1321 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1322 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1323 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1325 // If low bits are zero in either operand, output low known-0 bits.
1326 // Also compute a conserative estimate for high known-0 bits.
1327 // More trickiness is possible, but this is sufficient for the
1328 // interesting case of alignment computation.
1330 unsigned TrailZ = KnownZero.countTrailingOnes() +
1331 KnownZero2.countTrailingOnes();
1332 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
1333 KnownZero2.countLeadingOnes(),
1334 BitWidth) - BitWidth;
1336 TrailZ = std::min(TrailZ, BitWidth);
1337 LeadZ = std::min(LeadZ, BitWidth);
1338 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1339 APInt::getHighBitsSet(BitWidth, LeadZ);
1344 // For the purposes of computing leading zeros we can conservatively
1345 // treat a udiv as a logical right shift by the power of 2 known to
1346 // be less than the denominator.
1347 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1348 ComputeMaskedBits(Op.getOperand(0),
1349 AllOnes, KnownZero2, KnownOne2, Depth+1);
1350 unsigned LeadZ = KnownZero2.countLeadingOnes();
1354 ComputeMaskedBits(Op.getOperand(1),
1355 AllOnes, KnownZero2, KnownOne2, Depth+1);
1356 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1357 if (RHSUnknownLeadingOnes != BitWidth)
1358 LeadZ = std::min(BitWidth,
1359 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1361 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1365 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1366 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1367 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1368 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1370 // Only known if known in both the LHS and RHS.
1371 KnownOne &= KnownOne2;
1372 KnownZero &= KnownZero2;
1374 case ISD::SELECT_CC:
1375 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1376 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1377 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1378 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1380 // Only known if known in both the LHS and RHS.
1381 KnownOne &= KnownOne2;
1382 KnownZero &= KnownZero2;
1385 // If we know the result of a setcc has the top bits zero, use this info.
1386 if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1388 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1391 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1392 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1393 unsigned ShAmt = SA->getValue();
1395 // If the shift count is an invalid immediate, don't do anything.
1396 if (ShAmt >= BitWidth)
1399 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1400 KnownZero, KnownOne, Depth+1);
1401 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1402 KnownZero <<= ShAmt;
1404 // low bits known zero.
1405 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1409 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1410 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1411 unsigned ShAmt = SA->getValue();
1413 // If the shift count is an invalid immediate, don't do anything.
1414 if (ShAmt >= BitWidth)
1417 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1418 KnownZero, KnownOne, Depth+1);
1419 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1420 KnownZero = KnownZero.lshr(ShAmt);
1421 KnownOne = KnownOne.lshr(ShAmt);
1423 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1424 KnownZero |= HighBits; // High bits known zero.
1428 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1429 unsigned ShAmt = SA->getValue();
1431 // If the shift count is an invalid immediate, don't do anything.
1432 if (ShAmt >= BitWidth)
1435 APInt InDemandedMask = (Mask << ShAmt);
1436 // If any of the demanded bits are produced by the sign extension, we also
1437 // demand the input sign bit.
1438 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1439 if (HighBits.getBoolValue())
1440 InDemandedMask |= APInt::getSignBit(BitWidth);
1442 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1444 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1445 KnownZero = KnownZero.lshr(ShAmt);
1446 KnownOne = KnownOne.lshr(ShAmt);
1448 // Handle the sign bits.
1449 APInt SignBit = APInt::getSignBit(BitWidth);
1450 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
1452 if (KnownZero.intersects(SignBit)) {
1453 KnownZero |= HighBits; // New bits are known zero.
1454 } else if (KnownOne.intersects(SignBit)) {
1455 KnownOne |= HighBits; // New bits are known one.
1459 case ISD::SIGN_EXTEND_INREG: {
1460 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1461 unsigned EBits = EVT.getSizeInBits();
1463 // Sign extension. Compute the demanded bits in the result that are not
1464 // present in the input.
1465 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1467 APInt InSignBit = APInt::getSignBit(EBits);
1468 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1470 // If the sign extended bits are demanded, we know that the sign
1472 InSignBit.zext(BitWidth);
1473 if (NewBits.getBoolValue())
1474 InputDemandedBits |= InSignBit;
1476 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1477 KnownZero, KnownOne, Depth+1);
1478 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1480 // If the sign bit of the input is known set or clear, then we know the
1481 // top bits of the result.
1482 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
1483 KnownZero |= NewBits;
1484 KnownOne &= ~NewBits;
1485 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
1486 KnownOne |= NewBits;
1487 KnownZero &= ~NewBits;
1488 } else { // Input sign bit unknown
1489 KnownZero &= ~NewBits;
1490 KnownOne &= ~NewBits;
1497 unsigned LowBits = Log2_32(BitWidth)+1;
1498 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1503 if (ISD::isZEXTLoad(Op.Val)) {
1504 LoadSDNode *LD = cast<LoadSDNode>(Op);
1505 MVT VT = LD->getMemoryVT();
1506 unsigned MemBits = VT.getSizeInBits();
1507 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1511 case ISD::ZERO_EXTEND: {
1512 MVT InVT = Op.getOperand(0).getValueType();
1513 unsigned InBits = InVT.getSizeInBits();
1514 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1515 APInt InMask = Mask;
1516 InMask.trunc(InBits);
1517 KnownZero.trunc(InBits);
1518 KnownOne.trunc(InBits);
1519 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1520 KnownZero.zext(BitWidth);
1521 KnownOne.zext(BitWidth);
1522 KnownZero |= NewBits;
1525 case ISD::SIGN_EXTEND: {
1526 MVT InVT = Op.getOperand(0).getValueType();
1527 unsigned InBits = InVT.getSizeInBits();
1528 APInt InSignBit = APInt::getSignBit(InBits);
1529 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1530 APInt InMask = Mask;
1531 InMask.trunc(InBits);
1533 // If any of the sign extended bits are demanded, we know that the sign
1534 // bit is demanded. Temporarily set this bit in the mask for our callee.
1535 if (NewBits.getBoolValue())
1536 InMask |= InSignBit;
1538 KnownZero.trunc(InBits);
1539 KnownOne.trunc(InBits);
1540 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1542 // Note if the sign bit is known to be zero or one.
1543 bool SignBitKnownZero = KnownZero.isNegative();
1544 bool SignBitKnownOne = KnownOne.isNegative();
1545 assert(!(SignBitKnownZero && SignBitKnownOne) &&
1546 "Sign bit can't be known to be both zero and one!");
1548 // If the sign bit wasn't actually demanded by our caller, we don't
1549 // want it set in the KnownZero and KnownOne result values. Reset the
1550 // mask and reapply it to the result values.
1552 InMask.trunc(InBits);
1553 KnownZero &= InMask;
1556 KnownZero.zext(BitWidth);
1557 KnownOne.zext(BitWidth);
1559 // If the sign bit is known zero or one, the top bits match.
1560 if (SignBitKnownZero)
1561 KnownZero |= NewBits;
1562 else if (SignBitKnownOne)
1563 KnownOne |= NewBits;
1566 case ISD::ANY_EXTEND: {
1567 MVT InVT = Op.getOperand(0).getValueType();
1568 unsigned InBits = InVT.getSizeInBits();
1569 APInt InMask = Mask;
1570 InMask.trunc(InBits);
1571 KnownZero.trunc(InBits);
1572 KnownOne.trunc(InBits);
1573 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1574 KnownZero.zext(BitWidth);
1575 KnownOne.zext(BitWidth);
1578 case ISD::TRUNCATE: {
1579 MVT InVT = Op.getOperand(0).getValueType();
1580 unsigned InBits = InVT.getSizeInBits();
1581 APInt InMask = Mask;
1582 InMask.zext(InBits);
1583 KnownZero.zext(InBits);
1584 KnownOne.zext(InBits);
1585 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1586 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1587 KnownZero.trunc(BitWidth);
1588 KnownOne.trunc(BitWidth);
1591 case ISD::AssertZext: {
1592 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1593 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1594 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
1596 KnownZero |= (~InMask) & Mask;
1600 // All bits are zero except the low bit.
1601 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1605 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1606 // We know that the top bits of C-X are clear if X contains less bits
1607 // than C (i.e. no wrap-around can happen). For example, 20-X is
1608 // positive if we can prove that X is >= 0 and < 16.
1609 if (CLHS->getAPIntValue().isNonNegative()) {
1610 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1611 // NLZ can't be BitWidth with no sign bit
1612 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1613 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1616 // If all of the MaskV bits are known to be zero, then we know the
1617 // output top bits are zero, because we now know that the output is
1619 if ((KnownZero2 & MaskV) == MaskV) {
1620 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1621 // Top bits known zero.
1622 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1629 // Output known-0 bits are known if clear or set in both the low clear bits
1630 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
1631 // low 3 bits clear.
1632 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1633 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1634 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1635 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1637 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1638 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1639 KnownZeroOut = std::min(KnownZeroOut,
1640 KnownZero2.countTrailingOnes());
1642 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1646 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1647 const APInt &RA = Rem->getAPIntValue();
1648 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1649 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1650 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1651 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1653 // If the sign bit of the first operand is zero, the sign bit of
1654 // the result is zero. If the first operand has no one bits below
1655 // the second operand's single 1 bit, its sign will be zero.
1656 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1657 KnownZero2 |= ~LowBits;
1659 KnownZero |= KnownZero2 & Mask;
1661 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1666 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1667 const APInt &RA = Rem->getAPIntValue();
1668 if (RA.isPowerOf2()) {
1669 APInt LowBits = (RA - 1);
1670 APInt Mask2 = LowBits & Mask;
1671 KnownZero |= ~LowBits & Mask;
1672 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1673 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1678 // Since the result is less than or equal to either operand, any leading
1679 // zero bits in either operand must also exist in the result.
1680 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1681 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1683 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1686 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1687 KnownZero2.countLeadingOnes());
1689 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1693 // Allow the target to implement this method for its nodes.
1694 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1695 case ISD::INTRINSIC_WO_CHAIN:
1696 case ISD::INTRINSIC_W_CHAIN:
1697 case ISD::INTRINSIC_VOID:
1698 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1704 /// ComputeNumSignBits - Return the number of times the sign bit of the
1705 /// register is replicated into the other bits. We know that at least 1 bit
1706 /// is always equal to the sign bit (itself), but other cases can give us
1707 /// information. For example, immediately after an "SRA X, 2", we know that
1708 /// the top 3 bits are all equal to each other, so we return 3.
1709 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
1710 MVT VT = Op.getValueType();
1711 assert(VT.isInteger() && "Invalid VT!");
1712 unsigned VTBits = VT.getSizeInBits();
1714 unsigned FirstAnswer = 1;
1717 return 1; // Limit search depth.
1719 switch (Op.getOpcode()) {
1721 case ISD::AssertSext:
1722 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1723 return VTBits-Tmp+1;
1724 case ISD::AssertZext:
1725 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1728 case ISD::Constant: {
1729 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1730 // If negative, return # leading ones.
1731 if (Val.isNegative())
1732 return Val.countLeadingOnes();
1734 // Return # leading zeros.
1735 return Val.countLeadingZeros();
1738 case ISD::SIGN_EXTEND:
1739 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1740 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1742 case ISD::SIGN_EXTEND_INREG:
1743 // Max of the input and what this extends.
1744 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1747 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1748 return std::max(Tmp, Tmp2);
1751 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1752 // SRA X, C -> adds C sign bits.
1753 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1754 Tmp += C->getValue();
1755 if (Tmp > VTBits) Tmp = VTBits;
1759 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1760 // shl destroys sign bits.
1761 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1762 if (C->getValue() >= VTBits || // Bad shift.
1763 C->getValue() >= Tmp) break; // Shifted all sign bits out.
1764 return Tmp - C->getValue();
1769 case ISD::XOR: // NOT is handled here.
1770 // Logical binary ops preserve the number of sign bits at the worst.
1771 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1773 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1774 FirstAnswer = std::min(Tmp, Tmp2);
1775 // We computed what we know about the sign bits as our first
1776 // answer. Now proceed to the generic code that uses
1777 // ComputeMaskedBits, and pick whichever answer is better.
1782 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1783 if (Tmp == 1) return 1; // Early out.
1784 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1785 return std::min(Tmp, Tmp2);
1788 // If setcc returns 0/-1, all bits are sign bits.
1789 if (TLI.getSetCCResultContents() ==
1790 TargetLowering::ZeroOrNegativeOneSetCCResult)
1795 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1796 unsigned RotAmt = C->getValue() & (VTBits-1);
1798 // Handle rotate right by N like a rotate left by 32-N.
1799 if (Op.getOpcode() == ISD::ROTR)
1800 RotAmt = (VTBits-RotAmt) & (VTBits-1);
1802 // If we aren't rotating out all of the known-in sign bits, return the
1803 // number that are left. This handles rotl(sext(x), 1) for example.
1804 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1805 if (Tmp > RotAmt+1) return Tmp-RotAmt;
1809 // Add can have at most one carry bit. Thus we know that the output
1810 // is, at worst, one more bit than the inputs.
1811 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1812 if (Tmp == 1) return 1; // Early out.
1814 // Special case decrementing a value (ADD X, -1):
1815 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1816 if (CRHS->isAllOnesValue()) {
1817 APInt KnownZero, KnownOne;
1818 APInt Mask = APInt::getAllOnesValue(VTBits);
1819 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1821 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1823 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1826 // If we are subtracting one from a positive number, there is no carry
1827 // out of the result.
1828 if (KnownZero.isNegative())
1832 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1833 if (Tmp2 == 1) return 1;
1834 return std::min(Tmp, Tmp2)-1;
1838 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1839 if (Tmp2 == 1) return 1;
1842 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1843 if (CLHS->isNullValue()) {
1844 APInt KnownZero, KnownOne;
1845 APInt Mask = APInt::getAllOnesValue(VTBits);
1846 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1847 // If the input is known to be 0 or 1, the output is 0/-1, which is all
1849 if ((KnownZero | APInt(VTBits, 1)) == Mask)
1852 // If the input is known to be positive (the sign bit is known clear),
1853 // the output of the NEG has the same number of sign bits as the input.
1854 if (KnownZero.isNegative())
1857 // Otherwise, we treat this like a SUB.
1860 // Sub can have at most one carry bit. Thus we know that the output
1861 // is, at worst, one more bit than the inputs.
1862 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1863 if (Tmp == 1) return 1; // Early out.
1864 return std::min(Tmp, Tmp2)-1;
1867 // FIXME: it's tricky to do anything useful for this, but it is an important
1868 // case for targets like X86.
1872 // Handle LOADX separately here. EXTLOAD case will fallthrough.
1873 if (Op.getOpcode() == ISD::LOAD) {
1874 LoadSDNode *LD = cast<LoadSDNode>(Op);
1875 unsigned ExtType = LD->getExtensionType();
1878 case ISD::SEXTLOAD: // '17' bits known
1879 Tmp = LD->getMemoryVT().getSizeInBits();
1880 return VTBits-Tmp+1;
1881 case ISD::ZEXTLOAD: // '16' bits known
1882 Tmp = LD->getMemoryVT().getSizeInBits();
1887 // Allow the target to implement this method for its nodes.
1888 if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1889 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1890 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1891 Op.getOpcode() == ISD::INTRINSIC_VOID) {
1892 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1893 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1896 // Finally, if we can prove that the top bits of the result are 0's or 1's,
1897 // use this information.
1898 APInt KnownZero, KnownOne;
1899 APInt Mask = APInt::getAllOnesValue(VTBits);
1900 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1902 if (KnownZero.isNegative()) { // sign bit is 0
1904 } else if (KnownOne.isNegative()) { // sign bit is 1;
1911 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
1912 // the number of identical bits in the top of the input value.
1914 Mask <<= Mask.getBitWidth()-VTBits;
1915 // Return # leading zeros. We use 'min' here in case Val was zero before
1916 // shifting. We don't want to return '64' as for an i32 "0".
1917 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1921 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
1922 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1923 if (!GA) return false;
1924 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1925 if (!GV) return false;
1926 MachineModuleInfo *MMI = getMachineModuleInfo();
1927 return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1931 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1932 /// element of the result of the vector shuffle.
1933 SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
1934 MVT VT = N->getValueType(0);
1935 SDValue PermMask = N->getOperand(2);
1936 SDValue Idx = PermMask.getOperand(i);
1937 if (Idx.getOpcode() == ISD::UNDEF)
1938 return getNode(ISD::UNDEF, VT.getVectorElementType());
1939 unsigned Index = cast<ConstantSDNode>(Idx)->getValue();
1940 unsigned NumElems = PermMask.getNumOperands();
1941 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
1944 if (V.getOpcode() == ISD::BIT_CONVERT) {
1945 V = V.getOperand(0);
1946 if (V.getValueType().getVectorNumElements() != NumElems)
1949 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1950 return (Index == 0) ? V.getOperand(0)
1951 : getNode(ISD::UNDEF, VT.getVectorElementType());
1952 if (V.getOpcode() == ISD::BUILD_VECTOR)
1953 return V.getOperand(Index);
1954 if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
1955 return getShuffleScalarElt(V.Val, Index);
1960 /// getNode - Gets or creates the specified node.
1962 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1963 FoldingSetNodeID ID;
1964 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1966 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1967 return SDValue(E, 0);
1968 SDNode *N = NodeAllocator.Allocate<SDNode>();
1969 new (N) SDNode(Opcode, SDNode::getSDVTList(VT));
1970 CSEMap.InsertNode(N, IP);
1972 AllNodes.push_back(N);
1976 return SDValue(N, 0);
1979 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
1980 // Constant fold unary operations with an integer constant operand.
1981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1982 const APInt &Val = C->getAPIntValue();
1983 unsigned BitWidth = VT.getSizeInBits();
1986 case ISD::SIGN_EXTEND:
1987 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1988 case ISD::ANY_EXTEND:
1989 case ISD::ZERO_EXTEND:
1991 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1992 case ISD::UINT_TO_FP:
1993 case ISD::SINT_TO_FP: {
1994 const uint64_t zero[] = {0, 0};
1995 // No compile time operations on this type.
1996 if (VT==MVT::ppcf128)
1998 APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1999 (void)apf.convertFromAPInt(Val,
2000 Opcode==ISD::SINT_TO_FP,
2001 APFloat::rmNearestTiesToEven);
2002 return getConstantFP(apf, VT);
2004 case ISD::BIT_CONVERT:
2005 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2006 return getConstantFP(Val.bitsToFloat(), VT);
2007 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2008 return getConstantFP(Val.bitsToDouble(), VT);
2011 return getConstant(Val.byteSwap(), VT);
2013 return getConstant(Val.countPopulation(), VT);
2015 return getConstant(Val.countLeadingZeros(), VT);
2017 return getConstant(Val.countTrailingZeros(), VT);
2021 // Constant fold unary operations with a floating point constant operand.
2022 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
2023 APFloat V = C->getValueAPF(); // make copy
2024 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2028 return getConstantFP(V, VT);
2031 return getConstantFP(V, VT);
2033 case ISD::FP_EXTEND:
2034 // This can return overflow, underflow, or inexact; we don't care.
2035 // FIXME need to be more flexible about rounding mode.
2036 (void)V.convert(*MVTToAPFloatSemantics(VT),
2037 APFloat::rmNearestTiesToEven);
2038 return getConstantFP(V, VT);
2039 case ISD::FP_TO_SINT:
2040 case ISD::FP_TO_UINT: {
2042 assert(integerPartWidth >= 64);
2043 // FIXME need to be more flexible about rounding mode.
2044 APFloat::opStatus s = V.convertToInteger(&x, 64U,
2045 Opcode==ISD::FP_TO_SINT,
2046 APFloat::rmTowardZero);
2047 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
2049 return getConstant(x, VT);
2051 case ISD::BIT_CONVERT:
2052 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2053 return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
2054 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2055 return getConstant(V.convertToAPInt().getZExtValue(), VT);
2061 unsigned OpOpcode = Operand.Val->getOpcode();
2063 case ISD::TokenFactor:
2064 case ISD::CONCAT_VECTORS:
2065 return Operand; // Factor or concat of one node? No need.
2066 case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
2067 case ISD::FP_EXTEND:
2068 assert(VT.isFloatingPoint() &&
2069 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2070 if (Operand.getValueType() == VT) return Operand; // noop conversion.
2071 if (Operand.getOpcode() == ISD::UNDEF)
2072 return getNode(ISD::UNDEF, VT);
2074 case ISD::SIGN_EXTEND:
2075 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2076 "Invalid SIGN_EXTEND!");
2077 if (Operand.getValueType() == VT) return Operand; // noop extension
2078 assert(Operand.getValueType().bitsLT(VT)
2079 && "Invalid sext node, dst < src!");
2080 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2081 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2083 case ISD::ZERO_EXTEND:
2084 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2085 "Invalid ZERO_EXTEND!");
2086 if (Operand.getValueType() == VT) return Operand; // noop extension
2087 assert(Operand.getValueType().bitsLT(VT)
2088 && "Invalid zext node, dst < src!");
2089 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
2090 return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
2092 case ISD::ANY_EXTEND:
2093 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2094 "Invalid ANY_EXTEND!");
2095 if (Operand.getValueType() == VT) return Operand; // noop extension
2096 assert(Operand.getValueType().bitsLT(VT)
2097 && "Invalid anyext node, dst < src!");
2098 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2099 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
2100 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2103 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2104 "Invalid TRUNCATE!");
2105 if (Operand.getValueType() == VT) return Operand; // noop truncate
2106 assert(Operand.getValueType().bitsGT(VT)
2107 && "Invalid truncate node, src < dst!");
2108 if (OpOpcode == ISD::TRUNCATE)
2109 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2110 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2111 OpOpcode == ISD::ANY_EXTEND) {
2112 // If the source is smaller than the dest, we still need an extend.
2113 if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2114 return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2115 else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2116 return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2118 return Operand.Val->getOperand(0);
2121 case ISD::BIT_CONVERT:
2122 // Basic sanity checking.
2123 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2124 && "Cannot BIT_CONVERT between types of different sizes!");
2125 if (VT == Operand.getValueType()) return Operand; // noop conversion.
2126 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
2127 return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2128 if (OpOpcode == ISD::UNDEF)
2129 return getNode(ISD::UNDEF, VT);
2131 case ISD::SCALAR_TO_VECTOR:
2132 assert(VT.isVector() && !Operand.getValueType().isVector() &&
2133 VT.getVectorElementType() == Operand.getValueType() &&
2134 "Illegal SCALAR_TO_VECTOR node!");
2135 if (OpOpcode == ISD::UNDEF)
2136 return getNode(ISD::UNDEF, VT);
2137 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2138 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2139 isa<ConstantSDNode>(Operand.getOperand(1)) &&
2140 Operand.getConstantOperandVal(1) == 0 &&
2141 Operand.getOperand(0).getValueType() == VT)
2142 return Operand.getOperand(0);
2145 if (OpOpcode == ISD::FSUB) // -(X-Y) -> (Y-X)
2146 return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2147 Operand.Val->getOperand(0));
2148 if (OpOpcode == ISD::FNEG) // --X -> X
2149 return Operand.Val->getOperand(0);
2152 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
2153 return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2158 SDVTList VTs = getVTList(VT);
2159 if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2160 FoldingSetNodeID ID;
2161 SDValue Ops[1] = { Operand };
2162 AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2164 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2165 return SDValue(E, 0);
2166 N = NodeAllocator.Allocate<UnarySDNode>();
2167 new (N) UnarySDNode(Opcode, VTs, Operand);
2168 CSEMap.InsertNode(N, IP);
2170 N = NodeAllocator.Allocate<UnarySDNode>();
2171 new (N) UnarySDNode(Opcode, VTs, Operand);
2174 AllNodes.push_back(N);
2178 return SDValue(N, 0);
2181 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2182 SDValue N1, SDValue N2) {
2183 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2184 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2187 case ISD::TokenFactor:
2188 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2189 N2.getValueType() == MVT::Other && "Invalid token factor!");
2190 // Fold trivial token factors.
2191 if (N1.getOpcode() == ISD::EntryToken) return N2;
2192 if (N2.getOpcode() == ISD::EntryToken) return N1;
2194 case ISD::CONCAT_VECTORS:
2195 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2196 // one big BUILD_VECTOR.
2197 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2198 N2.getOpcode() == ISD::BUILD_VECTOR) {
2199 SmallVector<SDValue, 16> Elts(N1.Val->op_begin(), N1.Val->op_end());
2200 Elts.insert(Elts.end(), N2.Val->op_begin(), N2.Val->op_end());
2201 return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2205 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2206 N1.getValueType() == VT && "Binary operator types must match!");
2207 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
2208 // worth handling here.
2209 if (N2C && N2C->isNullValue())
2211 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
2218 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2219 N1.getValueType() == VT && "Binary operator types must match!");
2220 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
2221 // it's worth handling here.
2222 if (N2C && N2C->isNullValue())
2229 assert(VT.isInteger() && "This operator does not apply to FP types!");
2239 assert(N1.getValueType() == N2.getValueType() &&
2240 N1.getValueType() == VT && "Binary operator types must match!");
2242 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
2243 assert(N1.getValueType() == VT &&
2244 N1.getValueType().isFloatingPoint() &&
2245 N2.getValueType().isFloatingPoint() &&
2246 "Invalid FCOPYSIGN!");
2253 assert(VT == N1.getValueType() &&
2254 "Shift operators return type must be the same as their first arg");
2255 assert(VT.isInteger() && N2.getValueType().isInteger() &&
2256 "Shifts only work on integers");
2258 // Always fold shifts of i1 values so the code generator doesn't need to
2259 // handle them. Since we know the size of the shift has to be less than the
2260 // size of the value, the shift/rotate count is guaranteed to be zero.
2264 case ISD::FP_ROUND_INREG: {
2265 MVT EVT = cast<VTSDNode>(N2)->getVT();
2266 assert(VT == N1.getValueType() && "Not an inreg round!");
2267 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2268 "Cannot FP_ROUND_INREG integer types");
2269 assert(EVT.bitsLE(VT) && "Not rounding down!");
2270 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
2274 assert(VT.isFloatingPoint() &&
2275 N1.getValueType().isFloatingPoint() &&
2276 VT.bitsLE(N1.getValueType()) &&
2277 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2278 if (N1.getValueType() == VT) return N1; // noop conversion.
2280 case ISD::AssertSext:
2281 case ISD::AssertZext: {
2282 MVT EVT = cast<VTSDNode>(N2)->getVT();
2283 assert(VT == N1.getValueType() && "Not an inreg extend!");
2284 assert(VT.isInteger() && EVT.isInteger() &&
2285 "Cannot *_EXTEND_INREG FP types");
2286 assert(EVT.bitsLE(VT) && "Not extending!");
2287 if (VT == EVT) return N1; // noop assertion.
2290 case ISD::SIGN_EXTEND_INREG: {
2291 MVT EVT = cast<VTSDNode>(N2)->getVT();
2292 assert(VT == N1.getValueType() && "Not an inreg extend!");
2293 assert(VT.isInteger() && EVT.isInteger() &&
2294 "Cannot *_EXTEND_INREG FP types");
2295 assert(EVT.bitsLE(VT) && "Not extending!");
2296 if (EVT == VT) return N1; // Not actually extending
2299 APInt Val = N1C->getAPIntValue();
2300 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2301 Val <<= Val.getBitWidth()-FromBits;
2302 Val = Val.ashr(Val.getBitWidth()-FromBits);
2303 return getConstant(Val, VT);
2307 case ISD::EXTRACT_VECTOR_ELT:
2308 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2309 if (N1.getOpcode() == ISD::UNDEF)
2310 return getNode(ISD::UNDEF, VT);
2312 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2313 // expanding copies of large vectors from registers.
2315 N1.getOpcode() == ISD::CONCAT_VECTORS &&
2316 N1.getNumOperands() > 0) {
2318 N1.getOperand(0).getValueType().getVectorNumElements();
2319 return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2320 N1.getOperand(N2C->getValue() / Factor),
2321 getConstant(N2C->getValue() % Factor, N2.getValueType()));
2324 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2325 // expanding large vector constants.
2326 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR)
2327 return N1.getOperand(N2C->getValue());
2329 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2330 // operations are lowered to scalars.
2331 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2332 if (N1.getOperand(2) == N2)
2333 return N1.getOperand(1);
2335 return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2338 case ISD::EXTRACT_ELEMENT:
2339 assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2340 assert(!N1.getValueType().isVector() && !VT.isVector() &&
2341 (N1.getValueType().isInteger() == VT.isInteger()) &&
2342 "Wrong types for EXTRACT_ELEMENT!");
2344 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2345 // 64-bit integers into 32-bit parts. Instead of building the extract of
2346 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2347 if (N1.getOpcode() == ISD::BUILD_PAIR)
2348 return N1.getOperand(N2C->getValue());
2350 // EXTRACT_ELEMENT of a constant int is also very common.
2351 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2352 unsigned ElementSize = VT.getSizeInBits();
2353 unsigned Shift = ElementSize * N2C->getValue();
2354 APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2355 return getConstant(ShiftedVal.trunc(ElementSize), VT);
2358 case ISD::EXTRACT_SUBVECTOR:
2359 if (N1.getValueType() == VT) // Trivial extraction.
2366 const APInt &C1 = N1C->getAPIntValue(), &C2 = N2C->getAPIntValue();
2368 case ISD::ADD: return getConstant(C1 + C2, VT);
2369 case ISD::SUB: return getConstant(C1 - C2, VT);
2370 case ISD::MUL: return getConstant(C1 * C2, VT);
2372 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2375 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2378 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2381 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2383 case ISD::AND : return getConstant(C1 & C2, VT);
2384 case ISD::OR : return getConstant(C1 | C2, VT);
2385 case ISD::XOR : return getConstant(C1 ^ C2, VT);
2386 case ISD::SHL : return getConstant(C1 << C2, VT);
2387 case ISD::SRL : return getConstant(C1.lshr(C2), VT);
2388 case ISD::SRA : return getConstant(C1.ashr(C2), VT);
2389 case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2390 case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2393 } else { // Cannonicalize constant to RHS if commutative
2394 if (isCommutativeBinOp(Opcode)) {
2395 std::swap(N1C, N2C);
2401 // Constant fold FP operations.
2402 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2403 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2405 if (!N2CFP && isCommutativeBinOp(Opcode)) {
2406 // Cannonicalize constant to RHS if commutative
2407 std::swap(N1CFP, N2CFP);
2409 } else if (N2CFP && VT != MVT::ppcf128) {
2410 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2411 APFloat::opStatus s;
2414 s = V1.add(V2, APFloat::rmNearestTiesToEven);
2415 if (s != APFloat::opInvalidOp)
2416 return getConstantFP(V1, VT);
2419 s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2420 if (s!=APFloat::opInvalidOp)
2421 return getConstantFP(V1, VT);
2424 s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2425 if (s!=APFloat::opInvalidOp)
2426 return getConstantFP(V1, VT);
2429 s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2430 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2431 return getConstantFP(V1, VT);
2434 s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2435 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2436 return getConstantFP(V1, VT);
2438 case ISD::FCOPYSIGN:
2440 return getConstantFP(V1, VT);
2446 // Canonicalize an UNDEF to the RHS, even over a constant.
2447 if (N1.getOpcode() == ISD::UNDEF) {
2448 if (isCommutativeBinOp(Opcode)) {
2452 case ISD::FP_ROUND_INREG:
2453 case ISD::SIGN_EXTEND_INREG:
2459 return N1; // fold op(undef, arg2) -> undef
2467 return getConstant(0, VT); // fold op(undef, arg2) -> 0
2468 // For vectors, we can't easily build an all zero vector, just return
2475 // Fold a bunch of operators when the RHS is undef.
2476 if (N2.getOpcode() == ISD::UNDEF) {
2479 if (N1.getOpcode() == ISD::UNDEF)
2480 // Handle undef ^ undef -> 0 special case. This is a common
2482 return getConstant(0, VT);
2497 return N2; // fold op(arg1, undef) -> undef
2503 return getConstant(0, VT); // fold op(arg1, undef) -> 0
2504 // For vectors, we can't easily build an all zero vector, just return
2509 return getConstant(VT.getIntegerVTBitMask(), VT);
2510 // For vectors, we can't easily build an all one vector, just return
2518 // Memoize this node if possible.
2520 SDVTList VTs = getVTList(VT);
2521 if (VT != MVT::Flag) {
2522 SDValue Ops[] = { N1, N2 };
2523 FoldingSetNodeID ID;
2524 AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2526 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2527 return SDValue(E, 0);
2528 N = NodeAllocator.Allocate<BinarySDNode>();
2529 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2530 CSEMap.InsertNode(N, IP);
2532 N = NodeAllocator.Allocate<BinarySDNode>();
2533 new (N) BinarySDNode(Opcode, VTs, N1, N2);
2536 AllNodes.push_back(N);
2540 return SDValue(N, 0);
2543 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2544 SDValue N1, SDValue N2, SDValue N3) {
2545 // Perform various simplifications.
2546 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2547 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2549 case ISD::CONCAT_VECTORS:
2550 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2551 // one big BUILD_VECTOR.
2552 if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2553 N2.getOpcode() == ISD::BUILD_VECTOR &&
2554 N3.getOpcode() == ISD::BUILD_VECTOR) {
2555 SmallVector<SDValue, 16> Elts(N1.Val->op_begin(), N1.Val->op_end());
2556 Elts.insert(Elts.end(), N2.Val->op_begin(), N2.Val->op_end());
2557 Elts.insert(Elts.end(), N3.Val->op_begin(), N3.Val->op_end());
2558 return getNode(ISD::BUILD_VECTOR, VT, &Elts[0], Elts.size());
2562 // Use FoldSetCC to simplify SETCC's.
2563 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2564 if (Simp.Val) return Simp;
2569 if (N1C->getValue())
2570 return N2; // select true, X, Y -> X
2572 return N3; // select false, X, Y -> Y
2575 if (N2 == N3) return N2; // select C, X, X -> X
2579 if (N2C->getValue()) // Unconditional branch
2580 return getNode(ISD::BR, MVT::Other, N1, N3);
2582 return N1; // Never-taken branch
2585 case ISD::VECTOR_SHUFFLE:
2586 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2587 VT.isVector() && N3.getValueType().isVector() &&
2588 N3.getOpcode() == ISD::BUILD_VECTOR &&
2589 VT.getVectorNumElements() == N3.getNumOperands() &&
2590 "Illegal VECTOR_SHUFFLE node!");
2592 case ISD::BIT_CONVERT:
2593 // Fold bit_convert nodes from a type to themselves.
2594 if (N1.getValueType() == VT)
2599 // Memoize node if it doesn't produce a flag.
2601 SDVTList VTs = getVTList(VT);
2602 if (VT != MVT::Flag) {
2603 SDValue Ops[] = { N1, N2, N3 };
2604 FoldingSetNodeID ID;
2605 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2607 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2608 return SDValue(E, 0);
2609 N = NodeAllocator.Allocate<TernarySDNode>();
2610 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2611 CSEMap.InsertNode(N, IP);
2613 N = NodeAllocator.Allocate<TernarySDNode>();
2614 new (N) TernarySDNode(Opcode, VTs, N1, N2, N3);
2616 AllNodes.push_back(N);
2620 return SDValue(N, 0);
2623 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2624 SDValue N1, SDValue N2, SDValue N3,
2626 SDValue Ops[] = { N1, N2, N3, N4 };
2627 return getNode(Opcode, VT, Ops, 4);
2630 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
2631 SDValue N1, SDValue N2, SDValue N3,
2632 SDValue N4, SDValue N5) {
2633 SDValue Ops[] = { N1, N2, N3, N4, N5 };
2634 return getNode(Opcode, VT, Ops, 5);
2637 /// getMemsetValue - Vectorized representation of the memset value
2639 static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG) {
2640 unsigned NumBits = VT.isVector() ?
2641 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2642 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2643 APInt Val = APInt(NumBits, C->getValue() & 255);
2645 for (unsigned i = NumBits; i > 8; i >>= 1) {
2646 Val = (Val << Shift) | Val;
2650 return DAG.getConstant(Val, VT);
2651 return DAG.getConstantFP(APFloat(Val), VT);
2654 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2656 for (unsigned i = NumBits; i > 8; i >>= 1) {
2657 Value = DAG.getNode(ISD::OR, VT,
2658 DAG.getNode(ISD::SHL, VT, Value,
2659 DAG.getConstant(Shift, MVT::i8)), Value);
2666 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2667 /// used when a memcpy is turned into a memset when the source is a constant
2669 static SDValue getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2670 const TargetLowering &TLI,
2671 std::string &Str, unsigned Offset) {
2672 // Handle vector with all elements zero.
2675 return DAG.getConstant(0, VT);
2676 unsigned NumElts = VT.getVectorNumElements();
2677 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
2678 return DAG.getNode(ISD::BIT_CONVERT, VT,
2679 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
2682 assert(!VT.isVector() && "Can't handle vector type here!");
2683 unsigned NumBits = VT.getSizeInBits();
2684 unsigned MSB = NumBits / 8;
2686 if (TLI.isLittleEndian())
2687 Offset = Offset + MSB - 1;
2688 for (unsigned i = 0; i != MSB; ++i) {
2689 Val = (Val << 8) | (unsigned char)Str[Offset];
2690 Offset += TLI.isLittleEndian() ? -1 : 1;
2692 return DAG.getConstant(Val, VT);
2695 /// getMemBasePlusOffset - Returns base and offset node for the
2697 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
2698 SelectionDAG &DAG) {
2699 MVT VT = Base.getValueType();
2700 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2703 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2705 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
2706 unsigned SrcDelta = 0;
2707 GlobalAddressSDNode *G = NULL;
2708 if (Src.getOpcode() == ISD::GlobalAddress)
2709 G = cast<GlobalAddressSDNode>(Src);
2710 else if (Src.getOpcode() == ISD::ADD &&
2711 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2712 Src.getOperand(1).getOpcode() == ISD::Constant) {
2713 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2714 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2719 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2720 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
2726 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2727 /// to replace the memset / memcpy is below the threshold. It also returns the
2728 /// types of the sequence of memory ops to perform memset / memcpy.
2730 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2731 SDValue Dst, SDValue Src,
2732 unsigned Limit, uint64_t Size, unsigned &Align,
2733 std::string &Str, bool &isSrcStr,
2735 const TargetLowering &TLI) {
2736 isSrcStr = isMemSrcFromString(Src, Str);
2737 bool isSrcConst = isa<ConstantSDNode>(Src);
2738 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2739 MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2740 if (VT != MVT::iAny) {
2741 unsigned NewAlign = (unsigned)
2742 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2743 // If source is a string constant, this will require an unaligned load.
2744 if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2745 if (Dst.getOpcode() != ISD::FrameIndex) {
2746 // Can't change destination alignment. It requires a unaligned store.
2750 int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2751 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2752 if (MFI->isFixedObjectIndex(FI)) {
2753 // Can't change destination alignment. It requires a unaligned store.
2757 // Give the stack frame object a larger alignment if needed.
2758 if (MFI->getObjectAlignment(FI) < NewAlign)
2759 MFI->setObjectAlignment(FI, NewAlign);
2766 if (VT == MVT::iAny) {
2770 switch (Align & 7) {
2771 case 0: VT = MVT::i64; break;
2772 case 4: VT = MVT::i32; break;
2773 case 2: VT = MVT::i16; break;
2774 default: VT = MVT::i8; break;
2779 while (!TLI.isTypeLegal(LVT))
2780 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2781 assert(LVT.isInteger());
2787 unsigned NumMemOps = 0;
2789 unsigned VTSize = VT.getSizeInBits() / 8;
2790 while (VTSize > Size) {
2791 // For now, only use non-vector load / store's for the left-over pieces.
2792 if (VT.isVector()) {
2794 while (!TLI.isTypeLegal(VT))
2795 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2796 VTSize = VT.getSizeInBits() / 8;
2798 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2803 if (++NumMemOps > Limit)
2805 MemOps.push_back(VT);
2812 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG,
2813 SDValue Chain, SDValue Dst,
2814 SDValue Src, uint64_t Size,
2815 unsigned Align, bool AlwaysInline,
2816 const Value *DstSV, uint64_t DstSVOff,
2817 const Value *SrcSV, uint64_t SrcSVOff){
2818 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2820 // Expand memcpy to a series of load and store ops if the size operand falls
2821 // below a certain threshold.
2822 std::vector<MVT> MemOps;
2823 uint64_t Limit = -1;
2825 Limit = TLI.getMaxStoresPerMemcpy();
2826 unsigned DstAlign = Align; // Destination alignment can change.
2829 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2830 Str, CopyFromStr, DAG, TLI))
2834 bool isZeroStr = CopyFromStr && Str.empty();
2835 SmallVector<SDValue, 8> OutChains;
2836 unsigned NumMemOps = MemOps.size();
2837 uint64_t SrcOff = 0, DstOff = 0;
2838 for (unsigned i = 0; i < NumMemOps; i++) {
2840 unsigned VTSize = VT.getSizeInBits() / 8;
2841 SDValue Value, Store;
2843 if (CopyFromStr && (isZeroStr || !VT.isVector())) {
2844 // It's unlikely a store of a vector immediate can be done in a single
2845 // instruction. It would require a load from a constantpool first.
2846 // We also handle store a vector with all zero's.
2847 // FIXME: Handle other cases where store of vector immediate is done in
2848 // a single instruction.
2849 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2850 Store = DAG.getStore(Chain, Value,
2851 getMemBasePlusOffset(Dst, DstOff, DAG),
2852 DstSV, DstSVOff + DstOff, false, DstAlign);
2854 Value = DAG.getLoad(VT, Chain,
2855 getMemBasePlusOffset(Src, SrcOff, DAG),
2856 SrcSV, SrcSVOff + SrcOff, false, Align);
2857 Store = DAG.getStore(Chain, Value,
2858 getMemBasePlusOffset(Dst, DstOff, DAG),
2859 DstSV, DstSVOff + DstOff, false, DstAlign);
2861 OutChains.push_back(Store);
2866 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2867 &OutChains[0], OutChains.size());
2870 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG,
2871 SDValue Chain, SDValue Dst,
2872 SDValue Src, uint64_t Size,
2873 unsigned Align, bool AlwaysInline,
2874 const Value *DstSV, uint64_t DstSVOff,
2875 const Value *SrcSV, uint64_t SrcSVOff){
2876 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2878 // Expand memmove to a series of load and store ops if the size operand falls
2879 // below a certain threshold.
2880 std::vector<MVT> MemOps;
2881 uint64_t Limit = -1;
2883 Limit = TLI.getMaxStoresPerMemmove();
2884 unsigned DstAlign = Align; // Destination alignment can change.
2887 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2888 Str, CopyFromStr, DAG, TLI))
2891 uint64_t SrcOff = 0, DstOff = 0;
2893 SmallVector<SDValue, 8> LoadValues;
2894 SmallVector<SDValue, 8> LoadChains;
2895 SmallVector<SDValue, 8> OutChains;
2896 unsigned NumMemOps = MemOps.size();
2897 for (unsigned i = 0; i < NumMemOps; i++) {
2899 unsigned VTSize = VT.getSizeInBits() / 8;
2900 SDValue Value, Store;
2902 Value = DAG.getLoad(VT, Chain,
2903 getMemBasePlusOffset(Src, SrcOff, DAG),
2904 SrcSV, SrcSVOff + SrcOff, false, Align);
2905 LoadValues.push_back(Value);
2906 LoadChains.push_back(Value.getValue(1));
2909 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2910 &LoadChains[0], LoadChains.size());
2912 for (unsigned i = 0; i < NumMemOps; i++) {
2914 unsigned VTSize = VT.getSizeInBits() / 8;
2915 SDValue Value, Store;
2917 Store = DAG.getStore(Chain, LoadValues[i],
2918 getMemBasePlusOffset(Dst, DstOff, DAG),
2919 DstSV, DstSVOff + DstOff, false, DstAlign);
2920 OutChains.push_back(Store);
2924 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2925 &OutChains[0], OutChains.size());
2928 static SDValue getMemsetStores(SelectionDAG &DAG,
2929 SDValue Chain, SDValue Dst,
2930 SDValue Src, uint64_t Size,
2932 const Value *DstSV, uint64_t DstSVOff) {
2933 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2935 // Expand memset to a series of load/store ops if the size operand
2936 // falls below a certain threshold.
2937 std::vector<MVT> MemOps;
2940 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2941 Size, Align, Str, CopyFromStr, DAG, TLI))
2944 SmallVector<SDValue, 8> OutChains;
2945 uint64_t DstOff = 0;
2947 unsigned NumMemOps = MemOps.size();
2948 for (unsigned i = 0; i < NumMemOps; i++) {
2950 unsigned VTSize = VT.getSizeInBits() / 8;
2951 SDValue Value = getMemsetValue(Src, VT, DAG);
2952 SDValue Store = DAG.getStore(Chain, Value,
2953 getMemBasePlusOffset(Dst, DstOff, DAG),
2954 DstSV, DstSVOff + DstOff);
2955 OutChains.push_back(Store);
2959 return DAG.getNode(ISD::TokenFactor, MVT::Other,
2960 &OutChains[0], OutChains.size());
2963 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDValue Dst,
2964 SDValue Src, SDValue Size,
2965 unsigned Align, bool AlwaysInline,
2966 const Value *DstSV, uint64_t DstSVOff,
2967 const Value *SrcSV, uint64_t SrcSVOff) {
2969 // Check to see if we should lower the memcpy to loads and stores first.
2970 // For cases within the target-specified limits, this is the best choice.
2971 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2973 // Memcpy with size zero? Just return the original chain.
2974 if (ConstantSize->isNullValue())
2978 getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2979 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2984 // Then check to see if we should lower the memcpy with target-specific
2985 // code. If the target chooses to do this, this is the next best.
2987 TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2989 DstSV, DstSVOff, SrcSV, SrcSVOff);
2993 // If we really need inline code and the target declined to provide it,
2994 // use a (potentially long) sequence of loads and stores.
2996 assert(ConstantSize && "AlwaysInline requires a constant size!");
2997 return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2998 ConstantSize->getValue(), Align, true,
2999 DstSV, DstSVOff, SrcSV, SrcSVOff);
3002 // Emit a library call.
3003 TargetLowering::ArgListTy Args;
3004 TargetLowering::ArgListEntry Entry;
3005 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3006 Entry.Node = Dst; Args.push_back(Entry);
3007 Entry.Node = Src; Args.push_back(Entry);
3008 Entry.Node = Size; Args.push_back(Entry);
3009 std::pair<SDValue,SDValue> CallResult =
3010 TLI.LowerCallTo(Chain, Type::VoidTy,
3011 false, false, false, CallingConv::C, false,
3012 getExternalSymbol("memcpy", TLI.getPointerTy()),
3014 return CallResult.second;
3017 SDValue SelectionDAG::getMemmove(SDValue Chain, SDValue Dst,
3018 SDValue Src, SDValue Size,
3020 const Value *DstSV, uint64_t DstSVOff,
3021 const Value *SrcSV, uint64_t SrcSVOff) {
3023 // Check to see if we should lower the memmove to loads and stores first.
3024 // For cases within the target-specified limits, this is the best choice.
3025 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3027 // Memmove with size zero? Just return the original chain.
3028 if (ConstantSize->isNullValue())
3032 getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
3033 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
3038 // Then check to see if we should lower the memmove with target-specific
3039 // code. If the target chooses to do this, this is the next best.
3041 TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
3042 DstSV, DstSVOff, SrcSV, SrcSVOff);
3046 // Emit a library call.
3047 TargetLowering::ArgListTy Args;
3048 TargetLowering::ArgListEntry Entry;
3049 Entry.Ty = TLI.getTargetData()->getIntPtrType();
3050 Entry.Node = Dst; Args.push_back(Entry);
3051 Entry.Node = Src; Args.push_back(Entry);
3052 Entry.Node = Size; Args.push_back(Entry);
3053 std::pair<SDValue,SDValue> CallResult =
3054 TLI.LowerCallTo(Chain, Type::VoidTy,
3055 false, false, false, CallingConv::C, false,
3056 getExternalSymbol("memmove", TLI.getPointerTy()),
3058 return CallResult.second;
3061 SDValue SelectionDAG::getMemset(SDValue Chain, SDValue Dst,
3062 SDValue Src, SDValue Size,
3064 const Value *DstSV, uint64_t DstSVOff) {
3066 // Check to see if we should lower the memset to stores first.
3067 // For cases within the target-specified limits, this is the best choice.
3068 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3070 // Memset with size zero? Just return the original chain.
3071 if (ConstantSize->isNullValue())
3075 getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
3081 // Then check to see if we should lower the memset with target-specific
3082 // code. If the target chooses to do this, this is the next best.
3084 TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
3089 // Emit a library call.
3090 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
3091 TargetLowering::ArgListTy Args;
3092 TargetLowering::ArgListEntry Entry;
3093 Entry.Node = Dst; Entry.Ty = IntPtrTy;
3094 Args.push_back(Entry);
3095 // Extend or truncate the argument to be an i32 value for the call.
3096 if (Src.getValueType().bitsGT(MVT::i32))
3097 Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
3099 Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
3100 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
3101 Args.push_back(Entry);
3102 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
3103 Args.push_back(Entry);
3104 std::pair<SDValue,SDValue> CallResult =
3105 TLI.LowerCallTo(Chain, Type::VoidTy,
3106 false, false, false, CallingConv::C, false,
3107 getExternalSymbol("memset", TLI.getPointerTy()),
3109 return CallResult.second;
3112 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDValue Chain,
3113 SDValue Ptr, SDValue Cmp,
3114 SDValue Swp, const Value* PtrVal,
3115 unsigned Alignment) {
3116 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3117 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3119 MVT VT = Cmp.getValueType();
3121 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3122 Alignment = getMVTAlignment(VT);
3124 SDVTList VTs = getVTList(VT, MVT::Other);
3125 FoldingSetNodeID ID;
3126 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3127 AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3129 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3130 return SDValue(E, 0);
3131 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3132 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
3133 CSEMap.InsertNode(N, IP);
3134 AllNodes.push_back(N);
3135 return SDValue(N, 0);
3138 SDValue SelectionDAG::getAtomic(unsigned Opcode, SDValue Chain,
3139 SDValue Ptr, SDValue Val,
3140 const Value* PtrVal,
3141 unsigned Alignment) {
3142 assert(( Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB
3143 || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
3144 || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
3145 || Opcode == ISD::ATOMIC_LOAD_NAND
3146 || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3147 || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX)
3148 && "Invalid Atomic Op");
3150 MVT VT = Val.getValueType();
3152 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3153 Alignment = getMVTAlignment(VT);
3155 SDVTList VTs = getVTList(VT, MVT::Other);
3156 FoldingSetNodeID ID;
3157 SDValue Ops[] = {Chain, Ptr, Val};
3158 AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3160 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3161 return SDValue(E, 0);
3162 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
3163 new (N) AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, PtrVal, Alignment);
3164 CSEMap.InsertNode(N, IP);
3165 AllNodes.push_back(N);
3166 return SDValue(N, 0);
3169 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
3170 /// Allowed to return something different (and simpler) if Simplify is true.
3171 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3173 if (Simplify && NumOps == 1)
3176 SmallVector<MVT, 4> VTs;
3177 VTs.reserve(NumOps);
3178 for (unsigned i = 0; i < NumOps; ++i)
3179 VTs.push_back(Ops[i].getValueType());
3180 return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
3184 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3185 MVT VT, SDValue Chain,
3186 SDValue Ptr, SDValue Offset,
3187 const Value *SV, int SVOffset, MVT EVT,
3188 bool isVolatile, unsigned Alignment) {
3189 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3190 Alignment = getMVTAlignment(VT);
3193 ExtType = ISD::NON_EXTLOAD;
3194 } else if (ExtType == ISD::NON_EXTLOAD) {
3195 assert(VT == EVT && "Non-extending load from different memory type!");
3199 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
3200 "Invalid vector extload!");
3202 assert(EVT.bitsLT(VT) &&
3203 "Should only be an extending load, not truncating!");
3204 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3205 "Cannot sign/zero extend a FP/Vector load!");
3206 assert(VT.isInteger() == EVT.isInteger() &&
3207 "Cannot convert from FP to Int or Int -> FP!");
3210 bool Indexed = AM != ISD::UNINDEXED;
3211 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3212 "Unindexed load with an offset!");
3214 SDVTList VTs = Indexed ?
3215 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3216 SDValue Ops[] = { Chain, Ptr, Offset };
3217 FoldingSetNodeID ID;
3218 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3220 ID.AddInteger(ExtType);
3221 ID.AddInteger(EVT.getRawBits());
3222 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3224 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3225 return SDValue(E, 0);
3226 SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
3227 new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3228 Alignment, isVolatile);
3229 CSEMap.InsertNode(N, IP);
3230 AllNodes.push_back(N);
3231 return SDValue(N, 0);
3234 SDValue SelectionDAG::getLoad(MVT VT,
3235 SDValue Chain, SDValue Ptr,
3236 const Value *SV, int SVOffset,
3237 bool isVolatile, unsigned Alignment) {
3238 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3239 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3240 SV, SVOffset, VT, isVolatile, Alignment);
3243 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3244 SDValue Chain, SDValue Ptr,
3246 int SVOffset, MVT EVT,
3247 bool isVolatile, unsigned Alignment) {
3248 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3249 return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3250 SV, SVOffset, EVT, isVolatile, Alignment);
3254 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDValue Base,
3255 SDValue Offset, ISD::MemIndexedMode AM) {
3256 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3257 assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3258 "Load is already a indexed load!");
3259 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3260 LD->getChain(), Base, Offset, LD->getSrcValue(),
3261 LD->getSrcValueOffset(), LD->getMemoryVT(),
3262 LD->isVolatile(), LD->getAlignment());
3265 SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
3266 SDValue Ptr, const Value *SV, int SVOffset,
3267 bool isVolatile, unsigned Alignment) {
3268 MVT VT = Val.getValueType();
3270 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3271 Alignment = getMVTAlignment(VT);
3273 SDVTList VTs = getVTList(MVT::Other);
3274 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3275 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3276 FoldingSetNodeID ID;
3277 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3278 ID.AddInteger(ISD::UNINDEXED);
3279 ID.AddInteger(false);
3280 ID.AddInteger(VT.getRawBits());
3281 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3283 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3284 return SDValue(E, 0);
3285 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3286 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3287 VT, SV, SVOffset, Alignment, isVolatile);
3288 CSEMap.InsertNode(N, IP);
3289 AllNodes.push_back(N);
3290 return SDValue(N, 0);
3293 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDValue Val,
3294 SDValue Ptr, const Value *SV,
3295 int SVOffset, MVT SVT,
3296 bool isVolatile, unsigned Alignment) {
3297 MVT VT = Val.getValueType();
3300 return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3302 assert(VT.bitsGT(SVT) && "Not a truncation?");
3303 assert(VT.isInteger() == SVT.isInteger() &&
3304 "Can't do FP-INT conversion!");
3306 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3307 Alignment = getMVTAlignment(VT);
3309 SDVTList VTs = getVTList(MVT::Other);
3310 SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3311 SDValue Ops[] = { Chain, Val, Ptr, Undef };
3312 FoldingSetNodeID ID;
3313 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3314 ID.AddInteger(ISD::UNINDEXED);
3316 ID.AddInteger(SVT.getRawBits());
3317 ID.AddInteger(encodeMemSDNodeFlags(isVolatile, Alignment));
3319 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3320 return SDValue(E, 0);
3321 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3322 new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3323 SVT, SV, SVOffset, Alignment, isVolatile);
3324 CSEMap.InsertNode(N, IP);
3325 AllNodes.push_back(N);
3326 return SDValue(N, 0);
3330 SelectionDAG::getIndexedStore(SDValue OrigStore, SDValue Base,
3331 SDValue Offset, ISD::MemIndexedMode AM) {
3332 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3333 assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3334 "Store is already a indexed store!");
3335 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3336 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3337 FoldingSetNodeID ID;
3338 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3340 ID.AddInteger(ST->isTruncatingStore());
3341 ID.AddInteger(ST->getMemoryVT().getRawBits());
3342 ID.AddInteger(ST->getRawFlags());
3344 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3345 return SDValue(E, 0);
3346 SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
3347 new (N) StoreSDNode(Ops, VTs, AM,
3348 ST->isTruncatingStore(), ST->getMemoryVT(),
3349 ST->getSrcValue(), ST->getSrcValueOffset(),
3350 ST->getAlignment(), ST->isVolatile());
3351 CSEMap.InsertNode(N, IP);
3352 AllNodes.push_back(N);
3353 return SDValue(N, 0);
3356 SDValue SelectionDAG::getVAArg(MVT VT,
3357 SDValue Chain, SDValue Ptr,
3359 SDValue Ops[] = { Chain, Ptr, SV };
3360 return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3363 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3364 const SDUse *Ops, unsigned NumOps) {
3366 case 0: return getNode(Opcode, VT);
3367 case 1: return getNode(Opcode, VT, Ops[0]);
3368 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3369 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3373 // Copy from an SDUse array into an SDValue array for use with
3374 // the regular getNode logic.
3375 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
3376 return getNode(Opcode, VT, &NewOps[0], NumOps);
3379 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
3380 const SDValue *Ops, unsigned NumOps) {
3382 case 0: return getNode(Opcode, VT);
3383 case 1: return getNode(Opcode, VT, Ops[0]);
3384 case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3385 case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3391 case ISD::SELECT_CC: {
3392 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3393 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3394 "LHS and RHS of condition must have same type!");
3395 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3396 "True and False arms of SelectCC must have same type!");
3397 assert(Ops[2].getValueType() == VT &&
3398 "select_cc node must be of same type as true and false value!");
3402 assert(NumOps == 5 && "BR_CC takes 5 operands!");
3403 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3404 "LHS/RHS of comparison should match types!");
3411 SDVTList VTs = getVTList(VT);
3412 if (VT != MVT::Flag) {
3413 FoldingSetNodeID ID;
3414 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3416 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3417 return SDValue(E, 0);
3418 N = NodeAllocator.Allocate<SDNode>();
3419 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3420 CSEMap.InsertNode(N, IP);
3422 N = NodeAllocator.Allocate<SDNode>();
3423 new (N) SDNode(Opcode, VTs, Ops, NumOps);
3425 AllNodes.push_back(N);
3429 return SDValue(N, 0);
3432 SDValue SelectionDAG::getNode(unsigned Opcode,
3433 const std::vector<MVT> &ResultTys,
3434 const SDValue *Ops, unsigned NumOps) {
3435 return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3439 SDValue SelectionDAG::getNode(unsigned Opcode,
3440 const MVT *VTs, unsigned NumVTs,
3441 const SDValue *Ops, unsigned NumOps) {
3443 return getNode(Opcode, VTs[0], Ops, NumOps);
3444 return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3447 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3448 const SDValue *Ops, unsigned NumOps) {
3449 if (VTList.NumVTs == 1)
3450 return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3453 // FIXME: figure out how to safely handle things like
3454 // int foo(int x) { return 1 << (x & 255); }
3455 // int bar() { return foo(256); }
3457 case ISD::SRA_PARTS:
3458 case ISD::SRL_PARTS:
3459 case ISD::SHL_PARTS:
3460 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3461 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3462 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3463 else if (N3.getOpcode() == ISD::AND)
3464 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3465 // If the and is only masking out bits that cannot effect the shift,
3466 // eliminate the and.
3467 unsigned NumBits = VT.getSizeInBits()*2;
3468 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3469 return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3475 // Memoize the node unless it returns a flag.
3477 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3478 FoldingSetNodeID ID;
3479 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3481 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3482 return SDValue(E, 0);
3484 N = NodeAllocator.Allocate<UnarySDNode>();
3485 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3486 } else if (NumOps == 2) {
3487 N = NodeAllocator.Allocate<BinarySDNode>();
3488 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3489 } else if (NumOps == 3) {
3490 N = NodeAllocator.Allocate<TernarySDNode>();
3491 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3493 N = NodeAllocator.Allocate<SDNode>();
3494 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3496 CSEMap.InsertNode(N, IP);
3499 N = NodeAllocator.Allocate<UnarySDNode>();
3500 new (N) UnarySDNode(Opcode, VTList, Ops[0]);
3501 } else if (NumOps == 2) {
3502 N = NodeAllocator.Allocate<BinarySDNode>();
3503 new (N) BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3504 } else if (NumOps == 3) {
3505 N = NodeAllocator.Allocate<TernarySDNode>();
3506 new (N) TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3508 N = NodeAllocator.Allocate<SDNode>();
3509 new (N) SDNode(Opcode, VTList, Ops, NumOps);
3512 AllNodes.push_back(N);
3516 return SDValue(N, 0);
3519 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3520 return getNode(Opcode, VTList, 0, 0);
3523 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3525 SDValue Ops[] = { N1 };
3526 return getNode(Opcode, VTList, Ops, 1);
3529 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3530 SDValue N1, SDValue N2) {
3531 SDValue Ops[] = { N1, N2 };
3532 return getNode(Opcode, VTList, Ops, 2);
3535 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3536 SDValue N1, SDValue N2, SDValue N3) {
3537 SDValue Ops[] = { N1, N2, N3 };
3538 return getNode(Opcode, VTList, Ops, 3);
3541 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3542 SDValue N1, SDValue N2, SDValue N3,
3544 SDValue Ops[] = { N1, N2, N3, N4 };
3545 return getNode(Opcode, VTList, Ops, 4);
3548 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3549 SDValue N1, SDValue N2, SDValue N3,
3550 SDValue N4, SDValue N5) {
3551 SDValue Ops[] = { N1, N2, N3, N4, N5 };
3552 return getNode(Opcode, VTList, Ops, 5);
3555 SDVTList SelectionDAG::getVTList(MVT VT) {
3556 return makeVTList(SDNode::getValueTypeList(VT), 1);
3559 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3560 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3561 E = VTList.rend(); I != E; ++I)
3562 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
3565 MVT *Array = Allocator.Allocate<MVT>(2);
3568 SDVTList Result = makeVTList(Array, 2);
3569 VTList.push_back(Result);
3573 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
3574 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3575 E = VTList.rend(); I != E; ++I)
3576 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
3580 MVT *Array = Allocator.Allocate<MVT>(3);
3584 SDVTList Result = makeVTList(Array, 3);
3585 VTList.push_back(Result);
3589 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3591 case 0: assert(0 && "Cannot have nodes without results!");
3592 case 1: return getVTList(VTs[0]);
3593 case 2: return getVTList(VTs[0], VTs[1]);
3594 case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3598 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
3599 E = VTList.rend(); I != E; ++I) {
3600 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
3603 bool NoMatch = false;
3604 for (unsigned i = 2; i != NumVTs; ++i)
3605 if (VTs[i] != I->VTs[i]) {
3613 MVT *Array = Allocator.Allocate<MVT>(NumVTs);
3614 std::copy(VTs, VTs+NumVTs, Array);
3615 SDVTList Result = makeVTList(Array, NumVTs);
3616 VTList.push_back(Result);
3621 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3622 /// specified operands. If the resultant node already exists in the DAG,
3623 /// this does not modify the specified node, instead it returns the node that
3624 /// already exists. If the resultant node does not exist in the DAG, the
3625 /// input node is returned. As a degenerate case, if you specify the same
3626 /// input operands as the node already has, the input node is returned.
3627 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
3628 SDNode *N = InN.Val;
3629 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3631 // Check to see if there is no change.
3632 if (Op == N->getOperand(0)) return InN;
3634 // See if the modified node already exists.
3635 void *InsertPos = 0;
3636 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3637 return SDValue(Existing, InN.ResNo);
3639 // Nope it doesn't. Remove the node from its current place in the maps.
3641 RemoveNodeFromCSEMaps(N);
3643 // Now we update the operands.
3644 N->OperandList[0].getVal()->removeUser(0, N);
3645 N->OperandList[0] = Op;
3646 N->OperandList[0].setUser(N);
3647 Op.Val->addUser(0, N);
3649 // If this gets put into a CSE map, add it.
3650 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3654 SDValue SelectionDAG::
3655 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
3656 SDNode *N = InN.Val;
3657 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3659 // Check to see if there is no change.
3660 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3661 return InN; // No operands changed, just return the input node.
3663 // See if the modified node already exists.
3664 void *InsertPos = 0;
3665 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3666 return SDValue(Existing, InN.ResNo);
3668 // Nope it doesn't. Remove the node from its current place in the maps.
3670 RemoveNodeFromCSEMaps(N);
3672 // Now we update the operands.
3673 if (N->OperandList[0] != Op1) {
3674 N->OperandList[0].getVal()->removeUser(0, N);
3675 N->OperandList[0] = Op1;
3676 N->OperandList[0].setUser(N);
3677 Op1.Val->addUser(0, N);
3679 if (N->OperandList[1] != Op2) {
3680 N->OperandList[1].getVal()->removeUser(1, N);
3681 N->OperandList[1] = Op2;
3682 N->OperandList[1].setUser(N);
3683 Op2.Val->addUser(1, N);
3686 // If this gets put into a CSE map, add it.
3687 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3691 SDValue SelectionDAG::
3692 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
3693 SDValue Ops[] = { Op1, Op2, Op3 };
3694 return UpdateNodeOperands(N, Ops, 3);
3697 SDValue SelectionDAG::
3698 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3699 SDValue Op3, SDValue Op4) {
3700 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
3701 return UpdateNodeOperands(N, Ops, 4);
3704 SDValue SelectionDAG::
3705 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
3706 SDValue Op3, SDValue Op4, SDValue Op5) {
3707 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3708 return UpdateNodeOperands(N, Ops, 5);
3711 SDValue SelectionDAG::
3712 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
3713 SDNode *N = InN.Val;
3714 assert(N->getNumOperands() == NumOps &&
3715 "Update with wrong number of operands");
3717 // Check to see if there is no change.
3718 bool AnyChange = false;
3719 for (unsigned i = 0; i != NumOps; ++i) {
3720 if (Ops[i] != N->getOperand(i)) {
3726 // No operands changed, just return the input node.
3727 if (!AnyChange) return InN;
3729 // See if the modified node already exists.
3730 void *InsertPos = 0;
3731 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3732 return SDValue(Existing, InN.ResNo);
3734 // Nope it doesn't. Remove the node from its current place in the maps.
3736 RemoveNodeFromCSEMaps(N);
3738 // Now we update the operands.
3739 for (unsigned i = 0; i != NumOps; ++i) {
3740 if (N->OperandList[i] != Ops[i]) {
3741 N->OperandList[i].getVal()->removeUser(i, N);
3742 N->OperandList[i] = Ops[i];
3743 N->OperandList[i].setUser(N);
3744 Ops[i].Val->addUser(i, N);
3748 // If this gets put into a CSE map, add it.
3749 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3753 /// DropOperands - Release the operands and set this node to have
3755 void SDNode::DropOperands() {
3756 // Unlike the code in MorphNodeTo that does this, we don't need to
3757 // watch for dead nodes here.
3758 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3759 I->getVal()->removeUser(std::distance(op_begin(), I), this);
3764 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
3767 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3769 SDVTList VTs = getVTList(VT);
3770 return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
3773 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3774 MVT VT, SDValue Op1) {
3775 SDVTList VTs = getVTList(VT);
3776 SDValue Ops[] = { Op1 };
3777 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
3780 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3781 MVT VT, SDValue Op1,
3783 SDVTList VTs = getVTList(VT);
3784 SDValue Ops[] = { Op1, Op2 };
3785 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
3788 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3789 MVT VT, SDValue Op1,
3790 SDValue Op2, SDValue Op3) {
3791 SDVTList VTs = getVTList(VT);
3792 SDValue Ops[] = { Op1, Op2, Op3 };
3793 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
3796 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3797 MVT VT, const SDValue *Ops,
3799 SDVTList VTs = getVTList(VT);
3800 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3803 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3804 MVT VT1, MVT VT2, const SDValue *Ops,
3806 SDVTList VTs = getVTList(VT1, VT2);
3807 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3810 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3812 SDVTList VTs = getVTList(VT1, VT2);
3813 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
3816 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3817 MVT VT1, MVT VT2, MVT VT3,
3818 const SDValue *Ops, unsigned NumOps) {
3819 SDVTList VTs = getVTList(VT1, VT2, VT3);
3820 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
3823 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3826 SDVTList VTs = getVTList(VT1, VT2);
3827 SDValue Ops[] = { Op1 };
3828 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
3831 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3833 SDValue Op1, SDValue Op2) {
3834 SDVTList VTs = getVTList(VT1, VT2);
3835 SDValue Ops[] = { Op1, Op2 };
3836 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
3839 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3841 SDValue Op1, SDValue Op2,
3843 SDVTList VTs = getVTList(VT1, VT2);
3844 SDValue Ops[] = { Op1, Op2, Op3 };
3845 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
3848 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
3849 SDVTList VTs, const SDValue *Ops,
3851 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
3854 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3856 SDVTList VTs = getVTList(VT);
3857 return MorphNodeTo(N, Opc, VTs, 0, 0);
3860 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3861 MVT VT, SDValue Op1) {
3862 SDVTList VTs = getVTList(VT);
3863 SDValue Ops[] = { Op1 };
3864 return MorphNodeTo(N, Opc, VTs, Ops, 1);
3867 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3868 MVT VT, SDValue Op1,
3870 SDVTList VTs = getVTList(VT);
3871 SDValue Ops[] = { Op1, Op2 };
3872 return MorphNodeTo(N, Opc, VTs, Ops, 2);
3875 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3876 MVT VT, SDValue Op1,
3877 SDValue Op2, SDValue Op3) {
3878 SDVTList VTs = getVTList(VT);
3879 SDValue Ops[] = { Op1, Op2, Op3 };
3880 return MorphNodeTo(N, Opc, VTs, Ops, 3);
3883 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3884 MVT VT, const SDValue *Ops,
3886 SDVTList VTs = getVTList(VT);
3887 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3890 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3891 MVT VT1, MVT VT2, const SDValue *Ops,
3893 SDVTList VTs = getVTList(VT1, VT2);
3894 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3897 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3899 SDVTList VTs = getVTList(VT1, VT2);
3900 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
3903 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3904 MVT VT1, MVT VT2, MVT VT3,
3905 const SDValue *Ops, unsigned NumOps) {
3906 SDVTList VTs = getVTList(VT1, VT2, VT3);
3907 return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
3910 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3913 SDVTList VTs = getVTList(VT1, VT2);
3914 SDValue Ops[] = { Op1 };
3915 return MorphNodeTo(N, Opc, VTs, Ops, 1);
3918 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3920 SDValue Op1, SDValue Op2) {
3921 SDVTList VTs = getVTList(VT1, VT2);
3922 SDValue Ops[] = { Op1, Op2 };
3923 return MorphNodeTo(N, Opc, VTs, Ops, 2);
3926 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3928 SDValue Op1, SDValue Op2,
3930 SDVTList VTs = getVTList(VT1, VT2);
3931 SDValue Ops[] = { Op1, Op2, Op3 };
3932 return MorphNodeTo(N, Opc, VTs, Ops, 3);
3935 /// MorphNodeTo - These *mutate* the specified node to have the specified
3936 /// return type, opcode, and operands.
3938 /// Note that MorphNodeTo returns the resultant node. If there is already a
3939 /// node of the specified opcode and operands, it returns that node instead of
3940 /// the current one.
3942 /// Using MorphNodeTo is faster than creating a new node and swapping it in
3943 /// with ReplaceAllUsesWith both because it often avoids allocating a new
3944 /// node, and because it doesn't require CSE recalulation for any of
3945 /// the node's users.
3947 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
3948 SDVTList VTs, const SDValue *Ops,
3950 // If an identical node already exists, use it.
3952 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
3953 FoldingSetNodeID ID;
3954 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
3955 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3959 RemoveNodeFromCSEMaps(N);
3961 // Start the morphing.
3963 N->ValueList = VTs.VTs;
3964 N->NumValues = VTs.NumVTs;
3966 // Clear the operands list, updating used nodes to remove this from their
3967 // use list. Keep track of any operands that become dead as a result.
3968 SmallPtrSet<SDNode*, 16> DeadNodeSet;
3969 for (SDNode::op_iterator B = N->op_begin(), I = B, E = N->op_end();
3971 SDNode *Used = I->getVal();
3972 Used->removeUser(std::distance(B, I), N);
3973 if (Used->use_empty())
3974 DeadNodeSet.insert(Used);
3977 // If NumOps is larger than the # of operands we currently have, reallocate
3978 // the operand list.
3979 if (NumOps > N->NumOperands) {
3980 if (N->OperandsNeedDelete)
3981 delete[] N->OperandList;
3982 if (N->isMachineOpcode()) {
3983 // We're creating a final node that will live unmorphed for the
3984 // remainder of this SelectionDAG's duration, so we can allocate the
3985 // operands directly out of the pool with no recycling metadata.
3986 N->OperandList = Allocator.Allocate<SDUse>(NumOps);
3987 N->OperandsNeedDelete = false;
3989 N->OperandList = new SDUse[NumOps];
3990 N->OperandsNeedDelete = true;
3994 // Assign the new operands.
3995 N->NumOperands = NumOps;
3996 for (unsigned i = 0, e = NumOps; i != e; ++i) {
3997 N->OperandList[i] = Ops[i];
3998 N->OperandList[i].setUser(N);
3999 SDNode *ToUse = N->OperandList[i].getVal();
4000 ToUse->addUser(i, N);
4001 DeadNodeSet.erase(ToUse);
4004 // Delete any nodes that are still dead after adding the uses for the
4006 SmallVector<SDNode *, 16> DeadNodes;
4007 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4008 E = DeadNodeSet.end(); I != E; ++I)
4009 if ((*I)->use_empty())
4010 DeadNodes.push_back(*I);
4011 RemoveDeadNodes(DeadNodes);
4014 CSEMap.InsertNode(N, IP); // Memoize the new node.
4019 /// getTargetNode - These are used for target selectors to create a new node
4020 /// with specified return type(s), target opcode, and operands.
4022 /// Note that getTargetNode returns the resultant node. If there is already a
4023 /// node of the specified opcode and operands, it returns that node instead of
4024 /// the current one.
4025 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
4026 return getNode(~Opcode, VT).Val;
4028 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
4029 return getNode(~Opcode, VT, Op1).Val;
4031 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4032 SDValue Op1, SDValue Op2) {
4033 return getNode(~Opcode, VT, Op1, Op2).Val;
4035 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4036 SDValue Op1, SDValue Op2,
4038 return getNode(~Opcode, VT, Op1, Op2, Op3).Val;
4040 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
4041 const SDValue *Ops, unsigned NumOps) {
4042 return getNode(~Opcode, VT, Ops, NumOps).Val;
4044 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
4045 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4047 return getNode(~Opcode, VTs, 2, &Op, 0).Val;
4049 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4050 MVT VT2, SDValue Op1) {
4051 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4052 return getNode(~Opcode, VTs, 2, &Op1, 1).Val;
4054 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4055 MVT VT2, SDValue Op1,
4057 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4058 SDValue Ops[] = { Op1, Op2 };
4059 return getNode(~Opcode, VTs, 2, Ops, 2).Val;
4061 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4062 MVT VT2, SDValue Op1,
4063 SDValue Op2, SDValue Op3) {
4064 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4065 SDValue Ops[] = { Op1, Op2, Op3 };
4066 return getNode(~Opcode, VTs, 2, Ops, 3).Val;
4068 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
4069 const SDValue *Ops, unsigned NumOps) {
4070 const MVT *VTs = getNodeValueTypes(VT1, VT2);
4071 return getNode(~Opcode, VTs, 2, Ops, NumOps).Val;
4073 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4074 SDValue Op1, SDValue Op2) {
4075 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4076 SDValue Ops[] = { Op1, Op2 };
4077 return getNode(~Opcode, VTs, 3, Ops, 2).Val;
4079 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4080 SDValue Op1, SDValue Op2,
4082 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4083 SDValue Ops[] = { Op1, Op2, Op3 };
4084 return getNode(~Opcode, VTs, 3, Ops, 3).Val;
4086 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
4087 const SDValue *Ops, unsigned NumOps) {
4088 const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
4089 return getNode(~Opcode, VTs, 3, Ops, NumOps).Val;
4091 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
4092 MVT VT2, MVT VT3, MVT VT4,
4093 const SDValue *Ops, unsigned NumOps) {
4094 std::vector<MVT> VTList;
4095 VTList.push_back(VT1);
4096 VTList.push_back(VT2);
4097 VTList.push_back(VT3);
4098 VTList.push_back(VT4);
4099 const MVT *VTs = getNodeValueTypes(VTList);
4100 return getNode(~Opcode, VTs, 4, Ops, NumOps).Val;
4102 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
4103 const std::vector<MVT> &ResultTys,
4104 const SDValue *Ops, unsigned NumOps) {
4105 const MVT *VTs = getNodeValueTypes(ResultTys);
4106 return getNode(~Opcode, VTs, ResultTys.size(),
4110 /// getNodeIfExists - Get the specified node if it's already available, or
4111 /// else return NULL.
4112 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4113 const SDValue *Ops, unsigned NumOps) {
4114 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
4115 FoldingSetNodeID ID;
4116 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4118 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4125 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4126 /// This can cause recursive merging of nodes in the DAG.
4128 /// This version assumes From has a single result value.
4130 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
4131 DAGUpdateListener *UpdateListener) {
4132 SDNode *From = FromN.Val;
4133 assert(From->getNumValues() == 1 && FromN.ResNo == 0 &&
4134 "Cannot replace with this method!");
4135 assert(From != To.Val && "Cannot replace uses of with self");
4137 while (!From->use_empty()) {
4138 SDNode::use_iterator UI = From->use_begin();
4141 // This node is about to morph, remove its old self from the CSE maps.
4142 RemoveNodeFromCSEMaps(U);
4144 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4145 I != E; ++I, ++operandNum)
4146 if (I->getVal() == From) {
4147 From->removeUser(operandNum, U);
4150 To.Val->addUser(operandNum, U);
4153 // Now that we have modified U, add it back to the CSE maps. If it already
4154 // exists there, recursively merge the results together.
4155 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4156 ReplaceAllUsesWith(U, Existing, UpdateListener);
4157 // U is now dead. Inform the listener if it exists and delete it.
4159 UpdateListener->NodeDeleted(U, Existing);
4160 DeleteNodeNotInCSEMaps(U);
4162 // If the node doesn't already exist, we updated it. Inform a listener if
4165 UpdateListener->NodeUpdated(U);
4170 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4171 /// This can cause recursive merging of nodes in the DAG.
4173 /// This version assumes From/To have matching types and numbers of result
4176 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
4177 DAGUpdateListener *UpdateListener) {
4178 assert(From->getVTList().VTs == To->getVTList().VTs &&
4179 From->getNumValues() == To->getNumValues() &&
4180 "Cannot use this version of ReplaceAllUsesWith!");
4182 // Handle the trivial case.
4186 while (!From->use_empty()) {
4187 SDNode::use_iterator UI = From->use_begin();
4190 // This node is about to morph, remove its old self from the CSE maps.
4191 RemoveNodeFromCSEMaps(U);
4193 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4194 I != E; ++I, ++operandNum)
4195 if (I->getVal() == From) {
4196 From->removeUser(operandNum, U);
4198 To->addUser(operandNum, U);
4201 // Now that we have modified U, add it back to the CSE maps. If it already
4202 // exists there, recursively merge the results together.
4203 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4204 ReplaceAllUsesWith(U, Existing, UpdateListener);
4205 // U is now dead. Inform the listener if it exists and delete it.
4207 UpdateListener->NodeDeleted(U, Existing);
4208 DeleteNodeNotInCSEMaps(U);
4210 // If the node doesn't already exist, we updated it. Inform a listener if
4213 UpdateListener->NodeUpdated(U);
4218 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
4219 /// This can cause recursive merging of nodes in the DAG.
4221 /// This version can replace From with any result values. To must match the
4222 /// number and types of values returned by From.
4223 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
4225 DAGUpdateListener *UpdateListener) {
4226 if (From->getNumValues() == 1) // Handle the simple case efficiently.
4227 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
4229 while (!From->use_empty()) {
4230 SDNode::use_iterator UI = From->use_begin();
4233 // This node is about to morph, remove its old self from the CSE maps.
4234 RemoveNodeFromCSEMaps(U);
4236 for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
4237 I != E; ++I, ++operandNum)
4238 if (I->getVal() == From) {
4239 const SDValue &ToOp = To[I->getSDValue().ResNo];
4240 From->removeUser(operandNum, U);
4243 ToOp.Val->addUser(operandNum, U);
4246 // Now that we have modified U, add it back to the CSE maps. If it already
4247 // exists there, recursively merge the results together.
4248 if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
4249 ReplaceAllUsesWith(U, Existing, UpdateListener);
4250 // U is now dead. Inform the listener if it exists and delete it.
4252 UpdateListener->NodeDeleted(U, Existing);
4253 DeleteNodeNotInCSEMaps(U);
4255 // If the node doesn't already exist, we updated it. Inform a listener if
4258 UpdateListener->NodeUpdated(U);
4263 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4264 /// uses of other values produced by From.Val alone. The Deleted vector is
4265 /// handled the same way as for ReplaceAllUsesWith.
4266 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
4267 DAGUpdateListener *UpdateListener){
4268 // Handle the really simple, really trivial case efficiently.
4269 if (From == To) return;
4271 // Handle the simple, trivial, case efficiently.
4272 if (From.Val->getNumValues() == 1) {
4273 ReplaceAllUsesWith(From, To, UpdateListener);
4277 // Get all of the users of From.Val. We want these in a nice,
4278 // deterministically ordered and uniqued set, so we use a SmallSetVector.
4279 SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
4281 while (!Users.empty()) {
4282 // We know that this user uses some value of From. If it is the right
4283 // value, update it.
4284 SDNode *User = Users.back();
4287 // Scan for an operand that matches From.
4288 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4289 for (; Op != E; ++Op)
4290 if (*Op == From) break;
4292 // If there are no matches, the user must use some other result of From.
4293 if (Op == E) continue;
4295 // Okay, we know this user needs to be updated. Remove its old self
4296 // from the CSE maps.
4297 RemoveNodeFromCSEMaps(User);
4299 // Update all operands that match "From" in case there are multiple uses.
4300 for (; Op != E; ++Op) {
4302 From.Val->removeUser(Op-User->op_begin(), User);
4305 To.Val->addUser(Op-User->op_begin(), User);
4309 // Now that we have modified User, add it back to the CSE maps. If it
4310 // already exists there, recursively merge the results together.
4311 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4313 if (UpdateListener) UpdateListener->NodeUpdated(User);
4314 continue; // Continue on to next user.
4317 // If there was already an existing matching node, use ReplaceAllUsesWith
4318 // to replace the dead one with the existing one. This can cause
4319 // recursive merging of other unrelated nodes down the line.
4320 ReplaceAllUsesWith(User, Existing, UpdateListener);
4322 // User is now dead. Notify a listener if present.
4323 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4324 DeleteNodeNotInCSEMaps(User);
4328 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
4329 /// uses of other values produced by From.Val alone. The same value may
4330 /// appear in both the From and To list. The Deleted vector is
4331 /// handled the same way as for ReplaceAllUsesWith.
4332 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
4335 DAGUpdateListener *UpdateListener){
4336 // Handle the simple, trivial case efficiently.
4338 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
4340 SmallVector<std::pair<SDNode *, unsigned>, 16> Users;
4341 for (unsigned i = 0; i != Num; ++i)
4342 for (SDNode::use_iterator UI = From[i].Val->use_begin(),
4343 E = From[i].Val->use_end(); UI != E; ++UI)
4344 Users.push_back(std::make_pair(*UI, i));
4346 while (!Users.empty()) {
4347 // We know that this user uses some value of From. If it is the right
4348 // value, update it.
4349 SDNode *User = Users.back().first;
4350 unsigned i = Users.back().second;
4353 // Scan for an operand that matches From.
4354 SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4355 for (; Op != E; ++Op)
4356 if (*Op == From[i]) break;
4358 // If there are no matches, the user must use some other result of From.
4359 if (Op == E) continue;
4361 // Okay, we know this user needs to be updated. Remove its old self
4362 // from the CSE maps.
4363 RemoveNodeFromCSEMaps(User);
4365 // Update all operands that match "From" in case there are multiple uses.
4366 for (; Op != E; ++Op) {
4367 if (*Op == From[i]) {
4368 From[i].Val->removeUser(Op-User->op_begin(), User);
4371 To[i].Val->addUser(Op-User->op_begin(), User);
4375 // Now that we have modified User, add it back to the CSE maps. If it
4376 // already exists there, recursively merge the results together.
4377 SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4379 if (UpdateListener) UpdateListener->NodeUpdated(User);
4380 continue; // Continue on to next user.
4383 // If there was already an existing matching node, use ReplaceAllUsesWith
4384 // to replace the dead one with the existing one. This can cause
4385 // recursive merging of other unrelated nodes down the line.
4386 ReplaceAllUsesWith(User, Existing, UpdateListener);
4388 // User is now dead. Notify a listener if present.
4389 if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4390 DeleteNodeNotInCSEMaps(User);
4394 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4395 /// based on their topological order. It returns the maximum id and a vector
4396 /// of the SDNodes* in assigned order by reference.
4397 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4398 unsigned DAGSize = AllNodes.size();
4399 std::vector<unsigned> InDegree(DAGSize);
4400 std::vector<SDNode*> Sources;
4402 // Use a two pass approach to avoid using a std::map which is slow.
4404 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4407 unsigned Degree = N->use_size();
4408 InDegree[N->getNodeId()] = Degree;
4410 Sources.push_back(N);
4414 TopOrder.reserve(DAGSize);
4415 while (!Sources.empty()) {
4416 SDNode *N = Sources.back();
4418 TopOrder.push_back(N);
4419 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4420 SDNode *P = I->getVal();
4421 unsigned Degree = --InDegree[P->getNodeId()];
4423 Sources.push_back(P);
4427 // Second pass, assign the actual topological order as node ids.
4429 for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4431 (*TI)->setNodeId(Id++);
4438 //===----------------------------------------------------------------------===//
4440 //===----------------------------------------------------------------------===//
4442 // Out-of-line virtual method to give class a home.
4443 void SDNode::ANCHOR() {}
4444 void UnarySDNode::ANCHOR() {}
4445 void BinarySDNode::ANCHOR() {}
4446 void TernarySDNode::ANCHOR() {}
4447 void HandleSDNode::ANCHOR() {}
4448 void ConstantSDNode::ANCHOR() {}
4449 void ConstantFPSDNode::ANCHOR() {}
4450 void GlobalAddressSDNode::ANCHOR() {}
4451 void FrameIndexSDNode::ANCHOR() {}
4452 void JumpTableSDNode::ANCHOR() {}
4453 void ConstantPoolSDNode::ANCHOR() {}
4454 void BasicBlockSDNode::ANCHOR() {}
4455 void SrcValueSDNode::ANCHOR() {}
4456 void MemOperandSDNode::ANCHOR() {}
4457 void RegisterSDNode::ANCHOR() {}
4458 void DbgStopPointSDNode::ANCHOR() {}
4459 void LabelSDNode::ANCHOR() {}
4460 void ExternalSymbolSDNode::ANCHOR() {}
4461 void CondCodeSDNode::ANCHOR() {}
4462 void ARG_FLAGSSDNode::ANCHOR() {}
4463 void VTSDNode::ANCHOR() {}
4464 void MemSDNode::ANCHOR() {}
4465 void LoadSDNode::ANCHOR() {}
4466 void StoreSDNode::ANCHOR() {}
4467 void AtomicSDNode::ANCHOR() {}
4469 HandleSDNode::~HandleSDNode() {
4473 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4475 : SDNode(isa<GlobalVariable>(GA) &&
4476 cast<GlobalVariable>(GA)->isThreadLocal() ?
4478 (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4480 (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4481 getSDVTList(VT)), Offset(o) {
4482 TheGlobal = const_cast<GlobalValue*>(GA);
4485 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
4486 const Value *srcValue, int SVO,
4487 unsigned alignment, bool vol)
4488 : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO),
4489 Flags(encodeMemSDNodeFlags(vol, alignment)) {
4491 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
4492 assert(getAlignment() == alignment && "Alignment representation error!");
4493 assert(isVolatile() == vol && "Volatile representation error!");
4496 /// getMemOperand - Return a MachineMemOperand object describing the memory
4497 /// reference performed by this memory reference.
4498 MachineMemOperand MemSDNode::getMemOperand() const {
4500 if (isa<LoadSDNode>(this))
4501 Flags = MachineMemOperand::MOLoad;
4502 else if (isa<StoreSDNode>(this))
4503 Flags = MachineMemOperand::MOStore;
4505 assert(isa<AtomicSDNode>(this) && "Unknown MemSDNode opcode!");
4506 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4509 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4510 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
4512 // Check if the memory reference references a frame index
4513 const FrameIndexSDNode *FI =
4514 dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4515 if (!getSrcValue() && FI)
4516 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
4517 Flags, 0, Size, getAlignment());
4519 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
4520 Size, getAlignment());
4523 /// Profile - Gather unique data for the node.
4525 void SDNode::Profile(FoldingSetNodeID &ID) const {
4526 AddNodeIDNode(ID, this);
4529 /// getValueTypeList - Return a pointer to the specified value type.
4531 const MVT *SDNode::getValueTypeList(MVT VT) {
4532 if (VT.isExtended()) {
4533 static std::set<MVT, MVT::compareRawBits> EVTs;
4534 return &(*EVTs.insert(VT).first);
4536 static MVT VTs[MVT::LAST_VALUETYPE];
4537 VTs[VT.getSimpleVT()] = VT;
4538 return &VTs[VT.getSimpleVT()];
4542 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4543 /// indicated value. This method ignores uses of other values defined by this
4545 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4546 assert(Value < getNumValues() && "Bad value!");
4548 // TODO: Only iterate over uses of a given value of the node
4549 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4550 if (UI.getUse().getSDValue().ResNo == Value) {
4557 // Found exactly the right number of uses?
4562 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4563 /// value. This method ignores uses of other values defined by this operation.
4564 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4565 assert(Value < getNumValues() && "Bad value!");
4567 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
4568 if (UI.getUse().getSDValue().ResNo == Value)
4575 /// isOnlyUserOf - Return true if this node is the only use of N.
4577 bool SDNode::isOnlyUserOf(SDNode *N) const {
4579 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4590 /// isOperand - Return true if this node is an operand of N.
4592 bool SDValue::isOperandOf(SDNode *N) const {
4593 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4594 if (*this == N->getOperand(i))
4599 bool SDNode::isOperandOf(SDNode *N) const {
4600 for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4601 if (this == N->OperandList[i].getVal())
4606 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4607 /// be a chain) reaches the specified operand without crossing any
4608 /// side-effecting instructions. In practice, this looks through token
4609 /// factors and non-volatile loads. In order to remain efficient, this only
4610 /// looks a couple of nodes in, it does not do an exhaustive search.
4611 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
4612 unsigned Depth) const {
4613 if (*this == Dest) return true;
4615 // Don't search too deeply, we just want to be able to see through
4616 // TokenFactor's etc.
4617 if (Depth == 0) return false;
4619 // If this is a token factor, all inputs to the TF happen in parallel. If any
4620 // of the operands of the TF reach dest, then we can do the xform.
4621 if (getOpcode() == ISD::TokenFactor) {
4622 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4623 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4628 // Loads don't have side effects, look through them.
4629 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4630 if (!Ld->isVolatile())
4631 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4637 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4638 SmallPtrSet<SDNode *, 32> &Visited) {
4639 if (found || !Visited.insert(N))
4642 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4643 SDNode *Op = N->getOperand(i).Val;
4648 findPredecessor(Op, P, found, Visited);
4652 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4653 /// is either an operand of N or it can be reached by recursively traversing
4654 /// up the operands.
4655 /// NOTE: this is an expensive method. Use it carefully.
4656 bool SDNode::isPredecessorOf(SDNode *N) const {
4657 SmallPtrSet<SDNode *, 32> Visited;
4659 findPredecessor(N, this, found, Visited);
4663 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4664 assert(Num < NumOperands && "Invalid child # of SDNode!");
4665 return cast<ConstantSDNode>(OperandList[Num])->getValue();
4668 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4669 switch (getOpcode()) {
4671 if (getOpcode() < ISD::BUILTIN_OP_END)
4672 return "<<Unknown DAG Node>>";
4673 if (isMachineOpcode()) {
4675 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4676 if (getMachineOpcode() < TII->getNumOpcodes())
4677 return TII->get(getMachineOpcode()).getName();
4678 return "<<Unknown Machine Node>>";
4681 TargetLowering &TLI = G->getTargetLoweringInfo();
4682 const char *Name = TLI.getTargetNodeName(getOpcode());
4683 if (Name) return Name;
4684 return "<<Unknown Target Node>>";
4686 return "<<Unknown Node>>";
4689 case ISD::DELETED_NODE:
4690 return "<<Deleted Node!>>";
4692 case ISD::PREFETCH: return "Prefetch";
4693 case ISD::MEMBARRIER: return "MemBarrier";
4694 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
4695 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
4696 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
4697 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
4698 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
4699 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
4700 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4701 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
4702 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
4703 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4704 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4705 case ISD::ATOMIC_SWAP: return "AtomicSWAP";
4706 case ISD::PCMARKER: return "PCMarker";
4707 case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4708 case ISD::SRCVALUE: return "SrcValue";
4709 case ISD::MEMOPERAND: return "MemOperand";
4710 case ISD::EntryToken: return "EntryToken";
4711 case ISD::TokenFactor: return "TokenFactor";
4712 case ISD::AssertSext: return "AssertSext";
4713 case ISD::AssertZext: return "AssertZext";
4715 case ISD::BasicBlock: return "BasicBlock";
4716 case ISD::ARG_FLAGS: return "ArgFlags";
4717 case ISD::VALUETYPE: return "ValueType";
4718 case ISD::Register: return "Register";
4720 case ISD::Constant: return "Constant";
4721 case ISD::ConstantFP: return "ConstantFP";
4722 case ISD::GlobalAddress: return "GlobalAddress";
4723 case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4724 case ISD::FrameIndex: return "FrameIndex";
4725 case ISD::JumpTable: return "JumpTable";
4726 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4727 case ISD::RETURNADDR: return "RETURNADDR";
4728 case ISD::FRAMEADDR: return "FRAMEADDR";
4729 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4730 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4731 case ISD::EHSELECTION: return "EHSELECTION";
4732 case ISD::EH_RETURN: return "EH_RETURN";
4733 case ISD::ConstantPool: return "ConstantPool";
4734 case ISD::ExternalSymbol: return "ExternalSymbol";
4735 case ISD::INTRINSIC_WO_CHAIN: {
4736 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4737 return Intrinsic::getName((Intrinsic::ID)IID);
4739 case ISD::INTRINSIC_VOID:
4740 case ISD::INTRINSIC_W_CHAIN: {
4741 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4742 return Intrinsic::getName((Intrinsic::ID)IID);
4745 case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
4746 case ISD::TargetConstant: return "TargetConstant";
4747 case ISD::TargetConstantFP:return "TargetConstantFP";
4748 case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4749 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4750 case ISD::TargetFrameIndex: return "TargetFrameIndex";
4751 case ISD::TargetJumpTable: return "TargetJumpTable";
4752 case ISD::TargetConstantPool: return "TargetConstantPool";
4753 case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4755 case ISD::CopyToReg: return "CopyToReg";
4756 case ISD::CopyFromReg: return "CopyFromReg";
4757 case ISD::UNDEF: return "undef";
4758 case ISD::MERGE_VALUES: return "merge_values";
4759 case ISD::INLINEASM: return "inlineasm";
4760 case ISD::DBG_LABEL: return "dbg_label";
4761 case ISD::EH_LABEL: return "eh_label";
4762 case ISD::DECLARE: return "declare";
4763 case ISD::HANDLENODE: return "handlenode";
4764 case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4765 case ISD::CALL: return "call";
4768 case ISD::FABS: return "fabs";
4769 case ISD::FNEG: return "fneg";
4770 case ISD::FSQRT: return "fsqrt";
4771 case ISD::FSIN: return "fsin";
4772 case ISD::FCOS: return "fcos";
4773 case ISD::FPOWI: return "fpowi";
4774 case ISD::FPOW: return "fpow";
4777 case ISD::ADD: return "add";
4778 case ISD::SUB: return "sub";
4779 case ISD::MUL: return "mul";
4780 case ISD::MULHU: return "mulhu";
4781 case ISD::MULHS: return "mulhs";
4782 case ISD::SDIV: return "sdiv";
4783 case ISD::UDIV: return "udiv";
4784 case ISD::SREM: return "srem";
4785 case ISD::UREM: return "urem";
4786 case ISD::SMUL_LOHI: return "smul_lohi";
4787 case ISD::UMUL_LOHI: return "umul_lohi";
4788 case ISD::SDIVREM: return "sdivrem";
4789 case ISD::UDIVREM: return "divrem";
4790 case ISD::AND: return "and";
4791 case ISD::OR: return "or";
4792 case ISD::XOR: return "xor";
4793 case ISD::SHL: return "shl";
4794 case ISD::SRA: return "sra";
4795 case ISD::SRL: return "srl";
4796 case ISD::ROTL: return "rotl";
4797 case ISD::ROTR: return "rotr";
4798 case ISD::FADD: return "fadd";
4799 case ISD::FSUB: return "fsub";
4800 case ISD::FMUL: return "fmul";
4801 case ISD::FDIV: return "fdiv";
4802 case ISD::FREM: return "frem";
4803 case ISD::FCOPYSIGN: return "fcopysign";
4804 case ISD::FGETSIGN: return "fgetsign";
4806 case ISD::SETCC: return "setcc";
4807 case ISD::VSETCC: return "vsetcc";
4808 case ISD::SELECT: return "select";
4809 case ISD::SELECT_CC: return "select_cc";
4810 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
4811 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
4812 case ISD::CONCAT_VECTORS: return "concat_vectors";
4813 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
4814 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
4815 case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
4816 case ISD::CARRY_FALSE: return "carry_false";
4817 case ISD::ADDC: return "addc";
4818 case ISD::ADDE: return "adde";
4819 case ISD::SUBC: return "subc";
4820 case ISD::SUBE: return "sube";
4821 case ISD::SHL_PARTS: return "shl_parts";
4822 case ISD::SRA_PARTS: return "sra_parts";
4823 case ISD::SRL_PARTS: return "srl_parts";
4825 case ISD::EXTRACT_SUBREG: return "extract_subreg";
4826 case ISD::INSERT_SUBREG: return "insert_subreg";
4828 // Conversion operators.
4829 case ISD::SIGN_EXTEND: return "sign_extend";
4830 case ISD::ZERO_EXTEND: return "zero_extend";
4831 case ISD::ANY_EXTEND: return "any_extend";
4832 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4833 case ISD::TRUNCATE: return "truncate";
4834 case ISD::FP_ROUND: return "fp_round";
4835 case ISD::FLT_ROUNDS_: return "flt_rounds";
4836 case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4837 case ISD::FP_EXTEND: return "fp_extend";
4839 case ISD::SINT_TO_FP: return "sint_to_fp";
4840 case ISD::UINT_TO_FP: return "uint_to_fp";
4841 case ISD::FP_TO_SINT: return "fp_to_sint";
4842 case ISD::FP_TO_UINT: return "fp_to_uint";
4843 case ISD::BIT_CONVERT: return "bit_convert";
4845 // Control flow instructions
4846 case ISD::BR: return "br";
4847 case ISD::BRIND: return "brind";
4848 case ISD::BR_JT: return "br_jt";
4849 case ISD::BRCOND: return "brcond";
4850 case ISD::BR_CC: return "br_cc";
4851 case ISD::RET: return "ret";
4852 case ISD::CALLSEQ_START: return "callseq_start";
4853 case ISD::CALLSEQ_END: return "callseq_end";
4856 case ISD::LOAD: return "load";
4857 case ISD::STORE: return "store";
4858 case ISD::VAARG: return "vaarg";
4859 case ISD::VACOPY: return "vacopy";
4860 case ISD::VAEND: return "vaend";
4861 case ISD::VASTART: return "vastart";
4862 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4863 case ISD::EXTRACT_ELEMENT: return "extract_element";
4864 case ISD::BUILD_PAIR: return "build_pair";
4865 case ISD::STACKSAVE: return "stacksave";
4866 case ISD::STACKRESTORE: return "stackrestore";
4867 case ISD::TRAP: return "trap";
4870 case ISD::BSWAP: return "bswap";
4871 case ISD::CTPOP: return "ctpop";
4872 case ISD::CTTZ: return "cttz";
4873 case ISD::CTLZ: return "ctlz";
4876 case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
4877 case ISD::DEBUG_LOC: return "debug_loc";
4880 case ISD::TRAMPOLINE: return "trampoline";
4883 switch (cast<CondCodeSDNode>(this)->get()) {
4884 default: assert(0 && "Unknown setcc condition!");
4885 case ISD::SETOEQ: return "setoeq";
4886 case ISD::SETOGT: return "setogt";
4887 case ISD::SETOGE: return "setoge";
4888 case ISD::SETOLT: return "setolt";
4889 case ISD::SETOLE: return "setole";
4890 case ISD::SETONE: return "setone";
4892 case ISD::SETO: return "seto";
4893 case ISD::SETUO: return "setuo";
4894 case ISD::SETUEQ: return "setue";
4895 case ISD::SETUGT: return "setugt";
4896 case ISD::SETUGE: return "setuge";
4897 case ISD::SETULT: return "setult";
4898 case ISD::SETULE: return "setule";
4899 case ISD::SETUNE: return "setune";
4901 case ISD::SETEQ: return "seteq";
4902 case ISD::SETGT: return "setgt";
4903 case ISD::SETGE: return "setge";
4904 case ISD::SETLT: return "setlt";
4905 case ISD::SETLE: return "setle";
4906 case ISD::SETNE: return "setne";
4911 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4920 return "<post-inc>";
4922 return "<post-dec>";
4926 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4927 std::string S = "< ";
4941 if (getByValAlign())
4942 S += "byval-align:" + utostr(getByValAlign()) + " ";
4944 S += "orig-align:" + utostr(getOrigAlign()) + " ";
4946 S += "byval-size:" + utostr(getByValSize()) + " ";
4950 void SDNode::dump() const { dump(0); }
4951 void SDNode::dump(const SelectionDAG *G) const {
4952 cerr << (void*)this << ": ";
4954 for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4956 if (getValueType(i) == MVT::Other)
4959 cerr << getValueType(i).getMVTString();
4961 cerr << " = " << getOperationName(G);
4964 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4965 if (i) cerr << ", ";
4966 cerr << (void*)getOperand(i).Val;
4967 if (unsigned RN = getOperand(i).ResNo)
4971 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4972 SDNode *Mask = getOperand(2).Val;
4974 for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4976 if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4979 cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4984 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4985 cerr << '<' << CSDN->getAPIntValue() << '>';
4986 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4987 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4988 cerr << '<' << CSDN->getValueAPF().convertToFloat() << '>';
4989 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4990 cerr << '<' << CSDN->getValueAPF().convertToDouble() << '>';
4992 cerr << "<APFloat(";
4993 CSDN->getValueAPF().convertToAPInt().dump();
4996 } else if (const GlobalAddressSDNode *GADN =
4997 dyn_cast<GlobalAddressSDNode>(this)) {
4998 int offset = GADN->getOffset();
5000 WriteAsOperand(*cerr.stream(), GADN->getGlobal());
5003 cerr << " + " << offset;
5005 cerr << " " << offset;
5006 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
5007 cerr << "<" << FIDN->getIndex() << ">";
5008 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
5009 cerr << "<" << JTDN->getIndex() << ">";
5010 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
5011 int offset = CP->getOffset();
5012 if (CP->isMachineConstantPoolEntry())
5013 cerr << "<" << *CP->getMachineCPVal() << ">";
5015 cerr << "<" << *CP->getConstVal() << ">";
5017 cerr << " + " << offset;
5019 cerr << " " << offset;
5020 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
5022 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
5024 cerr << LBB->getName() << " ";
5025 cerr << (const void*)BBDN->getBasicBlock() << ">";
5026 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
5027 if (G && R->getReg() &&
5028 TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
5029 cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
5031 cerr << " #" << R->getReg();
5033 } else if (const ExternalSymbolSDNode *ES =
5034 dyn_cast<ExternalSymbolSDNode>(this)) {
5035 cerr << "'" << ES->getSymbol() << "'";
5036 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
5038 cerr << "<" << M->getValue() << ">";
5041 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
5042 if (M->MO.getValue())
5043 cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
5045 cerr << "<null:" << M->MO.getOffset() << ">";
5046 } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
5047 cerr << N->getArgFlags().getArgFlagsString();
5048 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
5049 cerr << ":" << N->getVT().getMVTString();
5051 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
5052 const Value *SrcValue = LD->getSrcValue();
5053 int SrcOffset = LD->getSrcValueOffset();
5059 cerr << ":" << SrcOffset << ">";
5062 switch (LD->getExtensionType()) {
5063 default: doExt = false; break;
5065 cerr << " <anyext ";
5075 cerr << LD->getMemoryVT().getMVTString() << ">";
5077 const char *AM = getIndexedModeName(LD->getAddressingMode());
5080 if (LD->isVolatile())
5081 cerr << " <volatile>";
5082 cerr << " alignment=" << LD->getAlignment();
5083 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
5084 const Value *SrcValue = ST->getSrcValue();
5085 int SrcOffset = ST->getSrcValueOffset();
5091 cerr << ":" << SrcOffset << ">";
5093 if (ST->isTruncatingStore())
5095 << ST->getMemoryVT().getMVTString() << ">";
5097 const char *AM = getIndexedModeName(ST->getAddressingMode());
5100 if (ST->isVolatile())
5101 cerr << " <volatile>";
5102 cerr << " alignment=" << ST->getAlignment();
5103 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
5104 const Value *SrcValue = AT->getSrcValue();
5105 int SrcOffset = AT->getSrcValueOffset();
5111 cerr << ":" << SrcOffset << ">";
5112 if (AT->isVolatile())
5113 cerr << " <volatile>";
5114 cerr << " alignment=" << AT->getAlignment();
5118 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
5119 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5120 if (N->getOperand(i).Val->hasOneUse())
5121 DumpNodes(N->getOperand(i).Val, indent+2, G);
5123 cerr << "\n" << std::string(indent+2, ' ')
5124 << (void*)N->getOperand(i).Val << ": <multiple use>";
5127 cerr << "\n" << std::string(indent, ' ');
5131 void SelectionDAG::dump() const {
5132 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
5134 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
5136 const SDNode *N = I;
5137 if (!N->hasOneUse() && N != getRoot().Val)
5138 DumpNodes(N, 2, this);
5141 if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
5146 const Type *ConstantPoolSDNode::getType() const {
5147 if (isMachineConstantPoolEntry())
5148 return Val.MachineCPVal->getType();
5149 return Val.ConstVal->getType();