SelectionDAG.cpp revision 98ca4f2a325f72374a477f9deba7d09e8999c29b
1//===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This implements the SelectionDAG class. 11// 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/Target/TargetRegisterInfo.h" 28#include "llvm/Target/TargetData.h" 29#include "llvm/Target/TargetLowering.h" 30#include "llvm/Target/TargetOptions.h" 31#include "llvm/Target/TargetInstrInfo.h" 32#include "llvm/Target/TargetMachine.h" 33#include "llvm/Support/CommandLine.h" 34#include "llvm/Support/ErrorHandling.h" 35#include "llvm/Support/ManagedStatic.h" 36#include "llvm/Support/MathExtras.h" 37#include "llvm/Support/raw_ostream.h" 38#include "llvm/System/Mutex.h" 39#include "llvm/ADT/SetVector.h" 40#include "llvm/ADT/SmallPtrSet.h" 41#include "llvm/ADT/SmallSet.h" 42#include "llvm/ADT/SmallVector.h" 43#include "llvm/ADT/StringExtras.h" 44#include <algorithm> 45#include <cmath> 46using namespace llvm; 47 48/// makeVTList - Return an instance of the SDVTList struct initialized with the 49/// specified members. 50static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) { 51 SDVTList Res = {VTs, NumVTs}; 52 return Res; 53} 54 55static const fltSemantics *MVTToAPFloatSemantics(MVT VT) { 56 switch (VT.getSimpleVT()) { 57 default: llvm_unreachable("Unknown FP format"); 58 case MVT::f32: return &APFloat::IEEEsingle; 59 case MVT::f64: return &APFloat::IEEEdouble; 60 case MVT::f80: return &APFloat::x87DoubleExtended; 61 case MVT::f128: return &APFloat::IEEEquad; 62 case MVT::ppcf128: return &APFloat::PPCDoubleDouble; 63 } 64} 65 66SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {} 67 68//===----------------------------------------------------------------------===// 69// ConstantFPSDNode Class 70//===----------------------------------------------------------------------===// 71 72/// isExactlyValue - We don't rely on operator== working on double values, as 73/// it returns true for things that are clearly not equal, like -0.0 and 0.0. 74/// As such, this method can be used to do an exact bit-for-bit comparison of 75/// two floating point values. 76bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 77 return getValueAPF().bitwiseIsEqual(V); 78} 79 80bool ConstantFPSDNode::isValueValidForType(MVT VT, 81 const APFloat& Val) { 82 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 83 84 // PPC long double cannot be converted to any other type. 85 if (VT == MVT::ppcf128 || 86 &Val.getSemantics() == &APFloat::PPCDoubleDouble) 87 return false; 88 89 // convert modifies in place, so make a copy. 90 APFloat Val2 = APFloat(Val); 91 bool losesInfo; 92 (void) Val2.convert(*MVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 93 &losesInfo); 94 return !losesInfo; 95} 96 97//===----------------------------------------------------------------------===// 98// ISD Namespace 99//===----------------------------------------------------------------------===// 100 101/// isBuildVectorAllOnes - Return true if the specified node is a 102/// BUILD_VECTOR where all of the elements are ~0 or undef. 103bool ISD::isBuildVectorAllOnes(const SDNode *N) { 104 // Look through a bit convert. 105 if (N->getOpcode() == ISD::BIT_CONVERT) 106 N = N->getOperand(0).getNode(); 107 108 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 109 110 unsigned i = 0, e = N->getNumOperands(); 111 112 // Skip over all of the undef values. 113 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF) 114 ++i; 115 116 // Do not accept an all-undef vector. 117 if (i == e) return false; 118 119 // Do not accept build_vectors that aren't all constants or which have non-~0 120 // elements. 121 SDValue NotZero = N->getOperand(i); 122 if (isa<ConstantSDNode>(NotZero)) { 123 if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue()) 124 return false; 125 } else if (isa<ConstantFPSDNode>(NotZero)) { 126 if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF(). 127 bitcastToAPInt().isAllOnesValue()) 128 return false; 129 } else 130 return false; 131 132 // Okay, we have at least one ~0 value, check to see if the rest match or are 133 // undefs. 134 for (++i; i != e; ++i) 135 if (N->getOperand(i) != NotZero && 136 N->getOperand(i).getOpcode() != ISD::UNDEF) 137 return false; 138 return true; 139} 140 141 142/// isBuildVectorAllZeros - Return true if the specified node is a 143/// BUILD_VECTOR where all of the elements are 0 or undef. 144bool ISD::isBuildVectorAllZeros(const SDNode *N) { 145 // Look through a bit convert. 146 if (N->getOpcode() == ISD::BIT_CONVERT) 147 N = N->getOperand(0).getNode(); 148 149 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 150 151 unsigned i = 0, e = N->getNumOperands(); 152 153 // Skip over all of the undef values. 154 while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF) 155 ++i; 156 157 // Do not accept an all-undef vector. 158 if (i == e) return false; 159 160 // Do not accept build_vectors that aren't all constants or which have non-0 161 // elements. 162 SDValue Zero = N->getOperand(i); 163 if (isa<ConstantSDNode>(Zero)) { 164 if (!cast<ConstantSDNode>(Zero)->isNullValue()) 165 return false; 166 } else if (isa<ConstantFPSDNode>(Zero)) { 167 if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero()) 168 return false; 169 } else 170 return false; 171 172 // Okay, we have at least one 0 value, check to see if the rest match or are 173 // undefs. 174 for (++i; i != e; ++i) 175 if (N->getOperand(i) != Zero && 176 N->getOperand(i).getOpcode() != ISD::UNDEF) 177 return false; 178 return true; 179} 180 181/// isScalarToVector - Return true if the specified node is a 182/// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low 183/// element is not an undef. 184bool ISD::isScalarToVector(const SDNode *N) { 185 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) 186 return true; 187 188 if (N->getOpcode() != ISD::BUILD_VECTOR) 189 return false; 190 if (N->getOperand(0).getOpcode() == ISD::UNDEF) 191 return false; 192 unsigned NumElems = N->getNumOperands(); 193 for (unsigned i = 1; i < NumElems; ++i) { 194 SDValue V = N->getOperand(i); 195 if (V.getOpcode() != ISD::UNDEF) 196 return false; 197 } 198 return true; 199} 200 201 202/// isDebugLabel - Return true if the specified node represents a debug 203/// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node). 204bool ISD::isDebugLabel(const SDNode *N) { 205 SDValue Zero; 206 if (N->getOpcode() == ISD::DBG_LABEL) 207 return true; 208 if (N->isMachineOpcode() && 209 N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL) 210 return true; 211 return false; 212} 213 214/// getSetCCSwappedOperands - Return the operation corresponding to (Y op X) 215/// when given the operation for (X op Y). 216ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 217 // To perform this operation, we just need to swap the L and G bits of the 218 // operation. 219 unsigned OldL = (Operation >> 2) & 1; 220 unsigned OldG = (Operation >> 1) & 1; 221 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 222 (OldL << 1) | // New G bit 223 (OldG << 2)); // New L bit. 224} 225 226/// getSetCCInverse - Return the operation corresponding to !(X op Y), where 227/// 'op' is a valid SetCC operation. 228ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) { 229 unsigned Operation = Op; 230 if (isInteger) 231 Operation ^= 7; // Flip L, G, E bits, but not U. 232 else 233 Operation ^= 15; // Flip all of the condition bits. 234 235 if (Operation > ISD::SETTRUE2) 236 Operation &= ~8; // Don't let N and U bits get set. 237 238 return ISD::CondCode(Operation); 239} 240 241 242/// isSignedOp - For an integer comparison, return 1 if the comparison is a 243/// signed operation and 2 if the result is an unsigned comparison. Return zero 244/// if the operation does not depend on the sign of the input (setne and seteq). 245static int isSignedOp(ISD::CondCode Opcode) { 246 switch (Opcode) { 247 default: llvm_unreachable("Illegal integer setcc operation!"); 248 case ISD::SETEQ: 249 case ISD::SETNE: return 0; 250 case ISD::SETLT: 251 case ISD::SETLE: 252 case ISD::SETGT: 253 case ISD::SETGE: return 1; 254 case ISD::SETULT: 255 case ISD::SETULE: 256 case ISD::SETUGT: 257 case ISD::SETUGE: return 2; 258 } 259} 260 261/// getSetCCOrOperation - Return the result of a logical OR between different 262/// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function 263/// returns SETCC_INVALID if it is not possible to represent the resultant 264/// comparison. 265ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 266 bool isInteger) { 267 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 268 // Cannot fold a signed integer setcc with an unsigned integer setcc. 269 return ISD::SETCC_INVALID; 270 271 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 272 273 // If the N and U bits get set then the resultant comparison DOES suddenly 274 // care about orderedness, and is true when ordered. 275 if (Op > ISD::SETTRUE2) 276 Op &= ~16; // Clear the U bit if the N bit is set. 277 278 // Canonicalize illegal integer setcc's. 279 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 280 Op = ISD::SETNE; 281 282 return ISD::CondCode(Op); 283} 284 285/// getSetCCAndOperation - Return the result of a logical AND between different 286/// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This 287/// function returns zero if it is not possible to represent the resultant 288/// comparison. 289ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 290 bool isInteger) { 291 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 292 // Cannot fold a signed setcc with an unsigned setcc. 293 return ISD::SETCC_INVALID; 294 295 // Combine all of the condition bits. 296 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 297 298 // Canonicalize illegal integer setcc's. 299 if (isInteger) { 300 switch (Result) { 301 default: break; 302 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 303 case ISD::SETOEQ: // SETEQ & SETU[LG]E 304 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 305 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 306 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 307 } 308 } 309 310 return Result; 311} 312 313const TargetMachine &SelectionDAG::getTarget() const { 314 return MF->getTarget(); 315} 316 317//===----------------------------------------------------------------------===// 318// SDNode Profile Support 319//===----------------------------------------------------------------------===// 320 321/// AddNodeIDOpcode - Add the node opcode to the NodeID data. 322/// 323static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 324 ID.AddInteger(OpC); 325} 326 327/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 328/// solely with their pointer. 329static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 330 ID.AddPointer(VTList.VTs); 331} 332 333/// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 334/// 335static void AddNodeIDOperands(FoldingSetNodeID &ID, 336 const SDValue *Ops, unsigned NumOps) { 337 for (; NumOps; --NumOps, ++Ops) { 338 ID.AddPointer(Ops->getNode()); 339 ID.AddInteger(Ops->getResNo()); 340 } 341} 342 343/// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 344/// 345static void AddNodeIDOperands(FoldingSetNodeID &ID, 346 const SDUse *Ops, unsigned NumOps) { 347 for (; NumOps; --NumOps, ++Ops) { 348 ID.AddPointer(Ops->getNode()); 349 ID.AddInteger(Ops->getResNo()); 350 } 351} 352 353static void AddNodeIDNode(FoldingSetNodeID &ID, 354 unsigned short OpC, SDVTList VTList, 355 const SDValue *OpList, unsigned N) { 356 AddNodeIDOpcode(ID, OpC); 357 AddNodeIDValueTypes(ID, VTList); 358 AddNodeIDOperands(ID, OpList, N); 359} 360 361/// AddNodeIDCustom - If this is an SDNode with special info, add this info to 362/// the NodeID data. 363static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 364 switch (N->getOpcode()) { 365 case ISD::TargetExternalSymbol: 366 case ISD::ExternalSymbol: 367 llvm_unreachable("Should only be used on nodes with operands"); 368 default: break; // Normal nodes don't need extra info. 369 case ISD::TargetConstant: 370 case ISD::Constant: 371 ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue()); 372 break; 373 case ISD::TargetConstantFP: 374 case ISD::ConstantFP: { 375 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 376 break; 377 } 378 case ISD::TargetGlobalAddress: 379 case ISD::GlobalAddress: 380 case ISD::TargetGlobalTLSAddress: 381 case ISD::GlobalTLSAddress: { 382 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 383 ID.AddPointer(GA->getGlobal()); 384 ID.AddInteger(GA->getOffset()); 385 ID.AddInteger(GA->getTargetFlags()); 386 break; 387 } 388 case ISD::BasicBlock: 389 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 390 break; 391 case ISD::Register: 392 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 393 break; 394 case ISD::DBG_STOPPOINT: { 395 const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N); 396 ID.AddInteger(DSP->getLine()); 397 ID.AddInteger(DSP->getColumn()); 398 ID.AddPointer(DSP->getCompileUnit()); 399 break; 400 } 401 case ISD::SRCVALUE: 402 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 403 break; 404 case ISD::MEMOPERAND: { 405 const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO; 406 MO.Profile(ID); 407 break; 408 } 409 case ISD::FrameIndex: 410 case ISD::TargetFrameIndex: 411 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 412 break; 413 case ISD::JumpTable: 414 case ISD::TargetJumpTable: 415 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 416 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 417 break; 418 case ISD::ConstantPool: 419 case ISD::TargetConstantPool: { 420 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 421 ID.AddInteger(CP->getAlignment()); 422 ID.AddInteger(CP->getOffset()); 423 if (CP->isMachineConstantPoolEntry()) 424 CP->getMachineCPVal()->AddSelectionDAGCSEId(ID); 425 else 426 ID.AddPointer(CP->getConstVal()); 427 ID.AddInteger(CP->getTargetFlags()); 428 break; 429 } 430 case ISD::LOAD: { 431 const LoadSDNode *LD = cast<LoadSDNode>(N); 432 ID.AddInteger(LD->getMemoryVT().getRawBits()); 433 ID.AddInteger(LD->getRawSubclassData()); 434 break; 435 } 436 case ISD::STORE: { 437 const StoreSDNode *ST = cast<StoreSDNode>(N); 438 ID.AddInteger(ST->getMemoryVT().getRawBits()); 439 ID.AddInteger(ST->getRawSubclassData()); 440 break; 441 } 442 case ISD::ATOMIC_CMP_SWAP: 443 case ISD::ATOMIC_SWAP: 444 case ISD::ATOMIC_LOAD_ADD: 445 case ISD::ATOMIC_LOAD_SUB: 446 case ISD::ATOMIC_LOAD_AND: 447 case ISD::ATOMIC_LOAD_OR: 448 case ISD::ATOMIC_LOAD_XOR: 449 case ISD::ATOMIC_LOAD_NAND: 450 case ISD::ATOMIC_LOAD_MIN: 451 case ISD::ATOMIC_LOAD_MAX: 452 case ISD::ATOMIC_LOAD_UMIN: 453 case ISD::ATOMIC_LOAD_UMAX: { 454 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 455 ID.AddInteger(AT->getMemoryVT().getRawBits()); 456 ID.AddInteger(AT->getRawSubclassData()); 457 break; 458 } 459 case ISD::VECTOR_SHUFFLE: { 460 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 461 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 462 i != e; ++i) 463 ID.AddInteger(SVN->getMaskElt(i)); 464 break; 465 } 466 } // end switch (N->getOpcode()) 467} 468 469/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 470/// data. 471static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 472 AddNodeIDOpcode(ID, N->getOpcode()); 473 // Add the return value info. 474 AddNodeIDValueTypes(ID, N->getVTList()); 475 // Add the operand info. 476 AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands()); 477 478 // Handle SDNode leafs with special info. 479 AddNodeIDCustom(ID, N); 480} 481 482/// encodeMemSDNodeFlags - Generic routine for computing a value for use in 483/// the CSE map that carries alignment, volatility, indexing mode, and 484/// extension/truncation information. 485/// 486static inline unsigned 487encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, 488 bool isVolatile, unsigned Alignment) { 489 assert((ConvType & 3) == ConvType && 490 "ConvType may not require more than 2 bits!"); 491 assert((AM & 7) == AM && 492 "AM may not require more than 3 bits!"); 493 return ConvType | 494 (AM << 2) | 495 (isVolatile << 5) | 496 ((Log2_32(Alignment) + 1) << 6); 497} 498 499//===----------------------------------------------------------------------===// 500// SelectionDAG Class 501//===----------------------------------------------------------------------===// 502 503/// doNotCSE - Return true if CSE should not be performed for this node. 504static bool doNotCSE(SDNode *N) { 505 if (N->getValueType(0) == MVT::Flag) 506 return true; // Never CSE anything that produces a flag. 507 508 switch (N->getOpcode()) { 509 default: break; 510 case ISD::HANDLENODE: 511 case ISD::DBG_LABEL: 512 case ISD::DBG_STOPPOINT: 513 case ISD::EH_LABEL: 514 case ISD::DECLARE: 515 return true; // Never CSE these nodes. 516 } 517 518 // Check that remaining values produced are not flags. 519 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 520 if (N->getValueType(i) == MVT::Flag) 521 return true; // Never CSE anything that produces a flag. 522 523 return false; 524} 525 526/// RemoveDeadNodes - This method deletes all unreachable nodes in the 527/// SelectionDAG. 528void SelectionDAG::RemoveDeadNodes() { 529 // Create a dummy node (which is not added to allnodes), that adds a reference 530 // to the root node, preventing it from being deleted. 531 HandleSDNode Dummy(getRoot()); 532 533 SmallVector<SDNode*, 128> DeadNodes; 534 535 // Add all obviously-dead nodes to the DeadNodes worklist. 536 for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I) 537 if (I->use_empty()) 538 DeadNodes.push_back(I); 539 540 RemoveDeadNodes(DeadNodes); 541 542 // If the root changed (e.g. it was a dead load, update the root). 543 setRoot(Dummy.getValue()); 544} 545 546/// RemoveDeadNodes - This method deletes the unreachable nodes in the 547/// given list, and any nodes that become unreachable as a result. 548void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes, 549 DAGUpdateListener *UpdateListener) { 550 551 // Process the worklist, deleting the nodes and adding their uses to the 552 // worklist. 553 while (!DeadNodes.empty()) { 554 SDNode *N = DeadNodes.pop_back_val(); 555 556 if (UpdateListener) 557 UpdateListener->NodeDeleted(N, 0); 558 559 // Take the node out of the appropriate CSE map. 560 RemoveNodeFromCSEMaps(N); 561 562 // Next, brutally remove the operand list. This is safe to do, as there are 563 // no cycles in the graph. 564 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 565 SDUse &Use = *I++; 566 SDNode *Operand = Use.getNode(); 567 Use.set(SDValue()); 568 569 // Now that we removed this operand, see if there are no uses of it left. 570 if (Operand->use_empty()) 571 DeadNodes.push_back(Operand); 572 } 573 574 DeallocateNode(N); 575 } 576} 577 578void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){ 579 SmallVector<SDNode*, 16> DeadNodes(1, N); 580 RemoveDeadNodes(DeadNodes, UpdateListener); 581} 582 583void SelectionDAG::DeleteNode(SDNode *N) { 584 // First take this out of the appropriate CSE map. 585 RemoveNodeFromCSEMaps(N); 586 587 // Finally, remove uses due to operands of this node, remove from the 588 // AllNodes list, and delete the node. 589 DeleteNodeNotInCSEMaps(N); 590} 591 592void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 593 assert(N != AllNodes.begin() && "Cannot delete the entry node!"); 594 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 595 596 // Drop all of the operands and decrement used node's use counts. 597 N->DropOperands(); 598 599 DeallocateNode(N); 600} 601 602void SelectionDAG::DeallocateNode(SDNode *N) { 603 if (N->OperandsNeedDelete) 604 delete[] N->OperandList; 605 606 // Set the opcode to DELETED_NODE to help catch bugs when node 607 // memory is reallocated. 608 N->NodeType = ISD::DELETED_NODE; 609 610 NodeAllocator.Deallocate(AllNodes.remove(N)); 611} 612 613/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 614/// correspond to it. This is useful when we're about to delete or repurpose 615/// the node. We don't want future request for structurally identical nodes 616/// to return N anymore. 617bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 618 bool Erased = false; 619 switch (N->getOpcode()) { 620 case ISD::EntryToken: 621 llvm_unreachable("EntryToken should not be in CSEMaps!"); 622 return false; 623 case ISD::HANDLENODE: return false; // noop. 624 case ISD::CONDCODE: 625 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 626 "Cond code doesn't exist!"); 627 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0; 628 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0; 629 break; 630 case ISD::ExternalSymbol: 631 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 632 break; 633 case ISD::TargetExternalSymbol: { 634 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 635 Erased = TargetExternalSymbols.erase( 636 std::pair<std::string,unsigned char>(ESN->getSymbol(), 637 ESN->getTargetFlags())); 638 break; 639 } 640 case ISD::VALUETYPE: { 641 MVT VT = cast<VTSDNode>(N)->getVT(); 642 if (VT.isExtended()) { 643 Erased = ExtendedValueTypeNodes.erase(VT); 644 } else { 645 Erased = ValueTypeNodes[VT.getSimpleVT()] != 0; 646 ValueTypeNodes[VT.getSimpleVT()] = 0; 647 } 648 break; 649 } 650 default: 651 // Remove it from the CSE Map. 652 Erased = CSEMap.RemoveNode(N); 653 break; 654 } 655#ifndef NDEBUG 656 // Verify that the node was actually in one of the CSE maps, unless it has a 657 // flag result (which cannot be CSE'd) or is one of the special cases that are 658 // not subject to CSE. 659 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag && 660 !N->isMachineOpcode() && !doNotCSE(N)) { 661 N->dump(this); 662 cerr << "\n"; 663 llvm_unreachable("Node is not in map!"); 664 } 665#endif 666 return Erased; 667} 668 669/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 670/// maps and modified in place. Add it back to the CSE maps, unless an identical 671/// node already exists, in which case transfer all its users to the existing 672/// node. This transfer can potentially trigger recursive merging. 673/// 674void 675SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N, 676 DAGUpdateListener *UpdateListener) { 677 // For node types that aren't CSE'd, just act as if no identical node 678 // already exists. 679 if (!doNotCSE(N)) { 680 SDNode *Existing = CSEMap.GetOrInsertNode(N); 681 if (Existing != N) { 682 // If there was already an existing matching node, use ReplaceAllUsesWith 683 // to replace the dead one with the existing one. This can cause 684 // recursive merging of other unrelated nodes down the line. 685 ReplaceAllUsesWith(N, Existing, UpdateListener); 686 687 // N is now dead. Inform the listener if it exists and delete it. 688 if (UpdateListener) 689 UpdateListener->NodeDeleted(N, Existing); 690 DeleteNodeNotInCSEMaps(N); 691 return; 692 } 693 } 694 695 // If the node doesn't already exist, we updated it. Inform a listener if 696 // it exists. 697 if (UpdateListener) 698 UpdateListener->NodeUpdated(N); 699} 700 701/// FindModifiedNodeSlot - Find a slot for the specified node if its operands 702/// were replaced with those specified. If this node is never memoized, 703/// return null, otherwise return a pointer to the slot it would take. If a 704/// node already exists with these operands, the slot will be non-null. 705SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 706 void *&InsertPos) { 707 if (doNotCSE(N)) 708 return 0; 709 710 SDValue Ops[] = { Op }; 711 FoldingSetNodeID ID; 712 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1); 713 AddNodeIDCustom(ID, N); 714 return CSEMap.FindNodeOrInsertPos(ID, InsertPos); 715} 716 717/// FindModifiedNodeSlot - Find a slot for the specified node if its operands 718/// were replaced with those specified. If this node is never memoized, 719/// return null, otherwise return a pointer to the slot it would take. If a 720/// node already exists with these operands, the slot will be non-null. 721SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 722 SDValue Op1, SDValue Op2, 723 void *&InsertPos) { 724 if (doNotCSE(N)) 725 return 0; 726 727 SDValue Ops[] = { Op1, Op2 }; 728 FoldingSetNodeID ID; 729 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2); 730 AddNodeIDCustom(ID, N); 731 return CSEMap.FindNodeOrInsertPos(ID, InsertPos); 732} 733 734 735/// FindModifiedNodeSlot - Find a slot for the specified node if its operands 736/// were replaced with those specified. If this node is never memoized, 737/// return null, otherwise return a pointer to the slot it would take. If a 738/// node already exists with these operands, the slot will be non-null. 739SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 740 const SDValue *Ops,unsigned NumOps, 741 void *&InsertPos) { 742 if (doNotCSE(N)) 743 return 0; 744 745 FoldingSetNodeID ID; 746 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps); 747 AddNodeIDCustom(ID, N); 748 return CSEMap.FindNodeOrInsertPos(ID, InsertPos); 749} 750 751/// VerifyNode - Sanity check the given node. Aborts if it is invalid. 752void SelectionDAG::VerifyNode(SDNode *N) { 753 switch (N->getOpcode()) { 754 default: 755 break; 756 case ISD::BUILD_PAIR: { 757 MVT VT = N->getValueType(0); 758 assert(N->getNumValues() == 1 && "Too many results!"); 759 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 760 "Wrong return type!"); 761 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 762 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 763 "Mismatched operand types!"); 764 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 765 "Wrong operand type!"); 766 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 767 "Wrong return type size"); 768 break; 769 } 770 case ISD::BUILD_VECTOR: { 771 assert(N->getNumValues() == 1 && "Too many results!"); 772 assert(N->getValueType(0).isVector() && "Wrong return type!"); 773 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 774 "Wrong number of operands!"); 775 MVT EltVT = N->getValueType(0).getVectorElementType(); 776 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) 777 assert((I->getValueType() == EltVT || 778 (EltVT.isInteger() && I->getValueType().isInteger() && 779 EltVT.bitsLE(I->getValueType()))) && 780 "Wrong operand type!"); 781 break; 782 } 783 } 784} 785 786/// getMVTAlignment - Compute the default alignment value for the 787/// given type. 788/// 789unsigned SelectionDAG::getMVTAlignment(MVT VT) const { 790 const Type *Ty = VT == MVT::iPTR ? 791 PointerType::get(Type::Int8Ty, 0) : 792 VT.getTypeForMVT(); 793 794 return TLI.getTargetData()->getABITypeAlignment(Ty); 795} 796 797// EntryNode could meaningfully have debug info if we can find it... 798SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli) 799 : TLI(tli), FLI(fli), DW(0), 800 EntryNode(ISD::EntryToken, DebugLoc::getUnknownLoc(), 801 getVTList(MVT::Other)), Root(getEntryNode()) { 802 AllNodes.push_back(&EntryNode); 803} 804 805void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi, 806 DwarfWriter *dw) { 807 MF = &mf; 808 MMI = mmi; 809 DW = dw; 810 Context = &mf.getFunction()->getContext(); 811} 812 813SelectionDAG::~SelectionDAG() { 814 allnodes_clear(); 815} 816 817void SelectionDAG::allnodes_clear() { 818 assert(&*AllNodes.begin() == &EntryNode); 819 AllNodes.remove(AllNodes.begin()); 820 while (!AllNodes.empty()) 821 DeallocateNode(AllNodes.begin()); 822} 823 824void SelectionDAG::clear() { 825 allnodes_clear(); 826 OperandAllocator.Reset(); 827 CSEMap.clear(); 828 829 ExtendedValueTypeNodes.clear(); 830 ExternalSymbols.clear(); 831 TargetExternalSymbols.clear(); 832 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 833 static_cast<CondCodeSDNode*>(0)); 834 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 835 static_cast<SDNode*>(0)); 836 837 EntryNode.UseList = 0; 838 AllNodes.push_back(&EntryNode); 839 Root = getEntryNode(); 840} 841 842SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, MVT VT) { 843 if (Op.getValueType() == VT) return Op; 844 APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(), 845 VT.getSizeInBits()); 846 return getNode(ISD::AND, DL, Op.getValueType(), Op, 847 getConstant(Imm, Op.getValueType())); 848} 849 850/// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 851/// 852SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, MVT VT) { 853 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 854 SDValue NegOne = 855 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT); 856 return getNode(ISD::XOR, DL, VT, Val, NegOne); 857} 858 859SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) { 860 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 861 assert((EltVT.getSizeInBits() >= 64 || 862 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 863 "getConstant with a uint64_t value that doesn't fit in the type!"); 864 return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT); 865} 866 867SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) { 868 return getConstant(*ConstantInt::get(*Context, Val), VT, isT); 869} 870 871SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) { 872 assert(VT.isInteger() && "Cannot create FP integer constant!"); 873 874 MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT; 875 assert(Val.getBitWidth() == EltVT.getSizeInBits() && 876 "APInt size does not match type size!"); 877 878 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 879 FoldingSetNodeID ID; 880 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0); 881 ID.AddPointer(&Val); 882 void *IP = 0; 883 SDNode *N = NULL; 884 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP))) 885 if (!VT.isVector()) 886 return SDValue(N, 0); 887 if (!N) { 888 N = NodeAllocator.Allocate<ConstantSDNode>(); 889 new (N) ConstantSDNode(isT, &Val, EltVT); 890 CSEMap.InsertNode(N, IP); 891 AllNodes.push_back(N); 892 } 893 894 SDValue Result(N, 0); 895 if (VT.isVector()) { 896 SmallVector<SDValue, 8> Ops; 897 Ops.assign(VT.getVectorNumElements(), Result); 898 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(), 899 VT, &Ops[0], Ops.size()); 900 } 901 return Result; 902} 903 904SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) { 905 return getConstant(Val, TLI.getPointerTy(), isTarget); 906} 907 908 909SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) { 910 return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget); 911} 912 913SDValue SelectionDAG::getConstantFP(const ConstantFP& V, MVT VT, bool isTarget){ 914 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 915 916 MVT EltVT = 917 VT.isVector() ? VT.getVectorElementType() : VT; 918 919 // Do the map lookup using the actual bit pattern for the floating point 920 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 921 // we don't have issues with SNANs. 922 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 923 FoldingSetNodeID ID; 924 AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0); 925 ID.AddPointer(&V); 926 void *IP = 0; 927 SDNode *N = NULL; 928 if ((N = CSEMap.FindNodeOrInsertPos(ID, IP))) 929 if (!VT.isVector()) 930 return SDValue(N, 0); 931 if (!N) { 932 N = NodeAllocator.Allocate<ConstantFPSDNode>(); 933 new (N) ConstantFPSDNode(isTarget, &V, EltVT); 934 CSEMap.InsertNode(N, IP); 935 AllNodes.push_back(N); 936 } 937 938 SDValue Result(N, 0); 939 if (VT.isVector()) { 940 SmallVector<SDValue, 8> Ops; 941 Ops.assign(VT.getVectorNumElements(), Result); 942 // FIXME DebugLoc info might be appropriate here 943 Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(), 944 VT, &Ops[0], Ops.size()); 945 } 946 return Result; 947} 948 949SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) { 950 MVT EltVT = 951 VT.isVector() ? VT.getVectorElementType() : VT; 952 if (EltVT==MVT::f32) 953 return getConstantFP(APFloat((float)Val), VT, isTarget); 954 else 955 return getConstantFP(APFloat(Val), VT, isTarget); 956} 957 958SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, 959 MVT VT, int64_t Offset, 960 bool isTargetGA, 961 unsigned char TargetFlags) { 962 assert((TargetFlags == 0 || isTargetGA) && 963 "Cannot set target flags on target-independent globals"); 964 965 // Truncate (with sign-extension) the offset value to the pointer size. 966 unsigned BitWidth = TLI.getPointerTy().getSizeInBits(); 967 if (BitWidth < 64) 968 Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth)); 969 970 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV); 971 if (!GVar) { 972 // If GV is an alias then use the aliasee for determining thread-localness. 973 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV)) 974 GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false)); 975 } 976 977 unsigned Opc; 978 if (GVar && GVar->isThreadLocal()) 979 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 980 else 981 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 982 983 FoldingSetNodeID ID; 984 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 985 ID.AddPointer(GV); 986 ID.AddInteger(Offset); 987 ID.AddInteger(TargetFlags); 988 void *IP = 0; 989 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 990 return SDValue(E, 0); 991 SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>(); 992 new (N) GlobalAddressSDNode(Opc, GV, VT, Offset, TargetFlags); 993 CSEMap.InsertNode(N, IP); 994 AllNodes.push_back(N); 995 return SDValue(N, 0); 996} 997 998SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) { 999 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1000 FoldingSetNodeID ID; 1001 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 1002 ID.AddInteger(FI); 1003 void *IP = 0; 1004 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1005 return SDValue(E, 0); 1006 SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>(); 1007 new (N) FrameIndexSDNode(FI, VT, isTarget); 1008 CSEMap.InsertNode(N, IP); 1009 AllNodes.push_back(N); 1010 return SDValue(N, 0); 1011} 1012 1013SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget, 1014 unsigned char TargetFlags) { 1015 assert((TargetFlags == 0 || isTarget) && 1016 "Cannot set target flags on target-independent jump tables"); 1017 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1018 FoldingSetNodeID ID; 1019 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 1020 ID.AddInteger(JTI); 1021 ID.AddInteger(TargetFlags); 1022 void *IP = 0; 1023 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1024 return SDValue(E, 0); 1025 SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>(); 1026 new (N) JumpTableSDNode(JTI, VT, isTarget, TargetFlags); 1027 CSEMap.InsertNode(N, IP); 1028 AllNodes.push_back(N); 1029 return SDValue(N, 0); 1030} 1031 1032SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT, 1033 unsigned Alignment, int Offset, 1034 bool isTarget, 1035 unsigned char TargetFlags) { 1036 assert((TargetFlags == 0 || isTarget) && 1037 "Cannot set target flags on target-independent globals"); 1038 if (Alignment == 0) 1039 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType()); 1040 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1041 FoldingSetNodeID ID; 1042 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 1043 ID.AddInteger(Alignment); 1044 ID.AddInteger(Offset); 1045 ID.AddPointer(C); 1046 ID.AddInteger(TargetFlags); 1047 void *IP = 0; 1048 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1049 return SDValue(E, 0); 1050 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>(); 1051 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags); 1052 CSEMap.InsertNode(N, IP); 1053 AllNodes.push_back(N); 1054 return SDValue(N, 0); 1055} 1056 1057 1058SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT, 1059 unsigned Alignment, int Offset, 1060 bool isTarget, 1061 unsigned char TargetFlags) { 1062 assert((TargetFlags == 0 || isTarget) && 1063 "Cannot set target flags on target-independent globals"); 1064 if (Alignment == 0) 1065 Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType()); 1066 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1067 FoldingSetNodeID ID; 1068 AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0); 1069 ID.AddInteger(Alignment); 1070 ID.AddInteger(Offset); 1071 C->AddSelectionDAGCSEId(ID); 1072 ID.AddInteger(TargetFlags); 1073 void *IP = 0; 1074 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1075 return SDValue(E, 0); 1076 SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>(); 1077 new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags); 1078 CSEMap.InsertNode(N, IP); 1079 AllNodes.push_back(N); 1080 return SDValue(N, 0); 1081} 1082 1083SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1084 FoldingSetNodeID ID; 1085 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0); 1086 ID.AddPointer(MBB); 1087 void *IP = 0; 1088 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1089 return SDValue(E, 0); 1090 SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>(); 1091 new (N) BasicBlockSDNode(MBB); 1092 CSEMap.InsertNode(N, IP); 1093 AllNodes.push_back(N); 1094 return SDValue(N, 0); 1095} 1096 1097SDValue SelectionDAG::getValueType(MVT VT) { 1098 if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size()) 1099 ValueTypeNodes.resize(VT.getSimpleVT()+1); 1100 1101 SDNode *&N = VT.isExtended() ? 1102 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()]; 1103 1104 if (N) return SDValue(N, 0); 1105 N = NodeAllocator.Allocate<VTSDNode>(); 1106 new (N) VTSDNode(VT); 1107 AllNodes.push_back(N); 1108 return SDValue(N, 0); 1109} 1110 1111SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) { 1112 SDNode *&N = ExternalSymbols[Sym]; 1113 if (N) return SDValue(N, 0); 1114 N = NodeAllocator.Allocate<ExternalSymbolSDNode>(); 1115 new (N) ExternalSymbolSDNode(false, Sym, 0, VT); 1116 AllNodes.push_back(N); 1117 return SDValue(N, 0); 1118} 1119 1120SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT, 1121 unsigned char TargetFlags) { 1122 SDNode *&N = 1123 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym, 1124 TargetFlags)]; 1125 if (N) return SDValue(N, 0); 1126 N = NodeAllocator.Allocate<ExternalSymbolSDNode>(); 1127 new (N) ExternalSymbolSDNode(true, Sym, TargetFlags, VT); 1128 AllNodes.push_back(N); 1129 return SDValue(N, 0); 1130} 1131 1132SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1133 if ((unsigned)Cond >= CondCodeNodes.size()) 1134 CondCodeNodes.resize(Cond+1); 1135 1136 if (CondCodeNodes[Cond] == 0) { 1137 CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>(); 1138 new (N) CondCodeSDNode(Cond); 1139 CondCodeNodes[Cond] = N; 1140 AllNodes.push_back(N); 1141 } 1142 return SDValue(CondCodeNodes[Cond], 0); 1143} 1144 1145// commuteShuffle - swaps the values of N1 and N2, and swaps all indices in 1146// the shuffle mask M that point at N1 to point at N2, and indices that point 1147// N2 to point at N1. 1148static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) { 1149 std::swap(N1, N2); 1150 int NElts = M.size(); 1151 for (int i = 0; i != NElts; ++i) { 1152 if (M[i] >= NElts) 1153 M[i] -= NElts; 1154 else if (M[i] >= 0) 1155 M[i] += NElts; 1156 } 1157} 1158 1159SDValue SelectionDAG::getVectorShuffle(MVT VT, DebugLoc dl, SDValue N1, 1160 SDValue N2, const int *Mask) { 1161 assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE"); 1162 assert(VT.isVector() && N1.getValueType().isVector() && 1163 "Vector Shuffle VTs must be a vectors"); 1164 assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType() 1165 && "Vector Shuffle VTs must have same element type"); 1166 1167 // Canonicalize shuffle undef, undef -> undef 1168 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF) 1169 return getUNDEF(VT); 1170 1171 // Validate that all indices in Mask are within the range of the elements 1172 // input to the shuffle. 1173 unsigned NElts = VT.getVectorNumElements(); 1174 SmallVector<int, 8> MaskVec; 1175 for (unsigned i = 0; i != NElts; ++i) { 1176 assert(Mask[i] < (int)(NElts * 2) && "Index out of range"); 1177 MaskVec.push_back(Mask[i]); 1178 } 1179 1180 // Canonicalize shuffle v, v -> v, undef 1181 if (N1 == N2) { 1182 N2 = getUNDEF(VT); 1183 for (unsigned i = 0; i != NElts; ++i) 1184 if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts; 1185 } 1186 1187 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1188 if (N1.getOpcode() == ISD::UNDEF) 1189 commuteShuffle(N1, N2, MaskVec); 1190 1191 // Canonicalize all index into lhs, -> shuffle lhs, undef 1192 // Canonicalize all index into rhs, -> shuffle rhs, undef 1193 bool AllLHS = true, AllRHS = true; 1194 bool N2Undef = N2.getOpcode() == ISD::UNDEF; 1195 for (unsigned i = 0; i != NElts; ++i) { 1196 if (MaskVec[i] >= (int)NElts) { 1197 if (N2Undef) 1198 MaskVec[i] = -1; 1199 else 1200 AllLHS = false; 1201 } else if (MaskVec[i] >= 0) { 1202 AllRHS = false; 1203 } 1204 } 1205 if (AllLHS && AllRHS) 1206 return getUNDEF(VT); 1207 if (AllLHS && !N2Undef) 1208 N2 = getUNDEF(VT); 1209 if (AllRHS) { 1210 N1 = getUNDEF(VT); 1211 commuteShuffle(N1, N2, MaskVec); 1212 } 1213 1214 // If Identity shuffle, or all shuffle in to undef, return that node. 1215 bool AllUndef = true; 1216 bool Identity = true; 1217 for (unsigned i = 0; i != NElts; ++i) { 1218 if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false; 1219 if (MaskVec[i] >= 0) AllUndef = false; 1220 } 1221 if (Identity && NElts == N1.getValueType().getVectorNumElements()) 1222 return N1; 1223 if (AllUndef) 1224 return getUNDEF(VT); 1225 1226 FoldingSetNodeID ID; 1227 SDValue Ops[2] = { N1, N2 }; 1228 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2); 1229 for (unsigned i = 0; i != NElts; ++i) 1230 ID.AddInteger(MaskVec[i]); 1231 1232 void* IP = 0; 1233 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1234 return SDValue(E, 0); 1235 1236 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1237 // SDNode doesn't have access to it. This memory will be "leaked" when 1238 // the node is deallocated, but recovered when the NodeAllocator is released. 1239 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1240 memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int)); 1241 1242 ShuffleVectorSDNode *N = NodeAllocator.Allocate<ShuffleVectorSDNode>(); 1243 new (N) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc); 1244 CSEMap.InsertNode(N, IP); 1245 AllNodes.push_back(N); 1246 return SDValue(N, 0); 1247} 1248 1249SDValue SelectionDAG::getConvertRndSat(MVT VT, DebugLoc dl, 1250 SDValue Val, SDValue DTy, 1251 SDValue STy, SDValue Rnd, SDValue Sat, 1252 ISD::CvtCode Code) { 1253 // If the src and dest types are the same and the conversion is between 1254 // integer types of the same sign or two floats, no conversion is necessary. 1255 if (DTy == STy && 1256 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF)) 1257 return Val; 1258 1259 FoldingSetNodeID ID; 1260 void* IP = 0; 1261 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1262 return SDValue(E, 0); 1263 CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>(); 1264 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat }; 1265 new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code); 1266 CSEMap.InsertNode(N, IP); 1267 AllNodes.push_back(N); 1268 return SDValue(N, 0); 1269} 1270 1271SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) { 1272 FoldingSetNodeID ID; 1273 AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0); 1274 ID.AddInteger(RegNo); 1275 void *IP = 0; 1276 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1277 return SDValue(E, 0); 1278 SDNode *N = NodeAllocator.Allocate<RegisterSDNode>(); 1279 new (N) RegisterSDNode(RegNo, VT); 1280 CSEMap.InsertNode(N, IP); 1281 AllNodes.push_back(N); 1282 return SDValue(N, 0); 1283} 1284 1285SDValue SelectionDAG::getDbgStopPoint(DebugLoc DL, SDValue Root, 1286 unsigned Line, unsigned Col, 1287 Value *CU) { 1288 SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>(); 1289 new (N) DbgStopPointSDNode(Root, Line, Col, CU); 1290 N->setDebugLoc(DL); 1291 AllNodes.push_back(N); 1292 return SDValue(N, 0); 1293} 1294 1295SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl, 1296 SDValue Root, 1297 unsigned LabelID) { 1298 FoldingSetNodeID ID; 1299 SDValue Ops[] = { Root }; 1300 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1); 1301 ID.AddInteger(LabelID); 1302 void *IP = 0; 1303 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1304 return SDValue(E, 0); 1305 SDNode *N = NodeAllocator.Allocate<LabelSDNode>(); 1306 new (N) LabelSDNode(Opcode, dl, Root, LabelID); 1307 CSEMap.InsertNode(N, IP); 1308 AllNodes.push_back(N); 1309 return SDValue(N, 0); 1310} 1311 1312SDValue SelectionDAG::getSrcValue(const Value *V) { 1313 assert((!V || isa<PointerType>(V->getType())) && 1314 "SrcValue is not a pointer?"); 1315 1316 FoldingSetNodeID ID; 1317 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0); 1318 ID.AddPointer(V); 1319 1320 void *IP = 0; 1321 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1322 return SDValue(E, 0); 1323 1324 SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>(); 1325 new (N) SrcValueSDNode(V); 1326 CSEMap.InsertNode(N, IP); 1327 AllNodes.push_back(N); 1328 return SDValue(N, 0); 1329} 1330 1331SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) { 1332#ifndef NDEBUG 1333 const Value *v = MO.getValue(); 1334 assert((!v || isa<PointerType>(v->getType())) && 1335 "SrcValue is not a pointer?"); 1336#endif 1337 1338 FoldingSetNodeID ID; 1339 AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0); 1340 MO.Profile(ID); 1341 1342 void *IP = 0; 1343 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 1344 return SDValue(E, 0); 1345 1346 SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>(); 1347 new (N) MemOperandSDNode(MO); 1348 CSEMap.InsertNode(N, IP); 1349 AllNodes.push_back(N); 1350 return SDValue(N, 0); 1351} 1352 1353/// getShiftAmountOperand - Return the specified value casted to 1354/// the target's desired shift amount type. 1355SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) { 1356 MVT OpTy = Op.getValueType(); 1357 MVT ShTy = TLI.getShiftAmountTy(); 1358 if (OpTy == ShTy || OpTy.isVector()) return Op; 1359 1360 ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND; 1361 return getNode(Opcode, Op.getDebugLoc(), ShTy, Op); 1362} 1363 1364/// CreateStackTemporary - Create a stack temporary, suitable for holding the 1365/// specified value type. 1366SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) { 1367 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo(); 1368 unsigned ByteSize = VT.getStoreSizeInBits()/8; 1369 const Type *Ty = VT.getTypeForMVT(); 1370 unsigned StackAlign = 1371 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign); 1372 1373 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign); 1374 return getFrameIndex(FrameIdx, TLI.getPointerTy()); 1375} 1376 1377/// CreateStackTemporary - Create a stack temporary suitable for holding 1378/// either of the specified value types. 1379SDValue SelectionDAG::CreateStackTemporary(MVT VT1, MVT VT2) { 1380 unsigned Bytes = std::max(VT1.getStoreSizeInBits(), 1381 VT2.getStoreSizeInBits())/8; 1382 const Type *Ty1 = VT1.getTypeForMVT(); 1383 const Type *Ty2 = VT2.getTypeForMVT(); 1384 const TargetData *TD = TLI.getTargetData(); 1385 unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1), 1386 TD->getPrefTypeAlignment(Ty2)); 1387 1388 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo(); 1389 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align); 1390 return getFrameIndex(FrameIdx, TLI.getPointerTy()); 1391} 1392 1393SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1, 1394 SDValue N2, ISD::CondCode Cond, DebugLoc dl) { 1395 // These setcc operations always fold. 1396 switch (Cond) { 1397 default: break; 1398 case ISD::SETFALSE: 1399 case ISD::SETFALSE2: return getConstant(0, VT); 1400 case ISD::SETTRUE: 1401 case ISD::SETTRUE2: return getConstant(1, VT); 1402 1403 case ISD::SETOEQ: 1404 case ISD::SETOGT: 1405 case ISD::SETOGE: 1406 case ISD::SETOLT: 1407 case ISD::SETOLE: 1408 case ISD::SETONE: 1409 case ISD::SETO: 1410 case ISD::SETUO: 1411 case ISD::SETUEQ: 1412 case ISD::SETUNE: 1413 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!"); 1414 break; 1415 } 1416 1417 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) { 1418 const APInt &C2 = N2C->getAPIntValue(); 1419 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 1420 const APInt &C1 = N1C->getAPIntValue(); 1421 1422 switch (Cond) { 1423 default: llvm_unreachable("Unknown integer setcc!"); 1424 case ISD::SETEQ: return getConstant(C1 == C2, VT); 1425 case ISD::SETNE: return getConstant(C1 != C2, VT); 1426 case ISD::SETULT: return getConstant(C1.ult(C2), VT); 1427 case ISD::SETUGT: return getConstant(C1.ugt(C2), VT); 1428 case ISD::SETULE: return getConstant(C1.ule(C2), VT); 1429 case ISD::SETUGE: return getConstant(C1.uge(C2), VT); 1430 case ISD::SETLT: return getConstant(C1.slt(C2), VT); 1431 case ISD::SETGT: return getConstant(C1.sgt(C2), VT); 1432 case ISD::SETLE: return getConstant(C1.sle(C2), VT); 1433 case ISD::SETGE: return getConstant(C1.sge(C2), VT); 1434 } 1435 } 1436 } 1437 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) { 1438 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) { 1439 // No compile time operations on this type yet. 1440 if (N1C->getValueType(0) == MVT::ppcf128) 1441 return SDValue(); 1442 1443 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF()); 1444 switch (Cond) { 1445 default: break; 1446 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 1447 return getUNDEF(VT); 1448 // fall through 1449 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT); 1450 case ISD::SETNE: if (R==APFloat::cmpUnordered) 1451 return getUNDEF(VT); 1452 // fall through 1453 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan || 1454 R==APFloat::cmpLessThan, VT); 1455 case ISD::SETLT: if (R==APFloat::cmpUnordered) 1456 return getUNDEF(VT); 1457 // fall through 1458 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT); 1459 case ISD::SETGT: if (R==APFloat::cmpUnordered) 1460 return getUNDEF(VT); 1461 // fall through 1462 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT); 1463 case ISD::SETLE: if (R==APFloat::cmpUnordered) 1464 return getUNDEF(VT); 1465 // fall through 1466 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan || 1467 R==APFloat::cmpEqual, VT); 1468 case ISD::SETGE: if (R==APFloat::cmpUnordered) 1469 return getUNDEF(VT); 1470 // fall through 1471 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan || 1472 R==APFloat::cmpEqual, VT); 1473 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT); 1474 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT); 1475 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered || 1476 R==APFloat::cmpEqual, VT); 1477 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT); 1478 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered || 1479 R==APFloat::cmpLessThan, VT); 1480 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan || 1481 R==APFloat::cmpUnordered, VT); 1482 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT); 1483 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT); 1484 } 1485 } else { 1486 // Ensure that the constant occurs on the RHS. 1487 return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond)); 1488 } 1489 } 1490 1491 // Could not fold it. 1492 return SDValue(); 1493} 1494 1495/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 1496/// use this predicate to simplify operations downstream. 1497bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 1498 // This predicate is not safe for vector operations. 1499 if (Op.getValueType().isVector()) 1500 return false; 1501 1502 unsigned BitWidth = Op.getValueSizeInBits(); 1503 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth); 1504} 1505 1506/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 1507/// this predicate to simplify operations downstream. Mask is known to be zero 1508/// for bits that V cannot have. 1509bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask, 1510 unsigned Depth) const { 1511 APInt KnownZero, KnownOne; 1512 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth); 1513 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1514 return (KnownZero & Mask) == Mask; 1515} 1516 1517/// ComputeMaskedBits - Determine which of the bits specified in Mask are 1518/// known to be either zero or one and return them in the KnownZero/KnownOne 1519/// bitsets. This code only analyzes bits in Mask, in order to short-circuit 1520/// processing. 1521void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask, 1522 APInt &KnownZero, APInt &KnownOne, 1523 unsigned Depth) const { 1524 unsigned BitWidth = Mask.getBitWidth(); 1525 assert(BitWidth == Op.getValueType().getSizeInBits() && 1526 "Mask size mismatches value type size!"); 1527 1528 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything. 1529 if (Depth == 6 || Mask == 0) 1530 return; // Limit search depth. 1531 1532 APInt KnownZero2, KnownOne2; 1533 1534 switch (Op.getOpcode()) { 1535 case ISD::Constant: 1536 // We know all of the bits for a constant! 1537 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask; 1538 KnownZero = ~KnownOne & Mask; 1539 return; 1540 case ISD::AND: 1541 // If either the LHS or the RHS are Zero, the result is zero. 1542 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1); 1543 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero, 1544 KnownZero2, KnownOne2, Depth+1); 1545 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1546 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1547 1548 // Output known-1 bits are only known if set in both the LHS & RHS. 1549 KnownOne &= KnownOne2; 1550 // Output known-0 are known to be clear if zero in either the LHS | RHS. 1551 KnownZero |= KnownZero2; 1552 return; 1553 case ISD::OR: 1554 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1); 1555 ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne, 1556 KnownZero2, KnownOne2, Depth+1); 1557 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1558 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1559 1560 // Output known-0 bits are only known if clear in both the LHS & RHS. 1561 KnownZero &= KnownZero2; 1562 // Output known-1 are known to be set if set in either the LHS | RHS. 1563 KnownOne |= KnownOne2; 1564 return; 1565 case ISD::XOR: { 1566 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1); 1567 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1); 1568 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1569 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1570 1571 // Output known-0 bits are known if clear or set in both the LHS & RHS. 1572 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 1573 // Output known-1 are known to be set if set in only one of the LHS, RHS. 1574 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 1575 KnownZero = KnownZeroOut; 1576 return; 1577 } 1578 case ISD::MUL: { 1579 APInt Mask2 = APInt::getAllOnesValue(BitWidth); 1580 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1); 1581 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1); 1582 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1583 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1584 1585 // If low bits are zero in either operand, output low known-0 bits. 1586 // Also compute a conserative estimate for high known-0 bits. 1587 // More trickiness is possible, but this is sufficient for the 1588 // interesting case of alignment computation. 1589 KnownOne.clear(); 1590 unsigned TrailZ = KnownZero.countTrailingOnes() + 1591 KnownZero2.countTrailingOnes(); 1592 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() + 1593 KnownZero2.countLeadingOnes(), 1594 BitWidth) - BitWidth; 1595 1596 TrailZ = std::min(TrailZ, BitWidth); 1597 LeadZ = std::min(LeadZ, BitWidth); 1598 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) | 1599 APInt::getHighBitsSet(BitWidth, LeadZ); 1600 KnownZero &= Mask; 1601 return; 1602 } 1603 case ISD::UDIV: { 1604 // For the purposes of computing leading zeros we can conservatively 1605 // treat a udiv as a logical right shift by the power of 2 known to 1606 // be less than the denominator. 1607 APInt AllOnes = APInt::getAllOnesValue(BitWidth); 1608 ComputeMaskedBits(Op.getOperand(0), 1609 AllOnes, KnownZero2, KnownOne2, Depth+1); 1610 unsigned LeadZ = KnownZero2.countLeadingOnes(); 1611 1612 KnownOne2.clear(); 1613 KnownZero2.clear(); 1614 ComputeMaskedBits(Op.getOperand(1), 1615 AllOnes, KnownZero2, KnownOne2, Depth+1); 1616 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros(); 1617 if (RHSUnknownLeadingOnes != BitWidth) 1618 LeadZ = std::min(BitWidth, 1619 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); 1620 1621 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask; 1622 return; 1623 } 1624 case ISD::SELECT: 1625 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1); 1626 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1); 1627 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1628 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1629 1630 // Only known if known in both the LHS and RHS. 1631 KnownOne &= KnownOne2; 1632 KnownZero &= KnownZero2; 1633 return; 1634 case ISD::SELECT_CC: 1635 ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1); 1636 ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1); 1637 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1638 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1639 1640 // Only known if known in both the LHS and RHS. 1641 KnownOne &= KnownOne2; 1642 KnownZero &= KnownZero2; 1643 return; 1644 case ISD::SADDO: 1645 case ISD::UADDO: 1646 case ISD::SSUBO: 1647 case ISD::USUBO: 1648 case ISD::SMULO: 1649 case ISD::UMULO: 1650 if (Op.getResNo() != 1) 1651 return; 1652 // The boolean result conforms to getBooleanContents. Fall through. 1653 case ISD::SETCC: 1654 // If we know the result of a setcc has the top bits zero, use this info. 1655 if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent && 1656 BitWidth > 1) 1657 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 1658 return; 1659 case ISD::SHL: 1660 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0 1661 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1662 unsigned ShAmt = SA->getZExtValue(); 1663 1664 // If the shift count is an invalid immediate, don't do anything. 1665 if (ShAmt >= BitWidth) 1666 return; 1667 1668 ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt), 1669 KnownZero, KnownOne, Depth+1); 1670 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1671 KnownZero <<= ShAmt; 1672 KnownOne <<= ShAmt; 1673 // low bits known zero. 1674 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt); 1675 } 1676 return; 1677 case ISD::SRL: 1678 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 1679 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1680 unsigned ShAmt = SA->getZExtValue(); 1681 1682 // If the shift count is an invalid immediate, don't do anything. 1683 if (ShAmt >= BitWidth) 1684 return; 1685 1686 ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt), 1687 KnownZero, KnownOne, Depth+1); 1688 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1689 KnownZero = KnownZero.lshr(ShAmt); 1690 KnownOne = KnownOne.lshr(ShAmt); 1691 1692 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask; 1693 KnownZero |= HighBits; // High bits known zero. 1694 } 1695 return; 1696 case ISD::SRA: 1697 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1698 unsigned ShAmt = SA->getZExtValue(); 1699 1700 // If the shift count is an invalid immediate, don't do anything. 1701 if (ShAmt >= BitWidth) 1702 return; 1703 1704 APInt InDemandedMask = (Mask << ShAmt); 1705 // If any of the demanded bits are produced by the sign extension, we also 1706 // demand the input sign bit. 1707 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask; 1708 if (HighBits.getBoolValue()) 1709 InDemandedMask |= APInt::getSignBit(BitWidth); 1710 1711 ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne, 1712 Depth+1); 1713 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1714 KnownZero = KnownZero.lshr(ShAmt); 1715 KnownOne = KnownOne.lshr(ShAmt); 1716 1717 // Handle the sign bits. 1718 APInt SignBit = APInt::getSignBit(BitWidth); 1719 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask. 1720 1721 if (KnownZero.intersects(SignBit)) { 1722 KnownZero |= HighBits; // New bits are known zero. 1723 } else if (KnownOne.intersects(SignBit)) { 1724 KnownOne |= HighBits; // New bits are known one. 1725 } 1726 } 1727 return; 1728 case ISD::SIGN_EXTEND_INREG: { 1729 MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1730 unsigned EBits = EVT.getSizeInBits(); 1731 1732 // Sign extension. Compute the demanded bits in the result that are not 1733 // present in the input. 1734 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask; 1735 1736 APInt InSignBit = APInt::getSignBit(EBits); 1737 APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits); 1738 1739 // If the sign extended bits are demanded, we know that the sign 1740 // bit is demanded. 1741 InSignBit.zext(BitWidth); 1742 if (NewBits.getBoolValue()) 1743 InputDemandedBits |= InSignBit; 1744 1745 ComputeMaskedBits(Op.getOperand(0), InputDemandedBits, 1746 KnownZero, KnownOne, Depth+1); 1747 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1748 1749 // If the sign bit of the input is known set or clear, then we know the 1750 // top bits of the result. 1751 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear 1752 KnownZero |= NewBits; 1753 KnownOne &= ~NewBits; 1754 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 1755 KnownOne |= NewBits; 1756 KnownZero &= ~NewBits; 1757 } else { // Input sign bit unknown 1758 KnownZero &= ~NewBits; 1759 KnownOne &= ~NewBits; 1760 } 1761 return; 1762 } 1763 case ISD::CTTZ: 1764 case ISD::CTLZ: 1765 case ISD::CTPOP: { 1766 unsigned LowBits = Log2_32(BitWidth)+1; 1767 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits); 1768 KnownOne.clear(); 1769 return; 1770 } 1771 case ISD::LOAD: { 1772 if (ISD::isZEXTLoad(Op.getNode())) { 1773 LoadSDNode *LD = cast<LoadSDNode>(Op); 1774 MVT VT = LD->getMemoryVT(); 1775 unsigned MemBits = VT.getSizeInBits(); 1776 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask; 1777 } 1778 return; 1779 } 1780 case ISD::ZERO_EXTEND: { 1781 MVT InVT = Op.getOperand(0).getValueType(); 1782 unsigned InBits = InVT.getSizeInBits(); 1783 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask; 1784 APInt InMask = Mask; 1785 InMask.trunc(InBits); 1786 KnownZero.trunc(InBits); 1787 KnownOne.trunc(InBits); 1788 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1); 1789 KnownZero.zext(BitWidth); 1790 KnownOne.zext(BitWidth); 1791 KnownZero |= NewBits; 1792 return; 1793 } 1794 case ISD::SIGN_EXTEND: { 1795 MVT InVT = Op.getOperand(0).getValueType(); 1796 unsigned InBits = InVT.getSizeInBits(); 1797 APInt InSignBit = APInt::getSignBit(InBits); 1798 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask; 1799 APInt InMask = Mask; 1800 InMask.trunc(InBits); 1801 1802 // If any of the sign extended bits are demanded, we know that the sign 1803 // bit is demanded. Temporarily set this bit in the mask for our callee. 1804 if (NewBits.getBoolValue()) 1805 InMask |= InSignBit; 1806 1807 KnownZero.trunc(InBits); 1808 KnownOne.trunc(InBits); 1809 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1); 1810 1811 // Note if the sign bit is known to be zero or one. 1812 bool SignBitKnownZero = KnownZero.isNegative(); 1813 bool SignBitKnownOne = KnownOne.isNegative(); 1814 assert(!(SignBitKnownZero && SignBitKnownOne) && 1815 "Sign bit can't be known to be both zero and one!"); 1816 1817 // If the sign bit wasn't actually demanded by our caller, we don't 1818 // want it set in the KnownZero and KnownOne result values. Reset the 1819 // mask and reapply it to the result values. 1820 InMask = Mask; 1821 InMask.trunc(InBits); 1822 KnownZero &= InMask; 1823 KnownOne &= InMask; 1824 1825 KnownZero.zext(BitWidth); 1826 KnownOne.zext(BitWidth); 1827 1828 // If the sign bit is known zero or one, the top bits match. 1829 if (SignBitKnownZero) 1830 KnownZero |= NewBits; 1831 else if (SignBitKnownOne) 1832 KnownOne |= NewBits; 1833 return; 1834 } 1835 case ISD::ANY_EXTEND: { 1836 MVT InVT = Op.getOperand(0).getValueType(); 1837 unsigned InBits = InVT.getSizeInBits(); 1838 APInt InMask = Mask; 1839 InMask.trunc(InBits); 1840 KnownZero.trunc(InBits); 1841 KnownOne.trunc(InBits); 1842 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1); 1843 KnownZero.zext(BitWidth); 1844 KnownOne.zext(BitWidth); 1845 return; 1846 } 1847 case ISD::TRUNCATE: { 1848 MVT InVT = Op.getOperand(0).getValueType(); 1849 unsigned InBits = InVT.getSizeInBits(); 1850 APInt InMask = Mask; 1851 InMask.zext(InBits); 1852 KnownZero.zext(InBits); 1853 KnownOne.zext(InBits); 1854 ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1); 1855 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1856 KnownZero.trunc(BitWidth); 1857 KnownOne.trunc(BitWidth); 1858 break; 1859 } 1860 case ISD::AssertZext: { 1861 MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1862 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 1863 ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero, 1864 KnownOne, Depth+1); 1865 KnownZero |= (~InMask) & Mask; 1866 return; 1867 } 1868 case ISD::FGETSIGN: 1869 // All bits are zero except the low bit. 1870 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1); 1871 return; 1872 1873 case ISD::SUB: { 1874 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) { 1875 // We know that the top bits of C-X are clear if X contains less bits 1876 // than C (i.e. no wrap-around can happen). For example, 20-X is 1877 // positive if we can prove that X is >= 0 and < 16. 1878 if (CLHS->getAPIntValue().isNonNegative()) { 1879 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros(); 1880 // NLZ can't be BitWidth with no sign bit 1881 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1); 1882 ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2, 1883 Depth+1); 1884 1885 // If all of the MaskV bits are known to be zero, then we know the 1886 // output top bits are zero, because we now know that the output is 1887 // from [0-C]. 1888 if ((KnownZero2 & MaskV) == MaskV) { 1889 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros(); 1890 // Top bits known zero. 1891 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask; 1892 } 1893 } 1894 } 1895 } 1896 // fall through 1897 case ISD::ADD: { 1898 // Output known-0 bits are known if clear or set in both the low clear bits 1899 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the 1900 // low 3 bits clear. 1901 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes()); 1902 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1); 1903 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1904 unsigned KnownZeroOut = KnownZero2.countTrailingOnes(); 1905 1906 ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1); 1907 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 1908 KnownZeroOut = std::min(KnownZeroOut, 1909 KnownZero2.countTrailingOnes()); 1910 1911 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut); 1912 return; 1913 } 1914 case ISD::SREM: 1915 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1916 const APInt &RA = Rem->getAPIntValue(); 1917 if (RA.isPowerOf2() || (-RA).isPowerOf2()) { 1918 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA; 1919 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth); 1920 ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1); 1921 1922 // If the sign bit of the first operand is zero, the sign bit of 1923 // the result is zero. If the first operand has no one bits below 1924 // the second operand's single 1 bit, its sign will be zero. 1925 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits)) 1926 KnownZero2 |= ~LowBits; 1927 1928 KnownZero |= KnownZero2 & Mask; 1929 1930 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 1931 } 1932 } 1933 return; 1934 case ISD::UREM: { 1935 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1936 const APInt &RA = Rem->getAPIntValue(); 1937 if (RA.isPowerOf2()) { 1938 APInt LowBits = (RA - 1); 1939 APInt Mask2 = LowBits & Mask; 1940 KnownZero |= ~LowBits & Mask; 1941 ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1); 1942 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 1943 break; 1944 } 1945 } 1946 1947 // Since the result is less than or equal to either operand, any leading 1948 // zero bits in either operand must also exist in the result. 1949 APInt AllOnes = APInt::getAllOnesValue(BitWidth); 1950 ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne, 1951 Depth+1); 1952 ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2, 1953 Depth+1); 1954 1955 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(), 1956 KnownZero2.countLeadingOnes()); 1957 KnownOne.clear(); 1958 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask; 1959 return; 1960 } 1961 default: 1962 // Allow the target to implement this method for its nodes. 1963 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 1964 case ISD::INTRINSIC_WO_CHAIN: 1965 case ISD::INTRINSIC_W_CHAIN: 1966 case ISD::INTRINSIC_VOID: 1967 TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this, 1968 Depth); 1969 } 1970 return; 1971 } 1972} 1973 1974/// ComputeNumSignBits - Return the number of times the sign bit of the 1975/// register is replicated into the other bits. We know that at least 1 bit 1976/// is always equal to the sign bit (itself), but other cases can give us 1977/// information. For example, immediately after an "SRA X, 2", we know that 1978/// the top 3 bits are all equal to each other, so we return 3. 1979unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{ 1980 MVT VT = Op.getValueType(); 1981 assert(VT.isInteger() && "Invalid VT!"); 1982 unsigned VTBits = VT.getSizeInBits(); 1983 unsigned Tmp, Tmp2; 1984 unsigned FirstAnswer = 1; 1985 1986 if (Depth == 6) 1987 return 1; // Limit search depth. 1988 1989 switch (Op.getOpcode()) { 1990 default: break; 1991 case ISD::AssertSext: 1992 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 1993 return VTBits-Tmp+1; 1994 case ISD::AssertZext: 1995 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 1996 return VTBits-Tmp; 1997 1998 case ISD::Constant: { 1999 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue(); 2000 // If negative, return # leading ones. 2001 if (Val.isNegative()) 2002 return Val.countLeadingOnes(); 2003 2004 // Return # leading zeros. 2005 return Val.countLeadingZeros(); 2006 } 2007 2008 case ISD::SIGN_EXTEND: 2009 Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits(); 2010 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp; 2011 2012 case ISD::SIGN_EXTEND_INREG: 2013 // Max of the input and what this extends. 2014 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2015 Tmp = VTBits-Tmp+1; 2016 2017 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2018 return std::max(Tmp, Tmp2); 2019 2020 case ISD::SRA: 2021 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2022 // SRA X, C -> adds C sign bits. 2023 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2024 Tmp += C->getZExtValue(); 2025 if (Tmp > VTBits) Tmp = VTBits; 2026 } 2027 return Tmp; 2028 case ISD::SHL: 2029 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2030 // shl destroys sign bits. 2031 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2032 if (C->getZExtValue() >= VTBits || // Bad shift. 2033 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out. 2034 return Tmp - C->getZExtValue(); 2035 } 2036 break; 2037 case ISD::AND: 2038 case ISD::OR: 2039 case ISD::XOR: // NOT is handled here. 2040 // Logical binary ops preserve the number of sign bits at the worst. 2041 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2042 if (Tmp != 1) { 2043 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2044 FirstAnswer = std::min(Tmp, Tmp2); 2045 // We computed what we know about the sign bits as our first 2046 // answer. Now proceed to the generic code that uses 2047 // ComputeMaskedBits, and pick whichever answer is better. 2048 } 2049 break; 2050 2051 case ISD::SELECT: 2052 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2053 if (Tmp == 1) return 1; // Early out. 2054 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1); 2055 return std::min(Tmp, Tmp2); 2056 2057 case ISD::SADDO: 2058 case ISD::UADDO: 2059 case ISD::SSUBO: 2060 case ISD::USUBO: 2061 case ISD::SMULO: 2062 case ISD::UMULO: 2063 if (Op.getResNo() != 1) 2064 break; 2065 // The boolean result conforms to getBooleanContents. Fall through. 2066 case ISD::SETCC: 2067 // If setcc returns 0/-1, all bits are sign bits. 2068 if (TLI.getBooleanContents() == 2069 TargetLowering::ZeroOrNegativeOneBooleanContent) 2070 return VTBits; 2071 break; 2072 case ISD::ROTL: 2073 case ISD::ROTR: 2074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2075 unsigned RotAmt = C->getZExtValue() & (VTBits-1); 2076 2077 // Handle rotate right by N like a rotate left by 32-N. 2078 if (Op.getOpcode() == ISD::ROTR) 2079 RotAmt = (VTBits-RotAmt) & (VTBits-1); 2080 2081 // If we aren't rotating out all of the known-in sign bits, return the 2082 // number that are left. This handles rotl(sext(x), 1) for example. 2083 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2084 if (Tmp > RotAmt+1) return Tmp-RotAmt; 2085 } 2086 break; 2087 case ISD::ADD: 2088 // Add can have at most one carry bit. Thus we know that the output 2089 // is, at worst, one more bit than the inputs. 2090 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2091 if (Tmp == 1) return 1; // Early out. 2092 2093 // Special case decrementing a value (ADD X, -1): 2094 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2095 if (CRHS->isAllOnesValue()) { 2096 APInt KnownZero, KnownOne; 2097 APInt Mask = APInt::getAllOnesValue(VTBits); 2098 ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1); 2099 2100 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2101 // sign bits set. 2102 if ((KnownZero | APInt(VTBits, 1)) == Mask) 2103 return VTBits; 2104 2105 // If we are subtracting one from a positive number, there is no carry 2106 // out of the result. 2107 if (KnownZero.isNegative()) 2108 return Tmp; 2109 } 2110 2111 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2112 if (Tmp2 == 1) return 1; 2113 return std::min(Tmp, Tmp2)-1; 2114 break; 2115 2116 case ISD::SUB: 2117 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2118 if (Tmp2 == 1) return 1; 2119 2120 // Handle NEG. 2121 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) 2122 if (CLHS->isNullValue()) { 2123 APInt KnownZero, KnownOne; 2124 APInt Mask = APInt::getAllOnesValue(VTBits); 2125 ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1); 2126 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2127 // sign bits set. 2128 if ((KnownZero | APInt(VTBits, 1)) == Mask) 2129 return VTBits; 2130 2131 // If the input is known to be positive (the sign bit is known clear), 2132 // the output of the NEG has the same number of sign bits as the input. 2133 if (KnownZero.isNegative()) 2134 return Tmp2; 2135 2136 // Otherwise, we treat this like a SUB. 2137 } 2138 2139 // Sub can have at most one carry bit. Thus we know that the output 2140 // is, at worst, one more bit than the inputs. 2141 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2142 if (Tmp == 1) return 1; // Early out. 2143 return std::min(Tmp, Tmp2)-1; 2144 break; 2145 case ISD::TRUNCATE: 2146 // FIXME: it's tricky to do anything useful for this, but it is an important 2147 // case for targets like X86. 2148 break; 2149 } 2150 2151 // Handle LOADX separately here. EXTLOAD case will fallthrough. 2152 if (Op.getOpcode() == ISD::LOAD) { 2153 LoadSDNode *LD = cast<LoadSDNode>(Op); 2154 unsigned ExtType = LD->getExtensionType(); 2155 switch (ExtType) { 2156 default: break; 2157 case ISD::SEXTLOAD: // '17' bits known 2158 Tmp = LD->getMemoryVT().getSizeInBits(); 2159 return VTBits-Tmp+1; 2160 case ISD::ZEXTLOAD: // '16' bits known 2161 Tmp = LD->getMemoryVT().getSizeInBits(); 2162 return VTBits-Tmp; 2163 } 2164 } 2165 2166 // Allow the target to implement this method for its nodes. 2167 if (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2168 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2169 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2170 Op.getOpcode() == ISD::INTRINSIC_VOID) { 2171 unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth); 2172 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits); 2173 } 2174 2175 // Finally, if we can prove that the top bits of the result are 0's or 1's, 2176 // use this information. 2177 APInt KnownZero, KnownOne; 2178 APInt Mask = APInt::getAllOnesValue(VTBits); 2179 ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth); 2180 2181 if (KnownZero.isNegative()) { // sign bit is 0 2182 Mask = KnownZero; 2183 } else if (KnownOne.isNegative()) { // sign bit is 1; 2184 Mask = KnownOne; 2185 } else { 2186 // Nothing known. 2187 return FirstAnswer; 2188 } 2189 2190 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine 2191 // the number of identical bits in the top of the input value. 2192 Mask = ~Mask; 2193 Mask <<= Mask.getBitWidth()-VTBits; 2194 // Return # leading zeros. We use 'min' here in case Val was zero before 2195 // shifting. We don't want to return '64' as for an i32 "0". 2196 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros())); 2197} 2198 2199 2200bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const { 2201 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op); 2202 if (!GA) return false; 2203 if (GA->getOffset() != 0) return false; 2204 GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal()); 2205 if (!GV) return false; 2206 MachineModuleInfo *MMI = getMachineModuleInfo(); 2207 return MMI && MMI->hasDebugInfo(); 2208} 2209 2210 2211/// getShuffleScalarElt - Returns the scalar element that will make up the ith 2212/// element of the result of the vector shuffle. 2213SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N, 2214 unsigned i) { 2215 MVT VT = N->getValueType(0); 2216 DebugLoc dl = N->getDebugLoc(); 2217 if (N->getMaskElt(i) < 0) 2218 return getUNDEF(VT.getVectorElementType()); 2219 unsigned Index = N->getMaskElt(i); 2220 unsigned NumElems = VT.getVectorNumElements(); 2221 SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1); 2222 Index %= NumElems; 2223 2224 if (V.getOpcode() == ISD::BIT_CONVERT) { 2225 V = V.getOperand(0); 2226 MVT VVT = V.getValueType(); 2227 if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems) 2228 return SDValue(); 2229 } 2230 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) 2231 return (Index == 0) ? V.getOperand(0) 2232 : getUNDEF(VT.getVectorElementType()); 2233 if (V.getOpcode() == ISD::BUILD_VECTOR) 2234 return V.getOperand(Index); 2235 if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V)) 2236 return getShuffleScalarElt(SVN, Index); 2237 return SDValue(); 2238} 2239 2240 2241/// getNode - Gets or creates the specified node. 2242/// 2243SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT) { 2244 FoldingSetNodeID ID; 2245 AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0); 2246 void *IP = 0; 2247 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 2248 return SDValue(E, 0); 2249 SDNode *N = NodeAllocator.Allocate<SDNode>(); 2250 new (N) SDNode(Opcode, DL, getVTList(VT)); 2251 CSEMap.InsertNode(N, IP); 2252 2253 AllNodes.push_back(N); 2254#ifndef NDEBUG 2255 VerifyNode(N); 2256#endif 2257 return SDValue(N, 0); 2258} 2259 2260SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, 2261 MVT VT, SDValue Operand) { 2262 // Constant fold unary operations with an integer constant operand. 2263 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) { 2264 const APInt &Val = C->getAPIntValue(); 2265 unsigned BitWidth = VT.getSizeInBits(); 2266 switch (Opcode) { 2267 default: break; 2268 case ISD::SIGN_EXTEND: 2269 return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT); 2270 case ISD::ANY_EXTEND: 2271 case ISD::ZERO_EXTEND: 2272 case ISD::TRUNCATE: 2273 return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT); 2274 case ISD::UINT_TO_FP: 2275 case ISD::SINT_TO_FP: { 2276 const uint64_t zero[] = {0, 0}; 2277 // No compile time operations on this type. 2278 if (VT==MVT::ppcf128) 2279 break; 2280 APFloat apf = APFloat(APInt(BitWidth, 2, zero)); 2281 (void)apf.convertFromAPInt(Val, 2282 Opcode==ISD::SINT_TO_FP, 2283 APFloat::rmNearestTiesToEven); 2284 return getConstantFP(apf, VT); 2285 } 2286 case ISD::BIT_CONVERT: 2287 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 2288 return getConstantFP(Val.bitsToFloat(), VT); 2289 else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 2290 return getConstantFP(Val.bitsToDouble(), VT); 2291 break; 2292 case ISD::BSWAP: 2293 return getConstant(Val.byteSwap(), VT); 2294 case ISD::CTPOP: 2295 return getConstant(Val.countPopulation(), VT); 2296 case ISD::CTLZ: 2297 return getConstant(Val.countLeadingZeros(), VT); 2298 case ISD::CTTZ: 2299 return getConstant(Val.countTrailingZeros(), VT); 2300 } 2301 } 2302 2303 // Constant fold unary operations with a floating point constant operand. 2304 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) { 2305 APFloat V = C->getValueAPF(); // make copy 2306 if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) { 2307 switch (Opcode) { 2308 case ISD::FNEG: 2309 V.changeSign(); 2310 return getConstantFP(V, VT); 2311 case ISD::FABS: 2312 V.clearSign(); 2313 return getConstantFP(V, VT); 2314 case ISD::FP_ROUND: 2315 case ISD::FP_EXTEND: { 2316 bool ignored; 2317 // This can return overflow, underflow, or inexact; we don't care. 2318 // FIXME need to be more flexible about rounding mode. 2319 (void)V.convert(*MVTToAPFloatSemantics(VT), 2320 APFloat::rmNearestTiesToEven, &ignored); 2321 return getConstantFP(V, VT); 2322 } 2323 case ISD::FP_TO_SINT: 2324 case ISD::FP_TO_UINT: { 2325 integerPart x[2]; 2326 bool ignored; 2327 assert(integerPartWidth >= 64); 2328 // FIXME need to be more flexible about rounding mode. 2329 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(), 2330 Opcode==ISD::FP_TO_SINT, 2331 APFloat::rmTowardZero, &ignored); 2332 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual 2333 break; 2334 APInt api(VT.getSizeInBits(), 2, x); 2335 return getConstant(api, VT); 2336 } 2337 case ISD::BIT_CONVERT: 2338 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 2339 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT); 2340 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 2341 return getConstant(V.bitcastToAPInt().getZExtValue(), VT); 2342 break; 2343 } 2344 } 2345 } 2346 2347 unsigned OpOpcode = Operand.getNode()->getOpcode(); 2348 switch (Opcode) { 2349 case ISD::TokenFactor: 2350 case ISD::MERGE_VALUES: 2351 case ISD::CONCAT_VECTORS: 2352 return Operand; // Factor, merge or concat of one node? No need. 2353 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 2354 case ISD::FP_EXTEND: 2355 assert(VT.isFloatingPoint() && 2356 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 2357 if (Operand.getValueType() == VT) return Operand; // noop conversion. 2358 if (Operand.getOpcode() == ISD::UNDEF) 2359 return getUNDEF(VT); 2360 break; 2361 case ISD::SIGN_EXTEND: 2362 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2363 "Invalid SIGN_EXTEND!"); 2364 if (Operand.getValueType() == VT) return Operand; // noop extension 2365 assert(Operand.getValueType().bitsLT(VT) 2366 && "Invalid sext node, dst < src!"); 2367 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 2368 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 2369 break; 2370 case ISD::ZERO_EXTEND: 2371 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2372 "Invalid ZERO_EXTEND!"); 2373 if (Operand.getValueType() == VT) return Operand; // noop extension 2374 assert(Operand.getValueType().bitsLT(VT) 2375 && "Invalid zext node, dst < src!"); 2376 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 2377 return getNode(ISD::ZERO_EXTEND, DL, VT, 2378 Operand.getNode()->getOperand(0)); 2379 break; 2380 case ISD::ANY_EXTEND: 2381 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2382 "Invalid ANY_EXTEND!"); 2383 if (Operand.getValueType() == VT) return Operand; // noop extension 2384 assert(Operand.getValueType().bitsLT(VT) 2385 && "Invalid anyext node, dst < src!"); 2386 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND) 2387 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 2388 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 2389 break; 2390 case ISD::TRUNCATE: 2391 assert(VT.isInteger() && Operand.getValueType().isInteger() && 2392 "Invalid TRUNCATE!"); 2393 if (Operand.getValueType() == VT) return Operand; // noop truncate 2394 assert(Operand.getValueType().bitsGT(VT) 2395 && "Invalid truncate node, src < dst!"); 2396 if (OpOpcode == ISD::TRUNCATE) 2397 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 2398 else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 2399 OpOpcode == ISD::ANY_EXTEND) { 2400 // If the source is smaller than the dest, we still need an extend. 2401 if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT)) 2402 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 2403 else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT)) 2404 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 2405 else 2406 return Operand.getNode()->getOperand(0); 2407 } 2408 break; 2409 case ISD::BIT_CONVERT: 2410 // Basic sanity checking. 2411 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits() 2412 && "Cannot BIT_CONVERT between types of different sizes!"); 2413 if (VT == Operand.getValueType()) return Operand; // noop conversion. 2414 if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x) 2415 return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0)); 2416 if (OpOpcode == ISD::UNDEF) 2417 return getUNDEF(VT); 2418 break; 2419 case ISD::SCALAR_TO_VECTOR: 2420 assert(VT.isVector() && !Operand.getValueType().isVector() && 2421 (VT.getVectorElementType() == Operand.getValueType() || 2422 (VT.getVectorElementType().isInteger() && 2423 Operand.getValueType().isInteger() && 2424 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 2425 "Illegal SCALAR_TO_VECTOR node!"); 2426 if (OpOpcode == ISD::UNDEF) 2427 return getUNDEF(VT); 2428 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 2429 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 2430 isa<ConstantSDNode>(Operand.getOperand(1)) && 2431 Operand.getConstantOperandVal(1) == 0 && 2432 Operand.getOperand(0).getValueType() == VT) 2433 return Operand.getOperand(0); 2434 break; 2435 case ISD::FNEG: 2436 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 2437 if (UnsafeFPMath && OpOpcode == ISD::FSUB) 2438 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1), 2439 Operand.getNode()->getOperand(0)); 2440 if (OpOpcode == ISD::FNEG) // --X -> X 2441 return Operand.getNode()->getOperand(0); 2442 break; 2443 case ISD::FABS: 2444 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 2445 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0)); 2446 break; 2447 } 2448 2449 SDNode *N; 2450 SDVTList VTs = getVTList(VT); 2451 if (VT != MVT::Flag) { // Don't CSE flag producing nodes 2452 FoldingSetNodeID ID; 2453 SDValue Ops[1] = { Operand }; 2454 AddNodeIDNode(ID, Opcode, VTs, Ops, 1); 2455 void *IP = 0; 2456 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 2457 return SDValue(E, 0); 2458 N = NodeAllocator.Allocate<UnarySDNode>(); 2459 new (N) UnarySDNode(Opcode, DL, VTs, Operand); 2460 CSEMap.InsertNode(N, IP); 2461 } else { 2462 N = NodeAllocator.Allocate<UnarySDNode>(); 2463 new (N) UnarySDNode(Opcode, DL, VTs, Operand); 2464 } 2465 2466 AllNodes.push_back(N); 2467#ifndef NDEBUG 2468 VerifyNode(N); 2469#endif 2470 return SDValue(N, 0); 2471} 2472 2473SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, 2474 MVT VT, 2475 ConstantSDNode *Cst1, 2476 ConstantSDNode *Cst2) { 2477 const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue(); 2478 2479 switch (Opcode) { 2480 case ISD::ADD: return getConstant(C1 + C2, VT); 2481 case ISD::SUB: return getConstant(C1 - C2, VT); 2482 case ISD::MUL: return getConstant(C1 * C2, VT); 2483 case ISD::UDIV: 2484 if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT); 2485 break; 2486 case ISD::UREM: 2487 if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT); 2488 break; 2489 case ISD::SDIV: 2490 if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT); 2491 break; 2492 case ISD::SREM: 2493 if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT); 2494 break; 2495 case ISD::AND: return getConstant(C1 & C2, VT); 2496 case ISD::OR: return getConstant(C1 | C2, VT); 2497 case ISD::XOR: return getConstant(C1 ^ C2, VT); 2498 case ISD::SHL: return getConstant(C1 << C2, VT); 2499 case ISD::SRL: return getConstant(C1.lshr(C2), VT); 2500 case ISD::SRA: return getConstant(C1.ashr(C2), VT); 2501 case ISD::ROTL: return getConstant(C1.rotl(C2), VT); 2502 case ISD::ROTR: return getConstant(C1.rotr(C2), VT); 2503 default: break; 2504 } 2505 2506 return SDValue(); 2507} 2508 2509SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT, 2510 SDValue N1, SDValue N2) { 2511 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 2512 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 2513 switch (Opcode) { 2514 default: break; 2515 case ISD::TokenFactor: 2516 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 2517 N2.getValueType() == MVT::Other && "Invalid token factor!"); 2518 // Fold trivial token factors. 2519 if (N1.getOpcode() == ISD::EntryToken) return N2; 2520 if (N2.getOpcode() == ISD::EntryToken) return N1; 2521 if (N1 == N2) return N1; 2522 break; 2523 case ISD::CONCAT_VECTORS: 2524 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to 2525 // one big BUILD_VECTOR. 2526 if (N1.getOpcode() == ISD::BUILD_VECTOR && 2527 N2.getOpcode() == ISD::BUILD_VECTOR) { 2528 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end()); 2529 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end()); 2530 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size()); 2531 } 2532 break; 2533 case ISD::AND: 2534 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() && 2535 N1.getValueType() == VT && "Binary operator types must match!"); 2536 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 2537 // worth handling here. 2538 if (N2C && N2C->isNullValue()) 2539 return N2; 2540 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 2541 return N1; 2542 break; 2543 case ISD::OR: 2544 case ISD::XOR: 2545 case ISD::ADD: 2546 case ISD::SUB: 2547 assert(VT.isInteger() && N1.getValueType() == N2.getValueType() && 2548 N1.getValueType() == VT && "Binary operator types must match!"); 2549 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 2550 // it's worth handling here. 2551 if (N2C && N2C->isNullValue()) 2552 return N1; 2553 break; 2554 case ISD::UDIV: 2555 case ISD::UREM: 2556 case ISD::MULHU: 2557 case ISD::MULHS: 2558 case ISD::MUL: 2559 case ISD::SDIV: 2560 case ISD::SREM: 2561 assert(VT.isInteger() && "This operator does not apply to FP types!"); 2562 // fall through 2563 case ISD::FADD: 2564 case ISD::FSUB: 2565 case ISD::FMUL: 2566 case ISD::FDIV: 2567 case ISD::FREM: 2568 if (UnsafeFPMath) { 2569 if (Opcode == ISD::FADD) { 2570 // 0+x --> x 2571 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) 2572 if (CFP->getValueAPF().isZero()) 2573 return N2; 2574 // x+0 --> x 2575 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2)) 2576 if (CFP->getValueAPF().isZero()) 2577 return N1; 2578 } else if (Opcode == ISD::FSUB) { 2579 // x-0 --> x 2580 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2)) 2581 if (CFP->getValueAPF().isZero()) 2582 return N1; 2583 } 2584 } 2585 assert(N1.getValueType() == N2.getValueType() && 2586 N1.getValueType() == VT && "Binary operator types must match!"); 2587 break; 2588 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 2589 assert(N1.getValueType() == VT && 2590 N1.getValueType().isFloatingPoint() && 2591 N2.getValueType().isFloatingPoint() && 2592 "Invalid FCOPYSIGN!"); 2593 break; 2594 case ISD::SHL: 2595 case ISD::SRA: 2596 case ISD::SRL: 2597 case ISD::ROTL: 2598 case ISD::ROTR: 2599 assert(VT == N1.getValueType() && 2600 "Shift operators return type must be the same as their first arg"); 2601 assert(VT.isInteger() && N2.getValueType().isInteger() && 2602 "Shifts only work on integers"); 2603 2604 // Always fold shifts of i1 values so the code generator doesn't need to 2605 // handle them. Since we know the size of the shift has to be less than the 2606 // size of the value, the shift/rotate count is guaranteed to be zero. 2607 if (VT == MVT::i1) 2608 return N1; 2609 break; 2610 case ISD::FP_ROUND_INREG: { 2611 MVT EVT = cast<VTSDNode>(N2)->getVT(); 2612 assert(VT == N1.getValueType() && "Not an inreg round!"); 2613 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() && 2614 "Cannot FP_ROUND_INREG integer types"); 2615 assert(EVT.bitsLE(VT) && "Not rounding down!"); 2616 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding. 2617 break; 2618 } 2619 case ISD::FP_ROUND: 2620 assert(VT.isFloatingPoint() && 2621 N1.getValueType().isFloatingPoint() && 2622 VT.bitsLE(N1.getValueType()) && 2623 isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!"); 2624 if (N1.getValueType() == VT) return N1; // noop conversion. 2625 break; 2626 case ISD::AssertSext: 2627 case ISD::AssertZext: { 2628 MVT EVT = cast<VTSDNode>(N2)->getVT(); 2629 assert(VT == N1.getValueType() && "Not an inreg extend!"); 2630 assert(VT.isInteger() && EVT.isInteger() && 2631 "Cannot *_EXTEND_INREG FP types"); 2632 assert(EVT.bitsLE(VT) && "Not extending!"); 2633 if (VT == EVT) return N1; // noop assertion. 2634 break; 2635 } 2636 case ISD::SIGN_EXTEND_INREG: { 2637 MVT EVT = cast<VTSDNode>(N2)->getVT(); 2638 assert(VT == N1.getValueType() && "Not an inreg extend!"); 2639 assert(VT.isInteger() && EVT.isInteger() && 2640 "Cannot *_EXTEND_INREG FP types"); 2641 assert(EVT.bitsLE(VT) && "Not extending!"); 2642 if (EVT == VT) return N1; // Not actually extending 2643 2644 if (N1C) { 2645 APInt Val = N1C->getAPIntValue(); 2646 unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits(); 2647 Val <<= Val.getBitWidth()-FromBits; 2648 Val = Val.ashr(Val.getBitWidth()-FromBits); 2649 return getConstant(Val, VT); 2650 } 2651 break; 2652 } 2653 case ISD::EXTRACT_VECTOR_ELT: 2654 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF. 2655 if (N1.getOpcode() == ISD::UNDEF) 2656 return getUNDEF(VT); 2657 2658 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 2659 // expanding copies of large vectors from registers. 2660 if (N2C && 2661 N1.getOpcode() == ISD::CONCAT_VECTORS && 2662 N1.getNumOperands() > 0) { 2663 unsigned Factor = 2664 N1.getOperand(0).getValueType().getVectorNumElements(); 2665 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 2666 N1.getOperand(N2C->getZExtValue() / Factor), 2667 getConstant(N2C->getZExtValue() % Factor, 2668 N2.getValueType())); 2669 } 2670 2671 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is 2672 // expanding large vector constants. 2673 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) { 2674 SDValue Elt = N1.getOperand(N2C->getZExtValue()); 2675 MVT VEltTy = N1.getValueType().getVectorElementType(); 2676 if (Elt.getValueType() != VEltTy) { 2677 // If the vector element type is not legal, the BUILD_VECTOR operands 2678 // are promoted and implicitly truncated. Make that explicit here. 2679 Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt); 2680 } 2681 if (VT != VEltTy) { 2682 // If the vector element type is not legal, the EXTRACT_VECTOR_ELT 2683 // result is implicitly extended. 2684 Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt); 2685 } 2686 return Elt; 2687 } 2688 2689 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 2690 // operations are lowered to scalars. 2691 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 2692 // If the indices are the same, return the inserted element. 2693 if (N1.getOperand(2) == N2) 2694 return N1.getOperand(1); 2695 // If the indices are known different, extract the element from 2696 // the original vector. 2697 else if (isa<ConstantSDNode>(N1.getOperand(2)) && 2698 isa<ConstantSDNode>(N2)) 2699 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 2700 } 2701 break; 2702 case ISD::EXTRACT_ELEMENT: 2703 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 2704 assert(!N1.getValueType().isVector() && !VT.isVector() && 2705 (N1.getValueType().isInteger() == VT.isInteger()) && 2706 "Wrong types for EXTRACT_ELEMENT!"); 2707 2708 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 2709 // 64-bit integers into 32-bit parts. Instead of building the extract of 2710 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 2711 if (N1.getOpcode() == ISD::BUILD_PAIR) 2712 return N1.getOperand(N2C->getZExtValue()); 2713 2714 // EXTRACT_ELEMENT of a constant int is also very common. 2715 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 2716 unsigned ElementSize = VT.getSizeInBits(); 2717 unsigned Shift = ElementSize * N2C->getZExtValue(); 2718 APInt ShiftedVal = C->getAPIntValue().lshr(Shift); 2719 return getConstant(ShiftedVal.trunc(ElementSize), VT); 2720 } 2721 break; 2722 case ISD::EXTRACT_SUBVECTOR: 2723 if (N1.getValueType() == VT) // Trivial extraction. 2724 return N1; 2725 break; 2726 } 2727 2728 if (N1C) { 2729 if (N2C) { 2730 SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C); 2731 if (SV.getNode()) return SV; 2732 } else { // Cannonicalize constant to RHS if commutative 2733 if (isCommutativeBinOp(Opcode)) { 2734 std::swap(N1C, N2C); 2735 std::swap(N1, N2); 2736 } 2737 } 2738 } 2739 2740 // Constant fold FP operations. 2741 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 2742 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 2743 if (N1CFP) { 2744 if (!N2CFP && isCommutativeBinOp(Opcode)) { 2745 // Cannonicalize constant to RHS if commutative 2746 std::swap(N1CFP, N2CFP); 2747 std::swap(N1, N2); 2748 } else if (N2CFP && VT != MVT::ppcf128) { 2749 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF(); 2750 APFloat::opStatus s; 2751 switch (Opcode) { 2752 case ISD::FADD: 2753 s = V1.add(V2, APFloat::rmNearestTiesToEven); 2754 if (s != APFloat::opInvalidOp) 2755 return getConstantFP(V1, VT); 2756 break; 2757 case ISD::FSUB: 2758 s = V1.subtract(V2, APFloat::rmNearestTiesToEven); 2759 if (s!=APFloat::opInvalidOp) 2760 return getConstantFP(V1, VT); 2761 break; 2762 case ISD::FMUL: 2763 s = V1.multiply(V2, APFloat::rmNearestTiesToEven); 2764 if (s!=APFloat::opInvalidOp) 2765 return getConstantFP(V1, VT); 2766 break; 2767 case ISD::FDIV: 2768 s = V1.divide(V2, APFloat::rmNearestTiesToEven); 2769 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero) 2770 return getConstantFP(V1, VT); 2771 break; 2772 case ISD::FREM : 2773 s = V1.mod(V2, APFloat::rmNearestTiesToEven); 2774 if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero) 2775 return getConstantFP(V1, VT); 2776 break; 2777 case ISD::FCOPYSIGN: 2778 V1.copySign(V2); 2779 return getConstantFP(V1, VT); 2780 default: break; 2781 } 2782 } 2783 } 2784 2785 // Canonicalize an UNDEF to the RHS, even over a constant. 2786 if (N1.getOpcode() == ISD::UNDEF) { 2787 if (isCommutativeBinOp(Opcode)) { 2788 std::swap(N1, N2); 2789 } else { 2790 switch (Opcode) { 2791 case ISD::FP_ROUND_INREG: 2792 case ISD::SIGN_EXTEND_INREG: 2793 case ISD::SUB: 2794 case ISD::FSUB: 2795 case ISD::FDIV: 2796 case ISD::FREM: 2797 case ISD::SRA: 2798 return N1; // fold op(undef, arg2) -> undef 2799 case ISD::UDIV: 2800 case ISD::SDIV: 2801 case ISD::UREM: 2802 case ISD::SREM: 2803 case ISD::SRL: 2804 case ISD::SHL: 2805 if (!VT.isVector()) 2806 return getConstant(0, VT); // fold op(undef, arg2) -> 0 2807 // For vectors, we can't easily build an all zero vector, just return 2808 // the LHS. 2809 return N2; 2810 } 2811 } 2812 } 2813 2814 // Fold a bunch of operators when the RHS is undef. 2815 if (N2.getOpcode() == ISD::UNDEF) { 2816 switch (Opcode) { 2817 case ISD::XOR: 2818 if (N1.getOpcode() == ISD::UNDEF) 2819 // Handle undef ^ undef -> 0 special case. This is a common 2820 // idiom (misuse). 2821 return getConstant(0, VT); 2822 // fallthrough 2823 case ISD::ADD: 2824 case ISD::ADDC: 2825 case ISD::ADDE: 2826 case ISD::SUB: 2827 case ISD::UDIV: 2828 case ISD::SDIV: 2829 case ISD::UREM: 2830 case ISD::SREM: 2831 return N2; // fold op(arg1, undef) -> undef 2832 case ISD::FADD: 2833 case ISD::FSUB: 2834 case ISD::FMUL: 2835 case ISD::FDIV: 2836 case ISD::FREM: 2837 if (UnsafeFPMath) 2838 return N2; 2839 break; 2840 case ISD::MUL: 2841 case ISD::AND: 2842 case ISD::SRL: 2843 case ISD::SHL: 2844 if (!VT.isVector()) 2845 return getConstant(0, VT); // fold op(arg1, undef) -> 0 2846 // For vectors, we can't easily build an all zero vector, just return 2847 // the LHS. 2848 return N1; 2849 case ISD::OR: 2850 if (!VT.isVector()) 2851 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT); 2852 // For vectors, we can't easily build an all one vector, just return 2853 // the LHS. 2854 return N1; 2855 case ISD::SRA: 2856 return N1; 2857 } 2858 } 2859 2860 // Memoize this node if possible. 2861 SDNode *N; 2862 SDVTList VTs = getVTList(VT); 2863 if (VT != MVT::Flag) { 2864 SDValue Ops[] = { N1, N2 }; 2865 FoldingSetNodeID ID; 2866 AddNodeIDNode(ID, Opcode, VTs, Ops, 2); 2867 void *IP = 0; 2868 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 2869 return SDValue(E, 0); 2870 N = NodeAllocator.Allocate<BinarySDNode>(); 2871 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2); 2872 CSEMap.InsertNode(N, IP); 2873 } else { 2874 N = NodeAllocator.Allocate<BinarySDNode>(); 2875 new (N) BinarySDNode(Opcode, DL, VTs, N1, N2); 2876 } 2877 2878 AllNodes.push_back(N); 2879#ifndef NDEBUG 2880 VerifyNode(N); 2881#endif 2882 return SDValue(N, 0); 2883} 2884 2885SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT, 2886 SDValue N1, SDValue N2, SDValue N3) { 2887 // Perform various simplifications. 2888 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 2889 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 2890 switch (Opcode) { 2891 case ISD::CONCAT_VECTORS: 2892 // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to 2893 // one big BUILD_VECTOR. 2894 if (N1.getOpcode() == ISD::BUILD_VECTOR && 2895 N2.getOpcode() == ISD::BUILD_VECTOR && 2896 N3.getOpcode() == ISD::BUILD_VECTOR) { 2897 SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end()); 2898 Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end()); 2899 Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end()); 2900 return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size()); 2901 } 2902 break; 2903 case ISD::SETCC: { 2904 // Use FoldSetCC to simplify SETCC's. 2905 SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL); 2906 if (Simp.getNode()) return Simp; 2907 break; 2908 } 2909 case ISD::SELECT: 2910 if (N1C) { 2911 if (N1C->getZExtValue()) 2912 return N2; // select true, X, Y -> X 2913 else 2914 return N3; // select false, X, Y -> Y 2915 } 2916 2917 if (N2 == N3) return N2; // select C, X, X -> X 2918 break; 2919 case ISD::BRCOND: 2920 if (N2C) { 2921 if (N2C->getZExtValue()) // Unconditional branch 2922 return getNode(ISD::BR, DL, MVT::Other, N1, N3); 2923 else 2924 return N1; // Never-taken branch 2925 } 2926 break; 2927 case ISD::VECTOR_SHUFFLE: 2928 llvm_unreachable("should use getVectorShuffle constructor!"); 2929 break; 2930 case ISD::BIT_CONVERT: 2931 // Fold bit_convert nodes from a type to themselves. 2932 if (N1.getValueType() == VT) 2933 return N1; 2934 break; 2935 } 2936 2937 // Memoize node if it doesn't produce a flag. 2938 SDNode *N; 2939 SDVTList VTs = getVTList(VT); 2940 if (VT != MVT::Flag) { 2941 SDValue Ops[] = { N1, N2, N3 }; 2942 FoldingSetNodeID ID; 2943 AddNodeIDNode(ID, Opcode, VTs, Ops, 3); 2944 void *IP = 0; 2945 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 2946 return SDValue(E, 0); 2947 N = NodeAllocator.Allocate<TernarySDNode>(); 2948 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3); 2949 CSEMap.InsertNode(N, IP); 2950 } else { 2951 N = NodeAllocator.Allocate<TernarySDNode>(); 2952 new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3); 2953 } 2954 AllNodes.push_back(N); 2955#ifndef NDEBUG 2956 VerifyNode(N); 2957#endif 2958 return SDValue(N, 0); 2959} 2960 2961SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT, 2962 SDValue N1, SDValue N2, SDValue N3, 2963 SDValue N4) { 2964 SDValue Ops[] = { N1, N2, N3, N4 }; 2965 return getNode(Opcode, DL, VT, Ops, 4); 2966} 2967 2968SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT, 2969 SDValue N1, SDValue N2, SDValue N3, 2970 SDValue N4, SDValue N5) { 2971 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 2972 return getNode(Opcode, DL, VT, Ops, 5); 2973} 2974 2975/// getStackArgumentTokenFactor - Compute a TokenFactor to force all 2976/// the incoming stack arguments to be loaded from the stack. 2977SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 2978 SmallVector<SDValue, 8> ArgChains; 2979 2980 // Include the original chain at the beginning of the list. When this is 2981 // used by target LowerCall hooks, this helps legalize find the 2982 // CALLSEQ_BEGIN node. 2983 ArgChains.push_back(Chain); 2984 2985 // Add a chain value for each stack argument. 2986 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 2987 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 2988 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 2989 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 2990 if (FI->getIndex() < 0) 2991 ArgChains.push_back(SDValue(L, 1)); 2992 2993 // Build a tokenfactor for all the chains. 2994 return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other, 2995 &ArgChains[0], ArgChains.size()); 2996} 2997 2998/// getMemsetValue - Vectorized representation of the memset value 2999/// operand. 3000static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG, 3001 DebugLoc dl) { 3002 unsigned NumBits = VT.isVector() ? 3003 VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits(); 3004 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 3005 APInt Val = APInt(NumBits, C->getZExtValue() & 255); 3006 unsigned Shift = 8; 3007 for (unsigned i = NumBits; i > 8; i >>= 1) { 3008 Val = (Val << Shift) | Val; 3009 Shift <<= 1; 3010 } 3011 if (VT.isInteger()) 3012 return DAG.getConstant(Val, VT); 3013 return DAG.getConstantFP(APFloat(Val), VT); 3014 } 3015 3016 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3017 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value); 3018 unsigned Shift = 8; 3019 for (unsigned i = NumBits; i > 8; i >>= 1) { 3020 Value = DAG.getNode(ISD::OR, dl, VT, 3021 DAG.getNode(ISD::SHL, dl, VT, Value, 3022 DAG.getConstant(Shift, 3023 TLI.getShiftAmountTy())), 3024 Value); 3025 Shift <<= 1; 3026 } 3027 3028 return Value; 3029} 3030 3031/// getMemsetStringVal - Similar to getMemsetValue. Except this is only 3032/// used when a memcpy is turned into a memset when the source is a constant 3033/// string ptr. 3034static SDValue getMemsetStringVal(MVT VT, DebugLoc dl, SelectionDAG &DAG, 3035 const TargetLowering &TLI, 3036 std::string &Str, unsigned Offset) { 3037 // Handle vector with all elements zero. 3038 if (Str.empty()) { 3039 if (VT.isInteger()) 3040 return DAG.getConstant(0, VT); 3041 unsigned NumElts = VT.getVectorNumElements(); 3042 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 3043 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, 3044 DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts))); 3045 } 3046 3047 assert(!VT.isVector() && "Can't handle vector type here!"); 3048 unsigned NumBits = VT.getSizeInBits(); 3049 unsigned MSB = NumBits / 8; 3050 uint64_t Val = 0; 3051 if (TLI.isLittleEndian()) 3052 Offset = Offset + MSB - 1; 3053 for (unsigned i = 0; i != MSB; ++i) { 3054 Val = (Val << 8) | (unsigned char)Str[Offset]; 3055 Offset += TLI.isLittleEndian() ? -1 : 1; 3056 } 3057 return DAG.getConstant(Val, VT); 3058} 3059 3060/// getMemBasePlusOffset - Returns base and offset node for the 3061/// 3062static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset, 3063 SelectionDAG &DAG) { 3064 MVT VT = Base.getValueType(); 3065 return DAG.getNode(ISD::ADD, Base.getDebugLoc(), 3066 VT, Base, DAG.getConstant(Offset, VT)); 3067} 3068 3069/// isMemSrcFromString - Returns true if memcpy source is a string constant. 3070/// 3071static bool isMemSrcFromString(SDValue Src, std::string &Str) { 3072 unsigned SrcDelta = 0; 3073 GlobalAddressSDNode *G = NULL; 3074 if (Src.getOpcode() == ISD::GlobalAddress) 3075 G = cast<GlobalAddressSDNode>(Src); 3076 else if (Src.getOpcode() == ISD::ADD && 3077 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 3078 Src.getOperand(1).getOpcode() == ISD::Constant) { 3079 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 3080 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 3081 } 3082 if (!G) 3083 return false; 3084 3085 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal()); 3086 if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false)) 3087 return true; 3088 3089 return false; 3090} 3091 3092/// MeetsMaxMemopRequirement - Determines if the number of memory ops required 3093/// to replace the memset / memcpy is below the threshold. It also returns the 3094/// types of the sequence of memory ops to perform memset / memcpy. 3095static 3096bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps, 3097 SDValue Dst, SDValue Src, 3098 unsigned Limit, uint64_t Size, unsigned &Align, 3099 std::string &Str, bool &isSrcStr, 3100 SelectionDAG &DAG, 3101 const TargetLowering &TLI) { 3102 isSrcStr = isMemSrcFromString(Src, Str); 3103 bool isSrcConst = isa<ConstantSDNode>(Src); 3104 bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses(); 3105 MVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG); 3106 if (VT != MVT::iAny) { 3107 unsigned NewAlign = (unsigned) 3108 TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT()); 3109 // If source is a string constant, this will require an unaligned load. 3110 if (NewAlign > Align && (isSrcConst || AllowUnalign)) { 3111 if (Dst.getOpcode() != ISD::FrameIndex) { 3112 // Can't change destination alignment. It requires a unaligned store. 3113 if (AllowUnalign) 3114 VT = MVT::iAny; 3115 } else { 3116 int FI = cast<FrameIndexSDNode>(Dst)->getIndex(); 3117 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 3118 if (MFI->isFixedObjectIndex(FI)) { 3119 // Can't change destination alignment. It requires a unaligned store. 3120 if (AllowUnalign) 3121 VT = MVT::iAny; 3122 } else { 3123 // Give the stack frame object a larger alignment if needed. 3124 if (MFI->getObjectAlignment(FI) < NewAlign) 3125 MFI->setObjectAlignment(FI, NewAlign); 3126 Align = NewAlign; 3127 } 3128 } 3129 } 3130 } 3131 3132 if (VT == MVT::iAny) { 3133 if (AllowUnalign) { 3134 VT = MVT::i64; 3135 } else { 3136 switch (Align & 7) { 3137 case 0: VT = MVT::i64; break; 3138 case 4: VT = MVT::i32; break; 3139 case 2: VT = MVT::i16; break; 3140 default: VT = MVT::i8; break; 3141 } 3142 } 3143 3144 MVT LVT = MVT::i64; 3145 while (!TLI.isTypeLegal(LVT)) 3146 LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1); 3147 assert(LVT.isInteger()); 3148 3149 if (VT.bitsGT(LVT)) 3150 VT = LVT; 3151 } 3152 3153 unsigned NumMemOps = 0; 3154 while (Size != 0) { 3155 unsigned VTSize = VT.getSizeInBits() / 8; 3156 while (VTSize > Size) { 3157 // For now, only use non-vector load / store's for the left-over pieces. 3158 if (VT.isVector()) { 3159 VT = MVT::i64; 3160 while (!TLI.isTypeLegal(VT)) 3161 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1); 3162 VTSize = VT.getSizeInBits() / 8; 3163 } else { 3164 // This can result in a type that is not legal on the target, e.g. 3165 // 1 or 2 bytes on PPC. 3166 VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1); 3167 VTSize >>= 1; 3168 } 3169 } 3170 3171 if (++NumMemOps > Limit) 3172 return false; 3173 MemOps.push_back(VT); 3174 Size -= VTSize; 3175 } 3176 3177 return true; 3178} 3179 3180static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl, 3181 SDValue Chain, SDValue Dst, 3182 SDValue Src, uint64_t Size, 3183 unsigned Align, bool AlwaysInline, 3184 const Value *DstSV, uint64_t DstSVOff, 3185 const Value *SrcSV, uint64_t SrcSVOff){ 3186 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3187 3188 // Expand memcpy to a series of load and store ops if the size operand falls 3189 // below a certain threshold. 3190 std::vector<MVT> MemOps; 3191 uint64_t Limit = -1ULL; 3192 if (!AlwaysInline) 3193 Limit = TLI.getMaxStoresPerMemcpy(); 3194 unsigned DstAlign = Align; // Destination alignment can change. 3195 std::string Str; 3196 bool CopyFromStr; 3197 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign, 3198 Str, CopyFromStr, DAG, TLI)) 3199 return SDValue(); 3200 3201 3202 bool isZeroStr = CopyFromStr && Str.empty(); 3203 SmallVector<SDValue, 8> OutChains; 3204 unsigned NumMemOps = MemOps.size(); 3205 uint64_t SrcOff = 0, DstOff = 0; 3206 for (unsigned i = 0; i < NumMemOps; i++) { 3207 MVT VT = MemOps[i]; 3208 unsigned VTSize = VT.getSizeInBits() / 8; 3209 SDValue Value, Store; 3210 3211 if (CopyFromStr && (isZeroStr || !VT.isVector())) { 3212 // It's unlikely a store of a vector immediate can be done in a single 3213 // instruction. It would require a load from a constantpool first. 3214 // We also handle store a vector with all zero's. 3215 // FIXME: Handle other cases where store of vector immediate is done in 3216 // a single instruction. 3217 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff); 3218 Store = DAG.getStore(Chain, dl, Value, 3219 getMemBasePlusOffset(Dst, DstOff, DAG), 3220 DstSV, DstSVOff + DstOff, false, DstAlign); 3221 } else { 3222 // The type might not be legal for the target. This should only happen 3223 // if the type is smaller than a legal type, as on PPC, so the right 3224 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 3225 // to Load/Store if NVT==VT. 3226 // FIXME does the case above also need this? 3227 MVT NVT = TLI.getTypeToTransformTo(VT); 3228 assert(NVT.bitsGE(VT)); 3229 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain, 3230 getMemBasePlusOffset(Src, SrcOff, DAG), 3231 SrcSV, SrcSVOff + SrcOff, VT, false, Align); 3232 Store = DAG.getTruncStore(Chain, dl, Value, 3233 getMemBasePlusOffset(Dst, DstOff, DAG), 3234 DstSV, DstSVOff + DstOff, VT, false, DstAlign); 3235 } 3236 OutChains.push_back(Store); 3237 SrcOff += VTSize; 3238 DstOff += VTSize; 3239 } 3240 3241 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3242 &OutChains[0], OutChains.size()); 3243} 3244 3245static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl, 3246 SDValue Chain, SDValue Dst, 3247 SDValue Src, uint64_t Size, 3248 unsigned Align, bool AlwaysInline, 3249 const Value *DstSV, uint64_t DstSVOff, 3250 const Value *SrcSV, uint64_t SrcSVOff){ 3251 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3252 3253 // Expand memmove to a series of load and store ops if the size operand falls 3254 // below a certain threshold. 3255 std::vector<MVT> MemOps; 3256 uint64_t Limit = -1ULL; 3257 if (!AlwaysInline) 3258 Limit = TLI.getMaxStoresPerMemmove(); 3259 unsigned DstAlign = Align; // Destination alignment can change. 3260 std::string Str; 3261 bool CopyFromStr; 3262 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign, 3263 Str, CopyFromStr, DAG, TLI)) 3264 return SDValue(); 3265 3266 uint64_t SrcOff = 0, DstOff = 0; 3267 3268 SmallVector<SDValue, 8> LoadValues; 3269 SmallVector<SDValue, 8> LoadChains; 3270 SmallVector<SDValue, 8> OutChains; 3271 unsigned NumMemOps = MemOps.size(); 3272 for (unsigned i = 0; i < NumMemOps; i++) { 3273 MVT VT = MemOps[i]; 3274 unsigned VTSize = VT.getSizeInBits() / 8; 3275 SDValue Value, Store; 3276 3277 Value = DAG.getLoad(VT, dl, Chain, 3278 getMemBasePlusOffset(Src, SrcOff, DAG), 3279 SrcSV, SrcSVOff + SrcOff, false, Align); 3280 LoadValues.push_back(Value); 3281 LoadChains.push_back(Value.getValue(1)); 3282 SrcOff += VTSize; 3283 } 3284 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3285 &LoadChains[0], LoadChains.size()); 3286 OutChains.clear(); 3287 for (unsigned i = 0; i < NumMemOps; i++) { 3288 MVT VT = MemOps[i]; 3289 unsigned VTSize = VT.getSizeInBits() / 8; 3290 SDValue Value, Store; 3291 3292 Store = DAG.getStore(Chain, dl, LoadValues[i], 3293 getMemBasePlusOffset(Dst, DstOff, DAG), 3294 DstSV, DstSVOff + DstOff, false, DstAlign); 3295 OutChains.push_back(Store); 3296 DstOff += VTSize; 3297 } 3298 3299 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3300 &OutChains[0], OutChains.size()); 3301} 3302 3303static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl, 3304 SDValue Chain, SDValue Dst, 3305 SDValue Src, uint64_t Size, 3306 unsigned Align, 3307 const Value *DstSV, uint64_t DstSVOff) { 3308 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3309 3310 // Expand memset to a series of load/store ops if the size operand 3311 // falls below a certain threshold. 3312 std::vector<MVT> MemOps; 3313 std::string Str; 3314 bool CopyFromStr; 3315 if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(), 3316 Size, Align, Str, CopyFromStr, DAG, TLI)) 3317 return SDValue(); 3318 3319 SmallVector<SDValue, 8> OutChains; 3320 uint64_t DstOff = 0; 3321 3322 unsigned NumMemOps = MemOps.size(); 3323 for (unsigned i = 0; i < NumMemOps; i++) { 3324 MVT VT = MemOps[i]; 3325 unsigned VTSize = VT.getSizeInBits() / 8; 3326 SDValue Value = getMemsetValue(Src, VT, DAG, dl); 3327 SDValue Store = DAG.getStore(Chain, dl, Value, 3328 getMemBasePlusOffset(Dst, DstOff, DAG), 3329 DstSV, DstSVOff + DstOff); 3330 OutChains.push_back(Store); 3331 DstOff += VTSize; 3332 } 3333 3334 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 3335 &OutChains[0], OutChains.size()); 3336} 3337 3338SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst, 3339 SDValue Src, SDValue Size, 3340 unsigned Align, bool AlwaysInline, 3341 const Value *DstSV, uint64_t DstSVOff, 3342 const Value *SrcSV, uint64_t SrcSVOff) { 3343 3344 // Check to see if we should lower the memcpy to loads and stores first. 3345 // For cases within the target-specified limits, this is the best choice. 3346 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 3347 if (ConstantSize) { 3348 // Memcpy with size zero? Just return the original chain. 3349 if (ConstantSize->isNullValue()) 3350 return Chain; 3351 3352 SDValue Result = 3353 getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 3354 ConstantSize->getZExtValue(), 3355 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff); 3356 if (Result.getNode()) 3357 return Result; 3358 } 3359 3360 // Then check to see if we should lower the memcpy with target-specific 3361 // code. If the target chooses to do this, this is the next best. 3362 SDValue Result = 3363 TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align, 3364 AlwaysInline, 3365 DstSV, DstSVOff, SrcSV, SrcSVOff); 3366 if (Result.getNode()) 3367 return Result; 3368 3369 // If we really need inline code and the target declined to provide it, 3370 // use a (potentially long) sequence of loads and stores. 3371 if (AlwaysInline) { 3372 assert(ConstantSize && "AlwaysInline requires a constant size!"); 3373 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 3374 ConstantSize->getZExtValue(), Align, true, 3375 DstSV, DstSVOff, SrcSV, SrcSVOff); 3376 } 3377 3378 // Emit a library call. 3379 TargetLowering::ArgListTy Args; 3380 TargetLowering::ArgListEntry Entry; 3381 Entry.Ty = TLI.getTargetData()->getIntPtrType(); 3382 Entry.Node = Dst; Args.push_back(Entry); 3383 Entry.Node = Src; Args.push_back(Entry); 3384 Entry.Node = Size; Args.push_back(Entry); 3385 // FIXME: pass in DebugLoc 3386 std::pair<SDValue,SDValue> CallResult = 3387 TLI.LowerCallTo(Chain, Type::VoidTy, 3388 false, false, false, false, 0, CallingConv::C, false, 3389 /*isReturnValueUsed=*/false, 3390 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY), 3391 TLI.getPointerTy()), 3392 Args, *this, dl); 3393 return CallResult.second; 3394} 3395 3396SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst, 3397 SDValue Src, SDValue Size, 3398 unsigned Align, 3399 const Value *DstSV, uint64_t DstSVOff, 3400 const Value *SrcSV, uint64_t SrcSVOff) { 3401 3402 // Check to see if we should lower the memmove to loads and stores first. 3403 // For cases within the target-specified limits, this is the best choice. 3404 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 3405 if (ConstantSize) { 3406 // Memmove with size zero? Just return the original chain. 3407 if (ConstantSize->isNullValue()) 3408 return Chain; 3409 3410 SDValue Result = 3411 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src, 3412 ConstantSize->getZExtValue(), 3413 Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff); 3414 if (Result.getNode()) 3415 return Result; 3416 } 3417 3418 // Then check to see if we should lower the memmove with target-specific 3419 // code. If the target chooses to do this, this is the next best. 3420 SDValue Result = 3421 TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align, 3422 DstSV, DstSVOff, SrcSV, SrcSVOff); 3423 if (Result.getNode()) 3424 return Result; 3425 3426 // Emit a library call. 3427 TargetLowering::ArgListTy Args; 3428 TargetLowering::ArgListEntry Entry; 3429 Entry.Ty = TLI.getTargetData()->getIntPtrType(); 3430 Entry.Node = Dst; Args.push_back(Entry); 3431 Entry.Node = Src; Args.push_back(Entry); 3432 Entry.Node = Size; Args.push_back(Entry); 3433 // FIXME: pass in DebugLoc 3434 std::pair<SDValue,SDValue> CallResult = 3435 TLI.LowerCallTo(Chain, Type::VoidTy, 3436 false, false, false, false, 0, CallingConv::C, false, 3437 /*isReturnValueUsed=*/false, 3438 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE), 3439 TLI.getPointerTy()), 3440 Args, *this, dl); 3441 return CallResult.second; 3442} 3443 3444SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst, 3445 SDValue Src, SDValue Size, 3446 unsigned Align, 3447 const Value *DstSV, uint64_t DstSVOff) { 3448 3449 // Check to see if we should lower the memset to stores first. 3450 // For cases within the target-specified limits, this is the best choice. 3451 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 3452 if (ConstantSize) { 3453 // Memset with size zero? Just return the original chain. 3454 if (ConstantSize->isNullValue()) 3455 return Chain; 3456 3457 SDValue Result = 3458 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), 3459 Align, DstSV, DstSVOff); 3460 if (Result.getNode()) 3461 return Result; 3462 } 3463 3464 // Then check to see if we should lower the memset with target-specific 3465 // code. If the target chooses to do this, this is the next best. 3466 SDValue Result = 3467 TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align, 3468 DstSV, DstSVOff); 3469 if (Result.getNode()) 3470 return Result; 3471 3472 // Emit a library call. 3473 const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(); 3474 TargetLowering::ArgListTy Args; 3475 TargetLowering::ArgListEntry Entry; 3476 Entry.Node = Dst; Entry.Ty = IntPtrTy; 3477 Args.push_back(Entry); 3478 // Extend or truncate the argument to be an i32 value for the call. 3479 if (Src.getValueType().bitsGT(MVT::i32)) 3480 Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src); 3481 else 3482 Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src); 3483 Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true; 3484 Args.push_back(Entry); 3485 Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false; 3486 Args.push_back(Entry); 3487 // FIXME: pass in DebugLoc 3488 std::pair<SDValue,SDValue> CallResult = 3489 TLI.LowerCallTo(Chain, Type::VoidTy, 3490 false, false, false, false, 0, CallingConv::C, false, 3491 /*isReturnValueUsed=*/false, 3492 getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET), 3493 TLI.getPointerTy()), 3494 Args, *this, dl); 3495 return CallResult.second; 3496} 3497 3498SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT, 3499 SDValue Chain, 3500 SDValue Ptr, SDValue Cmp, 3501 SDValue Swp, const Value* PtrVal, 3502 unsigned Alignment) { 3503 assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op"); 3504 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 3505 3506 MVT VT = Cmp.getValueType(); 3507 3508 if (Alignment == 0) // Ensure that codegen never sees alignment 0 3509 Alignment = getMVTAlignment(MemVT); 3510 3511 SDVTList VTs = getVTList(VT, MVT::Other); 3512 FoldingSetNodeID ID; 3513 ID.AddInteger(MemVT.getRawBits()); 3514 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 3515 AddNodeIDNode(ID, Opcode, VTs, Ops, 4); 3516 void* IP = 0; 3517 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3518 return SDValue(E, 0); 3519 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>(); 3520 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, 3521 Chain, Ptr, Cmp, Swp, PtrVal, Alignment); 3522 CSEMap.InsertNode(N, IP); 3523 AllNodes.push_back(N); 3524 return SDValue(N, 0); 3525} 3526 3527SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT, 3528 SDValue Chain, 3529 SDValue Ptr, SDValue Val, 3530 const Value* PtrVal, 3531 unsigned Alignment) { 3532 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 3533 Opcode == ISD::ATOMIC_LOAD_SUB || 3534 Opcode == ISD::ATOMIC_LOAD_AND || 3535 Opcode == ISD::ATOMIC_LOAD_OR || 3536 Opcode == ISD::ATOMIC_LOAD_XOR || 3537 Opcode == ISD::ATOMIC_LOAD_NAND || 3538 Opcode == ISD::ATOMIC_LOAD_MIN || 3539 Opcode == ISD::ATOMIC_LOAD_MAX || 3540 Opcode == ISD::ATOMIC_LOAD_UMIN || 3541 Opcode == ISD::ATOMIC_LOAD_UMAX || 3542 Opcode == ISD::ATOMIC_SWAP) && 3543 "Invalid Atomic Op"); 3544 3545 MVT VT = Val.getValueType(); 3546 3547 if (Alignment == 0) // Ensure that codegen never sees alignment 0 3548 Alignment = getMVTAlignment(MemVT); 3549 3550 SDVTList VTs = getVTList(VT, MVT::Other); 3551 FoldingSetNodeID ID; 3552 ID.AddInteger(MemVT.getRawBits()); 3553 SDValue Ops[] = {Chain, Ptr, Val}; 3554 AddNodeIDNode(ID, Opcode, VTs, Ops, 3); 3555 void* IP = 0; 3556 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3557 return SDValue(E, 0); 3558 SDNode* N = NodeAllocator.Allocate<AtomicSDNode>(); 3559 new (N) AtomicSDNode(Opcode, dl, VTs, MemVT, 3560 Chain, Ptr, Val, PtrVal, Alignment); 3561 CSEMap.InsertNode(N, IP); 3562 AllNodes.push_back(N); 3563 return SDValue(N, 0); 3564} 3565 3566/// getMergeValues - Create a MERGE_VALUES node from the given operands. 3567/// Allowed to return something different (and simpler) if Simplify is true. 3568SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps, 3569 DebugLoc dl) { 3570 if (NumOps == 1) 3571 return Ops[0]; 3572 3573 SmallVector<MVT, 4> VTs; 3574 VTs.reserve(NumOps); 3575 for (unsigned i = 0; i < NumOps; ++i) 3576 VTs.push_back(Ops[i].getValueType()); 3577 return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps), 3578 Ops, NumOps); 3579} 3580 3581SDValue 3582SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, 3583 const MVT *VTs, unsigned NumVTs, 3584 const SDValue *Ops, unsigned NumOps, 3585 MVT MemVT, const Value *srcValue, int SVOff, 3586 unsigned Align, bool Vol, 3587 bool ReadMem, bool WriteMem) { 3588 return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps, 3589 MemVT, srcValue, SVOff, Align, Vol, 3590 ReadMem, WriteMem); 3591} 3592 3593SDValue 3594SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList, 3595 const SDValue *Ops, unsigned NumOps, 3596 MVT MemVT, const Value *srcValue, int SVOff, 3597 unsigned Align, bool Vol, 3598 bool ReadMem, bool WriteMem) { 3599 // Memoize the node unless it returns a flag. 3600 MemIntrinsicSDNode *N; 3601 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) { 3602 FoldingSetNodeID ID; 3603 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps); 3604 void *IP = 0; 3605 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3606 return SDValue(E, 0); 3607 3608 N = NodeAllocator.Allocate<MemIntrinsicSDNode>(); 3609 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, 3610 srcValue, SVOff, Align, Vol, ReadMem, WriteMem); 3611 CSEMap.InsertNode(N, IP); 3612 } else { 3613 N = NodeAllocator.Allocate<MemIntrinsicSDNode>(); 3614 new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT, 3615 srcValue, SVOff, Align, Vol, ReadMem, WriteMem); 3616 } 3617 AllNodes.push_back(N); 3618 return SDValue(N, 0); 3619} 3620 3621SDValue 3622SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl, 3623 ISD::LoadExtType ExtType, MVT VT, SDValue Chain, 3624 SDValue Ptr, SDValue Offset, 3625 const Value *SV, int SVOffset, MVT EVT, 3626 bool isVolatile, unsigned Alignment) { 3627 if (Alignment == 0) // Ensure that codegen never sees alignment 0 3628 Alignment = getMVTAlignment(VT); 3629 3630 if (VT == EVT) { 3631 ExtType = ISD::NON_EXTLOAD; 3632 } else if (ExtType == ISD::NON_EXTLOAD) { 3633 assert(VT == EVT && "Non-extending load from different memory type!"); 3634 } else { 3635 // Extending load. 3636 if (VT.isVector()) 3637 assert(EVT.getVectorNumElements() == VT.getVectorNumElements() && 3638 "Invalid vector extload!"); 3639 else 3640 assert(EVT.bitsLT(VT) && 3641 "Should only be an extending load, not truncating!"); 3642 assert((ExtType == ISD::EXTLOAD || VT.isInteger()) && 3643 "Cannot sign/zero extend a FP/Vector load!"); 3644 assert(VT.isInteger() == EVT.isInteger() && 3645 "Cannot convert from FP to Int or Int -> FP!"); 3646 } 3647 3648 bool Indexed = AM != ISD::UNINDEXED; 3649 assert((Indexed || Offset.getOpcode() == ISD::UNDEF) && 3650 "Unindexed load with an offset!"); 3651 3652 SDVTList VTs = Indexed ? 3653 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 3654 SDValue Ops[] = { Chain, Ptr, Offset }; 3655 FoldingSetNodeID ID; 3656 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3); 3657 ID.AddInteger(EVT.getRawBits()); 3658 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, isVolatile, Alignment)); 3659 void *IP = 0; 3660 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3661 return SDValue(E, 0); 3662 SDNode *N = NodeAllocator.Allocate<LoadSDNode>(); 3663 new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, EVT, SV, SVOffset, 3664 Alignment, isVolatile); 3665 CSEMap.InsertNode(N, IP); 3666 AllNodes.push_back(N); 3667 return SDValue(N, 0); 3668} 3669 3670SDValue SelectionDAG::getLoad(MVT VT, DebugLoc dl, 3671 SDValue Chain, SDValue Ptr, 3672 const Value *SV, int SVOffset, 3673 bool isVolatile, unsigned Alignment) { 3674 SDValue Undef = getUNDEF(Ptr.getValueType()); 3675 return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef, 3676 SV, SVOffset, VT, isVolatile, Alignment); 3677} 3678 3679SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, MVT VT, 3680 SDValue Chain, SDValue Ptr, 3681 const Value *SV, 3682 int SVOffset, MVT EVT, 3683 bool isVolatile, unsigned Alignment) { 3684 SDValue Undef = getUNDEF(Ptr.getValueType()); 3685 return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef, 3686 SV, SVOffset, EVT, isVolatile, Alignment); 3687} 3688 3689SDValue 3690SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base, 3691 SDValue Offset, ISD::MemIndexedMode AM) { 3692 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 3693 assert(LD->getOffset().getOpcode() == ISD::UNDEF && 3694 "Load is already a indexed load!"); 3695 return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(), 3696 LD->getChain(), Base, Offset, LD->getSrcValue(), 3697 LD->getSrcValueOffset(), LD->getMemoryVT(), 3698 LD->isVolatile(), LD->getAlignment()); 3699} 3700 3701SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val, 3702 SDValue Ptr, const Value *SV, int SVOffset, 3703 bool isVolatile, unsigned Alignment) { 3704 MVT VT = Val.getValueType(); 3705 3706 if (Alignment == 0) // Ensure that codegen never sees alignment 0 3707 Alignment = getMVTAlignment(VT); 3708 3709 SDVTList VTs = getVTList(MVT::Other); 3710 SDValue Undef = getUNDEF(Ptr.getValueType()); 3711 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 3712 FoldingSetNodeID ID; 3713 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4); 3714 ID.AddInteger(VT.getRawBits()); 3715 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, 3716 isVolatile, Alignment)); 3717 void *IP = 0; 3718 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3719 return SDValue(E, 0); 3720 SDNode *N = NodeAllocator.Allocate<StoreSDNode>(); 3721 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false, 3722 VT, SV, SVOffset, Alignment, isVolatile); 3723 CSEMap.InsertNode(N, IP); 3724 AllNodes.push_back(N); 3725 return SDValue(N, 0); 3726} 3727 3728SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val, 3729 SDValue Ptr, const Value *SV, 3730 int SVOffset, MVT SVT, 3731 bool isVolatile, unsigned Alignment) { 3732 MVT VT = Val.getValueType(); 3733 3734 if (VT == SVT) 3735 return getStore(Chain, dl, Val, Ptr, SV, SVOffset, isVolatile, Alignment); 3736 3737 assert(VT.bitsGT(SVT) && "Not a truncation?"); 3738 assert(VT.isInteger() == SVT.isInteger() && 3739 "Can't do FP-INT conversion!"); 3740 3741 if (Alignment == 0) // Ensure that codegen never sees alignment 0 3742 Alignment = getMVTAlignment(VT); 3743 3744 SDVTList VTs = getVTList(MVT::Other); 3745 SDValue Undef = getUNDEF(Ptr.getValueType()); 3746 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 3747 FoldingSetNodeID ID; 3748 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4); 3749 ID.AddInteger(SVT.getRawBits()); 3750 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, 3751 isVolatile, Alignment)); 3752 void *IP = 0; 3753 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3754 return SDValue(E, 0); 3755 SDNode *N = NodeAllocator.Allocate<StoreSDNode>(); 3756 new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true, 3757 SVT, SV, SVOffset, Alignment, isVolatile); 3758 CSEMap.InsertNode(N, IP); 3759 AllNodes.push_back(N); 3760 return SDValue(N, 0); 3761} 3762 3763SDValue 3764SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base, 3765 SDValue Offset, ISD::MemIndexedMode AM) { 3766 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 3767 assert(ST->getOffset().getOpcode() == ISD::UNDEF && 3768 "Store is already a indexed store!"); 3769 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 3770 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 3771 FoldingSetNodeID ID; 3772 AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4); 3773 ID.AddInteger(ST->getMemoryVT().getRawBits()); 3774 ID.AddInteger(ST->getRawSubclassData()); 3775 void *IP = 0; 3776 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3777 return SDValue(E, 0); 3778 SDNode *N = NodeAllocator.Allocate<StoreSDNode>(); 3779 new (N) StoreSDNode(Ops, dl, VTs, AM, 3780 ST->isTruncatingStore(), ST->getMemoryVT(), 3781 ST->getSrcValue(), ST->getSrcValueOffset(), 3782 ST->getAlignment(), ST->isVolatile()); 3783 CSEMap.InsertNode(N, IP); 3784 AllNodes.push_back(N); 3785 return SDValue(N, 0); 3786} 3787 3788SDValue SelectionDAG::getVAArg(MVT VT, DebugLoc dl, 3789 SDValue Chain, SDValue Ptr, 3790 SDValue SV) { 3791 SDValue Ops[] = { Chain, Ptr, SV }; 3792 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3); 3793} 3794 3795SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT, 3796 const SDUse *Ops, unsigned NumOps) { 3797 switch (NumOps) { 3798 case 0: return getNode(Opcode, DL, VT); 3799 case 1: return getNode(Opcode, DL, VT, Ops[0]); 3800 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 3801 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 3802 default: break; 3803 } 3804 3805 // Copy from an SDUse array into an SDValue array for use with 3806 // the regular getNode logic. 3807 SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps); 3808 return getNode(Opcode, DL, VT, &NewOps[0], NumOps); 3809} 3810 3811SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT, 3812 const SDValue *Ops, unsigned NumOps) { 3813 switch (NumOps) { 3814 case 0: return getNode(Opcode, DL, VT); 3815 case 1: return getNode(Opcode, DL, VT, Ops[0]); 3816 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 3817 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 3818 default: break; 3819 } 3820 3821 switch (Opcode) { 3822 default: break; 3823 case ISD::SELECT_CC: { 3824 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 3825 assert(Ops[0].getValueType() == Ops[1].getValueType() && 3826 "LHS and RHS of condition must have same type!"); 3827 assert(Ops[2].getValueType() == Ops[3].getValueType() && 3828 "True and False arms of SelectCC must have same type!"); 3829 assert(Ops[2].getValueType() == VT && 3830 "select_cc node must be of same type as true and false value!"); 3831 break; 3832 } 3833 case ISD::BR_CC: { 3834 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 3835 assert(Ops[2].getValueType() == Ops[3].getValueType() && 3836 "LHS/RHS of comparison should match types!"); 3837 break; 3838 } 3839 } 3840 3841 // Memoize nodes. 3842 SDNode *N; 3843 SDVTList VTs = getVTList(VT); 3844 3845 if (VT != MVT::Flag) { 3846 FoldingSetNodeID ID; 3847 AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps); 3848 void *IP = 0; 3849 3850 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3851 return SDValue(E, 0); 3852 3853 N = NodeAllocator.Allocate<SDNode>(); 3854 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps); 3855 CSEMap.InsertNode(N, IP); 3856 } else { 3857 N = NodeAllocator.Allocate<SDNode>(); 3858 new (N) SDNode(Opcode, DL, VTs, Ops, NumOps); 3859 } 3860 3861 AllNodes.push_back(N); 3862#ifndef NDEBUG 3863 VerifyNode(N); 3864#endif 3865 return SDValue(N, 0); 3866} 3867 3868SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, 3869 const std::vector<MVT> &ResultTys, 3870 const SDValue *Ops, unsigned NumOps) { 3871 return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()), 3872 Ops, NumOps); 3873} 3874 3875SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, 3876 const MVT *VTs, unsigned NumVTs, 3877 const SDValue *Ops, unsigned NumOps) { 3878 if (NumVTs == 1) 3879 return getNode(Opcode, DL, VTs[0], Ops, NumOps); 3880 return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps); 3881} 3882 3883SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList, 3884 const SDValue *Ops, unsigned NumOps) { 3885 if (VTList.NumVTs == 1) 3886 return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps); 3887 3888#if 0 3889 switch (Opcode) { 3890 // FIXME: figure out how to safely handle things like 3891 // int foo(int x) { return 1 << (x & 255); } 3892 // int bar() { return foo(256); } 3893 case ISD::SRA_PARTS: 3894 case ISD::SRL_PARTS: 3895 case ISD::SHL_PARTS: 3896 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 3897 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 3898 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 3899 else if (N3.getOpcode() == ISD::AND) 3900 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 3901 // If the and is only masking out bits that cannot effect the shift, 3902 // eliminate the and. 3903 unsigned NumBits = VT.getSizeInBits()*2; 3904 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 3905 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 3906 } 3907 break; 3908 } 3909#endif 3910 3911 // Memoize the node unless it returns a flag. 3912 SDNode *N; 3913 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) { 3914 FoldingSetNodeID ID; 3915 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps); 3916 void *IP = 0; 3917 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 3918 return SDValue(E, 0); 3919 if (NumOps == 1) { 3920 N = NodeAllocator.Allocate<UnarySDNode>(); 3921 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]); 3922 } else if (NumOps == 2) { 3923 N = NodeAllocator.Allocate<BinarySDNode>(); 3924 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]); 3925 } else if (NumOps == 3) { 3926 N = NodeAllocator.Allocate<TernarySDNode>(); 3927 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]); 3928 } else { 3929 N = NodeAllocator.Allocate<SDNode>(); 3930 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps); 3931 } 3932 CSEMap.InsertNode(N, IP); 3933 } else { 3934 if (NumOps == 1) { 3935 N = NodeAllocator.Allocate<UnarySDNode>(); 3936 new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]); 3937 } else if (NumOps == 2) { 3938 N = NodeAllocator.Allocate<BinarySDNode>(); 3939 new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]); 3940 } else if (NumOps == 3) { 3941 N = NodeAllocator.Allocate<TernarySDNode>(); 3942 new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]); 3943 } else { 3944 N = NodeAllocator.Allocate<SDNode>(); 3945 new (N) SDNode(Opcode, DL, VTList, Ops, NumOps); 3946 } 3947 } 3948 AllNodes.push_back(N); 3949#ifndef NDEBUG 3950 VerifyNode(N); 3951#endif 3952 return SDValue(N, 0); 3953} 3954 3955SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) { 3956 return getNode(Opcode, DL, VTList, 0, 0); 3957} 3958 3959SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList, 3960 SDValue N1) { 3961 SDValue Ops[] = { N1 }; 3962 return getNode(Opcode, DL, VTList, Ops, 1); 3963} 3964 3965SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList, 3966 SDValue N1, SDValue N2) { 3967 SDValue Ops[] = { N1, N2 }; 3968 return getNode(Opcode, DL, VTList, Ops, 2); 3969} 3970 3971SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList, 3972 SDValue N1, SDValue N2, SDValue N3) { 3973 SDValue Ops[] = { N1, N2, N3 }; 3974 return getNode(Opcode, DL, VTList, Ops, 3); 3975} 3976 3977SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList, 3978 SDValue N1, SDValue N2, SDValue N3, 3979 SDValue N4) { 3980 SDValue Ops[] = { N1, N2, N3, N4 }; 3981 return getNode(Opcode, DL, VTList, Ops, 4); 3982} 3983 3984SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList, 3985 SDValue N1, SDValue N2, SDValue N3, 3986 SDValue N4, SDValue N5) { 3987 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 3988 return getNode(Opcode, DL, VTList, Ops, 5); 3989} 3990 3991SDVTList SelectionDAG::getVTList(MVT VT) { 3992 return makeVTList(SDNode::getValueTypeList(VT), 1); 3993} 3994 3995SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) { 3996 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(), 3997 E = VTList.rend(); I != E; ++I) 3998 if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2) 3999 return *I; 4000 4001 MVT *Array = Allocator.Allocate<MVT>(2); 4002 Array[0] = VT1; 4003 Array[1] = VT2; 4004 SDVTList Result = makeVTList(Array, 2); 4005 VTList.push_back(Result); 4006 return Result; 4007} 4008 4009SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) { 4010 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(), 4011 E = VTList.rend(); I != E; ++I) 4012 if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 && 4013 I->VTs[2] == VT3) 4014 return *I; 4015 4016 MVT *Array = Allocator.Allocate<MVT>(3); 4017 Array[0] = VT1; 4018 Array[1] = VT2; 4019 Array[2] = VT3; 4020 SDVTList Result = makeVTList(Array, 3); 4021 VTList.push_back(Result); 4022 return Result; 4023} 4024 4025SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3, MVT VT4) { 4026 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(), 4027 E = VTList.rend(); I != E; ++I) 4028 if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 && 4029 I->VTs[2] == VT3 && I->VTs[3] == VT4) 4030 return *I; 4031 4032 MVT *Array = Allocator.Allocate<MVT>(3); 4033 Array[0] = VT1; 4034 Array[1] = VT2; 4035 Array[2] = VT3; 4036 Array[3] = VT4; 4037 SDVTList Result = makeVTList(Array, 4); 4038 VTList.push_back(Result); 4039 return Result; 4040} 4041 4042SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) { 4043 switch (NumVTs) { 4044 case 0: llvm_unreachable("Cannot have nodes without results!"); 4045 case 1: return getVTList(VTs[0]); 4046 case 2: return getVTList(VTs[0], VTs[1]); 4047 case 3: return getVTList(VTs[0], VTs[1], VTs[2]); 4048 default: break; 4049 } 4050 4051 for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(), 4052 E = VTList.rend(); I != E; ++I) { 4053 if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1]) 4054 continue; 4055 4056 bool NoMatch = false; 4057 for (unsigned i = 2; i != NumVTs; ++i) 4058 if (VTs[i] != I->VTs[i]) { 4059 NoMatch = true; 4060 break; 4061 } 4062 if (!NoMatch) 4063 return *I; 4064 } 4065 4066 MVT *Array = Allocator.Allocate<MVT>(NumVTs); 4067 std::copy(VTs, VTs+NumVTs, Array); 4068 SDVTList Result = makeVTList(Array, NumVTs); 4069 VTList.push_back(Result); 4070 return Result; 4071} 4072 4073 4074/// UpdateNodeOperands - *Mutate* the specified node in-place to have the 4075/// specified operands. If the resultant node already exists in the DAG, 4076/// this does not modify the specified node, instead it returns the node that 4077/// already exists. If the resultant node does not exist in the DAG, the 4078/// input node is returned. As a degenerate case, if you specify the same 4079/// input operands as the node already has, the input node is returned. 4080SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) { 4081 SDNode *N = InN.getNode(); 4082 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 4083 4084 // Check to see if there is no change. 4085 if (Op == N->getOperand(0)) return InN; 4086 4087 // See if the modified node already exists. 4088 void *InsertPos = 0; 4089 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 4090 return SDValue(Existing, InN.getResNo()); 4091 4092 // Nope it doesn't. Remove the node from its current place in the maps. 4093 if (InsertPos) 4094 if (!RemoveNodeFromCSEMaps(N)) 4095 InsertPos = 0; 4096 4097 // Now we update the operands. 4098 N->OperandList[0].set(Op); 4099 4100 // If this gets put into a CSE map, add it. 4101 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 4102 return InN; 4103} 4104 4105SDValue SelectionDAG:: 4106UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) { 4107 SDNode *N = InN.getNode(); 4108 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 4109 4110 // Check to see if there is no change. 4111 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 4112 return InN; // No operands changed, just return the input node. 4113 4114 // See if the modified node already exists. 4115 void *InsertPos = 0; 4116 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 4117 return SDValue(Existing, InN.getResNo()); 4118 4119 // Nope it doesn't. Remove the node from its current place in the maps. 4120 if (InsertPos) 4121 if (!RemoveNodeFromCSEMaps(N)) 4122 InsertPos = 0; 4123 4124 // Now we update the operands. 4125 if (N->OperandList[0] != Op1) 4126 N->OperandList[0].set(Op1); 4127 if (N->OperandList[1] != Op2) 4128 N->OperandList[1].set(Op2); 4129 4130 // If this gets put into a CSE map, add it. 4131 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 4132 return InN; 4133} 4134 4135SDValue SelectionDAG:: 4136UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) { 4137 SDValue Ops[] = { Op1, Op2, Op3 }; 4138 return UpdateNodeOperands(N, Ops, 3); 4139} 4140 4141SDValue SelectionDAG:: 4142UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, 4143 SDValue Op3, SDValue Op4) { 4144 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 4145 return UpdateNodeOperands(N, Ops, 4); 4146} 4147 4148SDValue SelectionDAG:: 4149UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, 4150 SDValue Op3, SDValue Op4, SDValue Op5) { 4151 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 4152 return UpdateNodeOperands(N, Ops, 5); 4153} 4154 4155SDValue SelectionDAG:: 4156UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) { 4157 SDNode *N = InN.getNode(); 4158 assert(N->getNumOperands() == NumOps && 4159 "Update with wrong number of operands"); 4160 4161 // Check to see if there is no change. 4162 bool AnyChange = false; 4163 for (unsigned i = 0; i != NumOps; ++i) { 4164 if (Ops[i] != N->getOperand(i)) { 4165 AnyChange = true; 4166 break; 4167 } 4168 } 4169 4170 // No operands changed, just return the input node. 4171 if (!AnyChange) return InN; 4172 4173 // See if the modified node already exists. 4174 void *InsertPos = 0; 4175 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos)) 4176 return SDValue(Existing, InN.getResNo()); 4177 4178 // Nope it doesn't. Remove the node from its current place in the maps. 4179 if (InsertPos) 4180 if (!RemoveNodeFromCSEMaps(N)) 4181 InsertPos = 0; 4182 4183 // Now we update the operands. 4184 for (unsigned i = 0; i != NumOps; ++i) 4185 if (N->OperandList[i] != Ops[i]) 4186 N->OperandList[i].set(Ops[i]); 4187 4188 // If this gets put into a CSE map, add it. 4189 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 4190 return InN; 4191} 4192 4193/// DropOperands - Release the operands and set this node to have 4194/// zero operands. 4195void SDNode::DropOperands() { 4196 // Unlike the code in MorphNodeTo that does this, we don't need to 4197 // watch for dead nodes here. 4198 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 4199 SDUse &Use = *I++; 4200 Use.set(SDValue()); 4201 } 4202} 4203 4204/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 4205/// machine opcode. 4206/// 4207SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4208 MVT VT) { 4209 SDVTList VTs = getVTList(VT); 4210 return SelectNodeTo(N, MachineOpc, VTs, 0, 0); 4211} 4212 4213SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4214 MVT VT, SDValue Op1) { 4215 SDVTList VTs = getVTList(VT); 4216 SDValue Ops[] = { Op1 }; 4217 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1); 4218} 4219 4220SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4221 MVT VT, SDValue Op1, 4222 SDValue Op2) { 4223 SDVTList VTs = getVTList(VT); 4224 SDValue Ops[] = { Op1, Op2 }; 4225 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2); 4226} 4227 4228SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4229 MVT VT, SDValue Op1, 4230 SDValue Op2, SDValue Op3) { 4231 SDVTList VTs = getVTList(VT); 4232 SDValue Ops[] = { Op1, Op2, Op3 }; 4233 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3); 4234} 4235 4236SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4237 MVT VT, const SDValue *Ops, 4238 unsigned NumOps) { 4239 SDVTList VTs = getVTList(VT); 4240 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps); 4241} 4242 4243SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4244 MVT VT1, MVT VT2, const SDValue *Ops, 4245 unsigned NumOps) { 4246 SDVTList VTs = getVTList(VT1, VT2); 4247 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps); 4248} 4249 4250SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4251 MVT VT1, MVT VT2) { 4252 SDVTList VTs = getVTList(VT1, VT2); 4253 return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0); 4254} 4255 4256SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4257 MVT VT1, MVT VT2, MVT VT3, 4258 const SDValue *Ops, unsigned NumOps) { 4259 SDVTList VTs = getVTList(VT1, VT2, VT3); 4260 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps); 4261} 4262 4263SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4264 MVT VT1, MVT VT2, MVT VT3, MVT VT4, 4265 const SDValue *Ops, unsigned NumOps) { 4266 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4); 4267 return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps); 4268} 4269 4270SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4271 MVT VT1, MVT VT2, 4272 SDValue Op1) { 4273 SDVTList VTs = getVTList(VT1, VT2); 4274 SDValue Ops[] = { Op1 }; 4275 return SelectNodeTo(N, MachineOpc, VTs, Ops, 1); 4276} 4277 4278SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4279 MVT VT1, MVT VT2, 4280 SDValue Op1, SDValue Op2) { 4281 SDVTList VTs = getVTList(VT1, VT2); 4282 SDValue Ops[] = { Op1, Op2 }; 4283 return SelectNodeTo(N, MachineOpc, VTs, Ops, 2); 4284} 4285 4286SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4287 MVT VT1, MVT VT2, 4288 SDValue Op1, SDValue Op2, 4289 SDValue Op3) { 4290 SDVTList VTs = getVTList(VT1, VT2); 4291 SDValue Ops[] = { Op1, Op2, Op3 }; 4292 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3); 4293} 4294 4295SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4296 MVT VT1, MVT VT2, MVT VT3, 4297 SDValue Op1, SDValue Op2, 4298 SDValue Op3) { 4299 SDVTList VTs = getVTList(VT1, VT2, VT3); 4300 SDValue Ops[] = { Op1, Op2, Op3 }; 4301 return SelectNodeTo(N, MachineOpc, VTs, Ops, 3); 4302} 4303 4304SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 4305 SDVTList VTs, const SDValue *Ops, 4306 unsigned NumOps) { 4307 return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps); 4308} 4309 4310SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4311 MVT VT) { 4312 SDVTList VTs = getVTList(VT); 4313 return MorphNodeTo(N, Opc, VTs, 0, 0); 4314} 4315 4316SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4317 MVT VT, SDValue Op1) { 4318 SDVTList VTs = getVTList(VT); 4319 SDValue Ops[] = { Op1 }; 4320 return MorphNodeTo(N, Opc, VTs, Ops, 1); 4321} 4322 4323SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4324 MVT VT, SDValue Op1, 4325 SDValue Op2) { 4326 SDVTList VTs = getVTList(VT); 4327 SDValue Ops[] = { Op1, Op2 }; 4328 return MorphNodeTo(N, Opc, VTs, Ops, 2); 4329} 4330 4331SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4332 MVT VT, SDValue Op1, 4333 SDValue Op2, SDValue Op3) { 4334 SDVTList VTs = getVTList(VT); 4335 SDValue Ops[] = { Op1, Op2, Op3 }; 4336 return MorphNodeTo(N, Opc, VTs, Ops, 3); 4337} 4338 4339SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4340 MVT VT, const SDValue *Ops, 4341 unsigned NumOps) { 4342 SDVTList VTs = getVTList(VT); 4343 return MorphNodeTo(N, Opc, VTs, Ops, NumOps); 4344} 4345 4346SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4347 MVT VT1, MVT VT2, const SDValue *Ops, 4348 unsigned NumOps) { 4349 SDVTList VTs = getVTList(VT1, VT2); 4350 return MorphNodeTo(N, Opc, VTs, Ops, NumOps); 4351} 4352 4353SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4354 MVT VT1, MVT VT2) { 4355 SDVTList VTs = getVTList(VT1, VT2); 4356 return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0); 4357} 4358 4359SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4360 MVT VT1, MVT VT2, MVT VT3, 4361 const SDValue *Ops, unsigned NumOps) { 4362 SDVTList VTs = getVTList(VT1, VT2, VT3); 4363 return MorphNodeTo(N, Opc, VTs, Ops, NumOps); 4364} 4365 4366SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4367 MVT VT1, MVT VT2, 4368 SDValue Op1) { 4369 SDVTList VTs = getVTList(VT1, VT2); 4370 SDValue Ops[] = { Op1 }; 4371 return MorphNodeTo(N, Opc, VTs, Ops, 1); 4372} 4373 4374SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4375 MVT VT1, MVT VT2, 4376 SDValue Op1, SDValue Op2) { 4377 SDVTList VTs = getVTList(VT1, VT2); 4378 SDValue Ops[] = { Op1, Op2 }; 4379 return MorphNodeTo(N, Opc, VTs, Ops, 2); 4380} 4381 4382SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4383 MVT VT1, MVT VT2, 4384 SDValue Op1, SDValue Op2, 4385 SDValue Op3) { 4386 SDVTList VTs = getVTList(VT1, VT2); 4387 SDValue Ops[] = { Op1, Op2, Op3 }; 4388 return MorphNodeTo(N, Opc, VTs, Ops, 3); 4389} 4390 4391/// MorphNodeTo - These *mutate* the specified node to have the specified 4392/// return type, opcode, and operands. 4393/// 4394/// Note that MorphNodeTo returns the resultant node. If there is already a 4395/// node of the specified opcode and operands, it returns that node instead of 4396/// the current one. Note that the DebugLoc need not be the same. 4397/// 4398/// Using MorphNodeTo is faster than creating a new node and swapping it in 4399/// with ReplaceAllUsesWith both because it often avoids allocating a new 4400/// node, and because it doesn't require CSE recalculation for any of 4401/// the node's users. 4402/// 4403SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 4404 SDVTList VTs, const SDValue *Ops, 4405 unsigned NumOps) { 4406 // If an identical node already exists, use it. 4407 void *IP = 0; 4408 if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) { 4409 FoldingSetNodeID ID; 4410 AddNodeIDNode(ID, Opc, VTs, Ops, NumOps); 4411 if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP)) 4412 return ON; 4413 } 4414 4415 if (!RemoveNodeFromCSEMaps(N)) 4416 IP = 0; 4417 4418 // Start the morphing. 4419 N->NodeType = Opc; 4420 N->ValueList = VTs.VTs; 4421 N->NumValues = VTs.NumVTs; 4422 4423 // Clear the operands list, updating used nodes to remove this from their 4424 // use list. Keep track of any operands that become dead as a result. 4425 SmallPtrSet<SDNode*, 16> DeadNodeSet; 4426 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 4427 SDUse &Use = *I++; 4428 SDNode *Used = Use.getNode(); 4429 Use.set(SDValue()); 4430 if (Used->use_empty()) 4431 DeadNodeSet.insert(Used); 4432 } 4433 4434 // If NumOps is larger than the # of operands we currently have, reallocate 4435 // the operand list. 4436 if (NumOps > N->NumOperands) { 4437 if (N->OperandsNeedDelete) 4438 delete[] N->OperandList; 4439 4440 if (N->isMachineOpcode()) { 4441 // We're creating a final node that will live unmorphed for the 4442 // remainder of the current SelectionDAG iteration, so we can allocate 4443 // the operands directly out of a pool with no recycling metadata. 4444 N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps); 4445 N->OperandsNeedDelete = false; 4446 } else { 4447 N->OperandList = new SDUse[NumOps]; 4448 N->OperandsNeedDelete = true; 4449 } 4450 } 4451 4452 // Assign the new operands. 4453 N->NumOperands = NumOps; 4454 for (unsigned i = 0, e = NumOps; i != e; ++i) { 4455 N->OperandList[i].setUser(N); 4456 N->OperandList[i].setInitial(Ops[i]); 4457 } 4458 4459 // Delete any nodes that are still dead after adding the uses for the 4460 // new operands. 4461 SmallVector<SDNode *, 16> DeadNodes; 4462 for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(), 4463 E = DeadNodeSet.end(); I != E; ++I) 4464 if ((*I)->use_empty()) 4465 DeadNodes.push_back(*I); 4466 RemoveDeadNodes(DeadNodes); 4467 4468 if (IP) 4469 CSEMap.InsertNode(N, IP); // Memoize the new node. 4470 return N; 4471} 4472 4473 4474/// getTargetNode - These are used for target selectors to create a new node 4475/// with specified return type(s), target opcode, and operands. 4476/// 4477/// Note that getTargetNode returns the resultant node. If there is already a 4478/// node of the specified opcode and operands, it returns that node instead of 4479/// the current one. 4480SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT) { 4481 return getNode(~Opcode, dl, VT).getNode(); 4482} 4483 4484SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT, 4485 SDValue Op1) { 4486 return getNode(~Opcode, dl, VT, Op1).getNode(); 4487} 4488 4489SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT, 4490 SDValue Op1, SDValue Op2) { 4491 return getNode(~Opcode, dl, VT, Op1, Op2).getNode(); 4492} 4493 4494SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT, 4495 SDValue Op1, SDValue Op2, 4496 SDValue Op3) { 4497 return getNode(~Opcode, dl, VT, Op1, Op2, Op3).getNode(); 4498} 4499 4500SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT, 4501 const SDValue *Ops, unsigned NumOps) { 4502 return getNode(~Opcode, dl, VT, Ops, NumOps).getNode(); 4503} 4504 4505SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, 4506 MVT VT1, MVT VT2) { 4507 SDVTList VTs = getVTList(VT1, VT2); 4508 SDValue Op; 4509 return getNode(~Opcode, dl, VTs, &Op, 0).getNode(); 4510} 4511 4512SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1, 4513 MVT VT2, SDValue Op1) { 4514 SDVTList VTs = getVTList(VT1, VT2); 4515 return getNode(~Opcode, dl, VTs, &Op1, 1).getNode(); 4516} 4517 4518SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1, 4519 MVT VT2, SDValue Op1, 4520 SDValue Op2) { 4521 SDVTList VTs = getVTList(VT1, VT2); 4522 SDValue Ops[] = { Op1, Op2 }; 4523 return getNode(~Opcode, dl, VTs, Ops, 2).getNode(); 4524} 4525 4526SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1, 4527 MVT VT2, SDValue Op1, 4528 SDValue Op2, SDValue Op3) { 4529 SDVTList VTs = getVTList(VT1, VT2); 4530 SDValue Ops[] = { Op1, Op2, Op3 }; 4531 return getNode(~Opcode, dl, VTs, Ops, 3).getNode(); 4532} 4533 4534SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, 4535 MVT VT1, MVT VT2, 4536 const SDValue *Ops, unsigned NumOps) { 4537 SDVTList VTs = getVTList(VT1, VT2); 4538 return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode(); 4539} 4540 4541SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, 4542 MVT VT1, MVT VT2, MVT VT3, 4543 SDValue Op1, SDValue Op2) { 4544 SDVTList VTs = getVTList(VT1, VT2, VT3); 4545 SDValue Ops[] = { Op1, Op2 }; 4546 return getNode(~Opcode, dl, VTs, Ops, 2).getNode(); 4547} 4548 4549SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, 4550 MVT VT1, MVT VT2, MVT VT3, 4551 SDValue Op1, SDValue Op2, 4552 SDValue Op3) { 4553 SDVTList VTs = getVTList(VT1, VT2, VT3); 4554 SDValue Ops[] = { Op1, Op2, Op3 }; 4555 return getNode(~Opcode, dl, VTs, Ops, 3).getNode(); 4556} 4557 4558SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, 4559 MVT VT1, MVT VT2, MVT VT3, 4560 const SDValue *Ops, unsigned NumOps) { 4561 SDVTList VTs = getVTList(VT1, VT2, VT3); 4562 return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode(); 4563} 4564 4565SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1, 4566 MVT VT2, MVT VT3, MVT VT4, 4567 const SDValue *Ops, unsigned NumOps) { 4568 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4); 4569 return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode(); 4570} 4571 4572SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, 4573 const std::vector<MVT> &ResultTys, 4574 const SDValue *Ops, unsigned NumOps) { 4575 return getNode(~Opcode, dl, ResultTys, Ops, NumOps).getNode(); 4576} 4577 4578/// getNodeIfExists - Get the specified node if it's already available, or 4579/// else return NULL. 4580SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 4581 const SDValue *Ops, unsigned NumOps) { 4582 if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) { 4583 FoldingSetNodeID ID; 4584 AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps); 4585 void *IP = 0; 4586 if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) 4587 return E; 4588 } 4589 return NULL; 4590} 4591 4592/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 4593/// This can cause recursive merging of nodes in the DAG. 4594/// 4595/// This version assumes From has a single result value. 4596/// 4597void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To, 4598 DAGUpdateListener *UpdateListener) { 4599 SDNode *From = FromN.getNode(); 4600 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 4601 "Cannot replace with this method!"); 4602 assert(From != To.getNode() && "Cannot replace uses of with self"); 4603 4604 // Iterate over all the existing uses of From. New uses will be added 4605 // to the beginning of the use list, which we avoid visiting. 4606 // This specifically avoids visiting uses of From that arise while the 4607 // replacement is happening, because any such uses would be the result 4608 // of CSE: If an existing node looks like From after one of its operands 4609 // is replaced by To, we don't want to replace of all its users with To 4610 // too. See PR3018 for more info. 4611 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 4612 while (UI != UE) { 4613 SDNode *User = *UI; 4614 4615 // This node is about to morph, remove its old self from the CSE maps. 4616 RemoveNodeFromCSEMaps(User); 4617 4618 // A user can appear in a use list multiple times, and when this 4619 // happens the uses are usually next to each other in the list. 4620 // To help reduce the number of CSE recomputations, process all 4621 // the uses of this user that we can find this way. 4622 do { 4623 SDUse &Use = UI.getUse(); 4624 ++UI; 4625 Use.set(To); 4626 } while (UI != UE && *UI == User); 4627 4628 // Now that we have modified User, add it back to the CSE maps. If it 4629 // already exists there, recursively merge the results together. 4630 AddModifiedNodeToCSEMaps(User, UpdateListener); 4631 } 4632} 4633 4634/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 4635/// This can cause recursive merging of nodes in the DAG. 4636/// 4637/// This version assumes that for each value of From, there is a 4638/// corresponding value in To in the same position with the same type. 4639/// 4640void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To, 4641 DAGUpdateListener *UpdateListener) { 4642#ifndef NDEBUG 4643 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 4644 assert((!From->hasAnyUseOfValue(i) || 4645 From->getValueType(i) == To->getValueType(i)) && 4646 "Cannot use this version of ReplaceAllUsesWith!"); 4647#endif 4648 4649 // Handle the trivial case. 4650 if (From == To) 4651 return; 4652 4653 // Iterate over just the existing users of From. See the comments in 4654 // the ReplaceAllUsesWith above. 4655 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 4656 while (UI != UE) { 4657 SDNode *User = *UI; 4658 4659 // This node is about to morph, remove its old self from the CSE maps. 4660 RemoveNodeFromCSEMaps(User); 4661 4662 // A user can appear in a use list multiple times, and when this 4663 // happens the uses are usually next to each other in the list. 4664 // To help reduce the number of CSE recomputations, process all 4665 // the uses of this user that we can find this way. 4666 do { 4667 SDUse &Use = UI.getUse(); 4668 ++UI; 4669 Use.setNode(To); 4670 } while (UI != UE && *UI == User); 4671 4672 // Now that we have modified User, add it back to the CSE maps. If it 4673 // already exists there, recursively merge the results together. 4674 AddModifiedNodeToCSEMaps(User, UpdateListener); 4675 } 4676} 4677 4678/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 4679/// This can cause recursive merging of nodes in the DAG. 4680/// 4681/// This version can replace From with any result values. To must match the 4682/// number and types of values returned by From. 4683void SelectionDAG::ReplaceAllUsesWith(SDNode *From, 4684 const SDValue *To, 4685 DAGUpdateListener *UpdateListener) { 4686 if (From->getNumValues() == 1) // Handle the simple case efficiently. 4687 return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener); 4688 4689 // Iterate over just the existing users of From. See the comments in 4690 // the ReplaceAllUsesWith above. 4691 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 4692 while (UI != UE) { 4693 SDNode *User = *UI; 4694 4695 // This node is about to morph, remove its old self from the CSE maps. 4696 RemoveNodeFromCSEMaps(User); 4697 4698 // A user can appear in a use list multiple times, and when this 4699 // happens the uses are usually next to each other in the list. 4700 // To help reduce the number of CSE recomputations, process all 4701 // the uses of this user that we can find this way. 4702 do { 4703 SDUse &Use = UI.getUse(); 4704 const SDValue &ToOp = To[Use.getResNo()]; 4705 ++UI; 4706 Use.set(ToOp); 4707 } while (UI != UE && *UI == User); 4708 4709 // Now that we have modified User, add it back to the CSE maps. If it 4710 // already exists there, recursively merge the results together. 4711 AddModifiedNodeToCSEMaps(User, UpdateListener); 4712 } 4713} 4714 4715/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 4716/// uses of other values produced by From.getNode() alone. The Deleted 4717/// vector is handled the same way as for ReplaceAllUsesWith. 4718void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To, 4719 DAGUpdateListener *UpdateListener){ 4720 // Handle the really simple, really trivial case efficiently. 4721 if (From == To) return; 4722 4723 // Handle the simple, trivial, case efficiently. 4724 if (From.getNode()->getNumValues() == 1) { 4725 ReplaceAllUsesWith(From, To, UpdateListener); 4726 return; 4727 } 4728 4729 // Iterate over just the existing users of From. See the comments in 4730 // the ReplaceAllUsesWith above. 4731 SDNode::use_iterator UI = From.getNode()->use_begin(), 4732 UE = From.getNode()->use_end(); 4733 while (UI != UE) { 4734 SDNode *User = *UI; 4735 bool UserRemovedFromCSEMaps = false; 4736 4737 // A user can appear in a use list multiple times, and when this 4738 // happens the uses are usually next to each other in the list. 4739 // To help reduce the number of CSE recomputations, process all 4740 // the uses of this user that we can find this way. 4741 do { 4742 SDUse &Use = UI.getUse(); 4743 4744 // Skip uses of different values from the same node. 4745 if (Use.getResNo() != From.getResNo()) { 4746 ++UI; 4747 continue; 4748 } 4749 4750 // If this node hasn't been modified yet, it's still in the CSE maps, 4751 // so remove its old self from the CSE maps. 4752 if (!UserRemovedFromCSEMaps) { 4753 RemoveNodeFromCSEMaps(User); 4754 UserRemovedFromCSEMaps = true; 4755 } 4756 4757 ++UI; 4758 Use.set(To); 4759 } while (UI != UE && *UI == User); 4760 4761 // We are iterating over all uses of the From node, so if a use 4762 // doesn't use the specific value, no changes are made. 4763 if (!UserRemovedFromCSEMaps) 4764 continue; 4765 4766 // Now that we have modified User, add it back to the CSE maps. If it 4767 // already exists there, recursively merge the results together. 4768 AddModifiedNodeToCSEMaps(User, UpdateListener); 4769 } 4770} 4771 4772namespace { 4773 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 4774 /// to record information about a use. 4775 struct UseMemo { 4776 SDNode *User; 4777 unsigned Index; 4778 SDUse *Use; 4779 }; 4780 4781 /// operator< - Sort Memos by User. 4782 bool operator<(const UseMemo &L, const UseMemo &R) { 4783 return (intptr_t)L.User < (intptr_t)R.User; 4784 } 4785} 4786 4787/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 4788/// uses of other values produced by From.getNode() alone. The same value 4789/// may appear in both the From and To list. The Deleted vector is 4790/// handled the same way as for ReplaceAllUsesWith. 4791void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 4792 const SDValue *To, 4793 unsigned Num, 4794 DAGUpdateListener *UpdateListener){ 4795 // Handle the simple, trivial case efficiently. 4796 if (Num == 1) 4797 return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener); 4798 4799 // Read up all the uses and make records of them. This helps 4800 // processing new uses that are introduced during the 4801 // replacement process. 4802 SmallVector<UseMemo, 4> Uses; 4803 for (unsigned i = 0; i != Num; ++i) { 4804 unsigned FromResNo = From[i].getResNo(); 4805 SDNode *FromNode = From[i].getNode(); 4806 for (SDNode::use_iterator UI = FromNode->use_begin(), 4807 E = FromNode->use_end(); UI != E; ++UI) { 4808 SDUse &Use = UI.getUse(); 4809 if (Use.getResNo() == FromResNo) { 4810 UseMemo Memo = { *UI, i, &Use }; 4811 Uses.push_back(Memo); 4812 } 4813 } 4814 } 4815 4816 // Sort the uses, so that all the uses from a given User are together. 4817 std::sort(Uses.begin(), Uses.end()); 4818 4819 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 4820 UseIndex != UseIndexEnd; ) { 4821 // We know that this user uses some value of From. If it is the right 4822 // value, update it. 4823 SDNode *User = Uses[UseIndex].User; 4824 4825 // This node is about to morph, remove its old self from the CSE maps. 4826 RemoveNodeFromCSEMaps(User); 4827 4828 // The Uses array is sorted, so all the uses for a given User 4829 // are next to each other in the list. 4830 // To help reduce the number of CSE recomputations, process all 4831 // the uses of this user that we can find this way. 4832 do { 4833 unsigned i = Uses[UseIndex].Index; 4834 SDUse &Use = *Uses[UseIndex].Use; 4835 ++UseIndex; 4836 4837 Use.set(To[i]); 4838 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 4839 4840 // Now that we have modified User, add it back to the CSE maps. If it 4841 // already exists there, recursively merge the results together. 4842 AddModifiedNodeToCSEMaps(User, UpdateListener); 4843 } 4844} 4845 4846/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 4847/// based on their topological order. It returns the maximum id and a vector 4848/// of the SDNodes* in assigned order by reference. 4849unsigned SelectionDAG::AssignTopologicalOrder() { 4850 4851 unsigned DAGSize = 0; 4852 4853 // SortedPos tracks the progress of the algorithm. Nodes before it are 4854 // sorted, nodes after it are unsorted. When the algorithm completes 4855 // it is at the end of the list. 4856 allnodes_iterator SortedPos = allnodes_begin(); 4857 4858 // Visit all the nodes. Move nodes with no operands to the front of 4859 // the list immediately. Annotate nodes that do have operands with their 4860 // operand count. Before we do this, the Node Id fields of the nodes 4861 // may contain arbitrary values. After, the Node Id fields for nodes 4862 // before SortedPos will contain the topological sort index, and the 4863 // Node Id fields for nodes At SortedPos and after will contain the 4864 // count of outstanding operands. 4865 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 4866 SDNode *N = I++; 4867 unsigned Degree = N->getNumOperands(); 4868 if (Degree == 0) { 4869 // A node with no uses, add it to the result array immediately. 4870 N->setNodeId(DAGSize++); 4871 allnodes_iterator Q = N; 4872 if (Q != SortedPos) 4873 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 4874 ++SortedPos; 4875 } else { 4876 // Temporarily use the Node Id as scratch space for the degree count. 4877 N->setNodeId(Degree); 4878 } 4879 } 4880 4881 // Visit all the nodes. As we iterate, moves nodes into sorted order, 4882 // such that by the time the end is reached all nodes will be sorted. 4883 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) { 4884 SDNode *N = I; 4885 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 4886 UI != UE; ++UI) { 4887 SDNode *P = *UI; 4888 unsigned Degree = P->getNodeId(); 4889 --Degree; 4890 if (Degree == 0) { 4891 // All of P's operands are sorted, so P may sorted now. 4892 P->setNodeId(DAGSize++); 4893 if (P != SortedPos) 4894 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 4895 ++SortedPos; 4896 } else { 4897 // Update P's outstanding operand count. 4898 P->setNodeId(Degree); 4899 } 4900 } 4901 } 4902 4903 assert(SortedPos == AllNodes.end() && 4904 "Topological sort incomplete!"); 4905 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 4906 "First node in topological sort is not the entry token!"); 4907 assert(AllNodes.front().getNodeId() == 0 && 4908 "First node in topological sort has non-zero id!"); 4909 assert(AllNodes.front().getNumOperands() == 0 && 4910 "First node in topological sort has operands!"); 4911 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 4912 "Last node in topologic sort has unexpected id!"); 4913 assert(AllNodes.back().use_empty() && 4914 "Last node in topologic sort has users!"); 4915 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 4916 return DAGSize; 4917} 4918 4919 4920 4921//===----------------------------------------------------------------------===// 4922// SDNode Class 4923//===----------------------------------------------------------------------===// 4924 4925HandleSDNode::~HandleSDNode() { 4926 DropOperands(); 4927} 4928 4929GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA, 4930 MVT VT, int64_t o, unsigned char TF) 4931 : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)), 4932 Offset(o), TargetFlags(TF) { 4933 TheGlobal = const_cast<GlobalValue*>(GA); 4934} 4935 4936MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, MVT memvt, 4937 const Value *srcValue, int SVO, 4938 unsigned alignment, bool vol) 4939 : SDNode(Opc, dl, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) { 4940 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment); 4941 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!"); 4942 assert(getAlignment() == alignment && "Alignment representation error!"); 4943 assert(isVolatile() == vol && "Volatile representation error!"); 4944} 4945 4946MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, 4947 const SDValue *Ops, 4948 unsigned NumOps, MVT memvt, const Value *srcValue, 4949 int SVO, unsigned alignment, bool vol) 4950 : SDNode(Opc, dl, VTs, Ops, NumOps), 4951 MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) { 4952 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment); 4953 assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!"); 4954 assert(getAlignment() == alignment && "Alignment representation error!"); 4955 assert(isVolatile() == vol && "Volatile representation error!"); 4956} 4957 4958/// getMemOperand - Return a MachineMemOperand object describing the memory 4959/// reference performed by this memory reference. 4960MachineMemOperand MemSDNode::getMemOperand() const { 4961 int Flags = 0; 4962 if (isa<LoadSDNode>(this)) 4963 Flags = MachineMemOperand::MOLoad; 4964 else if (isa<StoreSDNode>(this)) 4965 Flags = MachineMemOperand::MOStore; 4966 else if (isa<AtomicSDNode>(this)) { 4967 Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 4968 } 4969 else { 4970 const MemIntrinsicSDNode* MemIntrinNode = dyn_cast<MemIntrinsicSDNode>(this); 4971 assert(MemIntrinNode && "Unknown MemSDNode opcode!"); 4972 if (MemIntrinNode->readMem()) Flags |= MachineMemOperand::MOLoad; 4973 if (MemIntrinNode->writeMem()) Flags |= MachineMemOperand::MOStore; 4974 } 4975 4976 int Size = (getMemoryVT().getSizeInBits() + 7) >> 3; 4977 if (isVolatile()) Flags |= MachineMemOperand::MOVolatile; 4978 4979 // Check if the memory reference references a frame index 4980 const FrameIndexSDNode *FI = 4981 dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode()); 4982 if (!getSrcValue() && FI) 4983 return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()), 4984 Flags, 0, Size, getAlignment()); 4985 else 4986 return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(), 4987 Size, getAlignment()); 4988} 4989 4990/// Profile - Gather unique data for the node. 4991/// 4992void SDNode::Profile(FoldingSetNodeID &ID) const { 4993 AddNodeIDNode(ID, this); 4994} 4995 4996static ManagedStatic<std::set<MVT, MVT::compareRawBits> > EVTs; 4997static MVT VTs[MVT::LAST_VALUETYPE]; 4998static ManagedStatic<sys::SmartMutex<true> > VTMutex; 4999 5000/// getValueTypeList - Return a pointer to the specified value type. 5001/// 5002const MVT *SDNode::getValueTypeList(MVT VT) { 5003 sys::SmartScopedLock<true> Lock(*VTMutex); 5004 if (VT.isExtended()) { 5005 return &(*EVTs->insert(VT).first); 5006 } else { 5007 VTs[VT.getSimpleVT()] = VT; 5008 return &VTs[VT.getSimpleVT()]; 5009 } 5010} 5011 5012/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 5013/// indicated value. This method ignores uses of other values defined by this 5014/// operation. 5015bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 5016 assert(Value < getNumValues() && "Bad value!"); 5017 5018 // TODO: Only iterate over uses of a given value of the node 5019 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 5020 if (UI.getUse().getResNo() == Value) { 5021 if (NUses == 0) 5022 return false; 5023 --NUses; 5024 } 5025 } 5026 5027 // Found exactly the right number of uses? 5028 return NUses == 0; 5029} 5030 5031 5032/// hasAnyUseOfValue - Return true if there are any use of the indicated 5033/// value. This method ignores uses of other values defined by this operation. 5034bool SDNode::hasAnyUseOfValue(unsigned Value) const { 5035 assert(Value < getNumValues() && "Bad value!"); 5036 5037 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 5038 if (UI.getUse().getResNo() == Value) 5039 return true; 5040 5041 return false; 5042} 5043 5044 5045/// isOnlyUserOf - Return true if this node is the only use of N. 5046/// 5047bool SDNode::isOnlyUserOf(SDNode *N) const { 5048 bool Seen = false; 5049 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 5050 SDNode *User = *I; 5051 if (User == this) 5052 Seen = true; 5053 else 5054 return false; 5055 } 5056 5057 return Seen; 5058} 5059 5060/// isOperand - Return true if this node is an operand of N. 5061/// 5062bool SDValue::isOperandOf(SDNode *N) const { 5063 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 5064 if (*this == N->getOperand(i)) 5065 return true; 5066 return false; 5067} 5068 5069bool SDNode::isOperandOf(SDNode *N) const { 5070 for (unsigned i = 0, e = N->NumOperands; i != e; ++i) 5071 if (this == N->OperandList[i].getNode()) 5072 return true; 5073 return false; 5074} 5075 5076/// reachesChainWithoutSideEffects - Return true if this operand (which must 5077/// be a chain) reaches the specified operand without crossing any 5078/// side-effecting instructions. In practice, this looks through token 5079/// factors and non-volatile loads. In order to remain efficient, this only 5080/// looks a couple of nodes in, it does not do an exhaustive search. 5081bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 5082 unsigned Depth) const { 5083 if (*this == Dest) return true; 5084 5085 // Don't search too deeply, we just want to be able to see through 5086 // TokenFactor's etc. 5087 if (Depth == 0) return false; 5088 5089 // If this is a token factor, all inputs to the TF happen in parallel. If any 5090 // of the operands of the TF reach dest, then we can do the xform. 5091 if (getOpcode() == ISD::TokenFactor) { 5092 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 5093 if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1)) 5094 return true; 5095 return false; 5096 } 5097 5098 // Loads don't have side effects, look through them. 5099 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 5100 if (!Ld->isVolatile()) 5101 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 5102 } 5103 return false; 5104} 5105 5106 5107static void findPredecessor(SDNode *N, const SDNode *P, bool &found, 5108 SmallPtrSet<SDNode *, 32> &Visited) { 5109 if (found || !Visited.insert(N)) 5110 return; 5111 5112 for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) { 5113 SDNode *Op = N->getOperand(i).getNode(); 5114 if (Op == P) { 5115 found = true; 5116 return; 5117 } 5118 findPredecessor(Op, P, found, Visited); 5119 } 5120} 5121 5122/// isPredecessorOf - Return true if this node is a predecessor of N. This node 5123/// is either an operand of N or it can be reached by recursively traversing 5124/// up the operands. 5125/// NOTE: this is an expensive method. Use it carefully. 5126bool SDNode::isPredecessorOf(SDNode *N) const { 5127 SmallPtrSet<SDNode *, 32> Visited; 5128 bool found = false; 5129 findPredecessor(N, this, found, Visited); 5130 return found; 5131} 5132 5133uint64_t SDNode::getConstantOperandVal(unsigned Num) const { 5134 assert(Num < NumOperands && "Invalid child # of SDNode!"); 5135 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue(); 5136} 5137 5138std::string SDNode::getOperationName(const SelectionDAG *G) const { 5139 switch (getOpcode()) { 5140 default: 5141 if (getOpcode() < ISD::BUILTIN_OP_END) 5142 return "<<Unknown DAG Node>>"; 5143 if (isMachineOpcode()) { 5144 if (G) 5145 if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo()) 5146 if (getMachineOpcode() < TII->getNumOpcodes()) 5147 return TII->get(getMachineOpcode()).getName(); 5148 return "<<Unknown Machine Node>>"; 5149 } 5150 if (G) { 5151 const TargetLowering &TLI = G->getTargetLoweringInfo(); 5152 const char *Name = TLI.getTargetNodeName(getOpcode()); 5153 if (Name) return Name; 5154 return "<<Unknown Target Node>>"; 5155 } 5156 return "<<Unknown Node>>"; 5157 5158#ifndef NDEBUG 5159 case ISD::DELETED_NODE: 5160 return "<<Deleted Node!>>"; 5161#endif 5162 case ISD::PREFETCH: return "Prefetch"; 5163 case ISD::MEMBARRIER: return "MemBarrier"; 5164 case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap"; 5165 case ISD::ATOMIC_SWAP: return "AtomicSwap"; 5166 case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd"; 5167 case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub"; 5168 case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd"; 5169 case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr"; 5170 case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor"; 5171 case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand"; 5172 case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin"; 5173 case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax"; 5174 case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin"; 5175 case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax"; 5176 case ISD::PCMARKER: return "PCMarker"; 5177 case ISD::READCYCLECOUNTER: return "ReadCycleCounter"; 5178 case ISD::SRCVALUE: return "SrcValue"; 5179 case ISD::MEMOPERAND: return "MemOperand"; 5180 case ISD::EntryToken: return "EntryToken"; 5181 case ISD::TokenFactor: return "TokenFactor"; 5182 case ISD::AssertSext: return "AssertSext"; 5183 case ISD::AssertZext: return "AssertZext"; 5184 5185 case ISD::BasicBlock: return "BasicBlock"; 5186 case ISD::VALUETYPE: return "ValueType"; 5187 case ISD::Register: return "Register"; 5188 5189 case ISD::Constant: return "Constant"; 5190 case ISD::ConstantFP: return "ConstantFP"; 5191 case ISD::GlobalAddress: return "GlobalAddress"; 5192 case ISD::GlobalTLSAddress: return "GlobalTLSAddress"; 5193 case ISD::FrameIndex: return "FrameIndex"; 5194 case ISD::JumpTable: return "JumpTable"; 5195 case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE"; 5196 case ISD::RETURNADDR: return "RETURNADDR"; 5197 case ISD::FRAMEADDR: return "FRAMEADDR"; 5198 case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET"; 5199 case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR"; 5200 case ISD::EHSELECTION: return "EHSELECTION"; 5201 case ISD::EH_RETURN: return "EH_RETURN"; 5202 case ISD::ConstantPool: return "ConstantPool"; 5203 case ISD::ExternalSymbol: return "ExternalSymbol"; 5204 case ISD::INTRINSIC_WO_CHAIN: { 5205 unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue(); 5206 return Intrinsic::getName((Intrinsic::ID)IID); 5207 } 5208 case ISD::INTRINSIC_VOID: 5209 case ISD::INTRINSIC_W_CHAIN: { 5210 unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue(); 5211 return Intrinsic::getName((Intrinsic::ID)IID); 5212 } 5213 5214 case ISD::BUILD_VECTOR: return "BUILD_VECTOR"; 5215 case ISD::TargetConstant: return "TargetConstant"; 5216 case ISD::TargetConstantFP:return "TargetConstantFP"; 5217 case ISD::TargetGlobalAddress: return "TargetGlobalAddress"; 5218 case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress"; 5219 case ISD::TargetFrameIndex: return "TargetFrameIndex"; 5220 case ISD::TargetJumpTable: return "TargetJumpTable"; 5221 case ISD::TargetConstantPool: return "TargetConstantPool"; 5222 case ISD::TargetExternalSymbol: return "TargetExternalSymbol"; 5223 5224 case ISD::CopyToReg: return "CopyToReg"; 5225 case ISD::CopyFromReg: return "CopyFromReg"; 5226 case ISD::UNDEF: return "undef"; 5227 case ISD::MERGE_VALUES: return "merge_values"; 5228 case ISD::INLINEASM: return "inlineasm"; 5229 case ISD::DBG_LABEL: return "dbg_label"; 5230 case ISD::EH_LABEL: return "eh_label"; 5231 case ISD::DECLARE: return "declare"; 5232 case ISD::HANDLENODE: return "handlenode"; 5233 5234 // Unary operators 5235 case ISD::FABS: return "fabs"; 5236 case ISD::FNEG: return "fneg"; 5237 case ISD::FSQRT: return "fsqrt"; 5238 case ISD::FSIN: return "fsin"; 5239 case ISD::FCOS: return "fcos"; 5240 case ISD::FPOWI: return "fpowi"; 5241 case ISD::FPOW: return "fpow"; 5242 case ISD::FTRUNC: return "ftrunc"; 5243 case ISD::FFLOOR: return "ffloor"; 5244 case ISD::FCEIL: return "fceil"; 5245 case ISD::FRINT: return "frint"; 5246 case ISD::FNEARBYINT: return "fnearbyint"; 5247 5248 // Binary operators 5249 case ISD::ADD: return "add"; 5250 case ISD::SUB: return "sub"; 5251 case ISD::MUL: return "mul"; 5252 case ISD::MULHU: return "mulhu"; 5253 case ISD::MULHS: return "mulhs"; 5254 case ISD::SDIV: return "sdiv"; 5255 case ISD::UDIV: return "udiv"; 5256 case ISD::SREM: return "srem"; 5257 case ISD::UREM: return "urem"; 5258 case ISD::SMUL_LOHI: return "smul_lohi"; 5259 case ISD::UMUL_LOHI: return "umul_lohi"; 5260 case ISD::SDIVREM: return "sdivrem"; 5261 case ISD::UDIVREM: return "udivrem"; 5262 case ISD::AND: return "and"; 5263 case ISD::OR: return "or"; 5264 case ISD::XOR: return "xor"; 5265 case ISD::SHL: return "shl"; 5266 case ISD::SRA: return "sra"; 5267 case ISD::SRL: return "srl"; 5268 case ISD::ROTL: return "rotl"; 5269 case ISD::ROTR: return "rotr"; 5270 case ISD::FADD: return "fadd"; 5271 case ISD::FSUB: return "fsub"; 5272 case ISD::FMUL: return "fmul"; 5273 case ISD::FDIV: return "fdiv"; 5274 case ISD::FREM: return "frem"; 5275 case ISD::FCOPYSIGN: return "fcopysign"; 5276 case ISD::FGETSIGN: return "fgetsign"; 5277 5278 case ISD::SETCC: return "setcc"; 5279 case ISD::VSETCC: return "vsetcc"; 5280 case ISD::SELECT: return "select"; 5281 case ISD::SELECT_CC: return "select_cc"; 5282 case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt"; 5283 case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt"; 5284 case ISD::CONCAT_VECTORS: return "concat_vectors"; 5285 case ISD::EXTRACT_SUBVECTOR: return "extract_subvector"; 5286 case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector"; 5287 case ISD::VECTOR_SHUFFLE: return "vector_shuffle"; 5288 case ISD::CARRY_FALSE: return "carry_false"; 5289 case ISD::ADDC: return "addc"; 5290 case ISD::ADDE: return "adde"; 5291 case ISD::SADDO: return "saddo"; 5292 case ISD::UADDO: return "uaddo"; 5293 case ISD::SSUBO: return "ssubo"; 5294 case ISD::USUBO: return "usubo"; 5295 case ISD::SMULO: return "smulo"; 5296 case ISD::UMULO: return "umulo"; 5297 case ISD::SUBC: return "subc"; 5298 case ISD::SUBE: return "sube"; 5299 case ISD::SHL_PARTS: return "shl_parts"; 5300 case ISD::SRA_PARTS: return "sra_parts"; 5301 case ISD::SRL_PARTS: return "srl_parts"; 5302 5303 // Conversion operators. 5304 case ISD::SIGN_EXTEND: return "sign_extend"; 5305 case ISD::ZERO_EXTEND: return "zero_extend"; 5306 case ISD::ANY_EXTEND: return "any_extend"; 5307 case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg"; 5308 case ISD::TRUNCATE: return "truncate"; 5309 case ISD::FP_ROUND: return "fp_round"; 5310 case ISD::FLT_ROUNDS_: return "flt_rounds"; 5311 case ISD::FP_ROUND_INREG: return "fp_round_inreg"; 5312 case ISD::FP_EXTEND: return "fp_extend"; 5313 5314 case ISD::SINT_TO_FP: return "sint_to_fp"; 5315 case ISD::UINT_TO_FP: return "uint_to_fp"; 5316 case ISD::FP_TO_SINT: return "fp_to_sint"; 5317 case ISD::FP_TO_UINT: return "fp_to_uint"; 5318 case ISD::BIT_CONVERT: return "bit_convert"; 5319 5320 case ISD::CONVERT_RNDSAT: { 5321 switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) { 5322 default: llvm_unreachable("Unknown cvt code!"); 5323 case ISD::CVT_FF: return "cvt_ff"; 5324 case ISD::CVT_FS: return "cvt_fs"; 5325 case ISD::CVT_FU: return "cvt_fu"; 5326 case ISD::CVT_SF: return "cvt_sf"; 5327 case ISD::CVT_UF: return "cvt_uf"; 5328 case ISD::CVT_SS: return "cvt_ss"; 5329 case ISD::CVT_SU: return "cvt_su"; 5330 case ISD::CVT_US: return "cvt_us"; 5331 case ISD::CVT_UU: return "cvt_uu"; 5332 } 5333 } 5334 5335 // Control flow instructions 5336 case ISD::BR: return "br"; 5337 case ISD::BRIND: return "brind"; 5338 case ISD::BR_JT: return "br_jt"; 5339 case ISD::BRCOND: return "brcond"; 5340 case ISD::BR_CC: return "br_cc"; 5341 case ISD::CALLSEQ_START: return "callseq_start"; 5342 case ISD::CALLSEQ_END: return "callseq_end"; 5343 5344 // Other operators 5345 case ISD::LOAD: return "load"; 5346 case ISD::STORE: return "store"; 5347 case ISD::VAARG: return "vaarg"; 5348 case ISD::VACOPY: return "vacopy"; 5349 case ISD::VAEND: return "vaend"; 5350 case ISD::VASTART: return "vastart"; 5351 case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc"; 5352 case ISD::EXTRACT_ELEMENT: return "extract_element"; 5353 case ISD::BUILD_PAIR: return "build_pair"; 5354 case ISD::STACKSAVE: return "stacksave"; 5355 case ISD::STACKRESTORE: return "stackrestore"; 5356 case ISD::TRAP: return "trap"; 5357 5358 // Bit manipulation 5359 case ISD::BSWAP: return "bswap"; 5360 case ISD::CTPOP: return "ctpop"; 5361 case ISD::CTTZ: return "cttz"; 5362 case ISD::CTLZ: return "ctlz"; 5363 5364 // Debug info 5365 case ISD::DBG_STOPPOINT: return "dbg_stoppoint"; 5366 case ISD::DEBUG_LOC: return "debug_loc"; 5367 5368 // Trampolines 5369 case ISD::TRAMPOLINE: return "trampoline"; 5370 5371 case ISD::CONDCODE: 5372 switch (cast<CondCodeSDNode>(this)->get()) { 5373 default: llvm_unreachable("Unknown setcc condition!"); 5374 case ISD::SETOEQ: return "setoeq"; 5375 case ISD::SETOGT: return "setogt"; 5376 case ISD::SETOGE: return "setoge"; 5377 case ISD::SETOLT: return "setolt"; 5378 case ISD::SETOLE: return "setole"; 5379 case ISD::SETONE: return "setone"; 5380 5381 case ISD::SETO: return "seto"; 5382 case ISD::SETUO: return "setuo"; 5383 case ISD::SETUEQ: return "setue"; 5384 case ISD::SETUGT: return "setugt"; 5385 case ISD::SETUGE: return "setuge"; 5386 case ISD::SETULT: return "setult"; 5387 case ISD::SETULE: return "setule"; 5388 case ISD::SETUNE: return "setune"; 5389 5390 case ISD::SETEQ: return "seteq"; 5391 case ISD::SETGT: return "setgt"; 5392 case ISD::SETGE: return "setge"; 5393 case ISD::SETLT: return "setlt"; 5394 case ISD::SETLE: return "setle"; 5395 case ISD::SETNE: return "setne"; 5396 } 5397 } 5398} 5399 5400const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) { 5401 switch (AM) { 5402 default: 5403 return ""; 5404 case ISD::PRE_INC: 5405 return "<pre-inc>"; 5406 case ISD::PRE_DEC: 5407 return "<pre-dec>"; 5408 case ISD::POST_INC: 5409 return "<post-inc>"; 5410 case ISD::POST_DEC: 5411 return "<post-dec>"; 5412 } 5413} 5414 5415std::string ISD::ArgFlagsTy::getArgFlagsString() { 5416 std::string S = "< "; 5417 5418 if (isZExt()) 5419 S += "zext "; 5420 if (isSExt()) 5421 S += "sext "; 5422 if (isInReg()) 5423 S += "inreg "; 5424 if (isSRet()) 5425 S += "sret "; 5426 if (isByVal()) 5427 S += "byval "; 5428 if (isNest()) 5429 S += "nest "; 5430 if (getByValAlign()) 5431 S += "byval-align:" + utostr(getByValAlign()) + " "; 5432 if (getOrigAlign()) 5433 S += "orig-align:" + utostr(getOrigAlign()) + " "; 5434 if (getByValSize()) 5435 S += "byval-size:" + utostr(getByValSize()) + " "; 5436 return S + ">"; 5437} 5438 5439void SDNode::dump() const { dump(0); } 5440void SDNode::dump(const SelectionDAG *G) const { 5441 print(errs(), G); 5442} 5443 5444void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const { 5445 OS << (void*)this << ": "; 5446 5447 for (unsigned i = 0, e = getNumValues(); i != e; ++i) { 5448 if (i) OS << ","; 5449 if (getValueType(i) == MVT::Other) 5450 OS << "ch"; 5451 else 5452 OS << getValueType(i).getMVTString(); 5453 } 5454 OS << " = " << getOperationName(G); 5455} 5456 5457void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const { 5458 if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) { 5459 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(this); 5460 OS << "<"; 5461 for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) { 5462 int Idx = SVN->getMaskElt(i); 5463 if (i) OS << ","; 5464 if (Idx < 0) 5465 OS << "u"; 5466 else 5467 OS << Idx; 5468 } 5469 OS << ">"; 5470 } 5471 5472 if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) { 5473 OS << '<' << CSDN->getAPIntValue() << '>'; 5474 } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) { 5475 if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle) 5476 OS << '<' << CSDN->getValueAPF().convertToFloat() << '>'; 5477 else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble) 5478 OS << '<' << CSDN->getValueAPF().convertToDouble() << '>'; 5479 else { 5480 OS << "<APFloat("; 5481 CSDN->getValueAPF().bitcastToAPInt().dump(); 5482 OS << ")>"; 5483 } 5484 } else if (const GlobalAddressSDNode *GADN = 5485 dyn_cast<GlobalAddressSDNode>(this)) { 5486 int64_t offset = GADN->getOffset(); 5487 OS << '<'; 5488 WriteAsOperand(OS, GADN->getGlobal()); 5489 OS << '>'; 5490 if (offset > 0) 5491 OS << " + " << offset; 5492 else 5493 OS << " " << offset; 5494 if (unsigned int TF = GADN->getTargetFlags()) 5495 OS << " [TF=" << TF << ']'; 5496 } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) { 5497 OS << "<" << FIDN->getIndex() << ">"; 5498 } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) { 5499 OS << "<" << JTDN->getIndex() << ">"; 5500 if (unsigned int TF = JTDN->getTargetFlags()) 5501 OS << " [TF=" << TF << ']'; 5502 } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){ 5503 int offset = CP->getOffset(); 5504 if (CP->isMachineConstantPoolEntry()) 5505 OS << "<" << *CP->getMachineCPVal() << ">"; 5506 else 5507 OS << "<" << *CP->getConstVal() << ">"; 5508 if (offset > 0) 5509 OS << " + " << offset; 5510 else 5511 OS << " " << offset; 5512 if (unsigned int TF = CP->getTargetFlags()) 5513 OS << " [TF=" << TF << ']'; 5514 } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) { 5515 OS << "<"; 5516 const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock(); 5517 if (LBB) 5518 OS << LBB->getName() << " "; 5519 OS << (const void*)BBDN->getBasicBlock() << ">"; 5520 } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) { 5521 if (G && R->getReg() && 5522 TargetRegisterInfo::isPhysicalRegister(R->getReg())) { 5523 OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg()); 5524 } else { 5525 OS << " #" << R->getReg(); 5526 } 5527 } else if (const ExternalSymbolSDNode *ES = 5528 dyn_cast<ExternalSymbolSDNode>(this)) { 5529 OS << "'" << ES->getSymbol() << "'"; 5530 if (unsigned int TF = ES->getTargetFlags()) 5531 OS << " [TF=" << TF << ']'; 5532 } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) { 5533 if (M->getValue()) 5534 OS << "<" << M->getValue() << ">"; 5535 else 5536 OS << "<null>"; 5537 } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) { 5538 if (M->MO.getValue()) 5539 OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">"; 5540 else 5541 OS << "<null:" << M->MO.getOffset() << ">"; 5542 } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) { 5543 OS << ":" << N->getVT().getMVTString(); 5544 } 5545 else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) { 5546 const Value *SrcValue = LD->getSrcValue(); 5547 int SrcOffset = LD->getSrcValueOffset(); 5548 OS << " <"; 5549 if (SrcValue) 5550 OS << SrcValue; 5551 else 5552 OS << "null"; 5553 OS << ":" << SrcOffset << ">"; 5554 5555 bool doExt = true; 5556 switch (LD->getExtensionType()) { 5557 default: doExt = false; break; 5558 case ISD::EXTLOAD: OS << " <anyext "; break; 5559 case ISD::SEXTLOAD: OS << " <sext "; break; 5560 case ISD::ZEXTLOAD: OS << " <zext "; break; 5561 } 5562 if (doExt) 5563 OS << LD->getMemoryVT().getMVTString() << ">"; 5564 5565 const char *AM = getIndexedModeName(LD->getAddressingMode()); 5566 if (*AM) 5567 OS << " " << AM; 5568 if (LD->isVolatile()) 5569 OS << " <volatile>"; 5570 OS << " alignment=" << LD->getAlignment(); 5571 } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) { 5572 const Value *SrcValue = ST->getSrcValue(); 5573 int SrcOffset = ST->getSrcValueOffset(); 5574 OS << " <"; 5575 if (SrcValue) 5576 OS << SrcValue; 5577 else 5578 OS << "null"; 5579 OS << ":" << SrcOffset << ">"; 5580 5581 if (ST->isTruncatingStore()) 5582 OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">"; 5583 5584 const char *AM = getIndexedModeName(ST->getAddressingMode()); 5585 if (*AM) 5586 OS << " " << AM; 5587 if (ST->isVolatile()) 5588 OS << " <volatile>"; 5589 OS << " alignment=" << ST->getAlignment(); 5590 } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) { 5591 const Value *SrcValue = AT->getSrcValue(); 5592 int SrcOffset = AT->getSrcValueOffset(); 5593 OS << " <"; 5594 if (SrcValue) 5595 OS << SrcValue; 5596 else 5597 OS << "null"; 5598 OS << ":" << SrcOffset << ">"; 5599 if (AT->isVolatile()) 5600 OS << " <volatile>"; 5601 OS << " alignment=" << AT->getAlignment(); 5602 } 5603} 5604 5605void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const { 5606 print_types(OS, G); 5607 OS << " "; 5608 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 5609 if (i) OS << ", "; 5610 OS << (void*)getOperand(i).getNode(); 5611 if (unsigned RN = getOperand(i).getResNo()) 5612 OS << ":" << RN; 5613 } 5614 print_details(OS, G); 5615} 5616 5617static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) { 5618 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 5619 if (N->getOperand(i).getNode()->hasOneUse()) 5620 DumpNodes(N->getOperand(i).getNode(), indent+2, G); 5621 else 5622 cerr << "\n" << std::string(indent+2, ' ') 5623 << (void*)N->getOperand(i).getNode() << ": <multiple use>"; 5624 5625 5626 cerr << "\n" << std::string(indent, ' '); 5627 N->dump(G); 5628} 5629 5630void SelectionDAG::dump() const { 5631 cerr << "SelectionDAG has " << AllNodes.size() << " nodes:"; 5632 5633 for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end(); 5634 I != E; ++I) { 5635 const SDNode *N = I; 5636 if (!N->hasOneUse() && N != getRoot().getNode()) 5637 DumpNodes(N, 2, this); 5638 } 5639 5640 if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this); 5641 5642 cerr << "\n\n"; 5643} 5644 5645void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const { 5646 print_types(OS, G); 5647 print_details(OS, G); 5648} 5649 5650typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet; 5651static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent, 5652 const SelectionDAG *G, VisitedSDNodeSet &once) { 5653 if (!once.insert(N)) // If we've been here before, return now. 5654 return; 5655 // Dump the current SDNode, but don't end the line yet. 5656 OS << std::string(indent, ' '); 5657 N->printr(OS, G); 5658 // Having printed this SDNode, walk the children: 5659 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 5660 const SDNode *child = N->getOperand(i).getNode(); 5661 if (i) OS << ","; 5662 OS << " "; 5663 if (child->getNumOperands() == 0) { 5664 // This child has no grandchildren; print it inline right here. 5665 child->printr(OS, G); 5666 once.insert(child); 5667 } else { // Just the address. FIXME: also print the child's opcode 5668 OS << (void*)child; 5669 if (unsigned RN = N->getOperand(i).getResNo()) 5670 OS << ":" << RN; 5671 } 5672 } 5673 OS << "\n"; 5674 // Dump children that have grandchildren on their own line(s). 5675 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 5676 const SDNode *child = N->getOperand(i).getNode(); 5677 DumpNodesr(OS, child, indent+2, G, once); 5678 } 5679} 5680 5681void SDNode::dumpr() const { 5682 VisitedSDNodeSet once; 5683 DumpNodesr(errs(), this, 0, 0, once); 5684} 5685 5686 5687// getAddressSpace - Return the address space this GlobalAddress belongs to. 5688unsigned GlobalAddressSDNode::getAddressSpace() const { 5689 return getGlobal()->getType()->getAddressSpace(); 5690} 5691 5692 5693const Type *ConstantPoolSDNode::getType() const { 5694 if (isMachineConstantPoolEntry()) 5695 return Val.MachineCPVal->getType(); 5696 return Val.ConstVal->getType(); 5697} 5698 5699bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, 5700 APInt &SplatUndef, 5701 unsigned &SplatBitSize, 5702 bool &HasAnyUndefs, 5703 unsigned MinSplatBits) { 5704 MVT VT = getValueType(0); 5705 assert(VT.isVector() && "Expected a vector type"); 5706 unsigned sz = VT.getSizeInBits(); 5707 if (MinSplatBits > sz) 5708 return false; 5709 5710 SplatValue = APInt(sz, 0); 5711 SplatUndef = APInt(sz, 0); 5712 5713 // Get the bits. Bits with undefined values (when the corresponding element 5714 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 5715 // in SplatValue. If any of the values are not constant, give up and return 5716 // false. 5717 unsigned int nOps = getNumOperands(); 5718 assert(nOps > 0 && "isConstantSplat has 0-size build vector"); 5719 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits(); 5720 for (unsigned i = 0; i < nOps; ++i) { 5721 SDValue OpVal = getOperand(i); 5722 unsigned BitPos = i * EltBitSize; 5723 5724 if (OpVal.getOpcode() == ISD::UNDEF) 5725 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos +EltBitSize); 5726 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) 5727 SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize). 5728 zextOrTrunc(sz) << BitPos); 5729 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 5730 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos; 5731 else 5732 return false; 5733 } 5734 5735 // The build_vector is all constants or undefs. Find the smallest element 5736 // size that splats the vector. 5737 5738 HasAnyUndefs = (SplatUndef != 0); 5739 while (sz > 8) { 5740 5741 unsigned HalfSize = sz / 2; 5742 APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize); 5743 APInt LowValue = APInt(SplatValue).trunc(HalfSize); 5744 APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize); 5745 APInt LowUndef = APInt(SplatUndef).trunc(HalfSize); 5746 5747 // If the two halves do not match (ignoring undef bits), stop here. 5748 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 5749 MinSplatBits > HalfSize) 5750 break; 5751 5752 SplatValue = HighValue | LowValue; 5753 SplatUndef = HighUndef & LowUndef; 5754 5755 sz = HalfSize; 5756 } 5757 5758 SplatBitSize = sz; 5759 return true; 5760} 5761 5762bool ShuffleVectorSDNode::isSplatMask(const int *Mask, MVT VT) { 5763 // Find the first non-undef value in the shuffle mask. 5764 unsigned i, e; 5765 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 5766 /* search */; 5767 5768 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!"); 5769 5770 // Make sure all remaining elements are either undef or the same as the first 5771 // non-undef value. 5772 for (int Idx = Mask[i]; i != e; ++i) 5773 if (Mask[i] >= 0 && Mask[i] != Idx) 5774 return false; 5775 return true; 5776} 5777