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