1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This implements the SelectionDAG class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/SelectionDAG.h" 14 #include "SDNodeDbgValue.h" 15 #include "llvm/ADT/APFloat.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/APSInt.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/DenseSet.h" 21 #include "llvm/ADT/FoldingSet.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/Analysis/VectorUtils.h" 30 #include "llvm/CodeGen/Analysis.h" 31 #include "llvm/CodeGen/FunctionLoweringInfo.h" 32 #include "llvm/CodeGen/ISDOpcodes.h" 33 #include "llvm/CodeGen/MachineBasicBlock.h" 34 #include "llvm/CodeGen/MachineConstantPool.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineMemOperand.h" 38 #include "llvm/CodeGen/MachineValueType.h" 39 #include "llvm/CodeGen/RuntimeLibcalls.h" 40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 41 #include "llvm/CodeGen/SelectionDAGNodes.h" 42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 43 #include "llvm/CodeGen/TargetFrameLowering.h" 44 #include "llvm/CodeGen/TargetLowering.h" 45 #include "llvm/CodeGen/TargetRegisterInfo.h" 46 #include "llvm/CodeGen/TargetSubtargetInfo.h" 47 #include "llvm/CodeGen/ValueTypes.h" 48 #include "llvm/IR/Constant.h" 49 #include "llvm/IR/ConstantRange.h" 50 #include "llvm/IR/Constants.h" 51 #include "llvm/IR/DataLayout.h" 52 #include "llvm/IR/DebugInfoMetadata.h" 53 #include "llvm/IR/DebugLoc.h" 54 #include "llvm/IR/DerivedTypes.h" 55 #include "llvm/IR/Function.h" 56 #include "llvm/IR/GlobalValue.h" 57 #include "llvm/IR/Metadata.h" 58 #include "llvm/IR/Type.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CodeGen.h" 61 #include "llvm/Support/Compiler.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/KnownBits.h" 65 #include "llvm/Support/MathExtras.h" 66 #include "llvm/Support/Mutex.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Target/TargetMachine.h" 69 #include "llvm/Target/TargetOptions.h" 70 #include "llvm/TargetParser/Triple.h" 71 #include "llvm/Transforms/Utils/SizeOpts.h" 72 #include <algorithm> 73 #include <cassert> 74 #include <cstdint> 75 #include <cstdlib> 76 #include <limits> 77 #include <set> 78 #include <string> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 /// makeVTList - Return an instance of the SDVTList struct initialized with the 85 /// specified members. 86 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 87 SDVTList Res = {VTs, NumVTs}; 88 return Res; 89 } 90 91 // Default null implementations of the callbacks. 92 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 93 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 94 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 95 96 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 97 void SelectionDAG::DAGNodeInsertedListener::anchor() {} 98 99 #define DEBUG_TYPE "selectiondag" 100 101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 102 cl::Hidden, cl::init(true), 103 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 104 105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 106 cl::desc("Number limit for gluing ld/st of memcpy."), 107 cl::Hidden, cl::init(0)); 108 109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 110 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 111 } 112 113 //===----------------------------------------------------------------------===// 114 // ConstantFPSDNode Class 115 //===----------------------------------------------------------------------===// 116 117 /// isExactlyValue - We don't rely on operator== working on double values, as 118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 119 /// As such, this method can be used to do an exact bit-for-bit comparison of 120 /// two floating point values. 121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 122 return getValueAPF().bitwiseIsEqual(V); 123 } 124 125 bool ConstantFPSDNode::isValueValidForType(EVT VT, 126 const APFloat& Val) { 127 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 128 129 // convert modifies in place, so make a copy. 130 APFloat Val2 = APFloat(Val); 131 bool losesInfo; 132 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 133 APFloat::rmNearestTiesToEven, 134 &losesInfo); 135 return !losesInfo; 136 } 137 138 //===----------------------------------------------------------------------===// 139 // ISD Namespace 140 //===----------------------------------------------------------------------===// 141 142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 143 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 144 unsigned EltSize = 145 N->getValueType(0).getVectorElementType().getSizeInBits(); 146 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 147 SplatVal = Op0->getAPIntValue().trunc(EltSize); 148 return true; 149 } 150 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 151 SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize); 152 return true; 153 } 154 } 155 156 auto *BV = dyn_cast<BuildVectorSDNode>(N); 157 if (!BV) 158 return false; 159 160 APInt SplatUndef; 161 unsigned SplatBitSize; 162 bool HasUndefs; 163 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 164 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 165 EltSize) && 166 EltSize == SplatBitSize; 167 } 168 169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 170 // specializations of the more general isConstantSplatVector()? 171 172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 173 // Look through a bit convert. 174 while (N->getOpcode() == ISD::BITCAST) 175 N = N->getOperand(0).getNode(); 176 177 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 178 APInt SplatVal; 179 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 180 } 181 182 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 183 184 unsigned i = 0, e = N->getNumOperands(); 185 186 // Skip over all of the undef values. 187 while (i != e && N->getOperand(i).isUndef()) 188 ++i; 189 190 // Do not accept an all-undef vector. 191 if (i == e) return false; 192 193 // Do not accept build_vectors that aren't all constants or which have non-~0 194 // elements. We have to be a bit careful here, as the type of the constant 195 // may not be the same as the type of the vector elements due to type 196 // legalization (the elements are promoted to a legal type for the target and 197 // a vector of a type may be legal when the base element type is not). 198 // We only want to check enough bits to cover the vector elements, because 199 // we care if the resultant vector is all ones, not whether the individual 200 // constants are. 201 SDValue NotZero = N->getOperand(i); 202 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 203 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 204 if (CN->getAPIntValue().countr_one() < EltSize) 205 return false; 206 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 207 if (CFPN->getValueAPF().bitcastToAPInt().countr_one() < EltSize) 208 return false; 209 } else 210 return false; 211 212 // Okay, we have at least one ~0 value, check to see if the rest match or are 213 // undefs. Even with the above element type twiddling, this should be OK, as 214 // the same type legalization should have applied to all the elements. 215 for (++i; i != e; ++i) 216 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 217 return false; 218 return true; 219 } 220 221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 222 // Look through a bit convert. 223 while (N->getOpcode() == ISD::BITCAST) 224 N = N->getOperand(0).getNode(); 225 226 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 227 APInt SplatVal; 228 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 229 } 230 231 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 232 233 bool IsAllUndef = true; 234 for (const SDValue &Op : N->op_values()) { 235 if (Op.isUndef()) 236 continue; 237 IsAllUndef = false; 238 // Do not accept build_vectors that aren't all constants or which have non-0 239 // elements. We have to be a bit careful here, as the type of the constant 240 // may not be the same as the type of the vector elements due to type 241 // legalization (the elements are promoted to a legal type for the target 242 // and a vector of a type may be legal when the base element type is not). 243 // We only want to check enough bits to cover the vector elements, because 244 // we care if the resultant vector is all zeros, not whether the individual 245 // constants are. 246 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 247 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 248 if (CN->getAPIntValue().countr_zero() < EltSize) 249 return false; 250 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 251 if (CFPN->getValueAPF().bitcastToAPInt().countr_zero() < EltSize) 252 return false; 253 } else 254 return false; 255 } 256 257 // Do not accept an all-undef vector. 258 if (IsAllUndef) 259 return false; 260 return true; 261 } 262 263 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 264 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 265 } 266 267 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 268 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 269 } 270 271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 272 if (N->getOpcode() != ISD::BUILD_VECTOR) 273 return false; 274 275 for (const SDValue &Op : N->op_values()) { 276 if (Op.isUndef()) 277 continue; 278 if (!isa<ConstantSDNode>(Op)) 279 return false; 280 } 281 return true; 282 } 283 284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 285 if (N->getOpcode() != ISD::BUILD_VECTOR) 286 return false; 287 288 for (const SDValue &Op : N->op_values()) { 289 if (Op.isUndef()) 290 continue; 291 if (!isa<ConstantFPSDNode>(Op)) 292 return false; 293 } 294 return true; 295 } 296 297 bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize, 298 bool Signed) { 299 assert(N->getValueType(0).isVector() && "Expected a vector!"); 300 301 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 302 if (EltSize <= NewEltSize) 303 return false; 304 305 if (N->getOpcode() == ISD::ZERO_EXTEND) { 306 return (N->getOperand(0).getValueType().getScalarSizeInBits() <= 307 NewEltSize) && 308 !Signed; 309 } 310 if (N->getOpcode() == ISD::SIGN_EXTEND) { 311 return (N->getOperand(0).getValueType().getScalarSizeInBits() <= 312 NewEltSize) && 313 Signed; 314 } 315 if (N->getOpcode() != ISD::BUILD_VECTOR) 316 return false; 317 318 for (const SDValue &Op : N->op_values()) { 319 if (Op.isUndef()) 320 continue; 321 if (!isa<ConstantSDNode>(Op)) 322 return false; 323 324 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().trunc(EltSize); 325 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C) 326 return false; 327 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C) 328 return false; 329 } 330 331 return true; 332 } 333 334 bool ISD::allOperandsUndef(const SDNode *N) { 335 // Return false if the node has no operands. 336 // This is "logically inconsistent" with the definition of "all" but 337 // is probably the desired behavior. 338 if (N->getNumOperands() == 0) 339 return false; 340 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 341 } 342 343 bool ISD::isFreezeUndef(const SDNode *N) { 344 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef(); 345 } 346 347 bool ISD::matchUnaryPredicate(SDValue Op, 348 std::function<bool(ConstantSDNode *)> Match, 349 bool AllowUndefs) { 350 // FIXME: Add support for scalar UNDEF cases? 351 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 352 return Match(Cst); 353 354 // FIXME: Add support for vector UNDEF cases? 355 if (ISD::BUILD_VECTOR != Op.getOpcode() && 356 ISD::SPLAT_VECTOR != Op.getOpcode()) 357 return false; 358 359 EVT SVT = Op.getValueType().getScalarType(); 360 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 361 if (AllowUndefs && Op.getOperand(i).isUndef()) { 362 if (!Match(nullptr)) 363 return false; 364 continue; 365 } 366 367 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 368 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 369 return false; 370 } 371 return true; 372 } 373 374 bool ISD::matchBinaryPredicate( 375 SDValue LHS, SDValue RHS, 376 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 377 bool AllowUndefs, bool AllowTypeMismatch) { 378 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 379 return false; 380 381 // TODO: Add support for scalar UNDEF cases? 382 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 383 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 384 return Match(LHSCst, RHSCst); 385 386 // TODO: Add support for vector UNDEF cases? 387 if (LHS.getOpcode() != RHS.getOpcode() || 388 (LHS.getOpcode() != ISD::BUILD_VECTOR && 389 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 390 return false; 391 392 EVT SVT = LHS.getValueType().getScalarType(); 393 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 394 SDValue LHSOp = LHS.getOperand(i); 395 SDValue RHSOp = RHS.getOperand(i); 396 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 397 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 398 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 399 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 400 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 401 return false; 402 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 403 LHSOp.getValueType() != RHSOp.getValueType())) 404 return false; 405 if (!Match(LHSCst, RHSCst)) 406 return false; 407 } 408 return true; 409 } 410 411 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 412 switch (VecReduceOpcode) { 413 default: 414 llvm_unreachable("Expected VECREDUCE opcode"); 415 case ISD::VECREDUCE_FADD: 416 case ISD::VECREDUCE_SEQ_FADD: 417 case ISD::VP_REDUCE_FADD: 418 case ISD::VP_REDUCE_SEQ_FADD: 419 return ISD::FADD; 420 case ISD::VECREDUCE_FMUL: 421 case ISD::VECREDUCE_SEQ_FMUL: 422 case ISD::VP_REDUCE_FMUL: 423 case ISD::VP_REDUCE_SEQ_FMUL: 424 return ISD::FMUL; 425 case ISD::VECREDUCE_ADD: 426 case ISD::VP_REDUCE_ADD: 427 return ISD::ADD; 428 case ISD::VECREDUCE_MUL: 429 case ISD::VP_REDUCE_MUL: 430 return ISD::MUL; 431 case ISD::VECREDUCE_AND: 432 case ISD::VP_REDUCE_AND: 433 return ISD::AND; 434 case ISD::VECREDUCE_OR: 435 case ISD::VP_REDUCE_OR: 436 return ISD::OR; 437 case ISD::VECREDUCE_XOR: 438 case ISD::VP_REDUCE_XOR: 439 return ISD::XOR; 440 case ISD::VECREDUCE_SMAX: 441 case ISD::VP_REDUCE_SMAX: 442 return ISD::SMAX; 443 case ISD::VECREDUCE_SMIN: 444 case ISD::VP_REDUCE_SMIN: 445 return ISD::SMIN; 446 case ISD::VECREDUCE_UMAX: 447 case ISD::VP_REDUCE_UMAX: 448 return ISD::UMAX; 449 case ISD::VECREDUCE_UMIN: 450 case ISD::VP_REDUCE_UMIN: 451 return ISD::UMIN; 452 case ISD::VECREDUCE_FMAX: 453 case ISD::VP_REDUCE_FMAX: 454 return ISD::FMAXNUM; 455 case ISD::VECREDUCE_FMIN: 456 case ISD::VP_REDUCE_FMIN: 457 return ISD::FMINNUM; 458 case ISD::VECREDUCE_FMAXIMUM: 459 return ISD::FMAXIMUM; 460 case ISD::VECREDUCE_FMINIMUM: 461 return ISD::FMINIMUM; 462 } 463 } 464 465 bool ISD::isVPOpcode(unsigned Opcode) { 466 switch (Opcode) { 467 default: 468 return false; 469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 470 case ISD::VPSD: \ 471 return true; 472 #include "llvm/IR/VPIntrinsics.def" 473 } 474 } 475 476 bool ISD::isVPBinaryOp(unsigned Opcode) { 477 switch (Opcode) { 478 default: 479 break; 480 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 481 #define VP_PROPERTY_BINARYOP return true; 482 #define END_REGISTER_VP_SDNODE(VPSD) break; 483 #include "llvm/IR/VPIntrinsics.def" 484 } 485 return false; 486 } 487 488 bool ISD::isVPReduction(unsigned Opcode) { 489 switch (Opcode) { 490 default: 491 break; 492 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 493 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 494 #define END_REGISTER_VP_SDNODE(VPSD) break; 495 #include "llvm/IR/VPIntrinsics.def" 496 } 497 return false; 498 } 499 500 /// The operand position of the vector mask. 501 std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 502 switch (Opcode) { 503 default: 504 return std::nullopt; 505 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 506 case ISD::VPSD: \ 507 return MASKPOS; 508 #include "llvm/IR/VPIntrinsics.def" 509 } 510 } 511 512 /// The operand position of the explicit vector length parameter. 513 std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 514 switch (Opcode) { 515 default: 516 return std::nullopt; 517 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 518 case ISD::VPSD: \ 519 return EVLPOS; 520 #include "llvm/IR/VPIntrinsics.def" 521 } 522 } 523 524 std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode, 525 bool hasFPExcept) { 526 // FIXME: Return strict opcodes in case of fp exceptions. 527 switch (VPOpcode) { 528 default: 529 return std::nullopt; 530 #define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC: 531 #define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC; 532 #define END_REGISTER_VP_SDNODE(VPOPC) break; 533 #include "llvm/IR/VPIntrinsics.def" 534 } 535 return std::nullopt; 536 } 537 538 unsigned ISD::getVPForBaseOpcode(unsigned Opcode) { 539 switch (Opcode) { 540 default: 541 llvm_unreachable("can not translate this Opcode to VP."); 542 #define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break; 543 #define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC: 544 #define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC; 545 #include "llvm/IR/VPIntrinsics.def" 546 } 547 } 548 549 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 550 switch (ExtType) { 551 case ISD::EXTLOAD: 552 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 553 case ISD::SEXTLOAD: 554 return ISD::SIGN_EXTEND; 555 case ISD::ZEXTLOAD: 556 return ISD::ZERO_EXTEND; 557 default: 558 break; 559 } 560 561 llvm_unreachable("Invalid LoadExtType"); 562 } 563 564 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 565 // To perform this operation, we just need to swap the L and G bits of the 566 // operation. 567 unsigned OldL = (Operation >> 2) & 1; 568 unsigned OldG = (Operation >> 1) & 1; 569 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 570 (OldL << 1) | // New G bit 571 (OldG << 2)); // New L bit. 572 } 573 574 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 575 unsigned Operation = Op; 576 if (isIntegerLike) 577 Operation ^= 7; // Flip L, G, E bits, but not U. 578 else 579 Operation ^= 15; // Flip all of the condition bits. 580 581 if (Operation > ISD::SETTRUE2) 582 Operation &= ~8; // Don't let N and U bits get set. 583 584 return ISD::CondCode(Operation); 585 } 586 587 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 588 return getSetCCInverseImpl(Op, Type.isInteger()); 589 } 590 591 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 592 bool isIntegerLike) { 593 return getSetCCInverseImpl(Op, isIntegerLike); 594 } 595 596 /// For an integer comparison, return 1 if the comparison is a signed operation 597 /// and 2 if the result is an unsigned comparison. Return zero if the operation 598 /// does not depend on the sign of the input (setne and seteq). 599 static int isSignedOp(ISD::CondCode Opcode) { 600 switch (Opcode) { 601 default: llvm_unreachable("Illegal integer setcc operation!"); 602 case ISD::SETEQ: 603 case ISD::SETNE: return 0; 604 case ISD::SETLT: 605 case ISD::SETLE: 606 case ISD::SETGT: 607 case ISD::SETGE: return 1; 608 case ISD::SETULT: 609 case ISD::SETULE: 610 case ISD::SETUGT: 611 case ISD::SETUGE: return 2; 612 } 613 } 614 615 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 616 EVT Type) { 617 bool IsInteger = Type.isInteger(); 618 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 619 // Cannot fold a signed integer setcc with an unsigned integer setcc. 620 return ISD::SETCC_INVALID; 621 622 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 623 624 // If the N and U bits get set, then the resultant comparison DOES suddenly 625 // care about orderedness, and it is true when ordered. 626 if (Op > ISD::SETTRUE2) 627 Op &= ~16; // Clear the U bit if the N bit is set. 628 629 // Canonicalize illegal integer setcc's. 630 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 631 Op = ISD::SETNE; 632 633 return ISD::CondCode(Op); 634 } 635 636 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 637 EVT Type) { 638 bool IsInteger = Type.isInteger(); 639 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 640 // Cannot fold a signed setcc with an unsigned setcc. 641 return ISD::SETCC_INVALID; 642 643 // Combine all of the condition bits. 644 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 645 646 // Canonicalize illegal integer setcc's. 647 if (IsInteger) { 648 switch (Result) { 649 default: break; 650 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 651 case ISD::SETOEQ: // SETEQ & SETU[LG]E 652 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 653 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 654 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 655 } 656 } 657 658 return Result; 659 } 660 661 //===----------------------------------------------------------------------===// 662 // SDNode Profile Support 663 //===----------------------------------------------------------------------===// 664 665 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 666 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 667 ID.AddInteger(OpC); 668 } 669 670 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 671 /// solely with their pointer. 672 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 673 ID.AddPointer(VTList.VTs); 674 } 675 676 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 677 static void AddNodeIDOperands(FoldingSetNodeID &ID, 678 ArrayRef<SDValue> Ops) { 679 for (const auto &Op : Ops) { 680 ID.AddPointer(Op.getNode()); 681 ID.AddInteger(Op.getResNo()); 682 } 683 } 684 685 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 686 static void AddNodeIDOperands(FoldingSetNodeID &ID, 687 ArrayRef<SDUse> Ops) { 688 for (const auto &Op : Ops) { 689 ID.AddPointer(Op.getNode()); 690 ID.AddInteger(Op.getResNo()); 691 } 692 } 693 694 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC, 695 SDVTList VTList, ArrayRef<SDValue> OpList) { 696 AddNodeIDOpcode(ID, OpC); 697 AddNodeIDValueTypes(ID, VTList); 698 AddNodeIDOperands(ID, OpList); 699 } 700 701 /// If this is an SDNode with special info, add this info to the NodeID data. 702 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 703 switch (N->getOpcode()) { 704 case ISD::TargetExternalSymbol: 705 case ISD::ExternalSymbol: 706 case ISD::MCSymbol: 707 llvm_unreachable("Should only be used on nodes with operands"); 708 default: break; // Normal nodes don't need extra info. 709 case ISD::TargetConstant: 710 case ISD::Constant: { 711 const ConstantSDNode *C = cast<ConstantSDNode>(N); 712 ID.AddPointer(C->getConstantIntValue()); 713 ID.AddBoolean(C->isOpaque()); 714 break; 715 } 716 case ISD::TargetConstantFP: 717 case ISD::ConstantFP: 718 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 719 break; 720 case ISD::TargetGlobalAddress: 721 case ISD::GlobalAddress: 722 case ISD::TargetGlobalTLSAddress: 723 case ISD::GlobalTLSAddress: { 724 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 725 ID.AddPointer(GA->getGlobal()); 726 ID.AddInteger(GA->getOffset()); 727 ID.AddInteger(GA->getTargetFlags()); 728 break; 729 } 730 case ISD::BasicBlock: 731 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 732 break; 733 case ISD::Register: 734 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 735 break; 736 case ISD::RegisterMask: 737 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 738 break; 739 case ISD::SRCVALUE: 740 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 741 break; 742 case ISD::FrameIndex: 743 case ISD::TargetFrameIndex: 744 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 745 break; 746 case ISD::LIFETIME_START: 747 case ISD::LIFETIME_END: 748 if (cast<LifetimeSDNode>(N)->hasOffset()) { 749 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 750 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 751 } 752 break; 753 case ISD::PSEUDO_PROBE: 754 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 755 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 756 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 757 break; 758 case ISD::JumpTable: 759 case ISD::TargetJumpTable: 760 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 761 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 762 break; 763 case ISD::ConstantPool: 764 case ISD::TargetConstantPool: { 765 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 766 ID.AddInteger(CP->getAlign().value()); 767 ID.AddInteger(CP->getOffset()); 768 if (CP->isMachineConstantPoolEntry()) 769 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 770 else 771 ID.AddPointer(CP->getConstVal()); 772 ID.AddInteger(CP->getTargetFlags()); 773 break; 774 } 775 case ISD::TargetIndex: { 776 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 777 ID.AddInteger(TI->getIndex()); 778 ID.AddInteger(TI->getOffset()); 779 ID.AddInteger(TI->getTargetFlags()); 780 break; 781 } 782 case ISD::LOAD: { 783 const LoadSDNode *LD = cast<LoadSDNode>(N); 784 ID.AddInteger(LD->getMemoryVT().getRawBits()); 785 ID.AddInteger(LD->getRawSubclassData()); 786 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 787 ID.AddInteger(LD->getMemOperand()->getFlags()); 788 break; 789 } 790 case ISD::STORE: { 791 const StoreSDNode *ST = cast<StoreSDNode>(N); 792 ID.AddInteger(ST->getMemoryVT().getRawBits()); 793 ID.AddInteger(ST->getRawSubclassData()); 794 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 795 ID.AddInteger(ST->getMemOperand()->getFlags()); 796 break; 797 } 798 case ISD::VP_LOAD: { 799 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 800 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 801 ID.AddInteger(ELD->getRawSubclassData()); 802 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 803 ID.AddInteger(ELD->getMemOperand()->getFlags()); 804 break; 805 } 806 case ISD::VP_STORE: { 807 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 808 ID.AddInteger(EST->getMemoryVT().getRawBits()); 809 ID.AddInteger(EST->getRawSubclassData()); 810 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 811 ID.AddInteger(EST->getMemOperand()->getFlags()); 812 break; 813 } 814 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: { 815 const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N); 816 ID.AddInteger(SLD->getMemoryVT().getRawBits()); 817 ID.AddInteger(SLD->getRawSubclassData()); 818 ID.AddInteger(SLD->getPointerInfo().getAddrSpace()); 819 break; 820 } 821 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: { 822 const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N); 823 ID.AddInteger(SST->getMemoryVT().getRawBits()); 824 ID.AddInteger(SST->getRawSubclassData()); 825 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 826 break; 827 } 828 case ISD::VP_GATHER: { 829 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 830 ID.AddInteger(EG->getMemoryVT().getRawBits()); 831 ID.AddInteger(EG->getRawSubclassData()); 832 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 833 ID.AddInteger(EG->getMemOperand()->getFlags()); 834 break; 835 } 836 case ISD::VP_SCATTER: { 837 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 838 ID.AddInteger(ES->getMemoryVT().getRawBits()); 839 ID.AddInteger(ES->getRawSubclassData()); 840 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 841 ID.AddInteger(ES->getMemOperand()->getFlags()); 842 break; 843 } 844 case ISD::MLOAD: { 845 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 846 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 847 ID.AddInteger(MLD->getRawSubclassData()); 848 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 849 ID.AddInteger(MLD->getMemOperand()->getFlags()); 850 break; 851 } 852 case ISD::MSTORE: { 853 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 854 ID.AddInteger(MST->getMemoryVT().getRawBits()); 855 ID.AddInteger(MST->getRawSubclassData()); 856 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 857 ID.AddInteger(MST->getMemOperand()->getFlags()); 858 break; 859 } 860 case ISD::MGATHER: { 861 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 862 ID.AddInteger(MG->getMemoryVT().getRawBits()); 863 ID.AddInteger(MG->getRawSubclassData()); 864 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 865 ID.AddInteger(MG->getMemOperand()->getFlags()); 866 break; 867 } 868 case ISD::MSCATTER: { 869 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 870 ID.AddInteger(MS->getMemoryVT().getRawBits()); 871 ID.AddInteger(MS->getRawSubclassData()); 872 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 873 ID.AddInteger(MS->getMemOperand()->getFlags()); 874 break; 875 } 876 case ISD::ATOMIC_CMP_SWAP: 877 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 878 case ISD::ATOMIC_SWAP: 879 case ISD::ATOMIC_LOAD_ADD: 880 case ISD::ATOMIC_LOAD_SUB: 881 case ISD::ATOMIC_LOAD_AND: 882 case ISD::ATOMIC_LOAD_CLR: 883 case ISD::ATOMIC_LOAD_OR: 884 case ISD::ATOMIC_LOAD_XOR: 885 case ISD::ATOMIC_LOAD_NAND: 886 case ISD::ATOMIC_LOAD_MIN: 887 case ISD::ATOMIC_LOAD_MAX: 888 case ISD::ATOMIC_LOAD_UMIN: 889 case ISD::ATOMIC_LOAD_UMAX: 890 case ISD::ATOMIC_LOAD: 891 case ISD::ATOMIC_STORE: { 892 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 893 ID.AddInteger(AT->getMemoryVT().getRawBits()); 894 ID.AddInteger(AT->getRawSubclassData()); 895 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 896 ID.AddInteger(AT->getMemOperand()->getFlags()); 897 break; 898 } 899 case ISD::VECTOR_SHUFFLE: { 900 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 901 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 902 i != e; ++i) 903 ID.AddInteger(SVN->getMaskElt(i)); 904 break; 905 } 906 case ISD::TargetBlockAddress: 907 case ISD::BlockAddress: { 908 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 909 ID.AddPointer(BA->getBlockAddress()); 910 ID.AddInteger(BA->getOffset()); 911 ID.AddInteger(BA->getTargetFlags()); 912 break; 913 } 914 case ISD::AssertAlign: 915 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value()); 916 break; 917 case ISD::PREFETCH: 918 case ISD::INTRINSIC_VOID: 919 case ISD::INTRINSIC_W_CHAIN: 920 // Handled by MemIntrinsicSDNode check after the switch. 921 break; 922 } // end switch (N->getOpcode()) 923 924 // MemIntrinsic nodes could also have subclass data, address spaces, and flags 925 // to check. 926 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) { 927 ID.AddInteger(MN->getRawSubclassData()); 928 ID.AddInteger(MN->getPointerInfo().getAddrSpace()); 929 ID.AddInteger(MN->getMemOperand()->getFlags()); 930 ID.AddInteger(MN->getMemoryVT().getRawBits()); 931 } 932 } 933 934 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 935 /// data. 936 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 937 AddNodeIDOpcode(ID, N->getOpcode()); 938 // Add the return value info. 939 AddNodeIDValueTypes(ID, N->getVTList()); 940 // Add the operand info. 941 AddNodeIDOperands(ID, N->ops()); 942 943 // Handle SDNode leafs with special info. 944 AddNodeIDCustom(ID, N); 945 } 946 947 //===----------------------------------------------------------------------===// 948 // SelectionDAG Class 949 //===----------------------------------------------------------------------===// 950 951 /// doNotCSE - Return true if CSE should not be performed for this node. 952 static bool doNotCSE(SDNode *N) { 953 if (N->getValueType(0) == MVT::Glue) 954 return true; // Never CSE anything that produces a flag. 955 956 switch (N->getOpcode()) { 957 default: break; 958 case ISD::HANDLENODE: 959 case ISD::EH_LABEL: 960 return true; // Never CSE these nodes. 961 } 962 963 // Check that remaining values produced are not flags. 964 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 965 if (N->getValueType(i) == MVT::Glue) 966 return true; // Never CSE anything that produces a flag. 967 968 return false; 969 } 970 971 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 972 /// SelectionDAG. 973 void SelectionDAG::RemoveDeadNodes() { 974 // Create a dummy node (which is not added to allnodes), that adds a reference 975 // to the root node, preventing it from being deleted. 976 HandleSDNode Dummy(getRoot()); 977 978 SmallVector<SDNode*, 128> DeadNodes; 979 980 // Add all obviously-dead nodes to the DeadNodes worklist. 981 for (SDNode &Node : allnodes()) 982 if (Node.use_empty()) 983 DeadNodes.push_back(&Node); 984 985 RemoveDeadNodes(DeadNodes); 986 987 // If the root changed (e.g. it was a dead load, update the root). 988 setRoot(Dummy.getValue()); 989 } 990 991 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 992 /// given list, and any nodes that become unreachable as a result. 993 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 994 995 // Process the worklist, deleting the nodes and adding their uses to the 996 // worklist. 997 while (!DeadNodes.empty()) { 998 SDNode *N = DeadNodes.pop_back_val(); 999 // Skip to next node if we've already managed to delete the node. This could 1000 // happen if replacing a node causes a node previously added to the node to 1001 // be deleted. 1002 if (N->getOpcode() == ISD::DELETED_NODE) 1003 continue; 1004 1005 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1006 DUL->NodeDeleted(N, nullptr); 1007 1008 // Take the node out of the appropriate CSE map. 1009 RemoveNodeFromCSEMaps(N); 1010 1011 // Next, brutally remove the operand list. This is safe to do, as there are 1012 // no cycles in the graph. 1013 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 1014 SDUse &Use = *I++; 1015 SDNode *Operand = Use.getNode(); 1016 Use.set(SDValue()); 1017 1018 // Now that we removed this operand, see if there are no uses of it left. 1019 if (Operand->use_empty()) 1020 DeadNodes.push_back(Operand); 1021 } 1022 1023 DeallocateNode(N); 1024 } 1025 } 1026 1027 void SelectionDAG::RemoveDeadNode(SDNode *N){ 1028 SmallVector<SDNode*, 16> DeadNodes(1, N); 1029 1030 // Create a dummy node that adds a reference to the root node, preventing 1031 // it from being deleted. (This matters if the root is an operand of the 1032 // dead node.) 1033 HandleSDNode Dummy(getRoot()); 1034 1035 RemoveDeadNodes(DeadNodes); 1036 } 1037 1038 void SelectionDAG::DeleteNode(SDNode *N) { 1039 // First take this out of the appropriate CSE map. 1040 RemoveNodeFromCSEMaps(N); 1041 1042 // Finally, remove uses due to operands of this node, remove from the 1043 // AllNodes list, and delete the node. 1044 DeleteNodeNotInCSEMaps(N); 1045 } 1046 1047 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 1048 assert(N->getIterator() != AllNodes.begin() && 1049 "Cannot delete the entry node!"); 1050 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 1051 1052 // Drop all of the operands and decrement used node's use counts. 1053 N->DropOperands(); 1054 1055 DeallocateNode(N); 1056 } 1057 1058 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 1059 assert(!(V->isVariadic() && isParameter)); 1060 if (isParameter) 1061 ByvalParmDbgValues.push_back(V); 1062 else 1063 DbgValues.push_back(V); 1064 for (const SDNode *Node : V->getSDNodes()) 1065 if (Node) 1066 DbgValMap[Node].push_back(V); 1067 } 1068 1069 void SDDbgInfo::erase(const SDNode *Node) { 1070 DbgValMapType::iterator I = DbgValMap.find(Node); 1071 if (I == DbgValMap.end()) 1072 return; 1073 for (auto &Val: I->second) 1074 Val->setIsInvalidated(); 1075 DbgValMap.erase(I); 1076 } 1077 1078 void SelectionDAG::DeallocateNode(SDNode *N) { 1079 // If we have operands, deallocate them. 1080 removeOperands(N); 1081 1082 NodeAllocator.Deallocate(AllNodes.remove(N)); 1083 1084 // Set the opcode to DELETED_NODE to help catch bugs when node 1085 // memory is reallocated. 1086 // FIXME: There are places in SDag that have grown a dependency on the opcode 1087 // value in the released node. 1088 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 1089 N->NodeType = ISD::DELETED_NODE; 1090 1091 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 1092 // them and forget about that node. 1093 DbgInfo->erase(N); 1094 1095 // Invalidate extra info. 1096 SDEI.erase(N); 1097 } 1098 1099 #ifndef NDEBUG 1100 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 1101 static void VerifySDNode(SDNode *N) { 1102 switch (N->getOpcode()) { 1103 default: 1104 break; 1105 case ISD::BUILD_PAIR: { 1106 EVT VT = N->getValueType(0); 1107 assert(N->getNumValues() == 1 && "Too many results!"); 1108 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1109 "Wrong return type!"); 1110 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1111 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1112 "Mismatched operand types!"); 1113 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1114 "Wrong operand type!"); 1115 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1116 "Wrong return type size"); 1117 break; 1118 } 1119 case ISD::BUILD_VECTOR: { 1120 assert(N->getNumValues() == 1 && "Too many results!"); 1121 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1122 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1123 "Wrong number of operands!"); 1124 EVT EltVT = N->getValueType(0).getVectorElementType(); 1125 for (const SDUse &Op : N->ops()) { 1126 assert((Op.getValueType() == EltVT || 1127 (EltVT.isInteger() && Op.getValueType().isInteger() && 1128 EltVT.bitsLE(Op.getValueType()))) && 1129 "Wrong operand type!"); 1130 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1131 "Operands must all have the same type"); 1132 } 1133 break; 1134 } 1135 } 1136 } 1137 #endif // NDEBUG 1138 1139 /// Insert a newly allocated node into the DAG. 1140 /// 1141 /// Handles insertion into the all nodes list and CSE map, as well as 1142 /// verification and other common operations when a new node is allocated. 1143 void SelectionDAG::InsertNode(SDNode *N) { 1144 AllNodes.push_back(N); 1145 #ifndef NDEBUG 1146 N->PersistentId = NextPersistentId++; 1147 VerifySDNode(N); 1148 #endif 1149 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1150 DUL->NodeInserted(N); 1151 } 1152 1153 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1154 /// correspond to it. This is useful when we're about to delete or repurpose 1155 /// the node. We don't want future request for structurally identical nodes 1156 /// to return N anymore. 1157 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1158 bool Erased = false; 1159 switch (N->getOpcode()) { 1160 case ISD::HANDLENODE: return false; // noop. 1161 case ISD::CONDCODE: 1162 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1163 "Cond code doesn't exist!"); 1164 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1165 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1166 break; 1167 case ISD::ExternalSymbol: 1168 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1169 break; 1170 case ISD::TargetExternalSymbol: { 1171 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1172 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1173 ESN->getSymbol(), ESN->getTargetFlags())); 1174 break; 1175 } 1176 case ISD::MCSymbol: { 1177 auto *MCSN = cast<MCSymbolSDNode>(N); 1178 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1179 break; 1180 } 1181 case ISD::VALUETYPE: { 1182 EVT VT = cast<VTSDNode>(N)->getVT(); 1183 if (VT.isExtended()) { 1184 Erased = ExtendedValueTypeNodes.erase(VT); 1185 } else { 1186 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1187 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1188 } 1189 break; 1190 } 1191 default: 1192 // Remove it from the CSE Map. 1193 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1194 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1195 Erased = CSEMap.RemoveNode(N); 1196 break; 1197 } 1198 #ifndef NDEBUG 1199 // Verify that the node was actually in one of the CSE maps, unless it has a 1200 // flag result (which cannot be CSE'd) or is one of the special cases that are 1201 // not subject to CSE. 1202 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1203 !N->isMachineOpcode() && !doNotCSE(N)) { 1204 N->dump(this); 1205 dbgs() << "\n"; 1206 llvm_unreachable("Node is not in map!"); 1207 } 1208 #endif 1209 return Erased; 1210 } 1211 1212 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1213 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1214 /// node already exists, in which case transfer all its users to the existing 1215 /// node. This transfer can potentially trigger recursive merging. 1216 void 1217 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1218 // For node types that aren't CSE'd, just act as if no identical node 1219 // already exists. 1220 if (!doNotCSE(N)) { 1221 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1222 if (Existing != N) { 1223 // If there was already an existing matching node, use ReplaceAllUsesWith 1224 // to replace the dead one with the existing one. This can cause 1225 // recursive merging of other unrelated nodes down the line. 1226 ReplaceAllUsesWith(N, Existing); 1227 1228 // N is now dead. Inform the listeners and delete it. 1229 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1230 DUL->NodeDeleted(N, Existing); 1231 DeleteNodeNotInCSEMaps(N); 1232 return; 1233 } 1234 } 1235 1236 // If the node doesn't already exist, we updated it. Inform listeners. 1237 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1238 DUL->NodeUpdated(N); 1239 } 1240 1241 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1242 /// were replaced with those specified. If this node is never memoized, 1243 /// return null, otherwise return a pointer to the slot it would take. If a 1244 /// node already exists with these operands, the slot will be non-null. 1245 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1246 void *&InsertPos) { 1247 if (doNotCSE(N)) 1248 return nullptr; 1249 1250 SDValue Ops[] = { Op }; 1251 FoldingSetNodeID ID; 1252 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1253 AddNodeIDCustom(ID, N); 1254 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1255 if (Node) 1256 Node->intersectFlagsWith(N->getFlags()); 1257 return Node; 1258 } 1259 1260 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1261 /// were replaced with those specified. If this node is never memoized, 1262 /// return null, otherwise return a pointer to the slot it would take. If a 1263 /// node already exists with these operands, the slot will be non-null. 1264 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1265 SDValue Op1, SDValue Op2, 1266 void *&InsertPos) { 1267 if (doNotCSE(N)) 1268 return nullptr; 1269 1270 SDValue Ops[] = { Op1, Op2 }; 1271 FoldingSetNodeID ID; 1272 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1273 AddNodeIDCustom(ID, N); 1274 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1275 if (Node) 1276 Node->intersectFlagsWith(N->getFlags()); 1277 return Node; 1278 } 1279 1280 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1281 /// were replaced with those specified. If this node is never memoized, 1282 /// return null, otherwise return a pointer to the slot it would take. If a 1283 /// node already exists with these operands, the slot will be non-null. 1284 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1285 void *&InsertPos) { 1286 if (doNotCSE(N)) 1287 return nullptr; 1288 1289 FoldingSetNodeID ID; 1290 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1291 AddNodeIDCustom(ID, N); 1292 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1293 if (Node) 1294 Node->intersectFlagsWith(N->getFlags()); 1295 return Node; 1296 } 1297 1298 Align SelectionDAG::getEVTAlign(EVT VT) const { 1299 Type *Ty = VT == MVT::iPTR ? 1300 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1301 VT.getTypeForEVT(*getContext()); 1302 1303 return getDataLayout().getABITypeAlign(Ty); 1304 } 1305 1306 // EntryNode could meaningfully have debug info if we can find it... 1307 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1308 : TM(tm), OptLevel(OL), 1309 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other, MVT::Glue)), 1310 Root(getEntryNode()) { 1311 InsertNode(&EntryNode); 1312 DbgInfo = new SDDbgInfo(); 1313 } 1314 1315 void SelectionDAG::init(MachineFunction &NewMF, 1316 OptimizationRemarkEmitter &NewORE, Pass *PassPtr, 1317 const TargetLibraryInfo *LibraryInfo, 1318 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin, 1319 BlockFrequencyInfo *BFIin, 1320 FunctionVarLocs const *VarLocs) { 1321 MF = &NewMF; 1322 SDAGISelPass = PassPtr; 1323 ORE = &NewORE; 1324 TLI = getSubtarget().getTargetLowering(); 1325 TSI = getSubtarget().getSelectionDAGInfo(); 1326 LibInfo = LibraryInfo; 1327 Context = &MF->getFunction().getContext(); 1328 UA = NewUA; 1329 PSI = PSIin; 1330 BFI = BFIin; 1331 FnVarLocs = VarLocs; 1332 } 1333 1334 SelectionDAG::~SelectionDAG() { 1335 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1336 allnodes_clear(); 1337 OperandRecycler.clear(OperandAllocator); 1338 delete DbgInfo; 1339 } 1340 1341 bool SelectionDAG::shouldOptForSize() const { 1342 return MF->getFunction().hasOptSize() || 1343 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1344 } 1345 1346 void SelectionDAG::allnodes_clear() { 1347 assert(&*AllNodes.begin() == &EntryNode); 1348 AllNodes.remove(AllNodes.begin()); 1349 while (!AllNodes.empty()) 1350 DeallocateNode(&AllNodes.front()); 1351 #ifndef NDEBUG 1352 NextPersistentId = 0; 1353 #endif 1354 } 1355 1356 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1357 void *&InsertPos) { 1358 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1359 if (N) { 1360 switch (N->getOpcode()) { 1361 default: break; 1362 case ISD::Constant: 1363 case ISD::ConstantFP: 1364 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1365 "debug location. Use another overload."); 1366 } 1367 } 1368 return N; 1369 } 1370 1371 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1372 const SDLoc &DL, void *&InsertPos) { 1373 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1374 if (N) { 1375 switch (N->getOpcode()) { 1376 case ISD::Constant: 1377 case ISD::ConstantFP: 1378 // Erase debug location from the node if the node is used at several 1379 // different places. Do not propagate one location to all uses as it 1380 // will cause a worse single stepping debugging experience. 1381 if (N->getDebugLoc() != DL.getDebugLoc()) 1382 N->setDebugLoc(DebugLoc()); 1383 break; 1384 default: 1385 // When the node's point of use is located earlier in the instruction 1386 // sequence than its prior point of use, update its debug info to the 1387 // earlier location. 1388 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1389 N->setDebugLoc(DL.getDebugLoc()); 1390 break; 1391 } 1392 } 1393 return N; 1394 } 1395 1396 void SelectionDAG::clear() { 1397 allnodes_clear(); 1398 OperandRecycler.clear(OperandAllocator); 1399 OperandAllocator.Reset(); 1400 CSEMap.clear(); 1401 1402 ExtendedValueTypeNodes.clear(); 1403 ExternalSymbols.clear(); 1404 TargetExternalSymbols.clear(); 1405 MCSymbols.clear(); 1406 SDEI.clear(); 1407 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1408 static_cast<CondCodeSDNode*>(nullptr)); 1409 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1410 static_cast<SDNode*>(nullptr)); 1411 1412 EntryNode.UseList = nullptr; 1413 InsertNode(&EntryNode); 1414 Root = getEntryNode(); 1415 DbgInfo->clear(); 1416 } 1417 1418 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1419 return VT.bitsGT(Op.getValueType()) 1420 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1421 : getNode(ISD::FP_ROUND, DL, VT, Op, 1422 getIntPtrConstant(0, DL, /*isTarget=*/true)); 1423 } 1424 1425 std::pair<SDValue, SDValue> 1426 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1427 const SDLoc &DL, EVT VT) { 1428 assert(!VT.bitsEq(Op.getValueType()) && 1429 "Strict no-op FP extend/round not allowed."); 1430 SDValue Res = 1431 VT.bitsGT(Op.getValueType()) 1432 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1433 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1434 {Chain, Op, getIntPtrConstant(0, DL)}); 1435 1436 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1437 } 1438 1439 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1440 return VT.bitsGT(Op.getValueType()) ? 1441 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1442 getNode(ISD::TRUNCATE, DL, VT, Op); 1443 } 1444 1445 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1446 return VT.bitsGT(Op.getValueType()) ? 1447 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1448 getNode(ISD::TRUNCATE, DL, VT, Op); 1449 } 1450 1451 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1452 return VT.bitsGT(Op.getValueType()) ? 1453 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1454 getNode(ISD::TRUNCATE, DL, VT, Op); 1455 } 1456 1457 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1458 EVT OpVT) { 1459 if (VT.bitsLE(Op.getValueType())) 1460 return getNode(ISD::TRUNCATE, SL, VT, Op); 1461 1462 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1463 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1464 } 1465 1466 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1467 EVT OpVT = Op.getValueType(); 1468 assert(VT.isInteger() && OpVT.isInteger() && 1469 "Cannot getZeroExtendInReg FP types"); 1470 assert(VT.isVector() == OpVT.isVector() && 1471 "getZeroExtendInReg type should be vector iff the operand " 1472 "type is vector!"); 1473 assert((!VT.isVector() || 1474 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1475 "Vector element counts must match in getZeroExtendInReg"); 1476 assert(VT.bitsLE(OpVT) && "Not extending!"); 1477 if (OpVT == VT) 1478 return Op; 1479 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1480 VT.getScalarSizeInBits()); 1481 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1482 } 1483 1484 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1485 // Only unsigned pointer semantics are supported right now. In the future this 1486 // might delegate to TLI to check pointer signedness. 1487 return getZExtOrTrunc(Op, DL, VT); 1488 } 1489 1490 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1491 // Only unsigned pointer semantics are supported right now. In the future this 1492 // might delegate to TLI to check pointer signedness. 1493 return getZeroExtendInReg(Op, DL, VT); 1494 } 1495 1496 SDValue SelectionDAG::getNegative(SDValue Val, const SDLoc &DL, EVT VT) { 1497 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val); 1498 } 1499 1500 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1501 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1502 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1503 } 1504 1505 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1506 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1507 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1508 } 1509 1510 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val, 1511 SDValue Mask, SDValue EVL, EVT VT) { 1512 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1513 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL); 1514 } 1515 1516 SDValue SelectionDAG::getVPPtrExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, 1517 SDValue Mask, SDValue EVL) { 1518 return getVPZExtOrTrunc(DL, VT, Op, Mask, EVL); 1519 } 1520 1521 SDValue SelectionDAG::getVPZExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, 1522 SDValue Mask, SDValue EVL) { 1523 if (VT.bitsGT(Op.getValueType())) 1524 return getNode(ISD::VP_ZERO_EXTEND, DL, VT, Op, Mask, EVL); 1525 if (VT.bitsLT(Op.getValueType())) 1526 return getNode(ISD::VP_TRUNCATE, DL, VT, Op, Mask, EVL); 1527 return Op; 1528 } 1529 1530 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1531 EVT OpVT) { 1532 if (!V) 1533 return getConstant(0, DL, VT); 1534 1535 switch (TLI->getBooleanContents(OpVT)) { 1536 case TargetLowering::ZeroOrOneBooleanContent: 1537 case TargetLowering::UndefinedBooleanContent: 1538 return getConstant(1, DL, VT); 1539 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1540 return getAllOnesConstant(DL, VT); 1541 } 1542 llvm_unreachable("Unexpected boolean content enum!"); 1543 } 1544 1545 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1546 bool isT, bool isO) { 1547 EVT EltVT = VT.getScalarType(); 1548 assert((EltVT.getSizeInBits() >= 64 || 1549 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1550 "getConstant with a uint64_t value that doesn't fit in the type!"); 1551 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1552 } 1553 1554 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1555 bool isT, bool isO) { 1556 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1557 } 1558 1559 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1560 EVT VT, bool isT, bool isO) { 1561 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1562 1563 EVT EltVT = VT.getScalarType(); 1564 const ConstantInt *Elt = &Val; 1565 1566 // In some cases the vector type is legal but the element type is illegal and 1567 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1568 // inserted value (the type does not need to match the vector element type). 1569 // Any extra bits introduced will be truncated away. 1570 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1571 TargetLowering::TypePromoteInteger) { 1572 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1573 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1574 Elt = ConstantInt::get(*getContext(), NewVal); 1575 } 1576 // In other cases the element type is illegal and needs to be expanded, for 1577 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1578 // the value into n parts and use a vector type with n-times the elements. 1579 // Then bitcast to the type requested. 1580 // Legalizing constants too early makes the DAGCombiner's job harder so we 1581 // only legalize if the DAG tells us we must produce legal types. 1582 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1583 TLI->getTypeAction(*getContext(), EltVT) == 1584 TargetLowering::TypeExpandInteger) { 1585 const APInt &NewVal = Elt->getValue(); 1586 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1587 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1588 1589 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1590 if (VT.isScalableVector()) { 1591 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1592 "Can only handle an even split!"); 1593 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1594 1595 SmallVector<SDValue, 2> ScalarParts; 1596 for (unsigned i = 0; i != Parts; ++i) 1597 ScalarParts.push_back(getConstant( 1598 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1599 ViaEltVT, isT, isO)); 1600 1601 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1602 } 1603 1604 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1605 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1606 1607 // Check the temporary vector is the correct size. If this fails then 1608 // getTypeToTransformTo() probably returned a type whose size (in bits) 1609 // isn't a power-of-2 factor of the requested type size. 1610 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1611 1612 SmallVector<SDValue, 2> EltParts; 1613 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1614 EltParts.push_back(getConstant( 1615 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1616 ViaEltVT, isT, isO)); 1617 1618 // EltParts is currently in little endian order. If we actually want 1619 // big-endian order then reverse it now. 1620 if (getDataLayout().isBigEndian()) 1621 std::reverse(EltParts.begin(), EltParts.end()); 1622 1623 // The elements must be reversed when the element order is different 1624 // to the endianness of the elements (because the BITCAST is itself a 1625 // vector shuffle in this situation). However, we do not need any code to 1626 // perform this reversal because getConstant() is producing a vector 1627 // splat. 1628 // This situation occurs in MIPS MSA. 1629 1630 SmallVector<SDValue, 8> Ops; 1631 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1632 llvm::append_range(Ops, EltParts); 1633 1634 SDValue V = 1635 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1636 return V; 1637 } 1638 1639 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1640 "APInt size does not match type size!"); 1641 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1642 FoldingSetNodeID ID; 1643 AddNodeIDNode(ID, Opc, getVTList(EltVT), std::nullopt); 1644 ID.AddPointer(Elt); 1645 ID.AddBoolean(isO); 1646 void *IP = nullptr; 1647 SDNode *N = nullptr; 1648 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1649 if (!VT.isVector()) 1650 return SDValue(N, 0); 1651 1652 if (!N) { 1653 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1654 CSEMap.InsertNode(N, IP); 1655 InsertNode(N); 1656 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1657 } 1658 1659 SDValue Result(N, 0); 1660 if (VT.isVector()) 1661 Result = getSplat(VT, DL, Result); 1662 return Result; 1663 } 1664 1665 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1666 bool isTarget) { 1667 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1668 } 1669 1670 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1671 const SDLoc &DL, bool LegalTypes) { 1672 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1673 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1674 return getConstant(Val, DL, ShiftVT); 1675 } 1676 1677 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1678 bool isTarget) { 1679 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1680 } 1681 1682 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1683 bool isTarget) { 1684 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1685 } 1686 1687 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1688 EVT VT, bool isTarget) { 1689 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1690 1691 EVT EltVT = VT.getScalarType(); 1692 1693 // Do the map lookup using the actual bit pattern for the floating point 1694 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1695 // we don't have issues with SNANs. 1696 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1697 FoldingSetNodeID ID; 1698 AddNodeIDNode(ID, Opc, getVTList(EltVT), std::nullopt); 1699 ID.AddPointer(&V); 1700 void *IP = nullptr; 1701 SDNode *N = nullptr; 1702 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1703 if (!VT.isVector()) 1704 return SDValue(N, 0); 1705 1706 if (!N) { 1707 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1708 CSEMap.InsertNode(N, IP); 1709 InsertNode(N); 1710 } 1711 1712 SDValue Result(N, 0); 1713 if (VT.isVector()) 1714 Result = getSplat(VT, DL, Result); 1715 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1716 return Result; 1717 } 1718 1719 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1720 bool isTarget) { 1721 EVT EltVT = VT.getScalarType(); 1722 if (EltVT == MVT::f32) 1723 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1724 if (EltVT == MVT::f64) 1725 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1726 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1727 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1728 bool Ignored; 1729 APFloat APF = APFloat(Val); 1730 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1731 &Ignored); 1732 return getConstantFP(APF, DL, VT, isTarget); 1733 } 1734 llvm_unreachable("Unsupported type in getConstantFP"); 1735 } 1736 1737 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1738 EVT VT, int64_t Offset, bool isTargetGA, 1739 unsigned TargetFlags) { 1740 assert((TargetFlags == 0 || isTargetGA) && 1741 "Cannot set target flags on target-independent globals"); 1742 1743 // Truncate (with sign-extension) the offset value to the pointer size. 1744 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1745 if (BitWidth < 64) 1746 Offset = SignExtend64(Offset, BitWidth); 1747 1748 unsigned Opc; 1749 if (GV->isThreadLocal()) 1750 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1751 else 1752 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1753 1754 FoldingSetNodeID ID; 1755 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1756 ID.AddPointer(GV); 1757 ID.AddInteger(Offset); 1758 ID.AddInteger(TargetFlags); 1759 void *IP = nullptr; 1760 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1761 return SDValue(E, 0); 1762 1763 auto *N = newSDNode<GlobalAddressSDNode>( 1764 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1765 CSEMap.InsertNode(N, IP); 1766 InsertNode(N); 1767 return SDValue(N, 0); 1768 } 1769 1770 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1771 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1772 FoldingSetNodeID ID; 1773 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1774 ID.AddInteger(FI); 1775 void *IP = nullptr; 1776 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1777 return SDValue(E, 0); 1778 1779 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1780 CSEMap.InsertNode(N, IP); 1781 InsertNode(N); 1782 return SDValue(N, 0); 1783 } 1784 1785 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1786 unsigned TargetFlags) { 1787 assert((TargetFlags == 0 || isTarget) && 1788 "Cannot set target flags on target-independent jump tables"); 1789 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1790 FoldingSetNodeID ID; 1791 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1792 ID.AddInteger(JTI); 1793 ID.AddInteger(TargetFlags); 1794 void *IP = nullptr; 1795 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1796 return SDValue(E, 0); 1797 1798 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1799 CSEMap.InsertNode(N, IP); 1800 InsertNode(N); 1801 return SDValue(N, 0); 1802 } 1803 1804 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1805 MaybeAlign Alignment, int Offset, 1806 bool isTarget, unsigned TargetFlags) { 1807 assert((TargetFlags == 0 || isTarget) && 1808 "Cannot set target flags on target-independent globals"); 1809 if (!Alignment) 1810 Alignment = shouldOptForSize() 1811 ? getDataLayout().getABITypeAlign(C->getType()) 1812 : getDataLayout().getPrefTypeAlign(C->getType()); 1813 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1814 FoldingSetNodeID ID; 1815 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1816 ID.AddInteger(Alignment->value()); 1817 ID.AddInteger(Offset); 1818 ID.AddPointer(C); 1819 ID.AddInteger(TargetFlags); 1820 void *IP = nullptr; 1821 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1822 return SDValue(E, 0); 1823 1824 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1825 TargetFlags); 1826 CSEMap.InsertNode(N, IP); 1827 InsertNode(N); 1828 SDValue V = SDValue(N, 0); 1829 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1830 return V; 1831 } 1832 1833 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1834 MaybeAlign Alignment, int Offset, 1835 bool isTarget, unsigned TargetFlags) { 1836 assert((TargetFlags == 0 || isTarget) && 1837 "Cannot set target flags on target-independent globals"); 1838 if (!Alignment) 1839 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1840 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1841 FoldingSetNodeID ID; 1842 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 1843 ID.AddInteger(Alignment->value()); 1844 ID.AddInteger(Offset); 1845 C->addSelectionDAGCSEId(ID); 1846 ID.AddInteger(TargetFlags); 1847 void *IP = nullptr; 1848 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1849 return SDValue(E, 0); 1850 1851 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1852 TargetFlags); 1853 CSEMap.InsertNode(N, IP); 1854 InsertNode(N); 1855 return SDValue(N, 0); 1856 } 1857 1858 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1859 unsigned TargetFlags) { 1860 FoldingSetNodeID ID; 1861 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), std::nullopt); 1862 ID.AddInteger(Index); 1863 ID.AddInteger(Offset); 1864 ID.AddInteger(TargetFlags); 1865 void *IP = nullptr; 1866 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1867 return SDValue(E, 0); 1868 1869 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1870 CSEMap.InsertNode(N, IP); 1871 InsertNode(N); 1872 return SDValue(N, 0); 1873 } 1874 1875 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1876 FoldingSetNodeID ID; 1877 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), std::nullopt); 1878 ID.AddPointer(MBB); 1879 void *IP = nullptr; 1880 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1881 return SDValue(E, 0); 1882 1883 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1884 CSEMap.InsertNode(N, IP); 1885 InsertNode(N); 1886 return SDValue(N, 0); 1887 } 1888 1889 SDValue SelectionDAG::getValueType(EVT VT) { 1890 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1891 ValueTypeNodes.size()) 1892 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1893 1894 SDNode *&N = VT.isExtended() ? 1895 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1896 1897 if (N) return SDValue(N, 0); 1898 N = newSDNode<VTSDNode>(VT); 1899 InsertNode(N); 1900 return SDValue(N, 0); 1901 } 1902 1903 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1904 SDNode *&N = ExternalSymbols[Sym]; 1905 if (N) return SDValue(N, 0); 1906 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1907 InsertNode(N); 1908 return SDValue(N, 0); 1909 } 1910 1911 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1912 SDNode *&N = MCSymbols[Sym]; 1913 if (N) 1914 return SDValue(N, 0); 1915 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1916 InsertNode(N); 1917 return SDValue(N, 0); 1918 } 1919 1920 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1921 unsigned TargetFlags) { 1922 SDNode *&N = 1923 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1924 if (N) return SDValue(N, 0); 1925 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1926 InsertNode(N); 1927 return SDValue(N, 0); 1928 } 1929 1930 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1931 if ((unsigned)Cond >= CondCodeNodes.size()) 1932 CondCodeNodes.resize(Cond+1); 1933 1934 if (!CondCodeNodes[Cond]) { 1935 auto *N = newSDNode<CondCodeSDNode>(Cond); 1936 CondCodeNodes[Cond] = N; 1937 InsertNode(N); 1938 } 1939 1940 return SDValue(CondCodeNodes[Cond], 0); 1941 } 1942 1943 SDValue SelectionDAG::getVScale(const SDLoc &DL, EVT VT, APInt MulImm, 1944 bool ConstantFold) { 1945 assert(MulImm.getBitWidth() == VT.getSizeInBits() && 1946 "APInt size does not match type size!"); 1947 1948 if (MulImm == 0) 1949 return getConstant(0, DL, VT); 1950 1951 if (ConstantFold) { 1952 const MachineFunction &MF = getMachineFunction(); 1953 auto Attr = MF.getFunction().getFnAttribute(Attribute::VScaleRange); 1954 if (Attr.isValid()) { 1955 unsigned VScaleMin = Attr.getVScaleRangeMin(); 1956 if (std::optional<unsigned> VScaleMax = Attr.getVScaleRangeMax()) 1957 if (*VScaleMax == VScaleMin) 1958 return getConstant(MulImm * VScaleMin, DL, VT); 1959 } 1960 } 1961 1962 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT)); 1963 } 1964 1965 SDValue SelectionDAG::getElementCount(const SDLoc &DL, EVT VT, ElementCount EC, 1966 bool ConstantFold) { 1967 if (EC.isScalable()) 1968 return getVScale(DL, VT, 1969 APInt(VT.getSizeInBits(), EC.getKnownMinValue())); 1970 1971 return getConstant(EC.getKnownMinValue(), DL, VT); 1972 } 1973 1974 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1975 APInt One(ResVT.getScalarSizeInBits(), 1); 1976 return getStepVector(DL, ResVT, One); 1977 } 1978 1979 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1980 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1981 if (ResVT.isScalableVector()) 1982 return getNode( 1983 ISD::STEP_VECTOR, DL, ResVT, 1984 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1985 1986 SmallVector<SDValue, 16> OpsStepConstants; 1987 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1988 OpsStepConstants.push_back( 1989 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1990 return getBuildVector(ResVT, DL, OpsStepConstants); 1991 } 1992 1993 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1994 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1995 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1996 std::swap(N1, N2); 1997 ShuffleVectorSDNode::commuteMask(M); 1998 } 1999 2000 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 2001 SDValue N2, ArrayRef<int> Mask) { 2002 assert(VT.getVectorNumElements() == Mask.size() && 2003 "Must have the same number of vector elements as mask elements!"); 2004 assert(VT == N1.getValueType() && VT == N2.getValueType() && 2005 "Invalid VECTOR_SHUFFLE"); 2006 2007 // Canonicalize shuffle undef, undef -> undef 2008 if (N1.isUndef() && N2.isUndef()) 2009 return getUNDEF(VT); 2010 2011 // Validate that all indices in Mask are within the range of the elements 2012 // input to the shuffle. 2013 int NElts = Mask.size(); 2014 assert(llvm::all_of(Mask, 2015 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 2016 "Index out of range"); 2017 2018 // Copy the mask so we can do any needed cleanup. 2019 SmallVector<int, 8> MaskVec(Mask); 2020 2021 // Canonicalize shuffle v, v -> v, undef 2022 if (N1 == N2) { 2023 N2 = getUNDEF(VT); 2024 for (int i = 0; i != NElts; ++i) 2025 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 2026 } 2027 2028 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 2029 if (N1.isUndef()) 2030 commuteShuffle(N1, N2, MaskVec); 2031 2032 if (TLI->hasVectorBlend()) { 2033 // If shuffling a splat, try to blend the splat instead. We do this here so 2034 // that even when this arises during lowering we don't have to re-handle it. 2035 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 2036 BitVector UndefElements; 2037 SDValue Splat = BV->getSplatValue(&UndefElements); 2038 if (!Splat) 2039 return; 2040 2041 for (int i = 0; i < NElts; ++i) { 2042 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 2043 continue; 2044 2045 // If this input comes from undef, mark it as such. 2046 if (UndefElements[MaskVec[i] - Offset]) { 2047 MaskVec[i] = -1; 2048 continue; 2049 } 2050 2051 // If we can blend a non-undef lane, use that instead. 2052 if (!UndefElements[i]) 2053 MaskVec[i] = i + Offset; 2054 } 2055 }; 2056 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 2057 BlendSplat(N1BV, 0); 2058 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 2059 BlendSplat(N2BV, NElts); 2060 } 2061 2062 // Canonicalize all index into lhs, -> shuffle lhs, undef 2063 // Canonicalize all index into rhs, -> shuffle rhs, undef 2064 bool AllLHS = true, AllRHS = true; 2065 bool N2Undef = N2.isUndef(); 2066 for (int i = 0; i != NElts; ++i) { 2067 if (MaskVec[i] >= NElts) { 2068 if (N2Undef) 2069 MaskVec[i] = -1; 2070 else 2071 AllLHS = false; 2072 } else if (MaskVec[i] >= 0) { 2073 AllRHS = false; 2074 } 2075 } 2076 if (AllLHS && AllRHS) 2077 return getUNDEF(VT); 2078 if (AllLHS && !N2Undef) 2079 N2 = getUNDEF(VT); 2080 if (AllRHS) { 2081 N1 = getUNDEF(VT); 2082 commuteShuffle(N1, N2, MaskVec); 2083 } 2084 // Reset our undef status after accounting for the mask. 2085 N2Undef = N2.isUndef(); 2086 // Re-check whether both sides ended up undef. 2087 if (N1.isUndef() && N2Undef) 2088 return getUNDEF(VT); 2089 2090 // If Identity shuffle return that node. 2091 bool Identity = true, AllSame = true; 2092 for (int i = 0; i != NElts; ++i) { 2093 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 2094 if (MaskVec[i] != MaskVec[0]) AllSame = false; 2095 } 2096 if (Identity && NElts) 2097 return N1; 2098 2099 // Shuffling a constant splat doesn't change the result. 2100 if (N2Undef) { 2101 SDValue V = N1; 2102 2103 // Look through any bitcasts. We check that these don't change the number 2104 // (and size) of elements and just changes their types. 2105 while (V.getOpcode() == ISD::BITCAST) 2106 V = V->getOperand(0); 2107 2108 // A splat should always show up as a build vector node. 2109 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 2110 BitVector UndefElements; 2111 SDValue Splat = BV->getSplatValue(&UndefElements); 2112 // If this is a splat of an undef, shuffling it is also undef. 2113 if (Splat && Splat.isUndef()) 2114 return getUNDEF(VT); 2115 2116 bool SameNumElts = 2117 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 2118 2119 // We only have a splat which can skip shuffles if there is a splatted 2120 // value and no undef lanes rearranged by the shuffle. 2121 if (Splat && UndefElements.none()) { 2122 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 2123 // number of elements match or the value splatted is a zero constant. 2124 if (SameNumElts) 2125 return N1; 2126 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 2127 if (C->isZero()) 2128 return N1; 2129 } 2130 2131 // If the shuffle itself creates a splat, build the vector directly. 2132 if (AllSame && SameNumElts) { 2133 EVT BuildVT = BV->getValueType(0); 2134 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2135 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2136 2137 // We may have jumped through bitcasts, so the type of the 2138 // BUILD_VECTOR may not match the type of the shuffle. 2139 if (BuildVT != VT) 2140 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2141 return NewBV; 2142 } 2143 } 2144 } 2145 2146 FoldingSetNodeID ID; 2147 SDValue Ops[2] = { N1, N2 }; 2148 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2149 for (int i = 0; i != NElts; ++i) 2150 ID.AddInteger(MaskVec[i]); 2151 2152 void* IP = nullptr; 2153 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2154 return SDValue(E, 0); 2155 2156 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2157 // SDNode doesn't have access to it. This memory will be "leaked" when 2158 // the node is deallocated, but recovered when the NodeAllocator is released. 2159 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2160 llvm::copy(MaskVec, MaskAlloc); 2161 2162 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2163 dl.getDebugLoc(), MaskAlloc); 2164 createOperands(N, Ops); 2165 2166 CSEMap.InsertNode(N, IP); 2167 InsertNode(N); 2168 SDValue V = SDValue(N, 0); 2169 NewSDValueDbgMsg(V, "Creating new node: ", this); 2170 return V; 2171 } 2172 2173 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2174 EVT VT = SV.getValueType(0); 2175 SmallVector<int, 8> MaskVec(SV.getMask()); 2176 ShuffleVectorSDNode::commuteMask(MaskVec); 2177 2178 SDValue Op0 = SV.getOperand(0); 2179 SDValue Op1 = SV.getOperand(1); 2180 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2181 } 2182 2183 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2184 FoldingSetNodeID ID; 2185 AddNodeIDNode(ID, ISD::Register, getVTList(VT), std::nullopt); 2186 ID.AddInteger(RegNo); 2187 void *IP = nullptr; 2188 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2189 return SDValue(E, 0); 2190 2191 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2192 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA); 2193 CSEMap.InsertNode(N, IP); 2194 InsertNode(N); 2195 return SDValue(N, 0); 2196 } 2197 2198 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2199 FoldingSetNodeID ID; 2200 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), std::nullopt); 2201 ID.AddPointer(RegMask); 2202 void *IP = nullptr; 2203 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2204 return SDValue(E, 0); 2205 2206 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2207 CSEMap.InsertNode(N, IP); 2208 InsertNode(N); 2209 return SDValue(N, 0); 2210 } 2211 2212 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2213 MCSymbol *Label) { 2214 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2215 } 2216 2217 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2218 SDValue Root, MCSymbol *Label) { 2219 FoldingSetNodeID ID; 2220 SDValue Ops[] = { Root }; 2221 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2222 ID.AddPointer(Label); 2223 void *IP = nullptr; 2224 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2225 return SDValue(E, 0); 2226 2227 auto *N = 2228 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2229 createOperands(N, Ops); 2230 2231 CSEMap.InsertNode(N, IP); 2232 InsertNode(N); 2233 return SDValue(N, 0); 2234 } 2235 2236 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2237 int64_t Offset, bool isTarget, 2238 unsigned TargetFlags) { 2239 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2240 2241 FoldingSetNodeID ID; 2242 AddNodeIDNode(ID, Opc, getVTList(VT), std::nullopt); 2243 ID.AddPointer(BA); 2244 ID.AddInteger(Offset); 2245 ID.AddInteger(TargetFlags); 2246 void *IP = nullptr; 2247 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2248 return SDValue(E, 0); 2249 2250 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2251 CSEMap.InsertNode(N, IP); 2252 InsertNode(N); 2253 return SDValue(N, 0); 2254 } 2255 2256 SDValue SelectionDAG::getSrcValue(const Value *V) { 2257 FoldingSetNodeID ID; 2258 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), std::nullopt); 2259 ID.AddPointer(V); 2260 2261 void *IP = nullptr; 2262 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2263 return SDValue(E, 0); 2264 2265 auto *N = newSDNode<SrcValueSDNode>(V); 2266 CSEMap.InsertNode(N, IP); 2267 InsertNode(N); 2268 return SDValue(N, 0); 2269 } 2270 2271 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2272 FoldingSetNodeID ID; 2273 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), std::nullopt); 2274 ID.AddPointer(MD); 2275 2276 void *IP = nullptr; 2277 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2278 return SDValue(E, 0); 2279 2280 auto *N = newSDNode<MDNodeSDNode>(MD); 2281 CSEMap.InsertNode(N, IP); 2282 InsertNode(N); 2283 return SDValue(N, 0); 2284 } 2285 2286 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2287 if (VT == V.getValueType()) 2288 return V; 2289 2290 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2291 } 2292 2293 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2294 unsigned SrcAS, unsigned DestAS) { 2295 SDValue Ops[] = {Ptr}; 2296 FoldingSetNodeID ID; 2297 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2298 ID.AddInteger(SrcAS); 2299 ID.AddInteger(DestAS); 2300 2301 void *IP = nullptr; 2302 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2303 return SDValue(E, 0); 2304 2305 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2306 VT, SrcAS, DestAS); 2307 createOperands(N, Ops); 2308 2309 CSEMap.InsertNode(N, IP); 2310 InsertNode(N); 2311 return SDValue(N, 0); 2312 } 2313 2314 SDValue SelectionDAG::getFreeze(SDValue V) { 2315 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2316 } 2317 2318 /// getShiftAmountOperand - Return the specified value casted to 2319 /// the target's desired shift amount type. 2320 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2321 EVT OpTy = Op.getValueType(); 2322 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2323 if (OpTy == ShTy || OpTy.isVector()) return Op; 2324 2325 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2326 } 2327 2328 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2329 SDLoc dl(Node); 2330 const TargetLowering &TLI = getTargetLoweringInfo(); 2331 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2332 EVT VT = Node->getValueType(0); 2333 SDValue Tmp1 = Node->getOperand(0); 2334 SDValue Tmp2 = Node->getOperand(1); 2335 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2336 2337 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2338 Tmp2, MachinePointerInfo(V)); 2339 SDValue VAList = VAListLoad; 2340 2341 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2342 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2343 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2344 2345 VAList = 2346 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2347 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2348 } 2349 2350 // Increment the pointer, VAList, to the next vaarg 2351 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2352 getConstant(getDataLayout().getTypeAllocSize( 2353 VT.getTypeForEVT(*getContext())), 2354 dl, VAList.getValueType())); 2355 // Store the incremented VAList to the legalized pointer 2356 Tmp1 = 2357 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2358 // Load the actual argument out of the pointer VAList 2359 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2360 } 2361 2362 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2363 SDLoc dl(Node); 2364 const TargetLowering &TLI = getTargetLoweringInfo(); 2365 // This defaults to loading a pointer from the input and storing it to the 2366 // output, returning the chain. 2367 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2368 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2369 SDValue Tmp1 = 2370 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2371 Node->getOperand(2), MachinePointerInfo(VS)); 2372 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2373 MachinePointerInfo(VD)); 2374 } 2375 2376 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2377 const DataLayout &DL = getDataLayout(); 2378 Type *Ty = VT.getTypeForEVT(*getContext()); 2379 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2380 2381 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2382 return RedAlign; 2383 2384 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2385 const Align StackAlign = TFI->getStackAlign(); 2386 2387 // See if we can choose a smaller ABI alignment in cases where it's an 2388 // illegal vector type that will get broken down. 2389 if (RedAlign > StackAlign) { 2390 EVT IntermediateVT; 2391 MVT RegisterVT; 2392 unsigned NumIntermediates; 2393 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2394 NumIntermediates, RegisterVT); 2395 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2396 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2397 if (RedAlign2 < RedAlign) 2398 RedAlign = RedAlign2; 2399 } 2400 2401 return RedAlign; 2402 } 2403 2404 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2405 MachineFrameInfo &MFI = MF->getFrameInfo(); 2406 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2407 int StackID = 0; 2408 if (Bytes.isScalable()) 2409 StackID = TFI->getStackIDForScalableVectors(); 2410 // The stack id gives an indication of whether the object is scalable or 2411 // not, so it's safe to pass in the minimum size here. 2412 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment, 2413 false, nullptr, StackID); 2414 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2415 } 2416 2417 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2418 Type *Ty = VT.getTypeForEVT(*getContext()); 2419 Align StackAlign = 2420 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2421 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2422 } 2423 2424 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2425 TypeSize VT1Size = VT1.getStoreSize(); 2426 TypeSize VT2Size = VT2.getStoreSize(); 2427 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2428 "Don't know how to choose the maximum size when creating a stack " 2429 "temporary"); 2430 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue() 2431 ? VT1Size 2432 : VT2Size; 2433 2434 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2435 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2436 const DataLayout &DL = getDataLayout(); 2437 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2438 return CreateStackTemporary(Bytes, Align); 2439 } 2440 2441 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2442 ISD::CondCode Cond, const SDLoc &dl) { 2443 EVT OpVT = N1.getValueType(); 2444 2445 auto GetUndefBooleanConstant = [&]() { 2446 if (VT.getScalarType() == MVT::i1 || 2447 TLI->getBooleanContents(OpVT) == 2448 TargetLowering::UndefinedBooleanContent) 2449 return getUNDEF(VT); 2450 // ZeroOrOne / ZeroOrNegative require specific values for the high bits, 2451 // so we cannot use getUNDEF(). Return zero instead. 2452 return getConstant(0, dl, VT); 2453 }; 2454 2455 // These setcc operations always fold. 2456 switch (Cond) { 2457 default: break; 2458 case ISD::SETFALSE: 2459 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2460 case ISD::SETTRUE: 2461 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2462 2463 case ISD::SETOEQ: 2464 case ISD::SETOGT: 2465 case ISD::SETOGE: 2466 case ISD::SETOLT: 2467 case ISD::SETOLE: 2468 case ISD::SETONE: 2469 case ISD::SETO: 2470 case ISD::SETUO: 2471 case ISD::SETUEQ: 2472 case ISD::SETUNE: 2473 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2474 break; 2475 } 2476 2477 if (OpVT.isInteger()) { 2478 // For EQ and NE, we can always pick a value for the undef to make the 2479 // predicate pass or fail, so we can return undef. 2480 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2481 // icmp eq/ne X, undef -> undef. 2482 if ((N1.isUndef() || N2.isUndef()) && 2483 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2484 return GetUndefBooleanConstant(); 2485 2486 // If both operands are undef, we can return undef for int comparison. 2487 // icmp undef, undef -> undef. 2488 if (N1.isUndef() && N2.isUndef()) 2489 return GetUndefBooleanConstant(); 2490 2491 // icmp X, X -> true/false 2492 // icmp X, undef -> true/false because undef could be X. 2493 if (N1 == N2) 2494 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2495 } 2496 2497 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2498 const APInt &C2 = N2C->getAPIntValue(); 2499 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2500 const APInt &C1 = N1C->getAPIntValue(); 2501 2502 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2503 dl, VT, OpVT); 2504 } 2505 } 2506 2507 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2508 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2509 2510 if (N1CFP && N2CFP) { 2511 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2512 switch (Cond) { 2513 default: break; 2514 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2515 return GetUndefBooleanConstant(); 2516 [[fallthrough]]; 2517 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2518 OpVT); 2519 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2520 return GetUndefBooleanConstant(); 2521 [[fallthrough]]; 2522 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2523 R==APFloat::cmpLessThan, dl, VT, 2524 OpVT); 2525 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2526 return GetUndefBooleanConstant(); 2527 [[fallthrough]]; 2528 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2529 OpVT); 2530 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2531 return GetUndefBooleanConstant(); 2532 [[fallthrough]]; 2533 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2534 VT, OpVT); 2535 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2536 return GetUndefBooleanConstant(); 2537 [[fallthrough]]; 2538 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2539 R==APFloat::cmpEqual, dl, VT, 2540 OpVT); 2541 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2542 return GetUndefBooleanConstant(); 2543 [[fallthrough]]; 2544 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2545 R==APFloat::cmpEqual, dl, VT, OpVT); 2546 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2547 OpVT); 2548 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2549 OpVT); 2550 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2551 R==APFloat::cmpEqual, dl, VT, 2552 OpVT); 2553 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2554 OpVT); 2555 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2556 R==APFloat::cmpLessThan, dl, VT, 2557 OpVT); 2558 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2559 R==APFloat::cmpUnordered, dl, VT, 2560 OpVT); 2561 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2562 VT, OpVT); 2563 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2564 OpVT); 2565 } 2566 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2567 // Ensure that the constant occurs on the RHS. 2568 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2569 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2570 return SDValue(); 2571 return getSetCC(dl, VT, N2, N1, SwappedCond); 2572 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2573 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2574 // If an operand is known to be a nan (or undef that could be a nan), we can 2575 // fold it. 2576 // Choosing NaN for the undef will always make unordered comparison succeed 2577 // and ordered comparison fails. 2578 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2579 switch (ISD::getUnorderedFlavor(Cond)) { 2580 default: 2581 llvm_unreachable("Unknown flavor!"); 2582 case 0: // Known false. 2583 return getBoolConstant(false, dl, VT, OpVT); 2584 case 1: // Known true. 2585 return getBoolConstant(true, dl, VT, OpVT); 2586 case 2: // Undefined. 2587 return GetUndefBooleanConstant(); 2588 } 2589 } 2590 2591 // Could not fold it. 2592 return SDValue(); 2593 } 2594 2595 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2596 /// use this predicate to simplify operations downstream. 2597 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2598 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2599 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2600 } 2601 2602 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2603 /// this predicate to simplify operations downstream. Mask is known to be zero 2604 /// for bits that V cannot have. 2605 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2606 unsigned Depth) const { 2607 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2608 } 2609 2610 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2611 /// DemandedElts. We use this predicate to simplify operations downstream. 2612 /// Mask is known to be zero for bits that V cannot have. 2613 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2614 const APInt &DemandedElts, 2615 unsigned Depth) const { 2616 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2617 } 2618 2619 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in 2620 /// DemandedElts. We use this predicate to simplify operations downstream. 2621 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts, 2622 unsigned Depth /* = 0 */) const { 2623 return computeKnownBits(V, DemandedElts, Depth).isZero(); 2624 } 2625 2626 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2627 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2628 unsigned Depth) const { 2629 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2630 } 2631 2632 APInt SelectionDAG::computeVectorKnownZeroElements(SDValue Op, 2633 const APInt &DemandedElts, 2634 unsigned Depth) const { 2635 EVT VT = Op.getValueType(); 2636 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!"); 2637 2638 unsigned NumElts = VT.getVectorNumElements(); 2639 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask."); 2640 2641 APInt KnownZeroElements = APInt::getZero(NumElts); 2642 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) { 2643 if (!DemandedElts[EltIdx]) 2644 continue; // Don't query elements that are not demanded. 2645 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx); 2646 if (MaskedVectorIsZero(Op, Mask, Depth)) 2647 KnownZeroElements.setBit(EltIdx); 2648 } 2649 return KnownZeroElements; 2650 } 2651 2652 /// isSplatValue - Return true if the vector V has the same value 2653 /// across all DemandedElts. For scalable vectors, we don't know the 2654 /// number of lanes at compile time. Instead, we use a 1 bit APInt 2655 /// to represent a conservative value for all lanes; that is, that 2656 /// one bit value is implicitly splatted across all lanes. 2657 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2658 APInt &UndefElts, unsigned Depth) const { 2659 unsigned Opcode = V.getOpcode(); 2660 EVT VT = V.getValueType(); 2661 assert(VT.isVector() && "Vector type expected"); 2662 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) && 2663 "scalable demanded bits are ignored"); 2664 2665 if (!DemandedElts) 2666 return false; // No demanded elts, better to assume we don't know anything. 2667 2668 if (Depth >= MaxRecursionDepth) 2669 return false; // Limit search depth. 2670 2671 // Deal with some common cases here that work for both fixed and scalable 2672 // vector types. 2673 switch (Opcode) { 2674 case ISD::SPLAT_VECTOR: 2675 UndefElts = V.getOperand(0).isUndef() 2676 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2677 : APInt(DemandedElts.getBitWidth(), 0); 2678 return true; 2679 case ISD::ADD: 2680 case ISD::SUB: 2681 case ISD::AND: 2682 case ISD::XOR: 2683 case ISD::OR: { 2684 APInt UndefLHS, UndefRHS; 2685 SDValue LHS = V.getOperand(0); 2686 SDValue RHS = V.getOperand(1); 2687 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2688 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2689 UndefElts = UndefLHS | UndefRHS; 2690 return true; 2691 } 2692 return false; 2693 } 2694 case ISD::ABS: 2695 case ISD::TRUNCATE: 2696 case ISD::SIGN_EXTEND: 2697 case ISD::ZERO_EXTEND: 2698 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2699 default: 2700 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2701 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2702 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this, 2703 Depth); 2704 break; 2705 } 2706 2707 // We don't support other cases than those above for scalable vectors at 2708 // the moment. 2709 if (VT.isScalableVector()) 2710 return false; 2711 2712 unsigned NumElts = VT.getVectorNumElements(); 2713 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2714 UndefElts = APInt::getZero(NumElts); 2715 2716 switch (Opcode) { 2717 case ISD::BUILD_VECTOR: { 2718 SDValue Scl; 2719 for (unsigned i = 0; i != NumElts; ++i) { 2720 SDValue Op = V.getOperand(i); 2721 if (Op.isUndef()) { 2722 UndefElts.setBit(i); 2723 continue; 2724 } 2725 if (!DemandedElts[i]) 2726 continue; 2727 if (Scl && Scl != Op) 2728 return false; 2729 Scl = Op; 2730 } 2731 return true; 2732 } 2733 case ISD::VECTOR_SHUFFLE: { 2734 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2735 APInt DemandedLHS = APInt::getZero(NumElts); 2736 APInt DemandedRHS = APInt::getZero(NumElts); 2737 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2738 for (int i = 0; i != (int)NumElts; ++i) { 2739 int M = Mask[i]; 2740 if (M < 0) { 2741 UndefElts.setBit(i); 2742 continue; 2743 } 2744 if (!DemandedElts[i]) 2745 continue; 2746 if (M < (int)NumElts) 2747 DemandedLHS.setBit(M); 2748 else 2749 DemandedRHS.setBit(M - NumElts); 2750 } 2751 2752 // If we aren't demanding either op, assume there's no splat. 2753 // If we are demanding both ops, assume there's no splat. 2754 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2755 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2756 return false; 2757 2758 // See if the demanded elts of the source op is a splat or we only demand 2759 // one element, which should always be a splat. 2760 // TODO: Handle source ops splats with undefs. 2761 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2762 APInt SrcUndefs; 2763 return (SrcElts.popcount() == 1) || 2764 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2765 (SrcElts & SrcUndefs).isZero()); 2766 }; 2767 if (!DemandedLHS.isZero()) 2768 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2769 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2770 } 2771 case ISD::EXTRACT_SUBVECTOR: { 2772 // Offset the demanded elts by the subvector index. 2773 SDValue Src = V.getOperand(0); 2774 // We don't support scalable vectors at the moment. 2775 if (Src.getValueType().isScalableVector()) 2776 return false; 2777 uint64_t Idx = V.getConstantOperandVal(1); 2778 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2779 APInt UndefSrcElts; 2780 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 2781 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2782 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2783 return true; 2784 } 2785 break; 2786 } 2787 case ISD::ANY_EXTEND_VECTOR_INREG: 2788 case ISD::SIGN_EXTEND_VECTOR_INREG: 2789 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2790 // Widen the demanded elts by the src element count. 2791 SDValue Src = V.getOperand(0); 2792 // We don't support scalable vectors at the moment. 2793 if (Src.getValueType().isScalableVector()) 2794 return false; 2795 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2796 APInt UndefSrcElts; 2797 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 2798 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2799 UndefElts = UndefSrcElts.trunc(NumElts); 2800 return true; 2801 } 2802 break; 2803 } 2804 case ISD::BITCAST: { 2805 SDValue Src = V.getOperand(0); 2806 EVT SrcVT = Src.getValueType(); 2807 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2808 unsigned BitWidth = VT.getScalarSizeInBits(); 2809 2810 // Ignore bitcasts from unsupported types. 2811 // TODO: Add fp support? 2812 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2813 break; 2814 2815 // Bitcast 'small element' vector to 'large element' vector. 2816 if ((BitWidth % SrcBitWidth) == 0) { 2817 // See if each sub element is a splat. 2818 unsigned Scale = BitWidth / SrcBitWidth; 2819 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2820 APInt ScaledDemandedElts = 2821 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2822 for (unsigned I = 0; I != Scale; ++I) { 2823 APInt SubUndefElts; 2824 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2825 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2826 SubDemandedElts &= ScaledDemandedElts; 2827 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2828 return false; 2829 // TODO: Add support for merging sub undef elements. 2830 if (!SubUndefElts.isZero()) 2831 return false; 2832 } 2833 return true; 2834 } 2835 break; 2836 } 2837 } 2838 2839 return false; 2840 } 2841 2842 /// Helper wrapper to main isSplatValue function. 2843 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2844 EVT VT = V.getValueType(); 2845 assert(VT.isVector() && "Vector type expected"); 2846 2847 APInt UndefElts; 2848 // Since the number of lanes in a scalable vector is unknown at compile time, 2849 // we track one bit which is implicitly broadcast to all lanes. This means 2850 // that all lanes in a scalable vector are considered demanded. 2851 APInt DemandedElts 2852 = APInt::getAllOnes(VT.isScalableVector() ? 1 : VT.getVectorNumElements()); 2853 return isSplatValue(V, DemandedElts, UndefElts) && 2854 (AllowUndefs || !UndefElts); 2855 } 2856 2857 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2858 V = peekThroughExtractSubvectors(V); 2859 2860 EVT VT = V.getValueType(); 2861 unsigned Opcode = V.getOpcode(); 2862 switch (Opcode) { 2863 default: { 2864 APInt UndefElts; 2865 // Since the number of lanes in a scalable vector is unknown at compile time, 2866 // we track one bit which is implicitly broadcast to all lanes. This means 2867 // that all lanes in a scalable vector are considered demanded. 2868 APInt DemandedElts 2869 = APInt::getAllOnes(VT.isScalableVector() ? 1 : VT.getVectorNumElements()); 2870 2871 if (isSplatValue(V, DemandedElts, UndefElts)) { 2872 if (VT.isScalableVector()) { 2873 // DemandedElts and UndefElts are ignored for scalable vectors, since 2874 // the only supported cases are SPLAT_VECTOR nodes. 2875 SplatIdx = 0; 2876 } else { 2877 // Handle case where all demanded elements are UNDEF. 2878 if (DemandedElts.isSubsetOf(UndefElts)) { 2879 SplatIdx = 0; 2880 return getUNDEF(VT); 2881 } 2882 SplatIdx = (UndefElts & DemandedElts).countr_one(); 2883 } 2884 return V; 2885 } 2886 break; 2887 } 2888 case ISD::SPLAT_VECTOR: 2889 SplatIdx = 0; 2890 return V; 2891 case ISD::VECTOR_SHUFFLE: { 2892 assert(!VT.isScalableVector()); 2893 // Check if this is a shuffle node doing a splat. 2894 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2895 // getTargetVShiftNode currently struggles without the splat source. 2896 auto *SVN = cast<ShuffleVectorSDNode>(V); 2897 if (!SVN->isSplat()) 2898 break; 2899 int Idx = SVN->getSplatIndex(); 2900 int NumElts = V.getValueType().getVectorNumElements(); 2901 SplatIdx = Idx % NumElts; 2902 return V.getOperand(Idx / NumElts); 2903 } 2904 } 2905 2906 return SDValue(); 2907 } 2908 2909 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2910 int SplatIdx; 2911 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2912 EVT SVT = SrcVector.getValueType().getScalarType(); 2913 EVT LegalSVT = SVT; 2914 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2915 if (!SVT.isInteger()) 2916 return SDValue(); 2917 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2918 if (LegalSVT.bitsLT(SVT)) 2919 return SDValue(); 2920 } 2921 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2922 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2923 } 2924 return SDValue(); 2925 } 2926 2927 const APInt * 2928 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2929 const APInt &DemandedElts) const { 2930 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2931 V.getOpcode() == ISD::SRA) && 2932 "Unknown shift node"); 2933 unsigned BitWidth = V.getScalarValueSizeInBits(); 2934 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2935 // Shifting more than the bitwidth is not valid. 2936 const APInt &ShAmt = SA->getAPIntValue(); 2937 if (ShAmt.ult(BitWidth)) 2938 return &ShAmt; 2939 } 2940 return nullptr; 2941 } 2942 2943 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2944 SDValue V, const APInt &DemandedElts) const { 2945 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2946 V.getOpcode() == ISD::SRA) && 2947 "Unknown shift node"); 2948 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2949 return ValidAmt; 2950 unsigned BitWidth = V.getScalarValueSizeInBits(); 2951 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2952 if (!BV) 2953 return nullptr; 2954 const APInt *MinShAmt = nullptr; 2955 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2956 if (!DemandedElts[i]) 2957 continue; 2958 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2959 if (!SA) 2960 return nullptr; 2961 // Shifting more than the bitwidth is not valid. 2962 const APInt &ShAmt = SA->getAPIntValue(); 2963 if (ShAmt.uge(BitWidth)) 2964 return nullptr; 2965 if (MinShAmt && MinShAmt->ule(ShAmt)) 2966 continue; 2967 MinShAmt = &ShAmt; 2968 } 2969 return MinShAmt; 2970 } 2971 2972 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2973 SDValue V, const APInt &DemandedElts) const { 2974 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2975 V.getOpcode() == ISD::SRA) && 2976 "Unknown shift node"); 2977 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2978 return ValidAmt; 2979 unsigned BitWidth = V.getScalarValueSizeInBits(); 2980 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2981 if (!BV) 2982 return nullptr; 2983 const APInt *MaxShAmt = nullptr; 2984 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2985 if (!DemandedElts[i]) 2986 continue; 2987 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2988 if (!SA) 2989 return nullptr; 2990 // Shifting more than the bitwidth is not valid. 2991 const APInt &ShAmt = SA->getAPIntValue(); 2992 if (ShAmt.uge(BitWidth)) 2993 return nullptr; 2994 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2995 continue; 2996 MaxShAmt = &ShAmt; 2997 } 2998 return MaxShAmt; 2999 } 3000 3001 /// Determine which bits of Op are known to be either zero or one and return 3002 /// them in Known. For vectors, the known bits are those that are shared by 3003 /// every vector element. 3004 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 3005 EVT VT = Op.getValueType(); 3006 3007 // Since the number of lanes in a scalable vector is unknown at compile time, 3008 // we track one bit which is implicitly broadcast to all lanes. This means 3009 // that all lanes in a scalable vector are considered demanded. 3010 APInt DemandedElts = VT.isFixedLengthVector() 3011 ? APInt::getAllOnes(VT.getVectorNumElements()) 3012 : APInt(1, 1); 3013 return computeKnownBits(Op, DemandedElts, Depth); 3014 } 3015 3016 /// Determine which bits of Op are known to be either zero or one and return 3017 /// them in Known. The DemandedElts argument allows us to only collect the known 3018 /// bits that are shared by the requested vector elements. 3019 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 3020 unsigned Depth) const { 3021 unsigned BitWidth = Op.getScalarValueSizeInBits(); 3022 3023 KnownBits Known(BitWidth); // Don't know anything. 3024 3025 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3026 // We know all of the bits for a constant! 3027 return KnownBits::makeConstant(C->getAPIntValue()); 3028 } 3029 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 3030 // We know all of the bits for a constant fp! 3031 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 3032 } 3033 3034 if (Depth >= MaxRecursionDepth) 3035 return Known; // Limit search depth. 3036 3037 KnownBits Known2; 3038 unsigned NumElts = DemandedElts.getBitWidth(); 3039 assert((!Op.getValueType().isFixedLengthVector() || 3040 NumElts == Op.getValueType().getVectorNumElements()) && 3041 "Unexpected vector size"); 3042 3043 if (!DemandedElts) 3044 return Known; // No demanded elts, better to assume we don't know anything. 3045 3046 unsigned Opcode = Op.getOpcode(); 3047 switch (Opcode) { 3048 case ISD::MERGE_VALUES: 3049 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts, 3050 Depth + 1); 3051 case ISD::SPLAT_VECTOR: { 3052 SDValue SrcOp = Op.getOperand(0); 3053 assert(SrcOp.getValueSizeInBits() >= BitWidth && 3054 "Expected SPLAT_VECTOR implicit truncation"); 3055 // Implicitly truncate the bits to match the official semantics of 3056 // SPLAT_VECTOR. 3057 Known = computeKnownBits(SrcOp, Depth + 1).trunc(BitWidth); 3058 break; 3059 } 3060 case ISD::BUILD_VECTOR: 3061 assert(!Op.getValueType().isScalableVector()); 3062 // Collect the known bits that are shared by every demanded vector element. 3063 Known.Zero.setAllBits(); Known.One.setAllBits(); 3064 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 3065 if (!DemandedElts[i]) 3066 continue; 3067 3068 SDValue SrcOp = Op.getOperand(i); 3069 Known2 = computeKnownBits(SrcOp, Depth + 1); 3070 3071 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3072 if (SrcOp.getValueSizeInBits() != BitWidth) { 3073 assert(SrcOp.getValueSizeInBits() > BitWidth && 3074 "Expected BUILD_VECTOR implicit truncation"); 3075 Known2 = Known2.trunc(BitWidth); 3076 } 3077 3078 // Known bits are the values that are shared by every demanded element. 3079 Known = Known.intersectWith(Known2); 3080 3081 // If we don't know any bits, early out. 3082 if (Known.isUnknown()) 3083 break; 3084 } 3085 break; 3086 case ISD::VECTOR_SHUFFLE: { 3087 assert(!Op.getValueType().isScalableVector()); 3088 // Collect the known bits that are shared by every vector element referenced 3089 // by the shuffle. 3090 APInt DemandedLHS, DemandedRHS; 3091 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3092 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3093 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts, 3094 DemandedLHS, DemandedRHS)) 3095 break; 3096 3097 // Known bits are the values that are shared by every demanded element. 3098 Known.Zero.setAllBits(); Known.One.setAllBits(); 3099 if (!!DemandedLHS) { 3100 SDValue LHS = Op.getOperand(0); 3101 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 3102 Known = Known.intersectWith(Known2); 3103 } 3104 // If we don't know any bits, early out. 3105 if (Known.isUnknown()) 3106 break; 3107 if (!!DemandedRHS) { 3108 SDValue RHS = Op.getOperand(1); 3109 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3110 Known = Known.intersectWith(Known2); 3111 } 3112 break; 3113 } 3114 case ISD::VSCALE: { 3115 const Function &F = getMachineFunction().getFunction(); 3116 const APInt &Multiplier = Op.getConstantOperandAPInt(0); 3117 Known = getVScaleRange(&F, BitWidth).multiply(Multiplier).toKnownBits(); 3118 break; 3119 } 3120 case ISD::CONCAT_VECTORS: { 3121 if (Op.getValueType().isScalableVector()) 3122 break; 3123 // Split DemandedElts and test each of the demanded subvectors. 3124 Known.Zero.setAllBits(); Known.One.setAllBits(); 3125 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3126 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3127 unsigned NumSubVectors = Op.getNumOperands(); 3128 for (unsigned i = 0; i != NumSubVectors; ++i) { 3129 APInt DemandedSub = 3130 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3131 if (!!DemandedSub) { 3132 SDValue Sub = Op.getOperand(i); 3133 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3134 Known = Known.intersectWith(Known2); 3135 } 3136 // If we don't know any bits, early out. 3137 if (Known.isUnknown()) 3138 break; 3139 } 3140 break; 3141 } 3142 case ISD::INSERT_SUBVECTOR: { 3143 if (Op.getValueType().isScalableVector()) 3144 break; 3145 // Demand any elements from the subvector and the remainder from the src its 3146 // inserted into. 3147 SDValue Src = Op.getOperand(0); 3148 SDValue Sub = Op.getOperand(1); 3149 uint64_t Idx = Op.getConstantOperandVal(2); 3150 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3151 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3152 APInt DemandedSrcElts = DemandedElts; 3153 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3154 3155 Known.One.setAllBits(); 3156 Known.Zero.setAllBits(); 3157 if (!!DemandedSubElts) { 3158 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3159 if (Known.isUnknown()) 3160 break; // early-out. 3161 } 3162 if (!!DemandedSrcElts) { 3163 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3164 Known = Known.intersectWith(Known2); 3165 } 3166 break; 3167 } 3168 case ISD::EXTRACT_SUBVECTOR: { 3169 // Offset the demanded elts by the subvector index. 3170 SDValue Src = Op.getOperand(0); 3171 // Bail until we can represent demanded elements for scalable vectors. 3172 if (Op.getValueType().isScalableVector() || Src.getValueType().isScalableVector()) 3173 break; 3174 uint64_t Idx = Op.getConstantOperandVal(1); 3175 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3176 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3177 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3178 break; 3179 } 3180 case ISD::SCALAR_TO_VECTOR: { 3181 if (Op.getValueType().isScalableVector()) 3182 break; 3183 // We know about scalar_to_vector as much as we know about it source, 3184 // which becomes the first element of otherwise unknown vector. 3185 if (DemandedElts != 1) 3186 break; 3187 3188 SDValue N0 = Op.getOperand(0); 3189 Known = computeKnownBits(N0, Depth + 1); 3190 if (N0.getValueSizeInBits() != BitWidth) 3191 Known = Known.trunc(BitWidth); 3192 3193 break; 3194 } 3195 case ISD::BITCAST: { 3196 if (Op.getValueType().isScalableVector()) 3197 break; 3198 3199 SDValue N0 = Op.getOperand(0); 3200 EVT SubVT = N0.getValueType(); 3201 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3202 3203 // Ignore bitcasts from unsupported types. 3204 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3205 break; 3206 3207 // Fast handling of 'identity' bitcasts. 3208 if (BitWidth == SubBitWidth) { 3209 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3210 break; 3211 } 3212 3213 bool IsLE = getDataLayout().isLittleEndian(); 3214 3215 // Bitcast 'small element' vector to 'large element' scalar/vector. 3216 if ((BitWidth % SubBitWidth) == 0) { 3217 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3218 3219 // Collect known bits for the (larger) output by collecting the known 3220 // bits from each set of sub elements and shift these into place. 3221 // We need to separately call computeKnownBits for each set of 3222 // sub elements as the knownbits for each is likely to be different. 3223 unsigned SubScale = BitWidth / SubBitWidth; 3224 APInt SubDemandedElts(NumElts * SubScale, 0); 3225 for (unsigned i = 0; i != NumElts; ++i) 3226 if (DemandedElts[i]) 3227 SubDemandedElts.setBit(i * SubScale); 3228 3229 for (unsigned i = 0; i != SubScale; ++i) { 3230 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3231 Depth + 1); 3232 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3233 Known.insertBits(Known2, SubBitWidth * Shifts); 3234 } 3235 } 3236 3237 // Bitcast 'large element' scalar/vector to 'small element' vector. 3238 if ((SubBitWidth % BitWidth) == 0) { 3239 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3240 3241 // Collect known bits for the (smaller) output by collecting the known 3242 // bits from the overlapping larger input elements and extracting the 3243 // sub sections we actually care about. 3244 unsigned SubScale = SubBitWidth / BitWidth; 3245 APInt SubDemandedElts = 3246 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3247 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3248 3249 Known.Zero.setAllBits(); Known.One.setAllBits(); 3250 for (unsigned i = 0; i != NumElts; ++i) 3251 if (DemandedElts[i]) { 3252 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3253 unsigned Offset = (Shifts % SubScale) * BitWidth; 3254 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset)); 3255 // If we don't know any bits, early out. 3256 if (Known.isUnknown()) 3257 break; 3258 } 3259 } 3260 break; 3261 } 3262 case ISD::AND: 3263 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3264 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3265 3266 Known &= Known2; 3267 break; 3268 case ISD::OR: 3269 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3270 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3271 3272 Known |= Known2; 3273 break; 3274 case ISD::XOR: 3275 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3276 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3277 3278 Known ^= Known2; 3279 break; 3280 case ISD::MUL: { 3281 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3282 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3283 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3284 // TODO: SelfMultiply can be poison, but not undef. 3285 if (SelfMultiply) 3286 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3287 Op.getOperand(0), DemandedElts, false, Depth + 1); 3288 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3289 3290 // If the multiplication is known not to overflow, the product of a number 3291 // with itself is non-negative. Only do this if we didn't already computed 3292 // the opposite value for the sign bit. 3293 if (Op->getFlags().hasNoSignedWrap() && 3294 Op.getOperand(0) == Op.getOperand(1) && 3295 !Known.isNegative()) 3296 Known.makeNonNegative(); 3297 break; 3298 } 3299 case ISD::MULHU: { 3300 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3301 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3302 Known = KnownBits::mulhu(Known, Known2); 3303 break; 3304 } 3305 case ISD::MULHS: { 3306 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3307 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3308 Known = KnownBits::mulhs(Known, Known2); 3309 break; 3310 } 3311 case ISD::UMUL_LOHI: { 3312 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3313 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3314 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3315 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3316 if (Op.getResNo() == 0) 3317 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3318 else 3319 Known = KnownBits::mulhu(Known, Known2); 3320 break; 3321 } 3322 case ISD::SMUL_LOHI: { 3323 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3324 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3325 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3326 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3327 if (Op.getResNo() == 0) 3328 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3329 else 3330 Known = KnownBits::mulhs(Known, Known2); 3331 break; 3332 } 3333 case ISD::AVGCEILU: { 3334 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3335 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3336 Known = Known.zext(BitWidth + 1); 3337 Known2 = Known2.zext(BitWidth + 1); 3338 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3339 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3340 Known = Known.extractBits(BitWidth, 1); 3341 break; 3342 } 3343 case ISD::SELECT: 3344 case ISD::VSELECT: 3345 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3346 // If we don't know any bits, early out. 3347 if (Known.isUnknown()) 3348 break; 3349 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3350 3351 // Only known if known in both the LHS and RHS. 3352 Known = Known.intersectWith(Known2); 3353 break; 3354 case ISD::SELECT_CC: 3355 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3356 // If we don't know any bits, early out. 3357 if (Known.isUnknown()) 3358 break; 3359 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3360 3361 // Only known if known in both the LHS and RHS. 3362 Known = Known.intersectWith(Known2); 3363 break; 3364 case ISD::SMULO: 3365 case ISD::UMULO: 3366 if (Op.getResNo() != 1) 3367 break; 3368 // The boolean result conforms to getBooleanContents. 3369 // If we know the result of a setcc has the top bits zero, use this info. 3370 // We know that we have an integer-based boolean since these operations 3371 // are only available for integer. 3372 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3373 TargetLowering::ZeroOrOneBooleanContent && 3374 BitWidth > 1) 3375 Known.Zero.setBitsFrom(1); 3376 break; 3377 case ISD::SETCC: 3378 case ISD::SETCCCARRY: 3379 case ISD::STRICT_FSETCC: 3380 case ISD::STRICT_FSETCCS: { 3381 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3382 // If we know the result of a setcc has the top bits zero, use this info. 3383 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3384 TargetLowering::ZeroOrOneBooleanContent && 3385 BitWidth > 1) 3386 Known.Zero.setBitsFrom(1); 3387 break; 3388 } 3389 case ISD::SHL: 3390 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3391 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3392 Known = KnownBits::shl(Known, Known2); 3393 3394 // Minimum shift low bits are known zero. 3395 if (const APInt *ShMinAmt = 3396 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3397 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3398 break; 3399 case ISD::SRL: 3400 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3401 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3402 Known = KnownBits::lshr(Known, Known2); 3403 3404 // Minimum shift high bits are known zero. 3405 if (const APInt *ShMinAmt = 3406 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3407 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3408 break; 3409 case ISD::SRA: 3410 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3411 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3412 Known = KnownBits::ashr(Known, Known2); 3413 break; 3414 case ISD::FSHL: 3415 case ISD::FSHR: 3416 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3417 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3418 3419 // For fshl, 0-shift returns the 1st arg. 3420 // For fshr, 0-shift returns the 2nd arg. 3421 if (Amt == 0) { 3422 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3423 DemandedElts, Depth + 1); 3424 break; 3425 } 3426 3427 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3428 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3429 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3430 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3431 if (Opcode == ISD::FSHL) { 3432 Known.One <<= Amt; 3433 Known.Zero <<= Amt; 3434 Known2.One.lshrInPlace(BitWidth - Amt); 3435 Known2.Zero.lshrInPlace(BitWidth - Amt); 3436 } else { 3437 Known.One <<= BitWidth - Amt; 3438 Known.Zero <<= BitWidth - Amt; 3439 Known2.One.lshrInPlace(Amt); 3440 Known2.Zero.lshrInPlace(Amt); 3441 } 3442 Known = Known.unionWith(Known2); 3443 } 3444 break; 3445 case ISD::SHL_PARTS: 3446 case ISD::SRA_PARTS: 3447 case ISD::SRL_PARTS: { 3448 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3449 3450 // Collect lo/hi source values and concatenate. 3451 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits(); 3452 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits(); 3453 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3454 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3455 Known = Known2.concat(Known); 3456 3457 // Collect shift amount. 3458 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3459 3460 if (Opcode == ISD::SHL_PARTS) 3461 Known = KnownBits::shl(Known, Known2); 3462 else if (Opcode == ISD::SRA_PARTS) 3463 Known = KnownBits::ashr(Known, Known2); 3464 else // if (Opcode == ISD::SRL_PARTS) 3465 Known = KnownBits::lshr(Known, Known2); 3466 3467 // TODO: Minimum shift low/high bits are known zero. 3468 3469 if (Op.getResNo() == 0) 3470 Known = Known.extractBits(LoBits, 0); 3471 else 3472 Known = Known.extractBits(HiBits, LoBits); 3473 break; 3474 } 3475 case ISD::SIGN_EXTEND_INREG: { 3476 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3477 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3478 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3479 break; 3480 } 3481 case ISD::CTTZ: 3482 case ISD::CTTZ_ZERO_UNDEF: { 3483 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3484 // If we have a known 1, its position is our upper bound. 3485 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3486 unsigned LowBits = llvm::bit_width(PossibleTZ); 3487 Known.Zero.setBitsFrom(LowBits); 3488 break; 3489 } 3490 case ISD::CTLZ: 3491 case ISD::CTLZ_ZERO_UNDEF: { 3492 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3493 // If we have a known 1, its position is our upper bound. 3494 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3495 unsigned LowBits = llvm::bit_width(PossibleLZ); 3496 Known.Zero.setBitsFrom(LowBits); 3497 break; 3498 } 3499 case ISD::CTPOP: { 3500 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3501 // If we know some of the bits are zero, they can't be one. 3502 unsigned PossibleOnes = Known2.countMaxPopulation(); 3503 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes)); 3504 break; 3505 } 3506 case ISD::PARITY: { 3507 // Parity returns 0 everywhere but the LSB. 3508 Known.Zero.setBitsFrom(1); 3509 break; 3510 } 3511 case ISD::LOAD: { 3512 LoadSDNode *LD = cast<LoadSDNode>(Op); 3513 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3514 if (ISD::isNON_EXTLoad(LD) && Cst) { 3515 // Determine any common known bits from the loaded constant pool value. 3516 Type *CstTy = Cst->getType(); 3517 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() && 3518 !Op.getValueType().isScalableVector()) { 3519 // If its a vector splat, then we can (quickly) reuse the scalar path. 3520 // NOTE: We assume all elements match and none are UNDEF. 3521 if (CstTy->isVectorTy()) { 3522 if (const Constant *Splat = Cst->getSplatValue()) { 3523 Cst = Splat; 3524 CstTy = Cst->getType(); 3525 } 3526 } 3527 // TODO - do we need to handle different bitwidths? 3528 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3529 // Iterate across all vector elements finding common known bits. 3530 Known.One.setAllBits(); 3531 Known.Zero.setAllBits(); 3532 for (unsigned i = 0; i != NumElts; ++i) { 3533 if (!DemandedElts[i]) 3534 continue; 3535 if (Constant *Elt = Cst->getAggregateElement(i)) { 3536 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3537 const APInt &Value = CInt->getValue(); 3538 Known.One &= Value; 3539 Known.Zero &= ~Value; 3540 continue; 3541 } 3542 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3543 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3544 Known.One &= Value; 3545 Known.Zero &= ~Value; 3546 continue; 3547 } 3548 } 3549 Known.One.clearAllBits(); 3550 Known.Zero.clearAllBits(); 3551 break; 3552 } 3553 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3554 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3555 Known = KnownBits::makeConstant(CInt->getValue()); 3556 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3557 Known = 3558 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3559 } 3560 } 3561 } 3562 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3563 // If this is a ZEXTLoad and we are looking at the loaded value. 3564 EVT VT = LD->getMemoryVT(); 3565 unsigned MemBits = VT.getScalarSizeInBits(); 3566 Known.Zero.setBitsFrom(MemBits); 3567 } else if (const MDNode *Ranges = LD->getRanges()) { 3568 EVT VT = LD->getValueType(0); 3569 3570 // TODO: Handle for extending loads 3571 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 3572 if (VT.isVector()) { 3573 // Handle truncation to the first demanded element. 3574 // TODO: Figure out which demanded elements are covered 3575 if (DemandedElts != 1 || !getDataLayout().isLittleEndian()) 3576 break; 3577 3578 // Handle the case where a load has a vector type, but scalar memory 3579 // with an attached range. 3580 EVT MemVT = LD->getMemoryVT(); 3581 KnownBits KnownFull(MemVT.getSizeInBits()); 3582 3583 computeKnownBitsFromRangeMetadata(*Ranges, KnownFull); 3584 Known = KnownFull.trunc(BitWidth); 3585 } else 3586 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3587 } 3588 } 3589 break; 3590 } 3591 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3592 if (Op.getValueType().isScalableVector()) 3593 break; 3594 EVT InVT = Op.getOperand(0).getValueType(); 3595 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3596 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3597 Known = Known.zext(BitWidth); 3598 break; 3599 } 3600 case ISD::ZERO_EXTEND: { 3601 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3602 Known = Known.zext(BitWidth); 3603 break; 3604 } 3605 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3606 if (Op.getValueType().isScalableVector()) 3607 break; 3608 EVT InVT = Op.getOperand(0).getValueType(); 3609 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3610 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3611 // If the sign bit is known to be zero or one, then sext will extend 3612 // it to the top bits, else it will just zext. 3613 Known = Known.sext(BitWidth); 3614 break; 3615 } 3616 case ISD::SIGN_EXTEND: { 3617 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3618 // If the sign bit is known to be zero or one, then sext will extend 3619 // it to the top bits, else it will just zext. 3620 Known = Known.sext(BitWidth); 3621 break; 3622 } 3623 case ISD::ANY_EXTEND_VECTOR_INREG: { 3624 if (Op.getValueType().isScalableVector()) 3625 break; 3626 EVT InVT = Op.getOperand(0).getValueType(); 3627 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3628 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3629 Known = Known.anyext(BitWidth); 3630 break; 3631 } 3632 case ISD::ANY_EXTEND: { 3633 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3634 Known = Known.anyext(BitWidth); 3635 break; 3636 } 3637 case ISD::TRUNCATE: { 3638 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3639 Known = Known.trunc(BitWidth); 3640 break; 3641 } 3642 case ISD::AssertZext: { 3643 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3644 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3645 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3646 Known.Zero |= (~InMask); 3647 Known.One &= (~Known.Zero); 3648 break; 3649 } 3650 case ISD::AssertAlign: { 3651 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3652 assert(LogOfAlign != 0); 3653 3654 // TODO: Should use maximum with source 3655 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3656 // well as clearing one bits. 3657 Known.Zero.setLowBits(LogOfAlign); 3658 Known.One.clearLowBits(LogOfAlign); 3659 break; 3660 } 3661 case ISD::FGETSIGN: 3662 // All bits are zero except the low bit. 3663 Known.Zero.setBitsFrom(1); 3664 break; 3665 case ISD::ADD: 3666 case ISD::SUB: { 3667 SDNodeFlags Flags = Op.getNode()->getFlags(); 3668 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3669 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3670 Known = KnownBits::computeForAddSub(Op.getOpcode() == ISD::ADD, 3671 Flags.hasNoSignedWrap(), Known, Known2); 3672 break; 3673 } 3674 case ISD::USUBO: 3675 case ISD::SSUBO: 3676 case ISD::USUBO_CARRY: 3677 case ISD::SSUBO_CARRY: 3678 if (Op.getResNo() == 1) { 3679 // If we know the result of a setcc has the top bits zero, use this info. 3680 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3681 TargetLowering::ZeroOrOneBooleanContent && 3682 BitWidth > 1) 3683 Known.Zero.setBitsFrom(1); 3684 break; 3685 } 3686 [[fallthrough]]; 3687 case ISD::SUBC: { 3688 assert(Op.getResNo() == 0 && 3689 "We only compute knownbits for the difference here."); 3690 3691 // TODO: Compute influence of the carry operand. 3692 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) 3693 break; 3694 3695 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3696 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3697 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3698 Known, Known2); 3699 break; 3700 } 3701 case ISD::UADDO: 3702 case ISD::SADDO: 3703 case ISD::UADDO_CARRY: 3704 case ISD::SADDO_CARRY: 3705 if (Op.getResNo() == 1) { 3706 // If we know the result of a setcc has the top bits zero, use this info. 3707 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3708 TargetLowering::ZeroOrOneBooleanContent && 3709 BitWidth > 1) 3710 Known.Zero.setBitsFrom(1); 3711 break; 3712 } 3713 [[fallthrough]]; 3714 case ISD::ADDC: 3715 case ISD::ADDE: { 3716 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3717 3718 // With ADDE and UADDO_CARRY, a carry bit may be added in. 3719 KnownBits Carry(1); 3720 if (Opcode == ISD::ADDE) 3721 // Can't track carry from glue, set carry to unknown. 3722 Carry.resetAll(); 3723 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) 3724 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3725 // the trouble (how often will we find a known carry bit). And I haven't 3726 // tested this very much yet, but something like this might work: 3727 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3728 // Carry = Carry.zextOrTrunc(1, false); 3729 Carry.resetAll(); 3730 else 3731 Carry.setAllZero(); 3732 3733 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3734 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3735 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3736 break; 3737 } 3738 case ISD::UDIV: { 3739 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3740 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3741 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact()); 3742 break; 3743 } 3744 case ISD::SDIV: { 3745 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3746 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3747 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact()); 3748 break; 3749 } 3750 case ISD::SREM: { 3751 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3752 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3753 Known = KnownBits::srem(Known, Known2); 3754 break; 3755 } 3756 case ISD::UREM: { 3757 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3758 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3759 Known = KnownBits::urem(Known, Known2); 3760 break; 3761 } 3762 case ISD::EXTRACT_ELEMENT: { 3763 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3764 const unsigned Index = Op.getConstantOperandVal(1); 3765 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3766 3767 // Remove low part of known bits mask 3768 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3769 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3770 3771 // Remove high part of known bit mask 3772 Known = Known.trunc(EltBitWidth); 3773 break; 3774 } 3775 case ISD::EXTRACT_VECTOR_ELT: { 3776 SDValue InVec = Op.getOperand(0); 3777 SDValue EltNo = Op.getOperand(1); 3778 EVT VecVT = InVec.getValueType(); 3779 // computeKnownBits not yet implemented for scalable vectors. 3780 if (VecVT.isScalableVector()) 3781 break; 3782 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3783 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3784 3785 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3786 // anything about the extended bits. 3787 if (BitWidth > EltBitWidth) 3788 Known = Known.trunc(EltBitWidth); 3789 3790 // If we know the element index, just demand that vector element, else for 3791 // an unknown element index, ignore DemandedElts and demand them all. 3792 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3793 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3794 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3795 DemandedSrcElts = 3796 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3797 3798 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3799 if (BitWidth > EltBitWidth) 3800 Known = Known.anyext(BitWidth); 3801 break; 3802 } 3803 case ISD::INSERT_VECTOR_ELT: { 3804 if (Op.getValueType().isScalableVector()) 3805 break; 3806 3807 // If we know the element index, split the demand between the 3808 // source vector and the inserted element, otherwise assume we need 3809 // the original demanded vector elements and the value. 3810 SDValue InVec = Op.getOperand(0); 3811 SDValue InVal = Op.getOperand(1); 3812 SDValue EltNo = Op.getOperand(2); 3813 bool DemandedVal = true; 3814 APInt DemandedVecElts = DemandedElts; 3815 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3816 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3817 unsigned EltIdx = CEltNo->getZExtValue(); 3818 DemandedVal = !!DemandedElts[EltIdx]; 3819 DemandedVecElts.clearBit(EltIdx); 3820 } 3821 Known.One.setAllBits(); 3822 Known.Zero.setAllBits(); 3823 if (DemandedVal) { 3824 Known2 = computeKnownBits(InVal, Depth + 1); 3825 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth)); 3826 } 3827 if (!!DemandedVecElts) { 3828 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3829 Known = Known.intersectWith(Known2); 3830 } 3831 break; 3832 } 3833 case ISD::BITREVERSE: { 3834 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3835 Known = Known2.reverseBits(); 3836 break; 3837 } 3838 case ISD::BSWAP: { 3839 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3840 Known = Known2.byteSwap(); 3841 break; 3842 } 3843 case ISD::ABS: { 3844 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3845 Known = Known2.abs(); 3846 break; 3847 } 3848 case ISD::USUBSAT: { 3849 // The result of usubsat will never be larger than the LHS. 3850 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3851 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3852 break; 3853 } 3854 case ISD::UMIN: { 3855 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3856 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3857 Known = KnownBits::umin(Known, Known2); 3858 break; 3859 } 3860 case ISD::UMAX: { 3861 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3862 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3863 Known = KnownBits::umax(Known, Known2); 3864 break; 3865 } 3866 case ISD::SMIN: 3867 case ISD::SMAX: { 3868 // If we have a clamp pattern, we know that the number of sign bits will be 3869 // the minimum of the clamp min/max range. 3870 bool IsMax = (Opcode == ISD::SMAX); 3871 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3872 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3873 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3874 CstHigh = 3875 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3876 if (CstLow && CstHigh) { 3877 if (!IsMax) 3878 std::swap(CstLow, CstHigh); 3879 3880 const APInt &ValueLow = CstLow->getAPIntValue(); 3881 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3882 if (ValueLow.sle(ValueHigh)) { 3883 unsigned LowSignBits = ValueLow.getNumSignBits(); 3884 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3885 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3886 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3887 Known.One.setHighBits(MinSignBits); 3888 break; 3889 } 3890 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3891 Known.Zero.setHighBits(MinSignBits); 3892 break; 3893 } 3894 } 3895 } 3896 3897 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3898 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3899 if (IsMax) 3900 Known = KnownBits::smax(Known, Known2); 3901 else 3902 Known = KnownBits::smin(Known, Known2); 3903 3904 // For SMAX, if CstLow is non-negative we know the result will be 3905 // non-negative and thus all sign bits are 0. 3906 // TODO: There's an equivalent of this for smin with negative constant for 3907 // known ones. 3908 if (IsMax && CstLow) { 3909 const APInt &ValueLow = CstLow->getAPIntValue(); 3910 if (ValueLow.isNonNegative()) { 3911 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3912 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits())); 3913 } 3914 } 3915 3916 break; 3917 } 3918 case ISD::FP_TO_UINT_SAT: { 3919 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3920 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3921 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3922 break; 3923 } 3924 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3925 if (Op.getResNo() == 1) { 3926 // The boolean result conforms to getBooleanContents. 3927 // If we know the result of a setcc has the top bits zero, use this info. 3928 // We know that we have an integer-based boolean since these operations 3929 // are only available for integer. 3930 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3931 TargetLowering::ZeroOrOneBooleanContent && 3932 BitWidth > 1) 3933 Known.Zero.setBitsFrom(1); 3934 break; 3935 } 3936 [[fallthrough]]; 3937 case ISD::ATOMIC_CMP_SWAP: 3938 case ISD::ATOMIC_SWAP: 3939 case ISD::ATOMIC_LOAD_ADD: 3940 case ISD::ATOMIC_LOAD_SUB: 3941 case ISD::ATOMIC_LOAD_AND: 3942 case ISD::ATOMIC_LOAD_CLR: 3943 case ISD::ATOMIC_LOAD_OR: 3944 case ISD::ATOMIC_LOAD_XOR: 3945 case ISD::ATOMIC_LOAD_NAND: 3946 case ISD::ATOMIC_LOAD_MIN: 3947 case ISD::ATOMIC_LOAD_MAX: 3948 case ISD::ATOMIC_LOAD_UMIN: 3949 case ISD::ATOMIC_LOAD_UMAX: 3950 case ISD::ATOMIC_LOAD: { 3951 unsigned MemBits = 3952 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3953 // If we are looking at the loaded value. 3954 if (Op.getResNo() == 0) { 3955 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3956 Known.Zero.setBitsFrom(MemBits); 3957 } 3958 break; 3959 } 3960 case ISD::FrameIndex: 3961 case ISD::TargetFrameIndex: 3962 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3963 Known, getMachineFunction()); 3964 break; 3965 3966 default: 3967 if (Opcode < ISD::BUILTIN_OP_END) 3968 break; 3969 [[fallthrough]]; 3970 case ISD::INTRINSIC_WO_CHAIN: 3971 case ISD::INTRINSIC_W_CHAIN: 3972 case ISD::INTRINSIC_VOID: 3973 // TODO: Probably okay to remove after audit; here to reduce change size 3974 // in initial enablement patch for scalable vectors 3975 if (Op.getValueType().isScalableVector()) 3976 break; 3977 3978 // Allow the target to implement this method for its nodes. 3979 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3980 break; 3981 } 3982 3983 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3984 return Known; 3985 } 3986 3987 /// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind. 3988 static SelectionDAG::OverflowKind mapOverflowResult(ConstantRange::OverflowResult OR) { 3989 switch (OR) { 3990 case ConstantRange::OverflowResult::MayOverflow: 3991 return SelectionDAG::OFK_Sometime; 3992 case ConstantRange::OverflowResult::AlwaysOverflowsLow: 3993 case ConstantRange::OverflowResult::AlwaysOverflowsHigh: 3994 return SelectionDAG::OFK_Always; 3995 case ConstantRange::OverflowResult::NeverOverflows: 3996 return SelectionDAG::OFK_Never; 3997 } 3998 llvm_unreachable("Unknown OverflowResult"); 3999 } 4000 4001 SelectionDAG::OverflowKind 4002 SelectionDAG::computeOverflowForSignedAdd(SDValue N0, SDValue N1) const { 4003 // X + 0 never overflow 4004 if (isNullConstant(N1)) 4005 return OFK_Never; 4006 4007 // If both operands each have at least two sign bits, the addition 4008 // cannot overflow. 4009 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1) 4010 return OFK_Never; 4011 4012 // TODO: Add ConstantRange::signedAddMayOverflow handling. 4013 return OFK_Sometime; 4014 } 4015 4016 SelectionDAG::OverflowKind 4017 SelectionDAG::computeOverflowForUnsignedAdd(SDValue N0, SDValue N1) const { 4018 // X + 0 never overflow 4019 if (isNullConstant(N1)) 4020 return OFK_Never; 4021 4022 // mulhi + 1 never overflow 4023 KnownBits N1Known = computeKnownBits(N1); 4024 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 4025 N1Known.getMaxValue().ult(2)) 4026 return OFK_Never; 4027 4028 KnownBits N0Known = computeKnownBits(N0); 4029 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 && 4030 N0Known.getMaxValue().ult(2)) 4031 return OFK_Never; 4032 4033 // Fallback to ConstantRange::unsignedAddMayOverflow handling. 4034 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false); 4035 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false); 4036 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range)); 4037 } 4038 4039 SelectionDAG::OverflowKind 4040 SelectionDAG::computeOverflowForSignedSub(SDValue N0, SDValue N1) const { 4041 // X - 0 never overflow 4042 if (isNullConstant(N1)) 4043 return OFK_Never; 4044 4045 // If both operands each have at least two sign bits, the subtraction 4046 // cannot overflow. 4047 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1) 4048 return OFK_Never; 4049 4050 // TODO: Add ConstantRange::signedSubMayOverflow handling. 4051 return OFK_Sometime; 4052 } 4053 4054 SelectionDAG::OverflowKind 4055 SelectionDAG::computeOverflowForUnsignedSub(SDValue N0, SDValue N1) const { 4056 // X - 0 never overflow 4057 if (isNullConstant(N1)) 4058 return OFK_Never; 4059 4060 // TODO: Add ConstantRange::unsignedSubMayOverflow handling. 4061 return OFK_Sometime; 4062 } 4063 4064 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val, unsigned Depth) const { 4065 if (Depth >= MaxRecursionDepth) 4066 return false; // Limit search depth. 4067 4068 EVT OpVT = Val.getValueType(); 4069 unsigned BitWidth = OpVT.getScalarSizeInBits(); 4070 4071 // Is the constant a known power of 2? 4072 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 4073 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 4074 4075 // A left-shift of a constant one will have exactly one bit set because 4076 // shifting the bit off the end is undefined. 4077 if (Val.getOpcode() == ISD::SHL) { 4078 auto *C = isConstOrConstSplat(Val.getOperand(0)); 4079 if (C && C->getAPIntValue() == 1) 4080 return true; 4081 } 4082 4083 // Similarly, a logical right-shift of a constant sign-bit will have exactly 4084 // one bit set. 4085 if (Val.getOpcode() == ISD::SRL) { 4086 auto *C = isConstOrConstSplat(Val.getOperand(0)); 4087 if (C && C->getAPIntValue().isSignMask()) 4088 return true; 4089 } 4090 4091 // Are all operands of a build vector constant powers of two? 4092 if (Val.getOpcode() == ISD::BUILD_VECTOR) 4093 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 4094 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 4095 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 4096 return false; 4097 })) 4098 return true; 4099 4100 // Is the operand of a splat vector a constant power of two? 4101 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 4102 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 4103 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 4104 return true; 4105 4106 // vscale(power-of-two) is a power-of-two for some targets 4107 if (Val.getOpcode() == ISD::VSCALE && 4108 getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() && 4109 isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1)) 4110 return true; 4111 4112 // More could be done here, though the above checks are enough 4113 // to handle some common cases. 4114 return false; 4115 } 4116 4117 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 4118 EVT VT = Op.getValueType(); 4119 4120 // Since the number of lanes in a scalable vector is unknown at compile time, 4121 // we track one bit which is implicitly broadcast to all lanes. This means 4122 // that all lanes in a scalable vector are considered demanded. 4123 APInt DemandedElts = VT.isFixedLengthVector() 4124 ? APInt::getAllOnes(VT.getVectorNumElements()) 4125 : APInt(1, 1); 4126 return ComputeNumSignBits(Op, DemandedElts, Depth); 4127 } 4128 4129 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 4130 unsigned Depth) const { 4131 EVT VT = Op.getValueType(); 4132 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 4133 unsigned VTBits = VT.getScalarSizeInBits(); 4134 unsigned NumElts = DemandedElts.getBitWidth(); 4135 unsigned Tmp, Tmp2; 4136 unsigned FirstAnswer = 1; 4137 4138 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 4139 const APInt &Val = C->getAPIntValue(); 4140 return Val.getNumSignBits(); 4141 } 4142 4143 if (Depth >= MaxRecursionDepth) 4144 return 1; // Limit search depth. 4145 4146 if (!DemandedElts) 4147 return 1; // No demanded elts, better to assume we don't know anything. 4148 4149 unsigned Opcode = Op.getOpcode(); 4150 switch (Opcode) { 4151 default: break; 4152 case ISD::AssertSext: 4153 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 4154 return VTBits-Tmp+1; 4155 case ISD::AssertZext: 4156 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 4157 return VTBits-Tmp; 4158 case ISD::MERGE_VALUES: 4159 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts, 4160 Depth + 1); 4161 case ISD::SPLAT_VECTOR: { 4162 // Check if the sign bits of source go down as far as the truncated value. 4163 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits(); 4164 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4165 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4166 return NumSrcSignBits - (NumSrcBits - VTBits); 4167 break; 4168 } 4169 case ISD::BUILD_VECTOR: 4170 assert(!VT.isScalableVector()); 4171 Tmp = VTBits; 4172 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 4173 if (!DemandedElts[i]) 4174 continue; 4175 4176 SDValue SrcOp = Op.getOperand(i); 4177 // BUILD_VECTOR can implicitly truncate sources, we handle this specially 4178 // for constant nodes to ensure we only look at the sign bits. 4179 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SrcOp)) { 4180 APInt T = C->getAPIntValue().trunc(VTBits); 4181 Tmp2 = T.getNumSignBits(); 4182 } else { 4183 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 4184 4185 if (SrcOp.getValueSizeInBits() != VTBits) { 4186 assert(SrcOp.getValueSizeInBits() > VTBits && 4187 "Expected BUILD_VECTOR implicit truncation"); 4188 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 4189 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 4190 } 4191 } 4192 Tmp = std::min(Tmp, Tmp2); 4193 } 4194 return Tmp; 4195 4196 case ISD::VECTOR_SHUFFLE: { 4197 // Collect the minimum number of sign bits that are shared by every vector 4198 // element referenced by the shuffle. 4199 APInt DemandedLHS, DemandedRHS; 4200 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4201 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 4202 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts, 4203 DemandedLHS, DemandedRHS)) 4204 return 1; 4205 4206 Tmp = std::numeric_limits<unsigned>::max(); 4207 if (!!DemandedLHS) 4208 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 4209 if (!!DemandedRHS) { 4210 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 4211 Tmp = std::min(Tmp, Tmp2); 4212 } 4213 // If we don't know anything, early out and try computeKnownBits fall-back. 4214 if (Tmp == 1) 4215 break; 4216 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4217 return Tmp; 4218 } 4219 4220 case ISD::BITCAST: { 4221 if (VT.isScalableVector()) 4222 break; 4223 SDValue N0 = Op.getOperand(0); 4224 EVT SrcVT = N0.getValueType(); 4225 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 4226 4227 // Ignore bitcasts from unsupported types.. 4228 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 4229 break; 4230 4231 // Fast handling of 'identity' bitcasts. 4232 if (VTBits == SrcBits) 4233 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 4234 4235 bool IsLE = getDataLayout().isLittleEndian(); 4236 4237 // Bitcast 'large element' scalar/vector to 'small element' vector. 4238 if ((SrcBits % VTBits) == 0) { 4239 assert(VT.isVector() && "Expected bitcast to vector"); 4240 4241 unsigned Scale = SrcBits / VTBits; 4242 APInt SrcDemandedElts = 4243 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 4244 4245 // Fast case - sign splat can be simply split across the small elements. 4246 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 4247 if (Tmp == SrcBits) 4248 return VTBits; 4249 4250 // Slow case - determine how far the sign extends into each sub-element. 4251 Tmp2 = VTBits; 4252 for (unsigned i = 0; i != NumElts; ++i) 4253 if (DemandedElts[i]) { 4254 unsigned SubOffset = i % Scale; 4255 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 4256 SubOffset = SubOffset * VTBits; 4257 if (Tmp <= SubOffset) 4258 return 1; 4259 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 4260 } 4261 return Tmp2; 4262 } 4263 break; 4264 } 4265 4266 case ISD::FP_TO_SINT_SAT: 4267 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 4268 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4269 return VTBits - Tmp + 1; 4270 case ISD::SIGN_EXTEND: 4271 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 4272 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 4273 case ISD::SIGN_EXTEND_INREG: 4274 // Max of the input and what this extends. 4275 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4276 Tmp = VTBits-Tmp+1; 4277 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4278 return std::max(Tmp, Tmp2); 4279 case ISD::SIGN_EXTEND_VECTOR_INREG: { 4280 if (VT.isScalableVector()) 4281 break; 4282 SDValue Src = Op.getOperand(0); 4283 EVT SrcVT = Src.getValueType(); 4284 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements()); 4285 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4286 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4287 } 4288 case ISD::SRA: 4289 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4290 // SRA X, C -> adds C sign bits. 4291 if (const APInt *ShAmt = 4292 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4293 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4294 return Tmp; 4295 case ISD::SHL: 4296 if (const APInt *ShAmt = 4297 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4298 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4299 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4300 if (ShAmt->ult(Tmp)) 4301 return Tmp - ShAmt->getZExtValue(); 4302 } 4303 break; 4304 case ISD::AND: 4305 case ISD::OR: 4306 case ISD::XOR: // NOT is handled here. 4307 // Logical binary ops preserve the number of sign bits at the worst. 4308 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4309 if (Tmp != 1) { 4310 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4311 FirstAnswer = std::min(Tmp, Tmp2); 4312 // We computed what we know about the sign bits as our first 4313 // answer. Now proceed to the generic code that uses 4314 // computeKnownBits, and pick whichever answer is better. 4315 } 4316 break; 4317 4318 case ISD::SELECT: 4319 case ISD::VSELECT: 4320 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4321 if (Tmp == 1) return 1; // Early out. 4322 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4323 return std::min(Tmp, Tmp2); 4324 case ISD::SELECT_CC: 4325 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4326 if (Tmp == 1) return 1; // Early out. 4327 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4328 return std::min(Tmp, Tmp2); 4329 4330 case ISD::SMIN: 4331 case ISD::SMAX: { 4332 // If we have a clamp pattern, we know that the number of sign bits will be 4333 // the minimum of the clamp min/max range. 4334 bool IsMax = (Opcode == ISD::SMAX); 4335 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4336 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4337 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4338 CstHigh = 4339 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4340 if (CstLow && CstHigh) { 4341 if (!IsMax) 4342 std::swap(CstLow, CstHigh); 4343 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4344 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4345 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4346 return std::min(Tmp, Tmp2); 4347 } 4348 } 4349 4350 // Fallback - just get the minimum number of sign bits of the operands. 4351 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4352 if (Tmp == 1) 4353 return 1; // Early out. 4354 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4355 return std::min(Tmp, Tmp2); 4356 } 4357 case ISD::UMIN: 4358 case ISD::UMAX: 4359 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4360 if (Tmp == 1) 4361 return 1; // Early out. 4362 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4363 return std::min(Tmp, Tmp2); 4364 case ISD::SADDO: 4365 case ISD::UADDO: 4366 case ISD::SADDO_CARRY: 4367 case ISD::UADDO_CARRY: 4368 case ISD::SSUBO: 4369 case ISD::USUBO: 4370 case ISD::SSUBO_CARRY: 4371 case ISD::USUBO_CARRY: 4372 case ISD::SMULO: 4373 case ISD::UMULO: 4374 if (Op.getResNo() != 1) 4375 break; 4376 // The boolean result conforms to getBooleanContents. Fall through. 4377 // If setcc returns 0/-1, all bits are sign bits. 4378 // We know that we have an integer-based boolean since these operations 4379 // are only available for integer. 4380 if (TLI->getBooleanContents(VT.isVector(), false) == 4381 TargetLowering::ZeroOrNegativeOneBooleanContent) 4382 return VTBits; 4383 break; 4384 case ISD::SETCC: 4385 case ISD::SETCCCARRY: 4386 case ISD::STRICT_FSETCC: 4387 case ISD::STRICT_FSETCCS: { 4388 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4389 // If setcc returns 0/-1, all bits are sign bits. 4390 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4391 TargetLowering::ZeroOrNegativeOneBooleanContent) 4392 return VTBits; 4393 break; 4394 } 4395 case ISD::ROTL: 4396 case ISD::ROTR: 4397 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4398 4399 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4400 if (Tmp == VTBits) 4401 return VTBits; 4402 4403 if (ConstantSDNode *C = 4404 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4405 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4406 4407 // Handle rotate right by N like a rotate left by 32-N. 4408 if (Opcode == ISD::ROTR) 4409 RotAmt = (VTBits - RotAmt) % VTBits; 4410 4411 // If we aren't rotating out all of the known-in sign bits, return the 4412 // number that are left. This handles rotl(sext(x), 1) for example. 4413 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4414 } 4415 break; 4416 case ISD::ADD: 4417 case ISD::ADDC: 4418 // Add can have at most one carry bit. Thus we know that the output 4419 // is, at worst, one more bit than the inputs. 4420 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4421 if (Tmp == 1) return 1; // Early out. 4422 4423 // Special case decrementing a value (ADD X, -1): 4424 if (ConstantSDNode *CRHS = 4425 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4426 if (CRHS->isAllOnes()) { 4427 KnownBits Known = 4428 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4429 4430 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4431 // sign bits set. 4432 if ((Known.Zero | 1).isAllOnes()) 4433 return VTBits; 4434 4435 // If we are subtracting one from a positive number, there is no carry 4436 // out of the result. 4437 if (Known.isNonNegative()) 4438 return Tmp; 4439 } 4440 4441 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4442 if (Tmp2 == 1) return 1; // Early out. 4443 return std::min(Tmp, Tmp2) - 1; 4444 case ISD::SUB: 4445 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4446 if (Tmp2 == 1) return 1; // Early out. 4447 4448 // Handle NEG. 4449 if (ConstantSDNode *CLHS = 4450 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4451 if (CLHS->isZero()) { 4452 KnownBits Known = 4453 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4454 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4455 // sign bits set. 4456 if ((Known.Zero | 1).isAllOnes()) 4457 return VTBits; 4458 4459 // If the input is known to be positive (the sign bit is known clear), 4460 // the output of the NEG has the same number of sign bits as the input. 4461 if (Known.isNonNegative()) 4462 return Tmp2; 4463 4464 // Otherwise, we treat this like a SUB. 4465 } 4466 4467 // Sub can have at most one carry bit. Thus we know that the output 4468 // is, at worst, one more bit than the inputs. 4469 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4470 if (Tmp == 1) return 1; // Early out. 4471 return std::min(Tmp, Tmp2) - 1; 4472 case ISD::MUL: { 4473 // The output of the Mul can be at most twice the valid bits in the inputs. 4474 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4475 if (SignBitsOp0 == 1) 4476 break; 4477 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4478 if (SignBitsOp1 == 1) 4479 break; 4480 unsigned OutValidBits = 4481 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4482 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4483 } 4484 case ISD::SREM: 4485 // The sign bit is the LHS's sign bit, except when the result of the 4486 // remainder is zero. The magnitude of the result should be less than or 4487 // equal to the magnitude of the LHS. Therefore, the result should have 4488 // at least as many sign bits as the left hand side. 4489 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4490 case ISD::TRUNCATE: { 4491 // Check if the sign bits of source go down as far as the truncated value. 4492 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4493 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4494 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4495 return NumSrcSignBits - (NumSrcBits - VTBits); 4496 break; 4497 } 4498 case ISD::EXTRACT_ELEMENT: { 4499 if (VT.isScalableVector()) 4500 break; 4501 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4502 const int BitWidth = Op.getValueSizeInBits(); 4503 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4504 4505 // Get reverse index (starting from 1), Op1 value indexes elements from 4506 // little end. Sign starts at big end. 4507 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4508 4509 // If the sign portion ends in our element the subtraction gives correct 4510 // result. Otherwise it gives either negative or > bitwidth result 4511 return std::clamp(KnownSign - rIndex * BitWidth, 0, BitWidth); 4512 } 4513 case ISD::INSERT_VECTOR_ELT: { 4514 if (VT.isScalableVector()) 4515 break; 4516 // If we know the element index, split the demand between the 4517 // source vector and the inserted element, otherwise assume we need 4518 // the original demanded vector elements and the value. 4519 SDValue InVec = Op.getOperand(0); 4520 SDValue InVal = Op.getOperand(1); 4521 SDValue EltNo = Op.getOperand(2); 4522 bool DemandedVal = true; 4523 APInt DemandedVecElts = DemandedElts; 4524 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4525 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4526 unsigned EltIdx = CEltNo->getZExtValue(); 4527 DemandedVal = !!DemandedElts[EltIdx]; 4528 DemandedVecElts.clearBit(EltIdx); 4529 } 4530 Tmp = std::numeric_limits<unsigned>::max(); 4531 if (DemandedVal) { 4532 // TODO - handle implicit truncation of inserted elements. 4533 if (InVal.getScalarValueSizeInBits() != VTBits) 4534 break; 4535 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4536 Tmp = std::min(Tmp, Tmp2); 4537 } 4538 if (!!DemandedVecElts) { 4539 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4540 Tmp = std::min(Tmp, Tmp2); 4541 } 4542 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4543 return Tmp; 4544 } 4545 case ISD::EXTRACT_VECTOR_ELT: { 4546 assert(!VT.isScalableVector()); 4547 SDValue InVec = Op.getOperand(0); 4548 SDValue EltNo = Op.getOperand(1); 4549 EVT VecVT = InVec.getValueType(); 4550 // ComputeNumSignBits not yet implemented for scalable vectors. 4551 if (VecVT.isScalableVector()) 4552 break; 4553 const unsigned BitWidth = Op.getValueSizeInBits(); 4554 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4555 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4556 4557 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4558 // anything about sign bits. But if the sizes match we can derive knowledge 4559 // about sign bits from the vector operand. 4560 if (BitWidth != EltBitWidth) 4561 break; 4562 4563 // If we know the element index, just demand that vector element, else for 4564 // an unknown element index, ignore DemandedElts and demand them all. 4565 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4566 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4567 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4568 DemandedSrcElts = 4569 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4570 4571 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4572 } 4573 case ISD::EXTRACT_SUBVECTOR: { 4574 // Offset the demanded elts by the subvector index. 4575 SDValue Src = Op.getOperand(0); 4576 // Bail until we can represent demanded elements for scalable vectors. 4577 if (Src.getValueType().isScalableVector()) 4578 break; 4579 uint64_t Idx = Op.getConstantOperandVal(1); 4580 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4581 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 4582 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4583 } 4584 case ISD::CONCAT_VECTORS: { 4585 if (VT.isScalableVector()) 4586 break; 4587 // Determine the minimum number of sign bits across all demanded 4588 // elts of the input vectors. Early out if the result is already 1. 4589 Tmp = std::numeric_limits<unsigned>::max(); 4590 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4591 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4592 unsigned NumSubVectors = Op.getNumOperands(); 4593 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4594 APInt DemandedSub = 4595 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4596 if (!DemandedSub) 4597 continue; 4598 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4599 Tmp = std::min(Tmp, Tmp2); 4600 } 4601 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4602 return Tmp; 4603 } 4604 case ISD::INSERT_SUBVECTOR: { 4605 if (VT.isScalableVector()) 4606 break; 4607 // Demand any elements from the subvector and the remainder from the src its 4608 // inserted into. 4609 SDValue Src = Op.getOperand(0); 4610 SDValue Sub = Op.getOperand(1); 4611 uint64_t Idx = Op.getConstantOperandVal(2); 4612 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4613 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4614 APInt DemandedSrcElts = DemandedElts; 4615 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4616 4617 Tmp = std::numeric_limits<unsigned>::max(); 4618 if (!!DemandedSubElts) { 4619 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4620 if (Tmp == 1) 4621 return 1; // early-out 4622 } 4623 if (!!DemandedSrcElts) { 4624 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4625 Tmp = std::min(Tmp, Tmp2); 4626 } 4627 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4628 return Tmp; 4629 } 4630 case ISD::LOAD: { 4631 LoadSDNode *LD = cast<LoadSDNode>(Op); 4632 if (const MDNode *Ranges = LD->getRanges()) { 4633 if (DemandedElts != 1) 4634 break; 4635 4636 ConstantRange CR = getConstantRangeFromMetadata(*Ranges); 4637 if (VTBits > CR.getBitWidth()) { 4638 switch (LD->getExtensionType()) { 4639 case ISD::SEXTLOAD: 4640 CR = CR.signExtend(VTBits); 4641 break; 4642 case ISD::ZEXTLOAD: 4643 CR = CR.zeroExtend(VTBits); 4644 break; 4645 default: 4646 break; 4647 } 4648 } 4649 4650 if (VTBits != CR.getBitWidth()) 4651 break; 4652 return std::min(CR.getSignedMin().getNumSignBits(), 4653 CR.getSignedMax().getNumSignBits()); 4654 } 4655 4656 break; 4657 } 4658 case ISD::ATOMIC_CMP_SWAP: 4659 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4660 case ISD::ATOMIC_SWAP: 4661 case ISD::ATOMIC_LOAD_ADD: 4662 case ISD::ATOMIC_LOAD_SUB: 4663 case ISD::ATOMIC_LOAD_AND: 4664 case ISD::ATOMIC_LOAD_CLR: 4665 case ISD::ATOMIC_LOAD_OR: 4666 case ISD::ATOMIC_LOAD_XOR: 4667 case ISD::ATOMIC_LOAD_NAND: 4668 case ISD::ATOMIC_LOAD_MIN: 4669 case ISD::ATOMIC_LOAD_MAX: 4670 case ISD::ATOMIC_LOAD_UMIN: 4671 case ISD::ATOMIC_LOAD_UMAX: 4672 case ISD::ATOMIC_LOAD: { 4673 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4674 // If we are looking at the loaded value. 4675 if (Op.getResNo() == 0) { 4676 if (Tmp == VTBits) 4677 return 1; // early-out 4678 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4679 return VTBits - Tmp + 1; 4680 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4681 return VTBits - Tmp; 4682 } 4683 break; 4684 } 4685 } 4686 4687 // If we are looking at the loaded value of the SDNode. 4688 if (Op.getResNo() == 0) { 4689 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4690 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4691 unsigned ExtType = LD->getExtensionType(); 4692 switch (ExtType) { 4693 default: break; 4694 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4695 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4696 return VTBits - Tmp + 1; 4697 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4698 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4699 return VTBits - Tmp; 4700 case ISD::NON_EXTLOAD: 4701 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4702 // We only need to handle vectors - computeKnownBits should handle 4703 // scalar cases. 4704 Type *CstTy = Cst->getType(); 4705 if (CstTy->isVectorTy() && !VT.isScalableVector() && 4706 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4707 VTBits == CstTy->getScalarSizeInBits()) { 4708 Tmp = VTBits; 4709 for (unsigned i = 0; i != NumElts; ++i) { 4710 if (!DemandedElts[i]) 4711 continue; 4712 if (Constant *Elt = Cst->getAggregateElement(i)) { 4713 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4714 const APInt &Value = CInt->getValue(); 4715 Tmp = std::min(Tmp, Value.getNumSignBits()); 4716 continue; 4717 } 4718 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4719 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4720 Tmp = std::min(Tmp, Value.getNumSignBits()); 4721 continue; 4722 } 4723 } 4724 // Unknown type. Conservatively assume no bits match sign bit. 4725 return 1; 4726 } 4727 return Tmp; 4728 } 4729 } 4730 break; 4731 } 4732 } 4733 } 4734 4735 // Allow the target to implement this method for its nodes. 4736 if (Opcode >= ISD::BUILTIN_OP_END || 4737 Opcode == ISD::INTRINSIC_WO_CHAIN || 4738 Opcode == ISD::INTRINSIC_W_CHAIN || 4739 Opcode == ISD::INTRINSIC_VOID) { 4740 // TODO: This can probably be removed once target code is audited. This 4741 // is here purely to reduce patch size and review complexity. 4742 if (!VT.isScalableVector()) { 4743 unsigned NumBits = 4744 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4745 if (NumBits > 1) 4746 FirstAnswer = std::max(FirstAnswer, NumBits); 4747 } 4748 } 4749 4750 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4751 // use this information. 4752 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4753 return std::max(FirstAnswer, Known.countMinSignBits()); 4754 } 4755 4756 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4757 unsigned Depth) const { 4758 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4759 return Op.getScalarValueSizeInBits() - SignBits + 1; 4760 } 4761 4762 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4763 const APInt &DemandedElts, 4764 unsigned Depth) const { 4765 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4766 return Op.getScalarValueSizeInBits() - SignBits + 1; 4767 } 4768 4769 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4770 unsigned Depth) const { 4771 // Early out for FREEZE. 4772 if (Op.getOpcode() == ISD::FREEZE) 4773 return true; 4774 4775 // TODO: Assume we don't know anything for now. 4776 EVT VT = Op.getValueType(); 4777 if (VT.isScalableVector()) 4778 return false; 4779 4780 APInt DemandedElts = VT.isVector() 4781 ? APInt::getAllOnes(VT.getVectorNumElements()) 4782 : APInt(1, 1); 4783 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4784 } 4785 4786 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4787 const APInt &DemandedElts, 4788 bool PoisonOnly, 4789 unsigned Depth) const { 4790 unsigned Opcode = Op.getOpcode(); 4791 4792 // Early out for FREEZE. 4793 if (Opcode == ISD::FREEZE) 4794 return true; 4795 4796 if (Depth >= MaxRecursionDepth) 4797 return false; // Limit search depth. 4798 4799 if (isIntOrFPConstant(Op)) 4800 return true; 4801 4802 switch (Opcode) { 4803 case ISD::VALUETYPE: 4804 case ISD::FrameIndex: 4805 case ISD::TargetFrameIndex: 4806 return true; 4807 4808 case ISD::UNDEF: 4809 return PoisonOnly; 4810 4811 case ISD::BUILD_VECTOR: 4812 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4813 // this shouldn't affect the result. 4814 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4815 if (!DemandedElts[i]) 4816 continue; 4817 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4818 Depth + 1)) 4819 return false; 4820 } 4821 return true; 4822 4823 // TODO: Search for noundef attributes from library functions. 4824 4825 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4826 4827 default: 4828 // Allow the target to implement this method for its nodes. 4829 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4830 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4831 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4832 Op, DemandedElts, *this, PoisonOnly, Depth); 4833 break; 4834 } 4835 4836 // If Op can't create undef/poison and none of its operands are undef/poison 4837 // then Op is never undef/poison. 4838 // NOTE: TargetNodes should handle this in themselves in 4839 // isGuaranteedNotToBeUndefOrPoisonForTargetNode. 4840 return !canCreateUndefOrPoison(Op, PoisonOnly, /*ConsiderFlags*/ true, 4841 Depth) && 4842 all_of(Op->ops(), [&](SDValue V) { 4843 return isGuaranteedNotToBeUndefOrPoison(V, PoisonOnly, Depth + 1); 4844 }); 4845 } 4846 4847 bool SelectionDAG::canCreateUndefOrPoison(SDValue Op, bool PoisonOnly, 4848 bool ConsiderFlags, 4849 unsigned Depth) const { 4850 // TODO: Assume we don't know anything for now. 4851 EVT VT = Op.getValueType(); 4852 if (VT.isScalableVector()) 4853 return true; 4854 4855 APInt DemandedElts = VT.isVector() 4856 ? APInt::getAllOnes(VT.getVectorNumElements()) 4857 : APInt(1, 1); 4858 return canCreateUndefOrPoison(Op, DemandedElts, PoisonOnly, ConsiderFlags, 4859 Depth); 4860 } 4861 4862 bool SelectionDAG::canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts, 4863 bool PoisonOnly, bool ConsiderFlags, 4864 unsigned Depth) const { 4865 // TODO: Assume we don't know anything for now. 4866 EVT VT = Op.getValueType(); 4867 if (VT.isScalableVector()) 4868 return true; 4869 4870 unsigned Opcode = Op.getOpcode(); 4871 switch (Opcode) { 4872 case ISD::AssertSext: 4873 case ISD::AssertZext: 4874 case ISD::FREEZE: 4875 case ISD::CONCAT_VECTORS: 4876 case ISD::INSERT_SUBVECTOR: 4877 case ISD::AND: 4878 case ISD::OR: 4879 case ISD::XOR: 4880 case ISD::ROTL: 4881 case ISD::ROTR: 4882 case ISD::FSHL: 4883 case ISD::FSHR: 4884 case ISD::BSWAP: 4885 case ISD::CTPOP: 4886 case ISD::BITREVERSE: 4887 case ISD::PARITY: 4888 case ISD::SIGN_EXTEND: 4889 case ISD::ZERO_EXTEND: 4890 case ISD::TRUNCATE: 4891 case ISD::SIGN_EXTEND_INREG: 4892 case ISD::SIGN_EXTEND_VECTOR_INREG: 4893 case ISD::ZERO_EXTEND_VECTOR_INREG: 4894 case ISD::BITCAST: 4895 case ISD::BUILD_VECTOR: 4896 case ISD::BUILD_PAIR: 4897 return false; 4898 4899 case ISD::ADD: 4900 case ISD::SUB: 4901 case ISD::MUL: 4902 // Matches hasPoisonGeneratingFlags(). 4903 return ConsiderFlags && (Op->getFlags().hasNoSignedWrap() || 4904 Op->getFlags().hasNoUnsignedWrap()); 4905 4906 case ISD::SHL: 4907 // If the max shift amount isn't in range, then the shift can create poison. 4908 if (!getValidMaximumShiftAmountConstant(Op, DemandedElts)) 4909 return true; 4910 4911 // Matches hasPoisonGeneratingFlags(). 4912 return ConsiderFlags && (Op->getFlags().hasNoSignedWrap() || 4913 Op->getFlags().hasNoUnsignedWrap()); 4914 4915 case ISD::INSERT_VECTOR_ELT:{ 4916 // Ensure that the element index is in bounds. 4917 EVT VecVT = Op.getOperand(0).getValueType(); 4918 KnownBits KnownIdx = computeKnownBits(Op.getOperand(2), Depth + 1); 4919 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements()); 4920 } 4921 4922 default: 4923 // Allow the target to implement this method for its nodes. 4924 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4925 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4926 return TLI->canCreateUndefOrPoisonForTargetNode( 4927 Op, DemandedElts, *this, PoisonOnly, ConsiderFlags, Depth); 4928 break; 4929 } 4930 4931 // Be conservative and return true. 4932 return true; 4933 } 4934 4935 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4936 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4937 !isa<ConstantSDNode>(Op.getOperand(1))) 4938 return false; 4939 4940 if (Op.getOpcode() == ISD::OR && 4941 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4942 return false; 4943 4944 return true; 4945 } 4946 4947 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4948 // If we're told that NaNs won't happen, assume they won't. 4949 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4950 return true; 4951 4952 if (Depth >= MaxRecursionDepth) 4953 return false; // Limit search depth. 4954 4955 // If the value is a constant, we can obviously see if it is a NaN or not. 4956 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4957 return !C->getValueAPF().isNaN() || 4958 (SNaN && !C->getValueAPF().isSignaling()); 4959 } 4960 4961 unsigned Opcode = Op.getOpcode(); 4962 switch (Opcode) { 4963 case ISD::FADD: 4964 case ISD::FSUB: 4965 case ISD::FMUL: 4966 case ISD::FDIV: 4967 case ISD::FREM: 4968 case ISD::FSIN: 4969 case ISD::FCOS: 4970 case ISD::FMA: 4971 case ISD::FMAD: { 4972 if (SNaN) 4973 return true; 4974 // TODO: Need isKnownNeverInfinity 4975 return false; 4976 } 4977 case ISD::FCANONICALIZE: 4978 case ISD::FEXP: 4979 case ISD::FEXP2: 4980 case ISD::FTRUNC: 4981 case ISD::FFLOOR: 4982 case ISD::FCEIL: 4983 case ISD::FROUND: 4984 case ISD::FROUNDEVEN: 4985 case ISD::FRINT: 4986 case ISD::FNEARBYINT: 4987 case ISD::FLDEXP: { 4988 if (SNaN) 4989 return true; 4990 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4991 } 4992 case ISD::FABS: 4993 case ISD::FNEG: 4994 case ISD::FCOPYSIGN: { 4995 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4996 } 4997 case ISD::SELECT: 4998 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4999 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 5000 case ISD::FP_EXTEND: 5001 case ISD::FP_ROUND: { 5002 if (SNaN) 5003 return true; 5004 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 5005 } 5006 case ISD::SINT_TO_FP: 5007 case ISD::UINT_TO_FP: 5008 return true; 5009 case ISD::FSQRT: // Need is known positive 5010 case ISD::FLOG: 5011 case ISD::FLOG2: 5012 case ISD::FLOG10: 5013 case ISD::FPOWI: 5014 case ISD::FPOW: { 5015 if (SNaN) 5016 return true; 5017 // TODO: Refine on operand 5018 return false; 5019 } 5020 case ISD::FMINNUM: 5021 case ISD::FMAXNUM: { 5022 // Only one needs to be known not-nan, since it will be returned if the 5023 // other ends up being one. 5024 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 5025 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 5026 } 5027 case ISD::FMINNUM_IEEE: 5028 case ISD::FMAXNUM_IEEE: { 5029 if (SNaN) 5030 return true; 5031 // This can return a NaN if either operand is an sNaN, or if both operands 5032 // are NaN. 5033 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 5034 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 5035 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 5036 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 5037 } 5038 case ISD::FMINIMUM: 5039 case ISD::FMAXIMUM: { 5040 // TODO: Does this quiet or return the origina NaN as-is? 5041 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 5042 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 5043 } 5044 case ISD::EXTRACT_VECTOR_ELT: { 5045 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 5046 } 5047 case ISD::BUILD_VECTOR: { 5048 for (const SDValue &Opnd : Op->ops()) 5049 if (!isKnownNeverNaN(Opnd, SNaN, Depth + 1)) 5050 return false; 5051 return true; 5052 } 5053 default: 5054 if (Opcode >= ISD::BUILTIN_OP_END || 5055 Opcode == ISD::INTRINSIC_WO_CHAIN || 5056 Opcode == ISD::INTRINSIC_W_CHAIN || 5057 Opcode == ISD::INTRINSIC_VOID) { 5058 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 5059 } 5060 5061 return false; 5062 } 5063 } 5064 5065 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 5066 assert(Op.getValueType().isFloatingPoint() && 5067 "Floating point type expected"); 5068 5069 // If the value is a constant, we can obviously see if it is a zero or not. 5070 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 5071 return !C->isZero(); 5072 5073 // Return false if we find any zero in a vector. 5074 if (Op->getOpcode() == ISD::BUILD_VECTOR || 5075 Op->getOpcode() == ISD::SPLAT_VECTOR) { 5076 for (const SDValue &OpVal : Op->op_values()) { 5077 if (OpVal.isUndef()) 5078 return false; 5079 if (auto *C = dyn_cast<ConstantFPSDNode>(OpVal)) 5080 if (C->isZero()) 5081 return false; 5082 } 5083 return true; 5084 } 5085 return false; 5086 } 5087 5088 bool SelectionDAG::isKnownNeverZero(SDValue Op, unsigned Depth) const { 5089 if (Depth >= MaxRecursionDepth) 5090 return false; // Limit search depth. 5091 5092 assert(!Op.getValueType().isFloatingPoint() && 5093 "Floating point types unsupported - use isKnownNeverZeroFloat"); 5094 5095 // If the value is a constant, we can obviously see if it is a zero or not. 5096 if (ISD::matchUnaryPredicate(Op, 5097 [](ConstantSDNode *C) { return !C->isZero(); })) 5098 return true; 5099 5100 // TODO: Recognize more cases here. Most of the cases are also incomplete to 5101 // some degree. 5102 switch (Op.getOpcode()) { 5103 default: 5104 break; 5105 5106 case ISD::OR: 5107 return isKnownNeverZero(Op.getOperand(1), Depth + 1) || 5108 isKnownNeverZero(Op.getOperand(0), Depth + 1); 5109 5110 case ISD::VSELECT: 5111 case ISD::SELECT: 5112 return isKnownNeverZero(Op.getOperand(1), Depth + 1) && 5113 isKnownNeverZero(Op.getOperand(2), Depth + 1); 5114 5115 case ISD::SHL: 5116 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap()) 5117 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5118 5119 // 1 << X is never zero. TODO: This can be expanded if we can bound X. 5120 // The expression is really !Known.One[BitWidth-MaxLog2(Known):0].isZero() 5121 if (computeKnownBits(Op.getOperand(0), Depth + 1).One[0]) 5122 return true; 5123 break; 5124 5125 case ISD::UADDSAT: 5126 case ISD::UMAX: 5127 return isKnownNeverZero(Op.getOperand(1), Depth + 1) || 5128 isKnownNeverZero(Op.getOperand(0), Depth + 1); 5129 5130 case ISD::UMIN: 5131 return isKnownNeverZero(Op.getOperand(1), Depth + 1) && 5132 isKnownNeverZero(Op.getOperand(0), Depth + 1); 5133 5134 case ISD::ROTL: 5135 case ISD::ROTR: 5136 case ISD::BITREVERSE: 5137 case ISD::BSWAP: 5138 case ISD::CTPOP: 5139 case ISD::ABS: 5140 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5141 5142 case ISD::SRA: 5143 case ISD::SRL: 5144 if (Op->getFlags().hasExact()) 5145 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5146 // Signed >> X is never zero. TODO: This can be expanded if we can bound X. 5147 // The expression is really 5148 // !Known.One[SignBit:SignBit-(BitWidth-MaxLog2(Known))].isZero() 5149 if (computeKnownBits(Op.getOperand(0), Depth + 1).isNegative()) 5150 return true; 5151 break; 5152 5153 case ISD::UDIV: 5154 case ISD::SDIV: 5155 // div exact can only produce a zero if the dividend is zero. 5156 // TODO: For udiv this is also true if Op1 u<= Op0 5157 if (Op->getFlags().hasExact()) 5158 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5159 break; 5160 5161 case ISD::ADD: 5162 if (Op->getFlags().hasNoUnsignedWrap()) 5163 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) || 5164 isKnownNeverZero(Op.getOperand(0), Depth + 1)) 5165 return true; 5166 // TODO: There are a lot more cases we can prove for add. 5167 break; 5168 5169 case ISD::SUB: { 5170 if (isNullConstant(Op.getOperand(0))) 5171 return isKnownNeverZero(Op.getOperand(1), Depth + 1); 5172 5173 std::optional<bool> ne = 5174 KnownBits::ne(computeKnownBits(Op.getOperand(0), Depth + 1), 5175 computeKnownBits(Op.getOperand(1), Depth + 1)); 5176 return ne && *ne; 5177 } 5178 5179 case ISD::MUL: 5180 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap()) 5181 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) && 5182 isKnownNeverZero(Op.getOperand(0), Depth + 1)) 5183 return true; 5184 break; 5185 5186 case ISD::ZERO_EXTEND: 5187 case ISD::SIGN_EXTEND: 5188 return isKnownNeverZero(Op.getOperand(0), Depth + 1); 5189 } 5190 5191 return computeKnownBits(Op, Depth).isNonZero(); 5192 } 5193 5194 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 5195 // Check the obvious case. 5196 if (A == B) return true; 5197 5198 // For negative and positive zero. 5199 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 5200 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 5201 if (CA->isZero() && CB->isZero()) return true; 5202 5203 // Otherwise they may not be equal. 5204 return false; 5205 } 5206 5207 // Only bits set in Mask must be negated, other bits may be arbitrary. 5208 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) { 5209 if (isBitwiseNot(V, AllowUndefs)) 5210 return V.getOperand(0); 5211 5212 // Handle any_extend (not (truncate X)) pattern, where Mask only sets 5213 // bits in the non-extended part. 5214 ConstantSDNode *MaskC = isConstOrConstSplat(Mask); 5215 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND) 5216 return SDValue(); 5217 SDValue ExtArg = V.getOperand(0); 5218 if (ExtArg.getScalarValueSizeInBits() >= 5219 MaskC->getAPIntValue().getActiveBits() && 5220 isBitwiseNot(ExtArg, AllowUndefs) && 5221 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE && 5222 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType()) 5223 return ExtArg.getOperand(0).getOperand(0); 5224 return SDValue(); 5225 } 5226 5227 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) { 5228 // Match masked merge pattern (X & ~M) op (Y & M) 5229 // Including degenerate case (X & ~M) op M 5230 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask, 5231 SDValue Other) { 5232 if (SDValue NotOperand = 5233 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) { 5234 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND || 5235 NotOperand->getOpcode() == ISD::TRUNCATE) 5236 NotOperand = NotOperand->getOperand(0); 5237 5238 if (Other == NotOperand) 5239 return true; 5240 if (Other->getOpcode() == ISD::AND) 5241 return NotOperand == Other->getOperand(0) || 5242 NotOperand == Other->getOperand(1); 5243 } 5244 return false; 5245 }; 5246 5247 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE) 5248 A = A->getOperand(0); 5249 5250 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE) 5251 B = B->getOperand(0); 5252 5253 if (A->getOpcode() == ISD::AND) 5254 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) || 5255 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B); 5256 return false; 5257 } 5258 5259 // FIXME: unify with llvm::haveNoCommonBitsSet. 5260 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 5261 assert(A.getValueType() == B.getValueType() && 5262 "Values must have the same type"); 5263 if (haveNoCommonBitsSetCommutative(A, B) || 5264 haveNoCommonBitsSetCommutative(B, A)) 5265 return true; 5266 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 5267 computeKnownBits(B)); 5268 } 5269 5270 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 5271 SelectionDAG &DAG) { 5272 if (cast<ConstantSDNode>(Step)->isZero()) 5273 return DAG.getConstant(0, DL, VT); 5274 5275 return SDValue(); 5276 } 5277 5278 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 5279 ArrayRef<SDValue> Ops, 5280 SelectionDAG &DAG) { 5281 int NumOps = Ops.size(); 5282 assert(NumOps != 0 && "Can't build an empty vector!"); 5283 assert(!VT.isScalableVector() && 5284 "BUILD_VECTOR cannot be used with scalable types"); 5285 assert(VT.getVectorNumElements() == (unsigned)NumOps && 5286 "Incorrect element count in BUILD_VECTOR!"); 5287 5288 // BUILD_VECTOR of UNDEFs is UNDEF. 5289 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 5290 return DAG.getUNDEF(VT); 5291 5292 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 5293 SDValue IdentitySrc; 5294 bool IsIdentity = true; 5295 for (int i = 0; i != NumOps; ++i) { 5296 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5297 Ops[i].getOperand(0).getValueType() != VT || 5298 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 5299 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 5300 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 5301 IsIdentity = false; 5302 break; 5303 } 5304 IdentitySrc = Ops[i].getOperand(0); 5305 } 5306 if (IsIdentity) 5307 return IdentitySrc; 5308 5309 return SDValue(); 5310 } 5311 5312 /// Try to simplify vector concatenation to an input value, undef, or build 5313 /// vector. 5314 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 5315 ArrayRef<SDValue> Ops, 5316 SelectionDAG &DAG) { 5317 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 5318 assert(llvm::all_of(Ops, 5319 [Ops](SDValue Op) { 5320 return Ops[0].getValueType() == Op.getValueType(); 5321 }) && 5322 "Concatenation of vectors with inconsistent value types!"); 5323 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 5324 VT.getVectorElementCount() && 5325 "Incorrect element count in vector concatenation!"); 5326 5327 if (Ops.size() == 1) 5328 return Ops[0]; 5329 5330 // Concat of UNDEFs is UNDEF. 5331 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 5332 return DAG.getUNDEF(VT); 5333 5334 // Scan the operands and look for extract operations from a single source 5335 // that correspond to insertion at the same location via this concatenation: 5336 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 5337 SDValue IdentitySrc; 5338 bool IsIdentity = true; 5339 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 5340 SDValue Op = Ops[i]; 5341 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 5342 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 5343 Op.getOperand(0).getValueType() != VT || 5344 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 5345 Op.getConstantOperandVal(1) != IdentityIndex) { 5346 IsIdentity = false; 5347 break; 5348 } 5349 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 5350 "Unexpected identity source vector for concat of extracts"); 5351 IdentitySrc = Op.getOperand(0); 5352 } 5353 if (IsIdentity) { 5354 assert(IdentitySrc && "Failed to set source vector of extracts"); 5355 return IdentitySrc; 5356 } 5357 5358 // The code below this point is only designed to work for fixed width 5359 // vectors, so we bail out for now. 5360 if (VT.isScalableVector()) 5361 return SDValue(); 5362 5363 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 5364 // simplified to one big BUILD_VECTOR. 5365 // FIXME: Add support for SCALAR_TO_VECTOR as well. 5366 EVT SVT = VT.getScalarType(); 5367 SmallVector<SDValue, 16> Elts; 5368 for (SDValue Op : Ops) { 5369 EVT OpVT = Op.getValueType(); 5370 if (Op.isUndef()) 5371 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 5372 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 5373 Elts.append(Op->op_begin(), Op->op_end()); 5374 else 5375 return SDValue(); 5376 } 5377 5378 // BUILD_VECTOR requires all inputs to be of the same type, find the 5379 // maximum type and extend them all. 5380 for (SDValue Op : Elts) 5381 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 5382 5383 if (SVT.bitsGT(VT.getScalarType())) { 5384 for (SDValue &Op : Elts) { 5385 if (Op.isUndef()) 5386 Op = DAG.getUNDEF(SVT); 5387 else 5388 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 5389 ? DAG.getZExtOrTrunc(Op, DL, SVT) 5390 : DAG.getSExtOrTrunc(Op, DL, SVT); 5391 } 5392 } 5393 5394 SDValue V = DAG.getBuildVector(VT, DL, Elts); 5395 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 5396 return V; 5397 } 5398 5399 /// Gets or creates the specified node. 5400 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 5401 FoldingSetNodeID ID; 5402 AddNodeIDNode(ID, Opcode, getVTList(VT), std::nullopt); 5403 void *IP = nullptr; 5404 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5405 return SDValue(E, 0); 5406 5407 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 5408 getVTList(VT)); 5409 CSEMap.InsertNode(N, IP); 5410 5411 InsertNode(N); 5412 SDValue V = SDValue(N, 0); 5413 NewSDValueDbgMsg(V, "Creating new node: ", this); 5414 return V; 5415 } 5416 5417 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5418 SDValue N1) { 5419 SDNodeFlags Flags; 5420 if (Inserter) 5421 Flags = Inserter->getFlags(); 5422 return getNode(Opcode, DL, VT, N1, Flags); 5423 } 5424 5425 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5426 SDValue N1, const SDNodeFlags Flags) { 5427 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!"); 5428 // Constant fold unary operations with an integer constant operand. Even 5429 // opaque constant will be folded, because the folding of unary operations 5430 // doesn't create new constants with different values. Nevertheless, the 5431 // opaque flag is preserved during folding to prevent future folding with 5432 // other constants. 5433 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 5434 const APInt &Val = C->getAPIntValue(); 5435 switch (Opcode) { 5436 default: break; 5437 case ISD::SIGN_EXTEND: 5438 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 5439 C->isTargetOpcode(), C->isOpaque()); 5440 case ISD::TRUNCATE: 5441 if (C->isOpaque()) 5442 break; 5443 [[fallthrough]]; 5444 case ISD::ZERO_EXTEND: 5445 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 5446 C->isTargetOpcode(), C->isOpaque()); 5447 case ISD::ANY_EXTEND: 5448 // Some targets like RISCV prefer to sign extend some types. 5449 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT)) 5450 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 5451 C->isTargetOpcode(), C->isOpaque()); 5452 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 5453 C->isTargetOpcode(), C->isOpaque()); 5454 case ISD::UINT_TO_FP: 5455 case ISD::SINT_TO_FP: { 5456 APFloat apf(EVTToAPFloatSemantics(VT), 5457 APInt::getZero(VT.getSizeInBits())); 5458 (void)apf.convertFromAPInt(Val, 5459 Opcode==ISD::SINT_TO_FP, 5460 APFloat::rmNearestTiesToEven); 5461 return getConstantFP(apf, DL, VT); 5462 } 5463 case ISD::BITCAST: 5464 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 5465 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 5466 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 5467 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 5468 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 5469 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 5470 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 5471 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 5472 break; 5473 case ISD::ABS: 5474 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 5475 C->isOpaque()); 5476 case ISD::BITREVERSE: 5477 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 5478 C->isOpaque()); 5479 case ISD::BSWAP: 5480 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 5481 C->isOpaque()); 5482 case ISD::CTPOP: 5483 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(), 5484 C->isOpaque()); 5485 case ISD::CTLZ: 5486 case ISD::CTLZ_ZERO_UNDEF: 5487 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(), 5488 C->isOpaque()); 5489 case ISD::CTTZ: 5490 case ISD::CTTZ_ZERO_UNDEF: 5491 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(), 5492 C->isOpaque()); 5493 case ISD::FP16_TO_FP: 5494 case ISD::BF16_TO_FP: { 5495 bool Ignored; 5496 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf() 5497 : APFloat::BFloat(), 5498 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 5499 5500 // This can return overflow, underflow, or inexact; we don't care. 5501 // FIXME need to be more flexible about rounding mode. 5502 (void)FPV.convert(EVTToAPFloatSemantics(VT), 5503 APFloat::rmNearestTiesToEven, &Ignored); 5504 return getConstantFP(FPV, DL, VT); 5505 } 5506 case ISD::STEP_VECTOR: { 5507 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this)) 5508 return V; 5509 break; 5510 } 5511 } 5512 } 5513 5514 // Constant fold unary operations with a floating point constant operand. 5515 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N1)) { 5516 APFloat V = C->getValueAPF(); // make copy 5517 switch (Opcode) { 5518 case ISD::FNEG: 5519 V.changeSign(); 5520 return getConstantFP(V, DL, VT); 5521 case ISD::FABS: 5522 V.clearSign(); 5523 return getConstantFP(V, DL, VT); 5524 case ISD::FCEIL: { 5525 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 5526 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5527 return getConstantFP(V, DL, VT); 5528 break; 5529 } 5530 case ISD::FTRUNC: { 5531 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 5532 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5533 return getConstantFP(V, DL, VT); 5534 break; 5535 } 5536 case ISD::FFLOOR: { 5537 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 5538 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5539 return getConstantFP(V, DL, VT); 5540 break; 5541 } 5542 case ISD::FP_EXTEND: { 5543 bool ignored; 5544 // This can return overflow, underflow, or inexact; we don't care. 5545 // FIXME need to be more flexible about rounding mode. 5546 (void)V.convert(EVTToAPFloatSemantics(VT), 5547 APFloat::rmNearestTiesToEven, &ignored); 5548 return getConstantFP(V, DL, VT); 5549 } 5550 case ISD::FP_TO_SINT: 5551 case ISD::FP_TO_UINT: { 5552 bool ignored; 5553 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 5554 // FIXME need to be more flexible about rounding mode. 5555 APFloat::opStatus s = 5556 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 5557 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 5558 break; 5559 return getConstant(IntVal, DL, VT); 5560 } 5561 case ISD::BITCAST: 5562 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 5563 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5564 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 5565 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5566 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 5567 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5568 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 5569 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5570 break; 5571 case ISD::FP_TO_FP16: 5572 case ISD::FP_TO_BF16: { 5573 bool Ignored; 5574 // This can return overflow, underflow, or inexact; we don't care. 5575 // FIXME need to be more flexible about rounding mode. 5576 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf() 5577 : APFloat::BFloat(), 5578 APFloat::rmNearestTiesToEven, &Ignored); 5579 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5580 } 5581 } 5582 } 5583 5584 // Constant fold unary operations with a vector integer or float operand. 5585 switch (Opcode) { 5586 default: 5587 // FIXME: Entirely reasonable to perform folding of other unary 5588 // operations here as the need arises. 5589 break; 5590 case ISD::FNEG: 5591 case ISD::FABS: 5592 case ISD::FCEIL: 5593 case ISD::FTRUNC: 5594 case ISD::FFLOOR: 5595 case ISD::FP_EXTEND: 5596 case ISD::FP_TO_SINT: 5597 case ISD::FP_TO_UINT: 5598 case ISD::TRUNCATE: 5599 case ISD::ANY_EXTEND: 5600 case ISD::ZERO_EXTEND: 5601 case ISD::SIGN_EXTEND: 5602 case ISD::UINT_TO_FP: 5603 case ISD::SINT_TO_FP: 5604 case ISD::ABS: 5605 case ISD::BITREVERSE: 5606 case ISD::BSWAP: 5607 case ISD::CTLZ: 5608 case ISD::CTLZ_ZERO_UNDEF: 5609 case ISD::CTTZ: 5610 case ISD::CTTZ_ZERO_UNDEF: 5611 case ISD::CTPOP: { 5612 SDValue Ops = {N1}; 5613 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5614 return Fold; 5615 } 5616 } 5617 5618 unsigned OpOpcode = N1.getNode()->getOpcode(); 5619 switch (Opcode) { 5620 case ISD::STEP_VECTOR: 5621 assert(VT.isScalableVector() && 5622 "STEP_VECTOR can only be used with scalable types"); 5623 assert(OpOpcode == ISD::TargetConstant && 5624 VT.getVectorElementType() == N1.getValueType() && 5625 "Unexpected step operand"); 5626 break; 5627 case ISD::FREEZE: 5628 assert(VT == N1.getValueType() && "Unexpected VT!"); 5629 if (isGuaranteedNotToBeUndefOrPoison(N1, /*PoisonOnly*/ false, 5630 /*Depth*/ 1)) 5631 return N1; 5632 break; 5633 case ISD::TokenFactor: 5634 case ISD::MERGE_VALUES: 5635 case ISD::CONCAT_VECTORS: 5636 return N1; // Factor, merge or concat of one node? No need. 5637 case ISD::BUILD_VECTOR: { 5638 // Attempt to simplify BUILD_VECTOR. 5639 SDValue Ops[] = {N1}; 5640 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5641 return V; 5642 break; 5643 } 5644 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5645 case ISD::FP_EXTEND: 5646 assert(VT.isFloatingPoint() && N1.getValueType().isFloatingPoint() && 5647 "Invalid FP cast!"); 5648 if (N1.getValueType() == VT) return N1; // noop conversion. 5649 assert((!VT.isVector() || VT.getVectorElementCount() == 5650 N1.getValueType().getVectorElementCount()) && 5651 "Vector element count mismatch!"); 5652 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!"); 5653 if (N1.isUndef()) 5654 return getUNDEF(VT); 5655 break; 5656 case ISD::FP_TO_SINT: 5657 case ISD::FP_TO_UINT: 5658 if (N1.isUndef()) 5659 return getUNDEF(VT); 5660 break; 5661 case ISD::SINT_TO_FP: 5662 case ISD::UINT_TO_FP: 5663 // [us]itofp(undef) = 0, because the result value is bounded. 5664 if (N1.isUndef()) 5665 return getConstantFP(0.0, DL, VT); 5666 break; 5667 case ISD::SIGN_EXTEND: 5668 assert(VT.isInteger() && N1.getValueType().isInteger() && 5669 "Invalid SIGN_EXTEND!"); 5670 assert(VT.isVector() == N1.getValueType().isVector() && 5671 "SIGN_EXTEND result type type should be vector iff the operand " 5672 "type is vector!"); 5673 if (N1.getValueType() == VT) return N1; // noop extension 5674 assert((!VT.isVector() || VT.getVectorElementCount() == 5675 N1.getValueType().getVectorElementCount()) && 5676 "Vector element count mismatch!"); 5677 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!"); 5678 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5679 return getNode(OpOpcode, DL, VT, N1.getOperand(0)); 5680 if (OpOpcode == ISD::UNDEF) 5681 // sext(undef) = 0, because the top bits will all be the same. 5682 return getConstant(0, DL, VT); 5683 break; 5684 case ISD::ZERO_EXTEND: 5685 assert(VT.isInteger() && N1.getValueType().isInteger() && 5686 "Invalid ZERO_EXTEND!"); 5687 assert(VT.isVector() == N1.getValueType().isVector() && 5688 "ZERO_EXTEND result type type should be vector iff the operand " 5689 "type is vector!"); 5690 if (N1.getValueType() == VT) return N1; // noop extension 5691 assert((!VT.isVector() || VT.getVectorElementCount() == 5692 N1.getValueType().getVectorElementCount()) && 5693 "Vector element count mismatch!"); 5694 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!"); 5695 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5696 return getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0)); 5697 if (OpOpcode == ISD::UNDEF) 5698 // zext(undef) = 0, because the top bits will be zero. 5699 return getConstant(0, DL, VT); 5700 break; 5701 case ISD::ANY_EXTEND: 5702 assert(VT.isInteger() && N1.getValueType().isInteger() && 5703 "Invalid ANY_EXTEND!"); 5704 assert(VT.isVector() == N1.getValueType().isVector() && 5705 "ANY_EXTEND result type type should be vector iff the operand " 5706 "type is vector!"); 5707 if (N1.getValueType() == VT) return N1; // noop extension 5708 assert((!VT.isVector() || VT.getVectorElementCount() == 5709 N1.getValueType().getVectorElementCount()) && 5710 "Vector element count mismatch!"); 5711 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!"); 5712 5713 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5714 OpOpcode == ISD::ANY_EXTEND) 5715 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5716 return getNode(OpOpcode, DL, VT, N1.getOperand(0)); 5717 if (OpOpcode == ISD::UNDEF) 5718 return getUNDEF(VT); 5719 5720 // (ext (trunc x)) -> x 5721 if (OpOpcode == ISD::TRUNCATE) { 5722 SDValue OpOp = N1.getOperand(0); 5723 if (OpOp.getValueType() == VT) { 5724 transferDbgValues(N1, OpOp); 5725 return OpOp; 5726 } 5727 } 5728 break; 5729 case ISD::TRUNCATE: 5730 assert(VT.isInteger() && N1.getValueType().isInteger() && 5731 "Invalid TRUNCATE!"); 5732 assert(VT.isVector() == N1.getValueType().isVector() && 5733 "TRUNCATE result type type should be vector iff the operand " 5734 "type is vector!"); 5735 if (N1.getValueType() == VT) return N1; // noop truncate 5736 assert((!VT.isVector() || VT.getVectorElementCount() == 5737 N1.getValueType().getVectorElementCount()) && 5738 "Vector element count mismatch!"); 5739 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!"); 5740 if (OpOpcode == ISD::TRUNCATE) 5741 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0)); 5742 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5743 OpOpcode == ISD::ANY_EXTEND) { 5744 // If the source is smaller than the dest, we still need an extend. 5745 if (N1.getOperand(0).getValueType().getScalarType().bitsLT( 5746 VT.getScalarType())) 5747 return getNode(OpOpcode, DL, VT, N1.getOperand(0)); 5748 if (N1.getOperand(0).getValueType().bitsGT(VT)) 5749 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0)); 5750 return N1.getOperand(0); 5751 } 5752 if (OpOpcode == ISD::UNDEF) 5753 return getUNDEF(VT); 5754 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5755 return getVScale(DL, VT, 5756 N1.getConstantOperandAPInt(0).trunc(VT.getSizeInBits())); 5757 break; 5758 case ISD::ANY_EXTEND_VECTOR_INREG: 5759 case ISD::ZERO_EXTEND_VECTOR_INREG: 5760 case ISD::SIGN_EXTEND_VECTOR_INREG: 5761 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5762 assert(N1.getValueType().bitsLE(VT) && 5763 "The input must be the same size or smaller than the result."); 5764 assert(VT.getVectorMinNumElements() < 5765 N1.getValueType().getVectorMinNumElements() && 5766 "The destination vector type must have fewer lanes than the input."); 5767 break; 5768 case ISD::ABS: 5769 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!"); 5770 if (OpOpcode == ISD::UNDEF) 5771 return getConstant(0, DL, VT); 5772 break; 5773 case ISD::BSWAP: 5774 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!"); 5775 assert((VT.getScalarSizeInBits() % 16 == 0) && 5776 "BSWAP types must be a multiple of 16 bits!"); 5777 if (OpOpcode == ISD::UNDEF) 5778 return getUNDEF(VT); 5779 // bswap(bswap(X)) -> X. 5780 if (OpOpcode == ISD::BSWAP) 5781 return N1.getOperand(0); 5782 break; 5783 case ISD::BITREVERSE: 5784 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!"); 5785 if (OpOpcode == ISD::UNDEF) 5786 return getUNDEF(VT); 5787 break; 5788 case ISD::BITCAST: 5789 assert(VT.getSizeInBits() == N1.getValueSizeInBits() && 5790 "Cannot BITCAST between types of different sizes!"); 5791 if (VT == N1.getValueType()) return N1; // noop conversion. 5792 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5793 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0)); 5794 if (OpOpcode == ISD::UNDEF) 5795 return getUNDEF(VT); 5796 break; 5797 case ISD::SCALAR_TO_VECTOR: 5798 assert(VT.isVector() && !N1.getValueType().isVector() && 5799 (VT.getVectorElementType() == N1.getValueType() || 5800 (VT.getVectorElementType().isInteger() && 5801 N1.getValueType().isInteger() && 5802 VT.getVectorElementType().bitsLE(N1.getValueType()))) && 5803 "Illegal SCALAR_TO_VECTOR node!"); 5804 if (OpOpcode == ISD::UNDEF) 5805 return getUNDEF(VT); 5806 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5807 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5808 isa<ConstantSDNode>(N1.getOperand(1)) && 5809 N1.getConstantOperandVal(1) == 0 && 5810 N1.getOperand(0).getValueType() == VT) 5811 return N1.getOperand(0); 5812 break; 5813 case ISD::FNEG: 5814 // Negation of an unknown bag of bits is still completely undefined. 5815 if (OpOpcode == ISD::UNDEF) 5816 return getUNDEF(VT); 5817 5818 if (OpOpcode == ISD::FNEG) // --X -> X 5819 return N1.getOperand(0); 5820 break; 5821 case ISD::FABS: 5822 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5823 return getNode(ISD::FABS, DL, VT, N1.getOperand(0)); 5824 break; 5825 case ISD::VSCALE: 5826 assert(VT == N1.getValueType() && "Unexpected VT!"); 5827 break; 5828 case ISD::CTPOP: 5829 if (N1.getValueType().getScalarType() == MVT::i1) 5830 return N1; 5831 break; 5832 case ISD::CTLZ: 5833 case ISD::CTTZ: 5834 if (N1.getValueType().getScalarType() == MVT::i1) 5835 return getNOT(DL, N1, N1.getValueType()); 5836 break; 5837 case ISD::VECREDUCE_ADD: 5838 if (N1.getValueType().getScalarType() == MVT::i1) 5839 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1); 5840 break; 5841 case ISD::VECREDUCE_SMIN: 5842 case ISD::VECREDUCE_UMAX: 5843 if (N1.getValueType().getScalarType() == MVT::i1) 5844 return getNode(ISD::VECREDUCE_OR, DL, VT, N1); 5845 break; 5846 case ISD::VECREDUCE_SMAX: 5847 case ISD::VECREDUCE_UMIN: 5848 if (N1.getValueType().getScalarType() == MVT::i1) 5849 return getNode(ISD::VECREDUCE_AND, DL, VT, N1); 5850 break; 5851 } 5852 5853 SDNode *N; 5854 SDVTList VTs = getVTList(VT); 5855 SDValue Ops[] = {N1}; 5856 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5857 FoldingSetNodeID ID; 5858 AddNodeIDNode(ID, Opcode, VTs, Ops); 5859 void *IP = nullptr; 5860 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5861 E->intersectFlagsWith(Flags); 5862 return SDValue(E, 0); 5863 } 5864 5865 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5866 N->setFlags(Flags); 5867 createOperands(N, Ops); 5868 CSEMap.InsertNode(N, IP); 5869 } else { 5870 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5871 createOperands(N, Ops); 5872 } 5873 5874 InsertNode(N); 5875 SDValue V = SDValue(N, 0); 5876 NewSDValueDbgMsg(V, "Creating new node: ", this); 5877 return V; 5878 } 5879 5880 static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5881 const APInt &C2) { 5882 switch (Opcode) { 5883 case ISD::ADD: return C1 + C2; 5884 case ISD::SUB: return C1 - C2; 5885 case ISD::MUL: return C1 * C2; 5886 case ISD::AND: return C1 & C2; 5887 case ISD::OR: return C1 | C2; 5888 case ISD::XOR: return C1 ^ C2; 5889 case ISD::SHL: return C1 << C2; 5890 case ISD::SRL: return C1.lshr(C2); 5891 case ISD::SRA: return C1.ashr(C2); 5892 case ISD::ROTL: return C1.rotl(C2); 5893 case ISD::ROTR: return C1.rotr(C2); 5894 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5895 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5896 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5897 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5898 case ISD::SADDSAT: return C1.sadd_sat(C2); 5899 case ISD::UADDSAT: return C1.uadd_sat(C2); 5900 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5901 case ISD::USUBSAT: return C1.usub_sat(C2); 5902 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5903 case ISD::USHLSAT: return C1.ushl_sat(C2); 5904 case ISD::UDIV: 5905 if (!C2.getBoolValue()) 5906 break; 5907 return C1.udiv(C2); 5908 case ISD::UREM: 5909 if (!C2.getBoolValue()) 5910 break; 5911 return C1.urem(C2); 5912 case ISD::SDIV: 5913 if (!C2.getBoolValue()) 5914 break; 5915 return C1.sdiv(C2); 5916 case ISD::SREM: 5917 if (!C2.getBoolValue()) 5918 break; 5919 return C1.srem(C2); 5920 case ISD::MULHS: { 5921 unsigned FullWidth = C1.getBitWidth() * 2; 5922 APInt C1Ext = C1.sext(FullWidth); 5923 APInt C2Ext = C2.sext(FullWidth); 5924 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5925 } 5926 case ISD::MULHU: { 5927 unsigned FullWidth = C1.getBitWidth() * 2; 5928 APInt C1Ext = C1.zext(FullWidth); 5929 APInt C2Ext = C2.zext(FullWidth); 5930 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5931 } 5932 case ISD::AVGFLOORS: { 5933 unsigned FullWidth = C1.getBitWidth() + 1; 5934 APInt C1Ext = C1.sext(FullWidth); 5935 APInt C2Ext = C2.sext(FullWidth); 5936 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5937 } 5938 case ISD::AVGFLOORU: { 5939 unsigned FullWidth = C1.getBitWidth() + 1; 5940 APInt C1Ext = C1.zext(FullWidth); 5941 APInt C2Ext = C2.zext(FullWidth); 5942 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5943 } 5944 case ISD::AVGCEILS: { 5945 unsigned FullWidth = C1.getBitWidth() + 1; 5946 APInt C1Ext = C1.sext(FullWidth); 5947 APInt C2Ext = C2.sext(FullWidth); 5948 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5949 } 5950 case ISD::AVGCEILU: { 5951 unsigned FullWidth = C1.getBitWidth() + 1; 5952 APInt C1Ext = C1.zext(FullWidth); 5953 APInt C2Ext = C2.zext(FullWidth); 5954 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5955 } 5956 case ISD::ABDS: 5957 return APIntOps::smax(C1, C2) - APIntOps::smin(C1, C2); 5958 case ISD::ABDU: 5959 return APIntOps::umax(C1, C2) - APIntOps::umin(C1, C2); 5960 } 5961 return std::nullopt; 5962 } 5963 5964 // Handle constant folding with UNDEF. 5965 // TODO: Handle more cases. 5966 static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1, 5967 bool IsUndef1, const APInt &C2, 5968 bool IsUndef2) { 5969 if (!(IsUndef1 || IsUndef2)) 5970 return FoldValue(Opcode, C1, C2); 5971 5972 // Fold and(x, undef) -> 0 5973 // Fold mul(x, undef) -> 0 5974 if (Opcode == ISD::AND || Opcode == ISD::MUL) 5975 return APInt::getZero(C1.getBitWidth()); 5976 5977 return std::nullopt; 5978 } 5979 5980 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5981 const GlobalAddressSDNode *GA, 5982 const SDNode *N2) { 5983 if (GA->getOpcode() != ISD::GlobalAddress) 5984 return SDValue(); 5985 if (!TLI->isOffsetFoldingLegal(GA)) 5986 return SDValue(); 5987 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5988 if (!C2) 5989 return SDValue(); 5990 int64_t Offset = C2->getSExtValue(); 5991 switch (Opcode) { 5992 case ISD::ADD: break; 5993 case ISD::SUB: Offset = -uint64_t(Offset); break; 5994 default: return SDValue(); 5995 } 5996 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5997 GA->getOffset() + uint64_t(Offset)); 5998 } 5999 6000 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 6001 switch (Opcode) { 6002 case ISD::SDIV: 6003 case ISD::UDIV: 6004 case ISD::SREM: 6005 case ISD::UREM: { 6006 // If a divisor is zero/undef or any element of a divisor vector is 6007 // zero/undef, the whole op is undef. 6008 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 6009 SDValue Divisor = Ops[1]; 6010 if (Divisor.isUndef() || isNullConstant(Divisor)) 6011 return true; 6012 6013 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 6014 llvm::any_of(Divisor->op_values(), 6015 [](SDValue V) { return V.isUndef() || 6016 isNullConstant(V); }); 6017 // TODO: Handle signed overflow. 6018 } 6019 // TODO: Handle oversized shifts. 6020 default: 6021 return false; 6022 } 6023 } 6024 6025 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 6026 EVT VT, ArrayRef<SDValue> Ops) { 6027 // If the opcode is a target-specific ISD node, there's nothing we can 6028 // do here and the operand rules may not line up with the below, so 6029 // bail early. 6030 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 6031 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 6032 // foldCONCAT_VECTORS in getNode before this is called. 6033 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 6034 return SDValue(); 6035 6036 unsigned NumOps = Ops.size(); 6037 if (NumOps == 0) 6038 return SDValue(); 6039 6040 if (isUndef(Opcode, Ops)) 6041 return getUNDEF(VT); 6042 6043 // Handle binops special cases. 6044 if (NumOps == 2) { 6045 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 6046 return CFP; 6047 6048 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 6049 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 6050 if (C1->isOpaque() || C2->isOpaque()) 6051 return SDValue(); 6052 6053 std::optional<APInt> FoldAttempt = 6054 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 6055 if (!FoldAttempt) 6056 return SDValue(); 6057 6058 SDValue Folded = getConstant(*FoldAttempt, DL, VT); 6059 assert((!Folded || !VT.isVector()) && 6060 "Can't fold vectors ops with scalar operands"); 6061 return Folded; 6062 } 6063 } 6064 6065 // fold (add Sym, c) -> Sym+c 6066 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 6067 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 6068 if (TLI->isCommutativeBinOp(Opcode)) 6069 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 6070 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 6071 } 6072 6073 // This is for vector folding only from here on. 6074 if (!VT.isVector()) 6075 return SDValue(); 6076 6077 ElementCount NumElts = VT.getVectorElementCount(); 6078 6079 // See if we can fold through bitcasted integer ops. 6080 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 6081 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 6082 Ops[0].getOpcode() == ISD::BITCAST && 6083 Ops[1].getOpcode() == ISD::BITCAST) { 6084 SDValue N1 = peekThroughBitcasts(Ops[0]); 6085 SDValue N2 = peekThroughBitcasts(Ops[1]); 6086 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 6087 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 6088 EVT BVVT = N1.getValueType(); 6089 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 6090 bool IsLE = getDataLayout().isLittleEndian(); 6091 unsigned EltBits = VT.getScalarSizeInBits(); 6092 SmallVector<APInt> RawBits1, RawBits2; 6093 BitVector UndefElts1, UndefElts2; 6094 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 6095 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) { 6096 SmallVector<APInt> RawBits; 6097 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 6098 std::optional<APInt> Fold = FoldValueWithUndef( 6099 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]); 6100 if (!Fold) 6101 break; 6102 RawBits.push_back(*Fold); 6103 } 6104 if (RawBits.size() == NumElts.getFixedValue()) { 6105 // We have constant folded, but we need to cast this again back to 6106 // the original (possibly legalized) type. 6107 SmallVector<APInt> DstBits; 6108 BitVector DstUndefs; 6109 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 6110 DstBits, RawBits, DstUndefs, 6111 BitVector(RawBits.size(), false)); 6112 EVT BVEltVT = BV1->getOperand(0).getValueType(); 6113 unsigned BVEltBits = BVEltVT.getSizeInBits(); 6114 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 6115 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 6116 if (DstUndefs[I]) 6117 continue; 6118 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT); 6119 } 6120 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 6121 } 6122 } 6123 } 6124 } 6125 6126 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 6127 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 6128 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 6129 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 6130 APInt RHSVal; 6131 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 6132 APInt NewStep = Opcode == ISD::MUL 6133 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 6134 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 6135 return getStepVector(DL, VT, NewStep); 6136 } 6137 } 6138 6139 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 6140 return !Op.getValueType().isVector() || 6141 Op.getValueType().getVectorElementCount() == NumElts; 6142 }; 6143 6144 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 6145 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 6146 Op.getOpcode() == ISD::BUILD_VECTOR || 6147 Op.getOpcode() == ISD::SPLAT_VECTOR; 6148 }; 6149 6150 // All operands must be vector types with the same number of elements as 6151 // the result type and must be either UNDEF or a build/splat vector 6152 // or UNDEF scalars. 6153 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 6154 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 6155 return SDValue(); 6156 6157 // If we are comparing vectors, then the result needs to be a i1 boolean that 6158 // is then extended back to the legal result type depending on how booleans 6159 // are represented. 6160 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 6161 ISD::NodeType ExtendCode = 6162 (Opcode == ISD::SETCC && SVT != VT.getScalarType()) 6163 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT)) 6164 : ISD::SIGN_EXTEND; 6165 6166 // Find legal integer scalar type for constant promotion and 6167 // ensure that its scalar size is at least as large as source. 6168 EVT LegalSVT = VT.getScalarType(); 6169 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 6170 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 6171 if (LegalSVT.bitsLT(VT.getScalarType())) 6172 return SDValue(); 6173 } 6174 6175 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 6176 // only have one operand to check. For fixed-length vector types we may have 6177 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 6178 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 6179 6180 // Constant fold each scalar lane separately. 6181 SmallVector<SDValue, 4> ScalarResults; 6182 for (unsigned I = 0; I != NumVectorElts; I++) { 6183 SmallVector<SDValue, 4> ScalarOps; 6184 for (SDValue Op : Ops) { 6185 EVT InSVT = Op.getValueType().getScalarType(); 6186 if (Op.getOpcode() != ISD::BUILD_VECTOR && 6187 Op.getOpcode() != ISD::SPLAT_VECTOR) { 6188 if (Op.isUndef()) 6189 ScalarOps.push_back(getUNDEF(InSVT)); 6190 else 6191 ScalarOps.push_back(Op); 6192 continue; 6193 } 6194 6195 SDValue ScalarOp = 6196 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 6197 EVT ScalarVT = ScalarOp.getValueType(); 6198 6199 // Build vector (integer) scalar operands may need implicit 6200 // truncation - do this before constant folding. 6201 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 6202 // Don't create illegally-typed nodes unless they're constants or undef 6203 // - if we fail to constant fold we can't guarantee the (dead) nodes 6204 // we're creating will be cleaned up before being visited for 6205 // legalization. 6206 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 6207 !isa<ConstantSDNode>(ScalarOp) && 6208 TLI->getTypeAction(*getContext(), InSVT) != 6209 TargetLowering::TypeLegal) 6210 return SDValue(); 6211 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 6212 } 6213 6214 ScalarOps.push_back(ScalarOp); 6215 } 6216 6217 // Constant fold the scalar operands. 6218 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 6219 6220 // Legalize the (integer) scalar constant if necessary. 6221 if (LegalSVT != SVT) 6222 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult); 6223 6224 // Scalar folding only succeeded if the result is a constant or UNDEF. 6225 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 6226 ScalarResult.getOpcode() != ISD::ConstantFP) 6227 return SDValue(); 6228 ScalarResults.push_back(ScalarResult); 6229 } 6230 6231 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 6232 : getBuildVector(VT, DL, ScalarResults); 6233 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 6234 return V; 6235 } 6236 6237 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 6238 EVT VT, SDValue N1, SDValue N2) { 6239 // TODO: We don't do any constant folding for strict FP opcodes here, but we 6240 // should. That will require dealing with a potentially non-default 6241 // rounding mode, checking the "opStatus" return value from the APFloat 6242 // math calculations, and possibly other variations. 6243 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 6244 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 6245 if (N1CFP && N2CFP) { 6246 APFloat C1 = N1CFP->getValueAPF(); // make copy 6247 const APFloat &C2 = N2CFP->getValueAPF(); 6248 switch (Opcode) { 6249 case ISD::FADD: 6250 C1.add(C2, APFloat::rmNearestTiesToEven); 6251 return getConstantFP(C1, DL, VT); 6252 case ISD::FSUB: 6253 C1.subtract(C2, APFloat::rmNearestTiesToEven); 6254 return getConstantFP(C1, DL, VT); 6255 case ISD::FMUL: 6256 C1.multiply(C2, APFloat::rmNearestTiesToEven); 6257 return getConstantFP(C1, DL, VT); 6258 case ISD::FDIV: 6259 C1.divide(C2, APFloat::rmNearestTiesToEven); 6260 return getConstantFP(C1, DL, VT); 6261 case ISD::FREM: 6262 C1.mod(C2); 6263 return getConstantFP(C1, DL, VT); 6264 case ISD::FCOPYSIGN: 6265 C1.copySign(C2); 6266 return getConstantFP(C1, DL, VT); 6267 case ISD::FMINNUM: 6268 return getConstantFP(minnum(C1, C2), DL, VT); 6269 case ISD::FMAXNUM: 6270 return getConstantFP(maxnum(C1, C2), DL, VT); 6271 case ISD::FMINIMUM: 6272 return getConstantFP(minimum(C1, C2), DL, VT); 6273 case ISD::FMAXIMUM: 6274 return getConstantFP(maximum(C1, C2), DL, VT); 6275 default: break; 6276 } 6277 } 6278 if (N1CFP && Opcode == ISD::FP_ROUND) { 6279 APFloat C1 = N1CFP->getValueAPF(); // make copy 6280 bool Unused; 6281 // This can return overflow, underflow, or inexact; we don't care. 6282 // FIXME need to be more flexible about rounding mode. 6283 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 6284 &Unused); 6285 return getConstantFP(C1, DL, VT); 6286 } 6287 6288 switch (Opcode) { 6289 case ISD::FSUB: 6290 // -0.0 - undef --> undef (consistent with "fneg undef") 6291 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 6292 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 6293 return getUNDEF(VT); 6294 [[fallthrough]]; 6295 6296 case ISD::FADD: 6297 case ISD::FMUL: 6298 case ISD::FDIV: 6299 case ISD::FREM: 6300 // If both operands are undef, the result is undef. If 1 operand is undef, 6301 // the result is NaN. This should match the behavior of the IR optimizer. 6302 if (N1.isUndef() && N2.isUndef()) 6303 return getUNDEF(VT); 6304 if (N1.isUndef() || N2.isUndef()) 6305 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 6306 } 6307 return SDValue(); 6308 } 6309 6310 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 6311 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 6312 6313 // There's no need to assert on a byte-aligned pointer. All pointers are at 6314 // least byte aligned. 6315 if (A == Align(1)) 6316 return Val; 6317 6318 FoldingSetNodeID ID; 6319 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 6320 ID.AddInteger(A.value()); 6321 6322 void *IP = nullptr; 6323 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 6324 return SDValue(E, 0); 6325 6326 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 6327 Val.getValueType(), A); 6328 createOperands(N, {Val}); 6329 6330 CSEMap.InsertNode(N, IP); 6331 InsertNode(N); 6332 6333 SDValue V(N, 0); 6334 NewSDValueDbgMsg(V, "Creating new node: ", this); 6335 return V; 6336 } 6337 6338 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6339 SDValue N1, SDValue N2) { 6340 SDNodeFlags Flags; 6341 if (Inserter) 6342 Flags = Inserter->getFlags(); 6343 return getNode(Opcode, DL, VT, N1, N2, Flags); 6344 } 6345 6346 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 6347 SDValue &N2) const { 6348 if (!TLI->isCommutativeBinOp(Opcode)) 6349 return; 6350 6351 // Canonicalize: 6352 // binop(const, nonconst) -> binop(nonconst, const) 6353 SDNode *N1C = isConstantIntBuildVectorOrConstantInt(N1); 6354 SDNode *N2C = isConstantIntBuildVectorOrConstantInt(N2); 6355 SDNode *N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 6356 SDNode *N2CFP = isConstantFPBuildVectorOrConstantFP(N2); 6357 if ((N1C && !N2C) || (N1CFP && !N2CFP)) 6358 std::swap(N1, N2); 6359 6360 // Canonicalize: 6361 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 6362 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 6363 N2.getOpcode() == ISD::STEP_VECTOR) 6364 std::swap(N1, N2); 6365 } 6366 6367 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6368 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 6369 assert(N1.getOpcode() != ISD::DELETED_NODE && 6370 N2.getOpcode() != ISD::DELETED_NODE && 6371 "Operand is DELETED_NODE!"); 6372 6373 canonicalizeCommutativeBinop(Opcode, N1, N2); 6374 6375 auto *N1C = dyn_cast<ConstantSDNode>(N1); 6376 auto *N2C = dyn_cast<ConstantSDNode>(N2); 6377 6378 // Don't allow undefs in vector splats - we might be returning N2 when folding 6379 // to zero etc. 6380 ConstantSDNode *N2CV = 6381 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 6382 6383 switch (Opcode) { 6384 default: break; 6385 case ISD::TokenFactor: 6386 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 6387 N2.getValueType() == MVT::Other && "Invalid token factor!"); 6388 // Fold trivial token factors. 6389 if (N1.getOpcode() == ISD::EntryToken) return N2; 6390 if (N2.getOpcode() == ISD::EntryToken) return N1; 6391 if (N1 == N2) return N1; 6392 break; 6393 case ISD::BUILD_VECTOR: { 6394 // Attempt to simplify BUILD_VECTOR. 6395 SDValue Ops[] = {N1, N2}; 6396 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6397 return V; 6398 break; 6399 } 6400 case ISD::CONCAT_VECTORS: { 6401 SDValue Ops[] = {N1, N2}; 6402 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6403 return V; 6404 break; 6405 } 6406 case ISD::AND: 6407 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6408 assert(N1.getValueType() == N2.getValueType() && 6409 N1.getValueType() == VT && "Binary operator types must match!"); 6410 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 6411 // worth handling here. 6412 if (N2CV && N2CV->isZero()) 6413 return N2; 6414 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 6415 return N1; 6416 break; 6417 case ISD::OR: 6418 case ISD::XOR: 6419 case ISD::ADD: 6420 case ISD::SUB: 6421 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6422 assert(N1.getValueType() == N2.getValueType() && 6423 N1.getValueType() == VT && "Binary operator types must match!"); 6424 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 6425 // it's worth handling here. 6426 if (N2CV && N2CV->isZero()) 6427 return N1; 6428 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 6429 VT.getVectorElementType() == MVT::i1) 6430 return getNode(ISD::XOR, DL, VT, N1, N2); 6431 break; 6432 case ISD::MUL: 6433 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6434 assert(N1.getValueType() == N2.getValueType() && 6435 N1.getValueType() == VT && "Binary operator types must match!"); 6436 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6437 return getNode(ISD::AND, DL, VT, N1, N2); 6438 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 6439 const APInt &MulImm = N1->getConstantOperandAPInt(0); 6440 const APInt &N2CImm = N2C->getAPIntValue(); 6441 return getVScale(DL, VT, MulImm * N2CImm); 6442 } 6443 break; 6444 case ISD::UDIV: 6445 case ISD::UREM: 6446 case ISD::MULHU: 6447 case ISD::MULHS: 6448 case ISD::SDIV: 6449 case ISD::SREM: 6450 case ISD::SADDSAT: 6451 case ISD::SSUBSAT: 6452 case ISD::UADDSAT: 6453 case ISD::USUBSAT: 6454 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6455 assert(N1.getValueType() == N2.getValueType() && 6456 N1.getValueType() == VT && "Binary operator types must match!"); 6457 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 6458 // fold (add_sat x, y) -> (or x, y) for bool types. 6459 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 6460 return getNode(ISD::OR, DL, VT, N1, N2); 6461 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 6462 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 6463 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 6464 } 6465 break; 6466 case ISD::ABDS: 6467 case ISD::ABDU: 6468 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6469 assert(N1.getValueType() == N2.getValueType() && 6470 N1.getValueType() == VT && "Binary operator types must match!"); 6471 break; 6472 case ISD::SMIN: 6473 case ISD::UMAX: 6474 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6475 assert(N1.getValueType() == N2.getValueType() && 6476 N1.getValueType() == VT && "Binary operator types must match!"); 6477 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6478 return getNode(ISD::OR, DL, VT, N1, N2); 6479 break; 6480 case ISD::SMAX: 6481 case ISD::UMIN: 6482 assert(VT.isInteger() && "This operator does not apply to FP types!"); 6483 assert(N1.getValueType() == N2.getValueType() && 6484 N1.getValueType() == VT && "Binary operator types must match!"); 6485 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 6486 return getNode(ISD::AND, DL, VT, N1, N2); 6487 break; 6488 case ISD::FADD: 6489 case ISD::FSUB: 6490 case ISD::FMUL: 6491 case ISD::FDIV: 6492 case ISD::FREM: 6493 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6494 assert(N1.getValueType() == N2.getValueType() && 6495 N1.getValueType() == VT && "Binary operator types must match!"); 6496 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 6497 return V; 6498 break; 6499 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 6500 assert(N1.getValueType() == VT && 6501 N1.getValueType().isFloatingPoint() && 6502 N2.getValueType().isFloatingPoint() && 6503 "Invalid FCOPYSIGN!"); 6504 break; 6505 case ISD::SHL: 6506 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 6507 const APInt &MulImm = N1->getConstantOperandAPInt(0); 6508 const APInt &ShiftImm = N2C->getAPIntValue(); 6509 return getVScale(DL, VT, MulImm << ShiftImm); 6510 } 6511 [[fallthrough]]; 6512 case ISD::SRA: 6513 case ISD::SRL: 6514 if (SDValue V = simplifyShift(N1, N2)) 6515 return V; 6516 [[fallthrough]]; 6517 case ISD::ROTL: 6518 case ISD::ROTR: 6519 assert(VT == N1.getValueType() && 6520 "Shift operators return type must be the same as their first arg"); 6521 assert(VT.isInteger() && N2.getValueType().isInteger() && 6522 "Shifts only work on integers"); 6523 assert((!VT.isVector() || VT == N2.getValueType()) && 6524 "Vector shift amounts must be in the same as their first arg"); 6525 // Verify that the shift amount VT is big enough to hold valid shift 6526 // amounts. This catches things like trying to shift an i1024 value by an 6527 // i8, which is easy to fall into in generic code that uses 6528 // TLI.getShiftAmount(). 6529 assert(N2.getValueType().getScalarSizeInBits() >= 6530 Log2_32_Ceil(VT.getScalarSizeInBits()) && 6531 "Invalid use of small shift amount with oversized value!"); 6532 6533 // Always fold shifts of i1 values so the code generator doesn't need to 6534 // handle them. Since we know the size of the shift has to be less than the 6535 // size of the value, the shift/rotate count is guaranteed to be zero. 6536 if (VT == MVT::i1) 6537 return N1; 6538 if (N2CV && N2CV->isZero()) 6539 return N1; 6540 break; 6541 case ISD::FP_ROUND: 6542 assert(VT.isFloatingPoint() && 6543 N1.getValueType().isFloatingPoint() && 6544 VT.bitsLE(N1.getValueType()) && 6545 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 6546 "Invalid FP_ROUND!"); 6547 if (N1.getValueType() == VT) return N1; // noop conversion. 6548 break; 6549 case ISD::AssertSext: 6550 case ISD::AssertZext: { 6551 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6552 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6553 assert(VT.isInteger() && EVT.isInteger() && 6554 "Cannot *_EXTEND_INREG FP types"); 6555 assert(!EVT.isVector() && 6556 "AssertSExt/AssertZExt type should be the vector element type " 6557 "rather than the vector type!"); 6558 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 6559 if (VT.getScalarType() == EVT) return N1; // noop assertion. 6560 break; 6561 } 6562 case ISD::SIGN_EXTEND_INREG: { 6563 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6564 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6565 assert(VT.isInteger() && EVT.isInteger() && 6566 "Cannot *_EXTEND_INREG FP types"); 6567 assert(EVT.isVector() == VT.isVector() && 6568 "SIGN_EXTEND_INREG type should be vector iff the operand " 6569 "type is vector!"); 6570 assert((!EVT.isVector() || 6571 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 6572 "Vector element counts must match in SIGN_EXTEND_INREG"); 6573 assert(EVT.bitsLE(VT) && "Not extending!"); 6574 if (EVT == VT) return N1; // Not actually extending 6575 6576 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 6577 unsigned FromBits = EVT.getScalarSizeInBits(); 6578 Val <<= Val.getBitWidth() - FromBits; 6579 Val.ashrInPlace(Val.getBitWidth() - FromBits); 6580 return getConstant(Val, DL, ConstantVT); 6581 }; 6582 6583 if (N1C) { 6584 const APInt &Val = N1C->getAPIntValue(); 6585 return SignExtendInReg(Val, VT); 6586 } 6587 6588 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 6589 SmallVector<SDValue, 8> Ops; 6590 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 6591 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6592 SDValue Op = N1.getOperand(i); 6593 if (Op.isUndef()) { 6594 Ops.push_back(getUNDEF(OpVT)); 6595 continue; 6596 } 6597 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6598 APInt Val = C->getAPIntValue(); 6599 Ops.push_back(SignExtendInReg(Val, OpVT)); 6600 } 6601 return getBuildVector(VT, DL, Ops); 6602 } 6603 break; 6604 } 6605 case ISD::FP_TO_SINT_SAT: 6606 case ISD::FP_TO_UINT_SAT: { 6607 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6608 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6609 assert(N1.getValueType().isVector() == VT.isVector() && 6610 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6611 "vector!"); 6612 assert((!VT.isVector() || VT.getVectorElementCount() == 6613 N1.getValueType().getVectorElementCount()) && 6614 "Vector element counts must match in FP_TO_*INT_SAT"); 6615 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6616 "Type to saturate to must be a scalar."); 6617 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6618 "Not extending!"); 6619 break; 6620 } 6621 case ISD::EXTRACT_VECTOR_ELT: 6622 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6623 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6624 element type of the vector."); 6625 6626 // Extract from an undefined value or using an undefined index is undefined. 6627 if (N1.isUndef() || N2.isUndef()) 6628 return getUNDEF(VT); 6629 6630 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6631 // vectors. For scalable vectors we will provide appropriate support for 6632 // dealing with arbitrary indices. 6633 if (N2C && N1.getValueType().isFixedLengthVector() && 6634 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6635 return getUNDEF(VT); 6636 6637 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6638 // expanding copies of large vectors from registers. This only works for 6639 // fixed length vectors, since we need to know the exact number of 6640 // elements. 6641 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6642 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6643 unsigned Factor = 6644 N1.getOperand(0).getValueType().getVectorNumElements(); 6645 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6646 N1.getOperand(N2C->getZExtValue() / Factor), 6647 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6648 } 6649 6650 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6651 // lowering is expanding large vector constants. 6652 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6653 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6654 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6655 N1.getValueType().isFixedLengthVector()) && 6656 "BUILD_VECTOR used for scalable vectors"); 6657 unsigned Index = 6658 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6659 SDValue Elt = N1.getOperand(Index); 6660 6661 if (VT != Elt.getValueType()) 6662 // If the vector element type is not legal, the BUILD_VECTOR operands 6663 // are promoted and implicitly truncated, and the result implicitly 6664 // extended. Make that explicit here. 6665 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6666 6667 return Elt; 6668 } 6669 6670 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6671 // operations are lowered to scalars. 6672 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6673 // If the indices are the same, return the inserted element else 6674 // if the indices are known different, extract the element from 6675 // the original vector. 6676 SDValue N1Op2 = N1.getOperand(2); 6677 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6678 6679 if (N1Op2C && N2C) { 6680 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6681 if (VT == N1.getOperand(1).getValueType()) 6682 return N1.getOperand(1); 6683 if (VT.isFloatingPoint()) { 6684 assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits()); 6685 return getFPExtendOrRound(N1.getOperand(1), DL, VT); 6686 } 6687 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6688 } 6689 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6690 } 6691 } 6692 6693 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6694 // when vector types are scalarized and v1iX is legal. 6695 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6696 // Here we are completely ignoring the extract element index (N2), 6697 // which is fine for fixed width vectors, since any index other than 0 6698 // is undefined anyway. However, this cannot be ignored for scalable 6699 // vectors - in theory we could support this, but we don't want to do this 6700 // without a profitability check. 6701 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6702 N1.getValueType().isFixedLengthVector() && 6703 N1.getValueType().getVectorNumElements() == 1) { 6704 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6705 N1.getOperand(1)); 6706 } 6707 break; 6708 case ISD::EXTRACT_ELEMENT: 6709 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6710 assert(!N1.getValueType().isVector() && !VT.isVector() && 6711 (N1.getValueType().isInteger() == VT.isInteger()) && 6712 N1.getValueType() != VT && 6713 "Wrong types for EXTRACT_ELEMENT!"); 6714 6715 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6716 // 64-bit integers into 32-bit parts. Instead of building the extract of 6717 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6718 if (N1.getOpcode() == ISD::BUILD_PAIR) 6719 return N1.getOperand(N2C->getZExtValue()); 6720 6721 // EXTRACT_ELEMENT of a constant int is also very common. 6722 if (N1C) { 6723 unsigned ElementSize = VT.getSizeInBits(); 6724 unsigned Shift = ElementSize * N2C->getZExtValue(); 6725 const APInt &Val = N1C->getAPIntValue(); 6726 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6727 } 6728 break; 6729 case ISD::EXTRACT_SUBVECTOR: { 6730 EVT N1VT = N1.getValueType(); 6731 assert(VT.isVector() && N1VT.isVector() && 6732 "Extract subvector VTs must be vectors!"); 6733 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6734 "Extract subvector VTs must have the same element type!"); 6735 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6736 "Cannot extract a scalable vector from a fixed length vector!"); 6737 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6738 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6739 "Extract subvector must be from larger vector to smaller vector!"); 6740 assert(N2C && "Extract subvector index must be a constant"); 6741 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6742 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6743 N1VT.getVectorMinNumElements()) && 6744 "Extract subvector overflow!"); 6745 assert(N2C->getAPIntValue().getBitWidth() == 6746 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6747 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6748 6749 // Trivial extraction. 6750 if (VT == N1VT) 6751 return N1; 6752 6753 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6754 if (N1.isUndef()) 6755 return getUNDEF(VT); 6756 6757 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6758 // the concat have the same type as the extract. 6759 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6760 VT == N1.getOperand(0).getValueType()) { 6761 unsigned Factor = VT.getVectorMinNumElements(); 6762 return N1.getOperand(N2C->getZExtValue() / Factor); 6763 } 6764 6765 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6766 // during shuffle legalization. 6767 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6768 VT == N1.getOperand(1).getValueType()) 6769 return N1.getOperand(1); 6770 break; 6771 } 6772 } 6773 6774 // Perform trivial constant folding. 6775 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6776 return SV; 6777 6778 // Canonicalize an UNDEF to the RHS, even over a constant. 6779 if (N1.isUndef()) { 6780 if (TLI->isCommutativeBinOp(Opcode)) { 6781 std::swap(N1, N2); 6782 } else { 6783 switch (Opcode) { 6784 case ISD::SUB: 6785 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6786 case ISD::SIGN_EXTEND_INREG: 6787 case ISD::UDIV: 6788 case ISD::SDIV: 6789 case ISD::UREM: 6790 case ISD::SREM: 6791 case ISD::SSUBSAT: 6792 case ISD::USUBSAT: 6793 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6794 } 6795 } 6796 } 6797 6798 // Fold a bunch of operators when the RHS is undef. 6799 if (N2.isUndef()) { 6800 switch (Opcode) { 6801 case ISD::XOR: 6802 if (N1.isUndef()) 6803 // Handle undef ^ undef -> 0 special case. This is a common 6804 // idiom (misuse). 6805 return getConstant(0, DL, VT); 6806 [[fallthrough]]; 6807 case ISD::ADD: 6808 case ISD::SUB: 6809 case ISD::UDIV: 6810 case ISD::SDIV: 6811 case ISD::UREM: 6812 case ISD::SREM: 6813 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6814 case ISD::MUL: 6815 case ISD::AND: 6816 case ISD::SSUBSAT: 6817 case ISD::USUBSAT: 6818 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6819 case ISD::OR: 6820 case ISD::SADDSAT: 6821 case ISD::UADDSAT: 6822 return getAllOnesConstant(DL, VT); 6823 } 6824 } 6825 6826 // Memoize this node if possible. 6827 SDNode *N; 6828 SDVTList VTs = getVTList(VT); 6829 SDValue Ops[] = {N1, N2}; 6830 if (VT != MVT::Glue) { 6831 FoldingSetNodeID ID; 6832 AddNodeIDNode(ID, Opcode, VTs, Ops); 6833 void *IP = nullptr; 6834 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6835 E->intersectFlagsWith(Flags); 6836 return SDValue(E, 0); 6837 } 6838 6839 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6840 N->setFlags(Flags); 6841 createOperands(N, Ops); 6842 CSEMap.InsertNode(N, IP); 6843 } else { 6844 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6845 createOperands(N, Ops); 6846 } 6847 6848 InsertNode(N); 6849 SDValue V = SDValue(N, 0); 6850 NewSDValueDbgMsg(V, "Creating new node: ", this); 6851 return V; 6852 } 6853 6854 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6855 SDValue N1, SDValue N2, SDValue N3) { 6856 SDNodeFlags Flags; 6857 if (Inserter) 6858 Flags = Inserter->getFlags(); 6859 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6860 } 6861 6862 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6863 SDValue N1, SDValue N2, SDValue N3, 6864 const SDNodeFlags Flags) { 6865 assert(N1.getOpcode() != ISD::DELETED_NODE && 6866 N2.getOpcode() != ISD::DELETED_NODE && 6867 N3.getOpcode() != ISD::DELETED_NODE && 6868 "Operand is DELETED_NODE!"); 6869 // Perform various simplifications. 6870 switch (Opcode) { 6871 case ISD::FMA: { 6872 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6873 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6874 N3.getValueType() == VT && "FMA types must match!"); 6875 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6876 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6877 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6878 if (N1CFP && N2CFP && N3CFP) { 6879 APFloat V1 = N1CFP->getValueAPF(); 6880 const APFloat &V2 = N2CFP->getValueAPF(); 6881 const APFloat &V3 = N3CFP->getValueAPF(); 6882 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6883 return getConstantFP(V1, DL, VT); 6884 } 6885 break; 6886 } 6887 case ISD::BUILD_VECTOR: { 6888 // Attempt to simplify BUILD_VECTOR. 6889 SDValue Ops[] = {N1, N2, N3}; 6890 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6891 return V; 6892 break; 6893 } 6894 case ISD::CONCAT_VECTORS: { 6895 SDValue Ops[] = {N1, N2, N3}; 6896 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6897 return V; 6898 break; 6899 } 6900 case ISD::SETCC: { 6901 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6902 assert(N1.getValueType() == N2.getValueType() && 6903 "SETCC operands must have the same type!"); 6904 assert(VT.isVector() == N1.getValueType().isVector() && 6905 "SETCC type should be vector iff the operand type is vector!"); 6906 assert((!VT.isVector() || VT.getVectorElementCount() == 6907 N1.getValueType().getVectorElementCount()) && 6908 "SETCC vector element counts must match!"); 6909 // Use FoldSetCC to simplify SETCC's. 6910 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6911 return V; 6912 // Vector constant folding. 6913 SDValue Ops[] = {N1, N2, N3}; 6914 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6915 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6916 return V; 6917 } 6918 break; 6919 } 6920 case ISD::SELECT: 6921 case ISD::VSELECT: 6922 if (SDValue V = simplifySelect(N1, N2, N3)) 6923 return V; 6924 break; 6925 case ISD::VECTOR_SHUFFLE: 6926 llvm_unreachable("should use getVectorShuffle constructor!"); 6927 case ISD::VECTOR_SPLICE: { 6928 if (cast<ConstantSDNode>(N3)->isZero()) 6929 return N1; 6930 break; 6931 } 6932 case ISD::INSERT_VECTOR_ELT: { 6933 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6934 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6935 // for scalable vectors where we will generate appropriate code to 6936 // deal with out-of-bounds cases correctly. 6937 if (N3C && N1.getValueType().isFixedLengthVector() && 6938 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6939 return getUNDEF(VT); 6940 6941 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6942 if (N3.isUndef()) 6943 return getUNDEF(VT); 6944 6945 // If the inserted element is an UNDEF, just use the input vector. 6946 if (N2.isUndef()) 6947 return N1; 6948 6949 break; 6950 } 6951 case ISD::INSERT_SUBVECTOR: { 6952 // Inserting undef into undef is still undef. 6953 if (N1.isUndef() && N2.isUndef()) 6954 return getUNDEF(VT); 6955 6956 EVT N2VT = N2.getValueType(); 6957 assert(VT == N1.getValueType() && 6958 "Dest and insert subvector source types must match!"); 6959 assert(VT.isVector() && N2VT.isVector() && 6960 "Insert subvector VTs must be vectors!"); 6961 assert(VT.getVectorElementType() == N2VT.getVectorElementType() && 6962 "Insert subvector VTs must have the same element type!"); 6963 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6964 "Cannot insert a scalable vector into a fixed length vector!"); 6965 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6966 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6967 "Insert subvector must be from smaller vector to larger vector!"); 6968 assert(isa<ConstantSDNode>(N3) && 6969 "Insert subvector index must be constant"); 6970 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6971 (N2VT.getVectorMinNumElements() + 6972 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6973 VT.getVectorMinNumElements()) && 6974 "Insert subvector overflow!"); 6975 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6976 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6977 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6978 6979 // Trivial insertion. 6980 if (VT == N2VT) 6981 return N2; 6982 6983 // If this is an insert of an extracted vector into an undef vector, we 6984 // can just use the input to the extract. 6985 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6986 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6987 return N2.getOperand(0); 6988 break; 6989 } 6990 case ISD::BITCAST: 6991 // Fold bit_convert nodes from a type to themselves. 6992 if (N1.getValueType() == VT) 6993 return N1; 6994 break; 6995 case ISD::VP_TRUNCATE: 6996 case ISD::VP_SIGN_EXTEND: 6997 case ISD::VP_ZERO_EXTEND: 6998 // Don't create noop casts. 6999 if (N1.getValueType() == VT) 7000 return N1; 7001 break; 7002 } 7003 7004 // Memoize node if it doesn't produce a flag. 7005 SDNode *N; 7006 SDVTList VTs = getVTList(VT); 7007 SDValue Ops[] = {N1, N2, N3}; 7008 if (VT != MVT::Glue) { 7009 FoldingSetNodeID ID; 7010 AddNodeIDNode(ID, Opcode, VTs, Ops); 7011 void *IP = nullptr; 7012 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 7013 E->intersectFlagsWith(Flags); 7014 return SDValue(E, 0); 7015 } 7016 7017 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7018 N->setFlags(Flags); 7019 createOperands(N, Ops); 7020 CSEMap.InsertNode(N, IP); 7021 } else { 7022 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7023 createOperands(N, Ops); 7024 } 7025 7026 InsertNode(N); 7027 SDValue V = SDValue(N, 0); 7028 NewSDValueDbgMsg(V, "Creating new node: ", this); 7029 return V; 7030 } 7031 7032 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7033 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 7034 SDValue Ops[] = { N1, N2, N3, N4 }; 7035 return getNode(Opcode, DL, VT, Ops); 7036 } 7037 7038 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7039 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 7040 SDValue N5) { 7041 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 7042 return getNode(Opcode, DL, VT, Ops); 7043 } 7044 7045 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 7046 /// the incoming stack arguments to be loaded from the stack. 7047 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 7048 SmallVector<SDValue, 8> ArgChains; 7049 7050 // Include the original chain at the beginning of the list. When this is 7051 // used by target LowerCall hooks, this helps legalize find the 7052 // CALLSEQ_BEGIN node. 7053 ArgChains.push_back(Chain); 7054 7055 // Add a chain value for each stack argument. 7056 for (SDNode *U : getEntryNode().getNode()->uses()) 7057 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 7058 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 7059 if (FI->getIndex() < 0) 7060 ArgChains.push_back(SDValue(L, 1)); 7061 7062 // Build a tokenfactor for all the chains. 7063 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 7064 } 7065 7066 /// getMemsetValue - Vectorized representation of the memset value 7067 /// operand. 7068 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 7069 const SDLoc &dl) { 7070 assert(!Value.isUndef()); 7071 7072 unsigned NumBits = VT.getScalarSizeInBits(); 7073 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 7074 assert(C->getAPIntValue().getBitWidth() == 8); 7075 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 7076 if (VT.isInteger()) { 7077 bool IsOpaque = VT.getSizeInBits() > 64 || 7078 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 7079 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 7080 } 7081 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 7082 VT); 7083 } 7084 7085 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 7086 EVT IntVT = VT.getScalarType(); 7087 if (!IntVT.isInteger()) 7088 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 7089 7090 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 7091 if (NumBits > 8) { 7092 // Use a multiplication with 0x010101... to extend the input to the 7093 // required length. 7094 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 7095 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 7096 DAG.getConstant(Magic, dl, IntVT)); 7097 } 7098 7099 if (VT != Value.getValueType() && !VT.isInteger()) 7100 Value = DAG.getBitcast(VT.getScalarType(), Value); 7101 if (VT != Value.getValueType()) 7102 Value = DAG.getSplatBuildVector(VT, dl, Value); 7103 7104 return Value; 7105 } 7106 7107 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 7108 /// used when a memcpy is turned into a memset when the source is a constant 7109 /// string ptr. 7110 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 7111 const TargetLowering &TLI, 7112 const ConstantDataArraySlice &Slice) { 7113 // Handle vector with all elements zero. 7114 if (Slice.Array == nullptr) { 7115 if (VT.isInteger()) 7116 return DAG.getConstant(0, dl, VT); 7117 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 7118 return DAG.getConstantFP(0.0, dl, VT); 7119 if (VT.isVector()) { 7120 unsigned NumElts = VT.getVectorNumElements(); 7121 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 7122 return DAG.getNode(ISD::BITCAST, dl, VT, 7123 DAG.getConstant(0, dl, 7124 EVT::getVectorVT(*DAG.getContext(), 7125 EltVT, NumElts))); 7126 } 7127 llvm_unreachable("Expected type!"); 7128 } 7129 7130 assert(!VT.isVector() && "Can't handle vector type here!"); 7131 unsigned NumVTBits = VT.getSizeInBits(); 7132 unsigned NumVTBytes = NumVTBits / 8; 7133 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 7134 7135 APInt Val(NumVTBits, 0); 7136 if (DAG.getDataLayout().isLittleEndian()) { 7137 for (unsigned i = 0; i != NumBytes; ++i) 7138 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 7139 } else { 7140 for (unsigned i = 0; i != NumBytes; ++i) 7141 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 7142 } 7143 7144 // If the "cost" of materializing the integer immediate is less than the cost 7145 // of a load, then it is cost effective to turn the load into the immediate. 7146 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 7147 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 7148 return DAG.getConstant(Val, dl, VT); 7149 return SDValue(); 7150 } 7151 7152 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 7153 const SDLoc &DL, 7154 const SDNodeFlags Flags) { 7155 EVT VT = Base.getValueType(); 7156 SDValue Index; 7157 7158 if (Offset.isScalable()) 7159 Index = getVScale(DL, Base.getValueType(), 7160 APInt(Base.getValueSizeInBits().getFixedValue(), 7161 Offset.getKnownMinValue())); 7162 else 7163 Index = getConstant(Offset.getFixedValue(), DL, VT); 7164 7165 return getMemBasePlusOffset(Base, Index, DL, Flags); 7166 } 7167 7168 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 7169 const SDLoc &DL, 7170 const SDNodeFlags Flags) { 7171 assert(Offset.getValueType().isInteger()); 7172 EVT BasePtrVT = Ptr.getValueType(); 7173 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 7174 } 7175 7176 /// Returns true if memcpy source is constant data. 7177 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 7178 uint64_t SrcDelta = 0; 7179 GlobalAddressSDNode *G = nullptr; 7180 if (Src.getOpcode() == ISD::GlobalAddress) 7181 G = cast<GlobalAddressSDNode>(Src); 7182 else if (Src.getOpcode() == ISD::ADD && 7183 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 7184 Src.getOperand(1).getOpcode() == ISD::Constant) { 7185 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 7186 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 7187 } 7188 if (!G) 7189 return false; 7190 7191 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 7192 SrcDelta + G->getOffset()); 7193 } 7194 7195 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 7196 SelectionDAG &DAG) { 7197 // On Darwin, -Os means optimize for size without hurting performance, so 7198 // only really optimize for size when -Oz (MinSize) is used. 7199 if (MF.getTarget().getTargetTriple().isOSDarwin()) 7200 return MF.getFunction().hasMinSize(); 7201 return DAG.shouldOptForSize(); 7202 } 7203 7204 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 7205 SmallVector<SDValue, 32> &OutChains, unsigned From, 7206 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 7207 SmallVector<SDValue, 16> &OutStoreChains) { 7208 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 7209 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 7210 SmallVector<SDValue, 16> GluedLoadChains; 7211 for (unsigned i = From; i < To; ++i) { 7212 OutChains.push_back(OutLoadChains[i]); 7213 GluedLoadChains.push_back(OutLoadChains[i]); 7214 } 7215 7216 // Chain for all loads. 7217 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 7218 GluedLoadChains); 7219 7220 for (unsigned i = From; i < To; ++i) { 7221 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 7222 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 7223 ST->getBasePtr(), ST->getMemoryVT(), 7224 ST->getMemOperand()); 7225 OutChains.push_back(NewStore); 7226 } 7227 } 7228 7229 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 7230 SDValue Chain, SDValue Dst, SDValue Src, 7231 uint64_t Size, Align Alignment, 7232 bool isVol, bool AlwaysInline, 7233 MachinePointerInfo DstPtrInfo, 7234 MachinePointerInfo SrcPtrInfo, 7235 const AAMDNodes &AAInfo, AAResults *AA) { 7236 // Turn a memcpy of undef to nop. 7237 // FIXME: We need to honor volatile even is Src is undef. 7238 if (Src.isUndef()) 7239 return Chain; 7240 7241 // Expand memcpy to a series of load and store ops if the size operand falls 7242 // below a certain threshold. 7243 // TODO: In the AlwaysInline case, if the size is big then generate a loop 7244 // rather than maybe a humongous number of loads and stores. 7245 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7246 const DataLayout &DL = DAG.getDataLayout(); 7247 LLVMContext &C = *DAG.getContext(); 7248 std::vector<EVT> MemOps; 7249 bool DstAlignCanChange = false; 7250 MachineFunction &MF = DAG.getMachineFunction(); 7251 MachineFrameInfo &MFI = MF.getFrameInfo(); 7252 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7253 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7254 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7255 DstAlignCanChange = true; 7256 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 7257 if (!SrcAlign || Alignment > *SrcAlign) 7258 SrcAlign = Alignment; 7259 assert(SrcAlign && "SrcAlign must be set"); 7260 ConstantDataArraySlice Slice; 7261 // If marked as volatile, perform a copy even when marked as constant. 7262 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 7263 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 7264 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 7265 const MemOp Op = isZeroConstant 7266 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 7267 /*IsZeroMemset*/ true, isVol) 7268 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 7269 *SrcAlign, isVol, CopyFromConstant); 7270 if (!TLI.findOptimalMemOpLowering( 7271 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 7272 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 7273 return SDValue(); 7274 7275 if (DstAlignCanChange) { 7276 Type *Ty = MemOps[0].getTypeForEVT(C); 7277 Align NewAlign = DL.getABITypeAlign(Ty); 7278 7279 // Don't promote to an alignment that would require dynamic stack 7280 // realignment which may conflict with optimizations such as tail call 7281 // optimization. 7282 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 7283 if (!TRI->hasStackRealignment(MF)) 7284 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 7285 NewAlign = NewAlign.previous(); 7286 7287 if (NewAlign > Alignment) { 7288 // Give the stack frame object a larger alignment if needed. 7289 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7290 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7291 Alignment = NewAlign; 7292 } 7293 } 7294 7295 // Prepare AAInfo for loads/stores after lowering this memcpy. 7296 AAMDNodes NewAAInfo = AAInfo; 7297 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7298 7299 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V); 7300 bool isConstant = 7301 AA && SrcVal && 7302 AA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo)); 7303 7304 MachineMemOperand::Flags MMOFlags = 7305 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 7306 SmallVector<SDValue, 16> OutLoadChains; 7307 SmallVector<SDValue, 16> OutStoreChains; 7308 SmallVector<SDValue, 32> OutChains; 7309 unsigned NumMemOps = MemOps.size(); 7310 uint64_t SrcOff = 0, DstOff = 0; 7311 for (unsigned i = 0; i != NumMemOps; ++i) { 7312 EVT VT = MemOps[i]; 7313 unsigned VTSize = VT.getSizeInBits() / 8; 7314 SDValue Value, Store; 7315 7316 if (VTSize > Size) { 7317 // Issuing an unaligned load / store pair that overlaps with the previous 7318 // pair. Adjust the offset accordingly. 7319 assert(i == NumMemOps-1 && i != 0); 7320 SrcOff -= VTSize - Size; 7321 DstOff -= VTSize - Size; 7322 } 7323 7324 if (CopyFromConstant && 7325 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 7326 // It's unlikely a store of a vector immediate can be done in a single 7327 // instruction. It would require a load from a constantpool first. 7328 // We only handle zero vectors here. 7329 // FIXME: Handle other cases where store of vector immediate is done in 7330 // a single instruction. 7331 ConstantDataArraySlice SubSlice; 7332 if (SrcOff < Slice.Length) { 7333 SubSlice = Slice; 7334 SubSlice.move(SrcOff); 7335 } else { 7336 // This is an out-of-bounds access and hence UB. Pretend we read zero. 7337 SubSlice.Array = nullptr; 7338 SubSlice.Offset = 0; 7339 SubSlice.Length = VTSize; 7340 } 7341 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 7342 if (Value.getNode()) { 7343 Store = DAG.getStore( 7344 Chain, dl, Value, 7345 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7346 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 7347 OutChains.push_back(Store); 7348 } 7349 } 7350 7351 if (!Store.getNode()) { 7352 // The type might not be legal for the target. This should only happen 7353 // if the type is smaller than a legal type, as on PPC, so the right 7354 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 7355 // to Load/Store if NVT==VT. 7356 // FIXME does the case above also need this? 7357 EVT NVT = TLI.getTypeToTransformTo(C, VT); 7358 assert(NVT.bitsGE(VT)); 7359 7360 bool isDereferenceable = 7361 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 7362 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 7363 if (isDereferenceable) 7364 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 7365 if (isConstant) 7366 SrcMMOFlags |= MachineMemOperand::MOInvariant; 7367 7368 Value = DAG.getExtLoad( 7369 ISD::EXTLOAD, dl, NVT, Chain, 7370 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 7371 SrcPtrInfo.getWithOffset(SrcOff), VT, 7372 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 7373 OutLoadChains.push_back(Value.getValue(1)); 7374 7375 Store = DAG.getTruncStore( 7376 Chain, dl, Value, 7377 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7378 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 7379 OutStoreChains.push_back(Store); 7380 } 7381 SrcOff += VTSize; 7382 DstOff += VTSize; 7383 Size -= VTSize; 7384 } 7385 7386 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 7387 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 7388 unsigned NumLdStInMemcpy = OutStoreChains.size(); 7389 7390 if (NumLdStInMemcpy) { 7391 // It may be that memcpy might be converted to memset if it's memcpy 7392 // of constants. In such a case, we won't have loads and stores, but 7393 // just stores. In the absence of loads, there is nothing to gang up. 7394 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 7395 // If target does not care, just leave as it. 7396 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 7397 OutChains.push_back(OutLoadChains[i]); 7398 OutChains.push_back(OutStoreChains[i]); 7399 } 7400 } else { 7401 // Ld/St less than/equal limit set by target. 7402 if (NumLdStInMemcpy <= GluedLdStLimit) { 7403 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 7404 NumLdStInMemcpy, OutLoadChains, 7405 OutStoreChains); 7406 } else { 7407 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 7408 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 7409 unsigned GlueIter = 0; 7410 7411 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 7412 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 7413 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 7414 7415 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 7416 OutLoadChains, OutStoreChains); 7417 GlueIter += GluedLdStLimit; 7418 } 7419 7420 // Residual ld/st. 7421 if (RemainingLdStInMemcpy) { 7422 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 7423 RemainingLdStInMemcpy, OutLoadChains, 7424 OutStoreChains); 7425 } 7426 } 7427 } 7428 } 7429 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7430 } 7431 7432 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 7433 SDValue Chain, SDValue Dst, SDValue Src, 7434 uint64_t Size, Align Alignment, 7435 bool isVol, bool AlwaysInline, 7436 MachinePointerInfo DstPtrInfo, 7437 MachinePointerInfo SrcPtrInfo, 7438 const AAMDNodes &AAInfo) { 7439 // Turn a memmove of undef to nop. 7440 // FIXME: We need to honor volatile even is Src is undef. 7441 if (Src.isUndef()) 7442 return Chain; 7443 7444 // Expand memmove to a series of load and store ops if the size operand falls 7445 // below a certain threshold. 7446 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7447 const DataLayout &DL = DAG.getDataLayout(); 7448 LLVMContext &C = *DAG.getContext(); 7449 std::vector<EVT> MemOps; 7450 bool DstAlignCanChange = false; 7451 MachineFunction &MF = DAG.getMachineFunction(); 7452 MachineFrameInfo &MFI = MF.getFrameInfo(); 7453 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7454 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7455 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7456 DstAlignCanChange = true; 7457 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 7458 if (!SrcAlign || Alignment > *SrcAlign) 7459 SrcAlign = Alignment; 7460 assert(SrcAlign && "SrcAlign must be set"); 7461 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 7462 if (!TLI.findOptimalMemOpLowering( 7463 MemOps, Limit, 7464 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 7465 /*IsVolatile*/ true), 7466 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 7467 MF.getFunction().getAttributes())) 7468 return SDValue(); 7469 7470 if (DstAlignCanChange) { 7471 Type *Ty = MemOps[0].getTypeForEVT(C); 7472 Align NewAlign = DL.getABITypeAlign(Ty); 7473 7474 // Don't promote to an alignment that would require dynamic stack 7475 // realignment which may conflict with optimizations such as tail call 7476 // optimization. 7477 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 7478 if (!TRI->hasStackRealignment(MF)) 7479 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 7480 NewAlign = NewAlign.previous(); 7481 7482 if (NewAlign > Alignment) { 7483 // Give the stack frame object a larger alignment if needed. 7484 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7485 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7486 Alignment = NewAlign; 7487 } 7488 } 7489 7490 // Prepare AAInfo for loads/stores after lowering this memmove. 7491 AAMDNodes NewAAInfo = AAInfo; 7492 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7493 7494 MachineMemOperand::Flags MMOFlags = 7495 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 7496 uint64_t SrcOff = 0, DstOff = 0; 7497 SmallVector<SDValue, 8> LoadValues; 7498 SmallVector<SDValue, 8> LoadChains; 7499 SmallVector<SDValue, 8> OutChains; 7500 unsigned NumMemOps = MemOps.size(); 7501 for (unsigned i = 0; i < NumMemOps; i++) { 7502 EVT VT = MemOps[i]; 7503 unsigned VTSize = VT.getSizeInBits() / 8; 7504 SDValue Value; 7505 7506 bool isDereferenceable = 7507 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 7508 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 7509 if (isDereferenceable) 7510 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 7511 7512 Value = DAG.getLoad( 7513 VT, dl, Chain, 7514 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 7515 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 7516 LoadValues.push_back(Value); 7517 LoadChains.push_back(Value.getValue(1)); 7518 SrcOff += VTSize; 7519 } 7520 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 7521 OutChains.clear(); 7522 for (unsigned i = 0; i < NumMemOps; i++) { 7523 EVT VT = MemOps[i]; 7524 unsigned VTSize = VT.getSizeInBits() / 8; 7525 SDValue Store; 7526 7527 Store = DAG.getStore( 7528 Chain, dl, LoadValues[i], 7529 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7530 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 7531 OutChains.push_back(Store); 7532 DstOff += VTSize; 7533 } 7534 7535 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7536 } 7537 7538 /// Lower the call to 'memset' intrinsic function into a series of store 7539 /// operations. 7540 /// 7541 /// \param DAG Selection DAG where lowered code is placed. 7542 /// \param dl Link to corresponding IR location. 7543 /// \param Chain Control flow dependency. 7544 /// \param Dst Pointer to destination memory location. 7545 /// \param Src Value of byte to write into the memory. 7546 /// \param Size Number of bytes to write. 7547 /// \param Alignment Alignment of the destination in bytes. 7548 /// \param isVol True if destination is volatile. 7549 /// \param AlwaysInline Makes sure no function call is generated. 7550 /// \param DstPtrInfo IR information on the memory pointer. 7551 /// \returns New head in the control flow, if lowering was successful, empty 7552 /// SDValue otherwise. 7553 /// 7554 /// The function tries to replace 'llvm.memset' intrinsic with several store 7555 /// operations and value calculation code. This is usually profitable for small 7556 /// memory size or when the semantic requires inlining. 7557 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 7558 SDValue Chain, SDValue Dst, SDValue Src, 7559 uint64_t Size, Align Alignment, bool isVol, 7560 bool AlwaysInline, MachinePointerInfo DstPtrInfo, 7561 const AAMDNodes &AAInfo) { 7562 // Turn a memset of undef to nop. 7563 // FIXME: We need to honor volatile even is Src is undef. 7564 if (Src.isUndef()) 7565 return Chain; 7566 7567 // Expand memset to a series of load/store ops if the size operand 7568 // falls below a certain threshold. 7569 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7570 std::vector<EVT> MemOps; 7571 bool DstAlignCanChange = false; 7572 MachineFunction &MF = DAG.getMachineFunction(); 7573 MachineFrameInfo &MFI = MF.getFrameInfo(); 7574 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7575 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7576 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7577 DstAlignCanChange = true; 7578 bool IsZeroVal = isNullConstant(Src); 7579 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize); 7580 7581 if (!TLI.findOptimalMemOpLowering( 7582 MemOps, Limit, 7583 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 7584 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 7585 return SDValue(); 7586 7587 if (DstAlignCanChange) { 7588 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 7589 const DataLayout &DL = DAG.getDataLayout(); 7590 Align NewAlign = DL.getABITypeAlign(Ty); 7591 7592 // Don't promote to an alignment that would require dynamic stack 7593 // realignment which may conflict with optimizations such as tail call 7594 // optimization. 7595 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 7596 if (!TRI->hasStackRealignment(MF)) 7597 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 7598 NewAlign = NewAlign.previous(); 7599 7600 if (NewAlign > Alignment) { 7601 // Give the stack frame object a larger alignment if needed. 7602 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7603 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7604 Alignment = NewAlign; 7605 } 7606 } 7607 7608 SmallVector<SDValue, 8> OutChains; 7609 uint64_t DstOff = 0; 7610 unsigned NumMemOps = MemOps.size(); 7611 7612 // Find the largest store and generate the bit pattern for it. 7613 EVT LargestVT = MemOps[0]; 7614 for (unsigned i = 1; i < NumMemOps; i++) 7615 if (MemOps[i].bitsGT(LargestVT)) 7616 LargestVT = MemOps[i]; 7617 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 7618 7619 // Prepare AAInfo for loads/stores after lowering this memset. 7620 AAMDNodes NewAAInfo = AAInfo; 7621 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7622 7623 for (unsigned i = 0; i < NumMemOps; i++) { 7624 EVT VT = MemOps[i]; 7625 unsigned VTSize = VT.getSizeInBits() / 8; 7626 if (VTSize > Size) { 7627 // Issuing an unaligned load / store pair that overlaps with the previous 7628 // pair. Adjust the offset accordingly. 7629 assert(i == NumMemOps-1 && i != 0); 7630 DstOff -= VTSize - Size; 7631 } 7632 7633 // If this store is smaller than the largest store see whether we can get 7634 // the smaller value for free with a truncate. 7635 SDValue Value = MemSetValue; 7636 if (VT.bitsLT(LargestVT)) { 7637 if (!LargestVT.isVector() && !VT.isVector() && 7638 TLI.isTruncateFree(LargestVT, VT)) 7639 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7640 else 7641 Value = getMemsetValue(Src, VT, DAG, dl); 7642 } 7643 assert(Value.getValueType() == VT && "Value with wrong type."); 7644 SDValue Store = DAG.getStore( 7645 Chain, dl, Value, 7646 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7647 DstPtrInfo.getWithOffset(DstOff), Alignment, 7648 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7649 NewAAInfo); 7650 OutChains.push_back(Store); 7651 DstOff += VT.getSizeInBits() / 8; 7652 Size -= VTSize; 7653 } 7654 7655 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7656 } 7657 7658 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7659 unsigned AS) { 7660 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7661 // pointer operands can be losslessly bitcasted to pointers of address space 0 7662 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7663 report_fatal_error("cannot lower memory intrinsic in address space " + 7664 Twine(AS)); 7665 } 7666 } 7667 7668 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7669 SDValue Src, SDValue Size, Align Alignment, 7670 bool isVol, bool AlwaysInline, bool isTailCall, 7671 MachinePointerInfo DstPtrInfo, 7672 MachinePointerInfo SrcPtrInfo, 7673 const AAMDNodes &AAInfo, AAResults *AA) { 7674 // Check to see if we should lower the memcpy to loads and stores first. 7675 // For cases within the target-specified limits, this is the best choice. 7676 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7677 if (ConstantSize) { 7678 // Memcpy with size zero? Just return the original chain. 7679 if (ConstantSize->isZero()) 7680 return Chain; 7681 7682 SDValue Result = getMemcpyLoadsAndStores( 7683 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7684 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, AA); 7685 if (Result.getNode()) 7686 return Result; 7687 } 7688 7689 // Then check to see if we should lower the memcpy with target-specific 7690 // code. If the target chooses to do this, this is the next best. 7691 if (TSI) { 7692 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7693 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7694 DstPtrInfo, SrcPtrInfo); 7695 if (Result.getNode()) 7696 return Result; 7697 } 7698 7699 // If we really need inline code and the target declined to provide it, 7700 // use a (potentially long) sequence of loads and stores. 7701 if (AlwaysInline) { 7702 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7703 return getMemcpyLoadsAndStores( 7704 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7705 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, AA); 7706 } 7707 7708 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7709 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7710 7711 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7712 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7713 // respect volatile, so they may do things like read or write memory 7714 // beyond the given memory regions. But fixing this isn't easy, and most 7715 // people don't care. 7716 7717 // Emit a library call. 7718 TargetLowering::ArgListTy Args; 7719 TargetLowering::ArgListEntry Entry; 7720 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7721 Entry.Node = Dst; Args.push_back(Entry); 7722 Entry.Node = Src; Args.push_back(Entry); 7723 7724 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7725 Entry.Node = Size; Args.push_back(Entry); 7726 // FIXME: pass in SDLoc 7727 TargetLowering::CallLoweringInfo CLI(*this); 7728 CLI.setDebugLoc(dl) 7729 .setChain(Chain) 7730 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7731 Dst.getValueType().getTypeForEVT(*getContext()), 7732 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7733 TLI->getPointerTy(getDataLayout())), 7734 std::move(Args)) 7735 .setDiscardResult() 7736 .setTailCall(isTailCall); 7737 7738 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7739 return CallResult.second; 7740 } 7741 7742 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7743 SDValue Dst, SDValue Src, SDValue Size, 7744 Type *SizeTy, unsigned ElemSz, 7745 bool isTailCall, 7746 MachinePointerInfo DstPtrInfo, 7747 MachinePointerInfo SrcPtrInfo) { 7748 // Emit a library call. 7749 TargetLowering::ArgListTy Args; 7750 TargetLowering::ArgListEntry Entry; 7751 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7752 Entry.Node = Dst; 7753 Args.push_back(Entry); 7754 7755 Entry.Node = Src; 7756 Args.push_back(Entry); 7757 7758 Entry.Ty = SizeTy; 7759 Entry.Node = Size; 7760 Args.push_back(Entry); 7761 7762 RTLIB::Libcall LibraryCall = 7763 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7764 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7765 report_fatal_error("Unsupported element size"); 7766 7767 TargetLowering::CallLoweringInfo CLI(*this); 7768 CLI.setDebugLoc(dl) 7769 .setChain(Chain) 7770 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7771 Type::getVoidTy(*getContext()), 7772 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7773 TLI->getPointerTy(getDataLayout())), 7774 std::move(Args)) 7775 .setDiscardResult() 7776 .setTailCall(isTailCall); 7777 7778 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7779 return CallResult.second; 7780 } 7781 7782 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7783 SDValue Src, SDValue Size, Align Alignment, 7784 bool isVol, bool isTailCall, 7785 MachinePointerInfo DstPtrInfo, 7786 MachinePointerInfo SrcPtrInfo, 7787 const AAMDNodes &AAInfo, AAResults *AA) { 7788 // Check to see if we should lower the memmove to loads and stores first. 7789 // For cases within the target-specified limits, this is the best choice. 7790 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7791 if (ConstantSize) { 7792 // Memmove with size zero? Just return the original chain. 7793 if (ConstantSize->isZero()) 7794 return Chain; 7795 7796 SDValue Result = getMemmoveLoadsAndStores( 7797 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7798 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7799 if (Result.getNode()) 7800 return Result; 7801 } 7802 7803 // Then check to see if we should lower the memmove with target-specific 7804 // code. If the target chooses to do this, this is the next best. 7805 if (TSI) { 7806 SDValue Result = 7807 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7808 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7809 if (Result.getNode()) 7810 return Result; 7811 } 7812 7813 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7814 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7815 7816 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7817 // not be safe. See memcpy above for more details. 7818 7819 // Emit a library call. 7820 TargetLowering::ArgListTy Args; 7821 TargetLowering::ArgListEntry Entry; 7822 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7823 Entry.Node = Dst; Args.push_back(Entry); 7824 Entry.Node = Src; Args.push_back(Entry); 7825 7826 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7827 Entry.Node = Size; Args.push_back(Entry); 7828 // FIXME: pass in SDLoc 7829 TargetLowering::CallLoweringInfo CLI(*this); 7830 CLI.setDebugLoc(dl) 7831 .setChain(Chain) 7832 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7833 Dst.getValueType().getTypeForEVT(*getContext()), 7834 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7835 TLI->getPointerTy(getDataLayout())), 7836 std::move(Args)) 7837 .setDiscardResult() 7838 .setTailCall(isTailCall); 7839 7840 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7841 return CallResult.second; 7842 } 7843 7844 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7845 SDValue Dst, SDValue Src, SDValue Size, 7846 Type *SizeTy, unsigned ElemSz, 7847 bool isTailCall, 7848 MachinePointerInfo DstPtrInfo, 7849 MachinePointerInfo SrcPtrInfo) { 7850 // Emit a library call. 7851 TargetLowering::ArgListTy Args; 7852 TargetLowering::ArgListEntry Entry; 7853 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7854 Entry.Node = Dst; 7855 Args.push_back(Entry); 7856 7857 Entry.Node = Src; 7858 Args.push_back(Entry); 7859 7860 Entry.Ty = SizeTy; 7861 Entry.Node = Size; 7862 Args.push_back(Entry); 7863 7864 RTLIB::Libcall LibraryCall = 7865 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7866 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7867 report_fatal_error("Unsupported element size"); 7868 7869 TargetLowering::CallLoweringInfo CLI(*this); 7870 CLI.setDebugLoc(dl) 7871 .setChain(Chain) 7872 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7873 Type::getVoidTy(*getContext()), 7874 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7875 TLI->getPointerTy(getDataLayout())), 7876 std::move(Args)) 7877 .setDiscardResult() 7878 .setTailCall(isTailCall); 7879 7880 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7881 return CallResult.second; 7882 } 7883 7884 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7885 SDValue Src, SDValue Size, Align Alignment, 7886 bool isVol, bool AlwaysInline, bool isTailCall, 7887 MachinePointerInfo DstPtrInfo, 7888 const AAMDNodes &AAInfo) { 7889 // Check to see if we should lower the memset to stores first. 7890 // For cases within the target-specified limits, this is the best choice. 7891 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7892 if (ConstantSize) { 7893 // Memset with size zero? Just return the original chain. 7894 if (ConstantSize->isZero()) 7895 return Chain; 7896 7897 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7898 ConstantSize->getZExtValue(), Alignment, 7899 isVol, false, DstPtrInfo, AAInfo); 7900 7901 if (Result.getNode()) 7902 return Result; 7903 } 7904 7905 // Then check to see if we should lower the memset with target-specific 7906 // code. If the target chooses to do this, this is the next best. 7907 if (TSI) { 7908 SDValue Result = TSI->EmitTargetCodeForMemset( 7909 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo); 7910 if (Result.getNode()) 7911 return Result; 7912 } 7913 7914 // If we really need inline code and the target declined to provide it, 7915 // use a (potentially long) sequence of loads and stores. 7916 if (AlwaysInline) { 7917 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7918 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7919 ConstantSize->getZExtValue(), Alignment, 7920 isVol, true, DstPtrInfo, AAInfo); 7921 assert(Result && 7922 "getMemsetStores must return a valid sequence when AlwaysInline"); 7923 return Result; 7924 } 7925 7926 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7927 7928 // Emit a library call. 7929 auto &Ctx = *getContext(); 7930 const auto& DL = getDataLayout(); 7931 7932 TargetLowering::CallLoweringInfo CLI(*this); 7933 // FIXME: pass in SDLoc 7934 CLI.setDebugLoc(dl).setChain(Chain); 7935 7936 ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src); 7937 const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero(); 7938 const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO); 7939 7940 // Helper function to create an Entry from Node and Type. 7941 const auto CreateEntry = [](SDValue Node, Type *Ty) { 7942 TargetLowering::ArgListEntry Entry; 7943 Entry.Node = Node; 7944 Entry.Ty = Ty; 7945 return Entry; 7946 }; 7947 7948 // If zeroing out and bzero is present, use it. 7949 if (SrcIsZero && BzeroName) { 7950 TargetLowering::ArgListTy Args; 7951 Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx))); 7952 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 7953 CLI.setLibCallee( 7954 TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx), 7955 getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args)); 7956 } else { 7957 TargetLowering::ArgListTy Args; 7958 Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx))); 7959 Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx))); 7960 Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx))); 7961 CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7962 Dst.getValueType().getTypeForEVT(Ctx), 7963 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7964 TLI->getPointerTy(DL)), 7965 std::move(Args)); 7966 } 7967 7968 CLI.setDiscardResult().setTailCall(isTailCall); 7969 7970 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7971 return CallResult.second; 7972 } 7973 7974 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7975 SDValue Dst, SDValue Value, SDValue Size, 7976 Type *SizeTy, unsigned ElemSz, 7977 bool isTailCall, 7978 MachinePointerInfo DstPtrInfo) { 7979 // Emit a library call. 7980 TargetLowering::ArgListTy Args; 7981 TargetLowering::ArgListEntry Entry; 7982 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7983 Entry.Node = Dst; 7984 Args.push_back(Entry); 7985 7986 Entry.Ty = Type::getInt8Ty(*getContext()); 7987 Entry.Node = Value; 7988 Args.push_back(Entry); 7989 7990 Entry.Ty = SizeTy; 7991 Entry.Node = Size; 7992 Args.push_back(Entry); 7993 7994 RTLIB::Libcall LibraryCall = 7995 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7996 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7997 report_fatal_error("Unsupported element size"); 7998 7999 TargetLowering::CallLoweringInfo CLI(*this); 8000 CLI.setDebugLoc(dl) 8001 .setChain(Chain) 8002 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 8003 Type::getVoidTy(*getContext()), 8004 getExternalSymbol(TLI->getLibcallName(LibraryCall), 8005 TLI->getPointerTy(getDataLayout())), 8006 std::move(Args)) 8007 .setDiscardResult() 8008 .setTailCall(isTailCall); 8009 8010 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 8011 return CallResult.second; 8012 } 8013 8014 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 8015 SDVTList VTList, ArrayRef<SDValue> Ops, 8016 MachineMemOperand *MMO) { 8017 FoldingSetNodeID ID; 8018 ID.AddInteger(MemVT.getRawBits()); 8019 AddNodeIDNode(ID, Opcode, VTList, Ops); 8020 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8021 ID.AddInteger(MMO->getFlags()); 8022 void* IP = nullptr; 8023 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8024 cast<AtomicSDNode>(E)->refineAlignment(MMO); 8025 return SDValue(E, 0); 8026 } 8027 8028 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 8029 VTList, MemVT, MMO); 8030 createOperands(N, Ops); 8031 8032 CSEMap.InsertNode(N, IP); 8033 InsertNode(N); 8034 return SDValue(N, 0); 8035 } 8036 8037 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 8038 EVT MemVT, SDVTList VTs, SDValue Chain, 8039 SDValue Ptr, SDValue Cmp, SDValue Swp, 8040 MachineMemOperand *MMO) { 8041 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 8042 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 8043 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 8044 8045 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 8046 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 8047 } 8048 8049 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 8050 SDValue Chain, SDValue Ptr, SDValue Val, 8051 MachineMemOperand *MMO) { 8052 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 8053 Opcode == ISD::ATOMIC_LOAD_SUB || 8054 Opcode == ISD::ATOMIC_LOAD_AND || 8055 Opcode == ISD::ATOMIC_LOAD_CLR || 8056 Opcode == ISD::ATOMIC_LOAD_OR || 8057 Opcode == ISD::ATOMIC_LOAD_XOR || 8058 Opcode == ISD::ATOMIC_LOAD_NAND || 8059 Opcode == ISD::ATOMIC_LOAD_MIN || 8060 Opcode == ISD::ATOMIC_LOAD_MAX || 8061 Opcode == ISD::ATOMIC_LOAD_UMIN || 8062 Opcode == ISD::ATOMIC_LOAD_UMAX || 8063 Opcode == ISD::ATOMIC_LOAD_FADD || 8064 Opcode == ISD::ATOMIC_LOAD_FSUB || 8065 Opcode == ISD::ATOMIC_LOAD_FMAX || 8066 Opcode == ISD::ATOMIC_LOAD_FMIN || 8067 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP || 8068 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP || 8069 Opcode == ISD::ATOMIC_SWAP || 8070 Opcode == ISD::ATOMIC_STORE) && 8071 "Invalid Atomic Op"); 8072 8073 EVT VT = Val.getValueType(); 8074 8075 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 8076 getVTList(VT, MVT::Other); 8077 SDValue Ops[] = {Chain, Ptr, Val}; 8078 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 8079 } 8080 8081 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 8082 EVT VT, SDValue Chain, SDValue Ptr, 8083 MachineMemOperand *MMO) { 8084 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 8085 8086 SDVTList VTs = getVTList(VT, MVT::Other); 8087 SDValue Ops[] = {Chain, Ptr}; 8088 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 8089 } 8090 8091 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 8092 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 8093 if (Ops.size() == 1) 8094 return Ops[0]; 8095 8096 SmallVector<EVT, 4> VTs; 8097 VTs.reserve(Ops.size()); 8098 for (const SDValue &Op : Ops) 8099 VTs.push_back(Op.getValueType()); 8100 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 8101 } 8102 8103 SDValue SelectionDAG::getMemIntrinsicNode( 8104 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 8105 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 8106 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 8107 if (!Size && MemVT.isScalableVector()) 8108 Size = MemoryLocation::UnknownSize; 8109 else if (!Size) 8110 Size = MemVT.getStoreSize(); 8111 8112 MachineFunction &MF = getMachineFunction(); 8113 MachineMemOperand *MMO = 8114 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 8115 8116 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 8117 } 8118 8119 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 8120 SDVTList VTList, 8121 ArrayRef<SDValue> Ops, EVT MemVT, 8122 MachineMemOperand *MMO) { 8123 assert((Opcode == ISD::INTRINSIC_VOID || 8124 Opcode == ISD::INTRINSIC_W_CHAIN || 8125 Opcode == ISD::PREFETCH || 8126 (Opcode <= (unsigned)std::numeric_limits<int>::max() && 8127 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 8128 "Opcode is not a memory-accessing opcode!"); 8129 8130 // Memoize the node unless it returns a flag. 8131 MemIntrinsicSDNode *N; 8132 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8133 FoldingSetNodeID ID; 8134 AddNodeIDNode(ID, Opcode, VTList, Ops); 8135 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 8136 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 8137 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8138 ID.AddInteger(MMO->getFlags()); 8139 ID.AddInteger(MemVT.getRawBits()); 8140 void *IP = nullptr; 8141 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8142 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 8143 return SDValue(E, 0); 8144 } 8145 8146 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 8147 VTList, MemVT, MMO); 8148 createOperands(N, Ops); 8149 8150 CSEMap.InsertNode(N, IP); 8151 } else { 8152 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 8153 VTList, MemVT, MMO); 8154 createOperands(N, Ops); 8155 } 8156 InsertNode(N); 8157 SDValue V(N, 0); 8158 NewSDValueDbgMsg(V, "Creating new node: ", this); 8159 return V; 8160 } 8161 8162 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 8163 SDValue Chain, int FrameIndex, 8164 int64_t Size, int64_t Offset) { 8165 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 8166 const auto VTs = getVTList(MVT::Other); 8167 SDValue Ops[2] = { 8168 Chain, 8169 getFrameIndex(FrameIndex, 8170 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 8171 true)}; 8172 8173 FoldingSetNodeID ID; 8174 AddNodeIDNode(ID, Opcode, VTs, Ops); 8175 ID.AddInteger(FrameIndex); 8176 ID.AddInteger(Size); 8177 ID.AddInteger(Offset); 8178 void *IP = nullptr; 8179 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8180 return SDValue(E, 0); 8181 8182 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 8183 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 8184 createOperands(N, Ops); 8185 CSEMap.InsertNode(N, IP); 8186 InsertNode(N); 8187 SDValue V(N, 0); 8188 NewSDValueDbgMsg(V, "Creating new node: ", this); 8189 return V; 8190 } 8191 8192 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 8193 uint64_t Guid, uint64_t Index, 8194 uint32_t Attr) { 8195 const unsigned Opcode = ISD::PSEUDO_PROBE; 8196 const auto VTs = getVTList(MVT::Other); 8197 SDValue Ops[] = {Chain}; 8198 FoldingSetNodeID ID; 8199 AddNodeIDNode(ID, Opcode, VTs, Ops); 8200 ID.AddInteger(Guid); 8201 ID.AddInteger(Index); 8202 void *IP = nullptr; 8203 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 8204 return SDValue(E, 0); 8205 8206 auto *N = newSDNode<PseudoProbeSDNode>( 8207 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 8208 createOperands(N, Ops); 8209 CSEMap.InsertNode(N, IP); 8210 InsertNode(N); 8211 SDValue V(N, 0); 8212 NewSDValueDbgMsg(V, "Creating new node: ", this); 8213 return V; 8214 } 8215 8216 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 8217 /// MachinePointerInfo record from it. This is particularly useful because the 8218 /// code generator has many cases where it doesn't bother passing in a 8219 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 8220 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 8221 SelectionDAG &DAG, SDValue Ptr, 8222 int64_t Offset = 0) { 8223 // If this is FI+Offset, we can model it. 8224 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 8225 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 8226 FI->getIndex(), Offset); 8227 8228 // If this is (FI+Offset1)+Offset2, we can model it. 8229 if (Ptr.getOpcode() != ISD::ADD || 8230 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 8231 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 8232 return Info; 8233 8234 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 8235 return MachinePointerInfo::getFixedStack( 8236 DAG.getMachineFunction(), FI, 8237 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 8238 } 8239 8240 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 8241 /// MachinePointerInfo record from it. This is particularly useful because the 8242 /// code generator has many cases where it doesn't bother passing in a 8243 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 8244 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 8245 SelectionDAG &DAG, SDValue Ptr, 8246 SDValue OffsetOp) { 8247 // If the 'Offset' value isn't a constant, we can't handle this. 8248 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 8249 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 8250 if (OffsetOp.isUndef()) 8251 return InferPointerInfo(Info, DAG, Ptr); 8252 return Info; 8253 } 8254 8255 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 8256 EVT VT, const SDLoc &dl, SDValue Chain, 8257 SDValue Ptr, SDValue Offset, 8258 MachinePointerInfo PtrInfo, EVT MemVT, 8259 Align Alignment, 8260 MachineMemOperand::Flags MMOFlags, 8261 const AAMDNodes &AAInfo, const MDNode *Ranges) { 8262 assert(Chain.getValueType() == MVT::Other && 8263 "Invalid chain type"); 8264 8265 MMOFlags |= MachineMemOperand::MOLoad; 8266 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8267 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8268 // clients. 8269 if (PtrInfo.V.isNull()) 8270 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8271 8272 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 8273 MachineFunction &MF = getMachineFunction(); 8274 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8275 Alignment, AAInfo, Ranges); 8276 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 8277 } 8278 8279 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 8280 EVT VT, const SDLoc &dl, SDValue Chain, 8281 SDValue Ptr, SDValue Offset, EVT MemVT, 8282 MachineMemOperand *MMO) { 8283 if (VT == MemVT) { 8284 ExtType = ISD::NON_EXTLOAD; 8285 } else if (ExtType == ISD::NON_EXTLOAD) { 8286 assert(VT == MemVT && "Non-extending load from different memory type!"); 8287 } else { 8288 // Extending load. 8289 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 8290 "Should only be an extending load, not truncating!"); 8291 assert(VT.isInteger() == MemVT.isInteger() && 8292 "Cannot convert from FP to Int or Int -> FP!"); 8293 assert(VT.isVector() == MemVT.isVector() && 8294 "Cannot use an ext load to convert to or from a vector!"); 8295 assert((!VT.isVector() || 8296 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 8297 "Cannot use an ext load to change the number of vector elements!"); 8298 } 8299 8300 bool Indexed = AM != ISD::UNINDEXED; 8301 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8302 8303 SDVTList VTs = Indexed ? 8304 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 8305 SDValue Ops[] = { Chain, Ptr, Offset }; 8306 FoldingSetNodeID ID; 8307 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 8308 ID.AddInteger(MemVT.getRawBits()); 8309 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 8310 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 8311 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8312 ID.AddInteger(MMO->getFlags()); 8313 void *IP = nullptr; 8314 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8315 cast<LoadSDNode>(E)->refineAlignment(MMO); 8316 return SDValue(E, 0); 8317 } 8318 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8319 ExtType, MemVT, MMO); 8320 createOperands(N, Ops); 8321 8322 CSEMap.InsertNode(N, IP); 8323 InsertNode(N); 8324 SDValue V(N, 0); 8325 NewSDValueDbgMsg(V, "Creating new node: ", this); 8326 return V; 8327 } 8328 8329 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8330 SDValue Ptr, MachinePointerInfo PtrInfo, 8331 MaybeAlign Alignment, 8332 MachineMemOperand::Flags MMOFlags, 8333 const AAMDNodes &AAInfo, const MDNode *Ranges) { 8334 SDValue Undef = getUNDEF(Ptr.getValueType()); 8335 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8336 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 8337 } 8338 8339 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8340 SDValue Ptr, MachineMemOperand *MMO) { 8341 SDValue Undef = getUNDEF(Ptr.getValueType()); 8342 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8343 VT, MMO); 8344 } 8345 8346 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 8347 EVT VT, SDValue Chain, SDValue Ptr, 8348 MachinePointerInfo PtrInfo, EVT MemVT, 8349 MaybeAlign Alignment, 8350 MachineMemOperand::Flags MMOFlags, 8351 const AAMDNodes &AAInfo) { 8352 SDValue Undef = getUNDEF(Ptr.getValueType()); 8353 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 8354 MemVT, Alignment, MMOFlags, AAInfo); 8355 } 8356 8357 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 8358 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 8359 MachineMemOperand *MMO) { 8360 SDValue Undef = getUNDEF(Ptr.getValueType()); 8361 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 8362 MemVT, MMO); 8363 } 8364 8365 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 8366 SDValue Base, SDValue Offset, 8367 ISD::MemIndexedMode AM) { 8368 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 8369 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8370 // Don't propagate the invariant or dereferenceable flags. 8371 auto MMOFlags = 8372 LD->getMemOperand()->getFlags() & 8373 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8374 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8375 LD->getChain(), Base, Offset, LD->getPointerInfo(), 8376 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 8377 } 8378 8379 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8380 SDValue Ptr, MachinePointerInfo PtrInfo, 8381 Align Alignment, 8382 MachineMemOperand::Flags MMOFlags, 8383 const AAMDNodes &AAInfo) { 8384 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8385 8386 MMOFlags |= MachineMemOperand::MOStore; 8387 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8388 8389 if (PtrInfo.V.isNull()) 8390 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8391 8392 MachineFunction &MF = getMachineFunction(); 8393 uint64_t Size = 8394 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 8395 MachineMemOperand *MMO = 8396 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 8397 return getStore(Chain, dl, Val, Ptr, MMO); 8398 } 8399 8400 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8401 SDValue Ptr, MachineMemOperand *MMO) { 8402 assert(Chain.getValueType() == MVT::Other && 8403 "Invalid chain type"); 8404 EVT VT = Val.getValueType(); 8405 SDVTList VTs = getVTList(MVT::Other); 8406 SDValue Undef = getUNDEF(Ptr.getValueType()); 8407 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 8408 FoldingSetNodeID ID; 8409 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 8410 ID.AddInteger(VT.getRawBits()); 8411 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 8412 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 8413 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8414 ID.AddInteger(MMO->getFlags()); 8415 void *IP = nullptr; 8416 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8417 cast<StoreSDNode>(E)->refineAlignment(MMO); 8418 return SDValue(E, 0); 8419 } 8420 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8421 ISD::UNINDEXED, false, VT, MMO); 8422 createOperands(N, Ops); 8423 8424 CSEMap.InsertNode(N, IP); 8425 InsertNode(N); 8426 SDValue V(N, 0); 8427 NewSDValueDbgMsg(V, "Creating new node: ", this); 8428 return V; 8429 } 8430 8431 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8432 SDValue Ptr, MachinePointerInfo PtrInfo, 8433 EVT SVT, Align Alignment, 8434 MachineMemOperand::Flags MMOFlags, 8435 const AAMDNodes &AAInfo) { 8436 assert(Chain.getValueType() == MVT::Other && 8437 "Invalid chain type"); 8438 8439 MMOFlags |= MachineMemOperand::MOStore; 8440 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8441 8442 if (PtrInfo.V.isNull()) 8443 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8444 8445 MachineFunction &MF = getMachineFunction(); 8446 MachineMemOperand *MMO = MF.getMachineMemOperand( 8447 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8448 Alignment, AAInfo); 8449 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 8450 } 8451 8452 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 8453 SDValue Ptr, EVT SVT, 8454 MachineMemOperand *MMO) { 8455 EVT VT = Val.getValueType(); 8456 8457 assert(Chain.getValueType() == MVT::Other && 8458 "Invalid chain type"); 8459 if (VT == SVT) 8460 return getStore(Chain, dl, Val, Ptr, MMO); 8461 8462 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8463 "Should only be a truncating store, not extending!"); 8464 assert(VT.isInteger() == SVT.isInteger() && 8465 "Can't do FP-INT conversion!"); 8466 assert(VT.isVector() == SVT.isVector() && 8467 "Cannot use trunc store to convert to or from a vector!"); 8468 assert((!VT.isVector() || 8469 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8470 "Cannot use trunc store to change the number of vector elements!"); 8471 8472 SDVTList VTs = getVTList(MVT::Other); 8473 SDValue Undef = getUNDEF(Ptr.getValueType()); 8474 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 8475 FoldingSetNodeID ID; 8476 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 8477 ID.AddInteger(SVT.getRawBits()); 8478 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 8479 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 8480 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8481 ID.AddInteger(MMO->getFlags()); 8482 void *IP = nullptr; 8483 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8484 cast<StoreSDNode>(E)->refineAlignment(MMO); 8485 return SDValue(E, 0); 8486 } 8487 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8488 ISD::UNINDEXED, true, SVT, MMO); 8489 createOperands(N, Ops); 8490 8491 CSEMap.InsertNode(N, IP); 8492 InsertNode(N); 8493 SDValue V(N, 0); 8494 NewSDValueDbgMsg(V, "Creating new node: ", this); 8495 return V; 8496 } 8497 8498 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 8499 SDValue Base, SDValue Offset, 8500 ISD::MemIndexedMode AM) { 8501 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 8502 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 8503 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8504 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 8505 FoldingSetNodeID ID; 8506 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 8507 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8508 ID.AddInteger(ST->getRawSubclassData()); 8509 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8510 ID.AddInteger(ST->getMemOperand()->getFlags()); 8511 void *IP = nullptr; 8512 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8513 return SDValue(E, 0); 8514 8515 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8516 ST->isTruncatingStore(), ST->getMemoryVT(), 8517 ST->getMemOperand()); 8518 createOperands(N, Ops); 8519 8520 CSEMap.InsertNode(N, IP); 8521 InsertNode(N); 8522 SDValue V(N, 0); 8523 NewSDValueDbgMsg(V, "Creating new node: ", this); 8524 return V; 8525 } 8526 8527 SDValue SelectionDAG::getLoadVP( 8528 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 8529 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 8530 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8531 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8532 const MDNode *Ranges, bool IsExpanding) { 8533 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8534 8535 MMOFlags |= MachineMemOperand::MOLoad; 8536 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8537 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8538 // clients. 8539 if (PtrInfo.V.isNull()) 8540 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8541 8542 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 8543 MachineFunction &MF = getMachineFunction(); 8544 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8545 Alignment, AAInfo, Ranges); 8546 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 8547 MMO, IsExpanding); 8548 } 8549 8550 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 8551 ISD::LoadExtType ExtType, EVT VT, 8552 const SDLoc &dl, SDValue Chain, SDValue Ptr, 8553 SDValue Offset, SDValue Mask, SDValue EVL, 8554 EVT MemVT, MachineMemOperand *MMO, 8555 bool IsExpanding) { 8556 bool Indexed = AM != ISD::UNINDEXED; 8557 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8558 8559 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8560 : getVTList(VT, MVT::Other); 8561 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 8562 FoldingSetNodeID ID; 8563 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 8564 ID.AddInteger(MemVT.getRawBits()); 8565 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 8566 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8567 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8568 ID.AddInteger(MMO->getFlags()); 8569 void *IP = nullptr; 8570 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8571 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 8572 return SDValue(E, 0); 8573 } 8574 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8575 ExtType, IsExpanding, MemVT, MMO); 8576 createOperands(N, Ops); 8577 8578 CSEMap.InsertNode(N, IP); 8579 InsertNode(N); 8580 SDValue V(N, 0); 8581 NewSDValueDbgMsg(V, "Creating new node: ", this); 8582 return V; 8583 } 8584 8585 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8586 SDValue Ptr, SDValue Mask, SDValue EVL, 8587 MachinePointerInfo PtrInfo, 8588 MaybeAlign Alignment, 8589 MachineMemOperand::Flags MMOFlags, 8590 const AAMDNodes &AAInfo, const MDNode *Ranges, 8591 bool IsExpanding) { 8592 SDValue Undef = getUNDEF(Ptr.getValueType()); 8593 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8594 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 8595 IsExpanding); 8596 } 8597 8598 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 8599 SDValue Ptr, SDValue Mask, SDValue EVL, 8600 MachineMemOperand *MMO, bool IsExpanding) { 8601 SDValue Undef = getUNDEF(Ptr.getValueType()); 8602 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 8603 Mask, EVL, VT, MMO, IsExpanding); 8604 } 8605 8606 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8607 EVT VT, SDValue Chain, SDValue Ptr, 8608 SDValue Mask, SDValue EVL, 8609 MachinePointerInfo PtrInfo, EVT MemVT, 8610 MaybeAlign Alignment, 8611 MachineMemOperand::Flags MMOFlags, 8612 const AAMDNodes &AAInfo, bool IsExpanding) { 8613 SDValue Undef = getUNDEF(Ptr.getValueType()); 8614 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8615 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 8616 IsExpanding); 8617 } 8618 8619 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8620 EVT VT, SDValue Chain, SDValue Ptr, 8621 SDValue Mask, SDValue EVL, EVT MemVT, 8622 MachineMemOperand *MMO, bool IsExpanding) { 8623 SDValue Undef = getUNDEF(Ptr.getValueType()); 8624 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8625 EVL, MemVT, MMO, IsExpanding); 8626 } 8627 8628 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 8629 SDValue Base, SDValue Offset, 8630 ISD::MemIndexedMode AM) { 8631 auto *LD = cast<VPLoadSDNode>(OrigLoad); 8632 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8633 // Don't propagate the invariant or dereferenceable flags. 8634 auto MMOFlags = 8635 LD->getMemOperand()->getFlags() & 8636 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8637 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8638 LD->getChain(), Base, Offset, LD->getMask(), 8639 LD->getVectorLength(), LD->getPointerInfo(), 8640 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 8641 nullptr, LD->isExpandingLoad()); 8642 } 8643 8644 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 8645 SDValue Ptr, SDValue Offset, SDValue Mask, 8646 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 8647 ISD::MemIndexedMode AM, bool IsTruncating, 8648 bool IsCompressing) { 8649 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8650 bool Indexed = AM != ISD::UNINDEXED; 8651 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8652 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8653 : getVTList(MVT::Other); 8654 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 8655 FoldingSetNodeID ID; 8656 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8657 ID.AddInteger(MemVT.getRawBits()); 8658 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8659 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8660 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8661 ID.AddInteger(MMO->getFlags()); 8662 void *IP = nullptr; 8663 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8664 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8665 return SDValue(E, 0); 8666 } 8667 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8668 IsTruncating, IsCompressing, MemVT, MMO); 8669 createOperands(N, Ops); 8670 8671 CSEMap.InsertNode(N, IP); 8672 InsertNode(N); 8673 SDValue V(N, 0); 8674 NewSDValueDbgMsg(V, "Creating new node: ", this); 8675 return V; 8676 } 8677 8678 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8679 SDValue Val, SDValue Ptr, SDValue Mask, 8680 SDValue EVL, MachinePointerInfo PtrInfo, 8681 EVT SVT, Align Alignment, 8682 MachineMemOperand::Flags MMOFlags, 8683 const AAMDNodes &AAInfo, 8684 bool IsCompressing) { 8685 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8686 8687 MMOFlags |= MachineMemOperand::MOStore; 8688 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8689 8690 if (PtrInfo.V.isNull()) 8691 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8692 8693 MachineFunction &MF = getMachineFunction(); 8694 MachineMemOperand *MMO = MF.getMachineMemOperand( 8695 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8696 Alignment, AAInfo); 8697 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8698 IsCompressing); 8699 } 8700 8701 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8702 SDValue Val, SDValue Ptr, SDValue Mask, 8703 SDValue EVL, EVT SVT, 8704 MachineMemOperand *MMO, 8705 bool IsCompressing) { 8706 EVT VT = Val.getValueType(); 8707 8708 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8709 if (VT == SVT) 8710 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8711 EVL, VT, MMO, ISD::UNINDEXED, 8712 /*IsTruncating*/ false, IsCompressing); 8713 8714 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8715 "Should only be a truncating store, not extending!"); 8716 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8717 assert(VT.isVector() == SVT.isVector() && 8718 "Cannot use trunc store to convert to or from a vector!"); 8719 assert((!VT.isVector() || 8720 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8721 "Cannot use trunc store to change the number of vector elements!"); 8722 8723 SDVTList VTs = getVTList(MVT::Other); 8724 SDValue Undef = getUNDEF(Ptr.getValueType()); 8725 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8726 FoldingSetNodeID ID; 8727 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8728 ID.AddInteger(SVT.getRawBits()); 8729 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8730 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8731 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8732 ID.AddInteger(MMO->getFlags()); 8733 void *IP = nullptr; 8734 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8735 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8736 return SDValue(E, 0); 8737 } 8738 auto *N = 8739 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8740 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8741 createOperands(N, Ops); 8742 8743 CSEMap.InsertNode(N, IP); 8744 InsertNode(N); 8745 SDValue V(N, 0); 8746 NewSDValueDbgMsg(V, "Creating new node: ", this); 8747 return V; 8748 } 8749 8750 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8751 SDValue Base, SDValue Offset, 8752 ISD::MemIndexedMode AM) { 8753 auto *ST = cast<VPStoreSDNode>(OrigStore); 8754 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8755 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8756 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8757 Offset, ST->getMask(), ST->getVectorLength()}; 8758 FoldingSetNodeID ID; 8759 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8760 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8761 ID.AddInteger(ST->getRawSubclassData()); 8762 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8763 ID.AddInteger(ST->getMemOperand()->getFlags()); 8764 void *IP = nullptr; 8765 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8766 return SDValue(E, 0); 8767 8768 auto *N = newSDNode<VPStoreSDNode>( 8769 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8770 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8771 createOperands(N, Ops); 8772 8773 CSEMap.InsertNode(N, IP); 8774 InsertNode(N); 8775 SDValue V(N, 0); 8776 NewSDValueDbgMsg(V, "Creating new node: ", this); 8777 return V; 8778 } 8779 8780 SDValue SelectionDAG::getStridedLoadVP( 8781 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8782 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8783 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8784 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8785 const MDNode *Ranges, bool IsExpanding) { 8786 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8787 8788 MMOFlags |= MachineMemOperand::MOLoad; 8789 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8790 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8791 // clients. 8792 if (PtrInfo.V.isNull()) 8793 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8794 8795 uint64_t Size = MemoryLocation::UnknownSize; 8796 MachineFunction &MF = getMachineFunction(); 8797 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8798 Alignment, AAInfo, Ranges); 8799 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8800 EVL, MemVT, MMO, IsExpanding); 8801 } 8802 8803 SDValue SelectionDAG::getStridedLoadVP( 8804 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8805 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8806 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8807 bool Indexed = AM != ISD::UNINDEXED; 8808 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8809 8810 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8811 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8812 : getVTList(VT, MVT::Other); 8813 FoldingSetNodeID ID; 8814 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8815 ID.AddInteger(VT.getRawBits()); 8816 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8817 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8818 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8819 8820 void *IP = nullptr; 8821 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8822 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8823 return SDValue(E, 0); 8824 } 8825 8826 auto *N = 8827 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8828 ExtType, IsExpanding, MemVT, MMO); 8829 createOperands(N, Ops); 8830 CSEMap.InsertNode(N, IP); 8831 InsertNode(N); 8832 SDValue V(N, 0); 8833 NewSDValueDbgMsg(V, "Creating new node: ", this); 8834 return V; 8835 } 8836 8837 SDValue SelectionDAG::getStridedLoadVP( 8838 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8839 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8840 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8841 const MDNode *Ranges, bool IsExpanding) { 8842 SDValue Undef = getUNDEF(Ptr.getValueType()); 8843 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8844 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8845 MMOFlags, AAInfo, Ranges, IsExpanding); 8846 } 8847 8848 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8849 SDValue Ptr, SDValue Stride, 8850 SDValue Mask, SDValue EVL, 8851 MachineMemOperand *MMO, 8852 bool IsExpanding) { 8853 SDValue Undef = getUNDEF(Ptr.getValueType()); 8854 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8855 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8856 } 8857 8858 SDValue SelectionDAG::getExtStridedLoadVP( 8859 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8860 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8861 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8862 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8863 bool IsExpanding) { 8864 SDValue Undef = getUNDEF(Ptr.getValueType()); 8865 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8866 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8867 MMOFlags, AAInfo, nullptr, IsExpanding); 8868 } 8869 8870 SDValue SelectionDAG::getExtStridedLoadVP( 8871 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8872 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8873 MachineMemOperand *MMO, bool IsExpanding) { 8874 SDValue Undef = getUNDEF(Ptr.getValueType()); 8875 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8876 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8877 } 8878 8879 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8880 SDValue Base, SDValue Offset, 8881 ISD::MemIndexedMode AM) { 8882 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8883 assert(SLD->getOffset().isUndef() && 8884 "Strided load is already a indexed load!"); 8885 // Don't propagate the invariant or dereferenceable flags. 8886 auto MMOFlags = 8887 SLD->getMemOperand()->getFlags() & 8888 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8889 return getStridedLoadVP( 8890 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8891 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8892 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8893 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8894 } 8895 8896 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8897 SDValue Val, SDValue Ptr, 8898 SDValue Offset, SDValue Stride, 8899 SDValue Mask, SDValue EVL, EVT MemVT, 8900 MachineMemOperand *MMO, 8901 ISD::MemIndexedMode AM, 8902 bool IsTruncating, bool IsCompressing) { 8903 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8904 bool Indexed = AM != ISD::UNINDEXED; 8905 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8906 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8907 : getVTList(MVT::Other); 8908 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8909 FoldingSetNodeID ID; 8910 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8911 ID.AddInteger(MemVT.getRawBits()); 8912 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8913 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8914 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8915 void *IP = nullptr; 8916 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8917 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8918 return SDValue(E, 0); 8919 } 8920 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8921 VTs, AM, IsTruncating, 8922 IsCompressing, MemVT, MMO); 8923 createOperands(N, Ops); 8924 8925 CSEMap.InsertNode(N, IP); 8926 InsertNode(N); 8927 SDValue V(N, 0); 8928 NewSDValueDbgMsg(V, "Creating new node: ", this); 8929 return V; 8930 } 8931 8932 SDValue SelectionDAG::getTruncStridedStoreVP( 8933 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8934 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8935 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8936 bool IsCompressing) { 8937 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8938 8939 MMOFlags |= MachineMemOperand::MOStore; 8940 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8941 8942 if (PtrInfo.V.isNull()) 8943 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8944 8945 MachineFunction &MF = getMachineFunction(); 8946 MachineMemOperand *MMO = MF.getMachineMemOperand( 8947 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8948 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8949 MMO, IsCompressing); 8950 } 8951 8952 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8953 SDValue Val, SDValue Ptr, 8954 SDValue Stride, SDValue Mask, 8955 SDValue EVL, EVT SVT, 8956 MachineMemOperand *MMO, 8957 bool IsCompressing) { 8958 EVT VT = Val.getValueType(); 8959 8960 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8961 if (VT == SVT) 8962 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8963 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8964 /*IsTruncating*/ false, IsCompressing); 8965 8966 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8967 "Should only be a truncating store, not extending!"); 8968 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8969 assert(VT.isVector() == SVT.isVector() && 8970 "Cannot use trunc store to convert to or from a vector!"); 8971 assert((!VT.isVector() || 8972 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8973 "Cannot use trunc store to change the number of vector elements!"); 8974 8975 SDVTList VTs = getVTList(MVT::Other); 8976 SDValue Undef = getUNDEF(Ptr.getValueType()); 8977 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8978 FoldingSetNodeID ID; 8979 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8980 ID.AddInteger(SVT.getRawBits()); 8981 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8982 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8983 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8984 void *IP = nullptr; 8985 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8986 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8987 return SDValue(E, 0); 8988 } 8989 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8990 VTs, ISD::UNINDEXED, true, 8991 IsCompressing, SVT, MMO); 8992 createOperands(N, Ops); 8993 8994 CSEMap.InsertNode(N, IP); 8995 InsertNode(N); 8996 SDValue V(N, 0); 8997 NewSDValueDbgMsg(V, "Creating new node: ", this); 8998 return V; 8999 } 9000 9001 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 9002 const SDLoc &DL, SDValue Base, 9003 SDValue Offset, 9004 ISD::MemIndexedMode AM) { 9005 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 9006 assert(SST->getOffset().isUndef() && 9007 "Strided store is already an indexed store!"); 9008 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 9009 SDValue Ops[] = { 9010 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 9011 SST->getMask(), SST->getVectorLength()}; 9012 FoldingSetNodeID ID; 9013 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 9014 ID.AddInteger(SST->getMemoryVT().getRawBits()); 9015 ID.AddInteger(SST->getRawSubclassData()); 9016 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 9017 void *IP = nullptr; 9018 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9019 return SDValue(E, 0); 9020 9021 auto *N = newSDNode<VPStridedStoreSDNode>( 9022 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 9023 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 9024 createOperands(N, Ops); 9025 9026 CSEMap.InsertNode(N, IP); 9027 InsertNode(N); 9028 SDValue V(N, 0); 9029 NewSDValueDbgMsg(V, "Creating new node: ", this); 9030 return V; 9031 } 9032 9033 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 9034 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 9035 ISD::MemIndexType IndexType) { 9036 assert(Ops.size() == 6 && "Incompatible number of operands"); 9037 9038 FoldingSetNodeID ID; 9039 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 9040 ID.AddInteger(VT.getRawBits()); 9041 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 9042 dl.getIROrder(), VTs, VT, MMO, IndexType)); 9043 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9044 ID.AddInteger(MMO->getFlags()); 9045 void *IP = nullptr; 9046 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9047 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 9048 return SDValue(E, 0); 9049 } 9050 9051 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 9052 VT, MMO, IndexType); 9053 createOperands(N, Ops); 9054 9055 assert(N->getMask().getValueType().getVectorElementCount() == 9056 N->getValueType(0).getVectorElementCount() && 9057 "Vector width mismatch between mask and data"); 9058 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 9059 N->getValueType(0).getVectorElementCount().isScalable() && 9060 "Scalable flags of index and data do not match"); 9061 assert(ElementCount::isKnownGE( 9062 N->getIndex().getValueType().getVectorElementCount(), 9063 N->getValueType(0).getVectorElementCount()) && 9064 "Vector width mismatch between index and data"); 9065 assert(isa<ConstantSDNode>(N->getScale()) && 9066 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9067 "Scale should be a constant power of 2"); 9068 9069 CSEMap.InsertNode(N, IP); 9070 InsertNode(N); 9071 SDValue V(N, 0); 9072 NewSDValueDbgMsg(V, "Creating new node: ", this); 9073 return V; 9074 } 9075 9076 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 9077 ArrayRef<SDValue> Ops, 9078 MachineMemOperand *MMO, 9079 ISD::MemIndexType IndexType) { 9080 assert(Ops.size() == 7 && "Incompatible number of operands"); 9081 9082 FoldingSetNodeID ID; 9083 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 9084 ID.AddInteger(VT.getRawBits()); 9085 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 9086 dl.getIROrder(), VTs, VT, MMO, IndexType)); 9087 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9088 ID.AddInteger(MMO->getFlags()); 9089 void *IP = nullptr; 9090 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9091 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 9092 return SDValue(E, 0); 9093 } 9094 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 9095 VT, MMO, IndexType); 9096 createOperands(N, Ops); 9097 9098 assert(N->getMask().getValueType().getVectorElementCount() == 9099 N->getValue().getValueType().getVectorElementCount() && 9100 "Vector width mismatch between mask and data"); 9101 assert( 9102 N->getIndex().getValueType().getVectorElementCount().isScalable() == 9103 N->getValue().getValueType().getVectorElementCount().isScalable() && 9104 "Scalable flags of index and data do not match"); 9105 assert(ElementCount::isKnownGE( 9106 N->getIndex().getValueType().getVectorElementCount(), 9107 N->getValue().getValueType().getVectorElementCount()) && 9108 "Vector width mismatch between index and data"); 9109 assert(isa<ConstantSDNode>(N->getScale()) && 9110 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9111 "Scale should be a constant power of 2"); 9112 9113 CSEMap.InsertNode(N, IP); 9114 InsertNode(N); 9115 SDValue V(N, 0); 9116 NewSDValueDbgMsg(V, "Creating new node: ", this); 9117 return V; 9118 } 9119 9120 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 9121 SDValue Base, SDValue Offset, SDValue Mask, 9122 SDValue PassThru, EVT MemVT, 9123 MachineMemOperand *MMO, 9124 ISD::MemIndexedMode AM, 9125 ISD::LoadExtType ExtTy, bool isExpanding) { 9126 bool Indexed = AM != ISD::UNINDEXED; 9127 assert((Indexed || Offset.isUndef()) && 9128 "Unindexed masked load with an offset!"); 9129 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 9130 : getVTList(VT, MVT::Other); 9131 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 9132 FoldingSetNodeID ID; 9133 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 9134 ID.AddInteger(MemVT.getRawBits()); 9135 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 9136 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 9137 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9138 ID.AddInteger(MMO->getFlags()); 9139 void *IP = nullptr; 9140 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9141 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 9142 return SDValue(E, 0); 9143 } 9144 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 9145 AM, ExtTy, isExpanding, MemVT, MMO); 9146 createOperands(N, Ops); 9147 9148 CSEMap.InsertNode(N, IP); 9149 InsertNode(N); 9150 SDValue V(N, 0); 9151 NewSDValueDbgMsg(V, "Creating new node: ", this); 9152 return V; 9153 } 9154 9155 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 9156 SDValue Base, SDValue Offset, 9157 ISD::MemIndexedMode AM) { 9158 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 9159 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 9160 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 9161 Offset, LD->getMask(), LD->getPassThru(), 9162 LD->getMemoryVT(), LD->getMemOperand(), AM, 9163 LD->getExtensionType(), LD->isExpandingLoad()); 9164 } 9165 9166 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 9167 SDValue Val, SDValue Base, SDValue Offset, 9168 SDValue Mask, EVT MemVT, 9169 MachineMemOperand *MMO, 9170 ISD::MemIndexedMode AM, bool IsTruncating, 9171 bool IsCompressing) { 9172 assert(Chain.getValueType() == MVT::Other && 9173 "Invalid chain type"); 9174 bool Indexed = AM != ISD::UNINDEXED; 9175 assert((Indexed || Offset.isUndef()) && 9176 "Unindexed masked store with an offset!"); 9177 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 9178 : getVTList(MVT::Other); 9179 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 9180 FoldingSetNodeID ID; 9181 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 9182 ID.AddInteger(MemVT.getRawBits()); 9183 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 9184 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 9185 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9186 ID.AddInteger(MMO->getFlags()); 9187 void *IP = nullptr; 9188 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9189 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 9190 return SDValue(E, 0); 9191 } 9192 auto *N = 9193 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 9194 IsTruncating, IsCompressing, MemVT, MMO); 9195 createOperands(N, Ops); 9196 9197 CSEMap.InsertNode(N, IP); 9198 InsertNode(N); 9199 SDValue V(N, 0); 9200 NewSDValueDbgMsg(V, "Creating new node: ", this); 9201 return V; 9202 } 9203 9204 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 9205 SDValue Base, SDValue Offset, 9206 ISD::MemIndexedMode AM) { 9207 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 9208 assert(ST->getOffset().isUndef() && 9209 "Masked store is already a indexed store!"); 9210 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 9211 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 9212 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 9213 } 9214 9215 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 9216 ArrayRef<SDValue> Ops, 9217 MachineMemOperand *MMO, 9218 ISD::MemIndexType IndexType, 9219 ISD::LoadExtType ExtTy) { 9220 assert(Ops.size() == 6 && "Incompatible number of operands"); 9221 9222 FoldingSetNodeID ID; 9223 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 9224 ID.AddInteger(MemVT.getRawBits()); 9225 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 9226 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 9227 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9228 ID.AddInteger(MMO->getFlags()); 9229 void *IP = nullptr; 9230 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9231 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 9232 return SDValue(E, 0); 9233 } 9234 9235 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 9236 VTs, MemVT, MMO, IndexType, ExtTy); 9237 createOperands(N, Ops); 9238 9239 assert(N->getPassThru().getValueType() == N->getValueType(0) && 9240 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 9241 assert(N->getMask().getValueType().getVectorElementCount() == 9242 N->getValueType(0).getVectorElementCount() && 9243 "Vector width mismatch between mask and data"); 9244 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 9245 N->getValueType(0).getVectorElementCount().isScalable() && 9246 "Scalable flags of index and data do not match"); 9247 assert(ElementCount::isKnownGE( 9248 N->getIndex().getValueType().getVectorElementCount(), 9249 N->getValueType(0).getVectorElementCount()) && 9250 "Vector width mismatch between index and data"); 9251 assert(isa<ConstantSDNode>(N->getScale()) && 9252 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9253 "Scale should be a constant power of 2"); 9254 9255 CSEMap.InsertNode(N, IP); 9256 InsertNode(N); 9257 SDValue V(N, 0); 9258 NewSDValueDbgMsg(V, "Creating new node: ", this); 9259 return V; 9260 } 9261 9262 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 9263 ArrayRef<SDValue> Ops, 9264 MachineMemOperand *MMO, 9265 ISD::MemIndexType IndexType, 9266 bool IsTrunc) { 9267 assert(Ops.size() == 6 && "Incompatible number of operands"); 9268 9269 FoldingSetNodeID ID; 9270 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 9271 ID.AddInteger(MemVT.getRawBits()); 9272 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 9273 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 9274 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9275 ID.AddInteger(MMO->getFlags()); 9276 void *IP = nullptr; 9277 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 9278 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 9279 return SDValue(E, 0); 9280 } 9281 9282 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 9283 VTs, MemVT, MMO, IndexType, IsTrunc); 9284 createOperands(N, Ops); 9285 9286 assert(N->getMask().getValueType().getVectorElementCount() == 9287 N->getValue().getValueType().getVectorElementCount() && 9288 "Vector width mismatch between mask and data"); 9289 assert( 9290 N->getIndex().getValueType().getVectorElementCount().isScalable() == 9291 N->getValue().getValueType().getVectorElementCount().isScalable() && 9292 "Scalable flags of index and data do not match"); 9293 assert(ElementCount::isKnownGE( 9294 N->getIndex().getValueType().getVectorElementCount(), 9295 N->getValue().getValueType().getVectorElementCount()) && 9296 "Vector width mismatch between index and data"); 9297 assert(isa<ConstantSDNode>(N->getScale()) && 9298 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 9299 "Scale should be a constant power of 2"); 9300 9301 CSEMap.InsertNode(N, IP); 9302 InsertNode(N); 9303 SDValue V(N, 0); 9304 NewSDValueDbgMsg(V, "Creating new node: ", this); 9305 return V; 9306 } 9307 9308 SDValue SelectionDAG::getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, 9309 EVT MemVT, MachineMemOperand *MMO) { 9310 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9311 SDVTList VTs = getVTList(MVT::Other); 9312 SDValue Ops[] = {Chain, Ptr}; 9313 FoldingSetNodeID ID; 9314 AddNodeIDNode(ID, ISD::GET_FPENV_MEM, VTs, Ops); 9315 ID.AddInteger(MemVT.getRawBits()); 9316 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>( 9317 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO)); 9318 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9319 ID.AddInteger(MMO->getFlags()); 9320 void *IP = nullptr; 9321 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 9322 return SDValue(E, 0); 9323 9324 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(), 9325 dl.getDebugLoc(), VTs, MemVT, MMO); 9326 createOperands(N, Ops); 9327 9328 CSEMap.InsertNode(N, IP); 9329 InsertNode(N); 9330 SDValue V(N, 0); 9331 NewSDValueDbgMsg(V, "Creating new node: ", this); 9332 return V; 9333 } 9334 9335 SDValue SelectionDAG::getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, 9336 EVT MemVT, MachineMemOperand *MMO) { 9337 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 9338 SDVTList VTs = getVTList(MVT::Other); 9339 SDValue Ops[] = {Chain, Ptr}; 9340 FoldingSetNodeID ID; 9341 AddNodeIDNode(ID, ISD::SET_FPENV_MEM, VTs, Ops); 9342 ID.AddInteger(MemVT.getRawBits()); 9343 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>( 9344 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO)); 9345 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 9346 ID.AddInteger(MMO->getFlags()); 9347 void *IP = nullptr; 9348 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 9349 return SDValue(E, 0); 9350 9351 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(), 9352 dl.getDebugLoc(), VTs, MemVT, MMO); 9353 createOperands(N, Ops); 9354 9355 CSEMap.InsertNode(N, IP); 9356 InsertNode(N); 9357 SDValue V(N, 0); 9358 NewSDValueDbgMsg(V, "Creating new node: ", this); 9359 return V; 9360 } 9361 9362 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 9363 // select undef, T, F --> T (if T is a constant), otherwise F 9364 // select, ?, undef, F --> F 9365 // select, ?, T, undef --> T 9366 if (Cond.isUndef()) 9367 return isConstantValueOfAnyType(T) ? T : F; 9368 if (T.isUndef()) 9369 return F; 9370 if (F.isUndef()) 9371 return T; 9372 9373 // select true, T, F --> T 9374 // select false, T, F --> F 9375 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 9376 return CondC->isZero() ? F : T; 9377 9378 // TODO: This should simplify VSELECT with non-zero constant condition using 9379 // something like this (but check boolean contents to be complete?): 9380 if (ConstantSDNode *CondC = isConstOrConstSplat(Cond, /*AllowUndefs*/ false, 9381 /*AllowTruncation*/ true)) 9382 if (CondC->isZero()) 9383 return F; 9384 9385 // select ?, T, T --> T 9386 if (T == F) 9387 return T; 9388 9389 return SDValue(); 9390 } 9391 9392 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 9393 // shift undef, Y --> 0 (can always assume that the undef value is 0) 9394 if (X.isUndef()) 9395 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 9396 // shift X, undef --> undef (because it may shift by the bitwidth) 9397 if (Y.isUndef()) 9398 return getUNDEF(X.getValueType()); 9399 9400 // shift 0, Y --> 0 9401 // shift X, 0 --> X 9402 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 9403 return X; 9404 9405 // shift X, C >= bitwidth(X) --> undef 9406 // All vector elements must be too big (or undef) to avoid partial undefs. 9407 auto isShiftTooBig = [X](ConstantSDNode *Val) { 9408 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 9409 }; 9410 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 9411 return getUNDEF(X.getValueType()); 9412 9413 return SDValue(); 9414 } 9415 9416 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 9417 SDNodeFlags Flags) { 9418 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 9419 // (an undef operand can be chosen to be Nan/Inf), then the result of this 9420 // operation is poison. That result can be relaxed to undef. 9421 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 9422 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 9423 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 9424 (YC && YC->getValueAPF().isNaN()); 9425 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 9426 (YC && YC->getValueAPF().isInfinity()); 9427 9428 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 9429 return getUNDEF(X.getValueType()); 9430 9431 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 9432 return getUNDEF(X.getValueType()); 9433 9434 if (!YC) 9435 return SDValue(); 9436 9437 // X + -0.0 --> X 9438 if (Opcode == ISD::FADD) 9439 if (YC->getValueAPF().isNegZero()) 9440 return X; 9441 9442 // X - +0.0 --> X 9443 if (Opcode == ISD::FSUB) 9444 if (YC->getValueAPF().isPosZero()) 9445 return X; 9446 9447 // X * 1.0 --> X 9448 // X / 1.0 --> X 9449 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 9450 if (YC->getValueAPF().isExactlyValue(1.0)) 9451 return X; 9452 9453 // X * 0.0 --> 0.0 9454 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 9455 if (YC->getValueAPF().isZero()) 9456 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 9457 9458 return SDValue(); 9459 } 9460 9461 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 9462 SDValue Ptr, SDValue SV, unsigned Align) { 9463 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 9464 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 9465 } 9466 9467 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 9468 ArrayRef<SDUse> Ops) { 9469 switch (Ops.size()) { 9470 case 0: return getNode(Opcode, DL, VT); 9471 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 9472 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 9473 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 9474 default: break; 9475 } 9476 9477 // Copy from an SDUse array into an SDValue array for use with 9478 // the regular getNode logic. 9479 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 9480 return getNode(Opcode, DL, VT, NewOps); 9481 } 9482 9483 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 9484 ArrayRef<SDValue> Ops) { 9485 SDNodeFlags Flags; 9486 if (Inserter) 9487 Flags = Inserter->getFlags(); 9488 return getNode(Opcode, DL, VT, Ops, Flags); 9489 } 9490 9491 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 9492 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 9493 unsigned NumOps = Ops.size(); 9494 switch (NumOps) { 9495 case 0: return getNode(Opcode, DL, VT); 9496 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 9497 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 9498 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 9499 default: break; 9500 } 9501 9502 #ifndef NDEBUG 9503 for (const auto &Op : Ops) 9504 assert(Op.getOpcode() != ISD::DELETED_NODE && 9505 "Operand is DELETED_NODE!"); 9506 #endif 9507 9508 switch (Opcode) { 9509 default: break; 9510 case ISD::BUILD_VECTOR: 9511 // Attempt to simplify BUILD_VECTOR. 9512 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 9513 return V; 9514 break; 9515 case ISD::CONCAT_VECTORS: 9516 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 9517 return V; 9518 break; 9519 case ISD::SELECT_CC: 9520 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 9521 assert(Ops[0].getValueType() == Ops[1].getValueType() && 9522 "LHS and RHS of condition must have same type!"); 9523 assert(Ops[2].getValueType() == Ops[3].getValueType() && 9524 "True and False arms of SelectCC must have same type!"); 9525 assert(Ops[2].getValueType() == VT && 9526 "select_cc node must be of same type as true and false value!"); 9527 assert((!Ops[0].getValueType().isVector() || 9528 Ops[0].getValueType().getVectorElementCount() == 9529 VT.getVectorElementCount()) && 9530 "Expected select_cc with vector result to have the same sized " 9531 "comparison type!"); 9532 break; 9533 case ISD::BR_CC: 9534 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 9535 assert(Ops[2].getValueType() == Ops[3].getValueType() && 9536 "LHS/RHS of comparison should match types!"); 9537 break; 9538 case ISD::VP_ADD: 9539 case ISD::VP_SUB: 9540 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR 9541 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 9542 Opcode = ISD::VP_XOR; 9543 break; 9544 case ISD::VP_MUL: 9545 // If it is VP_MUL mask operation then turn it to VP_AND 9546 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 9547 Opcode = ISD::VP_AND; 9548 break; 9549 case ISD::VP_REDUCE_MUL: 9550 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND 9551 if (VT == MVT::i1) 9552 Opcode = ISD::VP_REDUCE_AND; 9553 break; 9554 case ISD::VP_REDUCE_ADD: 9555 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR 9556 if (VT == MVT::i1) 9557 Opcode = ISD::VP_REDUCE_XOR; 9558 break; 9559 case ISD::VP_REDUCE_SMAX: 9560 case ISD::VP_REDUCE_UMIN: 9561 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to 9562 // VP_REDUCE_AND. 9563 if (VT == MVT::i1) 9564 Opcode = ISD::VP_REDUCE_AND; 9565 break; 9566 case ISD::VP_REDUCE_SMIN: 9567 case ISD::VP_REDUCE_UMAX: 9568 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to 9569 // VP_REDUCE_OR. 9570 if (VT == MVT::i1) 9571 Opcode = ISD::VP_REDUCE_OR; 9572 break; 9573 } 9574 9575 // Memoize nodes. 9576 SDNode *N; 9577 SDVTList VTs = getVTList(VT); 9578 9579 if (VT != MVT::Glue) { 9580 FoldingSetNodeID ID; 9581 AddNodeIDNode(ID, Opcode, VTs, Ops); 9582 void *IP = nullptr; 9583 9584 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9585 return SDValue(E, 0); 9586 9587 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9588 createOperands(N, Ops); 9589 9590 CSEMap.InsertNode(N, IP); 9591 } else { 9592 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9593 createOperands(N, Ops); 9594 } 9595 9596 N->setFlags(Flags); 9597 InsertNode(N); 9598 SDValue V(N, 0); 9599 NewSDValueDbgMsg(V, "Creating new node: ", this); 9600 return V; 9601 } 9602 9603 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 9604 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 9605 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 9606 } 9607 9608 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9609 ArrayRef<SDValue> Ops) { 9610 SDNodeFlags Flags; 9611 if (Inserter) 9612 Flags = Inserter->getFlags(); 9613 return getNode(Opcode, DL, VTList, Ops, Flags); 9614 } 9615 9616 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9617 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 9618 if (VTList.NumVTs == 1) 9619 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags); 9620 9621 #ifndef NDEBUG 9622 for (const auto &Op : Ops) 9623 assert(Op.getOpcode() != ISD::DELETED_NODE && 9624 "Operand is DELETED_NODE!"); 9625 #endif 9626 9627 switch (Opcode) { 9628 case ISD::SADDO: 9629 case ISD::UADDO: 9630 case ISD::SSUBO: 9631 case ISD::USUBO: { 9632 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 9633 "Invalid add/sub overflow op!"); 9634 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() && 9635 Ops[0].getValueType() == Ops[1].getValueType() && 9636 Ops[0].getValueType() == VTList.VTs[0] && 9637 "Binary operator types must match!"); 9638 SDValue N1 = Ops[0], N2 = Ops[1]; 9639 canonicalizeCommutativeBinop(Opcode, N1, N2); 9640 9641 // (X +- 0) -> X with zero-overflow. 9642 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false, 9643 /*AllowTruncation*/ true); 9644 if (N2CV && N2CV->isZero()) { 9645 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]); 9646 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags); 9647 } 9648 break; 9649 } 9650 case ISD::SMUL_LOHI: 9651 case ISD::UMUL_LOHI: { 9652 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!"); 9653 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] && 9654 VTList.VTs[0] == Ops[0].getValueType() && 9655 VTList.VTs[0] == Ops[1].getValueType() && 9656 "Binary operator types must match!"); 9657 break; 9658 } 9659 case ISD::FFREXP: { 9660 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!"); 9661 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() && 9662 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch"); 9663 9664 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Ops[0])) { 9665 int FrexpExp; 9666 APFloat FrexpMant = 9667 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven); 9668 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]); 9669 SDValue Result1 = 9670 getConstant(FrexpMant.isFinite() ? FrexpExp : 0, DL, VTList.VTs[1]); 9671 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags); 9672 } 9673 9674 break; 9675 } 9676 case ISD::STRICT_FP_EXTEND: 9677 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 9678 "Invalid STRICT_FP_EXTEND!"); 9679 assert(VTList.VTs[0].isFloatingPoint() && 9680 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 9681 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9682 "STRICT_FP_EXTEND result type should be vector iff the operand " 9683 "type is vector!"); 9684 assert((!VTList.VTs[0].isVector() || 9685 VTList.VTs[0].getVectorElementCount() == 9686 Ops[1].getValueType().getVectorElementCount()) && 9687 "Vector element count mismatch!"); 9688 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 9689 "Invalid fpext node, dst <= src!"); 9690 break; 9691 case ISD::STRICT_FP_ROUND: 9692 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 9693 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 9694 "STRICT_FP_ROUND result type should be vector iff the operand " 9695 "type is vector!"); 9696 assert((!VTList.VTs[0].isVector() || 9697 VTList.VTs[0].getVectorElementCount() == 9698 Ops[1].getValueType().getVectorElementCount()) && 9699 "Vector element count mismatch!"); 9700 assert(VTList.VTs[0].isFloatingPoint() && 9701 Ops[1].getValueType().isFloatingPoint() && 9702 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 9703 isa<ConstantSDNode>(Ops[2]) && 9704 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 9705 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 9706 "Invalid STRICT_FP_ROUND!"); 9707 break; 9708 #if 0 9709 // FIXME: figure out how to safely handle things like 9710 // int foo(int x) { return 1 << (x & 255); } 9711 // int bar() { return foo(256); } 9712 case ISD::SRA_PARTS: 9713 case ISD::SRL_PARTS: 9714 case ISD::SHL_PARTS: 9715 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 9716 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 9717 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9718 else if (N3.getOpcode() == ISD::AND) 9719 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 9720 // If the and is only masking out bits that cannot effect the shift, 9721 // eliminate the and. 9722 unsigned NumBits = VT.getScalarSizeInBits()*2; 9723 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 9724 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9725 } 9726 break; 9727 #endif 9728 } 9729 9730 // Memoize the node unless it returns a flag. 9731 SDNode *N; 9732 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 9733 FoldingSetNodeID ID; 9734 AddNodeIDNode(ID, Opcode, VTList, Ops); 9735 void *IP = nullptr; 9736 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9737 return SDValue(E, 0); 9738 9739 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9740 createOperands(N, Ops); 9741 CSEMap.InsertNode(N, IP); 9742 } else { 9743 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9744 createOperands(N, Ops); 9745 } 9746 9747 N->setFlags(Flags); 9748 InsertNode(N); 9749 SDValue V(N, 0); 9750 NewSDValueDbgMsg(V, "Creating new node: ", this); 9751 return V; 9752 } 9753 9754 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 9755 SDVTList VTList) { 9756 return getNode(Opcode, DL, VTList, std::nullopt); 9757 } 9758 9759 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9760 SDValue N1) { 9761 SDValue Ops[] = { N1 }; 9762 return getNode(Opcode, DL, VTList, Ops); 9763 } 9764 9765 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9766 SDValue N1, SDValue N2) { 9767 SDValue Ops[] = { N1, N2 }; 9768 return getNode(Opcode, DL, VTList, Ops); 9769 } 9770 9771 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9772 SDValue N1, SDValue N2, SDValue N3) { 9773 SDValue Ops[] = { N1, N2, N3 }; 9774 return getNode(Opcode, DL, VTList, Ops); 9775 } 9776 9777 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9778 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 9779 SDValue Ops[] = { N1, N2, N3, N4 }; 9780 return getNode(Opcode, DL, VTList, Ops); 9781 } 9782 9783 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9784 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 9785 SDValue N5) { 9786 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 9787 return getNode(Opcode, DL, VTList, Ops); 9788 } 9789 9790 SDVTList SelectionDAG::getVTList(EVT VT) { 9791 return makeVTList(SDNode::getValueTypeList(VT), 1); 9792 } 9793 9794 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 9795 FoldingSetNodeID ID; 9796 ID.AddInteger(2U); 9797 ID.AddInteger(VT1.getRawBits()); 9798 ID.AddInteger(VT2.getRawBits()); 9799 9800 void *IP = nullptr; 9801 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9802 if (!Result) { 9803 EVT *Array = Allocator.Allocate<EVT>(2); 9804 Array[0] = VT1; 9805 Array[1] = VT2; 9806 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 9807 VTListMap.InsertNode(Result, IP); 9808 } 9809 return Result->getSDVTList(); 9810 } 9811 9812 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 9813 FoldingSetNodeID ID; 9814 ID.AddInteger(3U); 9815 ID.AddInteger(VT1.getRawBits()); 9816 ID.AddInteger(VT2.getRawBits()); 9817 ID.AddInteger(VT3.getRawBits()); 9818 9819 void *IP = nullptr; 9820 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9821 if (!Result) { 9822 EVT *Array = Allocator.Allocate<EVT>(3); 9823 Array[0] = VT1; 9824 Array[1] = VT2; 9825 Array[2] = VT3; 9826 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9827 VTListMap.InsertNode(Result, IP); 9828 } 9829 return Result->getSDVTList(); 9830 } 9831 9832 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9833 FoldingSetNodeID ID; 9834 ID.AddInteger(4U); 9835 ID.AddInteger(VT1.getRawBits()); 9836 ID.AddInteger(VT2.getRawBits()); 9837 ID.AddInteger(VT3.getRawBits()); 9838 ID.AddInteger(VT4.getRawBits()); 9839 9840 void *IP = nullptr; 9841 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9842 if (!Result) { 9843 EVT *Array = Allocator.Allocate<EVT>(4); 9844 Array[0] = VT1; 9845 Array[1] = VT2; 9846 Array[2] = VT3; 9847 Array[3] = VT4; 9848 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9849 VTListMap.InsertNode(Result, IP); 9850 } 9851 return Result->getSDVTList(); 9852 } 9853 9854 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9855 unsigned NumVTs = VTs.size(); 9856 FoldingSetNodeID ID; 9857 ID.AddInteger(NumVTs); 9858 for (unsigned index = 0; index < NumVTs; index++) { 9859 ID.AddInteger(VTs[index].getRawBits()); 9860 } 9861 9862 void *IP = nullptr; 9863 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9864 if (!Result) { 9865 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9866 llvm::copy(VTs, Array); 9867 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9868 VTListMap.InsertNode(Result, IP); 9869 } 9870 return Result->getSDVTList(); 9871 } 9872 9873 9874 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9875 /// specified operands. If the resultant node already exists in the DAG, 9876 /// this does not modify the specified node, instead it returns the node that 9877 /// already exists. If the resultant node does not exist in the DAG, the 9878 /// input node is returned. As a degenerate case, if you specify the same 9879 /// input operands as the node already has, the input node is returned. 9880 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9881 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9882 9883 // Check to see if there is no change. 9884 if (Op == N->getOperand(0)) return N; 9885 9886 // See if the modified node already exists. 9887 void *InsertPos = nullptr; 9888 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9889 return Existing; 9890 9891 // Nope it doesn't. Remove the node from its current place in the maps. 9892 if (InsertPos) 9893 if (!RemoveNodeFromCSEMaps(N)) 9894 InsertPos = nullptr; 9895 9896 // Now we update the operands. 9897 N->OperandList[0].set(Op); 9898 9899 updateDivergence(N); 9900 // If this gets put into a CSE map, add it. 9901 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9902 return N; 9903 } 9904 9905 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9906 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9907 9908 // Check to see if there is no change. 9909 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9910 return N; // No operands changed, just return the input node. 9911 9912 // See if the modified node already exists. 9913 void *InsertPos = nullptr; 9914 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9915 return Existing; 9916 9917 // Nope it doesn't. Remove the node from its current place in the maps. 9918 if (InsertPos) 9919 if (!RemoveNodeFromCSEMaps(N)) 9920 InsertPos = nullptr; 9921 9922 // Now we update the operands. 9923 if (N->OperandList[0] != Op1) 9924 N->OperandList[0].set(Op1); 9925 if (N->OperandList[1] != Op2) 9926 N->OperandList[1].set(Op2); 9927 9928 updateDivergence(N); 9929 // If this gets put into a CSE map, add it. 9930 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9931 return N; 9932 } 9933 9934 SDNode *SelectionDAG:: 9935 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9936 SDValue Ops[] = { Op1, Op2, Op3 }; 9937 return UpdateNodeOperands(N, Ops); 9938 } 9939 9940 SDNode *SelectionDAG:: 9941 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9942 SDValue Op3, SDValue Op4) { 9943 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9944 return UpdateNodeOperands(N, Ops); 9945 } 9946 9947 SDNode *SelectionDAG:: 9948 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9949 SDValue Op3, SDValue Op4, SDValue Op5) { 9950 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9951 return UpdateNodeOperands(N, Ops); 9952 } 9953 9954 SDNode *SelectionDAG:: 9955 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9956 unsigned NumOps = Ops.size(); 9957 assert(N->getNumOperands() == NumOps && 9958 "Update with wrong number of operands"); 9959 9960 // If no operands changed just return the input node. 9961 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9962 return N; 9963 9964 // See if the modified node already exists. 9965 void *InsertPos = nullptr; 9966 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9967 return Existing; 9968 9969 // Nope it doesn't. Remove the node from its current place in the maps. 9970 if (InsertPos) 9971 if (!RemoveNodeFromCSEMaps(N)) 9972 InsertPos = nullptr; 9973 9974 // Now we update the operands. 9975 for (unsigned i = 0; i != NumOps; ++i) 9976 if (N->OperandList[i] != Ops[i]) 9977 N->OperandList[i].set(Ops[i]); 9978 9979 updateDivergence(N); 9980 // If this gets put into a CSE map, add it. 9981 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9982 return N; 9983 } 9984 9985 /// DropOperands - Release the operands and set this node to have 9986 /// zero operands. 9987 void SDNode::DropOperands() { 9988 // Unlike the code in MorphNodeTo that does this, we don't need to 9989 // watch for dead nodes here. 9990 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9991 SDUse &Use = *I++; 9992 Use.set(SDValue()); 9993 } 9994 } 9995 9996 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9997 ArrayRef<MachineMemOperand *> NewMemRefs) { 9998 if (NewMemRefs.empty()) { 9999 N->clearMemRefs(); 10000 return; 10001 } 10002 10003 // Check if we can avoid allocating by storing a single reference directly. 10004 if (NewMemRefs.size() == 1) { 10005 N->MemRefs = NewMemRefs[0]; 10006 N->NumMemRefs = 1; 10007 return; 10008 } 10009 10010 MachineMemOperand **MemRefsBuffer = 10011 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 10012 llvm::copy(NewMemRefs, MemRefsBuffer); 10013 N->MemRefs = MemRefsBuffer; 10014 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 10015 } 10016 10017 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 10018 /// machine opcode. 10019 /// 10020 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10021 EVT VT) { 10022 SDVTList VTs = getVTList(VT); 10023 return SelectNodeTo(N, MachineOpc, VTs, std::nullopt); 10024 } 10025 10026 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10027 EVT VT, SDValue Op1) { 10028 SDVTList VTs = getVTList(VT); 10029 SDValue Ops[] = { Op1 }; 10030 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10031 } 10032 10033 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10034 EVT VT, SDValue Op1, 10035 SDValue Op2) { 10036 SDVTList VTs = getVTList(VT); 10037 SDValue Ops[] = { Op1, Op2 }; 10038 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10039 } 10040 10041 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10042 EVT VT, SDValue Op1, 10043 SDValue Op2, SDValue Op3) { 10044 SDVTList VTs = getVTList(VT); 10045 SDValue Ops[] = { Op1, Op2, Op3 }; 10046 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10047 } 10048 10049 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10050 EVT VT, ArrayRef<SDValue> Ops) { 10051 SDVTList VTs = getVTList(VT); 10052 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10053 } 10054 10055 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10056 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 10057 SDVTList VTs = getVTList(VT1, VT2); 10058 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10059 } 10060 10061 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10062 EVT VT1, EVT VT2) { 10063 SDVTList VTs = getVTList(VT1, VT2); 10064 return SelectNodeTo(N, MachineOpc, VTs, std::nullopt); 10065 } 10066 10067 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10068 EVT VT1, EVT VT2, EVT VT3, 10069 ArrayRef<SDValue> Ops) { 10070 SDVTList VTs = getVTList(VT1, VT2, VT3); 10071 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10072 } 10073 10074 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10075 EVT VT1, EVT VT2, 10076 SDValue Op1, SDValue Op2) { 10077 SDVTList VTs = getVTList(VT1, VT2); 10078 SDValue Ops[] = { Op1, Op2 }; 10079 return SelectNodeTo(N, MachineOpc, VTs, Ops); 10080 } 10081 10082 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 10083 SDVTList VTs,ArrayRef<SDValue> Ops) { 10084 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 10085 // Reset the NodeID to -1. 10086 New->setNodeId(-1); 10087 if (New != N) { 10088 ReplaceAllUsesWith(N, New); 10089 RemoveDeadNode(N); 10090 } 10091 return New; 10092 } 10093 10094 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 10095 /// the line number information on the merged node since it is not possible to 10096 /// preserve the information that operation is associated with multiple lines. 10097 /// This will make the debugger working better at -O0, were there is a higher 10098 /// probability having other instructions associated with that line. 10099 /// 10100 /// For IROrder, we keep the smaller of the two 10101 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 10102 DebugLoc NLoc = N->getDebugLoc(); 10103 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 10104 N->setDebugLoc(DebugLoc()); 10105 } 10106 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 10107 N->setIROrder(Order); 10108 return N; 10109 } 10110 10111 /// MorphNodeTo - This *mutates* the specified node to have the specified 10112 /// return type, opcode, and operands. 10113 /// 10114 /// Note that MorphNodeTo returns the resultant node. If there is already a 10115 /// node of the specified opcode and operands, it returns that node instead of 10116 /// the current one. Note that the SDLoc need not be the same. 10117 /// 10118 /// Using MorphNodeTo is faster than creating a new node and swapping it in 10119 /// with ReplaceAllUsesWith both because it often avoids allocating a new 10120 /// node, and because it doesn't require CSE recalculation for any of 10121 /// the node's users. 10122 /// 10123 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 10124 /// As a consequence it isn't appropriate to use from within the DAG combiner or 10125 /// the legalizer which maintain worklists that would need to be updated when 10126 /// deleting things. 10127 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 10128 SDVTList VTs, ArrayRef<SDValue> Ops) { 10129 // If an identical node already exists, use it. 10130 void *IP = nullptr; 10131 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 10132 FoldingSetNodeID ID; 10133 AddNodeIDNode(ID, Opc, VTs, Ops); 10134 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 10135 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 10136 } 10137 10138 if (!RemoveNodeFromCSEMaps(N)) 10139 IP = nullptr; 10140 10141 // Start the morphing. 10142 N->NodeType = Opc; 10143 N->ValueList = VTs.VTs; 10144 N->NumValues = VTs.NumVTs; 10145 10146 // Clear the operands list, updating used nodes to remove this from their 10147 // use list. Keep track of any operands that become dead as a result. 10148 SmallPtrSet<SDNode*, 16> DeadNodeSet; 10149 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 10150 SDUse &Use = *I++; 10151 SDNode *Used = Use.getNode(); 10152 Use.set(SDValue()); 10153 if (Used->use_empty()) 10154 DeadNodeSet.insert(Used); 10155 } 10156 10157 // For MachineNode, initialize the memory references information. 10158 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 10159 MN->clearMemRefs(); 10160 10161 // Swap for an appropriately sized array from the recycler. 10162 removeOperands(N); 10163 createOperands(N, Ops); 10164 10165 // Delete any nodes that are still dead after adding the uses for the 10166 // new operands. 10167 if (!DeadNodeSet.empty()) { 10168 SmallVector<SDNode *, 16> DeadNodes; 10169 for (SDNode *N : DeadNodeSet) 10170 if (N->use_empty()) 10171 DeadNodes.push_back(N); 10172 RemoveDeadNodes(DeadNodes); 10173 } 10174 10175 if (IP) 10176 CSEMap.InsertNode(N, IP); // Memoize the new node. 10177 return N; 10178 } 10179 10180 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 10181 unsigned OrigOpc = Node->getOpcode(); 10182 unsigned NewOpc; 10183 switch (OrigOpc) { 10184 default: 10185 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 10186 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 10187 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 10188 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 10189 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 10190 #include "llvm/IR/ConstrainedOps.def" 10191 } 10192 10193 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 10194 10195 // We're taking this node out of the chain, so we need to re-link things. 10196 SDValue InputChain = Node->getOperand(0); 10197 SDValue OutputChain = SDValue(Node, 1); 10198 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 10199 10200 SmallVector<SDValue, 3> Ops; 10201 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 10202 Ops.push_back(Node->getOperand(i)); 10203 10204 SDVTList VTs = getVTList(Node->getValueType(0)); 10205 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 10206 10207 // MorphNodeTo can operate in two ways: if an existing node with the 10208 // specified operands exists, it can just return it. Otherwise, it 10209 // updates the node in place to have the requested operands. 10210 if (Res == Node) { 10211 // If we updated the node in place, reset the node ID. To the isel, 10212 // this should be just like a newly allocated machine node. 10213 Res->setNodeId(-1); 10214 } else { 10215 ReplaceAllUsesWith(Node, Res); 10216 RemoveDeadNode(Node); 10217 } 10218 10219 return Res; 10220 } 10221 10222 /// getMachineNode - These are used for target selectors to create a new node 10223 /// with specified return type(s), MachineInstr opcode, and operands. 10224 /// 10225 /// Note that getMachineNode returns the resultant node. If there is already a 10226 /// node of the specified opcode and operands, it returns that node instead of 10227 /// the current one. 10228 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10229 EVT VT) { 10230 SDVTList VTs = getVTList(VT); 10231 return getMachineNode(Opcode, dl, VTs, std::nullopt); 10232 } 10233 10234 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10235 EVT VT, SDValue Op1) { 10236 SDVTList VTs = getVTList(VT); 10237 SDValue Ops[] = { Op1 }; 10238 return getMachineNode(Opcode, dl, VTs, Ops); 10239 } 10240 10241 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10242 EVT VT, SDValue Op1, SDValue Op2) { 10243 SDVTList VTs = getVTList(VT); 10244 SDValue Ops[] = { Op1, Op2 }; 10245 return getMachineNode(Opcode, dl, VTs, Ops); 10246 } 10247 10248 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10249 EVT VT, SDValue Op1, SDValue Op2, 10250 SDValue Op3) { 10251 SDVTList VTs = getVTList(VT); 10252 SDValue Ops[] = { Op1, Op2, Op3 }; 10253 return getMachineNode(Opcode, dl, VTs, Ops); 10254 } 10255 10256 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10257 EVT VT, ArrayRef<SDValue> Ops) { 10258 SDVTList VTs = getVTList(VT); 10259 return getMachineNode(Opcode, dl, VTs, Ops); 10260 } 10261 10262 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10263 EVT VT1, EVT VT2, SDValue Op1, 10264 SDValue Op2) { 10265 SDVTList VTs = getVTList(VT1, VT2); 10266 SDValue Ops[] = { Op1, Op2 }; 10267 return getMachineNode(Opcode, dl, VTs, Ops); 10268 } 10269 10270 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10271 EVT VT1, EVT VT2, SDValue Op1, 10272 SDValue Op2, SDValue Op3) { 10273 SDVTList VTs = getVTList(VT1, VT2); 10274 SDValue Ops[] = { Op1, Op2, Op3 }; 10275 return getMachineNode(Opcode, dl, VTs, Ops); 10276 } 10277 10278 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10279 EVT VT1, EVT VT2, 10280 ArrayRef<SDValue> Ops) { 10281 SDVTList VTs = getVTList(VT1, VT2); 10282 return getMachineNode(Opcode, dl, VTs, Ops); 10283 } 10284 10285 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10286 EVT VT1, EVT VT2, EVT VT3, 10287 SDValue Op1, SDValue Op2) { 10288 SDVTList VTs = getVTList(VT1, VT2, VT3); 10289 SDValue Ops[] = { Op1, Op2 }; 10290 return getMachineNode(Opcode, dl, VTs, Ops); 10291 } 10292 10293 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10294 EVT VT1, EVT VT2, EVT VT3, 10295 SDValue Op1, SDValue Op2, 10296 SDValue Op3) { 10297 SDVTList VTs = getVTList(VT1, VT2, VT3); 10298 SDValue Ops[] = { Op1, Op2, Op3 }; 10299 return getMachineNode(Opcode, dl, VTs, Ops); 10300 } 10301 10302 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10303 EVT VT1, EVT VT2, EVT VT3, 10304 ArrayRef<SDValue> Ops) { 10305 SDVTList VTs = getVTList(VT1, VT2, VT3); 10306 return getMachineNode(Opcode, dl, VTs, Ops); 10307 } 10308 10309 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 10310 ArrayRef<EVT> ResultTys, 10311 ArrayRef<SDValue> Ops) { 10312 SDVTList VTs = getVTList(ResultTys); 10313 return getMachineNode(Opcode, dl, VTs, Ops); 10314 } 10315 10316 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 10317 SDVTList VTs, 10318 ArrayRef<SDValue> Ops) { 10319 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 10320 MachineSDNode *N; 10321 void *IP = nullptr; 10322 10323 if (DoCSE) { 10324 FoldingSetNodeID ID; 10325 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 10326 IP = nullptr; 10327 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 10328 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 10329 } 10330 } 10331 10332 // Allocate a new MachineSDNode. 10333 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 10334 createOperands(N, Ops); 10335 10336 if (DoCSE) 10337 CSEMap.InsertNode(N, IP); 10338 10339 InsertNode(N); 10340 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 10341 return N; 10342 } 10343 10344 /// getTargetExtractSubreg - A convenience function for creating 10345 /// TargetOpcode::EXTRACT_SUBREG nodes. 10346 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 10347 SDValue Operand) { 10348 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 10349 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 10350 VT, Operand, SRIdxVal); 10351 return SDValue(Subreg, 0); 10352 } 10353 10354 /// getTargetInsertSubreg - A convenience function for creating 10355 /// TargetOpcode::INSERT_SUBREG nodes. 10356 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 10357 SDValue Operand, SDValue Subreg) { 10358 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 10359 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 10360 VT, Operand, Subreg, SRIdxVal); 10361 return SDValue(Result, 0); 10362 } 10363 10364 /// getNodeIfExists - Get the specified node if it's already available, or 10365 /// else return NULL. 10366 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 10367 ArrayRef<SDValue> Ops) { 10368 SDNodeFlags Flags; 10369 if (Inserter) 10370 Flags = Inserter->getFlags(); 10371 return getNodeIfExists(Opcode, VTList, Ops, Flags); 10372 } 10373 10374 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 10375 ArrayRef<SDValue> Ops, 10376 const SDNodeFlags Flags) { 10377 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 10378 FoldingSetNodeID ID; 10379 AddNodeIDNode(ID, Opcode, VTList, Ops); 10380 void *IP = nullptr; 10381 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 10382 E->intersectFlagsWith(Flags); 10383 return E; 10384 } 10385 } 10386 return nullptr; 10387 } 10388 10389 /// doesNodeExist - Check if a node exists without modifying its flags. 10390 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 10391 ArrayRef<SDValue> Ops) { 10392 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 10393 FoldingSetNodeID ID; 10394 AddNodeIDNode(ID, Opcode, VTList, Ops); 10395 void *IP = nullptr; 10396 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 10397 return true; 10398 } 10399 return false; 10400 } 10401 10402 /// getDbgValue - Creates a SDDbgValue node. 10403 /// 10404 /// SDNode 10405 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 10406 SDNode *N, unsigned R, bool IsIndirect, 10407 const DebugLoc &DL, unsigned O) { 10408 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10409 "Expected inlined-at fields to agree"); 10410 return new (DbgInfo->getAlloc()) 10411 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 10412 {}, IsIndirect, DL, O, 10413 /*IsVariadic=*/false); 10414 } 10415 10416 /// Constant 10417 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 10418 DIExpression *Expr, 10419 const Value *C, 10420 const DebugLoc &DL, unsigned O) { 10421 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10422 "Expected inlined-at fields to agree"); 10423 return new (DbgInfo->getAlloc()) 10424 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 10425 /*IsIndirect=*/false, DL, O, 10426 /*IsVariadic=*/false); 10427 } 10428 10429 /// FrameIndex 10430 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 10431 DIExpression *Expr, unsigned FI, 10432 bool IsIndirect, 10433 const DebugLoc &DL, 10434 unsigned O) { 10435 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10436 "Expected inlined-at fields to agree"); 10437 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 10438 } 10439 10440 /// FrameIndex with dependencies 10441 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 10442 DIExpression *Expr, unsigned FI, 10443 ArrayRef<SDNode *> Dependencies, 10444 bool IsIndirect, 10445 const DebugLoc &DL, 10446 unsigned O) { 10447 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10448 "Expected inlined-at fields to agree"); 10449 return new (DbgInfo->getAlloc()) 10450 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 10451 Dependencies, IsIndirect, DL, O, 10452 /*IsVariadic=*/false); 10453 } 10454 10455 /// VReg 10456 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 10457 unsigned VReg, bool IsIndirect, 10458 const DebugLoc &DL, unsigned O) { 10459 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10460 "Expected inlined-at fields to agree"); 10461 return new (DbgInfo->getAlloc()) 10462 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 10463 {}, IsIndirect, DL, O, 10464 /*IsVariadic=*/false); 10465 } 10466 10467 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 10468 ArrayRef<SDDbgOperand> Locs, 10469 ArrayRef<SDNode *> Dependencies, 10470 bool IsIndirect, const DebugLoc &DL, 10471 unsigned O, bool IsVariadic) { 10472 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 10473 "Expected inlined-at fields to agree"); 10474 return new (DbgInfo->getAlloc()) 10475 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 10476 DL, O, IsVariadic); 10477 } 10478 10479 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 10480 unsigned OffsetInBits, unsigned SizeInBits, 10481 bool InvalidateDbg) { 10482 SDNode *FromNode = From.getNode(); 10483 SDNode *ToNode = To.getNode(); 10484 assert(FromNode && ToNode && "Can't modify dbg values"); 10485 10486 // PR35338 10487 // TODO: assert(From != To && "Redundant dbg value transfer"); 10488 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 10489 if (From == To || FromNode == ToNode) 10490 return; 10491 10492 if (!FromNode->getHasDebugValue()) 10493 return; 10494 10495 SDDbgOperand FromLocOp = 10496 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 10497 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 10498 10499 SmallVector<SDDbgValue *, 2> ClonedDVs; 10500 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 10501 if (Dbg->isInvalidated()) 10502 continue; 10503 10504 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 10505 10506 // Create a new location ops vector that is equal to the old vector, but 10507 // with each instance of FromLocOp replaced with ToLocOp. 10508 bool Changed = false; 10509 auto NewLocOps = Dbg->copyLocationOps(); 10510 std::replace_if( 10511 NewLocOps.begin(), NewLocOps.end(), 10512 [&Changed, FromLocOp](const SDDbgOperand &Op) { 10513 bool Match = Op == FromLocOp; 10514 Changed |= Match; 10515 return Match; 10516 }, 10517 ToLocOp); 10518 // Ignore this SDDbgValue if we didn't find a matching location. 10519 if (!Changed) 10520 continue; 10521 10522 DIVariable *Var = Dbg->getVariable(); 10523 auto *Expr = Dbg->getExpression(); 10524 // If a fragment is requested, update the expression. 10525 if (SizeInBits) { 10526 // When splitting a larger (e.g., sign-extended) value whose 10527 // lower bits are described with an SDDbgValue, do not attempt 10528 // to transfer the SDDbgValue to the upper bits. 10529 if (auto FI = Expr->getFragmentInfo()) 10530 if (OffsetInBits + SizeInBits > FI->SizeInBits) 10531 continue; 10532 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 10533 SizeInBits); 10534 if (!Fragment) 10535 continue; 10536 Expr = *Fragment; 10537 } 10538 10539 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 10540 // Clone the SDDbgValue and move it to To. 10541 SDDbgValue *Clone = getDbgValueList( 10542 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 10543 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 10544 Dbg->isVariadic()); 10545 ClonedDVs.push_back(Clone); 10546 10547 if (InvalidateDbg) { 10548 // Invalidate value and indicate the SDDbgValue should not be emitted. 10549 Dbg->setIsInvalidated(); 10550 Dbg->setIsEmitted(); 10551 } 10552 } 10553 10554 for (SDDbgValue *Dbg : ClonedDVs) { 10555 assert(is_contained(Dbg->getSDNodes(), ToNode) && 10556 "Transferred DbgValues should depend on the new SDNode"); 10557 AddDbgValue(Dbg, false); 10558 } 10559 } 10560 10561 void SelectionDAG::salvageDebugInfo(SDNode &N) { 10562 if (!N.getHasDebugValue()) 10563 return; 10564 10565 SmallVector<SDDbgValue *, 2> ClonedDVs; 10566 for (auto *DV : GetDbgValues(&N)) { 10567 if (DV->isInvalidated()) 10568 continue; 10569 switch (N.getOpcode()) { 10570 default: 10571 break; 10572 case ISD::ADD: 10573 SDValue N0 = N.getOperand(0); 10574 SDValue N1 = N.getOperand(1); 10575 if (!isa<ConstantSDNode>(N0) && isa<ConstantSDNode>(N1)) { 10576 uint64_t Offset = N.getConstantOperandVal(1); 10577 10578 // Rewrite an ADD constant node into a DIExpression. Since we are 10579 // performing arithmetic to compute the variable's *value* in the 10580 // DIExpression, we need to mark the expression with a 10581 // DW_OP_stack_value. 10582 auto *DIExpr = DV->getExpression(); 10583 auto NewLocOps = DV->copyLocationOps(); 10584 bool Changed = false; 10585 for (size_t i = 0; i < NewLocOps.size(); ++i) { 10586 // We're not given a ResNo to compare against because the whole 10587 // node is going away. We know that any ISD::ADD only has one 10588 // result, so we can assume any node match is using the result. 10589 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 10590 NewLocOps[i].getSDNode() != &N) 10591 continue; 10592 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 10593 SmallVector<uint64_t, 3> ExprOps; 10594 DIExpression::appendOffset(ExprOps, Offset); 10595 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 10596 Changed = true; 10597 } 10598 (void)Changed; 10599 assert(Changed && "Salvage target doesn't use N"); 10600 10601 auto AdditionalDependencies = DV->getAdditionalDependencies(); 10602 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 10603 NewLocOps, AdditionalDependencies, 10604 DV->isIndirect(), DV->getDebugLoc(), 10605 DV->getOrder(), DV->isVariadic()); 10606 ClonedDVs.push_back(Clone); 10607 DV->setIsInvalidated(); 10608 DV->setIsEmitted(); 10609 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 10610 N0.getNode()->dumprFull(this); 10611 dbgs() << " into " << *DIExpr << '\n'); 10612 } 10613 } 10614 } 10615 10616 for (SDDbgValue *Dbg : ClonedDVs) { 10617 assert(!Dbg->getSDNodes().empty() && 10618 "Salvaged DbgValue should depend on a new SDNode"); 10619 AddDbgValue(Dbg, false); 10620 } 10621 } 10622 10623 /// Creates a SDDbgLabel node. 10624 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 10625 const DebugLoc &DL, unsigned O) { 10626 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 10627 "Expected inlined-at fields to agree"); 10628 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 10629 } 10630 10631 namespace { 10632 10633 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 10634 /// pointed to by a use iterator is deleted, increment the use iterator 10635 /// so that it doesn't dangle. 10636 /// 10637 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 10638 SDNode::use_iterator &UI; 10639 SDNode::use_iterator &UE; 10640 10641 void NodeDeleted(SDNode *N, SDNode *E) override { 10642 // Increment the iterator as needed. 10643 while (UI != UE && N == *UI) 10644 ++UI; 10645 } 10646 10647 public: 10648 RAUWUpdateListener(SelectionDAG &d, 10649 SDNode::use_iterator &ui, 10650 SDNode::use_iterator &ue) 10651 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 10652 }; 10653 10654 } // end anonymous namespace 10655 10656 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10657 /// This can cause recursive merging of nodes in the DAG. 10658 /// 10659 /// This version assumes From has a single result value. 10660 /// 10661 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 10662 SDNode *From = FromN.getNode(); 10663 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 10664 "Cannot replace with this method!"); 10665 assert(From != To.getNode() && "Cannot replace uses of with self"); 10666 10667 // Preserve Debug Values 10668 transferDbgValues(FromN, To); 10669 // Preserve extra info. 10670 copyExtraInfo(From, To.getNode()); 10671 10672 // Iterate over all the existing uses of From. New uses will be added 10673 // to the beginning of the use list, which we avoid visiting. 10674 // This specifically avoids visiting uses of From that arise while the 10675 // replacement is happening, because any such uses would be the result 10676 // of CSE: If an existing node looks like From after one of its operands 10677 // is replaced by To, we don't want to replace of all its users with To 10678 // too. See PR3018 for more info. 10679 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10680 RAUWUpdateListener Listener(*this, UI, UE); 10681 while (UI != UE) { 10682 SDNode *User = *UI; 10683 10684 // This node is about to morph, remove its old self from the CSE maps. 10685 RemoveNodeFromCSEMaps(User); 10686 10687 // A user can appear in a use list multiple times, and when this 10688 // happens the uses are usually next to each other in the list. 10689 // To help reduce the number of CSE recomputations, process all 10690 // the uses of this user that we can find this way. 10691 do { 10692 SDUse &Use = UI.getUse(); 10693 ++UI; 10694 Use.set(To); 10695 if (To->isDivergent() != From->isDivergent()) 10696 updateDivergence(User); 10697 } while (UI != UE && *UI == User); 10698 // Now that we have modified User, add it back to the CSE maps. If it 10699 // already exists there, recursively merge the results together. 10700 AddModifiedNodeToCSEMaps(User); 10701 } 10702 10703 // If we just RAUW'd the root, take note. 10704 if (FromN == getRoot()) 10705 setRoot(To); 10706 } 10707 10708 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10709 /// This can cause recursive merging of nodes in the DAG. 10710 /// 10711 /// This version assumes that for each value of From, there is a 10712 /// corresponding value in To in the same position with the same type. 10713 /// 10714 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 10715 #ifndef NDEBUG 10716 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10717 assert((!From->hasAnyUseOfValue(i) || 10718 From->getValueType(i) == To->getValueType(i)) && 10719 "Cannot use this version of ReplaceAllUsesWith!"); 10720 #endif 10721 10722 // Handle the trivial case. 10723 if (From == To) 10724 return; 10725 10726 // Preserve Debug Info. Only do this if there's a use. 10727 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10728 if (From->hasAnyUseOfValue(i)) { 10729 assert((i < To->getNumValues()) && "Invalid To location"); 10730 transferDbgValues(SDValue(From, i), SDValue(To, i)); 10731 } 10732 // Preserve extra info. 10733 copyExtraInfo(From, To); 10734 10735 // Iterate over just the existing users of From. See the comments in 10736 // the ReplaceAllUsesWith above. 10737 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10738 RAUWUpdateListener Listener(*this, UI, UE); 10739 while (UI != UE) { 10740 SDNode *User = *UI; 10741 10742 // This node is about to morph, remove its old self from the CSE maps. 10743 RemoveNodeFromCSEMaps(User); 10744 10745 // A user can appear in a use list multiple times, and when this 10746 // happens the uses are usually next to each other in the list. 10747 // To help reduce the number of CSE recomputations, process all 10748 // the uses of this user that we can find this way. 10749 do { 10750 SDUse &Use = UI.getUse(); 10751 ++UI; 10752 Use.setNode(To); 10753 if (To->isDivergent() != From->isDivergent()) 10754 updateDivergence(User); 10755 } while (UI != UE && *UI == User); 10756 10757 // Now that we have modified User, add it back to the CSE maps. If it 10758 // already exists there, recursively merge the results together. 10759 AddModifiedNodeToCSEMaps(User); 10760 } 10761 10762 // If we just RAUW'd the root, take note. 10763 if (From == getRoot().getNode()) 10764 setRoot(SDValue(To, getRoot().getResNo())); 10765 } 10766 10767 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10768 /// This can cause recursive merging of nodes in the DAG. 10769 /// 10770 /// This version can replace From with any result values. To must match the 10771 /// number and types of values returned by From. 10772 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 10773 if (From->getNumValues() == 1) // Handle the simple case efficiently. 10774 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 10775 10776 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) { 10777 // Preserve Debug Info. 10778 transferDbgValues(SDValue(From, i), To[i]); 10779 // Preserve extra info. 10780 copyExtraInfo(From, To[i].getNode()); 10781 } 10782 10783 // Iterate over just the existing users of From. See the comments in 10784 // the ReplaceAllUsesWith above. 10785 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10786 RAUWUpdateListener Listener(*this, UI, UE); 10787 while (UI != UE) { 10788 SDNode *User = *UI; 10789 10790 // This node is about to morph, remove its old self from the CSE maps. 10791 RemoveNodeFromCSEMaps(User); 10792 10793 // A user can appear in a use list multiple times, and when this happens the 10794 // uses are usually next to each other in the list. To help reduce the 10795 // number of CSE and divergence recomputations, process all the uses of this 10796 // user that we can find this way. 10797 bool To_IsDivergent = false; 10798 do { 10799 SDUse &Use = UI.getUse(); 10800 const SDValue &ToOp = To[Use.getResNo()]; 10801 ++UI; 10802 Use.set(ToOp); 10803 To_IsDivergent |= ToOp->isDivergent(); 10804 } while (UI != UE && *UI == User); 10805 10806 if (To_IsDivergent != From->isDivergent()) 10807 updateDivergence(User); 10808 10809 // Now that we have modified User, add it back to the CSE maps. If it 10810 // already exists there, recursively merge the results together. 10811 AddModifiedNodeToCSEMaps(User); 10812 } 10813 10814 // If we just RAUW'd the root, take note. 10815 if (From == getRoot().getNode()) 10816 setRoot(SDValue(To[getRoot().getResNo()])); 10817 } 10818 10819 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 10820 /// uses of other values produced by From.getNode() alone. The Deleted 10821 /// vector is handled the same way as for ReplaceAllUsesWith. 10822 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 10823 // Handle the really simple, really trivial case efficiently. 10824 if (From == To) return; 10825 10826 // Handle the simple, trivial, case efficiently. 10827 if (From.getNode()->getNumValues() == 1) { 10828 ReplaceAllUsesWith(From, To); 10829 return; 10830 } 10831 10832 // Preserve Debug Info. 10833 transferDbgValues(From, To); 10834 copyExtraInfo(From.getNode(), To.getNode()); 10835 10836 // Iterate over just the existing users of From. See the comments in 10837 // the ReplaceAllUsesWith above. 10838 SDNode::use_iterator UI = From.getNode()->use_begin(), 10839 UE = From.getNode()->use_end(); 10840 RAUWUpdateListener Listener(*this, UI, UE); 10841 while (UI != UE) { 10842 SDNode *User = *UI; 10843 bool UserRemovedFromCSEMaps = false; 10844 10845 // A user can appear in a use list multiple times, and when this 10846 // happens the uses are usually next to each other in the list. 10847 // To help reduce the number of CSE recomputations, process all 10848 // the uses of this user that we can find this way. 10849 do { 10850 SDUse &Use = UI.getUse(); 10851 10852 // Skip uses of different values from the same node. 10853 if (Use.getResNo() != From.getResNo()) { 10854 ++UI; 10855 continue; 10856 } 10857 10858 // If this node hasn't been modified yet, it's still in the CSE maps, 10859 // so remove its old self from the CSE maps. 10860 if (!UserRemovedFromCSEMaps) { 10861 RemoveNodeFromCSEMaps(User); 10862 UserRemovedFromCSEMaps = true; 10863 } 10864 10865 ++UI; 10866 Use.set(To); 10867 if (To->isDivergent() != From->isDivergent()) 10868 updateDivergence(User); 10869 } while (UI != UE && *UI == User); 10870 // We are iterating over all uses of the From node, so if a use 10871 // doesn't use the specific value, no changes are made. 10872 if (!UserRemovedFromCSEMaps) 10873 continue; 10874 10875 // Now that we have modified User, add it back to the CSE maps. If it 10876 // already exists there, recursively merge the results together. 10877 AddModifiedNodeToCSEMaps(User); 10878 } 10879 10880 // If we just RAUW'd the root, take note. 10881 if (From == getRoot()) 10882 setRoot(To); 10883 } 10884 10885 namespace { 10886 10887 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10888 /// to record information about a use. 10889 struct UseMemo { 10890 SDNode *User; 10891 unsigned Index; 10892 SDUse *Use; 10893 }; 10894 10895 /// operator< - Sort Memos by User. 10896 bool operator<(const UseMemo &L, const UseMemo &R) { 10897 return (intptr_t)L.User < (intptr_t)R.User; 10898 } 10899 10900 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10901 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10902 /// the node already has been taken care of recursively. 10903 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10904 SmallVector<UseMemo, 4> &Uses; 10905 10906 void NodeDeleted(SDNode *N, SDNode *E) override { 10907 for (UseMemo &Memo : Uses) 10908 if (Memo.User == N) 10909 Memo.User = nullptr; 10910 } 10911 10912 public: 10913 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10914 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10915 }; 10916 10917 } // end anonymous namespace 10918 10919 bool SelectionDAG::calculateDivergence(SDNode *N) { 10920 if (TLI->isSDNodeAlwaysUniform(N)) { 10921 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) && 10922 "Conflicting divergence information!"); 10923 return false; 10924 } 10925 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA)) 10926 return true; 10927 for (const auto &Op : N->ops()) { 10928 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10929 return true; 10930 } 10931 return false; 10932 } 10933 10934 void SelectionDAG::updateDivergence(SDNode *N) { 10935 SmallVector<SDNode *, 16> Worklist(1, N); 10936 do { 10937 N = Worklist.pop_back_val(); 10938 bool IsDivergent = calculateDivergence(N); 10939 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10940 N->SDNodeBits.IsDivergent = IsDivergent; 10941 llvm::append_range(Worklist, N->uses()); 10942 } 10943 } while (!Worklist.empty()); 10944 } 10945 10946 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10947 DenseMap<SDNode *, unsigned> Degree; 10948 Order.reserve(AllNodes.size()); 10949 for (auto &N : allnodes()) { 10950 unsigned NOps = N.getNumOperands(); 10951 Degree[&N] = NOps; 10952 if (0 == NOps) 10953 Order.push_back(&N); 10954 } 10955 for (size_t I = 0; I != Order.size(); ++I) { 10956 SDNode *N = Order[I]; 10957 for (auto *U : N->uses()) { 10958 unsigned &UnsortedOps = Degree[U]; 10959 if (0 == --UnsortedOps) 10960 Order.push_back(U); 10961 } 10962 } 10963 } 10964 10965 #ifndef NDEBUG 10966 void SelectionDAG::VerifyDAGDivergence() { 10967 std::vector<SDNode *> TopoOrder; 10968 CreateTopologicalOrder(TopoOrder); 10969 for (auto *N : TopoOrder) { 10970 assert(calculateDivergence(N) == N->isDivergent() && 10971 "Divergence bit inconsistency detected"); 10972 } 10973 } 10974 #endif 10975 10976 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10977 /// uses of other values produced by From.getNode() alone. The same value 10978 /// may appear in both the From and To list. The Deleted vector is 10979 /// handled the same way as for ReplaceAllUsesWith. 10980 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10981 const SDValue *To, 10982 unsigned Num){ 10983 // Handle the simple, trivial case efficiently. 10984 if (Num == 1) 10985 return ReplaceAllUsesOfValueWith(*From, *To); 10986 10987 transferDbgValues(*From, *To); 10988 copyExtraInfo(From->getNode(), To->getNode()); 10989 10990 // Read up all the uses and make records of them. This helps 10991 // processing new uses that are introduced during the 10992 // replacement process. 10993 SmallVector<UseMemo, 4> Uses; 10994 for (unsigned i = 0; i != Num; ++i) { 10995 unsigned FromResNo = From[i].getResNo(); 10996 SDNode *FromNode = From[i].getNode(); 10997 for (SDNode::use_iterator UI = FromNode->use_begin(), 10998 E = FromNode->use_end(); UI != E; ++UI) { 10999 SDUse &Use = UI.getUse(); 11000 if (Use.getResNo() == FromResNo) { 11001 UseMemo Memo = { *UI, i, &Use }; 11002 Uses.push_back(Memo); 11003 } 11004 } 11005 } 11006 11007 // Sort the uses, so that all the uses from a given User are together. 11008 llvm::sort(Uses); 11009 RAUOVWUpdateListener Listener(*this, Uses); 11010 11011 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 11012 UseIndex != UseIndexEnd; ) { 11013 // We know that this user uses some value of From. If it is the right 11014 // value, update it. 11015 SDNode *User = Uses[UseIndex].User; 11016 // If the node has been deleted by recursive CSE updates when updating 11017 // another node, then just skip this entry. 11018 if (User == nullptr) { 11019 ++UseIndex; 11020 continue; 11021 } 11022 11023 // This node is about to morph, remove its old self from the CSE maps. 11024 RemoveNodeFromCSEMaps(User); 11025 11026 // The Uses array is sorted, so all the uses for a given User 11027 // are next to each other in the list. 11028 // To help reduce the number of CSE recomputations, process all 11029 // the uses of this user that we can find this way. 11030 do { 11031 unsigned i = Uses[UseIndex].Index; 11032 SDUse &Use = *Uses[UseIndex].Use; 11033 ++UseIndex; 11034 11035 Use.set(To[i]); 11036 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 11037 11038 // Now that we have modified User, add it back to the CSE maps. If it 11039 // already exists there, recursively merge the results together. 11040 AddModifiedNodeToCSEMaps(User); 11041 } 11042 } 11043 11044 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 11045 /// based on their topological order. It returns the maximum id and a vector 11046 /// of the SDNodes* in assigned order by reference. 11047 unsigned SelectionDAG::AssignTopologicalOrder() { 11048 unsigned DAGSize = 0; 11049 11050 // SortedPos tracks the progress of the algorithm. Nodes before it are 11051 // sorted, nodes after it are unsorted. When the algorithm completes 11052 // it is at the end of the list. 11053 allnodes_iterator SortedPos = allnodes_begin(); 11054 11055 // Visit all the nodes. Move nodes with no operands to the front of 11056 // the list immediately. Annotate nodes that do have operands with their 11057 // operand count. Before we do this, the Node Id fields of the nodes 11058 // may contain arbitrary values. After, the Node Id fields for nodes 11059 // before SortedPos will contain the topological sort index, and the 11060 // Node Id fields for nodes At SortedPos and after will contain the 11061 // count of outstanding operands. 11062 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 11063 checkForCycles(&N, this); 11064 unsigned Degree = N.getNumOperands(); 11065 if (Degree == 0) { 11066 // A node with no uses, add it to the result array immediately. 11067 N.setNodeId(DAGSize++); 11068 allnodes_iterator Q(&N); 11069 if (Q != SortedPos) 11070 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 11071 assert(SortedPos != AllNodes.end() && "Overran node list"); 11072 ++SortedPos; 11073 } else { 11074 // Temporarily use the Node Id as scratch space for the degree count. 11075 N.setNodeId(Degree); 11076 } 11077 } 11078 11079 // Visit all the nodes. As we iterate, move nodes into sorted order, 11080 // such that by the time the end is reached all nodes will be sorted. 11081 for (SDNode &Node : allnodes()) { 11082 SDNode *N = &Node; 11083 checkForCycles(N, this); 11084 // N is in sorted position, so all its uses have one less operand 11085 // that needs to be sorted. 11086 for (SDNode *P : N->uses()) { 11087 unsigned Degree = P->getNodeId(); 11088 assert(Degree != 0 && "Invalid node degree"); 11089 --Degree; 11090 if (Degree == 0) { 11091 // All of P's operands are sorted, so P may sorted now. 11092 P->setNodeId(DAGSize++); 11093 if (P->getIterator() != SortedPos) 11094 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 11095 assert(SortedPos != AllNodes.end() && "Overran node list"); 11096 ++SortedPos; 11097 } else { 11098 // Update P's outstanding operand count. 11099 P->setNodeId(Degree); 11100 } 11101 } 11102 if (Node.getIterator() == SortedPos) { 11103 #ifndef NDEBUG 11104 allnodes_iterator I(N); 11105 SDNode *S = &*++I; 11106 dbgs() << "Overran sorted position:\n"; 11107 S->dumprFull(this); dbgs() << "\n"; 11108 dbgs() << "Checking if this is due to cycles\n"; 11109 checkForCycles(this, true); 11110 #endif 11111 llvm_unreachable(nullptr); 11112 } 11113 } 11114 11115 assert(SortedPos == AllNodes.end() && 11116 "Topological sort incomplete!"); 11117 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 11118 "First node in topological sort is not the entry token!"); 11119 assert(AllNodes.front().getNodeId() == 0 && 11120 "First node in topological sort has non-zero id!"); 11121 assert(AllNodes.front().getNumOperands() == 0 && 11122 "First node in topological sort has operands!"); 11123 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 11124 "Last node in topologic sort has unexpected id!"); 11125 assert(AllNodes.back().use_empty() && 11126 "Last node in topologic sort has users!"); 11127 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 11128 return DAGSize; 11129 } 11130 11131 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 11132 /// value is produced by SD. 11133 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 11134 for (SDNode *SD : DB->getSDNodes()) { 11135 if (!SD) 11136 continue; 11137 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 11138 SD->setHasDebugValue(true); 11139 } 11140 DbgInfo->add(DB, isParameter); 11141 } 11142 11143 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 11144 11145 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 11146 SDValue NewMemOpChain) { 11147 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 11148 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 11149 // The new memory operation must have the same position as the old load in 11150 // terms of memory dependency. Create a TokenFactor for the old load and new 11151 // memory operation and update uses of the old load's output chain to use that 11152 // TokenFactor. 11153 if (OldChain == NewMemOpChain || OldChain.use_empty()) 11154 return NewMemOpChain; 11155 11156 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 11157 OldChain, NewMemOpChain); 11158 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 11159 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 11160 return TokenFactor; 11161 } 11162 11163 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 11164 SDValue NewMemOp) { 11165 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 11166 SDValue OldChain = SDValue(OldLoad, 1); 11167 SDValue NewMemOpChain = NewMemOp.getValue(1); 11168 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 11169 } 11170 11171 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 11172 Function **OutFunction) { 11173 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 11174 11175 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 11176 auto *Module = MF->getFunction().getParent(); 11177 auto *Function = Module->getFunction(Symbol); 11178 11179 if (OutFunction != nullptr) 11180 *OutFunction = Function; 11181 11182 if (Function != nullptr) { 11183 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 11184 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 11185 } 11186 11187 std::string ErrorStr; 11188 raw_string_ostream ErrorFormatter(ErrorStr); 11189 ErrorFormatter << "Undefined external symbol "; 11190 ErrorFormatter << '"' << Symbol << '"'; 11191 report_fatal_error(Twine(ErrorFormatter.str())); 11192 } 11193 11194 //===----------------------------------------------------------------------===// 11195 // SDNode Class 11196 //===----------------------------------------------------------------------===// 11197 11198 bool llvm::isNullConstant(SDValue V) { 11199 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11200 return Const != nullptr && Const->isZero(); 11201 } 11202 11203 bool llvm::isNullFPConstant(SDValue V) { 11204 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 11205 return Const != nullptr && Const->isZero() && !Const->isNegative(); 11206 } 11207 11208 bool llvm::isAllOnesConstant(SDValue V) { 11209 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11210 return Const != nullptr && Const->isAllOnes(); 11211 } 11212 11213 bool llvm::isOneConstant(SDValue V) { 11214 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11215 return Const != nullptr && Const->isOne(); 11216 } 11217 11218 bool llvm::isMinSignedConstant(SDValue V) { 11219 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 11220 return Const != nullptr && Const->isMinSignedValue(); 11221 } 11222 11223 bool llvm::isNeutralConstant(unsigned Opcode, SDNodeFlags Flags, SDValue V, 11224 unsigned OperandNo) { 11225 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity(). 11226 // TODO: Target-specific opcodes could be added. 11227 if (auto *Const = isConstOrConstSplat(V)) { 11228 switch (Opcode) { 11229 case ISD::ADD: 11230 case ISD::OR: 11231 case ISD::XOR: 11232 case ISD::UMAX: 11233 return Const->isZero(); 11234 case ISD::MUL: 11235 return Const->isOne(); 11236 case ISD::AND: 11237 case ISD::UMIN: 11238 return Const->isAllOnes(); 11239 case ISD::SMAX: 11240 return Const->isMinSignedValue(); 11241 case ISD::SMIN: 11242 return Const->isMaxSignedValue(); 11243 case ISD::SUB: 11244 case ISD::SHL: 11245 case ISD::SRA: 11246 case ISD::SRL: 11247 return OperandNo == 1 && Const->isZero(); 11248 case ISD::UDIV: 11249 case ISD::SDIV: 11250 return OperandNo == 1 && Const->isOne(); 11251 } 11252 } else if (auto *ConstFP = isConstOrConstSplatFP(V)) { 11253 switch (Opcode) { 11254 case ISD::FADD: 11255 return ConstFP->isZero() && 11256 (Flags.hasNoSignedZeros() || ConstFP->isNegative()); 11257 case ISD::FSUB: 11258 return OperandNo == 1 && ConstFP->isZero() && 11259 (Flags.hasNoSignedZeros() || !ConstFP->isNegative()); 11260 case ISD::FMUL: 11261 return ConstFP->isExactlyValue(1.0); 11262 case ISD::FDIV: 11263 return OperandNo == 1 && ConstFP->isExactlyValue(1.0); 11264 case ISD::FMINNUM: 11265 case ISD::FMAXNUM: { 11266 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11267 EVT VT = V.getValueType(); 11268 const fltSemantics &Semantics = SelectionDAG::EVTToAPFloatSemantics(VT); 11269 APFloat NeutralAF = !Flags.hasNoNaNs() 11270 ? APFloat::getQNaN(Semantics) 11271 : !Flags.hasNoInfs() 11272 ? APFloat::getInf(Semantics) 11273 : APFloat::getLargest(Semantics); 11274 if (Opcode == ISD::FMAXNUM) 11275 NeutralAF.changeSign(); 11276 11277 return ConstFP->isExactlyValue(NeutralAF); 11278 } 11279 } 11280 } 11281 return false; 11282 } 11283 11284 SDValue llvm::peekThroughBitcasts(SDValue V) { 11285 while (V.getOpcode() == ISD::BITCAST) 11286 V = V.getOperand(0); 11287 return V; 11288 } 11289 11290 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 11291 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 11292 V = V.getOperand(0); 11293 return V; 11294 } 11295 11296 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 11297 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 11298 V = V.getOperand(0); 11299 return V; 11300 } 11301 11302 SDValue llvm::peekThroughTruncates(SDValue V) { 11303 while (V.getOpcode() == ISD::TRUNCATE) 11304 V = V.getOperand(0); 11305 return V; 11306 } 11307 11308 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 11309 if (V.getOpcode() != ISD::XOR) 11310 return false; 11311 V = peekThroughBitcasts(V.getOperand(1)); 11312 unsigned NumBits = V.getScalarValueSizeInBits(); 11313 ConstantSDNode *C = 11314 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 11315 return C && (C->getAPIntValue().countr_one() >= NumBits); 11316 } 11317 11318 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 11319 bool AllowTruncation) { 11320 EVT VT = N.getValueType(); 11321 APInt DemandedElts = VT.isFixedLengthVector() 11322 ? APInt::getAllOnes(VT.getVectorMinNumElements()) 11323 : APInt(1, 1); 11324 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation); 11325 } 11326 11327 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 11328 bool AllowUndefs, 11329 bool AllowTruncation) { 11330 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 11331 return CN; 11332 11333 // SplatVectors can truncate their operands. Ignore that case here unless 11334 // AllowTruncation is set. 11335 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 11336 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 11337 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 11338 EVT CVT = CN->getValueType(0); 11339 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 11340 if (AllowTruncation || CVT == VecEltVT) 11341 return CN; 11342 } 11343 } 11344 11345 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 11346 BitVector UndefElements; 11347 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 11348 11349 // BuildVectors can truncate their operands. Ignore that case here unless 11350 // AllowTruncation is set. 11351 // TODO: Look into whether we should allow UndefElements in non-DemandedElts 11352 if (CN && (UndefElements.none() || AllowUndefs)) { 11353 EVT CVT = CN->getValueType(0); 11354 EVT NSVT = N.getValueType().getScalarType(); 11355 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 11356 if (AllowTruncation || (CVT == NSVT)) 11357 return CN; 11358 } 11359 } 11360 11361 return nullptr; 11362 } 11363 11364 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 11365 EVT VT = N.getValueType(); 11366 APInt DemandedElts = VT.isFixedLengthVector() 11367 ? APInt::getAllOnes(VT.getVectorMinNumElements()) 11368 : APInt(1, 1); 11369 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs); 11370 } 11371 11372 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 11373 const APInt &DemandedElts, 11374 bool AllowUndefs) { 11375 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 11376 return CN; 11377 11378 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 11379 BitVector UndefElements; 11380 ConstantFPSDNode *CN = 11381 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 11382 // TODO: Look into whether we should allow UndefElements in non-DemandedElts 11383 if (CN && (UndefElements.none() || AllowUndefs)) 11384 return CN; 11385 } 11386 11387 if (N.getOpcode() == ISD::SPLAT_VECTOR) 11388 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 11389 return CN; 11390 11391 return nullptr; 11392 } 11393 11394 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 11395 // TODO: may want to use peekThroughBitcast() here. 11396 ConstantSDNode *C = 11397 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 11398 return C && C->isZero(); 11399 } 11400 11401 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 11402 ConstantSDNode *C = 11403 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true); 11404 return C && C->isOne(); 11405 } 11406 11407 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 11408 N = peekThroughBitcasts(N); 11409 unsigned BitWidth = N.getScalarValueSizeInBits(); 11410 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 11411 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 11412 } 11413 11414 HandleSDNode::~HandleSDNode() { 11415 DropOperands(); 11416 } 11417 11418 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 11419 const DebugLoc &DL, 11420 const GlobalValue *GA, EVT VT, 11421 int64_t o, unsigned TF) 11422 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 11423 TheGlobal = GA; 11424 } 11425 11426 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 11427 EVT VT, unsigned SrcAS, 11428 unsigned DestAS) 11429 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 11430 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 11431 11432 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 11433 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 11434 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 11435 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 11436 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 11437 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 11438 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 11439 11440 // We check here that the size of the memory operand fits within the size of 11441 // the MMO. This is because the MMO might indicate only a possible address 11442 // range instead of specifying the affected memory addresses precisely. 11443 // TODO: Make MachineMemOperands aware of scalable vectors. 11444 assert(memvt.getStoreSize().getKnownMinValue() <= MMO->getSize() && 11445 "Size mismatch!"); 11446 } 11447 11448 /// Profile - Gather unique data for the node. 11449 /// 11450 void SDNode::Profile(FoldingSetNodeID &ID) const { 11451 AddNodeIDNode(ID, this); 11452 } 11453 11454 namespace { 11455 11456 struct EVTArray { 11457 std::vector<EVT> VTs; 11458 11459 EVTArray() { 11460 VTs.reserve(MVT::VALUETYPE_SIZE); 11461 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 11462 VTs.push_back(MVT((MVT::SimpleValueType)i)); 11463 } 11464 }; 11465 11466 } // end anonymous namespace 11467 11468 /// getValueTypeList - Return a pointer to the specified value type. 11469 /// 11470 const EVT *SDNode::getValueTypeList(EVT VT) { 11471 static std::set<EVT, EVT::compareRawBits> EVTs; 11472 static EVTArray SimpleVTArray; 11473 static sys::SmartMutex<true> VTMutex; 11474 11475 if (VT.isExtended()) { 11476 sys::SmartScopedLock<true> Lock(VTMutex); 11477 return &(*EVTs.insert(VT).first); 11478 } 11479 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 11480 return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy]; 11481 } 11482 11483 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 11484 /// indicated value. This method ignores uses of other values defined by this 11485 /// operation. 11486 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 11487 assert(Value < getNumValues() && "Bad value!"); 11488 11489 // TODO: Only iterate over uses of a given value of the node 11490 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 11491 if (UI.getUse().getResNo() == Value) { 11492 if (NUses == 0) 11493 return false; 11494 --NUses; 11495 } 11496 } 11497 11498 // Found exactly the right number of uses? 11499 return NUses == 0; 11500 } 11501 11502 /// hasAnyUseOfValue - Return true if there are any use of the indicated 11503 /// value. This method ignores uses of other values defined by this operation. 11504 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 11505 assert(Value < getNumValues() && "Bad value!"); 11506 11507 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 11508 if (UI.getUse().getResNo() == Value) 11509 return true; 11510 11511 return false; 11512 } 11513 11514 /// isOnlyUserOf - Return true if this node is the only use of N. 11515 bool SDNode::isOnlyUserOf(const SDNode *N) const { 11516 bool Seen = false; 11517 for (const SDNode *User : N->uses()) { 11518 if (User == this) 11519 Seen = true; 11520 else 11521 return false; 11522 } 11523 11524 return Seen; 11525 } 11526 11527 /// Return true if the only users of N are contained in Nodes. 11528 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 11529 bool Seen = false; 11530 for (const SDNode *User : N->uses()) { 11531 if (llvm::is_contained(Nodes, User)) 11532 Seen = true; 11533 else 11534 return false; 11535 } 11536 11537 return Seen; 11538 } 11539 11540 /// isOperand - Return true if this node is an operand of N. 11541 bool SDValue::isOperandOf(const SDNode *N) const { 11542 return is_contained(N->op_values(), *this); 11543 } 11544 11545 bool SDNode::isOperandOf(const SDNode *N) const { 11546 return any_of(N->op_values(), 11547 [this](SDValue Op) { return this == Op.getNode(); }); 11548 } 11549 11550 /// reachesChainWithoutSideEffects - Return true if this operand (which must 11551 /// be a chain) reaches the specified operand without crossing any 11552 /// side-effecting instructions on any chain path. In practice, this looks 11553 /// through token factors and non-volatile loads. In order to remain efficient, 11554 /// this only looks a couple of nodes in, it does not do an exhaustive search. 11555 /// 11556 /// Note that we only need to examine chains when we're searching for 11557 /// side-effects; SelectionDAG requires that all side-effects are represented 11558 /// by chains, even if another operand would force a specific ordering. This 11559 /// constraint is necessary to allow transformations like splitting loads. 11560 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 11561 unsigned Depth) const { 11562 if (*this == Dest) return true; 11563 11564 // Don't search too deeply, we just want to be able to see through 11565 // TokenFactor's etc. 11566 if (Depth == 0) return false; 11567 11568 // If this is a token factor, all inputs to the TF happen in parallel. 11569 if (getOpcode() == ISD::TokenFactor) { 11570 // First, try a shallow search. 11571 if (is_contained((*this)->ops(), Dest)) { 11572 // We found the chain we want as an operand of this TokenFactor. 11573 // Essentially, we reach the chain without side-effects if we could 11574 // serialize the TokenFactor into a simple chain of operations with 11575 // Dest as the last operation. This is automatically true if the 11576 // chain has one use: there are no other ordering constraints. 11577 // If the chain has more than one use, we give up: some other 11578 // use of Dest might force a side-effect between Dest and the current 11579 // node. 11580 if (Dest.hasOneUse()) 11581 return true; 11582 } 11583 // Next, try a deep search: check whether every operand of the TokenFactor 11584 // reaches Dest. 11585 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 11586 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 11587 }); 11588 } 11589 11590 // Loads don't have side effects, look through them. 11591 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 11592 if (Ld->isUnordered()) 11593 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 11594 } 11595 return false; 11596 } 11597 11598 bool SDNode::hasPredecessor(const SDNode *N) const { 11599 SmallPtrSet<const SDNode *, 32> Visited; 11600 SmallVector<const SDNode *, 16> Worklist; 11601 Worklist.push_back(this); 11602 return hasPredecessorHelper(N, Visited, Worklist); 11603 } 11604 11605 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 11606 this->Flags.intersectWith(Flags); 11607 } 11608 11609 SDValue 11610 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 11611 ArrayRef<ISD::NodeType> CandidateBinOps, 11612 bool AllowPartials) { 11613 // The pattern must end in an extract from index 0. 11614 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 11615 !isNullConstant(Extract->getOperand(1))) 11616 return SDValue(); 11617 11618 // Match against one of the candidate binary ops. 11619 SDValue Op = Extract->getOperand(0); 11620 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 11621 return Op.getOpcode() == unsigned(BinOp); 11622 })) 11623 return SDValue(); 11624 11625 // Floating-point reductions may require relaxed constraints on the final step 11626 // of the reduction because they may reorder intermediate operations. 11627 unsigned CandidateBinOp = Op.getOpcode(); 11628 if (Op.getValueType().isFloatingPoint()) { 11629 SDNodeFlags Flags = Op->getFlags(); 11630 switch (CandidateBinOp) { 11631 case ISD::FADD: 11632 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 11633 return SDValue(); 11634 break; 11635 default: 11636 llvm_unreachable("Unhandled FP opcode for binop reduction"); 11637 } 11638 } 11639 11640 // Matching failed - attempt to see if we did enough stages that a partial 11641 // reduction from a subvector is possible. 11642 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 11643 if (!AllowPartials || !Op) 11644 return SDValue(); 11645 EVT OpVT = Op.getValueType(); 11646 EVT OpSVT = OpVT.getScalarType(); 11647 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 11648 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 11649 return SDValue(); 11650 BinOp = (ISD::NodeType)CandidateBinOp; 11651 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 11652 getVectorIdxConstant(0, SDLoc(Op))); 11653 }; 11654 11655 // At each stage, we're looking for something that looks like: 11656 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 11657 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 11658 // i32 undef, i32 undef, i32 undef, i32 undef> 11659 // %a = binop <8 x i32> %op, %s 11660 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 11661 // we expect something like: 11662 // <4,5,6,7,u,u,u,u> 11663 // <2,3,u,u,u,u,u,u> 11664 // <1,u,u,u,u,u,u,u> 11665 // While a partial reduction match would be: 11666 // <2,3,u,u,u,u,u,u> 11667 // <1,u,u,u,u,u,u,u> 11668 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 11669 SDValue PrevOp; 11670 for (unsigned i = 0; i < Stages; ++i) { 11671 unsigned MaskEnd = (1 << i); 11672 11673 if (Op.getOpcode() != CandidateBinOp) 11674 return PartialReduction(PrevOp, MaskEnd); 11675 11676 SDValue Op0 = Op.getOperand(0); 11677 SDValue Op1 = Op.getOperand(1); 11678 11679 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 11680 if (Shuffle) { 11681 Op = Op1; 11682 } else { 11683 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 11684 Op = Op0; 11685 } 11686 11687 // The first operand of the shuffle should be the same as the other operand 11688 // of the binop. 11689 if (!Shuffle || Shuffle->getOperand(0) != Op) 11690 return PartialReduction(PrevOp, MaskEnd); 11691 11692 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 11693 for (int Index = 0; Index < (int)MaskEnd; ++Index) 11694 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 11695 return PartialReduction(PrevOp, MaskEnd); 11696 11697 PrevOp = Op; 11698 } 11699 11700 // Handle subvector reductions, which tend to appear after the shuffle 11701 // reduction stages. 11702 while (Op.getOpcode() == CandidateBinOp) { 11703 unsigned NumElts = Op.getValueType().getVectorNumElements(); 11704 SDValue Op0 = Op.getOperand(0); 11705 SDValue Op1 = Op.getOperand(1); 11706 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 11707 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 11708 Op0.getOperand(0) != Op1.getOperand(0)) 11709 break; 11710 SDValue Src = Op0.getOperand(0); 11711 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 11712 if (NumSrcElts != (2 * NumElts)) 11713 break; 11714 if (!(Op0.getConstantOperandAPInt(1) == 0 && 11715 Op1.getConstantOperandAPInt(1) == NumElts) && 11716 !(Op1.getConstantOperandAPInt(1) == 0 && 11717 Op0.getConstantOperandAPInt(1) == NumElts)) 11718 break; 11719 Op = Src; 11720 } 11721 11722 BinOp = (ISD::NodeType)CandidateBinOp; 11723 return Op; 11724 } 11725 11726 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 11727 EVT VT = N->getValueType(0); 11728 EVT EltVT = VT.getVectorElementType(); 11729 unsigned NE = VT.getVectorNumElements(); 11730 11731 SDLoc dl(N); 11732 11733 // If ResNE is 0, fully unroll the vector op. 11734 if (ResNE == 0) 11735 ResNE = NE; 11736 else if (NE > ResNE) 11737 NE = ResNE; 11738 11739 if (N->getNumValues() == 2) { 11740 SmallVector<SDValue, 8> Scalars0, Scalars1; 11741 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 11742 EVT VT1 = N->getValueType(1); 11743 EVT EltVT1 = VT1.getVectorElementType(); 11744 11745 unsigned i; 11746 for (i = 0; i != NE; ++i) { 11747 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 11748 SDValue Operand = N->getOperand(j); 11749 EVT OperandVT = Operand.getValueType(); 11750 11751 // A vector operand; extract a single element. 11752 EVT OperandEltVT = OperandVT.getVectorElementType(); 11753 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 11754 Operand, getVectorIdxConstant(i, dl)); 11755 } 11756 11757 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands); 11758 Scalars0.push_back(EltOp); 11759 Scalars1.push_back(EltOp.getValue(1)); 11760 } 11761 11762 SDValue Vec0 = getBuildVector(VT, dl, Scalars0); 11763 SDValue Vec1 = getBuildVector(VT1, dl, Scalars1); 11764 return getMergeValues({Vec0, Vec1}, dl); 11765 } 11766 11767 assert(N->getNumValues() == 1 && 11768 "Can't unroll a vector with multiple results!"); 11769 11770 SmallVector<SDValue, 8> Scalars; 11771 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 11772 11773 unsigned i; 11774 for (i= 0; i != NE; ++i) { 11775 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 11776 SDValue Operand = N->getOperand(j); 11777 EVT OperandVT = Operand.getValueType(); 11778 if (OperandVT.isVector()) { 11779 // A vector operand; extract a single element. 11780 EVT OperandEltVT = OperandVT.getVectorElementType(); 11781 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 11782 Operand, getVectorIdxConstant(i, dl)); 11783 } else { 11784 // A scalar operand; just use it as is. 11785 Operands[j] = Operand; 11786 } 11787 } 11788 11789 switch (N->getOpcode()) { 11790 default: { 11791 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 11792 N->getFlags())); 11793 break; 11794 } 11795 case ISD::VSELECT: 11796 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 11797 break; 11798 case ISD::SHL: 11799 case ISD::SRA: 11800 case ISD::SRL: 11801 case ISD::ROTL: 11802 case ISD::ROTR: 11803 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 11804 getShiftAmountOperand(Operands[0].getValueType(), 11805 Operands[1]))); 11806 break; 11807 case ISD::SIGN_EXTEND_INREG: { 11808 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 11809 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 11810 Operands[0], 11811 getValueType(ExtVT))); 11812 } 11813 } 11814 } 11815 11816 for (; i < ResNE; ++i) 11817 Scalars.push_back(getUNDEF(EltVT)); 11818 11819 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 11820 return getBuildVector(VecVT, dl, Scalars); 11821 } 11822 11823 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 11824 SDNode *N, unsigned ResNE) { 11825 unsigned Opcode = N->getOpcode(); 11826 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 11827 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 11828 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 11829 "Expected an overflow opcode"); 11830 11831 EVT ResVT = N->getValueType(0); 11832 EVT OvVT = N->getValueType(1); 11833 EVT ResEltVT = ResVT.getVectorElementType(); 11834 EVT OvEltVT = OvVT.getVectorElementType(); 11835 SDLoc dl(N); 11836 11837 // If ResNE is 0, fully unroll the vector op. 11838 unsigned NE = ResVT.getVectorNumElements(); 11839 if (ResNE == 0) 11840 ResNE = NE; 11841 else if (NE > ResNE) 11842 NE = ResNE; 11843 11844 SmallVector<SDValue, 8> LHSScalars; 11845 SmallVector<SDValue, 8> RHSScalars; 11846 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 11847 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 11848 11849 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 11850 SDVTList VTs = getVTList(ResEltVT, SVT); 11851 SmallVector<SDValue, 8> ResScalars; 11852 SmallVector<SDValue, 8> OvScalars; 11853 for (unsigned i = 0; i < NE; ++i) { 11854 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 11855 SDValue Ov = 11856 getSelect(dl, OvEltVT, Res.getValue(1), 11857 getBoolConstant(true, dl, OvEltVT, ResVT), 11858 getConstant(0, dl, OvEltVT)); 11859 11860 ResScalars.push_back(Res); 11861 OvScalars.push_back(Ov); 11862 } 11863 11864 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 11865 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 11866 11867 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 11868 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 11869 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 11870 getBuildVector(NewOvVT, dl, OvScalars)); 11871 } 11872 11873 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 11874 LoadSDNode *Base, 11875 unsigned Bytes, 11876 int Dist) const { 11877 if (LD->isVolatile() || Base->isVolatile()) 11878 return false; 11879 // TODO: probably too restrictive for atomics, revisit 11880 if (!LD->isSimple()) 11881 return false; 11882 if (LD->isIndexed() || Base->isIndexed()) 11883 return false; 11884 if (LD->getChain() != Base->getChain()) 11885 return false; 11886 EVT VT = LD->getMemoryVT(); 11887 if (VT.getSizeInBits() / 8 != Bytes) 11888 return false; 11889 11890 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 11891 auto LocDecomp = BaseIndexOffset::match(LD, *this); 11892 11893 int64_t Offset = 0; 11894 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 11895 return (Dist * (int64_t)Bytes == Offset); 11896 return false; 11897 } 11898 11899 /// InferPtrAlignment - Infer alignment of a load / store address. Return 11900 /// std::nullopt if it cannot be inferred. 11901 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 11902 // If this is a GlobalAddress + cst, return the alignment. 11903 const GlobalValue *GV = nullptr; 11904 int64_t GVOffset = 0; 11905 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 11906 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 11907 KnownBits Known(PtrWidth); 11908 llvm::computeKnownBits(GV, Known, getDataLayout()); 11909 unsigned AlignBits = Known.countMinTrailingZeros(); 11910 if (AlignBits) 11911 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11912 } 11913 11914 // If this is a direct reference to a stack slot, use information about the 11915 // stack slot's alignment. 11916 int FrameIdx = INT_MIN; 11917 int64_t FrameOffset = 0; 11918 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11919 FrameIdx = FI->getIndex(); 11920 } else if (isBaseWithConstantOffset(Ptr) && 11921 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11922 // Handle FI+Cst 11923 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11924 FrameOffset = Ptr.getConstantOperandVal(1); 11925 } 11926 11927 if (FrameIdx != INT_MIN) { 11928 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11929 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11930 } 11931 11932 return std::nullopt; 11933 } 11934 11935 /// Split the scalar node with EXTRACT_ELEMENT using the provided 11936 /// VTs and return the low/high part. 11937 std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N, 11938 const SDLoc &DL, 11939 const EVT &LoVT, 11940 const EVT &HiVT) { 11941 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() && 11942 "Split node must be a scalar type"); 11943 SDValue Lo = 11944 getNode(ISD::EXTRACT_ELEMENT, DL, LoVT, N, getIntPtrConstant(0, DL)); 11945 SDValue Hi = 11946 getNode(ISD::EXTRACT_ELEMENT, DL, HiVT, N, getIntPtrConstant(1, DL)); 11947 return std::make_pair(Lo, Hi); 11948 } 11949 11950 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11951 /// which is split (or expanded) into two not necessarily identical pieces. 11952 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11953 // Currently all types are split in half. 11954 EVT LoVT, HiVT; 11955 if (!VT.isVector()) 11956 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11957 else 11958 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11959 11960 return std::make_pair(LoVT, HiVT); 11961 } 11962 11963 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11964 /// type, dependent on an enveloping VT that has been split into two identical 11965 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11966 std::pair<EVT, EVT> 11967 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11968 bool *HiIsEmpty) const { 11969 EVT EltTp = VT.getVectorElementType(); 11970 // Examples: 11971 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11972 // custom VL=9 with enveloping VL=8/8 yields 8/1 11973 // custom VL=10 with enveloping VL=8/8 yields 8/2 11974 // etc. 11975 ElementCount VTNumElts = VT.getVectorElementCount(); 11976 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11977 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11978 "Mixing fixed width and scalable vectors when enveloping a type"); 11979 EVT LoVT, HiVT; 11980 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11981 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11982 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11983 *HiIsEmpty = false; 11984 } else { 11985 // Flag that hi type has zero storage size, but return split envelop type 11986 // (this would be easier if vector types with zero elements were allowed). 11987 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11988 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11989 *HiIsEmpty = true; 11990 } 11991 return std::make_pair(LoVT, HiVT); 11992 } 11993 11994 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11995 /// low/high part. 11996 std::pair<SDValue, SDValue> 11997 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11998 const EVT &HiVT) { 11999 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 12000 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 12001 "Splitting vector with an invalid mixture of fixed and scalable " 12002 "vector types"); 12003 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 12004 N.getValueType().getVectorMinNumElements() && 12005 "More vector elements requested than available!"); 12006 SDValue Lo, Hi; 12007 Lo = 12008 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 12009 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 12010 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 12011 // IDX with the runtime scaling factor of the result vector type. For 12012 // fixed-width result vectors, that runtime scaling factor is 1. 12013 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 12014 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 12015 return std::make_pair(Lo, Hi); 12016 } 12017 12018 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 12019 const SDLoc &DL) { 12020 // Split the vector length parameter. 12021 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 12022 EVT VT = N.getValueType(); 12023 assert(VecVT.getVectorElementCount().isKnownEven() && 12024 "Expecting the mask to be an evenly-sized vector"); 12025 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 12026 SDValue HalfNumElts = 12027 VecVT.isFixedLengthVector() 12028 ? getConstant(HalfMinNumElts, DL, VT) 12029 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 12030 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 12031 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 12032 return std::make_pair(Lo, Hi); 12033 } 12034 12035 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 12036 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 12037 EVT VT = N.getValueType(); 12038 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 12039 NextPowerOf2(VT.getVectorNumElements())); 12040 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 12041 getVectorIdxConstant(0, DL)); 12042 } 12043 12044 void SelectionDAG::ExtractVectorElements(SDValue Op, 12045 SmallVectorImpl<SDValue> &Args, 12046 unsigned Start, unsigned Count, 12047 EVT EltVT) { 12048 EVT VT = Op.getValueType(); 12049 if (Count == 0) 12050 Count = VT.getVectorNumElements(); 12051 if (EltVT == EVT()) 12052 EltVT = VT.getVectorElementType(); 12053 SDLoc SL(Op); 12054 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 12055 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 12056 getVectorIdxConstant(i, SL))); 12057 } 12058 } 12059 12060 // getAddressSpace - Return the address space this GlobalAddress belongs to. 12061 unsigned GlobalAddressSDNode::getAddressSpace() const { 12062 return getGlobal()->getType()->getAddressSpace(); 12063 } 12064 12065 Type *ConstantPoolSDNode::getType() const { 12066 if (isMachineConstantPoolEntry()) 12067 return Val.MachineCPVal->getType(); 12068 return Val.ConstVal->getType(); 12069 } 12070 12071 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 12072 unsigned &SplatBitSize, 12073 bool &HasAnyUndefs, 12074 unsigned MinSplatBits, 12075 bool IsBigEndian) const { 12076 EVT VT = getValueType(0); 12077 assert(VT.isVector() && "Expected a vector type"); 12078 unsigned VecWidth = VT.getSizeInBits(); 12079 if (MinSplatBits > VecWidth) 12080 return false; 12081 12082 // FIXME: The widths are based on this node's type, but build vectors can 12083 // truncate their operands. 12084 SplatValue = APInt(VecWidth, 0); 12085 SplatUndef = APInt(VecWidth, 0); 12086 12087 // Get the bits. Bits with undefined values (when the corresponding element 12088 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 12089 // in SplatValue. If any of the values are not constant, give up and return 12090 // false. 12091 unsigned int NumOps = getNumOperands(); 12092 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 12093 unsigned EltWidth = VT.getScalarSizeInBits(); 12094 12095 for (unsigned j = 0; j < NumOps; ++j) { 12096 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 12097 SDValue OpVal = getOperand(i); 12098 unsigned BitPos = j * EltWidth; 12099 12100 if (OpVal.isUndef()) 12101 SplatUndef.setBits(BitPos, BitPos + EltWidth); 12102 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 12103 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 12104 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 12105 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 12106 else 12107 return false; 12108 } 12109 12110 // The build_vector is all constants or undefs. Find the smallest element 12111 // size that splats the vector. 12112 HasAnyUndefs = (SplatUndef != 0); 12113 12114 // FIXME: This does not work for vectors with elements less than 8 bits. 12115 while (VecWidth > 8) { 12116 unsigned HalfSize = VecWidth / 2; 12117 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 12118 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 12119 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 12120 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 12121 12122 // If the two halves do not match (ignoring undef bits), stop here. 12123 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 12124 MinSplatBits > HalfSize) 12125 break; 12126 12127 SplatValue = HighValue | LowValue; 12128 SplatUndef = HighUndef & LowUndef; 12129 12130 VecWidth = HalfSize; 12131 } 12132 12133 SplatBitSize = VecWidth; 12134 return true; 12135 } 12136 12137 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 12138 BitVector *UndefElements) const { 12139 unsigned NumOps = getNumOperands(); 12140 if (UndefElements) { 12141 UndefElements->clear(); 12142 UndefElements->resize(NumOps); 12143 } 12144 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 12145 if (!DemandedElts) 12146 return SDValue(); 12147 SDValue Splatted; 12148 for (unsigned i = 0; i != NumOps; ++i) { 12149 if (!DemandedElts[i]) 12150 continue; 12151 SDValue Op = getOperand(i); 12152 if (Op.isUndef()) { 12153 if (UndefElements) 12154 (*UndefElements)[i] = true; 12155 } else if (!Splatted) { 12156 Splatted = Op; 12157 } else if (Splatted != Op) { 12158 return SDValue(); 12159 } 12160 } 12161 12162 if (!Splatted) { 12163 unsigned FirstDemandedIdx = DemandedElts.countr_zero(); 12164 assert(getOperand(FirstDemandedIdx).isUndef() && 12165 "Can only have a splat without a constant for all undefs."); 12166 return getOperand(FirstDemandedIdx); 12167 } 12168 12169 return Splatted; 12170 } 12171 12172 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 12173 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 12174 return getSplatValue(DemandedElts, UndefElements); 12175 } 12176 12177 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 12178 SmallVectorImpl<SDValue> &Sequence, 12179 BitVector *UndefElements) const { 12180 unsigned NumOps = getNumOperands(); 12181 Sequence.clear(); 12182 if (UndefElements) { 12183 UndefElements->clear(); 12184 UndefElements->resize(NumOps); 12185 } 12186 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 12187 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 12188 return false; 12189 12190 // Set the undefs even if we don't find a sequence (like getSplatValue). 12191 if (UndefElements) 12192 for (unsigned I = 0; I != NumOps; ++I) 12193 if (DemandedElts[I] && getOperand(I).isUndef()) 12194 (*UndefElements)[I] = true; 12195 12196 // Iteratively widen the sequence length looking for repetitions. 12197 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 12198 Sequence.append(SeqLen, SDValue()); 12199 for (unsigned I = 0; I != NumOps; ++I) { 12200 if (!DemandedElts[I]) 12201 continue; 12202 SDValue &SeqOp = Sequence[I % SeqLen]; 12203 SDValue Op = getOperand(I); 12204 if (Op.isUndef()) { 12205 if (!SeqOp) 12206 SeqOp = Op; 12207 continue; 12208 } 12209 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 12210 Sequence.clear(); 12211 break; 12212 } 12213 SeqOp = Op; 12214 } 12215 if (!Sequence.empty()) 12216 return true; 12217 } 12218 12219 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 12220 return false; 12221 } 12222 12223 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 12224 BitVector *UndefElements) const { 12225 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 12226 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 12227 } 12228 12229 ConstantSDNode * 12230 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 12231 BitVector *UndefElements) const { 12232 return dyn_cast_or_null<ConstantSDNode>( 12233 getSplatValue(DemandedElts, UndefElements)); 12234 } 12235 12236 ConstantSDNode * 12237 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 12238 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 12239 } 12240 12241 ConstantFPSDNode * 12242 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 12243 BitVector *UndefElements) const { 12244 return dyn_cast_or_null<ConstantFPSDNode>( 12245 getSplatValue(DemandedElts, UndefElements)); 12246 } 12247 12248 ConstantFPSDNode * 12249 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 12250 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 12251 } 12252 12253 int32_t 12254 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 12255 uint32_t BitWidth) const { 12256 if (ConstantFPSDNode *CN = 12257 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 12258 bool IsExact; 12259 APSInt IntVal(BitWidth); 12260 const APFloat &APF = CN->getValueAPF(); 12261 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 12262 APFloat::opOK || 12263 !IsExact) 12264 return -1; 12265 12266 return IntVal.exactLogBase2(); 12267 } 12268 return -1; 12269 } 12270 12271 bool BuildVectorSDNode::getConstantRawBits( 12272 bool IsLittleEndian, unsigned DstEltSizeInBits, 12273 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 12274 // Early-out if this contains anything but Undef/Constant/ConstantFP. 12275 if (!isConstant()) 12276 return false; 12277 12278 unsigned NumSrcOps = getNumOperands(); 12279 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 12280 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 12281 "Invalid bitcast scale"); 12282 12283 // Extract raw src bits. 12284 SmallVector<APInt> SrcBitElements(NumSrcOps, 12285 APInt::getZero(SrcEltSizeInBits)); 12286 BitVector SrcUndeElements(NumSrcOps, false); 12287 12288 for (unsigned I = 0; I != NumSrcOps; ++I) { 12289 SDValue Op = getOperand(I); 12290 if (Op.isUndef()) { 12291 SrcUndeElements.set(I); 12292 continue; 12293 } 12294 auto *CInt = dyn_cast<ConstantSDNode>(Op); 12295 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 12296 assert((CInt || CFP) && "Unknown constant"); 12297 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits) 12298 : CFP->getValueAPF().bitcastToAPInt(); 12299 } 12300 12301 // Recast to dst width. 12302 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 12303 SrcBitElements, UndefElements, SrcUndeElements); 12304 return true; 12305 } 12306 12307 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 12308 unsigned DstEltSizeInBits, 12309 SmallVectorImpl<APInt> &DstBitElements, 12310 ArrayRef<APInt> SrcBitElements, 12311 BitVector &DstUndefElements, 12312 const BitVector &SrcUndefElements) { 12313 unsigned NumSrcOps = SrcBitElements.size(); 12314 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 12315 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 12316 "Invalid bitcast scale"); 12317 assert(NumSrcOps == SrcUndefElements.size() && 12318 "Vector size mismatch"); 12319 12320 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 12321 DstUndefElements.clear(); 12322 DstUndefElements.resize(NumDstOps, false); 12323 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits)); 12324 12325 // Concatenate src elements constant bits together into dst element. 12326 if (SrcEltSizeInBits <= DstEltSizeInBits) { 12327 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 12328 for (unsigned I = 0; I != NumDstOps; ++I) { 12329 DstUndefElements.set(I); 12330 APInt &DstBits = DstBitElements[I]; 12331 for (unsigned J = 0; J != Scale; ++J) { 12332 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 12333 if (SrcUndefElements[Idx]) 12334 continue; 12335 DstUndefElements.reset(I); 12336 const APInt &SrcBits = SrcBitElements[Idx]; 12337 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 12338 "Illegal constant bitwidths"); 12339 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 12340 } 12341 } 12342 return; 12343 } 12344 12345 // Split src element constant bits into dst elements. 12346 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 12347 for (unsigned I = 0; I != NumSrcOps; ++I) { 12348 if (SrcUndefElements[I]) { 12349 DstUndefElements.set(I * Scale, (I + 1) * Scale); 12350 continue; 12351 } 12352 const APInt &SrcBits = SrcBitElements[I]; 12353 for (unsigned J = 0; J != Scale; ++J) { 12354 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 12355 APInt &DstBits = DstBitElements[Idx]; 12356 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 12357 } 12358 } 12359 } 12360 12361 bool BuildVectorSDNode::isConstant() const { 12362 for (const SDValue &Op : op_values()) { 12363 unsigned Opc = Op.getOpcode(); 12364 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 12365 return false; 12366 } 12367 return true; 12368 } 12369 12370 std::optional<std::pair<APInt, APInt>> 12371 BuildVectorSDNode::isConstantSequence() const { 12372 unsigned NumOps = getNumOperands(); 12373 if (NumOps < 2) 12374 return std::nullopt; 12375 12376 if (!isa<ConstantSDNode>(getOperand(0)) || 12377 !isa<ConstantSDNode>(getOperand(1))) 12378 return std::nullopt; 12379 12380 unsigned EltSize = getValueType(0).getScalarSizeInBits(); 12381 APInt Start = getConstantOperandAPInt(0).trunc(EltSize); 12382 APInt Stride = getConstantOperandAPInt(1).trunc(EltSize) - Start; 12383 12384 if (Stride.isZero()) 12385 return std::nullopt; 12386 12387 for (unsigned i = 2; i < NumOps; ++i) { 12388 if (!isa<ConstantSDNode>(getOperand(i))) 12389 return std::nullopt; 12390 12391 APInt Val = getConstantOperandAPInt(i).trunc(EltSize); 12392 if (Val != (Start + (Stride * i))) 12393 return std::nullopt; 12394 } 12395 12396 return std::make_pair(Start, Stride); 12397 } 12398 12399 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 12400 // Find the first non-undef value in the shuffle mask. 12401 unsigned i, e; 12402 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 12403 /* search */; 12404 12405 // If all elements are undefined, this shuffle can be considered a splat 12406 // (although it should eventually get simplified away completely). 12407 if (i == e) 12408 return true; 12409 12410 // Make sure all remaining elements are either undef or the same as the first 12411 // non-undef value. 12412 for (int Idx = Mask[i]; i != e; ++i) 12413 if (Mask[i] >= 0 && Mask[i] != Idx) 12414 return false; 12415 return true; 12416 } 12417 12418 // Returns the SDNode if it is a constant integer BuildVector 12419 // or constant integer. 12420 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 12421 if (isa<ConstantSDNode>(N)) 12422 return N.getNode(); 12423 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 12424 return N.getNode(); 12425 // Treat a GlobalAddress supporting constant offset folding as a 12426 // constant integer. 12427 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 12428 if (GA->getOpcode() == ISD::GlobalAddress && 12429 TLI->isOffsetFoldingLegal(GA)) 12430 return GA; 12431 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 12432 isa<ConstantSDNode>(N.getOperand(0))) 12433 return N.getNode(); 12434 return nullptr; 12435 } 12436 12437 // Returns the SDNode if it is a constant float BuildVector 12438 // or constant float. 12439 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 12440 if (isa<ConstantFPSDNode>(N)) 12441 return N.getNode(); 12442 12443 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 12444 return N.getNode(); 12445 12446 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 12447 isa<ConstantFPSDNode>(N.getOperand(0))) 12448 return N.getNode(); 12449 12450 return nullptr; 12451 } 12452 12453 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 12454 assert(!Node->OperandList && "Node already has operands"); 12455 assert(SDNode::getMaxNumOperands() >= Vals.size() && 12456 "too many operands to fit into SDNode"); 12457 SDUse *Ops = OperandRecycler.allocate( 12458 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 12459 12460 bool IsDivergent = false; 12461 for (unsigned I = 0; I != Vals.size(); ++I) { 12462 Ops[I].setUser(Node); 12463 Ops[I].setInitial(Vals[I]); 12464 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 12465 IsDivergent |= Ops[I].getNode()->isDivergent(); 12466 } 12467 Node->NumOperands = Vals.size(); 12468 Node->OperandList = Ops; 12469 if (!TLI->isSDNodeAlwaysUniform(Node)) { 12470 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA); 12471 Node->SDNodeBits.IsDivergent = IsDivergent; 12472 } 12473 checkForCycles(Node); 12474 } 12475 12476 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 12477 SmallVectorImpl<SDValue> &Vals) { 12478 size_t Limit = SDNode::getMaxNumOperands(); 12479 while (Vals.size() > Limit) { 12480 unsigned SliceIdx = Vals.size() - Limit; 12481 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 12482 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 12483 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 12484 Vals.emplace_back(NewTF); 12485 } 12486 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 12487 } 12488 12489 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 12490 EVT VT, SDNodeFlags Flags) { 12491 switch (Opcode) { 12492 default: 12493 return SDValue(); 12494 case ISD::ADD: 12495 case ISD::OR: 12496 case ISD::XOR: 12497 case ISD::UMAX: 12498 return getConstant(0, DL, VT); 12499 case ISD::MUL: 12500 return getConstant(1, DL, VT); 12501 case ISD::AND: 12502 case ISD::UMIN: 12503 return getAllOnesConstant(DL, VT); 12504 case ISD::SMAX: 12505 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 12506 case ISD::SMIN: 12507 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 12508 case ISD::FADD: 12509 return getConstantFP(-0.0, DL, VT); 12510 case ISD::FMUL: 12511 return getConstantFP(1.0, DL, VT); 12512 case ISD::FMINNUM: 12513 case ISD::FMAXNUM: { 12514 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 12515 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 12516 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 12517 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 12518 APFloat::getLargest(Semantics); 12519 if (Opcode == ISD::FMAXNUM) 12520 NeutralAF.changeSign(); 12521 12522 return getConstantFP(NeutralAF, DL, VT); 12523 } 12524 case ISD::FMINIMUM: 12525 case ISD::FMAXIMUM: { 12526 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF. 12527 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 12528 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics) 12529 : APFloat::getLargest(Semantics); 12530 if (Opcode == ISD::FMAXIMUM) 12531 NeutralAF.changeSign(); 12532 12533 return getConstantFP(NeutralAF, DL, VT); 12534 } 12535 12536 } 12537 } 12538 12539 /// Helper used to make a call to a library function that has one argument of 12540 /// pointer type. 12541 /// 12542 /// Such functions include 'fegetmode', 'fesetenv' and some others, which are 12543 /// used to get or set floating-point state. They have one argument of pointer 12544 /// type, which points to the memory region containing bits of the 12545 /// floating-point state. The value returned by such function is ignored in the 12546 /// created call. 12547 /// 12548 /// \param LibFunc Reference to library function (value of RTLIB::Libcall). 12549 /// \param Ptr Pointer used to save/load state. 12550 /// \param InChain Ingoing token chain. 12551 /// \returns Outgoing chain token. 12552 SDValue SelectionDAG::makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, 12553 SDValue InChain, 12554 const SDLoc &DLoc) { 12555 assert(InChain.getValueType() == MVT::Other && "Expected token chain"); 12556 TargetLowering::ArgListTy Args; 12557 TargetLowering::ArgListEntry Entry; 12558 Entry.Node = Ptr; 12559 Entry.Ty = Ptr.getValueType().getTypeForEVT(*getContext()); 12560 Args.push_back(Entry); 12561 RTLIB::Libcall LC = static_cast<RTLIB::Libcall>(LibFunc); 12562 SDValue Callee = getExternalSymbol(TLI->getLibcallName(LC), 12563 TLI->getPointerTy(getDataLayout())); 12564 TargetLowering::CallLoweringInfo CLI(*this); 12565 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee( 12566 TLI->getLibcallCallingConv(LC), Type::getVoidTy(*getContext()), Callee, 12567 std::move(Args)); 12568 return TLI->LowerCallTo(CLI).second; 12569 } 12570 12571 void SelectionDAG::copyExtraInfo(SDNode *From, SDNode *To) { 12572 assert(From && To && "Invalid SDNode; empty source SDValue?"); 12573 auto I = SDEI.find(From); 12574 if (I == SDEI.end()) 12575 return; 12576 12577 // Use of operator[] on the DenseMap may cause an insertion, which invalidates 12578 // the iterator, hence the need to make a copy to prevent a use-after-free. 12579 NodeExtraInfo NEI = I->second; 12580 if (LLVM_LIKELY(!NEI.PCSections)) { 12581 // No deep copy required for the types of extra info set. 12582 // 12583 // FIXME: Investigate if other types of extra info also need deep copy. This 12584 // depends on the types of nodes they can be attached to: if some extra info 12585 // is only ever attached to nodes where a replacement To node is always the 12586 // node where later use and propagation of the extra info has the intended 12587 // semantics, no deep copy is required. 12588 SDEI[To] = std::move(NEI); 12589 return; 12590 } 12591 12592 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced 12593 // through the replacement of From with To. Otherwise, replacements of a node 12594 // (From) with more complex nodes (To and its operands) may result in lost 12595 // extra info where the root node (To) is insignificant in further propagating 12596 // and using extra info when further lowering to MIR. 12597 // 12598 // In the first step pre-populate the visited set with the nodes reachable 12599 // from the old From node. This avoids copying NodeExtraInfo to parts of the 12600 // DAG that is not new and should be left untouched. 12601 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom. 12602 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From. 12603 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) { 12604 if (MaxDepth == 0) { 12605 // Remember this node in case we need to increase MaxDepth and continue 12606 // populating FromReach from this node. 12607 Leafs.emplace_back(N); 12608 return; 12609 } 12610 if (!FromReach.insert(N).second) 12611 return; 12612 for (const SDValue &Op : N->op_values()) 12613 Self(Self, Op.getNode(), MaxDepth - 1); 12614 }; 12615 12616 // Copy extra info to To and all its transitive operands (that are new). 12617 SmallPtrSet<const SDNode *, 8> Visited; 12618 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) { 12619 if (FromReach.contains(N)) 12620 return true; 12621 if (!Visited.insert(N).second) 12622 return true; 12623 if (getEntryNode().getNode() == N) 12624 return false; 12625 for (const SDValue &Op : N->op_values()) { 12626 if (!Self(Self, Op.getNode())) 12627 return false; 12628 } 12629 // Copy only if entry node was not reached. 12630 SDEI[N] = NEI; 12631 return true; 12632 }; 12633 12634 // We first try with a lower MaxDepth, assuming that the path to common 12635 // operands between From and To is relatively short. This significantly 12636 // improves performance in the common case. The initial MaxDepth is big 12637 // enough to avoid retry in the common case; the last MaxDepth is large 12638 // enough to avoid having to use the fallback below (and protects from 12639 // potential stack exhaustion from recursion). 12640 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024; 12641 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) { 12642 // StartFrom is the previous (or initial) set of leafs reachable at the 12643 // previous maximum depth. 12644 SmallVector<const SDNode *> StartFrom; 12645 std::swap(StartFrom, Leafs); 12646 for (const SDNode *N : StartFrom) 12647 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth); 12648 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To))) 12649 return; 12650 // This should happen very rarely (reached the entry node). 12651 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n"); 12652 assert(!Leafs.empty()); 12653 } 12654 12655 // This should not happen - but if it did, that means the subgraph reachable 12656 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom() 12657 // could not visit all reachable common operands. Consequently, we were able 12658 // to reach the entry node. 12659 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n"; 12660 assert(false && "From subgraph too complex - increase max. MaxDepth?"); 12661 // Best-effort fallback if assertions disabled. 12662 SDEI[To] = std::move(NEI); 12663 } 12664 12665 #ifndef NDEBUG 12666 static void checkForCyclesHelper(const SDNode *N, 12667 SmallPtrSetImpl<const SDNode*> &Visited, 12668 SmallPtrSetImpl<const SDNode*> &Checked, 12669 const llvm::SelectionDAG *DAG) { 12670 // If this node has already been checked, don't check it again. 12671 if (Checked.count(N)) 12672 return; 12673 12674 // If a node has already been visited on this depth-first walk, reject it as 12675 // a cycle. 12676 if (!Visited.insert(N).second) { 12677 errs() << "Detected cycle in SelectionDAG\n"; 12678 dbgs() << "Offending node:\n"; 12679 N->dumprFull(DAG); dbgs() << "\n"; 12680 abort(); 12681 } 12682 12683 for (const SDValue &Op : N->op_values()) 12684 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 12685 12686 Checked.insert(N); 12687 Visited.erase(N); 12688 } 12689 #endif 12690 12691 void llvm::checkForCycles(const llvm::SDNode *N, 12692 const llvm::SelectionDAG *DAG, 12693 bool force) { 12694 #ifndef NDEBUG 12695 bool check = force; 12696 #ifdef EXPENSIVE_CHECKS 12697 check = true; 12698 #endif // EXPENSIVE_CHECKS 12699 if (check) { 12700 assert(N && "Checking nonexistent SDNode"); 12701 SmallPtrSet<const SDNode*, 32> visited; 12702 SmallPtrSet<const SDNode*, 32> checked; 12703 checkForCyclesHelper(N, visited, checked, DAG); 12704 } 12705 #endif // !NDEBUG 12706 } 12707 12708 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 12709 checkForCycles(DAG->getRoot().getNode(), DAG, force); 12710 } 12711