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 "SDNodeDbgValue.h" 16 #include "llvm/ADT/APSInt.h" 17 #include "llvm/ADT/SetVector.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/CodeGen/MachineBasicBlock.h" 24 #include "llvm/CodeGen/MachineConstantPool.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineModuleInfo.h" 27 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 28 #include "llvm/IR/CallingConv.h" 29 #include "llvm/IR/Constants.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/DebugInfo.h" 32 #include "llvm/IR/DerivedTypes.h" 33 #include "llvm/IR/Function.h" 34 #include "llvm/IR/GlobalAlias.h" 35 #include "llvm/IR/GlobalVariable.h" 36 #include "llvm/IR/Intrinsics.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/ManagedStatic.h" 40 #include "llvm/Support/MathExtras.h" 41 #include "llvm/Support/Mutex.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include "llvm/Target/TargetInstrInfo.h" 44 #include "llvm/Target/TargetIntrinsicInfo.h" 45 #include "llvm/Target/TargetLowering.h" 46 #include "llvm/Target/TargetMachine.h" 47 #include "llvm/Target/TargetOptions.h" 48 #include "llvm/Target/TargetRegisterInfo.h" 49 #include "llvm/Target/TargetSubtargetInfo.h" 50 #include <algorithm> 51 #include <cmath> 52 #include <utility> 53 54 using namespace llvm; 55 56 /// makeVTList - Return an instance of the SDVTList struct initialized with the 57 /// specified members. 58 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 59 SDVTList Res = {VTs, NumVTs}; 60 return Res; 61 } 62 63 // Default null implementations of the callbacks. 64 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 65 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 66 67 //===----------------------------------------------------------------------===// 68 // ConstantFPSDNode Class 69 //===----------------------------------------------------------------------===// 70 71 /// isExactlyValue - We don't rely on operator== working on double values, as 72 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 73 /// As such, this method can be used to do an exact bit-for-bit comparison of 74 /// two floating point values. 75 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 76 return getValueAPF().bitwiseIsEqual(V); 77 } 78 79 bool ConstantFPSDNode::isValueValidForType(EVT VT, 80 const APFloat& Val) { 81 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 82 83 // convert modifies in place, so make a copy. 84 APFloat Val2 = APFloat(Val); 85 bool losesInfo; 86 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 87 APFloat::rmNearestTiesToEven, 88 &losesInfo); 89 return !losesInfo; 90 } 91 92 //===----------------------------------------------------------------------===// 93 // ISD Namespace 94 //===----------------------------------------------------------------------===// 95 96 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 97 auto *BV = dyn_cast<BuildVectorSDNode>(N); 98 if (!BV) 99 return false; 100 101 APInt SplatUndef; 102 unsigned SplatBitSize; 103 bool HasUndefs; 104 EVT EltVT = N->getValueType(0).getVectorElementType(); 105 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs) && 106 EltVT.getSizeInBits() >= SplatBitSize; 107 } 108 109 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 110 // specializations of the more general isConstantSplatVector()? 111 112 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 113 // Look through a bit convert. 114 while (N->getOpcode() == ISD::BITCAST) 115 N = N->getOperand(0).getNode(); 116 117 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 118 119 unsigned i = 0, e = N->getNumOperands(); 120 121 // Skip over all of the undef values. 122 while (i != e && N->getOperand(i).isUndef()) 123 ++i; 124 125 // Do not accept an all-undef vector. 126 if (i == e) return false; 127 128 // Do not accept build_vectors that aren't all constants or which have non-~0 129 // elements. We have to be a bit careful here, as the type of the constant 130 // may not be the same as the type of the vector elements due to type 131 // legalization (the elements are promoted to a legal type for the target and 132 // a vector of a type may be legal when the base element type is not). 133 // We only want to check enough bits to cover the vector elements, because 134 // we care if the resultant vector is all ones, not whether the individual 135 // constants are. 136 SDValue NotZero = N->getOperand(i); 137 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 138 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 139 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 140 return false; 141 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 142 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 143 return false; 144 } else 145 return false; 146 147 // Okay, we have at least one ~0 value, check to see if the rest match or are 148 // undefs. Even with the above element type twiddling, this should be OK, as 149 // the same type legalization should have applied to all the elements. 150 for (++i; i != e; ++i) 151 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 152 return false; 153 return true; 154 } 155 156 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 157 // Look through a bit convert. 158 while (N->getOpcode() == ISD::BITCAST) 159 N = N->getOperand(0).getNode(); 160 161 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 162 163 bool IsAllUndef = true; 164 for (const SDValue &Op : N->op_values()) { 165 if (Op.isUndef()) 166 continue; 167 IsAllUndef = false; 168 // Do not accept build_vectors that aren't all constants or which have non-0 169 // elements. We have to be a bit careful here, as the type of the constant 170 // may not be the same as the type of the vector elements due to type 171 // legalization (the elements are promoted to a legal type for the target 172 // and a vector of a type may be legal when the base element type is not). 173 // We only want to check enough bits to cover the vector elements, because 174 // we care if the resultant vector is all zeros, not whether the individual 175 // constants are. 176 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 177 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 178 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 179 return false; 180 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 181 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 182 return false; 183 } else 184 return false; 185 } 186 187 // Do not accept an all-undef vector. 188 if (IsAllUndef) 189 return false; 190 return true; 191 } 192 193 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 194 if (N->getOpcode() != ISD::BUILD_VECTOR) 195 return false; 196 197 for (const SDValue &Op : N->op_values()) { 198 if (Op.isUndef()) 199 continue; 200 if (!isa<ConstantSDNode>(Op)) 201 return false; 202 } 203 return true; 204 } 205 206 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 207 if (N->getOpcode() != ISD::BUILD_VECTOR) 208 return false; 209 210 for (const SDValue &Op : N->op_values()) { 211 if (Op.isUndef()) 212 continue; 213 if (!isa<ConstantFPSDNode>(Op)) 214 return false; 215 } 216 return true; 217 } 218 219 bool ISD::allOperandsUndef(const SDNode *N) { 220 // Return false if the node has no operands. 221 // This is "logically inconsistent" with the definition of "all" but 222 // is probably the desired behavior. 223 if (N->getNumOperands() == 0) 224 return false; 225 226 for (const SDValue &Op : N->op_values()) 227 if (!Op.isUndef()) 228 return false; 229 230 return true; 231 } 232 233 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 234 switch (ExtType) { 235 case ISD::EXTLOAD: 236 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 237 case ISD::SEXTLOAD: 238 return ISD::SIGN_EXTEND; 239 case ISD::ZEXTLOAD: 240 return ISD::ZERO_EXTEND; 241 default: 242 break; 243 } 244 245 llvm_unreachable("Invalid LoadExtType"); 246 } 247 248 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 249 // To perform this operation, we just need to swap the L and G bits of the 250 // operation. 251 unsigned OldL = (Operation >> 2) & 1; 252 unsigned OldG = (Operation >> 1) & 1; 253 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 254 (OldL << 1) | // New G bit 255 (OldG << 2)); // New L bit. 256 } 257 258 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) { 259 unsigned Operation = Op; 260 if (isInteger) 261 Operation ^= 7; // Flip L, G, E bits, but not U. 262 else 263 Operation ^= 15; // Flip all of the condition bits. 264 265 if (Operation > ISD::SETTRUE2) 266 Operation &= ~8; // Don't let N and U bits get set. 267 268 return ISD::CondCode(Operation); 269 } 270 271 272 /// For an integer comparison, return 1 if the comparison is a signed operation 273 /// and 2 if the result is an unsigned comparison. Return zero if the operation 274 /// does not depend on the sign of the input (setne and seteq). 275 static int isSignedOp(ISD::CondCode Opcode) { 276 switch (Opcode) { 277 default: llvm_unreachable("Illegal integer setcc operation!"); 278 case ISD::SETEQ: 279 case ISD::SETNE: return 0; 280 case ISD::SETLT: 281 case ISD::SETLE: 282 case ISD::SETGT: 283 case ISD::SETGE: return 1; 284 case ISD::SETULT: 285 case ISD::SETULE: 286 case ISD::SETUGT: 287 case ISD::SETUGE: return 2; 288 } 289 } 290 291 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 292 bool isInteger) { 293 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 294 // Cannot fold a signed integer setcc with an unsigned integer setcc. 295 return ISD::SETCC_INVALID; 296 297 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 298 299 // If the N and U bits get set then the resultant comparison DOES suddenly 300 // care about orderedness, and is true when ordered. 301 if (Op > ISD::SETTRUE2) 302 Op &= ~16; // Clear the U bit if the N bit is set. 303 304 // Canonicalize illegal integer setcc's. 305 if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 306 Op = ISD::SETNE; 307 308 return ISD::CondCode(Op); 309 } 310 311 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 312 bool isInteger) { 313 if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 314 // Cannot fold a signed setcc with an unsigned setcc. 315 return ISD::SETCC_INVALID; 316 317 // Combine all of the condition bits. 318 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 319 320 // Canonicalize illegal integer setcc's. 321 if (isInteger) { 322 switch (Result) { 323 default: break; 324 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 325 case ISD::SETOEQ: // SETEQ & SETU[LG]E 326 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 327 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 328 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 329 } 330 } 331 332 return Result; 333 } 334 335 //===----------------------------------------------------------------------===// 336 // SDNode Profile Support 337 //===----------------------------------------------------------------------===// 338 339 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 340 /// 341 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 342 ID.AddInteger(OpC); 343 } 344 345 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 346 /// solely with their pointer. 347 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 348 ID.AddPointer(VTList.VTs); 349 } 350 351 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 352 /// 353 static void AddNodeIDOperands(FoldingSetNodeID &ID, 354 ArrayRef<SDValue> Ops) { 355 for (auto& Op : Ops) { 356 ID.AddPointer(Op.getNode()); 357 ID.AddInteger(Op.getResNo()); 358 } 359 } 360 361 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 362 /// 363 static void AddNodeIDOperands(FoldingSetNodeID &ID, 364 ArrayRef<SDUse> Ops) { 365 for (auto& Op : Ops) { 366 ID.AddPointer(Op.getNode()); 367 ID.AddInteger(Op.getResNo()); 368 } 369 } 370 371 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 372 SDVTList VTList, ArrayRef<SDValue> OpList) { 373 AddNodeIDOpcode(ID, OpC); 374 AddNodeIDValueTypes(ID, VTList); 375 AddNodeIDOperands(ID, OpList); 376 } 377 378 /// If this is an SDNode with special info, add this info to the NodeID data. 379 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 380 switch (N->getOpcode()) { 381 case ISD::TargetExternalSymbol: 382 case ISD::ExternalSymbol: 383 case ISD::MCSymbol: 384 llvm_unreachable("Should only be used on nodes with operands"); 385 default: break; // Normal nodes don't need extra info. 386 case ISD::TargetConstant: 387 case ISD::Constant: { 388 const ConstantSDNode *C = cast<ConstantSDNode>(N); 389 ID.AddPointer(C->getConstantIntValue()); 390 ID.AddBoolean(C->isOpaque()); 391 break; 392 } 393 case ISD::TargetConstantFP: 394 case ISD::ConstantFP: { 395 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 396 break; 397 } 398 case ISD::TargetGlobalAddress: 399 case ISD::GlobalAddress: 400 case ISD::TargetGlobalTLSAddress: 401 case ISD::GlobalTLSAddress: { 402 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 403 ID.AddPointer(GA->getGlobal()); 404 ID.AddInteger(GA->getOffset()); 405 ID.AddInteger(GA->getTargetFlags()); 406 ID.AddInteger(GA->getAddressSpace()); 407 break; 408 } 409 case ISD::BasicBlock: 410 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 411 break; 412 case ISD::Register: 413 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 414 break; 415 case ISD::RegisterMask: 416 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 417 break; 418 case ISD::SRCVALUE: 419 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 420 break; 421 case ISD::FrameIndex: 422 case ISD::TargetFrameIndex: 423 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 424 break; 425 case ISD::JumpTable: 426 case ISD::TargetJumpTable: 427 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 428 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 429 break; 430 case ISD::ConstantPool: 431 case ISD::TargetConstantPool: { 432 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 433 ID.AddInteger(CP->getAlignment()); 434 ID.AddInteger(CP->getOffset()); 435 if (CP->isMachineConstantPoolEntry()) 436 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 437 else 438 ID.AddPointer(CP->getConstVal()); 439 ID.AddInteger(CP->getTargetFlags()); 440 break; 441 } 442 case ISD::TargetIndex: { 443 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 444 ID.AddInteger(TI->getIndex()); 445 ID.AddInteger(TI->getOffset()); 446 ID.AddInteger(TI->getTargetFlags()); 447 break; 448 } 449 case ISD::LOAD: { 450 const LoadSDNode *LD = cast<LoadSDNode>(N); 451 ID.AddInteger(LD->getMemoryVT().getRawBits()); 452 ID.AddInteger(LD->getRawSubclassData()); 453 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 454 break; 455 } 456 case ISD::STORE: { 457 const StoreSDNode *ST = cast<StoreSDNode>(N); 458 ID.AddInteger(ST->getMemoryVT().getRawBits()); 459 ID.AddInteger(ST->getRawSubclassData()); 460 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 461 break; 462 } 463 case ISD::ATOMIC_CMP_SWAP: 464 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 465 case ISD::ATOMIC_SWAP: 466 case ISD::ATOMIC_LOAD_ADD: 467 case ISD::ATOMIC_LOAD_SUB: 468 case ISD::ATOMIC_LOAD_AND: 469 case ISD::ATOMIC_LOAD_OR: 470 case ISD::ATOMIC_LOAD_XOR: 471 case ISD::ATOMIC_LOAD_NAND: 472 case ISD::ATOMIC_LOAD_MIN: 473 case ISD::ATOMIC_LOAD_MAX: 474 case ISD::ATOMIC_LOAD_UMIN: 475 case ISD::ATOMIC_LOAD_UMAX: 476 case ISD::ATOMIC_LOAD: 477 case ISD::ATOMIC_STORE: { 478 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 479 ID.AddInteger(AT->getMemoryVT().getRawBits()); 480 ID.AddInteger(AT->getRawSubclassData()); 481 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 482 break; 483 } 484 case ISD::PREFETCH: { 485 const MemSDNode *PF = cast<MemSDNode>(N); 486 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 487 break; 488 } 489 case ISD::VECTOR_SHUFFLE: { 490 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 491 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 492 i != e; ++i) 493 ID.AddInteger(SVN->getMaskElt(i)); 494 break; 495 } 496 case ISD::TargetBlockAddress: 497 case ISD::BlockAddress: { 498 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 499 ID.AddPointer(BA->getBlockAddress()); 500 ID.AddInteger(BA->getOffset()); 501 ID.AddInteger(BA->getTargetFlags()); 502 break; 503 } 504 } // end switch (N->getOpcode()) 505 506 // Target specific memory nodes could also have address spaces to check. 507 if (N->isTargetMemoryOpcode()) 508 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 509 } 510 511 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 512 /// data. 513 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 514 AddNodeIDOpcode(ID, N->getOpcode()); 515 // Add the return value info. 516 AddNodeIDValueTypes(ID, N->getVTList()); 517 // Add the operand info. 518 AddNodeIDOperands(ID, N->ops()); 519 520 // Handle SDNode leafs with special info. 521 AddNodeIDCustom(ID, N); 522 } 523 524 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in 525 /// the CSE map that carries volatility, temporalness, indexing mode, and 526 /// extension/truncation information. 527 /// 528 static inline unsigned 529 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM, bool isVolatile, 530 bool isNonTemporal, bool isInvariant) { 531 assert((ConvType & 3) == ConvType && 532 "ConvType may not require more than 2 bits!"); 533 assert((AM & 7) == AM && 534 "AM may not require more than 3 bits!"); 535 return ConvType | 536 (AM << 2) | 537 (isVolatile << 5) | 538 (isNonTemporal << 6) | 539 (isInvariant << 7); 540 } 541 542 //===----------------------------------------------------------------------===// 543 // SelectionDAG Class 544 //===----------------------------------------------------------------------===// 545 546 /// doNotCSE - Return true if CSE should not be performed for this node. 547 static bool doNotCSE(SDNode *N) { 548 if (N->getValueType(0) == MVT::Glue) 549 return true; // Never CSE anything that produces a flag. 550 551 switch (N->getOpcode()) { 552 default: break; 553 case ISD::HANDLENODE: 554 case ISD::EH_LABEL: 555 return true; // Never CSE these nodes. 556 } 557 558 // Check that remaining values produced are not flags. 559 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 560 if (N->getValueType(i) == MVT::Glue) 561 return true; // Never CSE anything that produces a flag. 562 563 return false; 564 } 565 566 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 567 /// SelectionDAG. 568 void SelectionDAG::RemoveDeadNodes() { 569 // Create a dummy node (which is not added to allnodes), that adds a reference 570 // to the root node, preventing it from being deleted. 571 HandleSDNode Dummy(getRoot()); 572 573 SmallVector<SDNode*, 128> DeadNodes; 574 575 // Add all obviously-dead nodes to the DeadNodes worklist. 576 for (SDNode &Node : allnodes()) 577 if (Node.use_empty()) 578 DeadNodes.push_back(&Node); 579 580 RemoveDeadNodes(DeadNodes); 581 582 // If the root changed (e.g. it was a dead load, update the root). 583 setRoot(Dummy.getValue()); 584 } 585 586 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 587 /// given list, and any nodes that become unreachable as a result. 588 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 589 590 // Process the worklist, deleting the nodes and adding their uses to the 591 // worklist. 592 while (!DeadNodes.empty()) { 593 SDNode *N = DeadNodes.pop_back_val(); 594 595 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 596 DUL->NodeDeleted(N, nullptr); 597 598 // Take the node out of the appropriate CSE map. 599 RemoveNodeFromCSEMaps(N); 600 601 // Next, brutally remove the operand list. This is safe to do, as there are 602 // no cycles in the graph. 603 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 604 SDUse &Use = *I++; 605 SDNode *Operand = Use.getNode(); 606 Use.set(SDValue()); 607 608 // Now that we removed this operand, see if there are no uses of it left. 609 if (Operand->use_empty()) 610 DeadNodes.push_back(Operand); 611 } 612 613 DeallocateNode(N); 614 } 615 } 616 617 void SelectionDAG::RemoveDeadNode(SDNode *N){ 618 SmallVector<SDNode*, 16> DeadNodes(1, N); 619 620 // Create a dummy node that adds a reference to the root node, preventing 621 // it from being deleted. (This matters if the root is an operand of the 622 // dead node.) 623 HandleSDNode Dummy(getRoot()); 624 625 RemoveDeadNodes(DeadNodes); 626 } 627 628 void SelectionDAG::DeleteNode(SDNode *N) { 629 // First take this out of the appropriate CSE map. 630 RemoveNodeFromCSEMaps(N); 631 632 // Finally, remove uses due to operands of this node, remove from the 633 // AllNodes list, and delete the node. 634 DeleteNodeNotInCSEMaps(N); 635 } 636 637 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 638 assert(N->getIterator() != AllNodes.begin() && 639 "Cannot delete the entry node!"); 640 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 641 642 // Drop all of the operands and decrement used node's use counts. 643 N->DropOperands(); 644 645 DeallocateNode(N); 646 } 647 648 void SDDbgInfo::erase(const SDNode *Node) { 649 DbgValMapType::iterator I = DbgValMap.find(Node); 650 if (I == DbgValMap.end()) 651 return; 652 for (auto &Val: I->second) 653 Val->setIsInvalidated(); 654 DbgValMap.erase(I); 655 } 656 657 void SelectionDAG::DeallocateNode(SDNode *N) { 658 // If we have operands, deallocate them. 659 removeOperands(N); 660 661 // Set the opcode to DELETED_NODE to help catch bugs when node 662 // memory is reallocated. 663 N->NodeType = ISD::DELETED_NODE; 664 665 NodeAllocator.Deallocate(AllNodes.remove(N)); 666 667 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 668 // them and forget about that node. 669 DbgInfo->erase(N); 670 } 671 672 #ifndef NDEBUG 673 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 674 static void VerifySDNode(SDNode *N) { 675 switch (N->getOpcode()) { 676 default: 677 break; 678 case ISD::BUILD_PAIR: { 679 EVT VT = N->getValueType(0); 680 assert(N->getNumValues() == 1 && "Too many results!"); 681 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 682 "Wrong return type!"); 683 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 684 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 685 "Mismatched operand types!"); 686 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 687 "Wrong operand type!"); 688 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 689 "Wrong return type size"); 690 break; 691 } 692 case ISD::BUILD_VECTOR: { 693 assert(N->getNumValues() == 1 && "Too many results!"); 694 assert(N->getValueType(0).isVector() && "Wrong return type!"); 695 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 696 "Wrong number of operands!"); 697 EVT EltVT = N->getValueType(0).getVectorElementType(); 698 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) { 699 assert((I->getValueType() == EltVT || 700 (EltVT.isInteger() && I->getValueType().isInteger() && 701 EltVT.bitsLE(I->getValueType()))) && 702 "Wrong operand type!"); 703 assert(I->getValueType() == N->getOperand(0).getValueType() && 704 "Operands must all have the same type"); 705 } 706 break; 707 } 708 } 709 } 710 #endif // NDEBUG 711 712 /// \brief Insert a newly allocated node into the DAG. 713 /// 714 /// Handles insertion into the all nodes list and CSE map, as well as 715 /// verification and other common operations when a new node is allocated. 716 void SelectionDAG::InsertNode(SDNode *N) { 717 AllNodes.push_back(N); 718 #ifndef NDEBUG 719 N->PersistentId = NextPersistentId++; 720 VerifySDNode(N); 721 #endif 722 } 723 724 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 725 /// correspond to it. This is useful when we're about to delete or repurpose 726 /// the node. We don't want future request for structurally identical nodes 727 /// to return N anymore. 728 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 729 bool Erased = false; 730 switch (N->getOpcode()) { 731 case ISD::HANDLENODE: return false; // noop. 732 case ISD::CONDCODE: 733 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 734 "Cond code doesn't exist!"); 735 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 736 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 737 break; 738 case ISD::ExternalSymbol: 739 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 740 break; 741 case ISD::TargetExternalSymbol: { 742 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 743 Erased = TargetExternalSymbols.erase( 744 std::pair<std::string,unsigned char>(ESN->getSymbol(), 745 ESN->getTargetFlags())); 746 break; 747 } 748 case ISD::MCSymbol: { 749 auto *MCSN = cast<MCSymbolSDNode>(N); 750 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 751 break; 752 } 753 case ISD::VALUETYPE: { 754 EVT VT = cast<VTSDNode>(N)->getVT(); 755 if (VT.isExtended()) { 756 Erased = ExtendedValueTypeNodes.erase(VT); 757 } else { 758 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 759 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 760 } 761 break; 762 } 763 default: 764 // Remove it from the CSE Map. 765 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 766 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 767 Erased = CSEMap.RemoveNode(N); 768 break; 769 } 770 #ifndef NDEBUG 771 // Verify that the node was actually in one of the CSE maps, unless it has a 772 // flag result (which cannot be CSE'd) or is one of the special cases that are 773 // not subject to CSE. 774 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 775 !N->isMachineOpcode() && !doNotCSE(N)) { 776 N->dump(this); 777 dbgs() << "\n"; 778 llvm_unreachable("Node is not in map!"); 779 } 780 #endif 781 return Erased; 782 } 783 784 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 785 /// maps and modified in place. Add it back to the CSE maps, unless an identical 786 /// node already exists, in which case transfer all its users to the existing 787 /// node. This transfer can potentially trigger recursive merging. 788 /// 789 void 790 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 791 // For node types that aren't CSE'd, just act as if no identical node 792 // already exists. 793 if (!doNotCSE(N)) { 794 SDNode *Existing = CSEMap.GetOrInsertNode(N); 795 if (Existing != N) { 796 // If there was already an existing matching node, use ReplaceAllUsesWith 797 // to replace the dead one with the existing one. This can cause 798 // recursive merging of other unrelated nodes down the line. 799 ReplaceAllUsesWith(N, Existing); 800 801 // N is now dead. Inform the listeners and delete it. 802 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 803 DUL->NodeDeleted(N, Existing); 804 DeleteNodeNotInCSEMaps(N); 805 return; 806 } 807 } 808 809 // If the node doesn't already exist, we updated it. Inform listeners. 810 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 811 DUL->NodeUpdated(N); 812 } 813 814 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 815 /// were replaced with those specified. If this node is never memoized, 816 /// return null, otherwise return a pointer to the slot it would take. If a 817 /// node already exists with these operands, the slot will be non-null. 818 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 819 void *&InsertPos) { 820 if (doNotCSE(N)) 821 return nullptr; 822 823 SDValue Ops[] = { Op }; 824 FoldingSetNodeID ID; 825 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 826 AddNodeIDCustom(ID, N); 827 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 828 if (Node) 829 if (const SDNodeFlags *Flags = N->getFlags()) 830 Node->intersectFlagsWith(Flags); 831 return Node; 832 } 833 834 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 835 /// were replaced with those specified. If this node is never memoized, 836 /// return null, otherwise return a pointer to the slot it would take. If a 837 /// node already exists with these operands, the slot will be non-null. 838 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 839 SDValue Op1, SDValue Op2, 840 void *&InsertPos) { 841 if (doNotCSE(N)) 842 return nullptr; 843 844 SDValue Ops[] = { Op1, Op2 }; 845 FoldingSetNodeID ID; 846 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 847 AddNodeIDCustom(ID, N); 848 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 849 if (Node) 850 if (const SDNodeFlags *Flags = N->getFlags()) 851 Node->intersectFlagsWith(Flags); 852 return Node; 853 } 854 855 856 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 857 /// were replaced with those specified. If this node is never memoized, 858 /// return null, otherwise return a pointer to the slot it would take. If a 859 /// node already exists with these operands, the slot will be non-null. 860 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 861 void *&InsertPos) { 862 if (doNotCSE(N)) 863 return nullptr; 864 865 FoldingSetNodeID ID; 866 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 867 AddNodeIDCustom(ID, N); 868 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 869 if (Node) 870 if (const SDNodeFlags *Flags = N->getFlags()) 871 Node->intersectFlagsWith(Flags); 872 return Node; 873 } 874 875 unsigned SelectionDAG::getEVTAlignment(EVT VT) const { 876 Type *Ty = VT == MVT::iPTR ? 877 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 878 VT.getTypeForEVT(*getContext()); 879 880 return getDataLayout().getABITypeAlignment(Ty); 881 } 882 883 // EntryNode could meaningfully have debug info if we can find it... 884 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 885 : TM(tm), TSI(nullptr), TLI(nullptr), OptLevel(OL), 886 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 887 Root(getEntryNode()), NewNodesMustHaveLegalTypes(false), 888 UpdateListeners(nullptr) { 889 InsertNode(&EntryNode); 890 DbgInfo = new SDDbgInfo(); 891 } 892 893 void SelectionDAG::init(MachineFunction &mf) { 894 MF = &mf; 895 TLI = getSubtarget().getTargetLowering(); 896 TSI = getSubtarget().getSelectionDAGInfo(); 897 Context = &mf.getFunction()->getContext(); 898 } 899 900 SelectionDAG::~SelectionDAG() { 901 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 902 allnodes_clear(); 903 OperandRecycler.clear(OperandAllocator); 904 delete DbgInfo; 905 } 906 907 void SelectionDAG::allnodes_clear() { 908 assert(&*AllNodes.begin() == &EntryNode); 909 AllNodes.remove(AllNodes.begin()); 910 while (!AllNodes.empty()) 911 DeallocateNode(&AllNodes.front()); 912 #ifndef NDEBUG 913 NextPersistentId = 0; 914 #endif 915 } 916 917 SDNode *SelectionDAG::GetBinarySDNode(unsigned Opcode, const SDLoc &DL, 918 SDVTList VTs, SDValue N1, SDValue N2, 919 const SDNodeFlags *Flags) { 920 SDValue Ops[] = {N1, N2}; 921 922 if (isBinOpWithFlags(Opcode)) { 923 // If no flags were passed in, use a default flags object. 924 SDNodeFlags F; 925 if (Flags == nullptr) 926 Flags = &F; 927 928 auto *FN = newSDNode<BinaryWithFlagsSDNode>(Opcode, DL.getIROrder(), 929 DL.getDebugLoc(), VTs, *Flags); 930 createOperands(FN, Ops); 931 932 return FN; 933 } 934 935 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 936 createOperands(N, Ops); 937 return N; 938 } 939 940 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 941 void *&InsertPos) { 942 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 943 if (N) { 944 switch (N->getOpcode()) { 945 default: break; 946 case ISD::Constant: 947 case ISD::ConstantFP: 948 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 949 "debug location. Use another overload."); 950 } 951 } 952 return N; 953 } 954 955 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 956 const SDLoc &DL, void *&InsertPos) { 957 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 958 if (N) { 959 switch (N->getOpcode()) { 960 case ISD::Constant: 961 case ISD::ConstantFP: 962 // Erase debug location from the node if the node is used at several 963 // different places. Do not propagate one location to all uses as it 964 // will cause a worse single stepping debugging experience. 965 if (N->getDebugLoc() != DL.getDebugLoc()) 966 N->setDebugLoc(DebugLoc()); 967 break; 968 default: 969 // When the node's point of use is located earlier in the instruction 970 // sequence than its prior point of use, update its debug info to the 971 // earlier location. 972 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 973 N->setDebugLoc(DL.getDebugLoc()); 974 break; 975 } 976 } 977 return N; 978 } 979 980 void SelectionDAG::clear() { 981 allnodes_clear(); 982 OperandRecycler.clear(OperandAllocator); 983 OperandAllocator.Reset(); 984 CSEMap.clear(); 985 986 ExtendedValueTypeNodes.clear(); 987 ExternalSymbols.clear(); 988 TargetExternalSymbols.clear(); 989 MCSymbols.clear(); 990 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 991 static_cast<CondCodeSDNode*>(nullptr)); 992 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 993 static_cast<SDNode*>(nullptr)); 994 995 EntryNode.UseList = nullptr; 996 InsertNode(&EntryNode); 997 Root = getEntryNode(); 998 DbgInfo->clear(); 999 } 1000 1001 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1002 return VT.bitsGT(Op.getValueType()) ? 1003 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1004 getNode(ISD::TRUNCATE, DL, VT, Op); 1005 } 1006 1007 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1008 return VT.bitsGT(Op.getValueType()) ? 1009 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1010 getNode(ISD::TRUNCATE, DL, VT, Op); 1011 } 1012 1013 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1014 return VT.bitsGT(Op.getValueType()) ? 1015 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1016 getNode(ISD::TRUNCATE, DL, VT, Op); 1017 } 1018 1019 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1020 EVT OpVT) { 1021 if (VT.bitsLE(Op.getValueType())) 1022 return getNode(ISD::TRUNCATE, SL, VT, Op); 1023 1024 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1025 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1026 } 1027 1028 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1029 assert(!VT.isVector() && 1030 "getZeroExtendInReg should use the vector element type instead of " 1031 "the vector type!"); 1032 if (Op.getValueType() == VT) return Op; 1033 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 1034 APInt Imm = APInt::getLowBitsSet(BitWidth, 1035 VT.getSizeInBits()); 1036 return getNode(ISD::AND, DL, Op.getValueType(), Op, 1037 getConstant(Imm, DL, Op.getValueType())); 1038 } 1039 1040 SDValue SelectionDAG::getAnyExtendVectorInReg(SDValue Op, const SDLoc &DL, 1041 EVT VT) { 1042 assert(VT.isVector() && "This DAG node is restricted to vector types."); 1043 assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() && 1044 "The sizes of the input and result must match in order to perform the " 1045 "extend in-register."); 1046 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() && 1047 "The destination vector type must have fewer lanes than the input."); 1048 return getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Op); 1049 } 1050 1051 SDValue SelectionDAG::getSignExtendVectorInReg(SDValue Op, const SDLoc &DL, 1052 EVT VT) { 1053 assert(VT.isVector() && "This DAG node is restricted to vector types."); 1054 assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() && 1055 "The sizes of the input and result must match in order to perform the " 1056 "extend in-register."); 1057 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() && 1058 "The destination vector type must have fewer lanes than the input."); 1059 return getNode(ISD::SIGN_EXTEND_VECTOR_INREG, DL, VT, Op); 1060 } 1061 1062 SDValue SelectionDAG::getZeroExtendVectorInReg(SDValue Op, const SDLoc &DL, 1063 EVT VT) { 1064 assert(VT.isVector() && "This DAG node is restricted to vector types."); 1065 assert(VT.getSizeInBits() == Op.getValueType().getSizeInBits() && 1066 "The sizes of the input and result must match in order to perform the " 1067 "extend in-register."); 1068 assert(VT.getVectorNumElements() < Op.getValueType().getVectorNumElements() && 1069 "The destination vector type must have fewer lanes than the input."); 1070 return getNode(ISD::ZERO_EXTEND_VECTOR_INREG, DL, VT, Op); 1071 } 1072 1073 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1074 /// 1075 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1076 EVT EltVT = VT.getScalarType(); 1077 SDValue NegOne = 1078 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT); 1079 return getNode(ISD::XOR, DL, VT, Val, NegOne); 1080 } 1081 1082 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1083 EVT EltVT = VT.getScalarType(); 1084 SDValue TrueValue; 1085 switch (TLI->getBooleanContents(VT)) { 1086 case TargetLowering::ZeroOrOneBooleanContent: 1087 case TargetLowering::UndefinedBooleanContent: 1088 TrueValue = getConstant(1, DL, VT); 1089 break; 1090 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1091 TrueValue = getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, 1092 VT); 1093 break; 1094 } 1095 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1096 } 1097 1098 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1099 bool isT, bool isO) { 1100 EVT EltVT = VT.getScalarType(); 1101 assert((EltVT.getSizeInBits() >= 64 || 1102 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1103 "getConstant with a uint64_t value that doesn't fit in the type!"); 1104 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1105 } 1106 1107 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1108 bool isT, bool isO) { 1109 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1110 } 1111 1112 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1113 EVT VT, bool isT, bool isO) { 1114 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1115 1116 EVT EltVT = VT.getScalarType(); 1117 const ConstantInt *Elt = &Val; 1118 1119 // In some cases the vector type is legal but the element type is illegal and 1120 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1121 // inserted value (the type does not need to match the vector element type). 1122 // Any extra bits introduced will be truncated away. 1123 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1124 TargetLowering::TypePromoteInteger) { 1125 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1126 APInt NewVal = Elt->getValue().zext(EltVT.getSizeInBits()); 1127 Elt = ConstantInt::get(*getContext(), NewVal); 1128 } 1129 // In other cases the element type is illegal and needs to be expanded, for 1130 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1131 // the value into n parts and use a vector type with n-times the elements. 1132 // Then bitcast to the type requested. 1133 // Legalizing constants too early makes the DAGCombiner's job harder so we 1134 // only legalize if the DAG tells us we must produce legal types. 1135 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1136 TLI->getTypeAction(*getContext(), EltVT) == 1137 TargetLowering::TypeExpandInteger) { 1138 const APInt &NewVal = Elt->getValue(); 1139 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1140 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1141 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1142 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1143 1144 // Check the temporary vector is the correct size. If this fails then 1145 // getTypeToTransformTo() probably returned a type whose size (in bits) 1146 // isn't a power-of-2 factor of the requested type size. 1147 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1148 1149 SmallVector<SDValue, 2> EltParts; 1150 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) { 1151 EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits) 1152 .trunc(ViaEltSizeInBits), DL, 1153 ViaEltVT, isT, isO)); 1154 } 1155 1156 // EltParts is currently in little endian order. If we actually want 1157 // big-endian order then reverse it now. 1158 if (getDataLayout().isBigEndian()) 1159 std::reverse(EltParts.begin(), EltParts.end()); 1160 1161 // The elements must be reversed when the element order is different 1162 // to the endianness of the elements (because the BITCAST is itself a 1163 // vector shuffle in this situation). However, we do not need any code to 1164 // perform this reversal because getConstant() is producing a vector 1165 // splat. 1166 // This situation occurs in MIPS MSA. 1167 1168 SmallVector<SDValue, 8> Ops; 1169 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) 1170 Ops.insert(Ops.end(), EltParts.begin(), EltParts.end()); 1171 1172 SDValue Result = getNode(ISD::BITCAST, DL, VT, 1173 getNode(ISD::BUILD_VECTOR, DL, ViaVecVT, Ops)); 1174 return Result; 1175 } 1176 1177 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1178 "APInt size does not match type size!"); 1179 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1180 FoldingSetNodeID ID; 1181 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1182 ID.AddPointer(Elt); 1183 ID.AddBoolean(isO); 1184 void *IP = nullptr; 1185 SDNode *N = nullptr; 1186 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1187 if (!VT.isVector()) 1188 return SDValue(N, 0); 1189 1190 if (!N) { 1191 N = newSDNode<ConstantSDNode>(isT, isO, Elt, DL.getDebugLoc(), EltVT); 1192 CSEMap.InsertNode(N, IP); 1193 InsertNode(N); 1194 } 1195 1196 SDValue Result(N, 0); 1197 if (VT.isVector()) 1198 Result = getSplatBuildVector(VT, DL, Result); 1199 return Result; 1200 } 1201 1202 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1203 bool isTarget) { 1204 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1205 } 1206 1207 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1208 bool isTarget) { 1209 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1210 } 1211 1212 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1213 EVT VT, bool isTarget) { 1214 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1215 1216 EVT EltVT = VT.getScalarType(); 1217 1218 // Do the map lookup using the actual bit pattern for the floating point 1219 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1220 // we don't have issues with SNANs. 1221 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1222 FoldingSetNodeID ID; 1223 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1224 ID.AddPointer(&V); 1225 void *IP = nullptr; 1226 SDNode *N = nullptr; 1227 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1228 if (!VT.isVector()) 1229 return SDValue(N, 0); 1230 1231 if (!N) { 1232 N = newSDNode<ConstantFPSDNode>(isTarget, &V, DL.getDebugLoc(), EltVT); 1233 CSEMap.InsertNode(N, IP); 1234 InsertNode(N); 1235 } 1236 1237 SDValue Result(N, 0); 1238 if (VT.isVector()) 1239 Result = getSplatBuildVector(VT, DL, Result); 1240 return Result; 1241 } 1242 1243 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1244 bool isTarget) { 1245 EVT EltVT = VT.getScalarType(); 1246 if (EltVT == MVT::f32) 1247 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1248 else if (EltVT == MVT::f64) 1249 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1250 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1251 EltVT == MVT::f16) { 1252 bool Ignored; 1253 APFloat APF = APFloat(Val); 1254 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1255 &Ignored); 1256 return getConstantFP(APF, DL, VT, isTarget); 1257 } else 1258 llvm_unreachable("Unsupported type in getConstantFP"); 1259 } 1260 1261 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1262 EVT VT, int64_t Offset, bool isTargetGA, 1263 unsigned char TargetFlags) { 1264 assert((TargetFlags == 0 || isTargetGA) && 1265 "Cannot set target flags on target-independent globals"); 1266 1267 // Truncate (with sign-extension) the offset value to the pointer size. 1268 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1269 if (BitWidth < 64) 1270 Offset = SignExtend64(Offset, BitWidth); 1271 1272 unsigned Opc; 1273 if (GV->isThreadLocal()) 1274 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1275 else 1276 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1277 1278 FoldingSetNodeID ID; 1279 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1280 ID.AddPointer(GV); 1281 ID.AddInteger(Offset); 1282 ID.AddInteger(TargetFlags); 1283 ID.AddInteger(GV->getType()->getAddressSpace()); 1284 void *IP = nullptr; 1285 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1286 return SDValue(E, 0); 1287 1288 auto *N = newSDNode<GlobalAddressSDNode>( 1289 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1290 CSEMap.InsertNode(N, IP); 1291 InsertNode(N); 1292 return SDValue(N, 0); 1293 } 1294 1295 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1296 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1297 FoldingSetNodeID ID; 1298 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1299 ID.AddInteger(FI); 1300 void *IP = nullptr; 1301 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1302 return SDValue(E, 0); 1303 1304 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1305 CSEMap.InsertNode(N, IP); 1306 InsertNode(N); 1307 return SDValue(N, 0); 1308 } 1309 1310 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1311 unsigned char TargetFlags) { 1312 assert((TargetFlags == 0 || isTarget) && 1313 "Cannot set target flags on target-independent jump tables"); 1314 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1315 FoldingSetNodeID ID; 1316 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1317 ID.AddInteger(JTI); 1318 ID.AddInteger(TargetFlags); 1319 void *IP = nullptr; 1320 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1321 return SDValue(E, 0); 1322 1323 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1324 CSEMap.InsertNode(N, IP); 1325 InsertNode(N); 1326 return SDValue(N, 0); 1327 } 1328 1329 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1330 unsigned Alignment, int Offset, 1331 bool isTarget, 1332 unsigned char TargetFlags) { 1333 assert((TargetFlags == 0 || isTarget) && 1334 "Cannot set target flags on target-independent globals"); 1335 if (Alignment == 0) 1336 Alignment = getDataLayout().getPrefTypeAlignment(C->getType()); 1337 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1338 FoldingSetNodeID ID; 1339 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1340 ID.AddInteger(Alignment); 1341 ID.AddInteger(Offset); 1342 ID.AddPointer(C); 1343 ID.AddInteger(TargetFlags); 1344 void *IP = nullptr; 1345 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1346 return SDValue(E, 0); 1347 1348 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment, 1349 TargetFlags); 1350 CSEMap.InsertNode(N, IP); 1351 InsertNode(N); 1352 return SDValue(N, 0); 1353 } 1354 1355 1356 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1357 unsigned Alignment, int Offset, 1358 bool isTarget, 1359 unsigned char TargetFlags) { 1360 assert((TargetFlags == 0 || isTarget) && 1361 "Cannot set target flags on target-independent globals"); 1362 if (Alignment == 0) 1363 Alignment = getDataLayout().getPrefTypeAlignment(C->getType()); 1364 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1365 FoldingSetNodeID ID; 1366 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1367 ID.AddInteger(Alignment); 1368 ID.AddInteger(Offset); 1369 C->addSelectionDAGCSEId(ID); 1370 ID.AddInteger(TargetFlags); 1371 void *IP = nullptr; 1372 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1373 return SDValue(E, 0); 1374 1375 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment, 1376 TargetFlags); 1377 CSEMap.InsertNode(N, IP); 1378 InsertNode(N); 1379 return SDValue(N, 0); 1380 } 1381 1382 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1383 unsigned char TargetFlags) { 1384 FoldingSetNodeID ID; 1385 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1386 ID.AddInteger(Index); 1387 ID.AddInteger(Offset); 1388 ID.AddInteger(TargetFlags); 1389 void *IP = nullptr; 1390 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1391 return SDValue(E, 0); 1392 1393 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1394 CSEMap.InsertNode(N, IP); 1395 InsertNode(N); 1396 return SDValue(N, 0); 1397 } 1398 1399 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1400 FoldingSetNodeID ID; 1401 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1402 ID.AddPointer(MBB); 1403 void *IP = nullptr; 1404 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1405 return SDValue(E, 0); 1406 1407 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1408 CSEMap.InsertNode(N, IP); 1409 InsertNode(N); 1410 return SDValue(N, 0); 1411 } 1412 1413 SDValue SelectionDAG::getValueType(EVT VT) { 1414 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1415 ValueTypeNodes.size()) 1416 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1417 1418 SDNode *&N = VT.isExtended() ? 1419 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1420 1421 if (N) return SDValue(N, 0); 1422 N = newSDNode<VTSDNode>(VT); 1423 InsertNode(N); 1424 return SDValue(N, 0); 1425 } 1426 1427 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1428 SDNode *&N = ExternalSymbols[Sym]; 1429 if (N) return SDValue(N, 0); 1430 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1431 InsertNode(N); 1432 return SDValue(N, 0); 1433 } 1434 1435 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1436 SDNode *&N = MCSymbols[Sym]; 1437 if (N) 1438 return SDValue(N, 0); 1439 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1440 InsertNode(N); 1441 return SDValue(N, 0); 1442 } 1443 1444 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1445 unsigned char TargetFlags) { 1446 SDNode *&N = 1447 TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym, 1448 TargetFlags)]; 1449 if (N) return SDValue(N, 0); 1450 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1451 InsertNode(N); 1452 return SDValue(N, 0); 1453 } 1454 1455 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1456 if ((unsigned)Cond >= CondCodeNodes.size()) 1457 CondCodeNodes.resize(Cond+1); 1458 1459 if (!CondCodeNodes[Cond]) { 1460 auto *N = newSDNode<CondCodeSDNode>(Cond); 1461 CondCodeNodes[Cond] = N; 1462 InsertNode(N); 1463 } 1464 1465 return SDValue(CondCodeNodes[Cond], 0); 1466 } 1467 1468 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1469 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1470 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1471 std::swap(N1, N2); 1472 ShuffleVectorSDNode::commuteMask(M); 1473 } 1474 1475 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1476 SDValue N2, ArrayRef<int> Mask) { 1477 assert(VT.getVectorNumElements() == Mask.size() && 1478 "Must have the same number of vector elements as mask elements!"); 1479 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1480 "Invalid VECTOR_SHUFFLE"); 1481 1482 // Canonicalize shuffle undef, undef -> undef 1483 if (N1.isUndef() && N2.isUndef()) 1484 return getUNDEF(VT); 1485 1486 // Validate that all indices in Mask are within the range of the elements 1487 // input to the shuffle. 1488 int NElts = Mask.size(); 1489 assert(all_of(Mask, [&](int M) { return M < (NElts * 2); }) && 1490 "Index out of range"); 1491 1492 // Copy the mask so we can do any needed cleanup. 1493 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1494 1495 // Canonicalize shuffle v, v -> v, undef 1496 if (N1 == N2) { 1497 N2 = getUNDEF(VT); 1498 for (int i = 0; i != NElts; ++i) 1499 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1500 } 1501 1502 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1503 if (N1.isUndef()) 1504 commuteShuffle(N1, N2, MaskVec); 1505 1506 // If shuffling a splat, try to blend the splat instead. We do this here so 1507 // that even when this arises during lowering we don't have to re-handle it. 1508 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1509 BitVector UndefElements; 1510 SDValue Splat = BV->getSplatValue(&UndefElements); 1511 if (!Splat) 1512 return; 1513 1514 for (int i = 0; i < NElts; ++i) { 1515 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1516 continue; 1517 1518 // If this input comes from undef, mark it as such. 1519 if (UndefElements[MaskVec[i] - Offset]) { 1520 MaskVec[i] = -1; 1521 continue; 1522 } 1523 1524 // If we can blend a non-undef lane, use that instead. 1525 if (!UndefElements[i]) 1526 MaskVec[i] = i + Offset; 1527 } 1528 }; 1529 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1530 BlendSplat(N1BV, 0); 1531 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1532 BlendSplat(N2BV, NElts); 1533 1534 // Canonicalize all index into lhs, -> shuffle lhs, undef 1535 // Canonicalize all index into rhs, -> shuffle rhs, undef 1536 bool AllLHS = true, AllRHS = true; 1537 bool N2Undef = N2.isUndef(); 1538 for (int i = 0; i != NElts; ++i) { 1539 if (MaskVec[i] >= NElts) { 1540 if (N2Undef) 1541 MaskVec[i] = -1; 1542 else 1543 AllLHS = false; 1544 } else if (MaskVec[i] >= 0) { 1545 AllRHS = false; 1546 } 1547 } 1548 if (AllLHS && AllRHS) 1549 return getUNDEF(VT); 1550 if (AllLHS && !N2Undef) 1551 N2 = getUNDEF(VT); 1552 if (AllRHS) { 1553 N1 = getUNDEF(VT); 1554 commuteShuffle(N1, N2, MaskVec); 1555 } 1556 // Reset our undef status after accounting for the mask. 1557 N2Undef = N2.isUndef(); 1558 // Re-check whether both sides ended up undef. 1559 if (N1.isUndef() && N2Undef) 1560 return getUNDEF(VT); 1561 1562 // If Identity shuffle return that node. 1563 bool Identity = true, AllSame = true; 1564 for (int i = 0; i != NElts; ++i) { 1565 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1566 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1567 } 1568 if (Identity && NElts) 1569 return N1; 1570 1571 // Shuffling a constant splat doesn't change the result. 1572 if (N2Undef) { 1573 SDValue V = N1; 1574 1575 // Look through any bitcasts. We check that these don't change the number 1576 // (and size) of elements and just changes their types. 1577 while (V.getOpcode() == ISD::BITCAST) 1578 V = V->getOperand(0); 1579 1580 // A splat should always show up as a build vector node. 1581 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1582 BitVector UndefElements; 1583 SDValue Splat = BV->getSplatValue(&UndefElements); 1584 // If this is a splat of an undef, shuffling it is also undef. 1585 if (Splat && Splat.isUndef()) 1586 return getUNDEF(VT); 1587 1588 bool SameNumElts = 1589 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1590 1591 // We only have a splat which can skip shuffles if there is a splatted 1592 // value and no undef lanes rearranged by the shuffle. 1593 if (Splat && UndefElements.none()) { 1594 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1595 // number of elements match or the value splatted is a zero constant. 1596 if (SameNumElts) 1597 return N1; 1598 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1599 if (C->isNullValue()) 1600 return N1; 1601 } 1602 1603 // If the shuffle itself creates a splat, build the vector directly. 1604 if (AllSame && SameNumElts) { 1605 EVT BuildVT = BV->getValueType(0); 1606 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1607 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1608 1609 // We may have jumped through bitcasts, so the type of the 1610 // BUILD_VECTOR may not match the type of the shuffle. 1611 if (BuildVT != VT) 1612 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1613 return NewBV; 1614 } 1615 } 1616 } 1617 1618 FoldingSetNodeID ID; 1619 SDValue Ops[2] = { N1, N2 }; 1620 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1621 for (int i = 0; i != NElts; ++i) 1622 ID.AddInteger(MaskVec[i]); 1623 1624 void* IP = nullptr; 1625 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1626 return SDValue(E, 0); 1627 1628 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1629 // SDNode doesn't have access to it. This memory will be "leaked" when 1630 // the node is deallocated, but recovered when the NodeAllocator is released. 1631 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1632 std::copy(MaskVec.begin(), MaskVec.end(), MaskAlloc); 1633 1634 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 1635 dl.getDebugLoc(), MaskAlloc); 1636 createOperands(N, Ops); 1637 1638 CSEMap.InsertNode(N, IP); 1639 InsertNode(N); 1640 return SDValue(N, 0); 1641 } 1642 1643 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 1644 MVT VT = SV.getSimpleValueType(0); 1645 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 1646 ShuffleVectorSDNode::commuteMask(MaskVec); 1647 1648 SDValue Op0 = SV.getOperand(0); 1649 SDValue Op1 = SV.getOperand(1); 1650 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 1651 } 1652 1653 SDValue SelectionDAG::getConvertRndSat(EVT VT, const SDLoc &dl, SDValue Val, 1654 SDValue DTy, SDValue STy, SDValue Rnd, 1655 SDValue Sat, ISD::CvtCode Code) { 1656 // If the src and dest types are the same and the conversion is between 1657 // integer types of the same sign or two floats, no conversion is necessary. 1658 if (DTy == STy && 1659 (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF)) 1660 return Val; 1661 1662 FoldingSetNodeID ID; 1663 SDValue Ops[] = { Val, DTy, STy, Rnd, Sat }; 1664 AddNodeIDNode(ID, ISD::CONVERT_RNDSAT, getVTList(VT), Ops); 1665 void* IP = nullptr; 1666 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1667 return SDValue(E, 0); 1668 1669 auto *N = 1670 newSDNode<CvtRndSatSDNode>(VT, dl.getIROrder(), dl.getDebugLoc(), Code); 1671 createOperands(N, Ops); 1672 1673 CSEMap.InsertNode(N, IP); 1674 InsertNode(N); 1675 return SDValue(N, 0); 1676 } 1677 1678 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1679 FoldingSetNodeID ID; 1680 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 1681 ID.AddInteger(RegNo); 1682 void *IP = nullptr; 1683 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1684 return SDValue(E, 0); 1685 1686 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 1687 CSEMap.InsertNode(N, IP); 1688 InsertNode(N); 1689 return SDValue(N, 0); 1690 } 1691 1692 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 1693 FoldingSetNodeID ID; 1694 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 1695 ID.AddPointer(RegMask); 1696 void *IP = nullptr; 1697 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1698 return SDValue(E, 0); 1699 1700 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 1701 CSEMap.InsertNode(N, IP); 1702 InsertNode(N); 1703 return SDValue(N, 0); 1704 } 1705 1706 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 1707 MCSymbol *Label) { 1708 FoldingSetNodeID ID; 1709 SDValue Ops[] = { Root }; 1710 AddNodeIDNode(ID, ISD::EH_LABEL, getVTList(MVT::Other), Ops); 1711 ID.AddPointer(Label); 1712 void *IP = nullptr; 1713 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1714 return SDValue(E, 0); 1715 1716 auto *N = newSDNode<EHLabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label); 1717 createOperands(N, Ops); 1718 1719 CSEMap.InsertNode(N, IP); 1720 InsertNode(N); 1721 return SDValue(N, 0); 1722 } 1723 1724 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 1725 int64_t Offset, 1726 bool isTarget, 1727 unsigned char TargetFlags) { 1728 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 1729 1730 FoldingSetNodeID ID; 1731 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1732 ID.AddPointer(BA); 1733 ID.AddInteger(Offset); 1734 ID.AddInteger(TargetFlags); 1735 void *IP = nullptr; 1736 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1737 return SDValue(E, 0); 1738 1739 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 1740 CSEMap.InsertNode(N, IP); 1741 InsertNode(N); 1742 return SDValue(N, 0); 1743 } 1744 1745 SDValue SelectionDAG::getSrcValue(const Value *V) { 1746 assert((!V || V->getType()->isPointerTy()) && 1747 "SrcValue is not a pointer?"); 1748 1749 FoldingSetNodeID ID; 1750 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 1751 ID.AddPointer(V); 1752 1753 void *IP = nullptr; 1754 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1755 return SDValue(E, 0); 1756 1757 auto *N = newSDNode<SrcValueSDNode>(V); 1758 CSEMap.InsertNode(N, IP); 1759 InsertNode(N); 1760 return SDValue(N, 0); 1761 } 1762 1763 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 1764 FoldingSetNodeID ID; 1765 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 1766 ID.AddPointer(MD); 1767 1768 void *IP = nullptr; 1769 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1770 return SDValue(E, 0); 1771 1772 auto *N = newSDNode<MDNodeSDNode>(MD); 1773 CSEMap.InsertNode(N, IP); 1774 InsertNode(N); 1775 return SDValue(N, 0); 1776 } 1777 1778 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 1779 if (VT == V.getValueType()) 1780 return V; 1781 1782 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 1783 } 1784 1785 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 1786 unsigned SrcAS, unsigned DestAS) { 1787 SDValue Ops[] = {Ptr}; 1788 FoldingSetNodeID ID; 1789 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 1790 ID.AddInteger(SrcAS); 1791 ID.AddInteger(DestAS); 1792 1793 void *IP = nullptr; 1794 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1795 return SDValue(E, 0); 1796 1797 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 1798 VT, SrcAS, DestAS); 1799 createOperands(N, Ops); 1800 1801 CSEMap.InsertNode(N, IP); 1802 InsertNode(N); 1803 return SDValue(N, 0); 1804 } 1805 1806 /// getShiftAmountOperand - Return the specified value casted to 1807 /// the target's desired shift amount type. 1808 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 1809 EVT OpTy = Op.getValueType(); 1810 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 1811 if (OpTy == ShTy || OpTy.isVector()) return Op; 1812 1813 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 1814 } 1815 1816 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 1817 SDLoc dl(Node); 1818 const TargetLowering &TLI = getTargetLoweringInfo(); 1819 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 1820 EVT VT = Node->getValueType(0); 1821 SDValue Tmp1 = Node->getOperand(0); 1822 SDValue Tmp2 = Node->getOperand(1); 1823 unsigned Align = Node->getConstantOperandVal(3); 1824 1825 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 1826 Tmp2, MachinePointerInfo(V)); 1827 SDValue VAList = VAListLoad; 1828 1829 if (Align > TLI.getMinStackArgumentAlignment()) { 1830 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2"); 1831 1832 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 1833 getConstant(Align - 1, dl, VAList.getValueType())); 1834 1835 VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList, 1836 getConstant(-(int64_t)Align, dl, VAList.getValueType())); 1837 } 1838 1839 // Increment the pointer, VAList, to the next vaarg 1840 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 1841 getConstant(getDataLayout().getTypeAllocSize( 1842 VT.getTypeForEVT(*getContext())), 1843 dl, VAList.getValueType())); 1844 // Store the incremented VAList to the legalized pointer 1845 Tmp1 = 1846 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 1847 // Load the actual argument out of the pointer VAList 1848 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 1849 } 1850 1851 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 1852 SDLoc dl(Node); 1853 const TargetLowering &TLI = getTargetLoweringInfo(); 1854 // This defaults to loading a pointer from the input and storing it to the 1855 // output, returning the chain. 1856 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 1857 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 1858 SDValue Tmp1 = 1859 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 1860 Node->getOperand(2), MachinePointerInfo(VS)); 1861 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 1862 MachinePointerInfo(VD)); 1863 } 1864 1865 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 1866 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo(); 1867 unsigned ByteSize = VT.getStoreSize(); 1868 Type *Ty = VT.getTypeForEVT(*getContext()); 1869 unsigned StackAlign = 1870 std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign); 1871 1872 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false); 1873 return getFrameIndex(FrameIdx, TLI->getPointerTy(getDataLayout())); 1874 } 1875 1876 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 1877 unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize()); 1878 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 1879 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 1880 const DataLayout &DL = getDataLayout(); 1881 unsigned Align = 1882 std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2)); 1883 1884 MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo(); 1885 int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align, false); 1886 return getFrameIndex(FrameIdx, TLI->getPointerTy(getDataLayout())); 1887 } 1888 1889 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 1890 ISD::CondCode Cond, const SDLoc &dl) { 1891 // These setcc operations always fold. 1892 switch (Cond) { 1893 default: break; 1894 case ISD::SETFALSE: 1895 case ISD::SETFALSE2: return getConstant(0, dl, VT); 1896 case ISD::SETTRUE: 1897 case ISD::SETTRUE2: { 1898 TargetLowering::BooleanContent Cnt = 1899 TLI->getBooleanContents(N1->getValueType(0)); 1900 return getConstant( 1901 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl, 1902 VT); 1903 } 1904 1905 case ISD::SETOEQ: 1906 case ISD::SETOGT: 1907 case ISD::SETOGE: 1908 case ISD::SETOLT: 1909 case ISD::SETOLE: 1910 case ISD::SETONE: 1911 case ISD::SETO: 1912 case ISD::SETUO: 1913 case ISD::SETUEQ: 1914 case ISD::SETUNE: 1915 assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!"); 1916 break; 1917 } 1918 1919 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 1920 const APInt &C2 = N2C->getAPIntValue(); 1921 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 1922 const APInt &C1 = N1C->getAPIntValue(); 1923 1924 switch (Cond) { 1925 default: llvm_unreachable("Unknown integer setcc!"); 1926 case ISD::SETEQ: return getConstant(C1 == C2, dl, VT); 1927 case ISD::SETNE: return getConstant(C1 != C2, dl, VT); 1928 case ISD::SETULT: return getConstant(C1.ult(C2), dl, VT); 1929 case ISD::SETUGT: return getConstant(C1.ugt(C2), dl, VT); 1930 case ISD::SETULE: return getConstant(C1.ule(C2), dl, VT); 1931 case ISD::SETUGE: return getConstant(C1.uge(C2), dl, VT); 1932 case ISD::SETLT: return getConstant(C1.slt(C2), dl, VT); 1933 case ISD::SETGT: return getConstant(C1.sgt(C2), dl, VT); 1934 case ISD::SETLE: return getConstant(C1.sle(C2), dl, VT); 1935 case ISD::SETGE: return getConstant(C1.sge(C2), dl, VT); 1936 } 1937 } 1938 } 1939 if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) { 1940 if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) { 1941 APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF()); 1942 switch (Cond) { 1943 default: break; 1944 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 1945 return getUNDEF(VT); 1946 // fall through 1947 case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, dl, VT); 1948 case ISD::SETNE: if (R==APFloat::cmpUnordered) 1949 return getUNDEF(VT); 1950 // fall through 1951 case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan || 1952 R==APFloat::cmpLessThan, dl, VT); 1953 case ISD::SETLT: if (R==APFloat::cmpUnordered) 1954 return getUNDEF(VT); 1955 // fall through 1956 case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, dl, VT); 1957 case ISD::SETGT: if (R==APFloat::cmpUnordered) 1958 return getUNDEF(VT); 1959 // fall through 1960 case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, dl, VT); 1961 case ISD::SETLE: if (R==APFloat::cmpUnordered) 1962 return getUNDEF(VT); 1963 // fall through 1964 case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan || 1965 R==APFloat::cmpEqual, dl, VT); 1966 case ISD::SETGE: if (R==APFloat::cmpUnordered) 1967 return getUNDEF(VT); 1968 // fall through 1969 case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan || 1970 R==APFloat::cmpEqual, dl, VT); 1971 case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, dl, VT); 1972 case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, dl, VT); 1973 case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered || 1974 R==APFloat::cmpEqual, dl, VT); 1975 case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, dl, VT); 1976 case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered || 1977 R==APFloat::cmpLessThan, dl, VT); 1978 case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan || 1979 R==APFloat::cmpUnordered, dl, VT); 1980 case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, dl, VT); 1981 case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, dl, VT); 1982 } 1983 } else { 1984 // Ensure that the constant occurs on the RHS. 1985 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 1986 MVT CompVT = N1.getValueType().getSimpleVT(); 1987 if (!TLI->isCondCodeLegal(SwappedCond, CompVT)) 1988 return SDValue(); 1989 1990 return getSetCC(dl, VT, N2, N1, SwappedCond); 1991 } 1992 } 1993 1994 // Could not fold it. 1995 return SDValue(); 1996 } 1997 1998 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 1999 /// use this predicate to simplify operations downstream. 2000 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2001 // This predicate is not safe for vector operations. 2002 if (Op.getValueType().isVector()) 2003 return false; 2004 2005 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 2006 return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth); 2007 } 2008 2009 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2010 /// this predicate to simplify operations downstream. Mask is known to be zero 2011 /// for bits that V cannot have. 2012 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask, 2013 unsigned Depth) const { 2014 APInt KnownZero, KnownOne; 2015 computeKnownBits(Op, KnownZero, KnownOne, Depth); 2016 return (KnownZero & Mask) == Mask; 2017 } 2018 2019 /// Determine which bits of Op are known to be either zero or one and return 2020 /// them in the KnownZero/KnownOne bitsets. 2021 void SelectionDAG::computeKnownBits(SDValue Op, APInt &KnownZero, 2022 APInt &KnownOne, unsigned Depth) const { 2023 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits(); 2024 2025 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything. 2026 if (Depth == 6) 2027 return; // Limit search depth. 2028 2029 APInt KnownZero2, KnownOne2; 2030 2031 switch (Op.getOpcode()) { 2032 case ISD::Constant: 2033 // We know all of the bits for a constant! 2034 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue(); 2035 KnownZero = ~KnownOne; 2036 break; 2037 case ISD::AND: 2038 // If either the LHS or the RHS are Zero, the result is zero. 2039 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2040 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2041 2042 // Output known-1 bits are only known if set in both the LHS & RHS. 2043 KnownOne &= KnownOne2; 2044 // Output known-0 are known to be clear if zero in either the LHS | RHS. 2045 KnownZero |= KnownZero2; 2046 break; 2047 case ISD::OR: 2048 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2049 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2050 2051 // Output known-0 bits are only known if clear in both the LHS & RHS. 2052 KnownZero &= KnownZero2; 2053 // Output known-1 are known to be set if set in either the LHS | RHS. 2054 KnownOne |= KnownOne2; 2055 break; 2056 case ISD::XOR: { 2057 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2058 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2059 2060 // Output known-0 bits are known if clear or set in both the LHS & RHS. 2061 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 2062 // Output known-1 are known to be set if set in only one of the LHS, RHS. 2063 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 2064 KnownZero = KnownZeroOut; 2065 break; 2066 } 2067 case ISD::MUL: { 2068 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2069 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2070 2071 // If low bits are zero in either operand, output low known-0 bits. 2072 // Also compute a conserative estimate for high known-0 bits. 2073 // More trickiness is possible, but this is sufficient for the 2074 // interesting case of alignment computation. 2075 KnownOne.clearAllBits(); 2076 unsigned TrailZ = KnownZero.countTrailingOnes() + 2077 KnownZero2.countTrailingOnes(); 2078 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() + 2079 KnownZero2.countLeadingOnes(), 2080 BitWidth) - BitWidth; 2081 2082 TrailZ = std::min(TrailZ, BitWidth); 2083 LeadZ = std::min(LeadZ, BitWidth); 2084 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) | 2085 APInt::getHighBitsSet(BitWidth, LeadZ); 2086 break; 2087 } 2088 case ISD::UDIV: { 2089 // For the purposes of computing leading zeros we can conservatively 2090 // treat a udiv as a logical right shift by the power of 2 known to 2091 // be less than the denominator. 2092 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2093 unsigned LeadZ = KnownZero2.countLeadingOnes(); 2094 2095 KnownOne2.clearAllBits(); 2096 KnownZero2.clearAllBits(); 2097 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2098 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros(); 2099 if (RHSUnknownLeadingOnes != BitWidth) 2100 LeadZ = std::min(BitWidth, 2101 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1); 2102 2103 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ); 2104 break; 2105 } 2106 case ISD::SELECT: 2107 computeKnownBits(Op.getOperand(2), KnownZero, KnownOne, Depth+1); 2108 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2109 2110 // Only known if known in both the LHS and RHS. 2111 KnownOne &= KnownOne2; 2112 KnownZero &= KnownZero2; 2113 break; 2114 case ISD::SELECT_CC: 2115 computeKnownBits(Op.getOperand(3), KnownZero, KnownOne, Depth+1); 2116 computeKnownBits(Op.getOperand(2), KnownZero2, KnownOne2, Depth+1); 2117 2118 // Only known if known in both the LHS and RHS. 2119 KnownOne &= KnownOne2; 2120 KnownZero &= KnownZero2; 2121 break; 2122 case ISD::SADDO: 2123 case ISD::UADDO: 2124 case ISD::SSUBO: 2125 case ISD::USUBO: 2126 case ISD::SMULO: 2127 case ISD::UMULO: 2128 if (Op.getResNo() != 1) 2129 break; 2130 // The boolean result conforms to getBooleanContents. 2131 // If we know the result of a setcc has the top bits zero, use this info. 2132 // We know that we have an integer-based boolean since these operations 2133 // are only available for integer. 2134 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 2135 TargetLowering::ZeroOrOneBooleanContent && 2136 BitWidth > 1) 2137 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2138 break; 2139 case ISD::SETCC: 2140 // If we know the result of a setcc has the top bits zero, use this info. 2141 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 2142 TargetLowering::ZeroOrOneBooleanContent && 2143 BitWidth > 1) 2144 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2145 break; 2146 case ISD::SHL: 2147 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0 2148 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2149 unsigned ShAmt = SA->getZExtValue(); 2150 2151 // If the shift count is an invalid immediate, don't do anything. 2152 if (ShAmt >= BitWidth) 2153 break; 2154 2155 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2156 KnownZero <<= ShAmt; 2157 KnownOne <<= ShAmt; 2158 // low bits known zero. 2159 KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt); 2160 } 2161 break; 2162 case ISD::SRL: 2163 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0 2164 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2165 unsigned ShAmt = SA->getZExtValue(); 2166 2167 // If the shift count is an invalid immediate, don't do anything. 2168 if (ShAmt >= BitWidth) 2169 break; 2170 2171 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2172 KnownZero = KnownZero.lshr(ShAmt); 2173 KnownOne = KnownOne.lshr(ShAmt); 2174 2175 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 2176 KnownZero |= HighBits; // High bits known zero. 2177 } 2178 break; 2179 case ISD::SRA: 2180 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2181 unsigned ShAmt = SA->getZExtValue(); 2182 2183 // If the shift count is an invalid immediate, don't do anything. 2184 if (ShAmt >= BitWidth) 2185 break; 2186 2187 // If any of the demanded bits are produced by the sign extension, we also 2188 // demand the input sign bit. 2189 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 2190 2191 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2192 KnownZero = KnownZero.lshr(ShAmt); 2193 KnownOne = KnownOne.lshr(ShAmt); 2194 2195 // Handle the sign bits. 2196 APInt SignBit = APInt::getSignBit(BitWidth); 2197 SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask. 2198 2199 if (KnownZero.intersects(SignBit)) { 2200 KnownZero |= HighBits; // New bits are known zero. 2201 } else if (KnownOne.intersects(SignBit)) { 2202 KnownOne |= HighBits; // New bits are known one. 2203 } 2204 } 2205 break; 2206 case ISD::SIGN_EXTEND_INREG: { 2207 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2208 unsigned EBits = EVT.getScalarType().getSizeInBits(); 2209 2210 // Sign extension. Compute the demanded bits in the result that are not 2211 // present in the input. 2212 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits); 2213 2214 APInt InSignBit = APInt::getSignBit(EBits); 2215 APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits); 2216 2217 // If the sign extended bits are demanded, we know that the sign 2218 // bit is demanded. 2219 InSignBit = InSignBit.zext(BitWidth); 2220 if (NewBits.getBoolValue()) 2221 InputDemandedBits |= InSignBit; 2222 2223 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2224 KnownOne &= InputDemandedBits; 2225 KnownZero &= InputDemandedBits; 2226 2227 // If the sign bit of the input is known set or clear, then we know the 2228 // top bits of the result. 2229 if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear 2230 KnownZero |= NewBits; 2231 KnownOne &= ~NewBits; 2232 } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 2233 KnownOne |= NewBits; 2234 KnownZero &= ~NewBits; 2235 } else { // Input sign bit unknown 2236 KnownZero &= ~NewBits; 2237 KnownOne &= ~NewBits; 2238 } 2239 break; 2240 } 2241 case ISD::CTTZ: 2242 case ISD::CTTZ_ZERO_UNDEF: 2243 case ISD::CTLZ: 2244 case ISD::CTLZ_ZERO_UNDEF: 2245 case ISD::CTPOP: { 2246 unsigned LowBits = Log2_32(BitWidth)+1; 2247 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits); 2248 KnownOne.clearAllBits(); 2249 break; 2250 } 2251 case ISD::LOAD: { 2252 LoadSDNode *LD = cast<LoadSDNode>(Op); 2253 // If this is a ZEXTLoad and we are looking at the loaded value. 2254 if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 2255 EVT VT = LD->getMemoryVT(); 2256 unsigned MemBits = VT.getScalarType().getSizeInBits(); 2257 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 2258 } else if (const MDNode *Ranges = LD->getRanges()) { 2259 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 2260 computeKnownBitsFromRangeMetadata(*Ranges, KnownZero, KnownOne); 2261 } 2262 break; 2263 } 2264 case ISD::ZERO_EXTEND: { 2265 EVT InVT = Op.getOperand(0).getValueType(); 2266 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2267 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits); 2268 KnownZero = KnownZero.trunc(InBits); 2269 KnownOne = KnownOne.trunc(InBits); 2270 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2271 KnownZero = KnownZero.zext(BitWidth); 2272 KnownOne = KnownOne.zext(BitWidth); 2273 KnownZero |= NewBits; 2274 break; 2275 } 2276 case ISD::SIGN_EXTEND: { 2277 EVT InVT = Op.getOperand(0).getValueType(); 2278 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2279 APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits); 2280 2281 KnownZero = KnownZero.trunc(InBits); 2282 KnownOne = KnownOne.trunc(InBits); 2283 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2284 2285 // Note if the sign bit is known to be zero or one. 2286 bool SignBitKnownZero = KnownZero.isNegative(); 2287 bool SignBitKnownOne = KnownOne.isNegative(); 2288 2289 KnownZero = KnownZero.zext(BitWidth); 2290 KnownOne = KnownOne.zext(BitWidth); 2291 2292 // If the sign bit is known zero or one, the top bits match. 2293 if (SignBitKnownZero) 2294 KnownZero |= NewBits; 2295 else if (SignBitKnownOne) 2296 KnownOne |= NewBits; 2297 break; 2298 } 2299 case ISD::ANY_EXTEND: { 2300 EVT InVT = Op.getOperand(0).getValueType(); 2301 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2302 KnownZero = KnownZero.trunc(InBits); 2303 KnownOne = KnownOne.trunc(InBits); 2304 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2305 KnownZero = KnownZero.zext(BitWidth); 2306 KnownOne = KnownOne.zext(BitWidth); 2307 break; 2308 } 2309 case ISD::TRUNCATE: { 2310 EVT InVT = Op.getOperand(0).getValueType(); 2311 unsigned InBits = InVT.getScalarType().getSizeInBits(); 2312 KnownZero = KnownZero.zext(InBits); 2313 KnownOne = KnownOne.zext(InBits); 2314 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2315 KnownZero = KnownZero.trunc(BitWidth); 2316 KnownOne = KnownOne.trunc(BitWidth); 2317 break; 2318 } 2319 case ISD::AssertZext: { 2320 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 2321 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 2322 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2323 KnownZero |= (~InMask); 2324 KnownOne &= (~KnownZero); 2325 break; 2326 } 2327 case ISD::FGETSIGN: 2328 // All bits are zero except the low bit. 2329 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1); 2330 break; 2331 2332 case ISD::SUB: { 2333 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) { 2334 // We know that the top bits of C-X are clear if X contains less bits 2335 // than C (i.e. no wrap-around can happen). For example, 20-X is 2336 // positive if we can prove that X is >= 0 and < 16. 2337 if (CLHS->getAPIntValue().isNonNegative()) { 2338 unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros(); 2339 // NLZ can't be BitWidth with no sign bit 2340 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1); 2341 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2342 2343 // If all of the MaskV bits are known to be zero, then we know the 2344 // output top bits are zero, because we now know that the output is 2345 // from [0-C]. 2346 if ((KnownZero2 & MaskV) == MaskV) { 2347 unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros(); 2348 // Top bits known zero. 2349 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2); 2350 } 2351 } 2352 } 2353 } 2354 // fall through 2355 case ISD::ADD: 2356 case ISD::ADDE: { 2357 // Output known-0 bits are known if clear or set in both the low clear bits 2358 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the 2359 // low 3 bits clear. 2360 // Output known-0 bits are also known if the top bits of each input are 2361 // known to be clear. For example, if one input has the top 10 bits clear 2362 // and the other has the top 8 bits clear, we know the top 7 bits of the 2363 // output must be clear. 2364 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2365 unsigned KnownZeroHigh = KnownZero2.countLeadingOnes(); 2366 unsigned KnownZeroLow = KnownZero2.countTrailingOnes(); 2367 2368 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2369 KnownZeroHigh = std::min(KnownZeroHigh, 2370 KnownZero2.countLeadingOnes()); 2371 KnownZeroLow = std::min(KnownZeroLow, 2372 KnownZero2.countTrailingOnes()); 2373 2374 if (Op.getOpcode() == ISD::ADD) { 2375 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroLow); 2376 if (KnownZeroHigh > 1) 2377 KnownZero |= APInt::getHighBitsSet(BitWidth, KnownZeroHigh - 1); 2378 break; 2379 } 2380 2381 // With ADDE, a carry bit may be added in, so we can only use this 2382 // information if we know (at least) that the low two bits are clear. We 2383 // then return to the caller that the low bit is unknown but that other bits 2384 // are known zero. 2385 if (KnownZeroLow >= 2) // ADDE 2386 KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroLow); 2387 break; 2388 } 2389 case ISD::SREM: 2390 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2391 const APInt &RA = Rem->getAPIntValue().abs(); 2392 if (RA.isPowerOf2()) { 2393 APInt LowBits = RA - 1; 2394 computeKnownBits(Op.getOperand(0), KnownZero2,KnownOne2,Depth+1); 2395 2396 // The low bits of the first operand are unchanged by the srem. 2397 KnownZero = KnownZero2 & LowBits; 2398 KnownOne = KnownOne2 & LowBits; 2399 2400 // If the first operand is non-negative or has all low bits zero, then 2401 // the upper bits are all zero. 2402 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits)) 2403 KnownZero |= ~LowBits; 2404 2405 // If the first operand is negative and not all low bits are zero, then 2406 // the upper bits are all one. 2407 if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0)) 2408 KnownOne |= ~LowBits; 2409 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 2410 } 2411 } 2412 break; 2413 case ISD::UREM: { 2414 if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2415 const APInt &RA = Rem->getAPIntValue(); 2416 if (RA.isPowerOf2()) { 2417 APInt LowBits = (RA - 1); 2418 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth + 1); 2419 2420 // The upper bits are all zero, the lower ones are unchanged. 2421 KnownZero = KnownZero2 | ~LowBits; 2422 KnownOne = KnownOne2 & LowBits; 2423 break; 2424 } 2425 } 2426 2427 // Since the result is less than or equal to either operand, any leading 2428 // zero bits in either operand must also exist in the result. 2429 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2430 computeKnownBits(Op.getOperand(1), KnownZero2, KnownOne2, Depth+1); 2431 2432 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(), 2433 KnownZero2.countLeadingOnes()); 2434 KnownOne.clearAllBits(); 2435 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders); 2436 break; 2437 } 2438 case ISD::EXTRACT_ELEMENT: { 2439 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2440 const unsigned Index = 2441 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2442 const unsigned BitWidth = Op.getValueType().getSizeInBits(); 2443 2444 // Remove low part of known bits mask 2445 KnownZero = KnownZero.getHiBits(KnownZero.getBitWidth() - Index * BitWidth); 2446 KnownOne = KnownOne.getHiBits(KnownOne.getBitWidth() - Index * BitWidth); 2447 2448 // Remove high part of known bit mask 2449 KnownZero = KnownZero.trunc(BitWidth); 2450 KnownOne = KnownOne.trunc(BitWidth); 2451 break; 2452 } 2453 case ISD::BSWAP: { 2454 computeKnownBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1); 2455 KnownZero = KnownZero2.byteSwap(); 2456 KnownOne = KnownOne2.byteSwap(); 2457 break; 2458 } 2459 case ISD::SMIN: 2460 case ISD::SMAX: 2461 case ISD::UMIN: 2462 case ISD::UMAX: { 2463 APInt Op0Zero, Op0One; 2464 APInt Op1Zero, Op1One; 2465 computeKnownBits(Op.getOperand(0), Op0Zero, Op0One, Depth); 2466 computeKnownBits(Op.getOperand(1), Op1Zero, Op1One, Depth); 2467 2468 KnownZero = Op0Zero & Op1Zero; 2469 KnownOne = Op0One & Op1One; 2470 break; 2471 } 2472 case ISD::FrameIndex: 2473 case ISD::TargetFrameIndex: 2474 if (unsigned Align = InferPtrAlignment(Op)) { 2475 // The low bits are known zero if the pointer is aligned. 2476 KnownZero = APInt::getLowBitsSet(BitWidth, Log2_32(Align)); 2477 break; 2478 } 2479 break; 2480 2481 default: 2482 if (Op.getOpcode() < ISD::BUILTIN_OP_END) 2483 break; 2484 // Fallthrough 2485 case ISD::INTRINSIC_WO_CHAIN: 2486 case ISD::INTRINSIC_W_CHAIN: 2487 case ISD::INTRINSIC_VOID: 2488 // Allow the target to implement this method for its nodes. 2489 TLI->computeKnownBitsForTargetNode(Op, KnownZero, KnownOne, *this, Depth); 2490 break; 2491 } 2492 2493 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 2494 } 2495 2496 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 2497 // A left-shift of a constant one will have exactly one bit set because 2498 // shifting the bit off the end is undefined. 2499 if (Val.getOpcode() == ISD::SHL) { 2500 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0)); 2501 if (C && C->getAPIntValue() == 1) 2502 return true; 2503 } 2504 2505 // Similarly, a logical right-shift of a constant sign-bit will have exactly 2506 // one bit set. 2507 if (Val.getOpcode() == ISD::SRL) { 2508 auto *C = dyn_cast<ConstantSDNode>(Val.getOperand(0)); 2509 if (C && C->getAPIntValue().isSignBit()) 2510 return true; 2511 } 2512 2513 // More could be done here, though the above checks are enough 2514 // to handle some common cases. 2515 2516 // Fall back to computeKnownBits to catch other known cases. 2517 EVT OpVT = Val.getValueType(); 2518 unsigned BitWidth = OpVT.getScalarType().getSizeInBits(); 2519 APInt KnownZero, KnownOne; 2520 computeKnownBits(Val, KnownZero, KnownOne); 2521 return (KnownZero.countPopulation() == BitWidth - 1) && 2522 (KnownOne.countPopulation() == 1); 2523 } 2524 2525 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 2526 EVT VT = Op.getValueType(); 2527 assert(VT.isInteger() && "Invalid VT!"); 2528 unsigned VTBits = VT.getScalarType().getSizeInBits(); 2529 unsigned Tmp, Tmp2; 2530 unsigned FirstAnswer = 1; 2531 2532 if (Depth == 6) 2533 return 1; // Limit search depth. 2534 2535 switch (Op.getOpcode()) { 2536 default: break; 2537 case ISD::AssertSext: 2538 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2539 return VTBits-Tmp+1; 2540 case ISD::AssertZext: 2541 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 2542 return VTBits-Tmp; 2543 2544 case ISD::Constant: { 2545 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue(); 2546 return Val.getNumSignBits(); 2547 } 2548 2549 case ISD::SIGN_EXTEND: 2550 Tmp = 2551 VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 2552 return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp; 2553 2554 case ISD::SIGN_EXTEND_INREG: 2555 // Max of the input and what this extends. 2556 Tmp = 2557 cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits(); 2558 Tmp = VTBits-Tmp+1; 2559 2560 Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2561 return std::max(Tmp, Tmp2); 2562 2563 case ISD::SRA: 2564 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2565 // SRA X, C -> adds C sign bits. 2566 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2567 Tmp += C->getZExtValue(); 2568 if (Tmp > VTBits) Tmp = VTBits; 2569 } 2570 return Tmp; 2571 case ISD::SHL: 2572 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2573 // shl destroys sign bits. 2574 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2575 if (C->getZExtValue() >= VTBits || // Bad shift. 2576 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out. 2577 return Tmp - C->getZExtValue(); 2578 } 2579 break; 2580 case ISD::AND: 2581 case ISD::OR: 2582 case ISD::XOR: // NOT is handled here. 2583 // Logical binary ops preserve the number of sign bits at the worst. 2584 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2585 if (Tmp != 1) { 2586 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2587 FirstAnswer = std::min(Tmp, Tmp2); 2588 // We computed what we know about the sign bits as our first 2589 // answer. Now proceed to the generic code that uses 2590 // computeKnownBits, and pick whichever answer is better. 2591 } 2592 break; 2593 2594 case ISD::SELECT: 2595 Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2596 if (Tmp == 1) return 1; // Early out. 2597 Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1); 2598 return std::min(Tmp, Tmp2); 2599 case ISD::SELECT_CC: 2600 Tmp = ComputeNumSignBits(Op.getOperand(2), Depth+1); 2601 if (Tmp == 1) return 1; // Early out. 2602 Tmp2 = ComputeNumSignBits(Op.getOperand(3), Depth+1); 2603 return std::min(Tmp, Tmp2); 2604 case ISD::SMIN: 2605 case ISD::SMAX: 2606 case ISD::UMIN: 2607 case ISD::UMAX: 2608 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 2609 if (Tmp == 1) 2610 return 1; // Early out. 2611 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 2612 return std::min(Tmp, Tmp2); 2613 case ISD::SADDO: 2614 case ISD::UADDO: 2615 case ISD::SSUBO: 2616 case ISD::USUBO: 2617 case ISD::SMULO: 2618 case ISD::UMULO: 2619 if (Op.getResNo() != 1) 2620 break; 2621 // The boolean result conforms to getBooleanContents. Fall through. 2622 // If setcc returns 0/-1, all bits are sign bits. 2623 // We know that we have an integer-based boolean since these operations 2624 // are only available for integer. 2625 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 2626 TargetLowering::ZeroOrNegativeOneBooleanContent) 2627 return VTBits; 2628 break; 2629 case ISD::SETCC: 2630 // If setcc returns 0/-1, all bits are sign bits. 2631 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 2632 TargetLowering::ZeroOrNegativeOneBooleanContent) 2633 return VTBits; 2634 break; 2635 case ISD::ROTL: 2636 case ISD::ROTR: 2637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2638 unsigned RotAmt = C->getZExtValue() & (VTBits-1); 2639 2640 // Handle rotate right by N like a rotate left by 32-N. 2641 if (Op.getOpcode() == ISD::ROTR) 2642 RotAmt = (VTBits-RotAmt) & (VTBits-1); 2643 2644 // If we aren't rotating out all of the known-in sign bits, return the 2645 // number that are left. This handles rotl(sext(x), 1) for example. 2646 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2647 if (Tmp > RotAmt+1) return Tmp-RotAmt; 2648 } 2649 break; 2650 case ISD::ADD: 2651 // Add can have at most one carry bit. Thus we know that the output 2652 // is, at worst, one more bit than the inputs. 2653 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2654 if (Tmp == 1) return 1; // Early out. 2655 2656 // Special case decrementing a value (ADD X, -1): 2657 if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2658 if (CRHS->isAllOnesValue()) { 2659 APInt KnownZero, KnownOne; 2660 computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1); 2661 2662 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2663 // sign bits set. 2664 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue()) 2665 return VTBits; 2666 2667 // If we are subtracting one from a positive number, there is no carry 2668 // out of the result. 2669 if (KnownZero.isNegative()) 2670 return Tmp; 2671 } 2672 2673 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2674 if (Tmp2 == 1) return 1; 2675 return std::min(Tmp, Tmp2)-1; 2676 2677 case ISD::SUB: 2678 Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1); 2679 if (Tmp2 == 1) return 1; 2680 2681 // Handle NEG. 2682 if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) 2683 if (CLHS->isNullValue()) { 2684 APInt KnownZero, KnownOne; 2685 computeKnownBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1); 2686 // If the input is known to be 0 or 1, the output is 0/-1, which is all 2687 // sign bits set. 2688 if ((KnownZero | APInt(VTBits, 1)).isAllOnesValue()) 2689 return VTBits; 2690 2691 // If the input is known to be positive (the sign bit is known clear), 2692 // the output of the NEG has the same number of sign bits as the input. 2693 if (KnownZero.isNegative()) 2694 return Tmp2; 2695 2696 // Otherwise, we treat this like a SUB. 2697 } 2698 2699 // Sub can have at most one carry bit. Thus we know that the output 2700 // is, at worst, one more bit than the inputs. 2701 Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2702 if (Tmp == 1) return 1; // Early out. 2703 return std::min(Tmp, Tmp2)-1; 2704 case ISD::TRUNCATE: 2705 // FIXME: it's tricky to do anything useful for this, but it is an important 2706 // case for targets like X86. 2707 break; 2708 case ISD::EXTRACT_ELEMENT: { 2709 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 2710 const int BitWidth = Op.getValueType().getSizeInBits(); 2711 const int Items = 2712 Op.getOperand(0).getValueType().getSizeInBits() / BitWidth; 2713 2714 // Get reverse index (starting from 1), Op1 value indexes elements from 2715 // little end. Sign starts at big end. 2716 const int rIndex = Items - 1 - 2717 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 2718 2719 // If the sign portion ends in our element the subtraction gives correct 2720 // result. Otherwise it gives either negative or > bitwidth result 2721 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 2722 } 2723 } 2724 2725 // If we are looking at the loaded value of the SDNode. 2726 if (Op.getResNo() == 0) { 2727 // Handle LOADX separately here. EXTLOAD case will fallthrough. 2728 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 2729 unsigned ExtType = LD->getExtensionType(); 2730 switch (ExtType) { 2731 default: break; 2732 case ISD::SEXTLOAD: // '17' bits known 2733 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits(); 2734 return VTBits-Tmp+1; 2735 case ISD::ZEXTLOAD: // '16' bits known 2736 Tmp = LD->getMemoryVT().getScalarType().getSizeInBits(); 2737 return VTBits-Tmp; 2738 } 2739 } 2740 } 2741 2742 // Allow the target to implement this method for its nodes. 2743 if (Op.getOpcode() >= ISD::BUILTIN_OP_END || 2744 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2745 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2746 Op.getOpcode() == ISD::INTRINSIC_VOID) { 2747 unsigned NumBits = TLI->ComputeNumSignBitsForTargetNode(Op, *this, Depth); 2748 if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits); 2749 } 2750 2751 // Finally, if we can prove that the top bits of the result are 0's or 1's, 2752 // use this information. 2753 APInt KnownZero, KnownOne; 2754 computeKnownBits(Op, KnownZero, KnownOne, Depth); 2755 2756 APInt Mask; 2757 if (KnownZero.isNegative()) { // sign bit is 0 2758 Mask = KnownZero; 2759 } else if (KnownOne.isNegative()) { // sign bit is 1; 2760 Mask = KnownOne; 2761 } else { 2762 // Nothing known. 2763 return FirstAnswer; 2764 } 2765 2766 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine 2767 // the number of identical bits in the top of the input value. 2768 Mask = ~Mask; 2769 Mask <<= Mask.getBitWidth()-VTBits; 2770 // Return # leading zeros. We use 'min' here in case Val was zero before 2771 // shifting. We don't want to return '64' as for an i32 "0". 2772 return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros())); 2773 } 2774 2775 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 2776 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 2777 !isa<ConstantSDNode>(Op.getOperand(1))) 2778 return false; 2779 2780 if (Op.getOpcode() == ISD::OR && 2781 !MaskedValueIsZero(Op.getOperand(0), 2782 cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue())) 2783 return false; 2784 2785 return true; 2786 } 2787 2788 bool SelectionDAG::isKnownNeverNaN(SDValue Op) const { 2789 // If we're told that NaNs won't happen, assume they won't. 2790 if (getTarget().Options.NoNaNsFPMath) 2791 return true; 2792 2793 // If the value is a constant, we can obviously see if it is a NaN or not. 2794 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 2795 return !C->getValueAPF().isNaN(); 2796 2797 // TODO: Recognize more cases here. 2798 2799 return false; 2800 } 2801 2802 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 2803 // If the value is a constant, we can obviously see if it is a zero or not. 2804 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 2805 return !C->isZero(); 2806 2807 // TODO: Recognize more cases here. 2808 switch (Op.getOpcode()) { 2809 default: break; 2810 case ISD::OR: 2811 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 2812 return !C->isNullValue(); 2813 break; 2814 } 2815 2816 return false; 2817 } 2818 2819 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 2820 // Check the obvious case. 2821 if (A == B) return true; 2822 2823 // For for negative and positive zero. 2824 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 2825 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 2826 if (CA->isZero() && CB->isZero()) return true; 2827 2828 // Otherwise they may not be equal. 2829 return false; 2830 } 2831 2832 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 2833 assert(A.getValueType() == B.getValueType() && 2834 "Values must have the same type"); 2835 APInt AZero, AOne; 2836 APInt BZero, BOne; 2837 computeKnownBits(A, AZero, AOne); 2838 computeKnownBits(B, BZero, BOne); 2839 return (AZero | BZero).isAllOnesValue(); 2840 } 2841 2842 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 2843 ArrayRef<SDValue> Ops, 2844 llvm::SelectionDAG &DAG) { 2845 if (Ops.size() == 1) 2846 return Ops[0]; 2847 2848 // Concat of UNDEFs is UNDEF. 2849 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 2850 return DAG.getUNDEF(VT); 2851 2852 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 2853 // simplified to one big BUILD_VECTOR. 2854 // FIXME: Add support for SCALAR_TO_VECTOR as well. 2855 EVT SVT = VT.getScalarType(); 2856 SmallVector<SDValue, 16> Elts; 2857 for (SDValue Op : Ops) { 2858 EVT OpVT = Op.getValueType(); 2859 if (Op.isUndef()) 2860 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 2861 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 2862 Elts.append(Op->op_begin(), Op->op_end()); 2863 else 2864 return SDValue(); 2865 } 2866 2867 // BUILD_VECTOR requires all inputs to be of the same type, find the 2868 // maximum type and extend them all. 2869 for (SDValue Op : Elts) 2870 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 2871 2872 if (SVT.bitsGT(VT.getScalarType())) 2873 for (SDValue &Op : Elts) 2874 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 2875 ? DAG.getZExtOrTrunc(Op, DL, SVT) 2876 : DAG.getSExtOrTrunc(Op, DL, SVT); 2877 2878 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts); 2879 } 2880 2881 /// Gets or creates the specified node. 2882 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 2883 FoldingSetNodeID ID; 2884 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 2885 void *IP = nullptr; 2886 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 2887 return SDValue(E, 0); 2888 2889 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 2890 getVTList(VT)); 2891 CSEMap.InsertNode(N, IP); 2892 2893 InsertNode(N); 2894 return SDValue(N, 0); 2895 } 2896 2897 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 2898 SDValue Operand) { 2899 // Constant fold unary operations with an integer constant operand. Even 2900 // opaque constant will be folded, because the folding of unary operations 2901 // doesn't create new constants with different values. Nevertheless, the 2902 // opaque flag is preserved during folding to prevent future folding with 2903 // other constants. 2904 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 2905 const APInt &Val = C->getAPIntValue(); 2906 switch (Opcode) { 2907 default: break; 2908 case ISD::SIGN_EXTEND: 2909 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 2910 C->isTargetOpcode(), C->isOpaque()); 2911 case ISD::ANY_EXTEND: 2912 case ISD::ZERO_EXTEND: 2913 case ISD::TRUNCATE: 2914 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 2915 C->isTargetOpcode(), C->isOpaque()); 2916 case ISD::UINT_TO_FP: 2917 case ISD::SINT_TO_FP: { 2918 APFloat apf(EVTToAPFloatSemantics(VT), 2919 APInt::getNullValue(VT.getSizeInBits())); 2920 (void)apf.convertFromAPInt(Val, 2921 Opcode==ISD::SINT_TO_FP, 2922 APFloat::rmNearestTiesToEven); 2923 return getConstantFP(apf, DL, VT); 2924 } 2925 case ISD::BITCAST: 2926 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 2927 return getConstantFP(APFloat(APFloat::IEEEhalf, Val), DL, VT); 2928 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 2929 return getConstantFP(APFloat(APFloat::IEEEsingle, Val), DL, VT); 2930 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 2931 return getConstantFP(APFloat(APFloat::IEEEdouble, Val), DL, VT); 2932 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 2933 return getConstantFP(APFloat(APFloat::IEEEquad, Val), DL, VT); 2934 break; 2935 case ISD::BSWAP: 2936 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 2937 C->isOpaque()); 2938 case ISD::CTPOP: 2939 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 2940 C->isOpaque()); 2941 case ISD::CTLZ: 2942 case ISD::CTLZ_ZERO_UNDEF: 2943 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 2944 C->isOpaque()); 2945 case ISD::CTTZ: 2946 case ISD::CTTZ_ZERO_UNDEF: 2947 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 2948 C->isOpaque()); 2949 } 2950 } 2951 2952 // Constant fold unary operations with a floating point constant operand. 2953 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 2954 APFloat V = C->getValueAPF(); // make copy 2955 switch (Opcode) { 2956 case ISD::FNEG: 2957 V.changeSign(); 2958 return getConstantFP(V, DL, VT); 2959 case ISD::FABS: 2960 V.clearSign(); 2961 return getConstantFP(V, DL, VT); 2962 case ISD::FCEIL: { 2963 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 2964 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2965 return getConstantFP(V, DL, VT); 2966 break; 2967 } 2968 case ISD::FTRUNC: { 2969 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 2970 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2971 return getConstantFP(V, DL, VT); 2972 break; 2973 } 2974 case ISD::FFLOOR: { 2975 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 2976 if (fs == APFloat::opOK || fs == APFloat::opInexact) 2977 return getConstantFP(V, DL, VT); 2978 break; 2979 } 2980 case ISD::FP_EXTEND: { 2981 bool ignored; 2982 // This can return overflow, underflow, or inexact; we don't care. 2983 // FIXME need to be more flexible about rounding mode. 2984 (void)V.convert(EVTToAPFloatSemantics(VT), 2985 APFloat::rmNearestTiesToEven, &ignored); 2986 return getConstantFP(V, DL, VT); 2987 } 2988 case ISD::FP_TO_SINT: 2989 case ISD::FP_TO_UINT: { 2990 integerPart x[2]; 2991 bool ignored; 2992 static_assert(integerPartWidth >= 64, "APFloat parts too small!"); 2993 // FIXME need to be more flexible about rounding mode. 2994 APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(), 2995 Opcode==ISD::FP_TO_SINT, 2996 APFloat::rmTowardZero, &ignored); 2997 if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual 2998 break; 2999 APInt api(VT.getSizeInBits(), x); 3000 return getConstant(api, DL, VT); 3001 } 3002 case ISD::BITCAST: 3003 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 3004 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 3005 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 3006 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 3007 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 3008 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 3009 break; 3010 } 3011 } 3012 3013 // Constant fold unary operations with a vector integer or float operand. 3014 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) { 3015 if (BV->isConstant()) { 3016 switch (Opcode) { 3017 default: 3018 // FIXME: Entirely reasonable to perform folding of other unary 3019 // operations here as the need arises. 3020 break; 3021 case ISD::FNEG: 3022 case ISD::FABS: 3023 case ISD::FCEIL: 3024 case ISD::FTRUNC: 3025 case ISD::FFLOOR: 3026 case ISD::FP_EXTEND: 3027 case ISD::FP_TO_SINT: 3028 case ISD::FP_TO_UINT: 3029 case ISD::TRUNCATE: 3030 case ISD::UINT_TO_FP: 3031 case ISD::SINT_TO_FP: 3032 case ISD::BSWAP: 3033 case ISD::CTLZ: 3034 case ISD::CTLZ_ZERO_UNDEF: 3035 case ISD::CTTZ: 3036 case ISD::CTTZ_ZERO_UNDEF: 3037 case ISD::CTPOP: { 3038 SDValue Ops = { Operand }; 3039 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 3040 return Fold; 3041 } 3042 } 3043 } 3044 } 3045 3046 unsigned OpOpcode = Operand.getNode()->getOpcode(); 3047 switch (Opcode) { 3048 case ISD::TokenFactor: 3049 case ISD::MERGE_VALUES: 3050 case ISD::CONCAT_VECTORS: 3051 return Operand; // Factor, merge or concat of one node? No need. 3052 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 3053 case ISD::FP_EXTEND: 3054 assert(VT.isFloatingPoint() && 3055 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 3056 if (Operand.getValueType() == VT) return Operand; // noop conversion. 3057 assert((!VT.isVector() || 3058 VT.getVectorNumElements() == 3059 Operand.getValueType().getVectorNumElements()) && 3060 "Vector element count mismatch!"); 3061 assert(Operand.getValueType().bitsLT(VT) && 3062 "Invalid fpext node, dst < src!"); 3063 if (Operand.isUndef()) 3064 return getUNDEF(VT); 3065 break; 3066 case ISD::SIGN_EXTEND: 3067 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3068 "Invalid SIGN_EXTEND!"); 3069 if (Operand.getValueType() == VT) return Operand; // noop extension 3070 assert((!VT.isVector() || 3071 VT.getVectorNumElements() == 3072 Operand.getValueType().getVectorNumElements()) && 3073 "Vector element count mismatch!"); 3074 assert(Operand.getValueType().bitsLT(VT) && 3075 "Invalid sext node, dst < src!"); 3076 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 3077 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 3078 else if (OpOpcode == ISD::UNDEF) 3079 // sext(undef) = 0, because the top bits will all be the same. 3080 return getConstant(0, DL, VT); 3081 break; 3082 case ISD::ZERO_EXTEND: 3083 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3084 "Invalid ZERO_EXTEND!"); 3085 if (Operand.getValueType() == VT) return Operand; // noop extension 3086 assert((!VT.isVector() || 3087 VT.getVectorNumElements() == 3088 Operand.getValueType().getVectorNumElements()) && 3089 "Vector element count mismatch!"); 3090 assert(Operand.getValueType().bitsLT(VT) && 3091 "Invalid zext node, dst < src!"); 3092 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 3093 return getNode(ISD::ZERO_EXTEND, DL, VT, 3094 Operand.getNode()->getOperand(0)); 3095 else if (OpOpcode == ISD::UNDEF) 3096 // zext(undef) = 0, because the top bits will be zero. 3097 return getConstant(0, DL, VT); 3098 break; 3099 case ISD::ANY_EXTEND: 3100 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3101 "Invalid ANY_EXTEND!"); 3102 if (Operand.getValueType() == VT) return Operand; // noop extension 3103 assert((!VT.isVector() || 3104 VT.getVectorNumElements() == 3105 Operand.getValueType().getVectorNumElements()) && 3106 "Vector element count mismatch!"); 3107 assert(Operand.getValueType().bitsLT(VT) && 3108 "Invalid anyext node, dst < src!"); 3109 3110 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 3111 OpOpcode == ISD::ANY_EXTEND) 3112 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 3113 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 3114 else if (OpOpcode == ISD::UNDEF) 3115 return getUNDEF(VT); 3116 3117 // (ext (trunx x)) -> x 3118 if (OpOpcode == ISD::TRUNCATE) { 3119 SDValue OpOp = Operand.getNode()->getOperand(0); 3120 if (OpOp.getValueType() == VT) 3121 return OpOp; 3122 } 3123 break; 3124 case ISD::TRUNCATE: 3125 assert(VT.isInteger() && Operand.getValueType().isInteger() && 3126 "Invalid TRUNCATE!"); 3127 if (Operand.getValueType() == VT) return Operand; // noop truncate 3128 assert((!VT.isVector() || 3129 VT.getVectorNumElements() == 3130 Operand.getValueType().getVectorNumElements()) && 3131 "Vector element count mismatch!"); 3132 assert(Operand.getValueType().bitsGT(VT) && 3133 "Invalid truncate node, src < dst!"); 3134 if (OpOpcode == ISD::TRUNCATE) 3135 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 3136 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 3137 OpOpcode == ISD::ANY_EXTEND) { 3138 // If the source is smaller than the dest, we still need an extend. 3139 if (Operand.getNode()->getOperand(0).getValueType().getScalarType() 3140 .bitsLT(VT.getScalarType())) 3141 return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0)); 3142 if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT)) 3143 return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0)); 3144 return Operand.getNode()->getOperand(0); 3145 } 3146 if (OpOpcode == ISD::UNDEF) 3147 return getUNDEF(VT); 3148 break; 3149 case ISD::BSWAP: 3150 assert(VT.isInteger() && VT == Operand.getValueType() && 3151 "Invalid BSWAP!"); 3152 assert((VT.getScalarSizeInBits() % 16 == 0) && 3153 "BSWAP types must be a multiple of 16 bits!"); 3154 if (OpOpcode == ISD::UNDEF) 3155 return getUNDEF(VT); 3156 break; 3157 case ISD::BITREVERSE: 3158 assert(VT.isInteger() && VT == Operand.getValueType() && 3159 "Invalid BITREVERSE!"); 3160 if (OpOpcode == ISD::UNDEF) 3161 return getUNDEF(VT); 3162 break; 3163 case ISD::BITCAST: 3164 // Basic sanity checking. 3165 assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits() 3166 && "Cannot BITCAST between types of different sizes!"); 3167 if (VT == Operand.getValueType()) return Operand; // noop conversion. 3168 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 3169 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 3170 if (OpOpcode == ISD::UNDEF) 3171 return getUNDEF(VT); 3172 break; 3173 case ISD::SCALAR_TO_VECTOR: 3174 assert(VT.isVector() && !Operand.getValueType().isVector() && 3175 (VT.getVectorElementType() == Operand.getValueType() || 3176 (VT.getVectorElementType().isInteger() && 3177 Operand.getValueType().isInteger() && 3178 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 3179 "Illegal SCALAR_TO_VECTOR node!"); 3180 if (OpOpcode == ISD::UNDEF) 3181 return getUNDEF(VT); 3182 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 3183 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 3184 isa<ConstantSDNode>(Operand.getOperand(1)) && 3185 Operand.getConstantOperandVal(1) == 0 && 3186 Operand.getOperand(0).getValueType() == VT) 3187 return Operand.getOperand(0); 3188 break; 3189 case ISD::FNEG: 3190 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 3191 if (getTarget().Options.UnsafeFPMath && OpOpcode == ISD::FSUB) 3192 // FIXME: FNEG has no fast-math-flags to propagate; use the FSUB's flags? 3193 return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1), 3194 Operand.getNode()->getOperand(0), 3195 &cast<BinaryWithFlagsSDNode>(Operand.getNode())->Flags); 3196 if (OpOpcode == ISD::FNEG) // --X -> X 3197 return Operand.getNode()->getOperand(0); 3198 break; 3199 case ISD::FABS: 3200 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 3201 return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0)); 3202 break; 3203 } 3204 3205 SDNode *N; 3206 SDVTList VTs = getVTList(VT); 3207 SDValue Ops[] = {Operand}; 3208 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 3209 FoldingSetNodeID ID; 3210 AddNodeIDNode(ID, Opcode, VTs, Ops); 3211 void *IP = nullptr; 3212 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 3213 return SDValue(E, 0); 3214 3215 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 3216 createOperands(N, Ops); 3217 CSEMap.InsertNode(N, IP); 3218 } else { 3219 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 3220 createOperands(N, Ops); 3221 } 3222 3223 InsertNode(N); 3224 return SDValue(N, 0); 3225 } 3226 3227 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1, 3228 const APInt &C2) { 3229 switch (Opcode) { 3230 case ISD::ADD: return std::make_pair(C1 + C2, true); 3231 case ISD::SUB: return std::make_pair(C1 - C2, true); 3232 case ISD::MUL: return std::make_pair(C1 * C2, true); 3233 case ISD::AND: return std::make_pair(C1 & C2, true); 3234 case ISD::OR: return std::make_pair(C1 | C2, true); 3235 case ISD::XOR: return std::make_pair(C1 ^ C2, true); 3236 case ISD::SHL: return std::make_pair(C1 << C2, true); 3237 case ISD::SRL: return std::make_pair(C1.lshr(C2), true); 3238 case ISD::SRA: return std::make_pair(C1.ashr(C2), true); 3239 case ISD::ROTL: return std::make_pair(C1.rotl(C2), true); 3240 case ISD::ROTR: return std::make_pair(C1.rotr(C2), true); 3241 case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true); 3242 case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true); 3243 case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true); 3244 case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true); 3245 case ISD::UDIV: 3246 if (!C2.getBoolValue()) 3247 break; 3248 return std::make_pair(C1.udiv(C2), true); 3249 case ISD::UREM: 3250 if (!C2.getBoolValue()) 3251 break; 3252 return std::make_pair(C1.urem(C2), true); 3253 case ISD::SDIV: 3254 if (!C2.getBoolValue()) 3255 break; 3256 return std::make_pair(C1.sdiv(C2), true); 3257 case ISD::SREM: 3258 if (!C2.getBoolValue()) 3259 break; 3260 return std::make_pair(C1.srem(C2), true); 3261 } 3262 return std::make_pair(APInt(1, 0), false); 3263 } 3264 3265 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 3266 EVT VT, const ConstantSDNode *Cst1, 3267 const ConstantSDNode *Cst2) { 3268 if (Cst1->isOpaque() || Cst2->isOpaque()) 3269 return SDValue(); 3270 3271 std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(), 3272 Cst2->getAPIntValue()); 3273 if (!Folded.second) 3274 return SDValue(); 3275 return getConstant(Folded.first, DL, VT); 3276 } 3277 3278 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 3279 const GlobalAddressSDNode *GA, 3280 const SDNode *N2) { 3281 if (GA->getOpcode() != ISD::GlobalAddress) 3282 return SDValue(); 3283 if (!TLI->isOffsetFoldingLegal(GA)) 3284 return SDValue(); 3285 const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2); 3286 if (!Cst2) 3287 return SDValue(); 3288 int64_t Offset = Cst2->getSExtValue(); 3289 switch (Opcode) { 3290 case ISD::ADD: break; 3291 case ISD::SUB: Offset = -uint64_t(Offset); break; 3292 default: return SDValue(); 3293 } 3294 return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT, 3295 GA->getOffset() + uint64_t(Offset)); 3296 } 3297 3298 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 3299 EVT VT, SDNode *Cst1, 3300 SDNode *Cst2) { 3301 // If the opcode is a target-specific ISD node, there's nothing we can 3302 // do here and the operand rules may not line up with the below, so 3303 // bail early. 3304 if (Opcode >= ISD::BUILTIN_OP_END) 3305 return SDValue(); 3306 3307 // Handle the case of two scalars. 3308 if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) { 3309 if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) { 3310 SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2); 3311 assert((!Folded || !VT.isVector()) && 3312 "Can't fold vectors ops with scalar operands"); 3313 return Folded; 3314 } 3315 } 3316 3317 // fold (add Sym, c) -> Sym+c 3318 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1)) 3319 return FoldSymbolOffset(Opcode, VT, GA, Cst2); 3320 if (isCommutativeBinOp(Opcode)) 3321 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2)) 3322 return FoldSymbolOffset(Opcode, VT, GA, Cst1); 3323 3324 // For vectors extract each constant element into Inputs so we can constant 3325 // fold them individually. 3326 BuildVectorSDNode *BV1 = dyn_cast<BuildVectorSDNode>(Cst1); 3327 BuildVectorSDNode *BV2 = dyn_cast<BuildVectorSDNode>(Cst2); 3328 if (!BV1 || !BV2) 3329 return SDValue(); 3330 3331 assert(BV1->getNumOperands() == BV2->getNumOperands() && "Out of sync!"); 3332 3333 EVT SVT = VT.getScalarType(); 3334 SmallVector<SDValue, 4> Outputs; 3335 for (unsigned I = 0, E = BV1->getNumOperands(); I != E; ++I) { 3336 ConstantSDNode *V1 = dyn_cast<ConstantSDNode>(BV1->getOperand(I)); 3337 ConstantSDNode *V2 = dyn_cast<ConstantSDNode>(BV2->getOperand(I)); 3338 if (!V1 || !V2) // Not a constant, bail. 3339 return SDValue(); 3340 3341 if (V1->isOpaque() || V2->isOpaque()) 3342 return SDValue(); 3343 3344 // Avoid BUILD_VECTOR nodes that perform implicit truncation. 3345 // FIXME: This is valid and could be handled by truncating the APInts. 3346 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT) 3347 return SDValue(); 3348 3349 // Fold one vector element. 3350 std::pair<APInt, bool> Folded = FoldValue(Opcode, V1->getAPIntValue(), 3351 V2->getAPIntValue()); 3352 if (!Folded.second) 3353 return SDValue(); 3354 Outputs.push_back(getConstant(Folded.first, DL, SVT)); 3355 } 3356 3357 assert(VT.getVectorNumElements() == Outputs.size() && 3358 "Vector size mismatch!"); 3359 3360 // We may have a vector type but a scalar result. Create a splat. 3361 Outputs.resize(VT.getVectorNumElements(), Outputs.back()); 3362 3363 // Build a big vector out of the scalar elements we generated. 3364 return getBuildVector(VT, SDLoc(), Outputs); 3365 } 3366 3367 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 3368 const SDLoc &DL, EVT VT, 3369 ArrayRef<SDValue> Ops, 3370 const SDNodeFlags *Flags) { 3371 // If the opcode is a target-specific ISD node, there's nothing we can 3372 // do here and the operand rules may not line up with the below, so 3373 // bail early. 3374 if (Opcode >= ISD::BUILTIN_OP_END) 3375 return SDValue(); 3376 3377 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 3378 if (!VT.isVector()) 3379 return SDValue(); 3380 3381 unsigned NumElts = VT.getVectorNumElements(); 3382 3383 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) { 3384 return !Op.getValueType().isVector() || 3385 Op.getValueType().getVectorNumElements() == NumElts; 3386 }; 3387 3388 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) { 3389 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 3390 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) || 3391 (BV && BV->isConstant()); 3392 }; 3393 3394 // All operands must be vector types with the same number of elements as 3395 // the result type and must be either UNDEF or a build vector of constant 3396 // or UNDEF scalars. 3397 if (!std::all_of(Ops.begin(), Ops.end(), IsConstantBuildVectorOrUndef) || 3398 !std::all_of(Ops.begin(), Ops.end(), IsScalarOrSameVectorSize)) 3399 return SDValue(); 3400 3401 // If we are comparing vectors, then the result needs to be a i1 boolean 3402 // that is then sign-extended back to the legal result type. 3403 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 3404 3405 // Find legal integer scalar type for constant promotion and 3406 // ensure that its scalar size is at least as large as source. 3407 EVT LegalSVT = VT.getScalarType(); 3408 if (LegalSVT.isInteger()) { 3409 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 3410 if (LegalSVT.bitsLT(VT.getScalarType())) 3411 return SDValue(); 3412 } 3413 3414 // Constant fold each scalar lane separately. 3415 SmallVector<SDValue, 4> ScalarResults; 3416 for (unsigned i = 0; i != NumElts; i++) { 3417 SmallVector<SDValue, 4> ScalarOps; 3418 for (SDValue Op : Ops) { 3419 EVT InSVT = Op.getValueType().getScalarType(); 3420 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op); 3421 if (!InBV) { 3422 // We've checked that this is UNDEF or a constant of some kind. 3423 if (Op.isUndef()) 3424 ScalarOps.push_back(getUNDEF(InSVT)); 3425 else 3426 ScalarOps.push_back(Op); 3427 continue; 3428 } 3429 3430 SDValue ScalarOp = InBV->getOperand(i); 3431 EVT ScalarVT = ScalarOp.getValueType(); 3432 3433 // Build vector (integer) scalar operands may need implicit 3434 // truncation - do this before constant folding. 3435 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 3436 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 3437 3438 ScalarOps.push_back(ScalarOp); 3439 } 3440 3441 // Constant fold the scalar operands. 3442 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 3443 3444 // Legalize the (integer) scalar constant if necessary. 3445 if (LegalSVT != SVT) 3446 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 3447 3448 // Scalar folding only succeeded if the result is a constant or UNDEF. 3449 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 3450 ScalarResult.getOpcode() != ISD::ConstantFP) 3451 return SDValue(); 3452 ScalarResults.push_back(ScalarResult); 3453 } 3454 3455 return getBuildVector(VT, DL, ScalarResults); 3456 } 3457 3458 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 3459 SDValue N1, SDValue N2, 3460 const SDNodeFlags *Flags) { 3461 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 3462 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 3463 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3464 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 3465 3466 // Canonicalize constant to RHS if commutative. 3467 if (isCommutativeBinOp(Opcode)) { 3468 if (N1C && !N2C) { 3469 std::swap(N1C, N2C); 3470 std::swap(N1, N2); 3471 } else if (N1CFP && !N2CFP) { 3472 std::swap(N1CFP, N2CFP); 3473 std::swap(N1, N2); 3474 } 3475 } 3476 3477 switch (Opcode) { 3478 default: break; 3479 case ISD::TokenFactor: 3480 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 3481 N2.getValueType() == MVT::Other && "Invalid token factor!"); 3482 // Fold trivial token factors. 3483 if (N1.getOpcode() == ISD::EntryToken) return N2; 3484 if (N2.getOpcode() == ISD::EntryToken) return N1; 3485 if (N1 == N2) return N1; 3486 break; 3487 case ISD::CONCAT_VECTORS: { 3488 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 3489 SDValue Ops[] = {N1, N2}; 3490 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 3491 return V; 3492 break; 3493 } 3494 case ISD::AND: 3495 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3496 assert(N1.getValueType() == N2.getValueType() && 3497 N1.getValueType() == VT && "Binary operator types must match!"); 3498 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 3499 // worth handling here. 3500 if (N2C && N2C->isNullValue()) 3501 return N2; 3502 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 3503 return N1; 3504 break; 3505 case ISD::OR: 3506 case ISD::XOR: 3507 case ISD::ADD: 3508 case ISD::SUB: 3509 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3510 assert(N1.getValueType() == N2.getValueType() && 3511 N1.getValueType() == VT && "Binary operator types must match!"); 3512 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 3513 // it's worth handling here. 3514 if (N2C && N2C->isNullValue()) 3515 return N1; 3516 break; 3517 case ISD::UDIV: 3518 case ISD::UREM: 3519 case ISD::MULHU: 3520 case ISD::MULHS: 3521 case ISD::MUL: 3522 case ISD::SDIV: 3523 case ISD::SREM: 3524 case ISD::SMIN: 3525 case ISD::SMAX: 3526 case ISD::UMIN: 3527 case ISD::UMAX: 3528 assert(VT.isInteger() && "This operator does not apply to FP types!"); 3529 assert(N1.getValueType() == N2.getValueType() && 3530 N1.getValueType() == VT && "Binary operator types must match!"); 3531 break; 3532 case ISD::FADD: 3533 case ISD::FSUB: 3534 case ISD::FMUL: 3535 case ISD::FDIV: 3536 case ISD::FREM: 3537 if (getTarget().Options.UnsafeFPMath) { 3538 if (Opcode == ISD::FADD) { 3539 // x+0 --> x 3540 if (N2CFP && N2CFP->getValueAPF().isZero()) 3541 return N1; 3542 } else if (Opcode == ISD::FSUB) { 3543 // x-0 --> x 3544 if (N2CFP && N2CFP->getValueAPF().isZero()) 3545 return N1; 3546 } else if (Opcode == ISD::FMUL) { 3547 // x*0 --> 0 3548 if (N2CFP && N2CFP->isZero()) 3549 return N2; 3550 // x*1 --> x 3551 if (N2CFP && N2CFP->isExactlyValue(1.0)) 3552 return N1; 3553 } 3554 } 3555 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 3556 assert(N1.getValueType() == N2.getValueType() && 3557 N1.getValueType() == VT && "Binary operator types must match!"); 3558 break; 3559 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 3560 assert(N1.getValueType() == VT && 3561 N1.getValueType().isFloatingPoint() && 3562 N2.getValueType().isFloatingPoint() && 3563 "Invalid FCOPYSIGN!"); 3564 break; 3565 case ISD::SHL: 3566 case ISD::SRA: 3567 case ISD::SRL: 3568 case ISD::ROTL: 3569 case ISD::ROTR: 3570 assert(VT == N1.getValueType() && 3571 "Shift operators return type must be the same as their first arg"); 3572 assert(VT.isInteger() && N2.getValueType().isInteger() && 3573 "Shifts only work on integers"); 3574 assert((!VT.isVector() || VT == N2.getValueType()) && 3575 "Vector shift amounts must be in the same as their first arg"); 3576 // Verify that the shift amount VT is bit enough to hold valid shift 3577 // amounts. This catches things like trying to shift an i1024 value by an 3578 // i8, which is easy to fall into in generic code that uses 3579 // TLI.getShiftAmount(). 3580 assert(N2.getValueType().getSizeInBits() >= 3581 Log2_32_Ceil(N1.getValueType().getSizeInBits()) && 3582 "Invalid use of small shift amount with oversized value!"); 3583 3584 // Always fold shifts of i1 values so the code generator doesn't need to 3585 // handle them. Since we know the size of the shift has to be less than the 3586 // size of the value, the shift/rotate count is guaranteed to be zero. 3587 if (VT == MVT::i1) 3588 return N1; 3589 if (N2C && N2C->isNullValue()) 3590 return N1; 3591 break; 3592 case ISD::FP_ROUND_INREG: { 3593 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3594 assert(VT == N1.getValueType() && "Not an inreg round!"); 3595 assert(VT.isFloatingPoint() && EVT.isFloatingPoint() && 3596 "Cannot FP_ROUND_INREG integer types"); 3597 assert(EVT.isVector() == VT.isVector() && 3598 "FP_ROUND_INREG type should be vector iff the operand " 3599 "type is vector!"); 3600 assert((!EVT.isVector() || 3601 EVT.getVectorNumElements() == VT.getVectorNumElements()) && 3602 "Vector element counts must match in FP_ROUND_INREG"); 3603 assert(EVT.bitsLE(VT) && "Not rounding down!"); 3604 (void)EVT; 3605 if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding. 3606 break; 3607 } 3608 case ISD::FP_ROUND: 3609 assert(VT.isFloatingPoint() && 3610 N1.getValueType().isFloatingPoint() && 3611 VT.bitsLE(N1.getValueType()) && 3612 N2C && "Invalid FP_ROUND!"); 3613 if (N1.getValueType() == VT) return N1; // noop conversion. 3614 break; 3615 case ISD::AssertSext: 3616 case ISD::AssertZext: { 3617 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3618 assert(VT == N1.getValueType() && "Not an inreg extend!"); 3619 assert(VT.isInteger() && EVT.isInteger() && 3620 "Cannot *_EXTEND_INREG FP types"); 3621 assert(!EVT.isVector() && 3622 "AssertSExt/AssertZExt type should be the vector element type " 3623 "rather than the vector type!"); 3624 assert(EVT.bitsLE(VT) && "Not extending!"); 3625 if (VT == EVT) return N1; // noop assertion. 3626 break; 3627 } 3628 case ISD::SIGN_EXTEND_INREG: { 3629 EVT EVT = cast<VTSDNode>(N2)->getVT(); 3630 assert(VT == N1.getValueType() && "Not an inreg extend!"); 3631 assert(VT.isInteger() && EVT.isInteger() && 3632 "Cannot *_EXTEND_INREG FP types"); 3633 assert(EVT.isVector() == VT.isVector() && 3634 "SIGN_EXTEND_INREG type should be vector iff the operand " 3635 "type is vector!"); 3636 assert((!EVT.isVector() || 3637 EVT.getVectorNumElements() == VT.getVectorNumElements()) && 3638 "Vector element counts must match in SIGN_EXTEND_INREG"); 3639 assert(EVT.bitsLE(VT) && "Not extending!"); 3640 if (EVT == VT) return N1; // Not actually extending 3641 3642 auto SignExtendInReg = [&](APInt Val) { 3643 unsigned FromBits = EVT.getScalarType().getSizeInBits(); 3644 Val <<= Val.getBitWidth() - FromBits; 3645 Val = Val.ashr(Val.getBitWidth() - FromBits); 3646 return getConstant(Val, DL, VT.getScalarType()); 3647 }; 3648 3649 if (N1C) { 3650 const APInt &Val = N1C->getAPIntValue(); 3651 return SignExtendInReg(Val); 3652 } 3653 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 3654 SmallVector<SDValue, 8> Ops; 3655 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 3656 SDValue Op = N1.getOperand(i); 3657 if (Op.isUndef()) { 3658 Ops.push_back(getUNDEF(VT.getScalarType())); 3659 continue; 3660 } 3661 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 3662 APInt Val = C->getAPIntValue(); 3663 Val = Val.zextOrTrunc(VT.getScalarSizeInBits()); 3664 Ops.push_back(SignExtendInReg(Val)); 3665 continue; 3666 } 3667 break; 3668 } 3669 if (Ops.size() == VT.getVectorNumElements()) 3670 return getBuildVector(VT, DL, Ops); 3671 } 3672 break; 3673 } 3674 case ISD::EXTRACT_VECTOR_ELT: 3675 // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF. 3676 if (N1.isUndef()) 3677 return getUNDEF(VT); 3678 3679 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF 3680 if (N2C && N2C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 3681 return getUNDEF(VT); 3682 3683 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 3684 // expanding copies of large vectors from registers. 3685 if (N2C && 3686 N1.getOpcode() == ISD::CONCAT_VECTORS && 3687 N1.getNumOperands() > 0) { 3688 unsigned Factor = 3689 N1.getOperand(0).getValueType().getVectorNumElements(); 3690 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 3691 N1.getOperand(N2C->getZExtValue() / Factor), 3692 getConstant(N2C->getZExtValue() % Factor, DL, 3693 N2.getValueType())); 3694 } 3695 3696 // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is 3697 // expanding large vector constants. 3698 if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) { 3699 SDValue Elt = N1.getOperand(N2C->getZExtValue()); 3700 3701 if (VT != Elt.getValueType()) 3702 // If the vector element type is not legal, the BUILD_VECTOR operands 3703 // are promoted and implicitly truncated, and the result implicitly 3704 // extended. Make that explicit here. 3705 Elt = getAnyExtOrTrunc(Elt, DL, VT); 3706 3707 return Elt; 3708 } 3709 3710 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 3711 // operations are lowered to scalars. 3712 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 3713 // If the indices are the same, return the inserted element else 3714 // if the indices are known different, extract the element from 3715 // the original vector. 3716 SDValue N1Op2 = N1.getOperand(2); 3717 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 3718 3719 if (N1Op2C && N2C) { 3720 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 3721 if (VT == N1.getOperand(1).getValueType()) 3722 return N1.getOperand(1); 3723 else 3724 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 3725 } 3726 3727 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 3728 } 3729 } 3730 break; 3731 case ISD::EXTRACT_ELEMENT: 3732 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 3733 assert(!N1.getValueType().isVector() && !VT.isVector() && 3734 (N1.getValueType().isInteger() == VT.isInteger()) && 3735 N1.getValueType() != VT && 3736 "Wrong types for EXTRACT_ELEMENT!"); 3737 3738 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 3739 // 64-bit integers into 32-bit parts. Instead of building the extract of 3740 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 3741 if (N1.getOpcode() == ISD::BUILD_PAIR) 3742 return N1.getOperand(N2C->getZExtValue()); 3743 3744 // EXTRACT_ELEMENT of a constant int is also very common. 3745 if (N1C) { 3746 unsigned ElementSize = VT.getSizeInBits(); 3747 unsigned Shift = ElementSize * N2C->getZExtValue(); 3748 APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift); 3749 return getConstant(ShiftedVal.trunc(ElementSize), DL, VT); 3750 } 3751 break; 3752 case ISD::EXTRACT_SUBVECTOR: 3753 if (VT.isSimple() && N1.getValueType().isSimple()) { 3754 assert(VT.isVector() && N1.getValueType().isVector() && 3755 "Extract subvector VTs must be a vectors!"); 3756 assert(VT.getVectorElementType() == 3757 N1.getValueType().getVectorElementType() && 3758 "Extract subvector VTs must have the same element type!"); 3759 assert(VT.getSimpleVT() <= N1.getSimpleValueType() && 3760 "Extract subvector must be from larger vector to smaller vector!"); 3761 3762 if (N2C) { 3763 assert((VT.getVectorNumElements() + N2C->getZExtValue() 3764 <= N1.getValueType().getVectorNumElements()) 3765 && "Extract subvector overflow!"); 3766 } 3767 3768 // Trivial extraction. 3769 if (VT.getSimpleVT() == N1.getSimpleValueType()) 3770 return N1; 3771 } 3772 break; 3773 } 3774 3775 // Perform trivial constant folding. 3776 if (SDValue SV = 3777 FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode())) 3778 return SV; 3779 3780 // Constant fold FP operations. 3781 bool HasFPExceptions = TLI->hasFloatingPointExceptions(); 3782 if (N1CFP) { 3783 if (N2CFP) { 3784 APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF(); 3785 APFloat::opStatus s; 3786 switch (Opcode) { 3787 case ISD::FADD: 3788 s = V1.add(V2, APFloat::rmNearestTiesToEven); 3789 if (!HasFPExceptions || s != APFloat::opInvalidOp) 3790 return getConstantFP(V1, DL, VT); 3791 break; 3792 case ISD::FSUB: 3793 s = V1.subtract(V2, APFloat::rmNearestTiesToEven); 3794 if (!HasFPExceptions || s!=APFloat::opInvalidOp) 3795 return getConstantFP(V1, DL, VT); 3796 break; 3797 case ISD::FMUL: 3798 s = V1.multiply(V2, APFloat::rmNearestTiesToEven); 3799 if (!HasFPExceptions || s!=APFloat::opInvalidOp) 3800 return getConstantFP(V1, DL, VT); 3801 break; 3802 case ISD::FDIV: 3803 s = V1.divide(V2, APFloat::rmNearestTiesToEven); 3804 if (!HasFPExceptions || (s!=APFloat::opInvalidOp && 3805 s!=APFloat::opDivByZero)) { 3806 return getConstantFP(V1, DL, VT); 3807 } 3808 break; 3809 case ISD::FREM : 3810 s = V1.mod(V2); 3811 if (!HasFPExceptions || (s!=APFloat::opInvalidOp && 3812 s!=APFloat::opDivByZero)) { 3813 return getConstantFP(V1, DL, VT); 3814 } 3815 break; 3816 case ISD::FCOPYSIGN: 3817 V1.copySign(V2); 3818 return getConstantFP(V1, DL, VT); 3819 default: break; 3820 } 3821 } 3822 3823 if (Opcode == ISD::FP_ROUND) { 3824 APFloat V = N1CFP->getValueAPF(); // make copy 3825 bool ignored; 3826 // This can return overflow, underflow, or inexact; we don't care. 3827 // FIXME need to be more flexible about rounding mode. 3828 (void)V.convert(EVTToAPFloatSemantics(VT), 3829 APFloat::rmNearestTiesToEven, &ignored); 3830 return getConstantFP(V, DL, VT); 3831 } 3832 } 3833 3834 // Canonicalize an UNDEF to the RHS, even over a constant. 3835 if (N1.isUndef()) { 3836 if (isCommutativeBinOp(Opcode)) { 3837 std::swap(N1, N2); 3838 } else { 3839 switch (Opcode) { 3840 case ISD::FP_ROUND_INREG: 3841 case ISD::SIGN_EXTEND_INREG: 3842 case ISD::SUB: 3843 case ISD::FSUB: 3844 case ISD::FDIV: 3845 case ISD::FREM: 3846 case ISD::SRA: 3847 return N1; // fold op(undef, arg2) -> undef 3848 case ISD::UDIV: 3849 case ISD::SDIV: 3850 case ISD::UREM: 3851 case ISD::SREM: 3852 case ISD::SRL: 3853 case ISD::SHL: 3854 if (!VT.isVector()) 3855 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 3856 // For vectors, we can't easily build an all zero vector, just return 3857 // the LHS. 3858 return N2; 3859 } 3860 } 3861 } 3862 3863 // Fold a bunch of operators when the RHS is undef. 3864 if (N2.isUndef()) { 3865 switch (Opcode) { 3866 case ISD::XOR: 3867 if (N1.isUndef()) 3868 // Handle undef ^ undef -> 0 special case. This is a common 3869 // idiom (misuse). 3870 return getConstant(0, DL, VT); 3871 // fallthrough 3872 case ISD::ADD: 3873 case ISD::ADDC: 3874 case ISD::ADDE: 3875 case ISD::SUB: 3876 case ISD::UDIV: 3877 case ISD::SDIV: 3878 case ISD::UREM: 3879 case ISD::SREM: 3880 return N2; // fold op(arg1, undef) -> undef 3881 case ISD::FADD: 3882 case ISD::FSUB: 3883 case ISD::FMUL: 3884 case ISD::FDIV: 3885 case ISD::FREM: 3886 if (getTarget().Options.UnsafeFPMath) 3887 return N2; 3888 break; 3889 case ISD::MUL: 3890 case ISD::AND: 3891 case ISD::SRL: 3892 case ISD::SHL: 3893 if (!VT.isVector()) 3894 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 3895 // For vectors, we can't easily build an all zero vector, just return 3896 // the LHS. 3897 return N1; 3898 case ISD::OR: 3899 if (!VT.isVector()) 3900 return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT); 3901 // For vectors, we can't easily build an all one vector, just return 3902 // the LHS. 3903 return N1; 3904 case ISD::SRA: 3905 return N1; 3906 } 3907 } 3908 3909 // Memoize this node if possible. 3910 SDNode *N; 3911 SDVTList VTs = getVTList(VT); 3912 if (VT != MVT::Glue) { 3913 SDValue Ops[] = {N1, N2}; 3914 FoldingSetNodeID ID; 3915 AddNodeIDNode(ID, Opcode, VTs, Ops); 3916 void *IP = nullptr; 3917 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 3918 if (Flags) 3919 E->intersectFlagsWith(Flags); 3920 return SDValue(E, 0); 3921 } 3922 3923 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags); 3924 CSEMap.InsertNode(N, IP); 3925 } else { 3926 N = GetBinarySDNode(Opcode, DL, VTs, N1, N2, Flags); 3927 } 3928 3929 InsertNode(N); 3930 return SDValue(N, 0); 3931 } 3932 3933 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 3934 SDValue N1, SDValue N2, SDValue N3) { 3935 // Perform various simplifications. 3936 switch (Opcode) { 3937 case ISD::FMA: { 3938 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 3939 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 3940 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 3941 if (N1CFP && N2CFP && N3CFP) { 3942 APFloat V1 = N1CFP->getValueAPF(); 3943 const APFloat &V2 = N2CFP->getValueAPF(); 3944 const APFloat &V3 = N3CFP->getValueAPF(); 3945 APFloat::opStatus s = 3946 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 3947 if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp) 3948 return getConstantFP(V1, DL, VT); 3949 } 3950 break; 3951 } 3952 case ISD::CONCAT_VECTORS: { 3953 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 3954 SDValue Ops[] = {N1, N2, N3}; 3955 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 3956 return V; 3957 break; 3958 } 3959 case ISD::SETCC: { 3960 // Use FoldSetCC to simplify SETCC's. 3961 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 3962 return V; 3963 // Vector constant folding. 3964 SDValue Ops[] = {N1, N2, N3}; 3965 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 3966 return V; 3967 break; 3968 } 3969 case ISD::SELECT: 3970 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 3971 if (N1C->getZExtValue()) 3972 return N2; // select true, X, Y -> X 3973 return N3; // select false, X, Y -> Y 3974 } 3975 3976 if (N2 == N3) return N2; // select C, X, X -> X 3977 break; 3978 case ISD::VECTOR_SHUFFLE: 3979 llvm_unreachable("should use getVectorShuffle constructor!"); 3980 case ISD::INSERT_SUBVECTOR: { 3981 SDValue Index = N3; 3982 if (VT.isSimple() && N1.getValueType().isSimple() 3983 && N2.getValueType().isSimple()) { 3984 assert(VT.isVector() && N1.getValueType().isVector() && 3985 N2.getValueType().isVector() && 3986 "Insert subvector VTs must be a vectors"); 3987 assert(VT == N1.getValueType() && 3988 "Dest and insert subvector source types must match!"); 3989 assert(N2.getSimpleValueType() <= N1.getSimpleValueType() && 3990 "Insert subvector must be from smaller vector to larger vector!"); 3991 if (isa<ConstantSDNode>(Index)) { 3992 assert((N2.getValueType().getVectorNumElements() + 3993 cast<ConstantSDNode>(Index)->getZExtValue() 3994 <= VT.getVectorNumElements()) 3995 && "Insert subvector overflow!"); 3996 } 3997 3998 // Trivial insertion. 3999 if (VT.getSimpleVT() == N2.getSimpleValueType()) 4000 return N2; 4001 } 4002 break; 4003 } 4004 case ISD::BITCAST: 4005 // Fold bit_convert nodes from a type to themselves. 4006 if (N1.getValueType() == VT) 4007 return N1; 4008 break; 4009 } 4010 4011 // Memoize node if it doesn't produce a flag. 4012 SDNode *N; 4013 SDVTList VTs = getVTList(VT); 4014 SDValue Ops[] = {N1, N2, N3}; 4015 if (VT != MVT::Glue) { 4016 FoldingSetNodeID ID; 4017 AddNodeIDNode(ID, Opcode, VTs, Ops); 4018 void *IP = nullptr; 4019 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4020 return SDValue(E, 0); 4021 4022 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4023 createOperands(N, Ops); 4024 CSEMap.InsertNode(N, IP); 4025 } else { 4026 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4027 createOperands(N, Ops); 4028 } 4029 4030 InsertNode(N); 4031 return SDValue(N, 0); 4032 } 4033 4034 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4035 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 4036 SDValue Ops[] = { N1, N2, N3, N4 }; 4037 return getNode(Opcode, DL, VT, Ops); 4038 } 4039 4040 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4041 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 4042 SDValue N5) { 4043 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 4044 return getNode(Opcode, DL, VT, Ops); 4045 } 4046 4047 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 4048 /// the incoming stack arguments to be loaded from the stack. 4049 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 4050 SmallVector<SDValue, 8> ArgChains; 4051 4052 // Include the original chain at the beginning of the list. When this is 4053 // used by target LowerCall hooks, this helps legalize find the 4054 // CALLSEQ_BEGIN node. 4055 ArgChains.push_back(Chain); 4056 4057 // Add a chain value for each stack argument. 4058 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 4059 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 4060 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 4061 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 4062 if (FI->getIndex() < 0) 4063 ArgChains.push_back(SDValue(L, 1)); 4064 4065 // Build a tokenfactor for all the chains. 4066 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 4067 } 4068 4069 /// getMemsetValue - Vectorized representation of the memset value 4070 /// operand. 4071 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 4072 const SDLoc &dl) { 4073 assert(!Value.isUndef()); 4074 4075 unsigned NumBits = VT.getScalarType().getSizeInBits(); 4076 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 4077 assert(C->getAPIntValue().getBitWidth() == 8); 4078 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 4079 if (VT.isInteger()) 4080 return DAG.getConstant(Val, dl, VT); 4081 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 4082 VT); 4083 } 4084 4085 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 4086 EVT IntVT = VT.getScalarType(); 4087 if (!IntVT.isInteger()) 4088 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 4089 4090 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 4091 if (NumBits > 8) { 4092 // Use a multiplication with 0x010101... to extend the input to the 4093 // required length. 4094 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 4095 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 4096 DAG.getConstant(Magic, dl, IntVT)); 4097 } 4098 4099 if (VT != Value.getValueType() && !VT.isInteger()) 4100 Value = DAG.getBitcast(VT.getScalarType(), Value); 4101 if (VT != Value.getValueType()) 4102 Value = DAG.getSplatBuildVector(VT, dl, Value); 4103 4104 return Value; 4105 } 4106 4107 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 4108 /// used when a memcpy is turned into a memset when the source is a constant 4109 /// string ptr. 4110 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 4111 const TargetLowering &TLI, StringRef Str) { 4112 // Handle vector with all elements zero. 4113 if (Str.empty()) { 4114 if (VT.isInteger()) 4115 return DAG.getConstant(0, dl, VT); 4116 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 4117 return DAG.getConstantFP(0.0, dl, VT); 4118 else if (VT.isVector()) { 4119 unsigned NumElts = VT.getVectorNumElements(); 4120 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 4121 return DAG.getNode(ISD::BITCAST, dl, VT, 4122 DAG.getConstant(0, dl, 4123 EVT::getVectorVT(*DAG.getContext(), 4124 EltVT, NumElts))); 4125 } else 4126 llvm_unreachable("Expected type!"); 4127 } 4128 4129 assert(!VT.isVector() && "Can't handle vector type here!"); 4130 unsigned NumVTBits = VT.getSizeInBits(); 4131 unsigned NumVTBytes = NumVTBits / 8; 4132 unsigned NumBytes = std::min(NumVTBytes, unsigned(Str.size())); 4133 4134 APInt Val(NumVTBits, 0); 4135 if (DAG.getDataLayout().isLittleEndian()) { 4136 for (unsigned i = 0; i != NumBytes; ++i) 4137 Val |= (uint64_t)(unsigned char)Str[i] << i*8; 4138 } else { 4139 for (unsigned i = 0; i != NumBytes; ++i) 4140 Val |= (uint64_t)(unsigned char)Str[i] << (NumVTBytes-i-1)*8; 4141 } 4142 4143 // If the "cost" of materializing the integer immediate is less than the cost 4144 // of a load, then it is cost effective to turn the load into the immediate. 4145 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 4146 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 4147 return DAG.getConstant(Val, dl, VT); 4148 return SDValue(nullptr, 0); 4149 } 4150 4151 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset, 4152 const SDLoc &DL) { 4153 EVT VT = Base.getValueType(); 4154 return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT)); 4155 } 4156 4157 /// isMemSrcFromString - Returns true if memcpy source is a string constant. 4158 /// 4159 static bool isMemSrcFromString(SDValue Src, StringRef &Str) { 4160 uint64_t SrcDelta = 0; 4161 GlobalAddressSDNode *G = nullptr; 4162 if (Src.getOpcode() == ISD::GlobalAddress) 4163 G = cast<GlobalAddressSDNode>(Src); 4164 else if (Src.getOpcode() == ISD::ADD && 4165 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 4166 Src.getOperand(1).getOpcode() == ISD::Constant) { 4167 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 4168 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 4169 } 4170 if (!G) 4171 return false; 4172 4173 return getConstantStringInfo(G->getGlobal(), Str, 4174 SrcDelta + G->getOffset(), false); 4175 } 4176 4177 /// Determines the optimal series of memory ops to replace the memset / memcpy. 4178 /// Return true if the number of memory ops is below the threshold (Limit). 4179 /// It returns the types of the sequence of memory ops to perform 4180 /// memset / memcpy by reference. 4181 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps, 4182 unsigned Limit, uint64_t Size, 4183 unsigned DstAlign, unsigned SrcAlign, 4184 bool IsMemset, 4185 bool ZeroMemset, 4186 bool MemcpyStrSrc, 4187 bool AllowOverlap, 4188 unsigned DstAS, unsigned SrcAS, 4189 SelectionDAG &DAG, 4190 const TargetLowering &TLI) { 4191 assert((SrcAlign == 0 || SrcAlign >= DstAlign) && 4192 "Expecting memcpy / memset source to meet alignment requirement!"); 4193 // If 'SrcAlign' is zero, that means the memory operation does not need to 4194 // load the value, i.e. memset or memcpy from constant string. Otherwise, 4195 // it's the inferred alignment of the source. 'DstAlign', on the other hand, 4196 // is the specified alignment of the memory operation. If it is zero, that 4197 // means it's possible to change the alignment of the destination. 4198 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does 4199 // not need to be loaded. 4200 EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign, 4201 IsMemset, ZeroMemset, MemcpyStrSrc, 4202 DAG.getMachineFunction()); 4203 4204 if (VT == MVT::Other) { 4205 if (DstAlign >= DAG.getDataLayout().getPointerPrefAlignment(DstAS) || 4206 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign)) { 4207 VT = TLI.getPointerTy(DAG.getDataLayout(), DstAS); 4208 } else { 4209 switch (DstAlign & 7) { 4210 case 0: VT = MVT::i64; break; 4211 case 4: VT = MVT::i32; break; 4212 case 2: VT = MVT::i16; break; 4213 default: VT = MVT::i8; break; 4214 } 4215 } 4216 4217 MVT LVT = MVT::i64; 4218 while (!TLI.isTypeLegal(LVT)) 4219 LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1); 4220 assert(LVT.isInteger()); 4221 4222 if (VT.bitsGT(LVT)) 4223 VT = LVT; 4224 } 4225 4226 unsigned NumMemOps = 0; 4227 while (Size != 0) { 4228 unsigned VTSize = VT.getSizeInBits() / 8; 4229 while (VTSize > Size) { 4230 // For now, only use non-vector load / store's for the left-over pieces. 4231 EVT NewVT = VT; 4232 unsigned NewVTSize; 4233 4234 bool Found = false; 4235 if (VT.isVector() || VT.isFloatingPoint()) { 4236 NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32; 4237 if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) && 4238 TLI.isSafeMemOpType(NewVT.getSimpleVT())) 4239 Found = true; 4240 else if (NewVT == MVT::i64 && 4241 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) && 4242 TLI.isSafeMemOpType(MVT::f64)) { 4243 // i64 is usually not legal on 32-bit targets, but f64 may be. 4244 NewVT = MVT::f64; 4245 Found = true; 4246 } 4247 } 4248 4249 if (!Found) { 4250 do { 4251 NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1); 4252 if (NewVT == MVT::i8) 4253 break; 4254 } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT())); 4255 } 4256 NewVTSize = NewVT.getSizeInBits() / 8; 4257 4258 // If the new VT cannot cover all of the remaining bits, then consider 4259 // issuing a (or a pair of) unaligned and overlapping load / store. 4260 // FIXME: Only does this for 64-bit or more since we don't have proper 4261 // cost model for unaligned load / store. 4262 bool Fast; 4263 if (NumMemOps && AllowOverlap && 4264 VTSize >= 8 && NewVTSize < Size && 4265 TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) && Fast) 4266 VTSize = Size; 4267 else { 4268 VT = NewVT; 4269 VTSize = NewVTSize; 4270 } 4271 } 4272 4273 if (++NumMemOps > Limit) 4274 return false; 4275 4276 MemOps.push_back(VT); 4277 Size -= VTSize; 4278 } 4279 4280 return true; 4281 } 4282 4283 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) { 4284 // On Darwin, -Os means optimize for size without hurting performance, so 4285 // only really optimize for size when -Oz (MinSize) is used. 4286 if (MF.getTarget().getTargetTriple().isOSDarwin()) 4287 return MF.getFunction()->optForMinSize(); 4288 return MF.getFunction()->optForSize(); 4289 } 4290 4291 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 4292 SDValue Chain, SDValue Dst, SDValue Src, 4293 uint64_t Size, unsigned Align, 4294 bool isVol, bool AlwaysInline, 4295 MachinePointerInfo DstPtrInfo, 4296 MachinePointerInfo SrcPtrInfo) { 4297 // Turn a memcpy of undef to nop. 4298 if (Src.isUndef()) 4299 return Chain; 4300 4301 // Expand memcpy to a series of load and store ops if the size operand falls 4302 // below a certain threshold. 4303 // TODO: In the AlwaysInline case, if the size is big then generate a loop 4304 // rather than maybe a humongous number of loads and stores. 4305 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4306 std::vector<EVT> MemOps; 4307 bool DstAlignCanChange = false; 4308 MachineFunction &MF = DAG.getMachineFunction(); 4309 MachineFrameInfo *MFI = MF.getFrameInfo(); 4310 bool OptSize = shouldLowerMemFuncForSize(MF); 4311 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 4312 if (FI && !MFI->isFixedObjectIndex(FI->getIndex())) 4313 DstAlignCanChange = true; 4314 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 4315 if (Align > SrcAlign) 4316 SrcAlign = Align; 4317 StringRef Str; 4318 bool CopyFromStr = isMemSrcFromString(Src, Str); 4319 bool isZeroStr = CopyFromStr && Str.empty(); 4320 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 4321 4322 if (!FindOptimalMemOpLowering(MemOps, Limit, Size, 4323 (DstAlignCanChange ? 0 : Align), 4324 (isZeroStr ? 0 : SrcAlign), 4325 false, false, CopyFromStr, true, 4326 DstPtrInfo.getAddrSpace(), 4327 SrcPtrInfo.getAddrSpace(), 4328 DAG, TLI)) 4329 return SDValue(); 4330 4331 if (DstAlignCanChange) { 4332 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 4333 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty); 4334 4335 // Don't promote to an alignment that would require dynamic stack 4336 // realignment. 4337 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 4338 if (!TRI->needsStackRealignment(MF)) 4339 while (NewAlign > Align && 4340 DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign)) 4341 NewAlign /= 2; 4342 4343 if (NewAlign > Align) { 4344 // Give the stack frame object a larger alignment if needed. 4345 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign) 4346 MFI->setObjectAlignment(FI->getIndex(), NewAlign); 4347 Align = NewAlign; 4348 } 4349 } 4350 4351 MachineMemOperand::Flags MMOFlags = 4352 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 4353 SmallVector<SDValue, 8> OutChains; 4354 unsigned NumMemOps = MemOps.size(); 4355 uint64_t SrcOff = 0, DstOff = 0; 4356 for (unsigned i = 0; i != NumMemOps; ++i) { 4357 EVT VT = MemOps[i]; 4358 unsigned VTSize = VT.getSizeInBits() / 8; 4359 SDValue Value, Store; 4360 4361 if (VTSize > Size) { 4362 // Issuing an unaligned load / store pair that overlaps with the previous 4363 // pair. Adjust the offset accordingly. 4364 assert(i == NumMemOps-1 && i != 0); 4365 SrcOff -= VTSize - Size; 4366 DstOff -= VTSize - Size; 4367 } 4368 4369 if (CopyFromStr && 4370 (isZeroStr || (VT.isInteger() && !VT.isVector()))) { 4371 // It's unlikely a store of a vector immediate can be done in a single 4372 // instruction. It would require a load from a constantpool first. 4373 // We only handle zero vectors here. 4374 // FIXME: Handle other cases where store of vector immediate is done in 4375 // a single instruction. 4376 Value = getMemsetStringVal(VT, dl, DAG, TLI, Str.substr(SrcOff)); 4377 if (Value.getNode()) 4378 Store = DAG.getStore(Chain, dl, Value, 4379 DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4380 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags); 4381 } 4382 4383 if (!Store.getNode()) { 4384 // The type might not be legal for the target. This should only happen 4385 // if the type is smaller than a legal type, as on PPC, so the right 4386 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 4387 // to Load/Store if NVT==VT. 4388 // FIXME does the case above also need this? 4389 EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 4390 assert(NVT.bitsGE(VT)); 4391 Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain, 4392 DAG.getMemBasePlusOffset(Src, SrcOff, dl), 4393 SrcPtrInfo.getWithOffset(SrcOff), VT, 4394 MinAlign(SrcAlign, SrcOff), MMOFlags); 4395 OutChains.push_back(Value.getValue(1)); 4396 Store = DAG.getTruncStore( 4397 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4398 DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags); 4399 } 4400 OutChains.push_back(Store); 4401 SrcOff += VTSize; 4402 DstOff += VTSize; 4403 Size -= VTSize; 4404 } 4405 4406 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 4407 } 4408 4409 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 4410 SDValue Chain, SDValue Dst, SDValue Src, 4411 uint64_t Size, unsigned Align, 4412 bool isVol, bool AlwaysInline, 4413 MachinePointerInfo DstPtrInfo, 4414 MachinePointerInfo SrcPtrInfo) { 4415 // Turn a memmove of undef to nop. 4416 if (Src.isUndef()) 4417 return Chain; 4418 4419 // Expand memmove to a series of load and store ops if the size operand falls 4420 // below a certain threshold. 4421 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4422 std::vector<EVT> MemOps; 4423 bool DstAlignCanChange = false; 4424 MachineFunction &MF = DAG.getMachineFunction(); 4425 MachineFrameInfo *MFI = MF.getFrameInfo(); 4426 bool OptSize = shouldLowerMemFuncForSize(MF); 4427 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 4428 if (FI && !MFI->isFixedObjectIndex(FI->getIndex())) 4429 DstAlignCanChange = true; 4430 unsigned SrcAlign = DAG.InferPtrAlignment(Src); 4431 if (Align > SrcAlign) 4432 SrcAlign = Align; 4433 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 4434 4435 if (!FindOptimalMemOpLowering(MemOps, Limit, Size, 4436 (DstAlignCanChange ? 0 : Align), SrcAlign, 4437 false, false, false, false, 4438 DstPtrInfo.getAddrSpace(), 4439 SrcPtrInfo.getAddrSpace(), 4440 DAG, TLI)) 4441 return SDValue(); 4442 4443 if (DstAlignCanChange) { 4444 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 4445 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty); 4446 if (NewAlign > Align) { 4447 // Give the stack frame object a larger alignment if needed. 4448 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign) 4449 MFI->setObjectAlignment(FI->getIndex(), NewAlign); 4450 Align = NewAlign; 4451 } 4452 } 4453 4454 MachineMemOperand::Flags MMOFlags = 4455 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 4456 uint64_t SrcOff = 0, DstOff = 0; 4457 SmallVector<SDValue, 8> LoadValues; 4458 SmallVector<SDValue, 8> LoadChains; 4459 SmallVector<SDValue, 8> OutChains; 4460 unsigned NumMemOps = MemOps.size(); 4461 for (unsigned i = 0; i < NumMemOps; i++) { 4462 EVT VT = MemOps[i]; 4463 unsigned VTSize = VT.getSizeInBits() / 8; 4464 SDValue Value; 4465 4466 Value = 4467 DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl), 4468 SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, MMOFlags); 4469 LoadValues.push_back(Value); 4470 LoadChains.push_back(Value.getValue(1)); 4471 SrcOff += VTSize; 4472 } 4473 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 4474 OutChains.clear(); 4475 for (unsigned i = 0; i < NumMemOps; i++) { 4476 EVT VT = MemOps[i]; 4477 unsigned VTSize = VT.getSizeInBits() / 8; 4478 SDValue Store; 4479 4480 Store = DAG.getStore(Chain, dl, LoadValues[i], 4481 DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4482 DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags); 4483 OutChains.push_back(Store); 4484 DstOff += VTSize; 4485 } 4486 4487 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 4488 } 4489 4490 /// \brief Lower the call to 'memset' intrinsic function into a series of store 4491 /// operations. 4492 /// 4493 /// \param DAG Selection DAG where lowered code is placed. 4494 /// \param dl Link to corresponding IR location. 4495 /// \param Chain Control flow dependency. 4496 /// \param Dst Pointer to destination memory location. 4497 /// \param Src Value of byte to write into the memory. 4498 /// \param Size Number of bytes to write. 4499 /// \param Align Alignment of the destination in bytes. 4500 /// \param isVol True if destination is volatile. 4501 /// \param DstPtrInfo IR information on the memory pointer. 4502 /// \returns New head in the control flow, if lowering was successful, empty 4503 /// SDValue otherwise. 4504 /// 4505 /// The function tries to replace 'llvm.memset' intrinsic with several store 4506 /// operations and value calculation code. This is usually profitable for small 4507 /// memory size. 4508 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 4509 SDValue Chain, SDValue Dst, SDValue Src, 4510 uint64_t Size, unsigned Align, bool isVol, 4511 MachinePointerInfo DstPtrInfo) { 4512 // Turn a memset of undef to nop. 4513 if (Src.isUndef()) 4514 return Chain; 4515 4516 // Expand memset to a series of load/store ops if the size operand 4517 // falls below a certain threshold. 4518 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 4519 std::vector<EVT> MemOps; 4520 bool DstAlignCanChange = false; 4521 MachineFunction &MF = DAG.getMachineFunction(); 4522 MachineFrameInfo *MFI = MF.getFrameInfo(); 4523 bool OptSize = shouldLowerMemFuncForSize(MF); 4524 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 4525 if (FI && !MFI->isFixedObjectIndex(FI->getIndex())) 4526 DstAlignCanChange = true; 4527 bool IsZeroVal = 4528 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 4529 if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize), 4530 Size, (DstAlignCanChange ? 0 : Align), 0, 4531 true, IsZeroVal, false, true, 4532 DstPtrInfo.getAddrSpace(), ~0u, 4533 DAG, TLI)) 4534 return SDValue(); 4535 4536 if (DstAlignCanChange) { 4537 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 4538 unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty); 4539 if (NewAlign > Align) { 4540 // Give the stack frame object a larger alignment if needed. 4541 if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign) 4542 MFI->setObjectAlignment(FI->getIndex(), NewAlign); 4543 Align = NewAlign; 4544 } 4545 } 4546 4547 SmallVector<SDValue, 8> OutChains; 4548 uint64_t DstOff = 0; 4549 unsigned NumMemOps = MemOps.size(); 4550 4551 // Find the largest store and generate the bit pattern for it. 4552 EVT LargestVT = MemOps[0]; 4553 for (unsigned i = 1; i < NumMemOps; i++) 4554 if (MemOps[i].bitsGT(LargestVT)) 4555 LargestVT = MemOps[i]; 4556 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 4557 4558 for (unsigned i = 0; i < NumMemOps; i++) { 4559 EVT VT = MemOps[i]; 4560 unsigned VTSize = VT.getSizeInBits() / 8; 4561 if (VTSize > Size) { 4562 // Issuing an unaligned load / store pair that overlaps with the previous 4563 // pair. Adjust the offset accordingly. 4564 assert(i == NumMemOps-1 && i != 0); 4565 DstOff -= VTSize - Size; 4566 } 4567 4568 // If this store is smaller than the largest store see whether we can get 4569 // the smaller value for free with a truncate. 4570 SDValue Value = MemSetValue; 4571 if (VT.bitsLT(LargestVT)) { 4572 if (!LargestVT.isVector() && !VT.isVector() && 4573 TLI.isTruncateFree(LargestVT, VT)) 4574 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 4575 else 4576 Value = getMemsetValue(Src, VT, DAG, dl); 4577 } 4578 assert(Value.getValueType() == VT && "Value with wrong type."); 4579 SDValue Store = DAG.getStore( 4580 Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl), 4581 DstPtrInfo.getWithOffset(DstOff), Align, 4582 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone); 4583 OutChains.push_back(Store); 4584 DstOff += VT.getSizeInBits() / 8; 4585 Size -= VTSize; 4586 } 4587 4588 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 4589 } 4590 4591 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 4592 unsigned AS) { 4593 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 4594 // pointer operands can be losslessly bitcasted to pointers of address space 0 4595 if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) { 4596 report_fatal_error("cannot lower memory intrinsic in address space " + 4597 Twine(AS)); 4598 } 4599 } 4600 4601 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 4602 SDValue Src, SDValue Size, unsigned Align, 4603 bool isVol, bool AlwaysInline, bool isTailCall, 4604 MachinePointerInfo DstPtrInfo, 4605 MachinePointerInfo SrcPtrInfo) { 4606 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4607 4608 // Check to see if we should lower the memcpy to loads and stores first. 4609 // For cases within the target-specified limits, this is the best choice. 4610 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4611 if (ConstantSize) { 4612 // Memcpy with size zero? Just return the original chain. 4613 if (ConstantSize->isNullValue()) 4614 return Chain; 4615 4616 SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 4617 ConstantSize->getZExtValue(),Align, 4618 isVol, false, DstPtrInfo, SrcPtrInfo); 4619 if (Result.getNode()) 4620 return Result; 4621 } 4622 4623 // Then check to see if we should lower the memcpy with target-specific 4624 // code. If the target chooses to do this, this is the next best. 4625 if (TSI) { 4626 SDValue Result = TSI->EmitTargetCodeForMemcpy( 4627 *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline, 4628 DstPtrInfo, SrcPtrInfo); 4629 if (Result.getNode()) 4630 return Result; 4631 } 4632 4633 // If we really need inline code and the target declined to provide it, 4634 // use a (potentially long) sequence of loads and stores. 4635 if (AlwaysInline) { 4636 assert(ConstantSize && "AlwaysInline requires a constant size!"); 4637 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 4638 ConstantSize->getZExtValue(), Align, isVol, 4639 true, DstPtrInfo, SrcPtrInfo); 4640 } 4641 4642 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 4643 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 4644 4645 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 4646 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 4647 // respect volatile, so they may do things like read or write memory 4648 // beyond the given memory regions. But fixing this isn't easy, and most 4649 // people don't care. 4650 4651 // Emit a library call. 4652 TargetLowering::ArgListTy Args; 4653 TargetLowering::ArgListEntry Entry; 4654 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 4655 Entry.Node = Dst; Args.push_back(Entry); 4656 Entry.Node = Src; Args.push_back(Entry); 4657 Entry.Node = Size; Args.push_back(Entry); 4658 // FIXME: pass in SDLoc 4659 TargetLowering::CallLoweringInfo CLI(*this); 4660 CLI.setDebugLoc(dl) 4661 .setChain(Chain) 4662 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 4663 Dst.getValueType().getTypeForEVT(*getContext()), 4664 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 4665 TLI->getPointerTy(getDataLayout())), 4666 std::move(Args)) 4667 .setDiscardResult() 4668 .setTailCall(isTailCall); 4669 4670 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4671 return CallResult.second; 4672 } 4673 4674 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 4675 SDValue Src, SDValue Size, unsigned Align, 4676 bool isVol, bool isTailCall, 4677 MachinePointerInfo DstPtrInfo, 4678 MachinePointerInfo SrcPtrInfo) { 4679 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4680 4681 // Check to see if we should lower the memmove to loads and stores first. 4682 // For cases within the target-specified limits, this is the best choice. 4683 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4684 if (ConstantSize) { 4685 // Memmove with size zero? Just return the original chain. 4686 if (ConstantSize->isNullValue()) 4687 return Chain; 4688 4689 SDValue Result = 4690 getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src, 4691 ConstantSize->getZExtValue(), Align, isVol, 4692 false, DstPtrInfo, SrcPtrInfo); 4693 if (Result.getNode()) 4694 return Result; 4695 } 4696 4697 // Then check to see if we should lower the memmove with target-specific 4698 // code. If the target chooses to do this, this is the next best. 4699 if (TSI) { 4700 SDValue Result = TSI->EmitTargetCodeForMemmove( 4701 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo); 4702 if (Result.getNode()) 4703 return Result; 4704 } 4705 4706 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 4707 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 4708 4709 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 4710 // not be safe. See memcpy above for more details. 4711 4712 // Emit a library call. 4713 TargetLowering::ArgListTy Args; 4714 TargetLowering::ArgListEntry Entry; 4715 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 4716 Entry.Node = Dst; Args.push_back(Entry); 4717 Entry.Node = Src; Args.push_back(Entry); 4718 Entry.Node = Size; Args.push_back(Entry); 4719 // FIXME: pass in SDLoc 4720 TargetLowering::CallLoweringInfo CLI(*this); 4721 CLI.setDebugLoc(dl) 4722 .setChain(Chain) 4723 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 4724 Dst.getValueType().getTypeForEVT(*getContext()), 4725 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 4726 TLI->getPointerTy(getDataLayout())), 4727 std::move(Args)) 4728 .setDiscardResult() 4729 .setTailCall(isTailCall); 4730 4731 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4732 return CallResult.second; 4733 } 4734 4735 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 4736 SDValue Src, SDValue Size, unsigned Align, 4737 bool isVol, bool isTailCall, 4738 MachinePointerInfo DstPtrInfo) { 4739 assert(Align && "The SDAG layer expects explicit alignment and reserves 0"); 4740 4741 // Check to see if we should lower the memset to stores first. 4742 // For cases within the target-specified limits, this is the best choice. 4743 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 4744 if (ConstantSize) { 4745 // Memset with size zero? Just return the original chain. 4746 if (ConstantSize->isNullValue()) 4747 return Chain; 4748 4749 SDValue Result = 4750 getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), 4751 Align, isVol, DstPtrInfo); 4752 4753 if (Result.getNode()) 4754 return Result; 4755 } 4756 4757 // Then check to see if we should lower the memset with target-specific 4758 // code. If the target chooses to do this, this is the next best. 4759 if (TSI) { 4760 SDValue Result = TSI->EmitTargetCodeForMemset( 4761 *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo); 4762 if (Result.getNode()) 4763 return Result; 4764 } 4765 4766 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 4767 4768 // Emit a library call. 4769 Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext()); 4770 TargetLowering::ArgListTy Args; 4771 TargetLowering::ArgListEntry Entry; 4772 Entry.Node = Dst; Entry.Ty = IntPtrTy; 4773 Args.push_back(Entry); 4774 Entry.Node = Src; 4775 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 4776 Args.push_back(Entry); 4777 Entry.Node = Size; 4778 Entry.Ty = IntPtrTy; 4779 Args.push_back(Entry); 4780 4781 // FIXME: pass in SDLoc 4782 TargetLowering::CallLoweringInfo CLI(*this); 4783 CLI.setDebugLoc(dl) 4784 .setChain(Chain) 4785 .setCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 4786 Dst.getValueType().getTypeForEVT(*getContext()), 4787 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 4788 TLI->getPointerTy(getDataLayout())), 4789 std::move(Args)) 4790 .setDiscardResult() 4791 .setTailCall(isTailCall); 4792 4793 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 4794 return CallResult.second; 4795 } 4796 4797 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 4798 SDVTList VTList, ArrayRef<SDValue> Ops, 4799 MachineMemOperand *MMO, 4800 AtomicOrdering SuccessOrdering, 4801 AtomicOrdering FailureOrdering, 4802 SynchronizationScope SynchScope) { 4803 FoldingSetNodeID ID; 4804 ID.AddInteger(MemVT.getRawBits()); 4805 AddNodeIDNode(ID, Opcode, VTList, Ops); 4806 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 4807 void* IP = nullptr; 4808 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 4809 cast<AtomicSDNode>(E)->refineAlignment(MMO); 4810 return SDValue(E, 0); 4811 } 4812 4813 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 4814 VTList, MemVT, MMO, SuccessOrdering, 4815 FailureOrdering, SynchScope); 4816 createOperands(N, Ops); 4817 4818 CSEMap.InsertNode(N, IP); 4819 InsertNode(N); 4820 return SDValue(N, 0); 4821 } 4822 4823 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 4824 SDVTList VTList, ArrayRef<SDValue> Ops, 4825 MachineMemOperand *MMO, AtomicOrdering Ordering, 4826 SynchronizationScope SynchScope) { 4827 return getAtomic(Opcode, dl, MemVT, VTList, Ops, MMO, Ordering, 4828 Ordering, SynchScope); 4829 } 4830 4831 SDValue SelectionDAG::getAtomicCmpSwap( 4832 unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, 4833 SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo, 4834 unsigned Alignment, AtomicOrdering SuccessOrdering, 4835 AtomicOrdering FailureOrdering, SynchronizationScope SynchScope) { 4836 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 4837 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 4838 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 4839 4840 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4841 Alignment = getEVTAlignment(MemVT); 4842 4843 MachineFunction &MF = getMachineFunction(); 4844 4845 // FIXME: Volatile isn't really correct; we should keep track of atomic 4846 // orderings in the memoperand. 4847 auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad | 4848 MachineMemOperand::MOStore; 4849 MachineMemOperand *MMO = 4850 MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment); 4851 4852 return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO, 4853 SuccessOrdering, FailureOrdering, SynchScope); 4854 } 4855 4856 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 4857 EVT MemVT, SDVTList VTs, SDValue Chain, 4858 SDValue Ptr, SDValue Cmp, SDValue Swp, 4859 MachineMemOperand *MMO, 4860 AtomicOrdering SuccessOrdering, 4861 AtomicOrdering FailureOrdering, 4862 SynchronizationScope SynchScope) { 4863 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 4864 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 4865 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 4866 4867 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 4868 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, 4869 SuccessOrdering, FailureOrdering, SynchScope); 4870 } 4871 4872 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 4873 SDValue Chain, SDValue Ptr, SDValue Val, 4874 const Value *PtrVal, unsigned Alignment, 4875 AtomicOrdering Ordering, 4876 SynchronizationScope SynchScope) { 4877 if (Alignment == 0) // Ensure that codegen never sees alignment 0 4878 Alignment = getEVTAlignment(MemVT); 4879 4880 MachineFunction &MF = getMachineFunction(); 4881 // An atomic store does not load. An atomic load does not store. 4882 // (An atomicrmw obviously both loads and stores.) 4883 // For now, atomics are considered to be volatile always, and they are 4884 // chained as such. 4885 // FIXME: Volatile isn't really correct; we should keep track of atomic 4886 // orderings in the memoperand. 4887 auto Flags = MachineMemOperand::MOVolatile; 4888 if (Opcode != ISD::ATOMIC_STORE) 4889 Flags |= MachineMemOperand::MOLoad; 4890 if (Opcode != ISD::ATOMIC_LOAD) 4891 Flags |= MachineMemOperand::MOStore; 4892 4893 MachineMemOperand *MMO = 4894 MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags, 4895 MemVT.getStoreSize(), Alignment); 4896 4897 return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO, 4898 Ordering, SynchScope); 4899 } 4900 4901 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 4902 SDValue Chain, SDValue Ptr, SDValue Val, 4903 MachineMemOperand *MMO, AtomicOrdering Ordering, 4904 SynchronizationScope SynchScope) { 4905 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 4906 Opcode == ISD::ATOMIC_LOAD_SUB || 4907 Opcode == ISD::ATOMIC_LOAD_AND || 4908 Opcode == ISD::ATOMIC_LOAD_OR || 4909 Opcode == ISD::ATOMIC_LOAD_XOR || 4910 Opcode == ISD::ATOMIC_LOAD_NAND || 4911 Opcode == ISD::ATOMIC_LOAD_MIN || 4912 Opcode == ISD::ATOMIC_LOAD_MAX || 4913 Opcode == ISD::ATOMIC_LOAD_UMIN || 4914 Opcode == ISD::ATOMIC_LOAD_UMAX || 4915 Opcode == ISD::ATOMIC_SWAP || 4916 Opcode == ISD::ATOMIC_STORE) && 4917 "Invalid Atomic Op"); 4918 4919 EVT VT = Val.getValueType(); 4920 4921 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 4922 getVTList(VT, MVT::Other); 4923 SDValue Ops[] = {Chain, Ptr, Val}; 4924 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope); 4925 } 4926 4927 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 4928 EVT VT, SDValue Chain, SDValue Ptr, 4929 MachineMemOperand *MMO, AtomicOrdering Ordering, 4930 SynchronizationScope SynchScope) { 4931 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 4932 4933 SDVTList VTs = getVTList(VT, MVT::Other); 4934 SDValue Ops[] = {Chain, Ptr}; 4935 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO, Ordering, SynchScope); 4936 } 4937 4938 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 4939 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 4940 if (Ops.size() == 1) 4941 return Ops[0]; 4942 4943 SmallVector<EVT, 4> VTs; 4944 VTs.reserve(Ops.size()); 4945 for (unsigned i = 0; i < Ops.size(); ++i) 4946 VTs.push_back(Ops[i].getValueType()); 4947 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 4948 } 4949 4950 SDValue SelectionDAG::getMemIntrinsicNode( 4951 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 4952 EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align, bool Vol, 4953 bool ReadMem, bool WriteMem, unsigned Size) { 4954 if (Align == 0) // Ensure that codegen never sees alignment 0 4955 Align = getEVTAlignment(MemVT); 4956 4957 MachineFunction &MF = getMachineFunction(); 4958 auto Flags = MachineMemOperand::MONone; 4959 if (WriteMem) 4960 Flags |= MachineMemOperand::MOStore; 4961 if (ReadMem) 4962 Flags |= MachineMemOperand::MOLoad; 4963 if (Vol) 4964 Flags |= MachineMemOperand::MOVolatile; 4965 if (!Size) 4966 Size = MemVT.getStoreSize(); 4967 MachineMemOperand *MMO = 4968 MF.getMachineMemOperand(PtrInfo, Flags, Size, Align); 4969 4970 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 4971 } 4972 4973 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 4974 SDVTList VTList, 4975 ArrayRef<SDValue> Ops, EVT MemVT, 4976 MachineMemOperand *MMO) { 4977 assert((Opcode == ISD::INTRINSIC_VOID || 4978 Opcode == ISD::INTRINSIC_W_CHAIN || 4979 Opcode == ISD::PREFETCH || 4980 Opcode == ISD::LIFETIME_START || 4981 Opcode == ISD::LIFETIME_END || 4982 (Opcode <= INT_MAX && 4983 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 4984 "Opcode is not a memory-accessing opcode!"); 4985 4986 // Memoize the node unless it returns a flag. 4987 MemIntrinsicSDNode *N; 4988 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 4989 FoldingSetNodeID ID; 4990 AddNodeIDNode(ID, Opcode, VTList, Ops); 4991 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 4992 void *IP = nullptr; 4993 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 4994 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 4995 return SDValue(E, 0); 4996 } 4997 4998 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 4999 VTList, MemVT, MMO); 5000 createOperands(N, Ops); 5001 5002 CSEMap.InsertNode(N, IP); 5003 } else { 5004 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 5005 VTList, MemVT, MMO); 5006 createOperands(N, Ops); 5007 } 5008 InsertNode(N); 5009 return SDValue(N, 0); 5010 } 5011 5012 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 5013 /// MachinePointerInfo record from it. This is particularly useful because the 5014 /// code generator has many cases where it doesn't bother passing in a 5015 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 5016 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr, 5017 int64_t Offset = 0) { 5018 // If this is FI+Offset, we can model it. 5019 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 5020 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 5021 FI->getIndex(), Offset); 5022 5023 // If this is (FI+Offset1)+Offset2, we can model it. 5024 if (Ptr.getOpcode() != ISD::ADD || 5025 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 5026 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 5027 return MachinePointerInfo(); 5028 5029 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 5030 return MachinePointerInfo::getFixedStack( 5031 DAG.getMachineFunction(), FI, 5032 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 5033 } 5034 5035 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 5036 /// MachinePointerInfo record from it. This is particularly useful because the 5037 /// code generator has many cases where it doesn't bother passing in a 5038 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 5039 static MachinePointerInfo InferPointerInfo(SelectionDAG &DAG, SDValue Ptr, 5040 SDValue OffsetOp) { 5041 // If the 'Offset' value isn't a constant, we can't handle this. 5042 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 5043 return InferPointerInfo(DAG, Ptr, OffsetNode->getSExtValue()); 5044 if (OffsetOp.isUndef()) 5045 return InferPointerInfo(DAG, Ptr); 5046 return MachinePointerInfo(); 5047 } 5048 5049 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 5050 EVT VT, const SDLoc &dl, SDValue Chain, 5051 SDValue Ptr, SDValue Offset, 5052 MachinePointerInfo PtrInfo, EVT MemVT, 5053 unsigned Alignment, 5054 MachineMemOperand::Flags MMOFlags, 5055 const AAMDNodes &AAInfo, const MDNode *Ranges) { 5056 assert(Chain.getValueType() == MVT::Other && 5057 "Invalid chain type"); 5058 if (Alignment == 0) // Ensure that codegen never sees alignment 0 5059 Alignment = getEVTAlignment(VT); 5060 5061 MMOFlags |= MachineMemOperand::MOLoad; 5062 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 5063 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 5064 // clients. 5065 if (PtrInfo.V.isNull()) 5066 PtrInfo = InferPointerInfo(*this, Ptr, Offset); 5067 5068 MachineFunction &MF = getMachineFunction(); 5069 MachineMemOperand *MMO = MF.getMachineMemOperand( 5070 PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges); 5071 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 5072 } 5073 5074 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 5075 EVT VT, const SDLoc &dl, SDValue Chain, 5076 SDValue Ptr, SDValue Offset, EVT MemVT, 5077 MachineMemOperand *MMO) { 5078 if (VT == MemVT) { 5079 ExtType = ISD::NON_EXTLOAD; 5080 } else if (ExtType == ISD::NON_EXTLOAD) { 5081 assert(VT == MemVT && "Non-extending load from different memory type!"); 5082 } else { 5083 // Extending load. 5084 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 5085 "Should only be an extending load, not truncating!"); 5086 assert(VT.isInteger() == MemVT.isInteger() && 5087 "Cannot convert from FP to Int or Int -> FP!"); 5088 assert(VT.isVector() == MemVT.isVector() && 5089 "Cannot use an ext load to convert to or from a vector!"); 5090 assert((!VT.isVector() || 5091 VT.getVectorNumElements() == MemVT.getVectorNumElements()) && 5092 "Cannot use an ext load to change the number of vector elements!"); 5093 } 5094 5095 bool Indexed = AM != ISD::UNINDEXED; 5096 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 5097 5098 SDVTList VTs = Indexed ? 5099 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 5100 SDValue Ops[] = { Chain, Ptr, Offset }; 5101 FoldingSetNodeID ID; 5102 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 5103 ID.AddInteger(MemVT.getRawBits()); 5104 ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(), 5105 MMO->isNonTemporal(), 5106 MMO->isInvariant())); 5107 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5108 void *IP = nullptr; 5109 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5110 cast<LoadSDNode>(E)->refineAlignment(MMO); 5111 return SDValue(E, 0); 5112 } 5113 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 5114 ExtType, MemVT, MMO); 5115 createOperands(N, Ops); 5116 5117 CSEMap.InsertNode(N, IP); 5118 InsertNode(N); 5119 return SDValue(N, 0); 5120 } 5121 5122 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 5123 SDValue Ptr, MachinePointerInfo PtrInfo, 5124 unsigned Alignment, 5125 MachineMemOperand::Flags MMOFlags, 5126 const AAMDNodes &AAInfo, const MDNode *Ranges) { 5127 SDValue Undef = getUNDEF(Ptr.getValueType()); 5128 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 5129 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 5130 } 5131 5132 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 5133 SDValue Ptr, MachineMemOperand *MMO) { 5134 SDValue Undef = getUNDEF(Ptr.getValueType()); 5135 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 5136 VT, MMO); 5137 } 5138 5139 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 5140 EVT VT, SDValue Chain, SDValue Ptr, 5141 MachinePointerInfo PtrInfo, EVT MemVT, 5142 unsigned Alignment, 5143 MachineMemOperand::Flags MMOFlags, 5144 const AAMDNodes &AAInfo) { 5145 SDValue Undef = getUNDEF(Ptr.getValueType()); 5146 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 5147 MemVT, Alignment, MMOFlags, AAInfo); 5148 } 5149 5150 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 5151 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 5152 MachineMemOperand *MMO) { 5153 SDValue Undef = getUNDEF(Ptr.getValueType()); 5154 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 5155 MemVT, MMO); 5156 } 5157 5158 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 5159 SDValue Base, SDValue Offset, 5160 ISD::MemIndexedMode AM) { 5161 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 5162 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 5163 // Don't propagate the invariant flag. 5164 auto MMOFlags = 5165 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOInvariant; 5166 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 5167 LD->getChain(), Base, Offset, LD->getPointerInfo(), 5168 LD->getMemoryVT(), LD->getAlignment(), MMOFlags); 5169 } 5170 5171 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 5172 SDValue Ptr, MachinePointerInfo PtrInfo, 5173 unsigned Alignment, 5174 MachineMemOperand::Flags MMOFlags, 5175 const AAMDNodes &AAInfo) { 5176 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 5177 if (Alignment == 0) // Ensure that codegen never sees alignment 0 5178 Alignment = getEVTAlignment(Val.getValueType()); 5179 5180 MMOFlags |= MachineMemOperand::MOStore; 5181 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 5182 5183 if (PtrInfo.V.isNull()) 5184 PtrInfo = InferPointerInfo(*this, Ptr); 5185 5186 MachineFunction &MF = getMachineFunction(); 5187 MachineMemOperand *MMO = MF.getMachineMemOperand( 5188 PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo); 5189 return getStore(Chain, dl, Val, Ptr, MMO); 5190 } 5191 5192 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 5193 SDValue Ptr, MachineMemOperand *MMO) { 5194 assert(Chain.getValueType() == MVT::Other && 5195 "Invalid chain type"); 5196 EVT VT = Val.getValueType(); 5197 SDVTList VTs = getVTList(MVT::Other); 5198 SDValue Undef = getUNDEF(Ptr.getValueType()); 5199 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 5200 FoldingSetNodeID ID; 5201 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 5202 ID.AddInteger(VT.getRawBits()); 5203 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(), 5204 MMO->isNonTemporal(), MMO->isInvariant())); 5205 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5206 void *IP = nullptr; 5207 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5208 cast<StoreSDNode>(E)->refineAlignment(MMO); 5209 return SDValue(E, 0); 5210 } 5211 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 5212 ISD::UNINDEXED, false, VT, MMO); 5213 createOperands(N, Ops); 5214 5215 CSEMap.InsertNode(N, IP); 5216 InsertNode(N); 5217 return SDValue(N, 0); 5218 } 5219 5220 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 5221 SDValue Ptr, MachinePointerInfo PtrInfo, 5222 EVT SVT, unsigned Alignment, 5223 MachineMemOperand::Flags MMOFlags, 5224 const AAMDNodes &AAInfo) { 5225 assert(Chain.getValueType() == MVT::Other && 5226 "Invalid chain type"); 5227 if (Alignment == 0) // Ensure that codegen never sees alignment 0 5228 Alignment = getEVTAlignment(SVT); 5229 5230 MMOFlags |= MachineMemOperand::MOStore; 5231 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 5232 5233 if (PtrInfo.V.isNull()) 5234 PtrInfo = InferPointerInfo(*this, Ptr); 5235 5236 MachineFunction &MF = getMachineFunction(); 5237 MachineMemOperand *MMO = MF.getMachineMemOperand( 5238 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo); 5239 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 5240 } 5241 5242 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 5243 SDValue Ptr, EVT SVT, 5244 MachineMemOperand *MMO) { 5245 EVT VT = Val.getValueType(); 5246 5247 assert(Chain.getValueType() == MVT::Other && 5248 "Invalid chain type"); 5249 if (VT == SVT) 5250 return getStore(Chain, dl, Val, Ptr, MMO); 5251 5252 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 5253 "Should only be a truncating store, not extending!"); 5254 assert(VT.isInteger() == SVT.isInteger() && 5255 "Can't do FP-INT conversion!"); 5256 assert(VT.isVector() == SVT.isVector() && 5257 "Cannot use trunc store to convert to or from a vector!"); 5258 assert((!VT.isVector() || 5259 VT.getVectorNumElements() == SVT.getVectorNumElements()) && 5260 "Cannot use trunc store to change the number of vector elements!"); 5261 5262 SDVTList VTs = getVTList(MVT::Other); 5263 SDValue Undef = getUNDEF(Ptr.getValueType()); 5264 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 5265 FoldingSetNodeID ID; 5266 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 5267 ID.AddInteger(SVT.getRawBits()); 5268 ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(), 5269 MMO->isNonTemporal(), MMO->isInvariant())); 5270 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5271 void *IP = nullptr; 5272 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5273 cast<StoreSDNode>(E)->refineAlignment(MMO); 5274 return SDValue(E, 0); 5275 } 5276 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 5277 ISD::UNINDEXED, true, SVT, MMO); 5278 createOperands(N, Ops); 5279 5280 CSEMap.InsertNode(N, IP); 5281 InsertNode(N); 5282 return SDValue(N, 0); 5283 } 5284 5285 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 5286 SDValue Base, SDValue Offset, 5287 ISD::MemIndexedMode AM) { 5288 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 5289 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 5290 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 5291 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 5292 FoldingSetNodeID ID; 5293 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 5294 ID.AddInteger(ST->getMemoryVT().getRawBits()); 5295 ID.AddInteger(ST->getRawSubclassData()); 5296 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 5297 void *IP = nullptr; 5298 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 5299 return SDValue(E, 0); 5300 5301 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 5302 ST->isTruncatingStore(), ST->getMemoryVT(), 5303 ST->getMemOperand()); 5304 createOperands(N, Ops); 5305 5306 CSEMap.InsertNode(N, IP); 5307 InsertNode(N); 5308 return SDValue(N, 0); 5309 } 5310 5311 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 5312 SDValue Ptr, SDValue Mask, SDValue Src0, 5313 EVT MemVT, MachineMemOperand *MMO, 5314 ISD::LoadExtType ExtTy) { 5315 5316 SDVTList VTs = getVTList(VT, MVT::Other); 5317 SDValue Ops[] = { Chain, Ptr, Mask, Src0 }; 5318 FoldingSetNodeID ID; 5319 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 5320 ID.AddInteger(VT.getRawBits()); 5321 ID.AddInteger(encodeMemSDNodeFlags(ExtTy, ISD::UNINDEXED, 5322 MMO->isVolatile(), 5323 MMO->isNonTemporal(), 5324 MMO->isInvariant())); 5325 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5326 void *IP = nullptr; 5327 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5328 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 5329 return SDValue(E, 0); 5330 } 5331 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 5332 ExtTy, MemVT, MMO); 5333 createOperands(N, Ops); 5334 5335 CSEMap.InsertNode(N, IP); 5336 InsertNode(N); 5337 return SDValue(N, 0); 5338 } 5339 5340 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 5341 SDValue Val, SDValue Ptr, SDValue Mask, 5342 EVT MemVT, MachineMemOperand *MMO, 5343 bool isTrunc) { 5344 assert(Chain.getValueType() == MVT::Other && 5345 "Invalid chain type"); 5346 EVT VT = Val.getValueType(); 5347 SDVTList VTs = getVTList(MVT::Other); 5348 SDValue Ops[] = { Chain, Ptr, Mask, Val }; 5349 FoldingSetNodeID ID; 5350 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 5351 ID.AddInteger(VT.getRawBits()); 5352 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(), 5353 MMO->isNonTemporal(), MMO->isInvariant())); 5354 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5355 void *IP = nullptr; 5356 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5357 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 5358 return SDValue(E, 0); 5359 } 5360 auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 5361 isTrunc, MemVT, MMO); 5362 createOperands(N, Ops); 5363 5364 CSEMap.InsertNode(N, IP); 5365 InsertNode(N); 5366 return SDValue(N, 0); 5367 } 5368 5369 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl, 5370 ArrayRef<SDValue> Ops, 5371 MachineMemOperand *MMO) { 5372 assert(Ops.size() == 5 && "Incompatible number of operands"); 5373 5374 FoldingSetNodeID ID; 5375 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 5376 ID.AddInteger(VT.getRawBits()); 5377 ID.AddInteger(encodeMemSDNodeFlags(ISD::NON_EXTLOAD, ISD::UNINDEXED, 5378 MMO->isVolatile(), 5379 MMO->isNonTemporal(), 5380 MMO->isInvariant())); 5381 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5382 void *IP = nullptr; 5383 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5384 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 5385 return SDValue(E, 0); 5386 } 5387 5388 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 5389 VTs, VT, MMO); 5390 createOperands(N, Ops); 5391 5392 assert(N->getValue().getValueType() == N->getValueType(0) && 5393 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 5394 assert(N->getMask().getValueType().getVectorNumElements() == 5395 N->getValueType(0).getVectorNumElements() && 5396 "Vector width mismatch between mask and data"); 5397 assert(N->getIndex().getValueType().getVectorNumElements() == 5398 N->getValueType(0).getVectorNumElements() && 5399 "Vector width mismatch between index and data"); 5400 5401 CSEMap.InsertNode(N, IP); 5402 InsertNode(N); 5403 return SDValue(N, 0); 5404 } 5405 5406 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl, 5407 ArrayRef<SDValue> Ops, 5408 MachineMemOperand *MMO) { 5409 assert(Ops.size() == 5 && "Incompatible number of operands"); 5410 5411 FoldingSetNodeID ID; 5412 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 5413 ID.AddInteger(VT.getRawBits()); 5414 ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(), 5415 MMO->isNonTemporal(), 5416 MMO->isInvariant())); 5417 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 5418 void *IP = nullptr; 5419 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 5420 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 5421 return SDValue(E, 0); 5422 } 5423 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 5424 VTs, VT, MMO); 5425 createOperands(N, Ops); 5426 5427 assert(N->getMask().getValueType().getVectorNumElements() == 5428 N->getValue().getValueType().getVectorNumElements() && 5429 "Vector width mismatch between mask and data"); 5430 assert(N->getIndex().getValueType().getVectorNumElements() == 5431 N->getValue().getValueType().getVectorNumElements() && 5432 "Vector width mismatch between index and data"); 5433 5434 CSEMap.InsertNode(N, IP); 5435 InsertNode(N); 5436 return SDValue(N, 0); 5437 } 5438 5439 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 5440 SDValue Ptr, SDValue SV, unsigned Align) { 5441 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 5442 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 5443 } 5444 5445 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5446 ArrayRef<SDUse> Ops) { 5447 switch (Ops.size()) { 5448 case 0: return getNode(Opcode, DL, VT); 5449 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 5450 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 5451 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 5452 default: break; 5453 } 5454 5455 // Copy from an SDUse array into an SDValue array for use with 5456 // the regular getNode logic. 5457 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 5458 return getNode(Opcode, DL, VT, NewOps); 5459 } 5460 5461 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5462 ArrayRef<SDValue> Ops, const SDNodeFlags *Flags) { 5463 unsigned NumOps = Ops.size(); 5464 switch (NumOps) { 5465 case 0: return getNode(Opcode, DL, VT); 5466 case 1: return getNode(Opcode, DL, VT, Ops[0]); 5467 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 5468 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 5469 default: break; 5470 } 5471 5472 switch (Opcode) { 5473 default: break; 5474 case ISD::CONCAT_VECTORS: { 5475 // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF. 5476 if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this)) 5477 return V; 5478 break; 5479 } 5480 case ISD::SELECT_CC: { 5481 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 5482 assert(Ops[0].getValueType() == Ops[1].getValueType() && 5483 "LHS and RHS of condition must have same type!"); 5484 assert(Ops[2].getValueType() == Ops[3].getValueType() && 5485 "True and False arms of SelectCC must have same type!"); 5486 assert(Ops[2].getValueType() == VT && 5487 "select_cc node must be of same type as true and false value!"); 5488 break; 5489 } 5490 case ISD::BR_CC: { 5491 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 5492 assert(Ops[2].getValueType() == Ops[3].getValueType() && 5493 "LHS/RHS of comparison should match types!"); 5494 break; 5495 } 5496 } 5497 5498 // Memoize nodes. 5499 SDNode *N; 5500 SDVTList VTs = getVTList(VT); 5501 5502 if (VT != MVT::Glue) { 5503 FoldingSetNodeID ID; 5504 AddNodeIDNode(ID, Opcode, VTs, Ops); 5505 void *IP = nullptr; 5506 5507 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5508 return SDValue(E, 0); 5509 5510 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5511 createOperands(N, Ops); 5512 5513 CSEMap.InsertNode(N, IP); 5514 } else { 5515 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5516 createOperands(N, Ops); 5517 } 5518 5519 InsertNode(N); 5520 return SDValue(N, 0); 5521 } 5522 5523 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 5524 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 5525 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 5526 } 5527 5528 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 5529 ArrayRef<SDValue> Ops) { 5530 if (VTList.NumVTs == 1) 5531 return getNode(Opcode, DL, VTList.VTs[0], Ops); 5532 5533 #if 0 5534 switch (Opcode) { 5535 // FIXME: figure out how to safely handle things like 5536 // int foo(int x) { return 1 << (x & 255); } 5537 // int bar() { return foo(256); } 5538 case ISD::SRA_PARTS: 5539 case ISD::SRL_PARTS: 5540 case ISD::SHL_PARTS: 5541 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 5542 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 5543 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 5544 else if (N3.getOpcode() == ISD::AND) 5545 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 5546 // If the and is only masking out bits that cannot effect the shift, 5547 // eliminate the and. 5548 unsigned NumBits = VT.getScalarType().getSizeInBits()*2; 5549 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 5550 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 5551 } 5552 break; 5553 } 5554 #endif 5555 5556 // Memoize the node unless it returns a flag. 5557 SDNode *N; 5558 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 5559 FoldingSetNodeID ID; 5560 AddNodeIDNode(ID, Opcode, VTList, Ops); 5561 void *IP = nullptr; 5562 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5563 return SDValue(E, 0); 5564 5565 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 5566 createOperands(N, Ops); 5567 CSEMap.InsertNode(N, IP); 5568 } else { 5569 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 5570 createOperands(N, Ops); 5571 } 5572 InsertNode(N); 5573 return SDValue(N, 0); 5574 } 5575 5576 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 5577 SDVTList VTList) { 5578 return getNode(Opcode, DL, VTList, None); 5579 } 5580 5581 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 5582 SDValue N1) { 5583 SDValue Ops[] = { N1 }; 5584 return getNode(Opcode, DL, VTList, Ops); 5585 } 5586 5587 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 5588 SDValue N1, SDValue N2) { 5589 SDValue Ops[] = { N1, N2 }; 5590 return getNode(Opcode, DL, VTList, Ops); 5591 } 5592 5593 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 5594 SDValue N1, SDValue N2, SDValue N3) { 5595 SDValue Ops[] = { N1, N2, N3 }; 5596 return getNode(Opcode, DL, VTList, Ops); 5597 } 5598 5599 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 5600 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 5601 SDValue Ops[] = { N1, N2, N3, N4 }; 5602 return getNode(Opcode, DL, VTList, Ops); 5603 } 5604 5605 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 5606 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 5607 SDValue N5) { 5608 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 5609 return getNode(Opcode, DL, VTList, Ops); 5610 } 5611 5612 SDVTList SelectionDAG::getVTList(EVT VT) { 5613 return makeVTList(SDNode::getValueTypeList(VT), 1); 5614 } 5615 5616 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 5617 FoldingSetNodeID ID; 5618 ID.AddInteger(2U); 5619 ID.AddInteger(VT1.getRawBits()); 5620 ID.AddInteger(VT2.getRawBits()); 5621 5622 void *IP = nullptr; 5623 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5624 if (!Result) { 5625 EVT *Array = Allocator.Allocate<EVT>(2); 5626 Array[0] = VT1; 5627 Array[1] = VT2; 5628 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 5629 VTListMap.InsertNode(Result, IP); 5630 } 5631 return Result->getSDVTList(); 5632 } 5633 5634 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 5635 FoldingSetNodeID ID; 5636 ID.AddInteger(3U); 5637 ID.AddInteger(VT1.getRawBits()); 5638 ID.AddInteger(VT2.getRawBits()); 5639 ID.AddInteger(VT3.getRawBits()); 5640 5641 void *IP = nullptr; 5642 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5643 if (!Result) { 5644 EVT *Array = Allocator.Allocate<EVT>(3); 5645 Array[0] = VT1; 5646 Array[1] = VT2; 5647 Array[2] = VT3; 5648 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 5649 VTListMap.InsertNode(Result, IP); 5650 } 5651 return Result->getSDVTList(); 5652 } 5653 5654 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 5655 FoldingSetNodeID ID; 5656 ID.AddInteger(4U); 5657 ID.AddInteger(VT1.getRawBits()); 5658 ID.AddInteger(VT2.getRawBits()); 5659 ID.AddInteger(VT3.getRawBits()); 5660 ID.AddInteger(VT4.getRawBits()); 5661 5662 void *IP = nullptr; 5663 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5664 if (!Result) { 5665 EVT *Array = Allocator.Allocate<EVT>(4); 5666 Array[0] = VT1; 5667 Array[1] = VT2; 5668 Array[2] = VT3; 5669 Array[3] = VT4; 5670 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 5671 VTListMap.InsertNode(Result, IP); 5672 } 5673 return Result->getSDVTList(); 5674 } 5675 5676 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 5677 unsigned NumVTs = VTs.size(); 5678 FoldingSetNodeID ID; 5679 ID.AddInteger(NumVTs); 5680 for (unsigned index = 0; index < NumVTs; index++) { 5681 ID.AddInteger(VTs[index].getRawBits()); 5682 } 5683 5684 void *IP = nullptr; 5685 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 5686 if (!Result) { 5687 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 5688 std::copy(VTs.begin(), VTs.end(), Array); 5689 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 5690 VTListMap.InsertNode(Result, IP); 5691 } 5692 return Result->getSDVTList(); 5693 } 5694 5695 5696 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 5697 /// specified operands. If the resultant node already exists in the DAG, 5698 /// this does not modify the specified node, instead it returns the node that 5699 /// already exists. If the resultant node does not exist in the DAG, the 5700 /// input node is returned. As a degenerate case, if you specify the same 5701 /// input operands as the node already has, the input node is returned. 5702 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 5703 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 5704 5705 // Check to see if there is no change. 5706 if (Op == N->getOperand(0)) return N; 5707 5708 // See if the modified node already exists. 5709 void *InsertPos = nullptr; 5710 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 5711 return Existing; 5712 5713 // Nope it doesn't. Remove the node from its current place in the maps. 5714 if (InsertPos) 5715 if (!RemoveNodeFromCSEMaps(N)) 5716 InsertPos = nullptr; 5717 5718 // Now we update the operands. 5719 N->OperandList[0].set(Op); 5720 5721 // If this gets put into a CSE map, add it. 5722 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5723 return N; 5724 } 5725 5726 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 5727 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 5728 5729 // Check to see if there is no change. 5730 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 5731 return N; // No operands changed, just return the input node. 5732 5733 // See if the modified node already exists. 5734 void *InsertPos = nullptr; 5735 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 5736 return Existing; 5737 5738 // Nope it doesn't. Remove the node from its current place in the maps. 5739 if (InsertPos) 5740 if (!RemoveNodeFromCSEMaps(N)) 5741 InsertPos = nullptr; 5742 5743 // Now we update the operands. 5744 if (N->OperandList[0] != Op1) 5745 N->OperandList[0].set(Op1); 5746 if (N->OperandList[1] != Op2) 5747 N->OperandList[1].set(Op2); 5748 5749 // If this gets put into a CSE map, add it. 5750 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5751 return N; 5752 } 5753 5754 SDNode *SelectionDAG:: 5755 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 5756 SDValue Ops[] = { Op1, Op2, Op3 }; 5757 return UpdateNodeOperands(N, Ops); 5758 } 5759 5760 SDNode *SelectionDAG:: 5761 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 5762 SDValue Op3, SDValue Op4) { 5763 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 5764 return UpdateNodeOperands(N, Ops); 5765 } 5766 5767 SDNode *SelectionDAG:: 5768 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 5769 SDValue Op3, SDValue Op4, SDValue Op5) { 5770 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 5771 return UpdateNodeOperands(N, Ops); 5772 } 5773 5774 SDNode *SelectionDAG:: 5775 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 5776 unsigned NumOps = Ops.size(); 5777 assert(N->getNumOperands() == NumOps && 5778 "Update with wrong number of operands"); 5779 5780 // If no operands changed just return the input node. 5781 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 5782 return N; 5783 5784 // See if the modified node already exists. 5785 void *InsertPos = nullptr; 5786 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 5787 return Existing; 5788 5789 // Nope it doesn't. Remove the node from its current place in the maps. 5790 if (InsertPos) 5791 if (!RemoveNodeFromCSEMaps(N)) 5792 InsertPos = nullptr; 5793 5794 // Now we update the operands. 5795 for (unsigned i = 0; i != NumOps; ++i) 5796 if (N->OperandList[i] != Ops[i]) 5797 N->OperandList[i].set(Ops[i]); 5798 5799 // If this gets put into a CSE map, add it. 5800 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 5801 return N; 5802 } 5803 5804 /// DropOperands - Release the operands and set this node to have 5805 /// zero operands. 5806 void SDNode::DropOperands() { 5807 // Unlike the code in MorphNodeTo that does this, we don't need to 5808 // watch for dead nodes here. 5809 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 5810 SDUse &Use = *I++; 5811 Use.set(SDValue()); 5812 } 5813 } 5814 5815 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 5816 /// machine opcode. 5817 /// 5818 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5819 EVT VT) { 5820 SDVTList VTs = getVTList(VT); 5821 return SelectNodeTo(N, MachineOpc, VTs, None); 5822 } 5823 5824 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5825 EVT VT, SDValue Op1) { 5826 SDVTList VTs = getVTList(VT); 5827 SDValue Ops[] = { Op1 }; 5828 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5829 } 5830 5831 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5832 EVT VT, SDValue Op1, 5833 SDValue Op2) { 5834 SDVTList VTs = getVTList(VT); 5835 SDValue Ops[] = { Op1, Op2 }; 5836 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5837 } 5838 5839 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5840 EVT VT, SDValue Op1, 5841 SDValue Op2, SDValue Op3) { 5842 SDVTList VTs = getVTList(VT); 5843 SDValue Ops[] = { Op1, Op2, Op3 }; 5844 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5845 } 5846 5847 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5848 EVT VT, ArrayRef<SDValue> Ops) { 5849 SDVTList VTs = getVTList(VT); 5850 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5851 } 5852 5853 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5854 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 5855 SDVTList VTs = getVTList(VT1, VT2); 5856 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5857 } 5858 5859 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5860 EVT VT1, EVT VT2) { 5861 SDVTList VTs = getVTList(VT1, VT2); 5862 return SelectNodeTo(N, MachineOpc, VTs, None); 5863 } 5864 5865 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5866 EVT VT1, EVT VT2, EVT VT3, 5867 ArrayRef<SDValue> Ops) { 5868 SDVTList VTs = getVTList(VT1, VT2, VT3); 5869 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5870 } 5871 5872 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5873 EVT VT1, EVT VT2, EVT VT3, EVT VT4, 5874 ArrayRef<SDValue> Ops) { 5875 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4); 5876 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5877 } 5878 5879 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5880 EVT VT1, EVT VT2, 5881 SDValue Op1) { 5882 SDVTList VTs = getVTList(VT1, VT2); 5883 SDValue Ops[] = { Op1 }; 5884 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5885 } 5886 5887 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5888 EVT VT1, EVT VT2, 5889 SDValue Op1, SDValue Op2) { 5890 SDVTList VTs = getVTList(VT1, VT2); 5891 SDValue Ops[] = { Op1, Op2 }; 5892 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5893 } 5894 5895 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5896 EVT VT1, EVT VT2, 5897 SDValue Op1, SDValue Op2, 5898 SDValue Op3) { 5899 SDVTList VTs = getVTList(VT1, VT2); 5900 SDValue Ops[] = { Op1, Op2, Op3 }; 5901 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5902 } 5903 5904 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5905 EVT VT1, EVT VT2, EVT VT3, 5906 SDValue Op1, SDValue Op2, 5907 SDValue Op3) { 5908 SDVTList VTs = getVTList(VT1, VT2, VT3); 5909 SDValue Ops[] = { Op1, Op2, Op3 }; 5910 return SelectNodeTo(N, MachineOpc, VTs, Ops); 5911 } 5912 5913 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 5914 SDVTList VTs,ArrayRef<SDValue> Ops) { 5915 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 5916 // Reset the NodeID to -1. 5917 New->setNodeId(-1); 5918 if (New != N) { 5919 ReplaceAllUsesWith(N, New); 5920 RemoveDeadNode(N); 5921 } 5922 return New; 5923 } 5924 5925 /// UpdadeSDLocOnMergedSDNode - If the opt level is -O0 then it throws away 5926 /// the line number information on the merged node since it is not possible to 5927 /// preserve the information that operation is associated with multiple lines. 5928 /// This will make the debugger working better at -O0, were there is a higher 5929 /// probability having other instructions associated with that line. 5930 /// 5931 /// For IROrder, we keep the smaller of the two 5932 SDNode *SelectionDAG::UpdadeSDLocOnMergedSDNode(SDNode *N, const SDLoc &OLoc) { 5933 DebugLoc NLoc = N->getDebugLoc(); 5934 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 5935 N->setDebugLoc(DebugLoc()); 5936 } 5937 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 5938 N->setIROrder(Order); 5939 return N; 5940 } 5941 5942 /// MorphNodeTo - This *mutates* the specified node to have the specified 5943 /// return type, opcode, and operands. 5944 /// 5945 /// Note that MorphNodeTo returns the resultant node. If there is already a 5946 /// node of the specified opcode and operands, it returns that node instead of 5947 /// the current one. Note that the SDLoc need not be the same. 5948 /// 5949 /// Using MorphNodeTo is faster than creating a new node and swapping it in 5950 /// with ReplaceAllUsesWith both because it often avoids allocating a new 5951 /// node, and because it doesn't require CSE recalculation for any of 5952 /// the node's users. 5953 /// 5954 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 5955 /// As a consequence it isn't appropriate to use from within the DAG combiner or 5956 /// the legalizer which maintain worklists that would need to be updated when 5957 /// deleting things. 5958 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 5959 SDVTList VTs, ArrayRef<SDValue> Ops) { 5960 // If an identical node already exists, use it. 5961 void *IP = nullptr; 5962 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 5963 FoldingSetNodeID ID; 5964 AddNodeIDNode(ID, Opc, VTs, Ops); 5965 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 5966 return UpdadeSDLocOnMergedSDNode(ON, SDLoc(N)); 5967 } 5968 5969 if (!RemoveNodeFromCSEMaps(N)) 5970 IP = nullptr; 5971 5972 // Start the morphing. 5973 N->NodeType = Opc; 5974 N->ValueList = VTs.VTs; 5975 N->NumValues = VTs.NumVTs; 5976 5977 // Clear the operands list, updating used nodes to remove this from their 5978 // use list. Keep track of any operands that become dead as a result. 5979 SmallPtrSet<SDNode*, 16> DeadNodeSet; 5980 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 5981 SDUse &Use = *I++; 5982 SDNode *Used = Use.getNode(); 5983 Use.set(SDValue()); 5984 if (Used->use_empty()) 5985 DeadNodeSet.insert(Used); 5986 } 5987 5988 // For MachineNode, initialize the memory references information. 5989 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 5990 MN->setMemRefs(nullptr, nullptr); 5991 5992 // Swap for an appropriately sized array from the recycler. 5993 removeOperands(N); 5994 createOperands(N, Ops); 5995 5996 // Delete any nodes that are still dead after adding the uses for the 5997 // new operands. 5998 if (!DeadNodeSet.empty()) { 5999 SmallVector<SDNode *, 16> DeadNodes; 6000 for (SDNode *N : DeadNodeSet) 6001 if (N->use_empty()) 6002 DeadNodes.push_back(N); 6003 RemoveDeadNodes(DeadNodes); 6004 } 6005 6006 if (IP) 6007 CSEMap.InsertNode(N, IP); // Memoize the new node. 6008 return N; 6009 } 6010 6011 6012 /// getMachineNode - These are used for target selectors to create a new node 6013 /// with specified return type(s), MachineInstr opcode, and operands. 6014 /// 6015 /// Note that getMachineNode returns the resultant node. If there is already a 6016 /// node of the specified opcode and operands, it returns that node instead of 6017 /// the current one. 6018 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6019 EVT VT) { 6020 SDVTList VTs = getVTList(VT); 6021 return getMachineNode(Opcode, dl, VTs, None); 6022 } 6023 6024 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6025 EVT VT, SDValue Op1) { 6026 SDVTList VTs = getVTList(VT); 6027 SDValue Ops[] = { Op1 }; 6028 return getMachineNode(Opcode, dl, VTs, Ops); 6029 } 6030 6031 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6032 EVT VT, SDValue Op1, SDValue Op2) { 6033 SDVTList VTs = getVTList(VT); 6034 SDValue Ops[] = { Op1, Op2 }; 6035 return getMachineNode(Opcode, dl, VTs, Ops); 6036 } 6037 6038 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6039 EVT VT, SDValue Op1, SDValue Op2, 6040 SDValue Op3) { 6041 SDVTList VTs = getVTList(VT); 6042 SDValue Ops[] = { Op1, Op2, Op3 }; 6043 return getMachineNode(Opcode, dl, VTs, Ops); 6044 } 6045 6046 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6047 EVT VT, ArrayRef<SDValue> Ops) { 6048 SDVTList VTs = getVTList(VT); 6049 return getMachineNode(Opcode, dl, VTs, Ops); 6050 } 6051 6052 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6053 EVT VT1, EVT VT2) { 6054 SDVTList VTs = getVTList(VT1, VT2); 6055 return getMachineNode(Opcode, dl, VTs, None); 6056 } 6057 6058 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6059 EVT VT1, EVT VT2, SDValue Op1) { 6060 SDVTList VTs = getVTList(VT1, VT2); 6061 SDValue Ops[] = { Op1 }; 6062 return getMachineNode(Opcode, dl, VTs, Ops); 6063 } 6064 6065 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6066 EVT VT1, EVT VT2, SDValue Op1, 6067 SDValue Op2) { 6068 SDVTList VTs = getVTList(VT1, VT2); 6069 SDValue Ops[] = { Op1, Op2 }; 6070 return getMachineNode(Opcode, dl, VTs, Ops); 6071 } 6072 6073 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6074 EVT VT1, EVT VT2, SDValue Op1, 6075 SDValue Op2, SDValue Op3) { 6076 SDVTList VTs = getVTList(VT1, VT2); 6077 SDValue Ops[] = { Op1, Op2, Op3 }; 6078 return getMachineNode(Opcode, dl, VTs, Ops); 6079 } 6080 6081 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6082 EVT VT1, EVT VT2, 6083 ArrayRef<SDValue> Ops) { 6084 SDVTList VTs = getVTList(VT1, VT2); 6085 return getMachineNode(Opcode, dl, VTs, Ops); 6086 } 6087 6088 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6089 EVT VT1, EVT VT2, EVT VT3, 6090 SDValue Op1, SDValue Op2) { 6091 SDVTList VTs = getVTList(VT1, VT2, VT3); 6092 SDValue Ops[] = { Op1, Op2 }; 6093 return getMachineNode(Opcode, dl, VTs, Ops); 6094 } 6095 6096 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6097 EVT VT1, EVT VT2, EVT VT3, 6098 SDValue Op1, SDValue Op2, 6099 SDValue Op3) { 6100 SDVTList VTs = getVTList(VT1, VT2, VT3); 6101 SDValue Ops[] = { Op1, Op2, Op3 }; 6102 return getMachineNode(Opcode, dl, VTs, Ops); 6103 } 6104 6105 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6106 EVT VT1, EVT VT2, EVT VT3, 6107 ArrayRef<SDValue> Ops) { 6108 SDVTList VTs = getVTList(VT1, VT2, VT3); 6109 return getMachineNode(Opcode, dl, VTs, Ops); 6110 } 6111 6112 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6113 EVT VT1, EVT VT2, EVT VT3, EVT VT4, 6114 ArrayRef<SDValue> Ops) { 6115 SDVTList VTs = getVTList(VT1, VT2, VT3, VT4); 6116 return getMachineNode(Opcode, dl, VTs, Ops); 6117 } 6118 6119 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 6120 ArrayRef<EVT> ResultTys, 6121 ArrayRef<SDValue> Ops) { 6122 SDVTList VTs = getVTList(ResultTys); 6123 return getMachineNode(Opcode, dl, VTs, Ops); 6124 } 6125 6126 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 6127 SDVTList VTs, 6128 ArrayRef<SDValue> Ops) { 6129 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 6130 MachineSDNode *N; 6131 void *IP = nullptr; 6132 6133 if (DoCSE) { 6134 FoldingSetNodeID ID; 6135 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 6136 IP = nullptr; 6137 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6138 return cast<MachineSDNode>(UpdadeSDLocOnMergedSDNode(E, DL)); 6139 } 6140 } 6141 6142 // Allocate a new MachineSDNode. 6143 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6144 createOperands(N, Ops); 6145 6146 if (DoCSE) 6147 CSEMap.InsertNode(N, IP); 6148 6149 InsertNode(N); 6150 return N; 6151 } 6152 6153 /// getTargetExtractSubreg - A convenience function for creating 6154 /// TargetOpcode::EXTRACT_SUBREG nodes. 6155 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 6156 SDValue Operand) { 6157 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 6158 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 6159 VT, Operand, SRIdxVal); 6160 return SDValue(Subreg, 0); 6161 } 6162 6163 /// getTargetInsertSubreg - A convenience function for creating 6164 /// TargetOpcode::INSERT_SUBREG nodes. 6165 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 6166 SDValue Operand, SDValue Subreg) { 6167 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 6168 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 6169 VT, Operand, Subreg, SRIdxVal); 6170 return SDValue(Result, 0); 6171 } 6172 6173 /// getNodeIfExists - Get the specified node if it's already available, or 6174 /// else return NULL. 6175 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 6176 ArrayRef<SDValue> Ops, 6177 const SDNodeFlags *Flags) { 6178 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 6179 FoldingSetNodeID ID; 6180 AddNodeIDNode(ID, Opcode, VTList, Ops); 6181 void *IP = nullptr; 6182 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 6183 if (Flags) 6184 E->intersectFlagsWith(Flags); 6185 return E; 6186 } 6187 } 6188 return nullptr; 6189 } 6190 6191 /// getDbgValue - Creates a SDDbgValue node. 6192 /// 6193 /// SDNode 6194 SDDbgValue *SelectionDAG::getDbgValue(MDNode *Var, MDNode *Expr, SDNode *N, 6195 unsigned R, bool IsIndirect, uint64_t Off, 6196 const DebugLoc &DL, unsigned O) { 6197 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 6198 "Expected inlined-at fields to agree"); 6199 return new (DbgInfo->getAlloc()) 6200 SDDbgValue(Var, Expr, N, R, IsIndirect, Off, DL, O); 6201 } 6202 6203 /// Constant 6204 SDDbgValue *SelectionDAG::getConstantDbgValue(MDNode *Var, MDNode *Expr, 6205 const Value *C, uint64_t Off, 6206 const DebugLoc &DL, unsigned O) { 6207 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 6208 "Expected inlined-at fields to agree"); 6209 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, Off, DL, O); 6210 } 6211 6212 /// FrameIndex 6213 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(MDNode *Var, MDNode *Expr, 6214 unsigned FI, uint64_t Off, 6215 const DebugLoc &DL, 6216 unsigned O) { 6217 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 6218 "Expected inlined-at fields to agree"); 6219 return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, FI, Off, DL, O); 6220 } 6221 6222 namespace { 6223 6224 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 6225 /// pointed to by a use iterator is deleted, increment the use iterator 6226 /// so that it doesn't dangle. 6227 /// 6228 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 6229 SDNode::use_iterator &UI; 6230 SDNode::use_iterator &UE; 6231 6232 void NodeDeleted(SDNode *N, SDNode *E) override { 6233 // Increment the iterator as needed. 6234 while (UI != UE && N == *UI) 6235 ++UI; 6236 } 6237 6238 public: 6239 RAUWUpdateListener(SelectionDAG &d, 6240 SDNode::use_iterator &ui, 6241 SDNode::use_iterator &ue) 6242 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 6243 }; 6244 6245 } 6246 6247 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 6248 /// This can cause recursive merging of nodes in the DAG. 6249 /// 6250 /// This version assumes From has a single result value. 6251 /// 6252 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 6253 SDNode *From = FromN.getNode(); 6254 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 6255 "Cannot replace with this method!"); 6256 assert(From != To.getNode() && "Cannot replace uses of with self"); 6257 6258 // Iterate over all the existing uses of From. New uses will be added 6259 // to the beginning of the use list, which we avoid visiting. 6260 // This specifically avoids visiting uses of From that arise while the 6261 // replacement is happening, because any such uses would be the result 6262 // of CSE: If an existing node looks like From after one of its operands 6263 // is replaced by To, we don't want to replace of all its users with To 6264 // too. See PR3018 for more info. 6265 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 6266 RAUWUpdateListener Listener(*this, UI, UE); 6267 while (UI != UE) { 6268 SDNode *User = *UI; 6269 6270 // This node is about to morph, remove its old self from the CSE maps. 6271 RemoveNodeFromCSEMaps(User); 6272 6273 // A user can appear in a use list multiple times, and when this 6274 // happens the uses are usually next to each other in the list. 6275 // To help reduce the number of CSE recomputations, process all 6276 // the uses of this user that we can find this way. 6277 do { 6278 SDUse &Use = UI.getUse(); 6279 ++UI; 6280 Use.set(To); 6281 } while (UI != UE && *UI == User); 6282 6283 // Now that we have modified User, add it back to the CSE maps. If it 6284 // already exists there, recursively merge the results together. 6285 AddModifiedNodeToCSEMaps(User); 6286 } 6287 6288 // Preserve Debug Values 6289 TransferDbgValues(FromN, To); 6290 6291 // If we just RAUW'd the root, take note. 6292 if (FromN == getRoot()) 6293 setRoot(To); 6294 } 6295 6296 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 6297 /// This can cause recursive merging of nodes in the DAG. 6298 /// 6299 /// This version assumes that for each value of From, there is a 6300 /// corresponding value in To in the same position with the same type. 6301 /// 6302 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 6303 #ifndef NDEBUG 6304 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 6305 assert((!From->hasAnyUseOfValue(i) || 6306 From->getValueType(i) == To->getValueType(i)) && 6307 "Cannot use this version of ReplaceAllUsesWith!"); 6308 #endif 6309 6310 // Handle the trivial case. 6311 if (From == To) 6312 return; 6313 6314 // Preserve Debug Info. Only do this if there's a use. 6315 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 6316 if (From->hasAnyUseOfValue(i)) { 6317 assert((i < To->getNumValues()) && "Invalid To location"); 6318 TransferDbgValues(SDValue(From, i), SDValue(To, i)); 6319 } 6320 6321 // Iterate over just the existing users of From. See the comments in 6322 // the ReplaceAllUsesWith above. 6323 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 6324 RAUWUpdateListener Listener(*this, UI, UE); 6325 while (UI != UE) { 6326 SDNode *User = *UI; 6327 6328 // This node is about to morph, remove its old self from the CSE maps. 6329 RemoveNodeFromCSEMaps(User); 6330 6331 // A user can appear in a use list multiple times, and when this 6332 // happens the uses are usually next to each other in the list. 6333 // To help reduce the number of CSE recomputations, process all 6334 // the uses of this user that we can find this way. 6335 do { 6336 SDUse &Use = UI.getUse(); 6337 ++UI; 6338 Use.setNode(To); 6339 } while (UI != UE && *UI == User); 6340 6341 // Now that we have modified User, add it back to the CSE maps. If it 6342 // already exists there, recursively merge the results together. 6343 AddModifiedNodeToCSEMaps(User); 6344 } 6345 6346 // If we just RAUW'd the root, take note. 6347 if (From == getRoot().getNode()) 6348 setRoot(SDValue(To, getRoot().getResNo())); 6349 } 6350 6351 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 6352 /// This can cause recursive merging of nodes in the DAG. 6353 /// 6354 /// This version can replace From with any result values. To must match the 6355 /// number and types of values returned by From. 6356 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 6357 if (From->getNumValues() == 1) // Handle the simple case efficiently. 6358 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 6359 6360 // Preserve Debug Info. 6361 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 6362 TransferDbgValues(SDValue(From, i), *To); 6363 6364 // Iterate over just the existing users of From. See the comments in 6365 // the ReplaceAllUsesWith above. 6366 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 6367 RAUWUpdateListener Listener(*this, UI, UE); 6368 while (UI != UE) { 6369 SDNode *User = *UI; 6370 6371 // This node is about to morph, remove its old self from the CSE maps. 6372 RemoveNodeFromCSEMaps(User); 6373 6374 // A user can appear in a use list multiple times, and when this 6375 // happens the uses are usually next to each other in the list. 6376 // To help reduce the number of CSE recomputations, process all 6377 // the uses of this user that we can find this way. 6378 do { 6379 SDUse &Use = UI.getUse(); 6380 const SDValue &ToOp = To[Use.getResNo()]; 6381 ++UI; 6382 Use.set(ToOp); 6383 } while (UI != UE && *UI == User); 6384 6385 // Now that we have modified User, add it back to the CSE maps. If it 6386 // already exists there, recursively merge the results together. 6387 AddModifiedNodeToCSEMaps(User); 6388 } 6389 6390 // If we just RAUW'd the root, take note. 6391 if (From == getRoot().getNode()) 6392 setRoot(SDValue(To[getRoot().getResNo()])); 6393 } 6394 6395 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 6396 /// uses of other values produced by From.getNode() alone. The Deleted 6397 /// vector is handled the same way as for ReplaceAllUsesWith. 6398 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 6399 // Handle the really simple, really trivial case efficiently. 6400 if (From == To) return; 6401 6402 // Handle the simple, trivial, case efficiently. 6403 if (From.getNode()->getNumValues() == 1) { 6404 ReplaceAllUsesWith(From, To); 6405 return; 6406 } 6407 6408 // Preserve Debug Info. 6409 TransferDbgValues(From, To); 6410 6411 // Iterate over just the existing users of From. See the comments in 6412 // the ReplaceAllUsesWith above. 6413 SDNode::use_iterator UI = From.getNode()->use_begin(), 6414 UE = From.getNode()->use_end(); 6415 RAUWUpdateListener Listener(*this, UI, UE); 6416 while (UI != UE) { 6417 SDNode *User = *UI; 6418 bool UserRemovedFromCSEMaps = false; 6419 6420 // A user can appear in a use list multiple times, and when this 6421 // happens the uses are usually next to each other in the list. 6422 // To help reduce the number of CSE recomputations, process all 6423 // the uses of this user that we can find this way. 6424 do { 6425 SDUse &Use = UI.getUse(); 6426 6427 // Skip uses of different values from the same node. 6428 if (Use.getResNo() != From.getResNo()) { 6429 ++UI; 6430 continue; 6431 } 6432 6433 // If this node hasn't been modified yet, it's still in the CSE maps, 6434 // so remove its old self from the CSE maps. 6435 if (!UserRemovedFromCSEMaps) { 6436 RemoveNodeFromCSEMaps(User); 6437 UserRemovedFromCSEMaps = true; 6438 } 6439 6440 ++UI; 6441 Use.set(To); 6442 } while (UI != UE && *UI == User); 6443 6444 // We are iterating over all uses of the From node, so if a use 6445 // doesn't use the specific value, no changes are made. 6446 if (!UserRemovedFromCSEMaps) 6447 continue; 6448 6449 // Now that we have modified User, add it back to the CSE maps. If it 6450 // already exists there, recursively merge the results together. 6451 AddModifiedNodeToCSEMaps(User); 6452 } 6453 6454 // If we just RAUW'd the root, take note. 6455 if (From == getRoot()) 6456 setRoot(To); 6457 } 6458 6459 namespace { 6460 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 6461 /// to record information about a use. 6462 struct UseMemo { 6463 SDNode *User; 6464 unsigned Index; 6465 SDUse *Use; 6466 }; 6467 6468 /// operator< - Sort Memos by User. 6469 bool operator<(const UseMemo &L, const UseMemo &R) { 6470 return (intptr_t)L.User < (intptr_t)R.User; 6471 } 6472 } 6473 6474 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 6475 /// uses of other values produced by From.getNode() alone. The same value 6476 /// may appear in both the From and To list. The Deleted vector is 6477 /// handled the same way as for ReplaceAllUsesWith. 6478 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 6479 const SDValue *To, 6480 unsigned Num){ 6481 // Handle the simple, trivial case efficiently. 6482 if (Num == 1) 6483 return ReplaceAllUsesOfValueWith(*From, *To); 6484 6485 TransferDbgValues(*From, *To); 6486 6487 // Read up all the uses and make records of them. This helps 6488 // processing new uses that are introduced during the 6489 // replacement process. 6490 SmallVector<UseMemo, 4> Uses; 6491 for (unsigned i = 0; i != Num; ++i) { 6492 unsigned FromResNo = From[i].getResNo(); 6493 SDNode *FromNode = From[i].getNode(); 6494 for (SDNode::use_iterator UI = FromNode->use_begin(), 6495 E = FromNode->use_end(); UI != E; ++UI) { 6496 SDUse &Use = UI.getUse(); 6497 if (Use.getResNo() == FromResNo) { 6498 UseMemo Memo = { *UI, i, &Use }; 6499 Uses.push_back(Memo); 6500 } 6501 } 6502 } 6503 6504 // Sort the uses, so that all the uses from a given User are together. 6505 std::sort(Uses.begin(), Uses.end()); 6506 6507 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 6508 UseIndex != UseIndexEnd; ) { 6509 // We know that this user uses some value of From. If it is the right 6510 // value, update it. 6511 SDNode *User = Uses[UseIndex].User; 6512 6513 // This node is about to morph, remove its old self from the CSE maps. 6514 RemoveNodeFromCSEMaps(User); 6515 6516 // The Uses array is sorted, so all the uses for a given User 6517 // are next to each other in the list. 6518 // To help reduce the number of CSE recomputations, process all 6519 // the uses of this user that we can find this way. 6520 do { 6521 unsigned i = Uses[UseIndex].Index; 6522 SDUse &Use = *Uses[UseIndex].Use; 6523 ++UseIndex; 6524 6525 Use.set(To[i]); 6526 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 6527 6528 // Now that we have modified User, add it back to the CSE maps. If it 6529 // already exists there, recursively merge the results together. 6530 AddModifiedNodeToCSEMaps(User); 6531 } 6532 } 6533 6534 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 6535 /// based on their topological order. It returns the maximum id and a vector 6536 /// of the SDNodes* in assigned order by reference. 6537 unsigned SelectionDAG::AssignTopologicalOrder() { 6538 6539 unsigned DAGSize = 0; 6540 6541 // SortedPos tracks the progress of the algorithm. Nodes before it are 6542 // sorted, nodes after it are unsorted. When the algorithm completes 6543 // it is at the end of the list. 6544 allnodes_iterator SortedPos = allnodes_begin(); 6545 6546 // Visit all the nodes. Move nodes with no operands to the front of 6547 // the list immediately. Annotate nodes that do have operands with their 6548 // operand count. Before we do this, the Node Id fields of the nodes 6549 // may contain arbitrary values. After, the Node Id fields for nodes 6550 // before SortedPos will contain the topological sort index, and the 6551 // Node Id fields for nodes At SortedPos and after will contain the 6552 // count of outstanding operands. 6553 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 6554 SDNode *N = &*I++; 6555 checkForCycles(N, this); 6556 unsigned Degree = N->getNumOperands(); 6557 if (Degree == 0) { 6558 // A node with no uses, add it to the result array immediately. 6559 N->setNodeId(DAGSize++); 6560 allnodes_iterator Q(N); 6561 if (Q != SortedPos) 6562 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 6563 assert(SortedPos != AllNodes.end() && "Overran node list"); 6564 ++SortedPos; 6565 } else { 6566 // Temporarily use the Node Id as scratch space for the degree count. 6567 N->setNodeId(Degree); 6568 } 6569 } 6570 6571 // Visit all the nodes. As we iterate, move nodes into sorted order, 6572 // such that by the time the end is reached all nodes will be sorted. 6573 for (SDNode &Node : allnodes()) { 6574 SDNode *N = &Node; 6575 checkForCycles(N, this); 6576 // N is in sorted position, so all its uses have one less operand 6577 // that needs to be sorted. 6578 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 6579 UI != UE; ++UI) { 6580 SDNode *P = *UI; 6581 unsigned Degree = P->getNodeId(); 6582 assert(Degree != 0 && "Invalid node degree"); 6583 --Degree; 6584 if (Degree == 0) { 6585 // All of P's operands are sorted, so P may sorted now. 6586 P->setNodeId(DAGSize++); 6587 if (P->getIterator() != SortedPos) 6588 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 6589 assert(SortedPos != AllNodes.end() && "Overran node list"); 6590 ++SortedPos; 6591 } else { 6592 // Update P's outstanding operand count. 6593 P->setNodeId(Degree); 6594 } 6595 } 6596 if (Node.getIterator() == SortedPos) { 6597 #ifndef NDEBUG 6598 allnodes_iterator I(N); 6599 SDNode *S = &*++I; 6600 dbgs() << "Overran sorted position:\n"; 6601 S->dumprFull(this); dbgs() << "\n"; 6602 dbgs() << "Checking if this is due to cycles\n"; 6603 checkForCycles(this, true); 6604 #endif 6605 llvm_unreachable(nullptr); 6606 } 6607 } 6608 6609 assert(SortedPos == AllNodes.end() && 6610 "Topological sort incomplete!"); 6611 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 6612 "First node in topological sort is not the entry token!"); 6613 assert(AllNodes.front().getNodeId() == 0 && 6614 "First node in topological sort has non-zero id!"); 6615 assert(AllNodes.front().getNumOperands() == 0 && 6616 "First node in topological sort has operands!"); 6617 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 6618 "Last node in topologic sort has unexpected id!"); 6619 assert(AllNodes.back().use_empty() && 6620 "Last node in topologic sort has users!"); 6621 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 6622 return DAGSize; 6623 } 6624 6625 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 6626 /// value is produced by SD. 6627 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) { 6628 if (SD) { 6629 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 6630 SD->setHasDebugValue(true); 6631 } 6632 DbgInfo->add(DB, SD, isParameter); 6633 } 6634 6635 /// TransferDbgValues - Transfer SDDbgValues. Called in replace nodes. 6636 void SelectionDAG::TransferDbgValues(SDValue From, SDValue To) { 6637 if (From == To || !From.getNode()->getHasDebugValue()) 6638 return; 6639 SDNode *FromNode = From.getNode(); 6640 SDNode *ToNode = To.getNode(); 6641 ArrayRef<SDDbgValue *> DVs = GetDbgValues(FromNode); 6642 for (ArrayRef<SDDbgValue *>::iterator I = DVs.begin(), E = DVs.end(); 6643 I != E; ++I) { 6644 SDDbgValue *Dbg = *I; 6645 // Only add Dbgvalues attached to same ResNo. 6646 if (Dbg->getKind() == SDDbgValue::SDNODE && 6647 Dbg->getResNo() == From.getResNo()) { 6648 SDDbgValue *Clone = 6649 getDbgValue(Dbg->getVariable(), Dbg->getExpression(), ToNode, 6650 To.getResNo(), Dbg->isIndirect(), Dbg->getOffset(), 6651 Dbg->getDebugLoc(), Dbg->getOrder()); 6652 AddDbgValue(Clone, ToNode, false); 6653 } 6654 } 6655 } 6656 6657 //===----------------------------------------------------------------------===// 6658 // SDNode Class 6659 //===----------------------------------------------------------------------===// 6660 6661 bool llvm::isNullConstant(SDValue V) { 6662 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 6663 return Const != nullptr && Const->isNullValue(); 6664 } 6665 6666 bool llvm::isNullFPConstant(SDValue V) { 6667 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 6668 return Const != nullptr && Const->isZero() && !Const->isNegative(); 6669 } 6670 6671 bool llvm::isAllOnesConstant(SDValue V) { 6672 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 6673 return Const != nullptr && Const->isAllOnesValue(); 6674 } 6675 6676 bool llvm::isOneConstant(SDValue V) { 6677 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 6678 return Const != nullptr && Const->isOne(); 6679 } 6680 6681 bool llvm::isBitwiseNot(SDValue V) { 6682 return V.getOpcode() == ISD::XOR && isAllOnesConstant(V.getOperand(1)); 6683 } 6684 6685 HandleSDNode::~HandleSDNode() { 6686 DropOperands(); 6687 } 6688 6689 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 6690 const DebugLoc &DL, 6691 const GlobalValue *GA, EVT VT, 6692 int64_t o, unsigned char TF) 6693 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 6694 TheGlobal = GA; 6695 } 6696 6697 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 6698 EVT VT, unsigned SrcAS, 6699 unsigned DestAS) 6700 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 6701 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 6702 6703 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 6704 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 6705 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 6706 SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(), 6707 MMO->isNonTemporal(), MMO->isInvariant()); 6708 assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!"); 6709 assert(isNonTemporal() == MMO->isNonTemporal() && 6710 "Non-temporal encoding error!"); 6711 // We check here that the size of the memory operand fits within the size of 6712 // the MMO. This is because the MMO might indicate only a possible address 6713 // range instead of specifying the affected memory addresses precisely. 6714 assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!"); 6715 } 6716 6717 /// Profile - Gather unique data for the node. 6718 /// 6719 void SDNode::Profile(FoldingSetNodeID &ID) const { 6720 AddNodeIDNode(ID, this); 6721 } 6722 6723 namespace { 6724 struct EVTArray { 6725 std::vector<EVT> VTs; 6726 6727 EVTArray() { 6728 VTs.reserve(MVT::LAST_VALUETYPE); 6729 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 6730 VTs.push_back(MVT((MVT::SimpleValueType)i)); 6731 } 6732 }; 6733 } 6734 6735 static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs; 6736 static ManagedStatic<EVTArray> SimpleVTArray; 6737 static ManagedStatic<sys::SmartMutex<true> > VTMutex; 6738 6739 /// getValueTypeList - Return a pointer to the specified value type. 6740 /// 6741 const EVT *SDNode::getValueTypeList(EVT VT) { 6742 if (VT.isExtended()) { 6743 sys::SmartScopedLock<true> Lock(*VTMutex); 6744 return &(*EVTs->insert(VT).first); 6745 } else { 6746 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 6747 "Value type out of range!"); 6748 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 6749 } 6750 } 6751 6752 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 6753 /// indicated value. This method ignores uses of other values defined by this 6754 /// operation. 6755 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 6756 assert(Value < getNumValues() && "Bad value!"); 6757 6758 // TODO: Only iterate over uses of a given value of the node 6759 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 6760 if (UI.getUse().getResNo() == Value) { 6761 if (NUses == 0) 6762 return false; 6763 --NUses; 6764 } 6765 } 6766 6767 // Found exactly the right number of uses? 6768 return NUses == 0; 6769 } 6770 6771 6772 /// hasAnyUseOfValue - Return true if there are any use of the indicated 6773 /// value. This method ignores uses of other values defined by this operation. 6774 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 6775 assert(Value < getNumValues() && "Bad value!"); 6776 6777 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 6778 if (UI.getUse().getResNo() == Value) 6779 return true; 6780 6781 return false; 6782 } 6783 6784 6785 /// isOnlyUserOf - Return true if this node is the only use of N. 6786 /// 6787 bool SDNode::isOnlyUserOf(const SDNode *N) const { 6788 bool Seen = false; 6789 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 6790 SDNode *User = *I; 6791 if (User == this) 6792 Seen = true; 6793 else 6794 return false; 6795 } 6796 6797 return Seen; 6798 } 6799 6800 /// isOperand - Return true if this node is an operand of N. 6801 /// 6802 bool SDValue::isOperandOf(const SDNode *N) const { 6803 for (const SDValue &Op : N->op_values()) 6804 if (*this == Op) 6805 return true; 6806 return false; 6807 } 6808 6809 bool SDNode::isOperandOf(const SDNode *N) const { 6810 for (const SDValue &Op : N->op_values()) 6811 if (this == Op.getNode()) 6812 return true; 6813 return false; 6814 } 6815 6816 /// reachesChainWithoutSideEffects - Return true if this operand (which must 6817 /// be a chain) reaches the specified operand without crossing any 6818 /// side-effecting instructions on any chain path. In practice, this looks 6819 /// through token factors and non-volatile loads. In order to remain efficient, 6820 /// this only looks a couple of nodes in, it does not do an exhaustive search. 6821 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 6822 unsigned Depth) const { 6823 if (*this == Dest) return true; 6824 6825 // Don't search too deeply, we just want to be able to see through 6826 // TokenFactor's etc. 6827 if (Depth == 0) return false; 6828 6829 // If this is a token factor, all inputs to the TF happen in parallel. If any 6830 // of the operands of the TF does not reach dest, then we cannot do the xform. 6831 if (getOpcode() == ISD::TokenFactor) { 6832 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) 6833 if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1)) 6834 return false; 6835 return true; 6836 } 6837 6838 // Loads don't have side effects, look through them. 6839 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 6840 if (!Ld->isVolatile()) 6841 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 6842 } 6843 return false; 6844 } 6845 6846 bool SDNode::hasPredecessor(const SDNode *N) const { 6847 SmallPtrSet<const SDNode *, 32> Visited; 6848 SmallVector<const SDNode *, 16> Worklist; 6849 Worklist.push_back(this); 6850 return hasPredecessorHelper(N, Visited, Worklist); 6851 } 6852 6853 uint64_t SDNode::getConstantOperandVal(unsigned Num) const { 6854 assert(Num < NumOperands && "Invalid child # of SDNode!"); 6855 return cast<ConstantSDNode>(OperandList[Num])->getZExtValue(); 6856 } 6857 6858 const SDNodeFlags *SDNode::getFlags() const { 6859 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this)) 6860 return &FlagsNode->Flags; 6861 return nullptr; 6862 } 6863 6864 void SDNode::intersectFlagsWith(const SDNodeFlags *Flags) { 6865 if (auto *FlagsNode = dyn_cast<BinaryWithFlagsSDNode>(this)) 6866 FlagsNode->Flags.intersectWith(Flags); 6867 } 6868 6869 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 6870 assert(N->getNumValues() == 1 && 6871 "Can't unroll a vector with multiple results!"); 6872 6873 EVT VT = N->getValueType(0); 6874 unsigned NE = VT.getVectorNumElements(); 6875 EVT EltVT = VT.getVectorElementType(); 6876 SDLoc dl(N); 6877 6878 SmallVector<SDValue, 8> Scalars; 6879 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 6880 6881 // If ResNE is 0, fully unroll the vector op. 6882 if (ResNE == 0) 6883 ResNE = NE; 6884 else if (NE > ResNE) 6885 NE = ResNE; 6886 6887 unsigned i; 6888 for (i= 0; i != NE; ++i) { 6889 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 6890 SDValue Operand = N->getOperand(j); 6891 EVT OperandVT = Operand.getValueType(); 6892 if (OperandVT.isVector()) { 6893 // A vector operand; extract a single element. 6894 EVT OperandEltVT = OperandVT.getVectorElementType(); 6895 Operands[j] = 6896 getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand, 6897 getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout()))); 6898 } else { 6899 // A scalar operand; just use it as is. 6900 Operands[j] = Operand; 6901 } 6902 } 6903 6904 switch (N->getOpcode()) { 6905 default: { 6906 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 6907 N->getFlags())); 6908 break; 6909 } 6910 case ISD::VSELECT: 6911 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 6912 break; 6913 case ISD::SHL: 6914 case ISD::SRA: 6915 case ISD::SRL: 6916 case ISD::ROTL: 6917 case ISD::ROTR: 6918 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 6919 getShiftAmountOperand(Operands[0].getValueType(), 6920 Operands[1]))); 6921 break; 6922 case ISD::SIGN_EXTEND_INREG: 6923 case ISD::FP_ROUND_INREG: { 6924 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 6925 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 6926 Operands[0], 6927 getValueType(ExtVT))); 6928 } 6929 } 6930 } 6931 6932 for (; i < ResNE; ++i) 6933 Scalars.push_back(getUNDEF(EltVT)); 6934 6935 return getNode(ISD::BUILD_VECTOR, dl, 6936 EVT::getVectorVT(*getContext(), EltVT, ResNE), Scalars); 6937 } 6938 6939 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 6940 LoadSDNode *Base, 6941 unsigned Bytes, 6942 int Dist) const { 6943 if (LD->isVolatile() || Base->isVolatile()) 6944 return false; 6945 if (LD->isIndexed() || Base->isIndexed()) 6946 return false; 6947 if (LD->getChain() != Base->getChain()) 6948 return false; 6949 EVT VT = LD->getValueType(0); 6950 if (VT.getSizeInBits() / 8 != Bytes) 6951 return false; 6952 6953 SDValue Loc = LD->getOperand(1); 6954 SDValue BaseLoc = Base->getOperand(1); 6955 if (Loc.getOpcode() == ISD::FrameIndex) { 6956 if (BaseLoc.getOpcode() != ISD::FrameIndex) 6957 return false; 6958 const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo(); 6959 int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); 6960 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); 6961 int FS = MFI->getObjectSize(FI); 6962 int BFS = MFI->getObjectSize(BFI); 6963 if (FS != BFS || FS != (int)Bytes) return false; 6964 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes); 6965 } 6966 6967 // Handle X + C. 6968 if (isBaseWithConstantOffset(Loc)) { 6969 int64_t LocOffset = cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); 6970 if (Loc.getOperand(0) == BaseLoc) { 6971 // If the base location is a simple address with no offset itself, then 6972 // the second load's first add operand should be the base address. 6973 if (LocOffset == Dist * (int)Bytes) 6974 return true; 6975 } else if (isBaseWithConstantOffset(BaseLoc)) { 6976 // The base location itself has an offset, so subtract that value from the 6977 // second load's offset before comparing to distance * size. 6978 int64_t BOffset = 6979 cast<ConstantSDNode>(BaseLoc.getOperand(1))->getSExtValue(); 6980 if (Loc.getOperand(0) == BaseLoc.getOperand(0)) { 6981 if ((LocOffset - BOffset) == Dist * (int)Bytes) 6982 return true; 6983 } 6984 } 6985 } 6986 const GlobalValue *GV1 = nullptr; 6987 const GlobalValue *GV2 = nullptr; 6988 int64_t Offset1 = 0; 6989 int64_t Offset2 = 0; 6990 bool isGA1 = TLI->isGAPlusOffset(Loc.getNode(), GV1, Offset1); 6991 bool isGA2 = TLI->isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); 6992 if (isGA1 && isGA2 && GV1 == GV2) 6993 return Offset1 == (Offset2 + Dist*Bytes); 6994 return false; 6995 } 6996 6997 6998 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if 6999 /// it cannot be inferred. 7000 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const { 7001 // If this is a GlobalAddress + cst, return the alignment. 7002 const GlobalValue *GV; 7003 int64_t GVOffset = 0; 7004 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 7005 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 7006 APInt KnownZero(PtrWidth, 0), KnownOne(PtrWidth, 0); 7007 llvm::computeKnownBits(const_cast<GlobalValue *>(GV), KnownZero, KnownOne, 7008 getDataLayout()); 7009 unsigned AlignBits = KnownZero.countTrailingOnes(); 7010 unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0; 7011 if (Align) 7012 return MinAlign(Align, GVOffset); 7013 } 7014 7015 // If this is a direct reference to a stack slot, use information about the 7016 // stack slot's alignment. 7017 int FrameIdx = 1 << 31; 7018 int64_t FrameOffset = 0; 7019 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 7020 FrameIdx = FI->getIndex(); 7021 } else if (isBaseWithConstantOffset(Ptr) && 7022 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 7023 // Handle FI+Cst 7024 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7025 FrameOffset = Ptr.getConstantOperandVal(1); 7026 } 7027 7028 if (FrameIdx != (1 << 31)) { 7029 const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo(); 7030 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx), 7031 FrameOffset); 7032 return FIInfoAlign; 7033 } 7034 7035 return 0; 7036 } 7037 7038 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 7039 /// which is split (or expanded) into two not necessarily identical pieces. 7040 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 7041 // Currently all types are split in half. 7042 EVT LoVT, HiVT; 7043 if (!VT.isVector()) { 7044 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 7045 } else { 7046 unsigned NumElements = VT.getVectorNumElements(); 7047 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 7048 LoVT = HiVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 7049 NumElements/2); 7050 } 7051 return std::make_pair(LoVT, HiVT); 7052 } 7053 7054 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 7055 /// low/high part. 7056 std::pair<SDValue, SDValue> 7057 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 7058 const EVT &HiVT) { 7059 assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <= 7060 N.getValueType().getVectorNumElements() && 7061 "More vector elements requested than available!"); 7062 SDValue Lo, Hi; 7063 Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, 7064 getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout()))); 7065 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 7066 getConstant(LoVT.getVectorNumElements(), DL, 7067 TLI->getVectorIdxTy(getDataLayout()))); 7068 return std::make_pair(Lo, Hi); 7069 } 7070 7071 void SelectionDAG::ExtractVectorElements(SDValue Op, 7072 SmallVectorImpl<SDValue> &Args, 7073 unsigned Start, unsigned Count) { 7074 EVT VT = Op.getValueType(); 7075 if (Count == 0) 7076 Count = VT.getVectorNumElements(); 7077 7078 EVT EltVT = VT.getVectorElementType(); 7079 EVT IdxTy = TLI->getVectorIdxTy(getDataLayout()); 7080 SDLoc SL(Op); 7081 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 7082 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 7083 Op, getConstant(i, SL, IdxTy))); 7084 } 7085 } 7086 7087 // getAddressSpace - Return the address space this GlobalAddress belongs to. 7088 unsigned GlobalAddressSDNode::getAddressSpace() const { 7089 return getGlobal()->getType()->getAddressSpace(); 7090 } 7091 7092 7093 Type *ConstantPoolSDNode::getType() const { 7094 if (isMachineConstantPoolEntry()) 7095 return Val.MachineCPVal->getType(); 7096 return Val.ConstVal->getType(); 7097 } 7098 7099 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, 7100 APInt &SplatUndef, 7101 unsigned &SplatBitSize, 7102 bool &HasAnyUndefs, 7103 unsigned MinSplatBits, 7104 bool isBigEndian) const { 7105 EVT VT = getValueType(0); 7106 assert(VT.isVector() && "Expected a vector type"); 7107 unsigned sz = VT.getSizeInBits(); 7108 if (MinSplatBits > sz) 7109 return false; 7110 7111 SplatValue = APInt(sz, 0); 7112 SplatUndef = APInt(sz, 0); 7113 7114 // Get the bits. Bits with undefined values (when the corresponding element 7115 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 7116 // in SplatValue. If any of the values are not constant, give up and return 7117 // false. 7118 unsigned int nOps = getNumOperands(); 7119 assert(nOps > 0 && "isConstantSplat has 0-size build vector"); 7120 unsigned EltBitSize = VT.getVectorElementType().getSizeInBits(); 7121 7122 for (unsigned j = 0; j < nOps; ++j) { 7123 unsigned i = isBigEndian ? nOps-1-j : j; 7124 SDValue OpVal = getOperand(i); 7125 unsigned BitPos = j * EltBitSize; 7126 7127 if (OpVal.isUndef()) 7128 SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize); 7129 else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) 7130 SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize). 7131 zextOrTrunc(sz) << BitPos; 7132 else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 7133 SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos; 7134 else 7135 return false; 7136 } 7137 7138 // The build_vector is all constants or undefs. Find the smallest element 7139 // size that splats the vector. 7140 7141 HasAnyUndefs = (SplatUndef != 0); 7142 while (sz > 8) { 7143 7144 unsigned HalfSize = sz / 2; 7145 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 7146 APInt LowValue = SplatValue.trunc(HalfSize); 7147 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 7148 APInt LowUndef = SplatUndef.trunc(HalfSize); 7149 7150 // If the two halves do not match (ignoring undef bits), stop here. 7151 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 7152 MinSplatBits > HalfSize) 7153 break; 7154 7155 SplatValue = HighValue | LowValue; 7156 SplatUndef = HighUndef & LowUndef; 7157 7158 sz = HalfSize; 7159 } 7160 7161 SplatBitSize = sz; 7162 return true; 7163 } 7164 7165 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 7166 if (UndefElements) { 7167 UndefElements->clear(); 7168 UndefElements->resize(getNumOperands()); 7169 } 7170 SDValue Splatted; 7171 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) { 7172 SDValue Op = getOperand(i); 7173 if (Op.isUndef()) { 7174 if (UndefElements) 7175 (*UndefElements)[i] = true; 7176 } else if (!Splatted) { 7177 Splatted = Op; 7178 } else if (Splatted != Op) { 7179 return SDValue(); 7180 } 7181 } 7182 7183 if (!Splatted) { 7184 assert(getOperand(0).isUndef() && 7185 "Can only have a splat without a constant for all undefs."); 7186 return getOperand(0); 7187 } 7188 7189 return Splatted; 7190 } 7191 7192 ConstantSDNode * 7193 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 7194 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 7195 } 7196 7197 ConstantFPSDNode * 7198 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 7199 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 7200 } 7201 7202 int32_t 7203 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 7204 uint32_t BitWidth) const { 7205 if (ConstantFPSDNode *CN = 7206 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 7207 bool IsExact; 7208 APSInt IntVal(BitWidth); 7209 const APFloat &APF = CN->getValueAPF(); 7210 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 7211 APFloat::opOK || 7212 !IsExact) 7213 return -1; 7214 7215 return IntVal.exactLogBase2(); 7216 } 7217 return -1; 7218 } 7219 7220 bool BuildVectorSDNode::isConstant() const { 7221 for (const SDValue &Op : op_values()) { 7222 unsigned Opc = Op.getOpcode(); 7223 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 7224 return false; 7225 } 7226 return true; 7227 } 7228 7229 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 7230 // Find the first non-undef value in the shuffle mask. 7231 unsigned i, e; 7232 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 7233 /* search */; 7234 7235 assert(i != e && "VECTOR_SHUFFLE node with all undef indices!"); 7236 7237 // Make sure all remaining elements are either undef or the same as the first 7238 // non-undef value. 7239 for (int Idx = Mask[i]; i != e; ++i) 7240 if (Mask[i] >= 0 && Mask[i] != Idx) 7241 return false; 7242 return true; 7243 } 7244 7245 // \brief Returns the SDNode if it is a constant integer BuildVector 7246 // or constant integer. 7247 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) { 7248 if (isa<ConstantSDNode>(N)) 7249 return N.getNode(); 7250 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 7251 return N.getNode(); 7252 // Treat a GlobalAddress supporting constant offset folding as a 7253 // constant integer. 7254 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 7255 if (GA->getOpcode() == ISD::GlobalAddress && 7256 TLI->isOffsetFoldingLegal(GA)) 7257 return GA; 7258 return nullptr; 7259 } 7260 7261 #ifndef NDEBUG 7262 static void checkForCyclesHelper(const SDNode *N, 7263 SmallPtrSetImpl<const SDNode*> &Visited, 7264 SmallPtrSetImpl<const SDNode*> &Checked, 7265 const llvm::SelectionDAG *DAG) { 7266 // If this node has already been checked, don't check it again. 7267 if (Checked.count(N)) 7268 return; 7269 7270 // If a node has already been visited on this depth-first walk, reject it as 7271 // a cycle. 7272 if (!Visited.insert(N).second) { 7273 errs() << "Detected cycle in SelectionDAG\n"; 7274 dbgs() << "Offending node:\n"; 7275 N->dumprFull(DAG); dbgs() << "\n"; 7276 abort(); 7277 } 7278 7279 for (const SDValue &Op : N->op_values()) 7280 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 7281 7282 Checked.insert(N); 7283 Visited.erase(N); 7284 } 7285 #endif 7286 7287 void llvm::checkForCycles(const llvm::SDNode *N, 7288 const llvm::SelectionDAG *DAG, 7289 bool force) { 7290 #ifndef NDEBUG 7291 bool check = force; 7292 #ifdef EXPENSIVE_CHECKS 7293 check = true; 7294 #endif // EXPENSIVE_CHECKS 7295 if (check) { 7296 assert(N && "Checking nonexistent SDNode"); 7297 SmallPtrSet<const SDNode*, 32> visited; 7298 SmallPtrSet<const SDNode*, 32> checked; 7299 checkForCyclesHelper(N, visited, checked, DAG); 7300 } 7301 #endif // !NDEBUG 7302 } 7303 7304 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 7305 checkForCycles(DAG->getRoot().getNode(), DAG, force); 7306 } 7307