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/FoldingSet.h" 21 #include "llvm/ADT/None.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Triple.h" 26 #include "llvm/ADT/Twine.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/ValueTracking.h" 29 #include "llvm/CodeGen/Analysis.h" 30 #include "llvm/CodeGen/FunctionLoweringInfo.h" 31 #include "llvm/CodeGen/ISDOpcodes.h" 32 #include "llvm/CodeGen/MachineBasicBlock.h" 33 #include "llvm/CodeGen/MachineConstantPool.h" 34 #include "llvm/CodeGen/MachineFrameInfo.h" 35 #include "llvm/CodeGen/MachineFunction.h" 36 #include "llvm/CodeGen/MachineMemOperand.h" 37 #include "llvm/CodeGen/RuntimeLibcalls.h" 38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 39 #include "llvm/CodeGen/SelectionDAGNodes.h" 40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 41 #include "llvm/CodeGen/TargetFrameLowering.h" 42 #include "llvm/CodeGen/TargetLowering.h" 43 #include "llvm/CodeGen/TargetRegisterInfo.h" 44 #include "llvm/CodeGen/TargetSubtargetInfo.h" 45 #include "llvm/CodeGen/ValueTypes.h" 46 #include "llvm/IR/Constant.h" 47 #include "llvm/IR/Constants.h" 48 #include "llvm/IR/DataLayout.h" 49 #include "llvm/IR/DebugInfoMetadata.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/IR/GlobalValue.h" 54 #include "llvm/IR/Metadata.h" 55 #include "llvm/IR/Type.h" 56 #include "llvm/Support/Casting.h" 57 #include "llvm/Support/CodeGen.h" 58 #include "llvm/Support/Compiler.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/KnownBits.h" 62 #include "llvm/Support/MachineValueType.h" 63 #include "llvm/Support/ManagedStatic.h" 64 #include "llvm/Support/MathExtras.h" 65 #include "llvm/Support/Mutex.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include "llvm/Target/TargetOptions.h" 69 #include "llvm/Transforms/Utils/SizeOpts.h" 70 #include <algorithm> 71 #include <cassert> 72 #include <cstdint> 73 #include <cstdlib> 74 #include <limits> 75 #include <set> 76 #include <string> 77 #include <utility> 78 #include <vector> 79 80 using namespace llvm; 81 82 /// makeVTList - Return an instance of the SDVTList struct initialized with the 83 /// specified members. 84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 85 SDVTList Res = {VTs, NumVTs}; 86 return Res; 87 } 88 89 // Default null implementations of the callbacks. 90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 93 94 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 95 96 #define DEBUG_TYPE "selectiondag" 97 98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 99 cl::Hidden, cl::init(true), 100 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 101 102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 103 cl::desc("Number limit for gluing ld/st of memcpy."), 104 cl::Hidden, cl::init(0)); 105 106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 107 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 108 } 109 110 //===----------------------------------------------------------------------===// 111 // ConstantFPSDNode Class 112 //===----------------------------------------------------------------------===// 113 114 /// isExactlyValue - We don't rely on operator== working on double values, as 115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 116 /// As such, this method can be used to do an exact bit-for-bit comparison of 117 /// two floating point values. 118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 119 return getValueAPF().bitwiseIsEqual(V); 120 } 121 122 bool ConstantFPSDNode::isValueValidForType(EVT VT, 123 const APFloat& Val) { 124 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 125 126 // convert modifies in place, so make a copy. 127 APFloat Val2 = APFloat(Val); 128 bool losesInfo; 129 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 130 APFloat::rmNearestTiesToEven, 131 &losesInfo); 132 return !losesInfo; 133 } 134 135 //===----------------------------------------------------------------------===// 136 // ISD Namespace 137 //===----------------------------------------------------------------------===// 138 139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 140 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 141 unsigned EltSize = 142 N->getValueType(0).getVectorElementType().getSizeInBits(); 143 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 144 SplatVal = Op0->getAPIntValue().trunc(EltSize); 145 return true; 146 } 147 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 148 SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize); 149 return true; 150 } 151 } 152 153 auto *BV = dyn_cast<BuildVectorSDNode>(N); 154 if (!BV) 155 return false; 156 157 APInt SplatUndef; 158 unsigned SplatBitSize; 159 bool HasUndefs; 160 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 161 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 162 EltSize) && 163 EltSize == SplatBitSize; 164 } 165 166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 167 // specializations of the more general isConstantSplatVector()? 168 169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 170 // Look through a bit convert. 171 while (N->getOpcode() == ISD::BITCAST) 172 N = N->getOperand(0).getNode(); 173 174 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 175 APInt SplatVal; 176 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 177 } 178 179 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 180 181 unsigned i = 0, e = N->getNumOperands(); 182 183 // Skip over all of the undef values. 184 while (i != e && N->getOperand(i).isUndef()) 185 ++i; 186 187 // Do not accept an all-undef vector. 188 if (i == e) return false; 189 190 // Do not accept build_vectors that aren't all constants or which have non-~0 191 // elements. We have to be a bit careful here, as the type of the constant 192 // may not be the same as the type of the vector elements due to type 193 // legalization (the elements are promoted to a legal type for the target and 194 // a vector of a type may be legal when the base element type is not). 195 // We only want to check enough bits to cover the vector elements, because 196 // we care if the resultant vector is all ones, not whether the individual 197 // constants are. 198 SDValue NotZero = N->getOperand(i); 199 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 200 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 201 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 202 return false; 203 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 204 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 205 return false; 206 } else 207 return false; 208 209 // Okay, we have at least one ~0 value, check to see if the rest match or are 210 // undefs. Even with the above element type twiddling, this should be OK, as 211 // the same type legalization should have applied to all the elements. 212 for (++i; i != e; ++i) 213 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 214 return false; 215 return true; 216 } 217 218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 219 // Look through a bit convert. 220 while (N->getOpcode() == ISD::BITCAST) 221 N = N->getOperand(0).getNode(); 222 223 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 224 APInt SplatVal; 225 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 226 } 227 228 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 229 230 bool IsAllUndef = true; 231 for (const SDValue &Op : N->op_values()) { 232 if (Op.isUndef()) 233 continue; 234 IsAllUndef = false; 235 // Do not accept build_vectors that aren't all constants or which have non-0 236 // elements. We have to be a bit careful here, as the type of the constant 237 // may not be the same as the type of the vector elements due to type 238 // legalization (the elements are promoted to a legal type for the target 239 // and a vector of a type may be legal when the base element type is not). 240 // We only want to check enough bits to cover the vector elements, because 241 // we care if the resultant vector is all zeros, not whether the individual 242 // constants are. 243 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 244 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 245 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 246 return false; 247 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 248 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 249 return false; 250 } else 251 return false; 252 } 253 254 // Do not accept an all-undef vector. 255 if (IsAllUndef) 256 return false; 257 return true; 258 } 259 260 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 261 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 262 } 263 264 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 265 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 266 } 267 268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 269 if (N->getOpcode() != ISD::BUILD_VECTOR) 270 return false; 271 272 for (const SDValue &Op : N->op_values()) { 273 if (Op.isUndef()) 274 continue; 275 if (!isa<ConstantSDNode>(Op)) 276 return false; 277 } 278 return true; 279 } 280 281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 282 if (N->getOpcode() != ISD::BUILD_VECTOR) 283 return false; 284 285 for (const SDValue &Op : N->op_values()) { 286 if (Op.isUndef()) 287 continue; 288 if (!isa<ConstantFPSDNode>(Op)) 289 return false; 290 } 291 return true; 292 } 293 294 bool ISD::allOperandsUndef(const SDNode *N) { 295 // Return false if the node has no operands. 296 // This is "logically inconsistent" with the definition of "all" but 297 // is probably the desired behavior. 298 if (N->getNumOperands() == 0) 299 return false; 300 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 301 } 302 303 bool ISD::matchUnaryPredicate(SDValue Op, 304 std::function<bool(ConstantSDNode *)> Match, 305 bool AllowUndefs) { 306 // FIXME: Add support for scalar UNDEF cases? 307 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 308 return Match(Cst); 309 310 // FIXME: Add support for vector UNDEF cases? 311 if (ISD::BUILD_VECTOR != Op.getOpcode() && 312 ISD::SPLAT_VECTOR != Op.getOpcode()) 313 return false; 314 315 EVT SVT = Op.getValueType().getScalarType(); 316 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 317 if (AllowUndefs && Op.getOperand(i).isUndef()) { 318 if (!Match(nullptr)) 319 return false; 320 continue; 321 } 322 323 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 324 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 325 return false; 326 } 327 return true; 328 } 329 330 bool ISD::matchBinaryPredicate( 331 SDValue LHS, SDValue RHS, 332 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 333 bool AllowUndefs, bool AllowTypeMismatch) { 334 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 335 return false; 336 337 // TODO: Add support for scalar UNDEF cases? 338 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 339 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 340 return Match(LHSCst, RHSCst); 341 342 // TODO: Add support for vector UNDEF cases? 343 if (LHS.getOpcode() != RHS.getOpcode() || 344 (LHS.getOpcode() != ISD::BUILD_VECTOR && 345 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 346 return false; 347 348 EVT SVT = LHS.getValueType().getScalarType(); 349 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 350 SDValue LHSOp = LHS.getOperand(i); 351 SDValue RHSOp = RHS.getOperand(i); 352 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 353 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 354 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 355 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 356 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 357 return false; 358 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 359 LHSOp.getValueType() != RHSOp.getValueType())) 360 return false; 361 if (!Match(LHSCst, RHSCst)) 362 return false; 363 } 364 return true; 365 } 366 367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 368 switch (VecReduceOpcode) { 369 default: 370 llvm_unreachable("Expected VECREDUCE opcode"); 371 case ISD::VECREDUCE_FADD: 372 case ISD::VECREDUCE_SEQ_FADD: 373 case ISD::VP_REDUCE_FADD: 374 case ISD::VP_REDUCE_SEQ_FADD: 375 return ISD::FADD; 376 case ISD::VECREDUCE_FMUL: 377 case ISD::VECREDUCE_SEQ_FMUL: 378 case ISD::VP_REDUCE_FMUL: 379 case ISD::VP_REDUCE_SEQ_FMUL: 380 return ISD::FMUL; 381 case ISD::VECREDUCE_ADD: 382 case ISD::VP_REDUCE_ADD: 383 return ISD::ADD; 384 case ISD::VECREDUCE_MUL: 385 case ISD::VP_REDUCE_MUL: 386 return ISD::MUL; 387 case ISD::VECREDUCE_AND: 388 case ISD::VP_REDUCE_AND: 389 return ISD::AND; 390 case ISD::VECREDUCE_OR: 391 case ISD::VP_REDUCE_OR: 392 return ISD::OR; 393 case ISD::VECREDUCE_XOR: 394 case ISD::VP_REDUCE_XOR: 395 return ISD::XOR; 396 case ISD::VECREDUCE_SMAX: 397 case ISD::VP_REDUCE_SMAX: 398 return ISD::SMAX; 399 case ISD::VECREDUCE_SMIN: 400 case ISD::VP_REDUCE_SMIN: 401 return ISD::SMIN; 402 case ISD::VECREDUCE_UMAX: 403 case ISD::VP_REDUCE_UMAX: 404 return ISD::UMAX; 405 case ISD::VECREDUCE_UMIN: 406 case ISD::VP_REDUCE_UMIN: 407 return ISD::UMIN; 408 case ISD::VECREDUCE_FMAX: 409 case ISD::VP_REDUCE_FMAX: 410 return ISD::FMAXNUM; 411 case ISD::VECREDUCE_FMIN: 412 case ISD::VP_REDUCE_FMIN: 413 return ISD::FMINNUM; 414 } 415 } 416 417 bool ISD::isVPOpcode(unsigned Opcode) { 418 switch (Opcode) { 419 default: 420 return false; 421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 422 case ISD::VPSD: \ 423 return true; 424 #include "llvm/IR/VPIntrinsics.def" 425 } 426 } 427 428 bool ISD::isVPBinaryOp(unsigned Opcode) { 429 switch (Opcode) { 430 default: 431 break; 432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 433 #define VP_PROPERTY_BINARYOP return true; 434 #define END_REGISTER_VP_SDNODE(VPSD) break; 435 #include "llvm/IR/VPIntrinsics.def" 436 } 437 return false; 438 } 439 440 bool ISD::isVPReduction(unsigned Opcode) { 441 switch (Opcode) { 442 default: 443 break; 444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 446 #define END_REGISTER_VP_SDNODE(VPSD) break; 447 #include "llvm/IR/VPIntrinsics.def" 448 } 449 return false; 450 } 451 452 /// The operand position of the vector mask. 453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 454 switch (Opcode) { 455 default: 456 return None; 457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 458 case ISD::VPSD: \ 459 return MASKPOS; 460 #include "llvm/IR/VPIntrinsics.def" 461 } 462 } 463 464 /// The operand position of the explicit vector length parameter. 465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 466 switch (Opcode) { 467 default: 468 return None; 469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 470 case ISD::VPSD: \ 471 return EVLPOS; 472 #include "llvm/IR/VPIntrinsics.def" 473 } 474 } 475 476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 477 switch (ExtType) { 478 case ISD::EXTLOAD: 479 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 480 case ISD::SEXTLOAD: 481 return ISD::SIGN_EXTEND; 482 case ISD::ZEXTLOAD: 483 return ISD::ZERO_EXTEND; 484 default: 485 break; 486 } 487 488 llvm_unreachable("Invalid LoadExtType"); 489 } 490 491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 492 // To perform this operation, we just need to swap the L and G bits of the 493 // operation. 494 unsigned OldL = (Operation >> 2) & 1; 495 unsigned OldG = (Operation >> 1) & 1; 496 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 497 (OldL << 1) | // New G bit 498 (OldG << 2)); // New L bit. 499 } 500 501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 502 unsigned Operation = Op; 503 if (isIntegerLike) 504 Operation ^= 7; // Flip L, G, E bits, but not U. 505 else 506 Operation ^= 15; // Flip all of the condition bits. 507 508 if (Operation > ISD::SETTRUE2) 509 Operation &= ~8; // Don't let N and U bits get set. 510 511 return ISD::CondCode(Operation); 512 } 513 514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 515 return getSetCCInverseImpl(Op, Type.isInteger()); 516 } 517 518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 519 bool isIntegerLike) { 520 return getSetCCInverseImpl(Op, isIntegerLike); 521 } 522 523 /// For an integer comparison, return 1 if the comparison is a signed operation 524 /// and 2 if the result is an unsigned comparison. Return zero if the operation 525 /// does not depend on the sign of the input (setne and seteq). 526 static int isSignedOp(ISD::CondCode Opcode) { 527 switch (Opcode) { 528 default: llvm_unreachable("Illegal integer setcc operation!"); 529 case ISD::SETEQ: 530 case ISD::SETNE: return 0; 531 case ISD::SETLT: 532 case ISD::SETLE: 533 case ISD::SETGT: 534 case ISD::SETGE: return 1; 535 case ISD::SETULT: 536 case ISD::SETULE: 537 case ISD::SETUGT: 538 case ISD::SETUGE: return 2; 539 } 540 } 541 542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 543 EVT Type) { 544 bool IsInteger = Type.isInteger(); 545 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 546 // Cannot fold a signed integer setcc with an unsigned integer setcc. 547 return ISD::SETCC_INVALID; 548 549 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 550 551 // If the N and U bits get set, then the resultant comparison DOES suddenly 552 // care about orderedness, and it is true when ordered. 553 if (Op > ISD::SETTRUE2) 554 Op &= ~16; // Clear the U bit if the N bit is set. 555 556 // Canonicalize illegal integer setcc's. 557 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 558 Op = ISD::SETNE; 559 560 return ISD::CondCode(Op); 561 } 562 563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 564 EVT Type) { 565 bool IsInteger = Type.isInteger(); 566 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 567 // Cannot fold a signed setcc with an unsigned setcc. 568 return ISD::SETCC_INVALID; 569 570 // Combine all of the condition bits. 571 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 572 573 // Canonicalize illegal integer setcc's. 574 if (IsInteger) { 575 switch (Result) { 576 default: break; 577 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 578 case ISD::SETOEQ: // SETEQ & SETU[LG]E 579 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 580 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 581 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 582 } 583 } 584 585 return Result; 586 } 587 588 //===----------------------------------------------------------------------===// 589 // SDNode Profile Support 590 //===----------------------------------------------------------------------===// 591 592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 594 ID.AddInteger(OpC); 595 } 596 597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 598 /// solely with their pointer. 599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 600 ID.AddPointer(VTList.VTs); 601 } 602 603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 604 static void AddNodeIDOperands(FoldingSetNodeID &ID, 605 ArrayRef<SDValue> Ops) { 606 for (auto& Op : Ops) { 607 ID.AddPointer(Op.getNode()); 608 ID.AddInteger(Op.getResNo()); 609 } 610 } 611 612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 613 static void AddNodeIDOperands(FoldingSetNodeID &ID, 614 ArrayRef<SDUse> Ops) { 615 for (auto& Op : Ops) { 616 ID.AddPointer(Op.getNode()); 617 ID.AddInteger(Op.getResNo()); 618 } 619 } 620 621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 622 SDVTList VTList, ArrayRef<SDValue> OpList) { 623 AddNodeIDOpcode(ID, OpC); 624 AddNodeIDValueTypes(ID, VTList); 625 AddNodeIDOperands(ID, OpList); 626 } 627 628 /// If this is an SDNode with special info, add this info to the NodeID data. 629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 630 switch (N->getOpcode()) { 631 case ISD::TargetExternalSymbol: 632 case ISD::ExternalSymbol: 633 case ISD::MCSymbol: 634 llvm_unreachable("Should only be used on nodes with operands"); 635 default: break; // Normal nodes don't need extra info. 636 case ISD::TargetConstant: 637 case ISD::Constant: { 638 const ConstantSDNode *C = cast<ConstantSDNode>(N); 639 ID.AddPointer(C->getConstantIntValue()); 640 ID.AddBoolean(C->isOpaque()); 641 break; 642 } 643 case ISD::TargetConstantFP: 644 case ISD::ConstantFP: 645 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 646 break; 647 case ISD::TargetGlobalAddress: 648 case ISD::GlobalAddress: 649 case ISD::TargetGlobalTLSAddress: 650 case ISD::GlobalTLSAddress: { 651 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 652 ID.AddPointer(GA->getGlobal()); 653 ID.AddInteger(GA->getOffset()); 654 ID.AddInteger(GA->getTargetFlags()); 655 break; 656 } 657 case ISD::BasicBlock: 658 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 659 break; 660 case ISD::Register: 661 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 662 break; 663 case ISD::RegisterMask: 664 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 665 break; 666 case ISD::SRCVALUE: 667 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 668 break; 669 case ISD::FrameIndex: 670 case ISD::TargetFrameIndex: 671 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 672 break; 673 case ISD::LIFETIME_START: 674 case ISD::LIFETIME_END: 675 if (cast<LifetimeSDNode>(N)->hasOffset()) { 676 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 677 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 678 } 679 break; 680 case ISD::PSEUDO_PROBE: 681 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 682 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 683 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 684 break; 685 case ISD::JumpTable: 686 case ISD::TargetJumpTable: 687 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 688 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 689 break; 690 case ISD::ConstantPool: 691 case ISD::TargetConstantPool: { 692 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 693 ID.AddInteger(CP->getAlign().value()); 694 ID.AddInteger(CP->getOffset()); 695 if (CP->isMachineConstantPoolEntry()) 696 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 697 else 698 ID.AddPointer(CP->getConstVal()); 699 ID.AddInteger(CP->getTargetFlags()); 700 break; 701 } 702 case ISD::TargetIndex: { 703 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 704 ID.AddInteger(TI->getIndex()); 705 ID.AddInteger(TI->getOffset()); 706 ID.AddInteger(TI->getTargetFlags()); 707 break; 708 } 709 case ISD::LOAD: { 710 const LoadSDNode *LD = cast<LoadSDNode>(N); 711 ID.AddInteger(LD->getMemoryVT().getRawBits()); 712 ID.AddInteger(LD->getRawSubclassData()); 713 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 714 ID.AddInteger(LD->getMemOperand()->getFlags()); 715 break; 716 } 717 case ISD::STORE: { 718 const StoreSDNode *ST = cast<StoreSDNode>(N); 719 ID.AddInteger(ST->getMemoryVT().getRawBits()); 720 ID.AddInteger(ST->getRawSubclassData()); 721 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 722 ID.AddInteger(ST->getMemOperand()->getFlags()); 723 break; 724 } 725 case ISD::VP_LOAD: { 726 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 727 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 728 ID.AddInteger(ELD->getRawSubclassData()); 729 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 730 ID.AddInteger(ELD->getMemOperand()->getFlags()); 731 break; 732 } 733 case ISD::VP_STORE: { 734 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N); 735 ID.AddInteger(EST->getMemoryVT().getRawBits()); 736 ID.AddInteger(EST->getRawSubclassData()); 737 ID.AddInteger(EST->getPointerInfo().getAddrSpace()); 738 ID.AddInteger(EST->getMemOperand()->getFlags()); 739 break; 740 } 741 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: { 742 const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N); 743 ID.AddInteger(SLD->getMemoryVT().getRawBits()); 744 ID.AddInteger(SLD->getRawSubclassData()); 745 ID.AddInteger(SLD->getPointerInfo().getAddrSpace()); 746 break; 747 } 748 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: { 749 const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N); 750 ID.AddInteger(SST->getMemoryVT().getRawBits()); 751 ID.AddInteger(SST->getRawSubclassData()); 752 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 753 break; 754 } 755 case ISD::VP_GATHER: { 756 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 757 ID.AddInteger(EG->getMemoryVT().getRawBits()); 758 ID.AddInteger(EG->getRawSubclassData()); 759 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 760 ID.AddInteger(EG->getMemOperand()->getFlags()); 761 break; 762 } 763 case ISD::VP_SCATTER: { 764 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 765 ID.AddInteger(ES->getMemoryVT().getRawBits()); 766 ID.AddInteger(ES->getRawSubclassData()); 767 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 768 ID.AddInteger(ES->getMemOperand()->getFlags()); 769 break; 770 } 771 case ISD::MLOAD: { 772 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 773 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 774 ID.AddInteger(MLD->getRawSubclassData()); 775 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 776 ID.AddInteger(MLD->getMemOperand()->getFlags()); 777 break; 778 } 779 case ISD::MSTORE: { 780 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 781 ID.AddInteger(MST->getMemoryVT().getRawBits()); 782 ID.AddInteger(MST->getRawSubclassData()); 783 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 784 ID.AddInteger(MST->getMemOperand()->getFlags()); 785 break; 786 } 787 case ISD::MGATHER: { 788 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 789 ID.AddInteger(MG->getMemoryVT().getRawBits()); 790 ID.AddInteger(MG->getRawSubclassData()); 791 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 792 ID.AddInteger(MG->getMemOperand()->getFlags()); 793 break; 794 } 795 case ISD::MSCATTER: { 796 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 797 ID.AddInteger(MS->getMemoryVT().getRawBits()); 798 ID.AddInteger(MS->getRawSubclassData()); 799 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 800 ID.AddInteger(MS->getMemOperand()->getFlags()); 801 break; 802 } 803 case ISD::ATOMIC_CMP_SWAP: 804 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 805 case ISD::ATOMIC_SWAP: 806 case ISD::ATOMIC_LOAD_ADD: 807 case ISD::ATOMIC_LOAD_SUB: 808 case ISD::ATOMIC_LOAD_AND: 809 case ISD::ATOMIC_LOAD_CLR: 810 case ISD::ATOMIC_LOAD_OR: 811 case ISD::ATOMIC_LOAD_XOR: 812 case ISD::ATOMIC_LOAD_NAND: 813 case ISD::ATOMIC_LOAD_MIN: 814 case ISD::ATOMIC_LOAD_MAX: 815 case ISD::ATOMIC_LOAD_UMIN: 816 case ISD::ATOMIC_LOAD_UMAX: 817 case ISD::ATOMIC_LOAD: 818 case ISD::ATOMIC_STORE: { 819 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 820 ID.AddInteger(AT->getMemoryVT().getRawBits()); 821 ID.AddInteger(AT->getRawSubclassData()); 822 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 823 ID.AddInteger(AT->getMemOperand()->getFlags()); 824 break; 825 } 826 case ISD::PREFETCH: { 827 const MemSDNode *PF = cast<MemSDNode>(N); 828 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 829 ID.AddInteger(PF->getMemOperand()->getFlags()); 830 break; 831 } 832 case ISD::VECTOR_SHUFFLE: { 833 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 834 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 835 i != e; ++i) 836 ID.AddInteger(SVN->getMaskElt(i)); 837 break; 838 } 839 case ISD::TargetBlockAddress: 840 case ISD::BlockAddress: { 841 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 842 ID.AddPointer(BA->getBlockAddress()); 843 ID.AddInteger(BA->getOffset()); 844 ID.AddInteger(BA->getTargetFlags()); 845 break; 846 } 847 case ISD::AssertAlign: 848 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value()); 849 break; 850 } // end switch (N->getOpcode()) 851 852 // Target specific memory nodes could also have address spaces and flags 853 // to check. 854 if (N->isTargetMemoryOpcode()) { 855 const MemSDNode *MN = cast<MemSDNode>(N); 856 ID.AddInteger(MN->getPointerInfo().getAddrSpace()); 857 ID.AddInteger(MN->getMemOperand()->getFlags()); 858 } 859 } 860 861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 862 /// data. 863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 864 AddNodeIDOpcode(ID, N->getOpcode()); 865 // Add the return value info. 866 AddNodeIDValueTypes(ID, N->getVTList()); 867 // Add the operand info. 868 AddNodeIDOperands(ID, N->ops()); 869 870 // Handle SDNode leafs with special info. 871 AddNodeIDCustom(ID, N); 872 } 873 874 //===----------------------------------------------------------------------===// 875 // SelectionDAG Class 876 //===----------------------------------------------------------------------===// 877 878 /// doNotCSE - Return true if CSE should not be performed for this node. 879 static bool doNotCSE(SDNode *N) { 880 if (N->getValueType(0) == MVT::Glue) 881 return true; // Never CSE anything that produces a flag. 882 883 switch (N->getOpcode()) { 884 default: break; 885 case ISD::HANDLENODE: 886 case ISD::EH_LABEL: 887 return true; // Never CSE these nodes. 888 } 889 890 // Check that remaining values produced are not flags. 891 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 892 if (N->getValueType(i) == MVT::Glue) 893 return true; // Never CSE anything that produces a flag. 894 895 return false; 896 } 897 898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 899 /// SelectionDAG. 900 void SelectionDAG::RemoveDeadNodes() { 901 // Create a dummy node (which is not added to allnodes), that adds a reference 902 // to the root node, preventing it from being deleted. 903 HandleSDNode Dummy(getRoot()); 904 905 SmallVector<SDNode*, 128> DeadNodes; 906 907 // Add all obviously-dead nodes to the DeadNodes worklist. 908 for (SDNode &Node : allnodes()) 909 if (Node.use_empty()) 910 DeadNodes.push_back(&Node); 911 912 RemoveDeadNodes(DeadNodes); 913 914 // If the root changed (e.g. it was a dead load, update the root). 915 setRoot(Dummy.getValue()); 916 } 917 918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 919 /// given list, and any nodes that become unreachable as a result. 920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 921 922 // Process the worklist, deleting the nodes and adding their uses to the 923 // worklist. 924 while (!DeadNodes.empty()) { 925 SDNode *N = DeadNodes.pop_back_val(); 926 // Skip to next node if we've already managed to delete the node. This could 927 // happen if replacing a node causes a node previously added to the node to 928 // be deleted. 929 if (N->getOpcode() == ISD::DELETED_NODE) 930 continue; 931 932 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 933 DUL->NodeDeleted(N, nullptr); 934 935 // Take the node out of the appropriate CSE map. 936 RemoveNodeFromCSEMaps(N); 937 938 // Next, brutally remove the operand list. This is safe to do, as there are 939 // no cycles in the graph. 940 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 941 SDUse &Use = *I++; 942 SDNode *Operand = Use.getNode(); 943 Use.set(SDValue()); 944 945 // Now that we removed this operand, see if there are no uses of it left. 946 if (Operand->use_empty()) 947 DeadNodes.push_back(Operand); 948 } 949 950 DeallocateNode(N); 951 } 952 } 953 954 void SelectionDAG::RemoveDeadNode(SDNode *N){ 955 SmallVector<SDNode*, 16> DeadNodes(1, N); 956 957 // Create a dummy node that adds a reference to the root node, preventing 958 // it from being deleted. (This matters if the root is an operand of the 959 // dead node.) 960 HandleSDNode Dummy(getRoot()); 961 962 RemoveDeadNodes(DeadNodes); 963 } 964 965 void SelectionDAG::DeleteNode(SDNode *N) { 966 // First take this out of the appropriate CSE map. 967 RemoveNodeFromCSEMaps(N); 968 969 // Finally, remove uses due to operands of this node, remove from the 970 // AllNodes list, and delete the node. 971 DeleteNodeNotInCSEMaps(N); 972 } 973 974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 975 assert(N->getIterator() != AllNodes.begin() && 976 "Cannot delete the entry node!"); 977 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 978 979 // Drop all of the operands and decrement used node's use counts. 980 N->DropOperands(); 981 982 DeallocateNode(N); 983 } 984 985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 986 assert(!(V->isVariadic() && isParameter)); 987 if (isParameter) 988 ByvalParmDbgValues.push_back(V); 989 else 990 DbgValues.push_back(V); 991 for (const SDNode *Node : V->getSDNodes()) 992 if (Node) 993 DbgValMap[Node].push_back(V); 994 } 995 996 void SDDbgInfo::erase(const SDNode *Node) { 997 DbgValMapType::iterator I = DbgValMap.find(Node); 998 if (I == DbgValMap.end()) 999 return; 1000 for (auto &Val: I->second) 1001 Val->setIsInvalidated(); 1002 DbgValMap.erase(I); 1003 } 1004 1005 void SelectionDAG::DeallocateNode(SDNode *N) { 1006 // If we have operands, deallocate them. 1007 removeOperands(N); 1008 1009 NodeAllocator.Deallocate(AllNodes.remove(N)); 1010 1011 // Set the opcode to DELETED_NODE to help catch bugs when node 1012 // memory is reallocated. 1013 // FIXME: There are places in SDag that have grown a dependency on the opcode 1014 // value in the released node. 1015 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 1016 N->NodeType = ISD::DELETED_NODE; 1017 1018 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 1019 // them and forget about that node. 1020 DbgInfo->erase(N); 1021 } 1022 1023 #ifndef NDEBUG 1024 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 1025 static void VerifySDNode(SDNode *N) { 1026 switch (N->getOpcode()) { 1027 default: 1028 break; 1029 case ISD::BUILD_PAIR: { 1030 EVT VT = N->getValueType(0); 1031 assert(N->getNumValues() == 1 && "Too many results!"); 1032 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1033 "Wrong return type!"); 1034 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1035 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1036 "Mismatched operand types!"); 1037 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1038 "Wrong operand type!"); 1039 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1040 "Wrong return type size"); 1041 break; 1042 } 1043 case ISD::BUILD_VECTOR: { 1044 assert(N->getNumValues() == 1 && "Too many results!"); 1045 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1046 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1047 "Wrong number of operands!"); 1048 EVT EltVT = N->getValueType(0).getVectorElementType(); 1049 for (const SDUse &Op : N->ops()) { 1050 assert((Op.getValueType() == EltVT || 1051 (EltVT.isInteger() && Op.getValueType().isInteger() && 1052 EltVT.bitsLE(Op.getValueType()))) && 1053 "Wrong operand type!"); 1054 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1055 "Operands must all have the same type"); 1056 } 1057 break; 1058 } 1059 } 1060 } 1061 #endif // NDEBUG 1062 1063 /// Insert a newly allocated node into the DAG. 1064 /// 1065 /// Handles insertion into the all nodes list and CSE map, as well as 1066 /// verification and other common operations when a new node is allocated. 1067 void SelectionDAG::InsertNode(SDNode *N) { 1068 AllNodes.push_back(N); 1069 #ifndef NDEBUG 1070 N->PersistentId = NextPersistentId++; 1071 VerifySDNode(N); 1072 #endif 1073 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1074 DUL->NodeInserted(N); 1075 } 1076 1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1078 /// correspond to it. This is useful when we're about to delete or repurpose 1079 /// the node. We don't want future request for structurally identical nodes 1080 /// to return N anymore. 1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1082 bool Erased = false; 1083 switch (N->getOpcode()) { 1084 case ISD::HANDLENODE: return false; // noop. 1085 case ISD::CONDCODE: 1086 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1087 "Cond code doesn't exist!"); 1088 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1089 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1090 break; 1091 case ISD::ExternalSymbol: 1092 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1093 break; 1094 case ISD::TargetExternalSymbol: { 1095 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1096 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1097 ESN->getSymbol(), ESN->getTargetFlags())); 1098 break; 1099 } 1100 case ISD::MCSymbol: { 1101 auto *MCSN = cast<MCSymbolSDNode>(N); 1102 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1103 break; 1104 } 1105 case ISD::VALUETYPE: { 1106 EVT VT = cast<VTSDNode>(N)->getVT(); 1107 if (VT.isExtended()) { 1108 Erased = ExtendedValueTypeNodes.erase(VT); 1109 } else { 1110 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1111 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1112 } 1113 break; 1114 } 1115 default: 1116 // Remove it from the CSE Map. 1117 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1118 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1119 Erased = CSEMap.RemoveNode(N); 1120 break; 1121 } 1122 #ifndef NDEBUG 1123 // Verify that the node was actually in one of the CSE maps, unless it has a 1124 // flag result (which cannot be CSE'd) or is one of the special cases that are 1125 // not subject to CSE. 1126 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1127 !N->isMachineOpcode() && !doNotCSE(N)) { 1128 N->dump(this); 1129 dbgs() << "\n"; 1130 llvm_unreachable("Node is not in map!"); 1131 } 1132 #endif 1133 return Erased; 1134 } 1135 1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1138 /// node already exists, in which case transfer all its users to the existing 1139 /// node. This transfer can potentially trigger recursive merging. 1140 void 1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1142 // For node types that aren't CSE'd, just act as if no identical node 1143 // already exists. 1144 if (!doNotCSE(N)) { 1145 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1146 if (Existing != N) { 1147 // If there was already an existing matching node, use ReplaceAllUsesWith 1148 // to replace the dead one with the existing one. This can cause 1149 // recursive merging of other unrelated nodes down the line. 1150 ReplaceAllUsesWith(N, Existing); 1151 1152 // N is now dead. Inform the listeners and delete it. 1153 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1154 DUL->NodeDeleted(N, Existing); 1155 DeleteNodeNotInCSEMaps(N); 1156 return; 1157 } 1158 } 1159 1160 // If the node doesn't already exist, we updated it. Inform listeners. 1161 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1162 DUL->NodeUpdated(N); 1163 } 1164 1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1166 /// were replaced with those specified. If this node is never memoized, 1167 /// return null, otherwise return a pointer to the slot it would take. If a 1168 /// node already exists with these operands, the slot will be non-null. 1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1170 void *&InsertPos) { 1171 if (doNotCSE(N)) 1172 return nullptr; 1173 1174 SDValue Ops[] = { Op }; 1175 FoldingSetNodeID ID; 1176 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1177 AddNodeIDCustom(ID, N); 1178 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1179 if (Node) 1180 Node->intersectFlagsWith(N->getFlags()); 1181 return Node; 1182 } 1183 1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1185 /// were replaced with those specified. If this node is never memoized, 1186 /// return null, otherwise return a pointer to the slot it would take. If a 1187 /// node already exists with these operands, the slot will be non-null. 1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1189 SDValue Op1, SDValue Op2, 1190 void *&InsertPos) { 1191 if (doNotCSE(N)) 1192 return nullptr; 1193 1194 SDValue Ops[] = { Op1, Op2 }; 1195 FoldingSetNodeID ID; 1196 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1197 AddNodeIDCustom(ID, N); 1198 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1199 if (Node) 1200 Node->intersectFlagsWith(N->getFlags()); 1201 return Node; 1202 } 1203 1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1205 /// were replaced with those specified. If this node is never memoized, 1206 /// return null, otherwise return a pointer to the slot it would take. If a 1207 /// node already exists with these operands, the slot will be non-null. 1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1209 void *&InsertPos) { 1210 if (doNotCSE(N)) 1211 return nullptr; 1212 1213 FoldingSetNodeID ID; 1214 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1215 AddNodeIDCustom(ID, N); 1216 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1217 if (Node) 1218 Node->intersectFlagsWith(N->getFlags()); 1219 return Node; 1220 } 1221 1222 Align SelectionDAG::getEVTAlign(EVT VT) const { 1223 Type *Ty = VT == MVT::iPTR ? 1224 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1225 VT.getTypeForEVT(*getContext()); 1226 1227 return getDataLayout().getABITypeAlign(Ty); 1228 } 1229 1230 // EntryNode could meaningfully have debug info if we can find it... 1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1232 : TM(tm), OptLevel(OL), 1233 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1234 Root(getEntryNode()) { 1235 InsertNode(&EntryNode); 1236 DbgInfo = new SDDbgInfo(); 1237 } 1238 1239 void SelectionDAG::init(MachineFunction &NewMF, 1240 OptimizationRemarkEmitter &NewORE, 1241 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1242 LegacyDivergenceAnalysis * Divergence, 1243 ProfileSummaryInfo *PSIin, 1244 BlockFrequencyInfo *BFIin) { 1245 MF = &NewMF; 1246 SDAGISelPass = PassPtr; 1247 ORE = &NewORE; 1248 TLI = getSubtarget().getTargetLowering(); 1249 TSI = getSubtarget().getSelectionDAGInfo(); 1250 LibInfo = LibraryInfo; 1251 Context = &MF->getFunction().getContext(); 1252 DA = Divergence; 1253 PSI = PSIin; 1254 BFI = BFIin; 1255 } 1256 1257 SelectionDAG::~SelectionDAG() { 1258 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1259 allnodes_clear(); 1260 OperandRecycler.clear(OperandAllocator); 1261 delete DbgInfo; 1262 } 1263 1264 bool SelectionDAG::shouldOptForSize() const { 1265 return MF->getFunction().hasOptSize() || 1266 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1267 } 1268 1269 void SelectionDAG::allnodes_clear() { 1270 assert(&*AllNodes.begin() == &EntryNode); 1271 AllNodes.remove(AllNodes.begin()); 1272 while (!AllNodes.empty()) 1273 DeallocateNode(&AllNodes.front()); 1274 #ifndef NDEBUG 1275 NextPersistentId = 0; 1276 #endif 1277 } 1278 1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1280 void *&InsertPos) { 1281 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1282 if (N) { 1283 switch (N->getOpcode()) { 1284 default: break; 1285 case ISD::Constant: 1286 case ISD::ConstantFP: 1287 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1288 "debug location. Use another overload."); 1289 } 1290 } 1291 return N; 1292 } 1293 1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1295 const SDLoc &DL, void *&InsertPos) { 1296 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1297 if (N) { 1298 switch (N->getOpcode()) { 1299 case ISD::Constant: 1300 case ISD::ConstantFP: 1301 // Erase debug location from the node if the node is used at several 1302 // different places. Do not propagate one location to all uses as it 1303 // will cause a worse single stepping debugging experience. 1304 if (N->getDebugLoc() != DL.getDebugLoc()) 1305 N->setDebugLoc(DebugLoc()); 1306 break; 1307 default: 1308 // When the node's point of use is located earlier in the instruction 1309 // sequence than its prior point of use, update its debug info to the 1310 // earlier location. 1311 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1312 N->setDebugLoc(DL.getDebugLoc()); 1313 break; 1314 } 1315 } 1316 return N; 1317 } 1318 1319 void SelectionDAG::clear() { 1320 allnodes_clear(); 1321 OperandRecycler.clear(OperandAllocator); 1322 OperandAllocator.Reset(); 1323 CSEMap.clear(); 1324 1325 ExtendedValueTypeNodes.clear(); 1326 ExternalSymbols.clear(); 1327 TargetExternalSymbols.clear(); 1328 MCSymbols.clear(); 1329 SDCallSiteDbgInfo.clear(); 1330 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1331 static_cast<CondCodeSDNode*>(nullptr)); 1332 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1333 static_cast<SDNode*>(nullptr)); 1334 1335 EntryNode.UseList = nullptr; 1336 InsertNode(&EntryNode); 1337 Root = getEntryNode(); 1338 DbgInfo->clear(); 1339 } 1340 1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1342 return VT.bitsGT(Op.getValueType()) 1343 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1344 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1345 } 1346 1347 std::pair<SDValue, SDValue> 1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1349 const SDLoc &DL, EVT VT) { 1350 assert(!VT.bitsEq(Op.getValueType()) && 1351 "Strict no-op FP extend/round not allowed."); 1352 SDValue Res = 1353 VT.bitsGT(Op.getValueType()) 1354 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1355 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1356 {Chain, Op, getIntPtrConstant(0, DL)}); 1357 1358 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1359 } 1360 1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1362 return VT.bitsGT(Op.getValueType()) ? 1363 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1364 getNode(ISD::TRUNCATE, DL, VT, Op); 1365 } 1366 1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1368 return VT.bitsGT(Op.getValueType()) ? 1369 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1370 getNode(ISD::TRUNCATE, DL, VT, Op); 1371 } 1372 1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1374 return VT.bitsGT(Op.getValueType()) ? 1375 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1376 getNode(ISD::TRUNCATE, DL, VT, Op); 1377 } 1378 1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1380 EVT OpVT) { 1381 if (VT.bitsLE(Op.getValueType())) 1382 return getNode(ISD::TRUNCATE, SL, VT, Op); 1383 1384 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1385 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1386 } 1387 1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1389 EVT OpVT = Op.getValueType(); 1390 assert(VT.isInteger() && OpVT.isInteger() && 1391 "Cannot getZeroExtendInReg FP types"); 1392 assert(VT.isVector() == OpVT.isVector() && 1393 "getZeroExtendInReg type should be vector iff the operand " 1394 "type is vector!"); 1395 assert((!VT.isVector() || 1396 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1397 "Vector element counts must match in getZeroExtendInReg"); 1398 assert(VT.bitsLE(OpVT) && "Not extending!"); 1399 if (OpVT == VT) 1400 return Op; 1401 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1402 VT.getScalarSizeInBits()); 1403 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1404 } 1405 1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1407 // Only unsigned pointer semantics are supported right now. In the future this 1408 // might delegate to TLI to check pointer signedness. 1409 return getZExtOrTrunc(Op, DL, VT); 1410 } 1411 1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1413 // Only unsigned pointer semantics are supported right now. In the future this 1414 // might delegate to TLI to check pointer signedness. 1415 return getZeroExtendInReg(Op, DL, VT); 1416 } 1417 1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1420 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1421 } 1422 1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1424 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1425 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1426 } 1427 1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val, 1429 SDValue Mask, SDValue EVL, EVT VT) { 1430 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1431 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL); 1432 } 1433 1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1435 EVT OpVT) { 1436 if (!V) 1437 return getConstant(0, DL, VT); 1438 1439 switch (TLI->getBooleanContents(OpVT)) { 1440 case TargetLowering::ZeroOrOneBooleanContent: 1441 case TargetLowering::UndefinedBooleanContent: 1442 return getConstant(1, DL, VT); 1443 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1444 return getAllOnesConstant(DL, VT); 1445 } 1446 llvm_unreachable("Unexpected boolean content enum!"); 1447 } 1448 1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1450 bool isT, bool isO) { 1451 EVT EltVT = VT.getScalarType(); 1452 assert((EltVT.getSizeInBits() >= 64 || 1453 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1454 "getConstant with a uint64_t value that doesn't fit in the type!"); 1455 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1456 } 1457 1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1459 bool isT, bool isO) { 1460 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1461 } 1462 1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1464 EVT VT, bool isT, bool isO) { 1465 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1466 1467 EVT EltVT = VT.getScalarType(); 1468 const ConstantInt *Elt = &Val; 1469 1470 // In some cases the vector type is legal but the element type is illegal and 1471 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1472 // inserted value (the type does not need to match the vector element type). 1473 // Any extra bits introduced will be truncated away. 1474 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1475 TargetLowering::TypePromoteInteger) { 1476 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1477 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1478 Elt = ConstantInt::get(*getContext(), NewVal); 1479 } 1480 // In other cases the element type is illegal and needs to be expanded, for 1481 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1482 // the value into n parts and use a vector type with n-times the elements. 1483 // Then bitcast to the type requested. 1484 // Legalizing constants too early makes the DAGCombiner's job harder so we 1485 // only legalize if the DAG tells us we must produce legal types. 1486 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1487 TLI->getTypeAction(*getContext(), EltVT) == 1488 TargetLowering::TypeExpandInteger) { 1489 const APInt &NewVal = Elt->getValue(); 1490 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1491 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1492 1493 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1494 if (VT.isScalableVector()) { 1495 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1496 "Can only handle an even split!"); 1497 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1498 1499 SmallVector<SDValue, 2> ScalarParts; 1500 for (unsigned i = 0; i != Parts; ++i) 1501 ScalarParts.push_back(getConstant( 1502 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1503 ViaEltVT, isT, isO)); 1504 1505 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1506 } 1507 1508 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1509 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1510 1511 // Check the temporary vector is the correct size. If this fails then 1512 // getTypeToTransformTo() probably returned a type whose size (in bits) 1513 // isn't a power-of-2 factor of the requested type size. 1514 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1515 1516 SmallVector<SDValue, 2> EltParts; 1517 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1518 EltParts.push_back(getConstant( 1519 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1520 ViaEltVT, isT, isO)); 1521 1522 // EltParts is currently in little endian order. If we actually want 1523 // big-endian order then reverse it now. 1524 if (getDataLayout().isBigEndian()) 1525 std::reverse(EltParts.begin(), EltParts.end()); 1526 1527 // The elements must be reversed when the element order is different 1528 // to the endianness of the elements (because the BITCAST is itself a 1529 // vector shuffle in this situation). However, we do not need any code to 1530 // perform this reversal because getConstant() is producing a vector 1531 // splat. 1532 // This situation occurs in MIPS MSA. 1533 1534 SmallVector<SDValue, 8> Ops; 1535 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1536 llvm::append_range(Ops, EltParts); 1537 1538 SDValue V = 1539 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1540 return V; 1541 } 1542 1543 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1544 "APInt size does not match type size!"); 1545 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1546 FoldingSetNodeID ID; 1547 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1548 ID.AddPointer(Elt); 1549 ID.AddBoolean(isO); 1550 void *IP = nullptr; 1551 SDNode *N = nullptr; 1552 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1553 if (!VT.isVector()) 1554 return SDValue(N, 0); 1555 1556 if (!N) { 1557 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1558 CSEMap.InsertNode(N, IP); 1559 InsertNode(N); 1560 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1561 } 1562 1563 SDValue Result(N, 0); 1564 if (VT.isScalableVector()) 1565 Result = getSplatVector(VT, DL, Result); 1566 else if (VT.isVector()) 1567 Result = getSplatBuildVector(VT, DL, Result); 1568 1569 return Result; 1570 } 1571 1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1573 bool isTarget) { 1574 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1575 } 1576 1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1578 const SDLoc &DL, bool LegalTypes) { 1579 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1580 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1581 return getConstant(Val, DL, ShiftVT); 1582 } 1583 1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1585 bool isTarget) { 1586 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1587 } 1588 1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1590 bool isTarget) { 1591 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1592 } 1593 1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1595 EVT VT, bool isTarget) { 1596 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1597 1598 EVT EltVT = VT.getScalarType(); 1599 1600 // Do the map lookup using the actual bit pattern for the floating point 1601 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1602 // we don't have issues with SNANs. 1603 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1604 FoldingSetNodeID ID; 1605 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1606 ID.AddPointer(&V); 1607 void *IP = nullptr; 1608 SDNode *N = nullptr; 1609 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1610 if (!VT.isVector()) 1611 return SDValue(N, 0); 1612 1613 if (!N) { 1614 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1615 CSEMap.InsertNode(N, IP); 1616 InsertNode(N); 1617 } 1618 1619 SDValue Result(N, 0); 1620 if (VT.isScalableVector()) 1621 Result = getSplatVector(VT, DL, Result); 1622 else if (VT.isVector()) 1623 Result = getSplatBuildVector(VT, DL, Result); 1624 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1625 return Result; 1626 } 1627 1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1629 bool isTarget) { 1630 EVT EltVT = VT.getScalarType(); 1631 if (EltVT == MVT::f32) 1632 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1633 if (EltVT == MVT::f64) 1634 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1635 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1636 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1637 bool Ignored; 1638 APFloat APF = APFloat(Val); 1639 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1640 &Ignored); 1641 return getConstantFP(APF, DL, VT, isTarget); 1642 } 1643 llvm_unreachable("Unsupported type in getConstantFP"); 1644 } 1645 1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1647 EVT VT, int64_t Offset, bool isTargetGA, 1648 unsigned TargetFlags) { 1649 assert((TargetFlags == 0 || isTargetGA) && 1650 "Cannot set target flags on target-independent globals"); 1651 1652 // Truncate (with sign-extension) the offset value to the pointer size. 1653 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1654 if (BitWidth < 64) 1655 Offset = SignExtend64(Offset, BitWidth); 1656 1657 unsigned Opc; 1658 if (GV->isThreadLocal()) 1659 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1660 else 1661 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1662 1663 FoldingSetNodeID ID; 1664 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1665 ID.AddPointer(GV); 1666 ID.AddInteger(Offset); 1667 ID.AddInteger(TargetFlags); 1668 void *IP = nullptr; 1669 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1670 return SDValue(E, 0); 1671 1672 auto *N = newSDNode<GlobalAddressSDNode>( 1673 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1674 CSEMap.InsertNode(N, IP); 1675 InsertNode(N); 1676 return SDValue(N, 0); 1677 } 1678 1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1680 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1681 FoldingSetNodeID ID; 1682 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1683 ID.AddInteger(FI); 1684 void *IP = nullptr; 1685 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1686 return SDValue(E, 0); 1687 1688 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1689 CSEMap.InsertNode(N, IP); 1690 InsertNode(N); 1691 return SDValue(N, 0); 1692 } 1693 1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1695 unsigned TargetFlags) { 1696 assert((TargetFlags == 0 || isTarget) && 1697 "Cannot set target flags on target-independent jump tables"); 1698 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1699 FoldingSetNodeID ID; 1700 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1701 ID.AddInteger(JTI); 1702 ID.AddInteger(TargetFlags); 1703 void *IP = nullptr; 1704 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1705 return SDValue(E, 0); 1706 1707 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1708 CSEMap.InsertNode(N, IP); 1709 InsertNode(N); 1710 return SDValue(N, 0); 1711 } 1712 1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1714 MaybeAlign Alignment, int Offset, 1715 bool isTarget, unsigned TargetFlags) { 1716 assert((TargetFlags == 0 || isTarget) && 1717 "Cannot set target flags on target-independent globals"); 1718 if (!Alignment) 1719 Alignment = shouldOptForSize() 1720 ? getDataLayout().getABITypeAlign(C->getType()) 1721 : getDataLayout().getPrefTypeAlign(C->getType()); 1722 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1723 FoldingSetNodeID ID; 1724 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1725 ID.AddInteger(Alignment->value()); 1726 ID.AddInteger(Offset); 1727 ID.AddPointer(C); 1728 ID.AddInteger(TargetFlags); 1729 void *IP = nullptr; 1730 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1731 return SDValue(E, 0); 1732 1733 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1734 TargetFlags); 1735 CSEMap.InsertNode(N, IP); 1736 InsertNode(N); 1737 SDValue V = SDValue(N, 0); 1738 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1739 return V; 1740 } 1741 1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1743 MaybeAlign Alignment, int Offset, 1744 bool isTarget, unsigned TargetFlags) { 1745 assert((TargetFlags == 0 || isTarget) && 1746 "Cannot set target flags on target-independent globals"); 1747 if (!Alignment) 1748 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1749 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1750 FoldingSetNodeID ID; 1751 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1752 ID.AddInteger(Alignment->value()); 1753 ID.AddInteger(Offset); 1754 C->addSelectionDAGCSEId(ID); 1755 ID.AddInteger(TargetFlags); 1756 void *IP = nullptr; 1757 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1758 return SDValue(E, 0); 1759 1760 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1761 TargetFlags); 1762 CSEMap.InsertNode(N, IP); 1763 InsertNode(N); 1764 return SDValue(N, 0); 1765 } 1766 1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1768 unsigned TargetFlags) { 1769 FoldingSetNodeID ID; 1770 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1771 ID.AddInteger(Index); 1772 ID.AddInteger(Offset); 1773 ID.AddInteger(TargetFlags); 1774 void *IP = nullptr; 1775 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1776 return SDValue(E, 0); 1777 1778 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1779 CSEMap.InsertNode(N, IP); 1780 InsertNode(N); 1781 return SDValue(N, 0); 1782 } 1783 1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1785 FoldingSetNodeID ID; 1786 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1787 ID.AddPointer(MBB); 1788 void *IP = nullptr; 1789 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1790 return SDValue(E, 0); 1791 1792 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1793 CSEMap.InsertNode(N, IP); 1794 InsertNode(N); 1795 return SDValue(N, 0); 1796 } 1797 1798 SDValue SelectionDAG::getValueType(EVT VT) { 1799 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1800 ValueTypeNodes.size()) 1801 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1802 1803 SDNode *&N = VT.isExtended() ? 1804 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1805 1806 if (N) return SDValue(N, 0); 1807 N = newSDNode<VTSDNode>(VT); 1808 InsertNode(N); 1809 return SDValue(N, 0); 1810 } 1811 1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1813 SDNode *&N = ExternalSymbols[Sym]; 1814 if (N) return SDValue(N, 0); 1815 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1816 InsertNode(N); 1817 return SDValue(N, 0); 1818 } 1819 1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1821 SDNode *&N = MCSymbols[Sym]; 1822 if (N) 1823 return SDValue(N, 0); 1824 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1825 InsertNode(N); 1826 return SDValue(N, 0); 1827 } 1828 1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1830 unsigned TargetFlags) { 1831 SDNode *&N = 1832 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1833 if (N) return SDValue(N, 0); 1834 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1835 InsertNode(N); 1836 return SDValue(N, 0); 1837 } 1838 1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1840 if ((unsigned)Cond >= CondCodeNodes.size()) 1841 CondCodeNodes.resize(Cond+1); 1842 1843 if (!CondCodeNodes[Cond]) { 1844 auto *N = newSDNode<CondCodeSDNode>(Cond); 1845 CondCodeNodes[Cond] = N; 1846 InsertNode(N); 1847 } 1848 1849 return SDValue(CondCodeNodes[Cond], 0); 1850 } 1851 1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1853 APInt One(ResVT.getScalarSizeInBits(), 1); 1854 return getStepVector(DL, ResVT, One); 1855 } 1856 1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1858 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1859 if (ResVT.isScalableVector()) 1860 return getNode( 1861 ISD::STEP_VECTOR, DL, ResVT, 1862 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1863 1864 SmallVector<SDValue, 16> OpsStepConstants; 1865 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1866 OpsStepConstants.push_back( 1867 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1868 return getBuildVector(ResVT, DL, OpsStepConstants); 1869 } 1870 1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1874 std::swap(N1, N2); 1875 ShuffleVectorSDNode::commuteMask(M); 1876 } 1877 1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1879 SDValue N2, ArrayRef<int> Mask) { 1880 assert(VT.getVectorNumElements() == Mask.size() && 1881 "Must have the same number of vector elements as mask elements!"); 1882 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1883 "Invalid VECTOR_SHUFFLE"); 1884 1885 // Canonicalize shuffle undef, undef -> undef 1886 if (N1.isUndef() && N2.isUndef()) 1887 return getUNDEF(VT); 1888 1889 // Validate that all indices in Mask are within the range of the elements 1890 // input to the shuffle. 1891 int NElts = Mask.size(); 1892 assert(llvm::all_of(Mask, 1893 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1894 "Index out of range"); 1895 1896 // Copy the mask so we can do any needed cleanup. 1897 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1898 1899 // Canonicalize shuffle v, v -> v, undef 1900 if (N1 == N2) { 1901 N2 = getUNDEF(VT); 1902 for (int i = 0; i != NElts; ++i) 1903 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1904 } 1905 1906 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1907 if (N1.isUndef()) 1908 commuteShuffle(N1, N2, MaskVec); 1909 1910 if (TLI->hasVectorBlend()) { 1911 // If shuffling a splat, try to blend the splat instead. We do this here so 1912 // that even when this arises during lowering we don't have to re-handle it. 1913 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1914 BitVector UndefElements; 1915 SDValue Splat = BV->getSplatValue(&UndefElements); 1916 if (!Splat) 1917 return; 1918 1919 for (int i = 0; i < NElts; ++i) { 1920 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1921 continue; 1922 1923 // If this input comes from undef, mark it as such. 1924 if (UndefElements[MaskVec[i] - Offset]) { 1925 MaskVec[i] = -1; 1926 continue; 1927 } 1928 1929 // If we can blend a non-undef lane, use that instead. 1930 if (!UndefElements[i]) 1931 MaskVec[i] = i + Offset; 1932 } 1933 }; 1934 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1935 BlendSplat(N1BV, 0); 1936 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1937 BlendSplat(N2BV, NElts); 1938 } 1939 1940 // Canonicalize all index into lhs, -> shuffle lhs, undef 1941 // Canonicalize all index into rhs, -> shuffle rhs, undef 1942 bool AllLHS = true, AllRHS = true; 1943 bool N2Undef = N2.isUndef(); 1944 for (int i = 0; i != NElts; ++i) { 1945 if (MaskVec[i] >= NElts) { 1946 if (N2Undef) 1947 MaskVec[i] = -1; 1948 else 1949 AllLHS = false; 1950 } else if (MaskVec[i] >= 0) { 1951 AllRHS = false; 1952 } 1953 } 1954 if (AllLHS && AllRHS) 1955 return getUNDEF(VT); 1956 if (AllLHS && !N2Undef) 1957 N2 = getUNDEF(VT); 1958 if (AllRHS) { 1959 N1 = getUNDEF(VT); 1960 commuteShuffle(N1, N2, MaskVec); 1961 } 1962 // Reset our undef status after accounting for the mask. 1963 N2Undef = N2.isUndef(); 1964 // Re-check whether both sides ended up undef. 1965 if (N1.isUndef() && N2Undef) 1966 return getUNDEF(VT); 1967 1968 // If Identity shuffle return that node. 1969 bool Identity = true, AllSame = true; 1970 for (int i = 0; i != NElts; ++i) { 1971 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1972 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1973 } 1974 if (Identity && NElts) 1975 return N1; 1976 1977 // Shuffling a constant splat doesn't change the result. 1978 if (N2Undef) { 1979 SDValue V = N1; 1980 1981 // Look through any bitcasts. We check that these don't change the number 1982 // (and size) of elements and just changes their types. 1983 while (V.getOpcode() == ISD::BITCAST) 1984 V = V->getOperand(0); 1985 1986 // A splat should always show up as a build vector node. 1987 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1988 BitVector UndefElements; 1989 SDValue Splat = BV->getSplatValue(&UndefElements); 1990 // If this is a splat of an undef, shuffling it is also undef. 1991 if (Splat && Splat.isUndef()) 1992 return getUNDEF(VT); 1993 1994 bool SameNumElts = 1995 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1996 1997 // We only have a splat which can skip shuffles if there is a splatted 1998 // value and no undef lanes rearranged by the shuffle. 1999 if (Splat && UndefElements.none()) { 2000 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 2001 // number of elements match or the value splatted is a zero constant. 2002 if (SameNumElts) 2003 return N1; 2004 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 2005 if (C->isZero()) 2006 return N1; 2007 } 2008 2009 // If the shuffle itself creates a splat, build the vector directly. 2010 if (AllSame && SameNumElts) { 2011 EVT BuildVT = BV->getValueType(0); 2012 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 2013 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 2014 2015 // We may have jumped through bitcasts, so the type of the 2016 // BUILD_VECTOR may not match the type of the shuffle. 2017 if (BuildVT != VT) 2018 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 2019 return NewBV; 2020 } 2021 } 2022 } 2023 2024 FoldingSetNodeID ID; 2025 SDValue Ops[2] = { N1, N2 }; 2026 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 2027 for (int i = 0; i != NElts; ++i) 2028 ID.AddInteger(MaskVec[i]); 2029 2030 void* IP = nullptr; 2031 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2032 return SDValue(E, 0); 2033 2034 // Allocate the mask array for the node out of the BumpPtrAllocator, since 2035 // SDNode doesn't have access to it. This memory will be "leaked" when 2036 // the node is deallocated, but recovered when the NodeAllocator is released. 2037 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2038 llvm::copy(MaskVec, MaskAlloc); 2039 2040 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2041 dl.getDebugLoc(), MaskAlloc); 2042 createOperands(N, Ops); 2043 2044 CSEMap.InsertNode(N, IP); 2045 InsertNode(N); 2046 SDValue V = SDValue(N, 0); 2047 NewSDValueDbgMsg(V, "Creating new node: ", this); 2048 return V; 2049 } 2050 2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2052 EVT VT = SV.getValueType(0); 2053 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2054 ShuffleVectorSDNode::commuteMask(MaskVec); 2055 2056 SDValue Op0 = SV.getOperand(0); 2057 SDValue Op1 = SV.getOperand(1); 2058 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2059 } 2060 2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2062 FoldingSetNodeID ID; 2063 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2064 ID.AddInteger(RegNo); 2065 void *IP = nullptr; 2066 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2067 return SDValue(E, 0); 2068 2069 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2070 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2071 CSEMap.InsertNode(N, IP); 2072 InsertNode(N); 2073 return SDValue(N, 0); 2074 } 2075 2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2077 FoldingSetNodeID ID; 2078 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2079 ID.AddPointer(RegMask); 2080 void *IP = nullptr; 2081 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2082 return SDValue(E, 0); 2083 2084 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2085 CSEMap.InsertNode(N, IP); 2086 InsertNode(N); 2087 return SDValue(N, 0); 2088 } 2089 2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2091 MCSymbol *Label) { 2092 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2093 } 2094 2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2096 SDValue Root, MCSymbol *Label) { 2097 FoldingSetNodeID ID; 2098 SDValue Ops[] = { Root }; 2099 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2100 ID.AddPointer(Label); 2101 void *IP = nullptr; 2102 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2103 return SDValue(E, 0); 2104 2105 auto *N = 2106 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2107 createOperands(N, Ops); 2108 2109 CSEMap.InsertNode(N, IP); 2110 InsertNode(N); 2111 return SDValue(N, 0); 2112 } 2113 2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2115 int64_t Offset, bool isTarget, 2116 unsigned TargetFlags) { 2117 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2118 2119 FoldingSetNodeID ID; 2120 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2121 ID.AddPointer(BA); 2122 ID.AddInteger(Offset); 2123 ID.AddInteger(TargetFlags); 2124 void *IP = nullptr; 2125 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2126 return SDValue(E, 0); 2127 2128 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2129 CSEMap.InsertNode(N, IP); 2130 InsertNode(N); 2131 return SDValue(N, 0); 2132 } 2133 2134 SDValue SelectionDAG::getSrcValue(const Value *V) { 2135 FoldingSetNodeID ID; 2136 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2137 ID.AddPointer(V); 2138 2139 void *IP = nullptr; 2140 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2141 return SDValue(E, 0); 2142 2143 auto *N = newSDNode<SrcValueSDNode>(V); 2144 CSEMap.InsertNode(N, IP); 2145 InsertNode(N); 2146 return SDValue(N, 0); 2147 } 2148 2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2150 FoldingSetNodeID ID; 2151 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2152 ID.AddPointer(MD); 2153 2154 void *IP = nullptr; 2155 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2156 return SDValue(E, 0); 2157 2158 auto *N = newSDNode<MDNodeSDNode>(MD); 2159 CSEMap.InsertNode(N, IP); 2160 InsertNode(N); 2161 return SDValue(N, 0); 2162 } 2163 2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2165 if (VT == V.getValueType()) 2166 return V; 2167 2168 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2169 } 2170 2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2172 unsigned SrcAS, unsigned DestAS) { 2173 SDValue Ops[] = {Ptr}; 2174 FoldingSetNodeID ID; 2175 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2176 ID.AddInteger(SrcAS); 2177 ID.AddInteger(DestAS); 2178 2179 void *IP = nullptr; 2180 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2181 return SDValue(E, 0); 2182 2183 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2184 VT, SrcAS, DestAS); 2185 createOperands(N, Ops); 2186 2187 CSEMap.InsertNode(N, IP); 2188 InsertNode(N); 2189 return SDValue(N, 0); 2190 } 2191 2192 SDValue SelectionDAG::getFreeze(SDValue V) { 2193 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2194 } 2195 2196 /// getShiftAmountOperand - Return the specified value casted to 2197 /// the target's desired shift amount type. 2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2199 EVT OpTy = Op.getValueType(); 2200 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2201 if (OpTy == ShTy || OpTy.isVector()) return Op; 2202 2203 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2204 } 2205 2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2207 SDLoc dl(Node); 2208 const TargetLowering &TLI = getTargetLoweringInfo(); 2209 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2210 EVT VT = Node->getValueType(0); 2211 SDValue Tmp1 = Node->getOperand(0); 2212 SDValue Tmp2 = Node->getOperand(1); 2213 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2214 2215 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2216 Tmp2, MachinePointerInfo(V)); 2217 SDValue VAList = VAListLoad; 2218 2219 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2220 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2221 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2222 2223 VAList = 2224 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2225 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2226 } 2227 2228 // Increment the pointer, VAList, to the next vaarg 2229 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2230 getConstant(getDataLayout().getTypeAllocSize( 2231 VT.getTypeForEVT(*getContext())), 2232 dl, VAList.getValueType())); 2233 // Store the incremented VAList to the legalized pointer 2234 Tmp1 = 2235 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2236 // Load the actual argument out of the pointer VAList 2237 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2238 } 2239 2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2241 SDLoc dl(Node); 2242 const TargetLowering &TLI = getTargetLoweringInfo(); 2243 // This defaults to loading a pointer from the input and storing it to the 2244 // output, returning the chain. 2245 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2246 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2247 SDValue Tmp1 = 2248 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2249 Node->getOperand(2), MachinePointerInfo(VS)); 2250 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2251 MachinePointerInfo(VD)); 2252 } 2253 2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2255 const DataLayout &DL = getDataLayout(); 2256 Type *Ty = VT.getTypeForEVT(*getContext()); 2257 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2258 2259 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2260 return RedAlign; 2261 2262 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2263 const Align StackAlign = TFI->getStackAlign(); 2264 2265 // See if we can choose a smaller ABI alignment in cases where it's an 2266 // illegal vector type that will get broken down. 2267 if (RedAlign > StackAlign) { 2268 EVT IntermediateVT; 2269 MVT RegisterVT; 2270 unsigned NumIntermediates; 2271 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2272 NumIntermediates, RegisterVT); 2273 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2274 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2275 if (RedAlign2 < RedAlign) 2276 RedAlign = RedAlign2; 2277 } 2278 2279 return RedAlign; 2280 } 2281 2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2283 MachineFrameInfo &MFI = MF->getFrameInfo(); 2284 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2285 int StackID = 0; 2286 if (Bytes.isScalable()) 2287 StackID = TFI->getStackIDForScalableVectors(); 2288 // The stack id gives an indication of whether the object is scalable or 2289 // not, so it's safe to pass in the minimum size here. 2290 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2291 false, nullptr, StackID); 2292 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2293 } 2294 2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2296 Type *Ty = VT.getTypeForEVT(*getContext()); 2297 Align StackAlign = 2298 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2299 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2300 } 2301 2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2303 TypeSize VT1Size = VT1.getStoreSize(); 2304 TypeSize VT2Size = VT2.getStoreSize(); 2305 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2306 "Don't know how to choose the maximum size when creating a stack " 2307 "temporary"); 2308 TypeSize Bytes = 2309 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2310 2311 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2312 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2313 const DataLayout &DL = getDataLayout(); 2314 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2315 return CreateStackTemporary(Bytes, Align); 2316 } 2317 2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2319 ISD::CondCode Cond, const SDLoc &dl) { 2320 EVT OpVT = N1.getValueType(); 2321 2322 // These setcc operations always fold. 2323 switch (Cond) { 2324 default: break; 2325 case ISD::SETFALSE: 2326 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2327 case ISD::SETTRUE: 2328 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2329 2330 case ISD::SETOEQ: 2331 case ISD::SETOGT: 2332 case ISD::SETOGE: 2333 case ISD::SETOLT: 2334 case ISD::SETOLE: 2335 case ISD::SETONE: 2336 case ISD::SETO: 2337 case ISD::SETUO: 2338 case ISD::SETUEQ: 2339 case ISD::SETUNE: 2340 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2341 break; 2342 } 2343 2344 if (OpVT.isInteger()) { 2345 // For EQ and NE, we can always pick a value for the undef to make the 2346 // predicate pass or fail, so we can return undef. 2347 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2348 // icmp eq/ne X, undef -> undef. 2349 if ((N1.isUndef() || N2.isUndef()) && 2350 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2351 return getUNDEF(VT); 2352 2353 // If both operands are undef, we can return undef for int comparison. 2354 // icmp undef, undef -> undef. 2355 if (N1.isUndef() && N2.isUndef()) 2356 return getUNDEF(VT); 2357 2358 // icmp X, X -> true/false 2359 // icmp X, undef -> true/false because undef could be X. 2360 if (N1 == N2) 2361 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2362 } 2363 2364 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2365 const APInt &C2 = N2C->getAPIntValue(); 2366 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2367 const APInt &C1 = N1C->getAPIntValue(); 2368 2369 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2370 dl, VT, OpVT); 2371 } 2372 } 2373 2374 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2375 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2376 2377 if (N1CFP && N2CFP) { 2378 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2379 switch (Cond) { 2380 default: break; 2381 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2382 return getUNDEF(VT); 2383 LLVM_FALLTHROUGH; 2384 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2385 OpVT); 2386 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2387 return getUNDEF(VT); 2388 LLVM_FALLTHROUGH; 2389 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2390 R==APFloat::cmpLessThan, dl, VT, 2391 OpVT); 2392 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2393 return getUNDEF(VT); 2394 LLVM_FALLTHROUGH; 2395 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2396 OpVT); 2397 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2398 return getUNDEF(VT); 2399 LLVM_FALLTHROUGH; 2400 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2401 VT, OpVT); 2402 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2403 return getUNDEF(VT); 2404 LLVM_FALLTHROUGH; 2405 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2406 R==APFloat::cmpEqual, dl, VT, 2407 OpVT); 2408 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2409 return getUNDEF(VT); 2410 LLVM_FALLTHROUGH; 2411 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2412 R==APFloat::cmpEqual, dl, VT, OpVT); 2413 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2414 OpVT); 2415 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2416 OpVT); 2417 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2418 R==APFloat::cmpEqual, dl, VT, 2419 OpVT); 2420 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2421 OpVT); 2422 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2423 R==APFloat::cmpLessThan, dl, VT, 2424 OpVT); 2425 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2426 R==APFloat::cmpUnordered, dl, VT, 2427 OpVT); 2428 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2429 VT, OpVT); 2430 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2431 OpVT); 2432 } 2433 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2434 // Ensure that the constant occurs on the RHS. 2435 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2436 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2437 return SDValue(); 2438 return getSetCC(dl, VT, N2, N1, SwappedCond); 2439 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2440 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2441 // If an operand is known to be a nan (or undef that could be a nan), we can 2442 // fold it. 2443 // Choosing NaN for the undef will always make unordered comparison succeed 2444 // and ordered comparison fails. 2445 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2446 switch (ISD::getUnorderedFlavor(Cond)) { 2447 default: 2448 llvm_unreachable("Unknown flavor!"); 2449 case 0: // Known false. 2450 return getBoolConstant(false, dl, VT, OpVT); 2451 case 1: // Known true. 2452 return getBoolConstant(true, dl, VT, OpVT); 2453 case 2: // Undefined. 2454 return getUNDEF(VT); 2455 } 2456 } 2457 2458 // Could not fold it. 2459 return SDValue(); 2460 } 2461 2462 /// See if the specified operand can be simplified with the knowledge that only 2463 /// the bits specified by DemandedBits are used. 2464 /// TODO: really we should be making this into the DAG equivalent of 2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2467 EVT VT = V.getValueType(); 2468 2469 if (VT.isScalableVector()) 2470 return SDValue(); 2471 2472 APInt DemandedElts = VT.isVector() 2473 ? APInt::getAllOnes(VT.getVectorNumElements()) 2474 : APInt(1, 1); 2475 return GetDemandedBits(V, DemandedBits, DemandedElts); 2476 } 2477 2478 /// See if the specified operand can be simplified with the knowledge that only 2479 /// the bits specified by DemandedBits are used in the elements specified by 2480 /// DemandedElts. 2481 /// TODO: really we should be making this into the DAG equivalent of 2482 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2483 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2484 const APInt &DemandedElts) { 2485 switch (V.getOpcode()) { 2486 default: 2487 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2488 *this); 2489 case ISD::Constant: { 2490 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2491 APInt NewVal = CVal & DemandedBits; 2492 if (NewVal != CVal) 2493 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2494 break; 2495 } 2496 case ISD::SRL: 2497 // Only look at single-use SRLs. 2498 if (!V.getNode()->hasOneUse()) 2499 break; 2500 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2501 // See if we can recursively simplify the LHS. 2502 unsigned Amt = RHSC->getZExtValue(); 2503 2504 // Watch out for shift count overflow though. 2505 if (Amt >= DemandedBits.getBitWidth()) 2506 break; 2507 APInt SrcDemandedBits = DemandedBits << Amt; 2508 if (SDValue SimplifyLHS = 2509 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2510 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2511 V.getOperand(1)); 2512 } 2513 break; 2514 } 2515 return SDValue(); 2516 } 2517 2518 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2519 /// use this predicate to simplify operations downstream. 2520 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2521 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2522 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2523 } 2524 2525 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2526 /// this predicate to simplify operations downstream. Mask is known to be zero 2527 /// for bits that V cannot have. 2528 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2529 unsigned Depth) const { 2530 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2531 } 2532 2533 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2534 /// DemandedElts. We use this predicate to simplify operations downstream. 2535 /// Mask is known to be zero for bits that V cannot have. 2536 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2537 const APInt &DemandedElts, 2538 unsigned Depth) const { 2539 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2540 } 2541 2542 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2543 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2544 unsigned Depth) const { 2545 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2546 } 2547 2548 /// isSplatValue - Return true if the vector V has the same value 2549 /// across all DemandedElts. For scalable vectors it does not make 2550 /// sense to specify which elements are demanded or undefined, therefore 2551 /// they are simply ignored. 2552 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2553 APInt &UndefElts, unsigned Depth) const { 2554 unsigned Opcode = V.getOpcode(); 2555 EVT VT = V.getValueType(); 2556 assert(VT.isVector() && "Vector type expected"); 2557 2558 if (!VT.isScalableVector() && !DemandedElts) 2559 return false; // No demanded elts, better to assume we don't know anything. 2560 2561 if (Depth >= MaxRecursionDepth) 2562 return false; // Limit search depth. 2563 2564 // Deal with some common cases here that work for both fixed and scalable 2565 // vector types. 2566 switch (Opcode) { 2567 case ISD::SPLAT_VECTOR: 2568 UndefElts = V.getOperand(0).isUndef() 2569 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2570 : APInt(DemandedElts.getBitWidth(), 0); 2571 return true; 2572 case ISD::ADD: 2573 case ISD::SUB: 2574 case ISD::AND: 2575 case ISD::XOR: 2576 case ISD::OR: { 2577 APInt UndefLHS, UndefRHS; 2578 SDValue LHS = V.getOperand(0); 2579 SDValue RHS = V.getOperand(1); 2580 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2581 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2582 UndefElts = UndefLHS | UndefRHS; 2583 return true; 2584 } 2585 return false; 2586 } 2587 case ISD::ABS: 2588 case ISD::TRUNCATE: 2589 case ISD::SIGN_EXTEND: 2590 case ISD::ZERO_EXTEND: 2591 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2592 default: 2593 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2594 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2595 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth); 2596 break; 2597 } 2598 2599 // We don't support other cases than those above for scalable vectors at 2600 // the moment. 2601 if (VT.isScalableVector()) 2602 return false; 2603 2604 unsigned NumElts = VT.getVectorNumElements(); 2605 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2606 UndefElts = APInt::getZero(NumElts); 2607 2608 switch (Opcode) { 2609 case ISD::BUILD_VECTOR: { 2610 SDValue Scl; 2611 for (unsigned i = 0; i != NumElts; ++i) { 2612 SDValue Op = V.getOperand(i); 2613 if (Op.isUndef()) { 2614 UndefElts.setBit(i); 2615 continue; 2616 } 2617 if (!DemandedElts[i]) 2618 continue; 2619 if (Scl && Scl != Op) 2620 return false; 2621 Scl = Op; 2622 } 2623 return true; 2624 } 2625 case ISD::VECTOR_SHUFFLE: { 2626 // Check if this is a shuffle node doing a splat or a shuffle of a splat. 2627 APInt DemandedLHS = APInt::getNullValue(NumElts); 2628 APInt DemandedRHS = APInt::getNullValue(NumElts); 2629 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2630 for (int i = 0; i != (int)NumElts; ++i) { 2631 int M = Mask[i]; 2632 if (M < 0) { 2633 UndefElts.setBit(i); 2634 continue; 2635 } 2636 if (!DemandedElts[i]) 2637 continue; 2638 if (M < (int)NumElts) 2639 DemandedLHS.setBit(M); 2640 else 2641 DemandedRHS.setBit(M - NumElts); 2642 } 2643 2644 // If we aren't demanding either op, assume there's no splat. 2645 // If we are demanding both ops, assume there's no splat. 2646 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) || 2647 (!DemandedLHS.isZero() && !DemandedRHS.isZero())) 2648 return false; 2649 2650 // See if the demanded elts of the source op is a splat or we only demand 2651 // one element, which should always be a splat. 2652 // TODO: Handle source ops splats with undefs. 2653 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) { 2654 APInt SrcUndefs; 2655 return (SrcElts.countPopulation() == 1) || 2656 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) && 2657 (SrcElts & SrcUndefs).isZero()); 2658 }; 2659 if (!DemandedLHS.isZero()) 2660 return CheckSplatSrc(V.getOperand(0), DemandedLHS); 2661 return CheckSplatSrc(V.getOperand(1), DemandedRHS); 2662 } 2663 case ISD::EXTRACT_SUBVECTOR: { 2664 // Offset the demanded elts by the subvector index. 2665 SDValue Src = V.getOperand(0); 2666 // We don't support scalable vectors at the moment. 2667 if (Src.getValueType().isScalableVector()) 2668 return false; 2669 uint64_t Idx = V.getConstantOperandVal(1); 2670 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2671 APInt UndefSrcElts; 2672 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 2673 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2674 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2675 return true; 2676 } 2677 break; 2678 } 2679 case ISD::ANY_EXTEND_VECTOR_INREG: 2680 case ISD::SIGN_EXTEND_VECTOR_INREG: 2681 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2682 // Widen the demanded elts by the src element count. 2683 SDValue Src = V.getOperand(0); 2684 // We don't support scalable vectors at the moment. 2685 if (Src.getValueType().isScalableVector()) 2686 return false; 2687 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2688 APInt UndefSrcElts; 2689 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts); 2690 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2691 UndefElts = UndefSrcElts.trunc(NumElts); 2692 return true; 2693 } 2694 break; 2695 } 2696 case ISD::BITCAST: { 2697 SDValue Src = V.getOperand(0); 2698 EVT SrcVT = Src.getValueType(); 2699 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits(); 2700 unsigned BitWidth = VT.getScalarSizeInBits(); 2701 2702 // Ignore bitcasts from unsupported types. 2703 // TODO: Add fp support? 2704 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger()) 2705 break; 2706 2707 // Bitcast 'small element' vector to 'large element' vector. 2708 if ((BitWidth % SrcBitWidth) == 0) { 2709 // See if each sub element is a splat. 2710 unsigned Scale = BitWidth / SrcBitWidth; 2711 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 2712 APInt ScaledDemandedElts = 2713 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts); 2714 for (unsigned I = 0; I != Scale; ++I) { 2715 APInt SubUndefElts; 2716 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I); 2717 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt); 2718 SubDemandedElts &= ScaledDemandedElts; 2719 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1)) 2720 return false; 2721 // TODO: Add support for merging sub undef elements. 2722 if (SubDemandedElts.isSubsetOf(SubUndefElts)) 2723 return false; 2724 } 2725 return true; 2726 } 2727 break; 2728 } 2729 } 2730 2731 return false; 2732 } 2733 2734 /// Helper wrapper to main isSplatValue function. 2735 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2736 EVT VT = V.getValueType(); 2737 assert(VT.isVector() && "Vector type expected"); 2738 2739 APInt UndefElts; 2740 APInt DemandedElts; 2741 2742 // For now we don't support this with scalable vectors. 2743 if (!VT.isScalableVector()) 2744 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2745 return isSplatValue(V, DemandedElts, UndefElts) && 2746 (AllowUndefs || !UndefElts); 2747 } 2748 2749 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2750 V = peekThroughExtractSubvectors(V); 2751 2752 EVT VT = V.getValueType(); 2753 unsigned Opcode = V.getOpcode(); 2754 switch (Opcode) { 2755 default: { 2756 APInt UndefElts; 2757 APInt DemandedElts; 2758 2759 if (!VT.isScalableVector()) 2760 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2761 2762 if (isSplatValue(V, DemandedElts, UndefElts)) { 2763 if (VT.isScalableVector()) { 2764 // DemandedElts and UndefElts are ignored for scalable vectors, since 2765 // the only supported cases are SPLAT_VECTOR nodes. 2766 SplatIdx = 0; 2767 } else { 2768 // Handle case where all demanded elements are UNDEF. 2769 if (DemandedElts.isSubsetOf(UndefElts)) { 2770 SplatIdx = 0; 2771 return getUNDEF(VT); 2772 } 2773 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2774 } 2775 return V; 2776 } 2777 break; 2778 } 2779 case ISD::SPLAT_VECTOR: 2780 SplatIdx = 0; 2781 return V; 2782 case ISD::VECTOR_SHUFFLE: { 2783 if (VT.isScalableVector()) 2784 return SDValue(); 2785 2786 // Check if this is a shuffle node doing a splat. 2787 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2788 // getTargetVShiftNode currently struggles without the splat source. 2789 auto *SVN = cast<ShuffleVectorSDNode>(V); 2790 if (!SVN->isSplat()) 2791 break; 2792 int Idx = SVN->getSplatIndex(); 2793 int NumElts = V.getValueType().getVectorNumElements(); 2794 SplatIdx = Idx % NumElts; 2795 return V.getOperand(Idx / NumElts); 2796 } 2797 } 2798 2799 return SDValue(); 2800 } 2801 2802 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2803 int SplatIdx; 2804 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2805 EVT SVT = SrcVector.getValueType().getScalarType(); 2806 EVT LegalSVT = SVT; 2807 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2808 if (!SVT.isInteger()) 2809 return SDValue(); 2810 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2811 if (LegalSVT.bitsLT(SVT)) 2812 return SDValue(); 2813 } 2814 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2815 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2816 } 2817 return SDValue(); 2818 } 2819 2820 const APInt * 2821 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2822 const APInt &DemandedElts) const { 2823 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2824 V.getOpcode() == ISD::SRA) && 2825 "Unknown shift node"); 2826 unsigned BitWidth = V.getScalarValueSizeInBits(); 2827 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2828 // Shifting more than the bitwidth is not valid. 2829 const APInt &ShAmt = SA->getAPIntValue(); 2830 if (ShAmt.ult(BitWidth)) 2831 return &ShAmt; 2832 } 2833 return nullptr; 2834 } 2835 2836 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2837 SDValue V, const APInt &DemandedElts) const { 2838 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2839 V.getOpcode() == ISD::SRA) && 2840 "Unknown shift node"); 2841 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2842 return ValidAmt; 2843 unsigned BitWidth = V.getScalarValueSizeInBits(); 2844 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2845 if (!BV) 2846 return nullptr; 2847 const APInt *MinShAmt = nullptr; 2848 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2849 if (!DemandedElts[i]) 2850 continue; 2851 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2852 if (!SA) 2853 return nullptr; 2854 // Shifting more than the bitwidth is not valid. 2855 const APInt &ShAmt = SA->getAPIntValue(); 2856 if (ShAmt.uge(BitWidth)) 2857 return nullptr; 2858 if (MinShAmt && MinShAmt->ule(ShAmt)) 2859 continue; 2860 MinShAmt = &ShAmt; 2861 } 2862 return MinShAmt; 2863 } 2864 2865 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2866 SDValue V, const APInt &DemandedElts) const { 2867 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2868 V.getOpcode() == ISD::SRA) && 2869 "Unknown shift node"); 2870 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2871 return ValidAmt; 2872 unsigned BitWidth = V.getScalarValueSizeInBits(); 2873 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2874 if (!BV) 2875 return nullptr; 2876 const APInt *MaxShAmt = nullptr; 2877 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2878 if (!DemandedElts[i]) 2879 continue; 2880 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2881 if (!SA) 2882 return nullptr; 2883 // Shifting more than the bitwidth is not valid. 2884 const APInt &ShAmt = SA->getAPIntValue(); 2885 if (ShAmt.uge(BitWidth)) 2886 return nullptr; 2887 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2888 continue; 2889 MaxShAmt = &ShAmt; 2890 } 2891 return MaxShAmt; 2892 } 2893 2894 /// Determine which bits of Op are known to be either zero or one and return 2895 /// them in Known. For vectors, the known bits are those that are shared by 2896 /// every vector element. 2897 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2898 EVT VT = Op.getValueType(); 2899 2900 // TOOD: Until we have a plan for how to represent demanded elements for 2901 // scalable vectors, we can just bail out for now. 2902 if (Op.getValueType().isScalableVector()) { 2903 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2904 return KnownBits(BitWidth); 2905 } 2906 2907 APInt DemandedElts = VT.isVector() 2908 ? APInt::getAllOnes(VT.getVectorNumElements()) 2909 : APInt(1, 1); 2910 return computeKnownBits(Op, DemandedElts, Depth); 2911 } 2912 2913 /// Determine which bits of Op are known to be either zero or one and return 2914 /// them in Known. The DemandedElts argument allows us to only collect the known 2915 /// bits that are shared by the requested vector elements. 2916 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2917 unsigned Depth) const { 2918 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2919 2920 KnownBits Known(BitWidth); // Don't know anything. 2921 2922 // TOOD: Until we have a plan for how to represent demanded elements for 2923 // scalable vectors, we can just bail out for now. 2924 if (Op.getValueType().isScalableVector()) 2925 return Known; 2926 2927 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2928 // We know all of the bits for a constant! 2929 return KnownBits::makeConstant(C->getAPIntValue()); 2930 } 2931 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2932 // We know all of the bits for a constant fp! 2933 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2934 } 2935 2936 if (Depth >= MaxRecursionDepth) 2937 return Known; // Limit search depth. 2938 2939 KnownBits Known2; 2940 unsigned NumElts = DemandedElts.getBitWidth(); 2941 assert((!Op.getValueType().isVector() || 2942 NumElts == Op.getValueType().getVectorNumElements()) && 2943 "Unexpected vector size"); 2944 2945 if (!DemandedElts) 2946 return Known; // No demanded elts, better to assume we don't know anything. 2947 2948 unsigned Opcode = Op.getOpcode(); 2949 switch (Opcode) { 2950 case ISD::BUILD_VECTOR: 2951 // Collect the known bits that are shared by every demanded vector element. 2952 Known.Zero.setAllBits(); Known.One.setAllBits(); 2953 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2954 if (!DemandedElts[i]) 2955 continue; 2956 2957 SDValue SrcOp = Op.getOperand(i); 2958 Known2 = computeKnownBits(SrcOp, Depth + 1); 2959 2960 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2961 if (SrcOp.getValueSizeInBits() != BitWidth) { 2962 assert(SrcOp.getValueSizeInBits() > BitWidth && 2963 "Expected BUILD_VECTOR implicit truncation"); 2964 Known2 = Known2.trunc(BitWidth); 2965 } 2966 2967 // Known bits are the values that are shared by every demanded element. 2968 Known = KnownBits::commonBits(Known, Known2); 2969 2970 // If we don't know any bits, early out. 2971 if (Known.isUnknown()) 2972 break; 2973 } 2974 break; 2975 case ISD::VECTOR_SHUFFLE: { 2976 // Collect the known bits that are shared by every vector element referenced 2977 // by the shuffle. 2978 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2979 Known.Zero.setAllBits(); Known.One.setAllBits(); 2980 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2981 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2982 for (unsigned i = 0; i != NumElts; ++i) { 2983 if (!DemandedElts[i]) 2984 continue; 2985 2986 int M = SVN->getMaskElt(i); 2987 if (M < 0) { 2988 // For UNDEF elements, we don't know anything about the common state of 2989 // the shuffle result. 2990 Known.resetAll(); 2991 DemandedLHS.clearAllBits(); 2992 DemandedRHS.clearAllBits(); 2993 break; 2994 } 2995 2996 if ((unsigned)M < NumElts) 2997 DemandedLHS.setBit((unsigned)M % NumElts); 2998 else 2999 DemandedRHS.setBit((unsigned)M % NumElts); 3000 } 3001 // Known bits are the values that are shared by every demanded element. 3002 if (!!DemandedLHS) { 3003 SDValue LHS = Op.getOperand(0); 3004 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 3005 Known = KnownBits::commonBits(Known, Known2); 3006 } 3007 // If we don't know any bits, early out. 3008 if (Known.isUnknown()) 3009 break; 3010 if (!!DemandedRHS) { 3011 SDValue RHS = Op.getOperand(1); 3012 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 3013 Known = KnownBits::commonBits(Known, Known2); 3014 } 3015 break; 3016 } 3017 case ISD::CONCAT_VECTORS: { 3018 // Split DemandedElts and test each of the demanded subvectors. 3019 Known.Zero.setAllBits(); Known.One.setAllBits(); 3020 EVT SubVectorVT = Op.getOperand(0).getValueType(); 3021 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 3022 unsigned NumSubVectors = Op.getNumOperands(); 3023 for (unsigned i = 0; i != NumSubVectors; ++i) { 3024 APInt DemandedSub = 3025 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 3026 if (!!DemandedSub) { 3027 SDValue Sub = Op.getOperand(i); 3028 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 3029 Known = KnownBits::commonBits(Known, Known2); 3030 } 3031 // If we don't know any bits, early out. 3032 if (Known.isUnknown()) 3033 break; 3034 } 3035 break; 3036 } 3037 case ISD::INSERT_SUBVECTOR: { 3038 // Demand any elements from the subvector and the remainder from the src its 3039 // inserted into. 3040 SDValue Src = Op.getOperand(0); 3041 SDValue Sub = Op.getOperand(1); 3042 uint64_t Idx = Op.getConstantOperandVal(2); 3043 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 3044 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 3045 APInt DemandedSrcElts = DemandedElts; 3046 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 3047 3048 Known.One.setAllBits(); 3049 Known.Zero.setAllBits(); 3050 if (!!DemandedSubElts) { 3051 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 3052 if (Known.isUnknown()) 3053 break; // early-out. 3054 } 3055 if (!!DemandedSrcElts) { 3056 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3057 Known = KnownBits::commonBits(Known, Known2); 3058 } 3059 break; 3060 } 3061 case ISD::EXTRACT_SUBVECTOR: { 3062 // Offset the demanded elts by the subvector index. 3063 SDValue Src = Op.getOperand(0); 3064 // Bail until we can represent demanded elements for scalable vectors. 3065 if (Src.getValueType().isScalableVector()) 3066 break; 3067 uint64_t Idx = Op.getConstantOperandVal(1); 3068 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 3069 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 3070 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 3071 break; 3072 } 3073 case ISD::SCALAR_TO_VECTOR: { 3074 // We know about scalar_to_vector as much as we know about it source, 3075 // which becomes the first element of otherwise unknown vector. 3076 if (DemandedElts != 1) 3077 break; 3078 3079 SDValue N0 = Op.getOperand(0); 3080 Known = computeKnownBits(N0, Depth + 1); 3081 if (N0.getValueSizeInBits() != BitWidth) 3082 Known = Known.trunc(BitWidth); 3083 3084 break; 3085 } 3086 case ISD::BITCAST: { 3087 SDValue N0 = Op.getOperand(0); 3088 EVT SubVT = N0.getValueType(); 3089 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3090 3091 // Ignore bitcasts from unsupported types. 3092 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3093 break; 3094 3095 // Fast handling of 'identity' bitcasts. 3096 if (BitWidth == SubBitWidth) { 3097 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3098 break; 3099 } 3100 3101 bool IsLE = getDataLayout().isLittleEndian(); 3102 3103 // Bitcast 'small element' vector to 'large element' scalar/vector. 3104 if ((BitWidth % SubBitWidth) == 0) { 3105 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3106 3107 // Collect known bits for the (larger) output by collecting the known 3108 // bits from each set of sub elements and shift these into place. 3109 // We need to separately call computeKnownBits for each set of 3110 // sub elements as the knownbits for each is likely to be different. 3111 unsigned SubScale = BitWidth / SubBitWidth; 3112 APInt SubDemandedElts(NumElts * SubScale, 0); 3113 for (unsigned i = 0; i != NumElts; ++i) 3114 if (DemandedElts[i]) 3115 SubDemandedElts.setBit(i * SubScale); 3116 3117 for (unsigned i = 0; i != SubScale; ++i) { 3118 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3119 Depth + 1); 3120 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3121 Known.insertBits(Known2, SubBitWidth * Shifts); 3122 } 3123 } 3124 3125 // Bitcast 'large element' scalar/vector to 'small element' vector. 3126 if ((SubBitWidth % BitWidth) == 0) { 3127 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3128 3129 // Collect known bits for the (smaller) output by collecting the known 3130 // bits from the overlapping larger input elements and extracting the 3131 // sub sections we actually care about. 3132 unsigned SubScale = SubBitWidth / BitWidth; 3133 APInt SubDemandedElts = 3134 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3135 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3136 3137 Known.Zero.setAllBits(); Known.One.setAllBits(); 3138 for (unsigned i = 0; i != NumElts; ++i) 3139 if (DemandedElts[i]) { 3140 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3141 unsigned Offset = (Shifts % SubScale) * BitWidth; 3142 Known = KnownBits::commonBits(Known, 3143 Known2.extractBits(BitWidth, Offset)); 3144 // If we don't know any bits, early out. 3145 if (Known.isUnknown()) 3146 break; 3147 } 3148 } 3149 break; 3150 } 3151 case ISD::AND: 3152 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3153 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3154 3155 Known &= Known2; 3156 break; 3157 case ISD::OR: 3158 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3159 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3160 3161 Known |= Known2; 3162 break; 3163 case ISD::XOR: 3164 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3165 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3166 3167 Known ^= Known2; 3168 break; 3169 case ISD::MUL: { 3170 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3171 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3172 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3173 // TODO: SelfMultiply can be poison, but not undef. 3174 if (SelfMultiply) 3175 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3176 Op.getOperand(0), DemandedElts, false, Depth + 1); 3177 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3178 break; 3179 } 3180 case ISD::MULHU: { 3181 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3182 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3183 Known = KnownBits::mulhu(Known, Known2); 3184 break; 3185 } 3186 case ISD::MULHS: { 3187 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3188 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3189 Known = KnownBits::mulhs(Known, Known2); 3190 break; 3191 } 3192 case ISD::UMUL_LOHI: { 3193 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3194 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3195 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3196 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3197 if (Op.getResNo() == 0) 3198 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3199 else 3200 Known = KnownBits::mulhu(Known, Known2); 3201 break; 3202 } 3203 case ISD::SMUL_LOHI: { 3204 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3205 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3206 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3207 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3208 if (Op.getResNo() == 0) 3209 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3210 else 3211 Known = KnownBits::mulhs(Known, Known2); 3212 break; 3213 } 3214 case ISD::UDIV: { 3215 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3216 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3217 Known = KnownBits::udiv(Known, Known2); 3218 break; 3219 } 3220 case ISD::AVGCEILU: { 3221 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3222 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3223 Known = Known.zext(BitWidth + 1); 3224 Known2 = Known2.zext(BitWidth + 1); 3225 KnownBits One = KnownBits::makeConstant(APInt(1, 1)); 3226 Known = KnownBits::computeForAddCarry(Known, Known2, One); 3227 Known = Known.extractBits(BitWidth, 1); 3228 break; 3229 } 3230 case ISD::SELECT: 3231 case ISD::VSELECT: 3232 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3233 // If we don't know any bits, early out. 3234 if (Known.isUnknown()) 3235 break; 3236 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3237 3238 // Only known if known in both the LHS and RHS. 3239 Known = KnownBits::commonBits(Known, Known2); 3240 break; 3241 case ISD::SELECT_CC: 3242 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3243 // If we don't know any bits, early out. 3244 if (Known.isUnknown()) 3245 break; 3246 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3247 3248 // Only known if known in both the LHS and RHS. 3249 Known = KnownBits::commonBits(Known, Known2); 3250 break; 3251 case ISD::SMULO: 3252 case ISD::UMULO: 3253 if (Op.getResNo() != 1) 3254 break; 3255 // The boolean result conforms to getBooleanContents. 3256 // If we know the result of a setcc has the top bits zero, use this info. 3257 // We know that we have an integer-based boolean since these operations 3258 // are only available for integer. 3259 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3260 TargetLowering::ZeroOrOneBooleanContent && 3261 BitWidth > 1) 3262 Known.Zero.setBitsFrom(1); 3263 break; 3264 case ISD::SETCC: 3265 case ISD::STRICT_FSETCC: 3266 case ISD::STRICT_FSETCCS: { 3267 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3268 // If we know the result of a setcc has the top bits zero, use this info. 3269 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3270 TargetLowering::ZeroOrOneBooleanContent && 3271 BitWidth > 1) 3272 Known.Zero.setBitsFrom(1); 3273 break; 3274 } 3275 case ISD::SHL: 3276 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3277 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3278 Known = KnownBits::shl(Known, Known2); 3279 3280 // Minimum shift low bits are known zero. 3281 if (const APInt *ShMinAmt = 3282 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3283 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3284 break; 3285 case ISD::SRL: 3286 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3287 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3288 Known = KnownBits::lshr(Known, Known2); 3289 3290 // Minimum shift high bits are known zero. 3291 if (const APInt *ShMinAmt = 3292 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3293 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3294 break; 3295 case ISD::SRA: 3296 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3297 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3298 Known = KnownBits::ashr(Known, Known2); 3299 // TODO: Add minimum shift high known sign bits. 3300 break; 3301 case ISD::FSHL: 3302 case ISD::FSHR: 3303 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3304 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3305 3306 // For fshl, 0-shift returns the 1st arg. 3307 // For fshr, 0-shift returns the 2nd arg. 3308 if (Amt == 0) { 3309 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3310 DemandedElts, Depth + 1); 3311 break; 3312 } 3313 3314 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3315 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3316 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3317 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3318 if (Opcode == ISD::FSHL) { 3319 Known.One <<= Amt; 3320 Known.Zero <<= Amt; 3321 Known2.One.lshrInPlace(BitWidth - Amt); 3322 Known2.Zero.lshrInPlace(BitWidth - Amt); 3323 } else { 3324 Known.One <<= BitWidth - Amt; 3325 Known.Zero <<= BitWidth - Amt; 3326 Known2.One.lshrInPlace(Amt); 3327 Known2.Zero.lshrInPlace(Amt); 3328 } 3329 Known.One |= Known2.One; 3330 Known.Zero |= Known2.Zero; 3331 } 3332 break; 3333 case ISD::SIGN_EXTEND_INREG: { 3334 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3335 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3336 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3337 break; 3338 } 3339 case ISD::CTTZ: 3340 case ISD::CTTZ_ZERO_UNDEF: { 3341 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3342 // If we have a known 1, its position is our upper bound. 3343 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3344 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3345 Known.Zero.setBitsFrom(LowBits); 3346 break; 3347 } 3348 case ISD::CTLZ: 3349 case ISD::CTLZ_ZERO_UNDEF: { 3350 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3351 // If we have a known 1, its position is our upper bound. 3352 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3353 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3354 Known.Zero.setBitsFrom(LowBits); 3355 break; 3356 } 3357 case ISD::CTPOP: { 3358 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3359 // If we know some of the bits are zero, they can't be one. 3360 unsigned PossibleOnes = Known2.countMaxPopulation(); 3361 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3362 break; 3363 } 3364 case ISD::PARITY: { 3365 // Parity returns 0 everywhere but the LSB. 3366 Known.Zero.setBitsFrom(1); 3367 break; 3368 } 3369 case ISD::LOAD: { 3370 LoadSDNode *LD = cast<LoadSDNode>(Op); 3371 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3372 if (ISD::isNON_EXTLoad(LD) && Cst) { 3373 // Determine any common known bits from the loaded constant pool value. 3374 Type *CstTy = Cst->getType(); 3375 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3376 // If its a vector splat, then we can (quickly) reuse the scalar path. 3377 // NOTE: We assume all elements match and none are UNDEF. 3378 if (CstTy->isVectorTy()) { 3379 if (const Constant *Splat = Cst->getSplatValue()) { 3380 Cst = Splat; 3381 CstTy = Cst->getType(); 3382 } 3383 } 3384 // TODO - do we need to handle different bitwidths? 3385 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3386 // Iterate across all vector elements finding common known bits. 3387 Known.One.setAllBits(); 3388 Known.Zero.setAllBits(); 3389 for (unsigned i = 0; i != NumElts; ++i) { 3390 if (!DemandedElts[i]) 3391 continue; 3392 if (Constant *Elt = Cst->getAggregateElement(i)) { 3393 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3394 const APInt &Value = CInt->getValue(); 3395 Known.One &= Value; 3396 Known.Zero &= ~Value; 3397 continue; 3398 } 3399 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3400 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3401 Known.One &= Value; 3402 Known.Zero &= ~Value; 3403 continue; 3404 } 3405 } 3406 Known.One.clearAllBits(); 3407 Known.Zero.clearAllBits(); 3408 break; 3409 } 3410 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3411 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3412 Known = KnownBits::makeConstant(CInt->getValue()); 3413 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3414 Known = 3415 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3416 } 3417 } 3418 } 3419 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3420 // If this is a ZEXTLoad and we are looking at the loaded value. 3421 EVT VT = LD->getMemoryVT(); 3422 unsigned MemBits = VT.getScalarSizeInBits(); 3423 Known.Zero.setBitsFrom(MemBits); 3424 } else if (const MDNode *Ranges = LD->getRanges()) { 3425 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3426 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3427 } 3428 break; 3429 } 3430 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3431 EVT InVT = Op.getOperand(0).getValueType(); 3432 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3433 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3434 Known = Known.zext(BitWidth); 3435 break; 3436 } 3437 case ISD::ZERO_EXTEND: { 3438 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3439 Known = Known.zext(BitWidth); 3440 break; 3441 } 3442 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3443 EVT InVT = Op.getOperand(0).getValueType(); 3444 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3445 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3446 // If the sign bit is known to be zero or one, then sext will extend 3447 // it to the top bits, else it will just zext. 3448 Known = Known.sext(BitWidth); 3449 break; 3450 } 3451 case ISD::SIGN_EXTEND: { 3452 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3453 // If the sign bit is known to be zero or one, then sext will extend 3454 // it to the top bits, else it will just zext. 3455 Known = Known.sext(BitWidth); 3456 break; 3457 } 3458 case ISD::ANY_EXTEND_VECTOR_INREG: { 3459 EVT InVT = Op.getOperand(0).getValueType(); 3460 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements()); 3461 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3462 Known = Known.anyext(BitWidth); 3463 break; 3464 } 3465 case ISD::ANY_EXTEND: { 3466 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3467 Known = Known.anyext(BitWidth); 3468 break; 3469 } 3470 case ISD::TRUNCATE: { 3471 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3472 Known = Known.trunc(BitWidth); 3473 break; 3474 } 3475 case ISD::AssertZext: { 3476 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3477 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3478 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3479 Known.Zero |= (~InMask); 3480 Known.One &= (~Known.Zero); 3481 break; 3482 } 3483 case ISD::AssertAlign: { 3484 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3485 assert(LogOfAlign != 0); 3486 3487 // TODO: Should use maximum with source 3488 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3489 // well as clearing one bits. 3490 Known.Zero.setLowBits(LogOfAlign); 3491 Known.One.clearLowBits(LogOfAlign); 3492 break; 3493 } 3494 case ISD::FGETSIGN: 3495 // All bits are zero except the low bit. 3496 Known.Zero.setBitsFrom(1); 3497 break; 3498 case ISD::USUBO: 3499 case ISD::SSUBO: 3500 if (Op.getResNo() == 1) { 3501 // If we know the result of a setcc has the top bits zero, use this info. 3502 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3503 TargetLowering::ZeroOrOneBooleanContent && 3504 BitWidth > 1) 3505 Known.Zero.setBitsFrom(1); 3506 break; 3507 } 3508 LLVM_FALLTHROUGH; 3509 case ISD::SUB: 3510 case ISD::SUBC: { 3511 assert(Op.getResNo() == 0 && 3512 "We only compute knownbits for the difference here."); 3513 3514 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3515 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3516 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3517 Known, Known2); 3518 break; 3519 } 3520 case ISD::UADDO: 3521 case ISD::SADDO: 3522 case ISD::ADDCARRY: 3523 if (Op.getResNo() == 1) { 3524 // If we know the result of a setcc has the top bits zero, use this info. 3525 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3526 TargetLowering::ZeroOrOneBooleanContent && 3527 BitWidth > 1) 3528 Known.Zero.setBitsFrom(1); 3529 break; 3530 } 3531 LLVM_FALLTHROUGH; 3532 case ISD::ADD: 3533 case ISD::ADDC: 3534 case ISD::ADDE: { 3535 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3536 3537 // With ADDE and ADDCARRY, a carry bit may be added in. 3538 KnownBits Carry(1); 3539 if (Opcode == ISD::ADDE) 3540 // Can't track carry from glue, set carry to unknown. 3541 Carry.resetAll(); 3542 else if (Opcode == ISD::ADDCARRY) 3543 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3544 // the trouble (how often will we find a known carry bit). And I haven't 3545 // tested this very much yet, but something like this might work: 3546 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3547 // Carry = Carry.zextOrTrunc(1, false); 3548 Carry.resetAll(); 3549 else 3550 Carry.setAllZero(); 3551 3552 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3553 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3554 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3555 break; 3556 } 3557 case ISD::SREM: { 3558 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3559 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3560 Known = KnownBits::srem(Known, Known2); 3561 break; 3562 } 3563 case ISD::UREM: { 3564 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3565 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3566 Known = KnownBits::urem(Known, Known2); 3567 break; 3568 } 3569 case ISD::EXTRACT_ELEMENT: { 3570 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3571 const unsigned Index = Op.getConstantOperandVal(1); 3572 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3573 3574 // Remove low part of known bits mask 3575 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3576 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3577 3578 // Remove high part of known bit mask 3579 Known = Known.trunc(EltBitWidth); 3580 break; 3581 } 3582 case ISD::EXTRACT_VECTOR_ELT: { 3583 SDValue InVec = Op.getOperand(0); 3584 SDValue EltNo = Op.getOperand(1); 3585 EVT VecVT = InVec.getValueType(); 3586 // computeKnownBits not yet implemented for scalable vectors. 3587 if (VecVT.isScalableVector()) 3588 break; 3589 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3590 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3591 3592 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3593 // anything about the extended bits. 3594 if (BitWidth > EltBitWidth) 3595 Known = Known.trunc(EltBitWidth); 3596 3597 // If we know the element index, just demand that vector element, else for 3598 // an unknown element index, ignore DemandedElts and demand them all. 3599 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3600 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3601 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3602 DemandedSrcElts = 3603 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3604 3605 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3606 if (BitWidth > EltBitWidth) 3607 Known = Known.anyext(BitWidth); 3608 break; 3609 } 3610 case ISD::INSERT_VECTOR_ELT: { 3611 // If we know the element index, split the demand between the 3612 // source vector and the inserted element, otherwise assume we need 3613 // the original demanded vector elements and the value. 3614 SDValue InVec = Op.getOperand(0); 3615 SDValue InVal = Op.getOperand(1); 3616 SDValue EltNo = Op.getOperand(2); 3617 bool DemandedVal = true; 3618 APInt DemandedVecElts = DemandedElts; 3619 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3620 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3621 unsigned EltIdx = CEltNo->getZExtValue(); 3622 DemandedVal = !!DemandedElts[EltIdx]; 3623 DemandedVecElts.clearBit(EltIdx); 3624 } 3625 Known.One.setAllBits(); 3626 Known.Zero.setAllBits(); 3627 if (DemandedVal) { 3628 Known2 = computeKnownBits(InVal, Depth + 1); 3629 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3630 } 3631 if (!!DemandedVecElts) { 3632 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3633 Known = KnownBits::commonBits(Known, Known2); 3634 } 3635 break; 3636 } 3637 case ISD::BITREVERSE: { 3638 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3639 Known = Known2.reverseBits(); 3640 break; 3641 } 3642 case ISD::BSWAP: { 3643 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3644 Known = Known2.byteSwap(); 3645 break; 3646 } 3647 case ISD::ABS: { 3648 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3649 Known = Known2.abs(); 3650 break; 3651 } 3652 case ISD::USUBSAT: { 3653 // The result of usubsat will never be larger than the LHS. 3654 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3655 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3656 break; 3657 } 3658 case ISD::UMIN: { 3659 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3660 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3661 Known = KnownBits::umin(Known, Known2); 3662 break; 3663 } 3664 case ISD::UMAX: { 3665 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3666 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3667 Known = KnownBits::umax(Known, Known2); 3668 break; 3669 } 3670 case ISD::SMIN: 3671 case ISD::SMAX: { 3672 // If we have a clamp pattern, we know that the number of sign bits will be 3673 // the minimum of the clamp min/max range. 3674 bool IsMax = (Opcode == ISD::SMAX); 3675 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3676 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3677 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3678 CstHigh = 3679 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3680 if (CstLow && CstHigh) { 3681 if (!IsMax) 3682 std::swap(CstLow, CstHigh); 3683 3684 const APInt &ValueLow = CstLow->getAPIntValue(); 3685 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3686 if (ValueLow.sle(ValueHigh)) { 3687 unsigned LowSignBits = ValueLow.getNumSignBits(); 3688 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3689 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3690 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3691 Known.One.setHighBits(MinSignBits); 3692 break; 3693 } 3694 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3695 Known.Zero.setHighBits(MinSignBits); 3696 break; 3697 } 3698 } 3699 } 3700 3701 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3702 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3703 if (IsMax) 3704 Known = KnownBits::smax(Known, Known2); 3705 else 3706 Known = KnownBits::smin(Known, Known2); 3707 3708 // For SMAX, if CstLow is non-negative we know the result will be 3709 // non-negative and thus all sign bits are 0. 3710 // TODO: There's an equivalent of this for smin with negative constant for 3711 // known ones. 3712 if (IsMax && CstLow) { 3713 const APInt &ValueLow = CstLow->getAPIntValue(); 3714 if (ValueLow.isNonNegative()) { 3715 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3716 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits())); 3717 } 3718 } 3719 3720 break; 3721 } 3722 case ISD::FP_TO_UINT_SAT: { 3723 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3724 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3725 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3726 break; 3727 } 3728 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3729 if (Op.getResNo() == 1) { 3730 // The boolean result conforms to getBooleanContents. 3731 // If we know the result of a setcc has the top bits zero, use this info. 3732 // We know that we have an integer-based boolean since these operations 3733 // are only available for integer. 3734 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3735 TargetLowering::ZeroOrOneBooleanContent && 3736 BitWidth > 1) 3737 Known.Zero.setBitsFrom(1); 3738 break; 3739 } 3740 LLVM_FALLTHROUGH; 3741 case ISD::ATOMIC_CMP_SWAP: 3742 case ISD::ATOMIC_SWAP: 3743 case ISD::ATOMIC_LOAD_ADD: 3744 case ISD::ATOMIC_LOAD_SUB: 3745 case ISD::ATOMIC_LOAD_AND: 3746 case ISD::ATOMIC_LOAD_CLR: 3747 case ISD::ATOMIC_LOAD_OR: 3748 case ISD::ATOMIC_LOAD_XOR: 3749 case ISD::ATOMIC_LOAD_NAND: 3750 case ISD::ATOMIC_LOAD_MIN: 3751 case ISD::ATOMIC_LOAD_MAX: 3752 case ISD::ATOMIC_LOAD_UMIN: 3753 case ISD::ATOMIC_LOAD_UMAX: 3754 case ISD::ATOMIC_LOAD: { 3755 unsigned MemBits = 3756 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3757 // If we are looking at the loaded value. 3758 if (Op.getResNo() == 0) { 3759 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3760 Known.Zero.setBitsFrom(MemBits); 3761 } 3762 break; 3763 } 3764 case ISD::FrameIndex: 3765 case ISD::TargetFrameIndex: 3766 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3767 Known, getMachineFunction()); 3768 break; 3769 3770 default: 3771 if (Opcode < ISD::BUILTIN_OP_END) 3772 break; 3773 LLVM_FALLTHROUGH; 3774 case ISD::INTRINSIC_WO_CHAIN: 3775 case ISD::INTRINSIC_W_CHAIN: 3776 case ISD::INTRINSIC_VOID: 3777 // Allow the target to implement this method for its nodes. 3778 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3779 break; 3780 } 3781 3782 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3783 return Known; 3784 } 3785 3786 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3787 SDValue N1) const { 3788 // X + 0 never overflow 3789 if (isNullConstant(N1)) 3790 return OFK_Never; 3791 3792 KnownBits N1Known = computeKnownBits(N1); 3793 if (N1Known.Zero.getBoolValue()) { 3794 KnownBits N0Known = computeKnownBits(N0); 3795 3796 bool overflow; 3797 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3798 if (!overflow) 3799 return OFK_Never; 3800 } 3801 3802 // mulhi + 1 never overflow 3803 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3804 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3805 return OFK_Never; 3806 3807 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3808 KnownBits N0Known = computeKnownBits(N0); 3809 3810 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3811 return OFK_Never; 3812 } 3813 3814 return OFK_Sometime; 3815 } 3816 3817 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3818 EVT OpVT = Val.getValueType(); 3819 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3820 3821 // Is the constant a known power of 2? 3822 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3823 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3824 3825 // A left-shift of a constant one will have exactly one bit set because 3826 // shifting the bit off the end is undefined. 3827 if (Val.getOpcode() == ISD::SHL) { 3828 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3829 if (C && C->getAPIntValue() == 1) 3830 return true; 3831 } 3832 3833 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3834 // one bit set. 3835 if (Val.getOpcode() == ISD::SRL) { 3836 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3837 if (C && C->getAPIntValue().isSignMask()) 3838 return true; 3839 } 3840 3841 // Are all operands of a build vector constant powers of two? 3842 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3843 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3844 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3845 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3846 return false; 3847 })) 3848 return true; 3849 3850 // Is the operand of a splat vector a constant power of two? 3851 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3853 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3854 return true; 3855 3856 // More could be done here, though the above checks are enough 3857 // to handle some common cases. 3858 3859 // Fall back to computeKnownBits to catch other known cases. 3860 KnownBits Known = computeKnownBits(Val); 3861 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3862 } 3863 3864 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3865 EVT VT = Op.getValueType(); 3866 3867 // TODO: Assume we don't know anything for now. 3868 if (VT.isScalableVector()) 3869 return 1; 3870 3871 APInt DemandedElts = VT.isVector() 3872 ? APInt::getAllOnes(VT.getVectorNumElements()) 3873 : APInt(1, 1); 3874 return ComputeNumSignBits(Op, DemandedElts, Depth); 3875 } 3876 3877 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3878 unsigned Depth) const { 3879 EVT VT = Op.getValueType(); 3880 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3881 unsigned VTBits = VT.getScalarSizeInBits(); 3882 unsigned NumElts = DemandedElts.getBitWidth(); 3883 unsigned Tmp, Tmp2; 3884 unsigned FirstAnswer = 1; 3885 3886 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3887 const APInt &Val = C->getAPIntValue(); 3888 return Val.getNumSignBits(); 3889 } 3890 3891 if (Depth >= MaxRecursionDepth) 3892 return 1; // Limit search depth. 3893 3894 if (!DemandedElts || VT.isScalableVector()) 3895 return 1; // No demanded elts, better to assume we don't know anything. 3896 3897 unsigned Opcode = Op.getOpcode(); 3898 switch (Opcode) { 3899 default: break; 3900 case ISD::AssertSext: 3901 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3902 return VTBits-Tmp+1; 3903 case ISD::AssertZext: 3904 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3905 return VTBits-Tmp; 3906 3907 case ISD::BUILD_VECTOR: 3908 Tmp = VTBits; 3909 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3910 if (!DemandedElts[i]) 3911 continue; 3912 3913 SDValue SrcOp = Op.getOperand(i); 3914 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3915 3916 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3917 if (SrcOp.getValueSizeInBits() != VTBits) { 3918 assert(SrcOp.getValueSizeInBits() > VTBits && 3919 "Expected BUILD_VECTOR implicit truncation"); 3920 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3921 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3922 } 3923 Tmp = std::min(Tmp, Tmp2); 3924 } 3925 return Tmp; 3926 3927 case ISD::VECTOR_SHUFFLE: { 3928 // Collect the minimum number of sign bits that are shared by every vector 3929 // element referenced by the shuffle. 3930 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3931 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3932 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3933 for (unsigned i = 0; i != NumElts; ++i) { 3934 int M = SVN->getMaskElt(i); 3935 if (!DemandedElts[i]) 3936 continue; 3937 // For UNDEF elements, we don't know anything about the common state of 3938 // the shuffle result. 3939 if (M < 0) 3940 return 1; 3941 if ((unsigned)M < NumElts) 3942 DemandedLHS.setBit((unsigned)M % NumElts); 3943 else 3944 DemandedRHS.setBit((unsigned)M % NumElts); 3945 } 3946 Tmp = std::numeric_limits<unsigned>::max(); 3947 if (!!DemandedLHS) 3948 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3949 if (!!DemandedRHS) { 3950 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3951 Tmp = std::min(Tmp, Tmp2); 3952 } 3953 // If we don't know anything, early out and try computeKnownBits fall-back. 3954 if (Tmp == 1) 3955 break; 3956 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3957 return Tmp; 3958 } 3959 3960 case ISD::BITCAST: { 3961 SDValue N0 = Op.getOperand(0); 3962 EVT SrcVT = N0.getValueType(); 3963 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3964 3965 // Ignore bitcasts from unsupported types.. 3966 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3967 break; 3968 3969 // Fast handling of 'identity' bitcasts. 3970 if (VTBits == SrcBits) 3971 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3972 3973 bool IsLE = getDataLayout().isLittleEndian(); 3974 3975 // Bitcast 'large element' scalar/vector to 'small element' vector. 3976 if ((SrcBits % VTBits) == 0) { 3977 assert(VT.isVector() && "Expected bitcast to vector"); 3978 3979 unsigned Scale = SrcBits / VTBits; 3980 APInt SrcDemandedElts = 3981 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3982 3983 // Fast case - sign splat can be simply split across the small elements. 3984 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3985 if (Tmp == SrcBits) 3986 return VTBits; 3987 3988 // Slow case - determine how far the sign extends into each sub-element. 3989 Tmp2 = VTBits; 3990 for (unsigned i = 0; i != NumElts; ++i) 3991 if (DemandedElts[i]) { 3992 unsigned SubOffset = i % Scale; 3993 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3994 SubOffset = SubOffset * VTBits; 3995 if (Tmp <= SubOffset) 3996 return 1; 3997 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3998 } 3999 return Tmp2; 4000 } 4001 break; 4002 } 4003 4004 case ISD::FP_TO_SINT_SAT: 4005 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 4006 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4007 return VTBits - Tmp + 1; 4008 case ISD::SIGN_EXTEND: 4009 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 4010 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 4011 case ISD::SIGN_EXTEND_INREG: 4012 // Max of the input and what this extends. 4013 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 4014 Tmp = VTBits-Tmp+1; 4015 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4016 return std::max(Tmp, Tmp2); 4017 case ISD::SIGN_EXTEND_VECTOR_INREG: { 4018 SDValue Src = Op.getOperand(0); 4019 EVT SrcVT = Src.getValueType(); 4020 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements()); 4021 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 4022 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 4023 } 4024 case ISD::SRA: 4025 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4026 // SRA X, C -> adds C sign bits. 4027 if (const APInt *ShAmt = 4028 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 4029 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 4030 return Tmp; 4031 case ISD::SHL: 4032 if (const APInt *ShAmt = 4033 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 4034 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 4035 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4036 if (ShAmt->ult(Tmp)) 4037 return Tmp - ShAmt->getZExtValue(); 4038 } 4039 break; 4040 case ISD::AND: 4041 case ISD::OR: 4042 case ISD::XOR: // NOT is handled here. 4043 // Logical binary ops preserve the number of sign bits at the worst. 4044 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 4045 if (Tmp != 1) { 4046 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4047 FirstAnswer = std::min(Tmp, Tmp2); 4048 // We computed what we know about the sign bits as our first 4049 // answer. Now proceed to the generic code that uses 4050 // computeKnownBits, and pick whichever answer is better. 4051 } 4052 break; 4053 4054 case ISD::SELECT: 4055 case ISD::VSELECT: 4056 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 4057 if (Tmp == 1) return 1; // Early out. 4058 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4059 return std::min(Tmp, Tmp2); 4060 case ISD::SELECT_CC: 4061 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 4062 if (Tmp == 1) return 1; // Early out. 4063 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 4064 return std::min(Tmp, Tmp2); 4065 4066 case ISD::SMIN: 4067 case ISD::SMAX: { 4068 // If we have a clamp pattern, we know that the number of sign bits will be 4069 // the minimum of the clamp min/max range. 4070 bool IsMax = (Opcode == ISD::SMAX); 4071 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 4072 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 4073 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 4074 CstHigh = 4075 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 4076 if (CstLow && CstHigh) { 4077 if (!IsMax) 4078 std::swap(CstLow, CstHigh); 4079 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 4080 Tmp = CstLow->getAPIntValue().getNumSignBits(); 4081 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 4082 return std::min(Tmp, Tmp2); 4083 } 4084 } 4085 4086 // Fallback - just get the minimum number of sign bits of the operands. 4087 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4088 if (Tmp == 1) 4089 return 1; // Early out. 4090 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4091 return std::min(Tmp, Tmp2); 4092 } 4093 case ISD::UMIN: 4094 case ISD::UMAX: 4095 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4096 if (Tmp == 1) 4097 return 1; // Early out. 4098 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4099 return std::min(Tmp, Tmp2); 4100 case ISD::SADDO: 4101 case ISD::UADDO: 4102 case ISD::SSUBO: 4103 case ISD::USUBO: 4104 case ISD::SMULO: 4105 case ISD::UMULO: 4106 if (Op.getResNo() != 1) 4107 break; 4108 // The boolean result conforms to getBooleanContents. Fall through. 4109 // If setcc returns 0/-1, all bits are sign bits. 4110 // We know that we have an integer-based boolean since these operations 4111 // are only available for integer. 4112 if (TLI->getBooleanContents(VT.isVector(), false) == 4113 TargetLowering::ZeroOrNegativeOneBooleanContent) 4114 return VTBits; 4115 break; 4116 case ISD::SETCC: 4117 case ISD::STRICT_FSETCC: 4118 case ISD::STRICT_FSETCCS: { 4119 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4120 // If setcc returns 0/-1, all bits are sign bits. 4121 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4122 TargetLowering::ZeroOrNegativeOneBooleanContent) 4123 return VTBits; 4124 break; 4125 } 4126 case ISD::ROTL: 4127 case ISD::ROTR: 4128 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4129 4130 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4131 if (Tmp == VTBits) 4132 return VTBits; 4133 4134 if (ConstantSDNode *C = 4135 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4136 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4137 4138 // Handle rotate right by N like a rotate left by 32-N. 4139 if (Opcode == ISD::ROTR) 4140 RotAmt = (VTBits - RotAmt) % VTBits; 4141 4142 // If we aren't rotating out all of the known-in sign bits, return the 4143 // number that are left. This handles rotl(sext(x), 1) for example. 4144 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4145 } 4146 break; 4147 case ISD::ADD: 4148 case ISD::ADDC: 4149 // Add can have at most one carry bit. Thus we know that the output 4150 // is, at worst, one more bit than the inputs. 4151 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4152 if (Tmp == 1) return 1; // Early out. 4153 4154 // Special case decrementing a value (ADD X, -1): 4155 if (ConstantSDNode *CRHS = 4156 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4157 if (CRHS->isAllOnes()) { 4158 KnownBits Known = 4159 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4160 4161 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4162 // sign bits set. 4163 if ((Known.Zero | 1).isAllOnes()) 4164 return VTBits; 4165 4166 // If we are subtracting one from a positive number, there is no carry 4167 // out of the result. 4168 if (Known.isNonNegative()) 4169 return Tmp; 4170 } 4171 4172 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4173 if (Tmp2 == 1) return 1; // Early out. 4174 return std::min(Tmp, Tmp2) - 1; 4175 case ISD::SUB: 4176 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4177 if (Tmp2 == 1) return 1; // Early out. 4178 4179 // Handle NEG. 4180 if (ConstantSDNode *CLHS = 4181 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4182 if (CLHS->isZero()) { 4183 KnownBits Known = 4184 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4185 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4186 // sign bits set. 4187 if ((Known.Zero | 1).isAllOnes()) 4188 return VTBits; 4189 4190 // If the input is known to be positive (the sign bit is known clear), 4191 // the output of the NEG has the same number of sign bits as the input. 4192 if (Known.isNonNegative()) 4193 return Tmp2; 4194 4195 // Otherwise, we treat this like a SUB. 4196 } 4197 4198 // Sub can have at most one carry bit. Thus we know that the output 4199 // is, at worst, one more bit than the inputs. 4200 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4201 if (Tmp == 1) return 1; // Early out. 4202 return std::min(Tmp, Tmp2) - 1; 4203 case ISD::MUL: { 4204 // The output of the Mul can be at most twice the valid bits in the inputs. 4205 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4206 if (SignBitsOp0 == 1) 4207 break; 4208 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4209 if (SignBitsOp1 == 1) 4210 break; 4211 unsigned OutValidBits = 4212 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4213 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4214 } 4215 case ISD::SREM: 4216 // The sign bit is the LHS's sign bit, except when the result of the 4217 // remainder is zero. The magnitude of the result should be less than or 4218 // equal to the magnitude of the LHS. Therefore, the result should have 4219 // at least as many sign bits as the left hand side. 4220 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4221 case ISD::TRUNCATE: { 4222 // Check if the sign bits of source go down as far as the truncated value. 4223 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4224 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4225 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4226 return NumSrcSignBits - (NumSrcBits - VTBits); 4227 break; 4228 } 4229 case ISD::EXTRACT_ELEMENT: { 4230 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4231 const int BitWidth = Op.getValueSizeInBits(); 4232 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4233 4234 // Get reverse index (starting from 1), Op1 value indexes elements from 4235 // little end. Sign starts at big end. 4236 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4237 4238 // If the sign portion ends in our element the subtraction gives correct 4239 // result. Otherwise it gives either negative or > bitwidth result 4240 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4241 } 4242 case ISD::INSERT_VECTOR_ELT: { 4243 // If we know the element index, split the demand between the 4244 // source vector and the inserted element, otherwise assume we need 4245 // the original demanded vector elements and the value. 4246 SDValue InVec = Op.getOperand(0); 4247 SDValue InVal = Op.getOperand(1); 4248 SDValue EltNo = Op.getOperand(2); 4249 bool DemandedVal = true; 4250 APInt DemandedVecElts = DemandedElts; 4251 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4252 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4253 unsigned EltIdx = CEltNo->getZExtValue(); 4254 DemandedVal = !!DemandedElts[EltIdx]; 4255 DemandedVecElts.clearBit(EltIdx); 4256 } 4257 Tmp = std::numeric_limits<unsigned>::max(); 4258 if (DemandedVal) { 4259 // TODO - handle implicit truncation of inserted elements. 4260 if (InVal.getScalarValueSizeInBits() != VTBits) 4261 break; 4262 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4263 Tmp = std::min(Tmp, Tmp2); 4264 } 4265 if (!!DemandedVecElts) { 4266 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4267 Tmp = std::min(Tmp, Tmp2); 4268 } 4269 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4270 return Tmp; 4271 } 4272 case ISD::EXTRACT_VECTOR_ELT: { 4273 SDValue InVec = Op.getOperand(0); 4274 SDValue EltNo = Op.getOperand(1); 4275 EVT VecVT = InVec.getValueType(); 4276 // ComputeNumSignBits not yet implemented for scalable vectors. 4277 if (VecVT.isScalableVector()) 4278 break; 4279 const unsigned BitWidth = Op.getValueSizeInBits(); 4280 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4281 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4282 4283 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4284 // anything about sign bits. But if the sizes match we can derive knowledge 4285 // about sign bits from the vector operand. 4286 if (BitWidth != EltBitWidth) 4287 break; 4288 4289 // If we know the element index, just demand that vector element, else for 4290 // an unknown element index, ignore DemandedElts and demand them all. 4291 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4292 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4293 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4294 DemandedSrcElts = 4295 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4296 4297 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4298 } 4299 case ISD::EXTRACT_SUBVECTOR: { 4300 // Offset the demanded elts by the subvector index. 4301 SDValue Src = Op.getOperand(0); 4302 // Bail until we can represent demanded elements for scalable vectors. 4303 if (Src.getValueType().isScalableVector()) 4304 break; 4305 uint64_t Idx = Op.getConstantOperandVal(1); 4306 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4307 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx); 4308 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4309 } 4310 case ISD::CONCAT_VECTORS: { 4311 // Determine the minimum number of sign bits across all demanded 4312 // elts of the input vectors. Early out if the result is already 1. 4313 Tmp = std::numeric_limits<unsigned>::max(); 4314 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4315 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4316 unsigned NumSubVectors = Op.getNumOperands(); 4317 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4318 APInt DemandedSub = 4319 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4320 if (!DemandedSub) 4321 continue; 4322 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4323 Tmp = std::min(Tmp, Tmp2); 4324 } 4325 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4326 return Tmp; 4327 } 4328 case ISD::INSERT_SUBVECTOR: { 4329 // Demand any elements from the subvector and the remainder from the src its 4330 // inserted into. 4331 SDValue Src = Op.getOperand(0); 4332 SDValue Sub = Op.getOperand(1); 4333 uint64_t Idx = Op.getConstantOperandVal(2); 4334 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4335 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4336 APInt DemandedSrcElts = DemandedElts; 4337 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4338 4339 Tmp = std::numeric_limits<unsigned>::max(); 4340 if (!!DemandedSubElts) { 4341 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4342 if (Tmp == 1) 4343 return 1; // early-out 4344 } 4345 if (!!DemandedSrcElts) { 4346 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4347 Tmp = std::min(Tmp, Tmp2); 4348 } 4349 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4350 return Tmp; 4351 } 4352 case ISD::ATOMIC_CMP_SWAP: 4353 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4354 case ISD::ATOMIC_SWAP: 4355 case ISD::ATOMIC_LOAD_ADD: 4356 case ISD::ATOMIC_LOAD_SUB: 4357 case ISD::ATOMIC_LOAD_AND: 4358 case ISD::ATOMIC_LOAD_CLR: 4359 case ISD::ATOMIC_LOAD_OR: 4360 case ISD::ATOMIC_LOAD_XOR: 4361 case ISD::ATOMIC_LOAD_NAND: 4362 case ISD::ATOMIC_LOAD_MIN: 4363 case ISD::ATOMIC_LOAD_MAX: 4364 case ISD::ATOMIC_LOAD_UMIN: 4365 case ISD::ATOMIC_LOAD_UMAX: 4366 case ISD::ATOMIC_LOAD: { 4367 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4368 // If we are looking at the loaded value. 4369 if (Op.getResNo() == 0) { 4370 if (Tmp == VTBits) 4371 return 1; // early-out 4372 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4373 return VTBits - Tmp + 1; 4374 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4375 return VTBits - Tmp; 4376 } 4377 break; 4378 } 4379 } 4380 4381 // If we are looking at the loaded value of the SDNode. 4382 if (Op.getResNo() == 0) { 4383 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4384 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4385 unsigned ExtType = LD->getExtensionType(); 4386 switch (ExtType) { 4387 default: break; 4388 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4389 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4390 return VTBits - Tmp + 1; 4391 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4392 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4393 return VTBits - Tmp; 4394 case ISD::NON_EXTLOAD: 4395 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4396 // We only need to handle vectors - computeKnownBits should handle 4397 // scalar cases. 4398 Type *CstTy = Cst->getType(); 4399 if (CstTy->isVectorTy() && 4400 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4401 VTBits == CstTy->getScalarSizeInBits()) { 4402 Tmp = VTBits; 4403 for (unsigned i = 0; i != NumElts; ++i) { 4404 if (!DemandedElts[i]) 4405 continue; 4406 if (Constant *Elt = Cst->getAggregateElement(i)) { 4407 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4408 const APInt &Value = CInt->getValue(); 4409 Tmp = std::min(Tmp, Value.getNumSignBits()); 4410 continue; 4411 } 4412 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4413 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4414 Tmp = std::min(Tmp, Value.getNumSignBits()); 4415 continue; 4416 } 4417 } 4418 // Unknown type. Conservatively assume no bits match sign bit. 4419 return 1; 4420 } 4421 return Tmp; 4422 } 4423 } 4424 break; 4425 } 4426 } 4427 } 4428 4429 // Allow the target to implement this method for its nodes. 4430 if (Opcode >= ISD::BUILTIN_OP_END || 4431 Opcode == ISD::INTRINSIC_WO_CHAIN || 4432 Opcode == ISD::INTRINSIC_W_CHAIN || 4433 Opcode == ISD::INTRINSIC_VOID) { 4434 unsigned NumBits = 4435 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4436 if (NumBits > 1) 4437 FirstAnswer = std::max(FirstAnswer, NumBits); 4438 } 4439 4440 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4441 // use this information. 4442 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4443 return std::max(FirstAnswer, Known.countMinSignBits()); 4444 } 4445 4446 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4447 unsigned Depth) const { 4448 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4449 return Op.getScalarValueSizeInBits() - SignBits + 1; 4450 } 4451 4452 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4453 const APInt &DemandedElts, 4454 unsigned Depth) const { 4455 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4456 return Op.getScalarValueSizeInBits() - SignBits + 1; 4457 } 4458 4459 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4460 unsigned Depth) const { 4461 // Early out for FREEZE. 4462 if (Op.getOpcode() == ISD::FREEZE) 4463 return true; 4464 4465 // TODO: Assume we don't know anything for now. 4466 EVT VT = Op.getValueType(); 4467 if (VT.isScalableVector()) 4468 return false; 4469 4470 APInt DemandedElts = VT.isVector() 4471 ? APInt::getAllOnes(VT.getVectorNumElements()) 4472 : APInt(1, 1); 4473 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4474 } 4475 4476 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4477 const APInt &DemandedElts, 4478 bool PoisonOnly, 4479 unsigned Depth) const { 4480 unsigned Opcode = Op.getOpcode(); 4481 4482 // Early out for FREEZE. 4483 if (Opcode == ISD::FREEZE) 4484 return true; 4485 4486 if (Depth >= MaxRecursionDepth) 4487 return false; // Limit search depth. 4488 4489 if (isIntOrFPConstant(Op)) 4490 return true; 4491 4492 switch (Opcode) { 4493 case ISD::UNDEF: 4494 return PoisonOnly; 4495 4496 case ISD::BUILD_VECTOR: 4497 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4498 // this shouldn't affect the result. 4499 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4500 if (!DemandedElts[i]) 4501 continue; 4502 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4503 Depth + 1)) 4504 return false; 4505 } 4506 return true; 4507 4508 // TODO: Search for noundef attributes from library functions. 4509 4510 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4511 4512 default: 4513 // Allow the target to implement this method for its nodes. 4514 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4515 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4516 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4517 Op, DemandedElts, *this, PoisonOnly, Depth); 4518 break; 4519 } 4520 4521 return false; 4522 } 4523 4524 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4525 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4526 !isa<ConstantSDNode>(Op.getOperand(1))) 4527 return false; 4528 4529 if (Op.getOpcode() == ISD::OR && 4530 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4531 return false; 4532 4533 return true; 4534 } 4535 4536 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4537 // If we're told that NaNs won't happen, assume they won't. 4538 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4539 return true; 4540 4541 if (Depth >= MaxRecursionDepth) 4542 return false; // Limit search depth. 4543 4544 // TODO: Handle vectors. 4545 // If the value is a constant, we can obviously see if it is a NaN or not. 4546 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4547 return !C->getValueAPF().isNaN() || 4548 (SNaN && !C->getValueAPF().isSignaling()); 4549 } 4550 4551 unsigned Opcode = Op.getOpcode(); 4552 switch (Opcode) { 4553 case ISD::FADD: 4554 case ISD::FSUB: 4555 case ISD::FMUL: 4556 case ISD::FDIV: 4557 case ISD::FREM: 4558 case ISD::FSIN: 4559 case ISD::FCOS: { 4560 if (SNaN) 4561 return true; 4562 // TODO: Need isKnownNeverInfinity 4563 return false; 4564 } 4565 case ISD::FCANONICALIZE: 4566 case ISD::FEXP: 4567 case ISD::FEXP2: 4568 case ISD::FTRUNC: 4569 case ISD::FFLOOR: 4570 case ISD::FCEIL: 4571 case ISD::FROUND: 4572 case ISD::FROUNDEVEN: 4573 case ISD::FRINT: 4574 case ISD::FNEARBYINT: { 4575 if (SNaN) 4576 return true; 4577 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4578 } 4579 case ISD::FABS: 4580 case ISD::FNEG: 4581 case ISD::FCOPYSIGN: { 4582 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4583 } 4584 case ISD::SELECT: 4585 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4586 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4587 case ISD::FP_EXTEND: 4588 case ISD::FP_ROUND: { 4589 if (SNaN) 4590 return true; 4591 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4592 } 4593 case ISD::SINT_TO_FP: 4594 case ISD::UINT_TO_FP: 4595 return true; 4596 case ISD::FMA: 4597 case ISD::FMAD: { 4598 if (SNaN) 4599 return true; 4600 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4601 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4602 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4603 } 4604 case ISD::FSQRT: // Need is known positive 4605 case ISD::FLOG: 4606 case ISD::FLOG2: 4607 case ISD::FLOG10: 4608 case ISD::FPOWI: 4609 case ISD::FPOW: { 4610 if (SNaN) 4611 return true; 4612 // TODO: Refine on operand 4613 return false; 4614 } 4615 case ISD::FMINNUM: 4616 case ISD::FMAXNUM: { 4617 // Only one needs to be known not-nan, since it will be returned if the 4618 // other ends up being one. 4619 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4620 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4621 } 4622 case ISD::FMINNUM_IEEE: 4623 case ISD::FMAXNUM_IEEE: { 4624 if (SNaN) 4625 return true; 4626 // This can return a NaN if either operand is an sNaN, or if both operands 4627 // are NaN. 4628 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4629 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4630 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4631 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4632 } 4633 case ISD::FMINIMUM: 4634 case ISD::FMAXIMUM: { 4635 // TODO: Does this quiet or return the origina NaN as-is? 4636 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4637 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4638 } 4639 case ISD::EXTRACT_VECTOR_ELT: { 4640 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4641 } 4642 default: 4643 if (Opcode >= ISD::BUILTIN_OP_END || 4644 Opcode == ISD::INTRINSIC_WO_CHAIN || 4645 Opcode == ISD::INTRINSIC_W_CHAIN || 4646 Opcode == ISD::INTRINSIC_VOID) { 4647 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4648 } 4649 4650 return false; 4651 } 4652 } 4653 4654 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4655 assert(Op.getValueType().isFloatingPoint() && 4656 "Floating point type expected"); 4657 4658 // If the value is a constant, we can obviously see if it is a zero or not. 4659 // TODO: Add BuildVector support. 4660 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4661 return !C->isZero(); 4662 return false; 4663 } 4664 4665 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4666 assert(!Op.getValueType().isFloatingPoint() && 4667 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4668 4669 // If the value is a constant, we can obviously see if it is a zero or not. 4670 if (ISD::matchUnaryPredicate(Op, 4671 [](ConstantSDNode *C) { return !C->isZero(); })) 4672 return true; 4673 4674 // TODO: Recognize more cases here. 4675 switch (Op.getOpcode()) { 4676 default: break; 4677 case ISD::OR: 4678 if (isKnownNeverZero(Op.getOperand(1)) || 4679 isKnownNeverZero(Op.getOperand(0))) 4680 return true; 4681 break; 4682 } 4683 4684 return false; 4685 } 4686 4687 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4688 // Check the obvious case. 4689 if (A == B) return true; 4690 4691 // For for negative and positive zero. 4692 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4693 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4694 if (CA->isZero() && CB->isZero()) return true; 4695 4696 // Otherwise they may not be equal. 4697 return false; 4698 } 4699 4700 // Only bits set in Mask must be negated, other bits may be arbitrary. 4701 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) { 4702 if (isBitwiseNot(V, AllowUndefs)) 4703 return V.getOperand(0); 4704 4705 // Handle any_extend (not (truncate X)) pattern, where Mask only sets 4706 // bits in the non-extended part. 4707 ConstantSDNode *MaskC = isConstOrConstSplat(Mask); 4708 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND) 4709 return SDValue(); 4710 SDValue ExtArg = V.getOperand(0); 4711 if (ExtArg.getScalarValueSizeInBits() >= 4712 MaskC->getAPIntValue().getActiveBits() && 4713 isBitwiseNot(ExtArg, AllowUndefs) && 4714 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE && 4715 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType()) 4716 return ExtArg.getOperand(0).getOperand(0); 4717 return SDValue(); 4718 } 4719 4720 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) { 4721 // Match masked merge pattern (X & ~M) op (Y & M) 4722 // Including degenerate case (X & ~M) op M 4723 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask, 4724 SDValue Other) { 4725 if (SDValue NotOperand = 4726 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) { 4727 if (Other == NotOperand) 4728 return true; 4729 if (Other->getOpcode() == ISD::AND) 4730 return NotOperand == Other->getOperand(0) || 4731 NotOperand == Other->getOperand(1); 4732 } 4733 return false; 4734 }; 4735 if (A->getOpcode() == ISD::AND) 4736 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) || 4737 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B); 4738 return false; 4739 } 4740 4741 // FIXME: unify with llvm::haveNoCommonBitsSet. 4742 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4743 assert(A.getValueType() == B.getValueType() && 4744 "Values must have the same type"); 4745 if (haveNoCommonBitsSetCommutative(A, B) || 4746 haveNoCommonBitsSetCommutative(B, A)) 4747 return true; 4748 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4749 computeKnownBits(B)); 4750 } 4751 4752 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4753 SelectionDAG &DAG) { 4754 if (cast<ConstantSDNode>(Step)->isZero()) 4755 return DAG.getConstant(0, DL, VT); 4756 4757 return SDValue(); 4758 } 4759 4760 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4761 ArrayRef<SDValue> Ops, 4762 SelectionDAG &DAG) { 4763 int NumOps = Ops.size(); 4764 assert(NumOps != 0 && "Can't build an empty vector!"); 4765 assert(!VT.isScalableVector() && 4766 "BUILD_VECTOR cannot be used with scalable types"); 4767 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4768 "Incorrect element count in BUILD_VECTOR!"); 4769 4770 // BUILD_VECTOR of UNDEFs is UNDEF. 4771 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4772 return DAG.getUNDEF(VT); 4773 4774 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4775 SDValue IdentitySrc; 4776 bool IsIdentity = true; 4777 for (int i = 0; i != NumOps; ++i) { 4778 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4779 Ops[i].getOperand(0).getValueType() != VT || 4780 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4781 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4782 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4783 IsIdentity = false; 4784 break; 4785 } 4786 IdentitySrc = Ops[i].getOperand(0); 4787 } 4788 if (IsIdentity) 4789 return IdentitySrc; 4790 4791 return SDValue(); 4792 } 4793 4794 /// Try to simplify vector concatenation to an input value, undef, or build 4795 /// vector. 4796 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4797 ArrayRef<SDValue> Ops, 4798 SelectionDAG &DAG) { 4799 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4800 assert(llvm::all_of(Ops, 4801 [Ops](SDValue Op) { 4802 return Ops[0].getValueType() == Op.getValueType(); 4803 }) && 4804 "Concatenation of vectors with inconsistent value types!"); 4805 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4806 VT.getVectorElementCount() && 4807 "Incorrect element count in vector concatenation!"); 4808 4809 if (Ops.size() == 1) 4810 return Ops[0]; 4811 4812 // Concat of UNDEFs is UNDEF. 4813 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4814 return DAG.getUNDEF(VT); 4815 4816 // Scan the operands and look for extract operations from a single source 4817 // that correspond to insertion at the same location via this concatenation: 4818 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4819 SDValue IdentitySrc; 4820 bool IsIdentity = true; 4821 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4822 SDValue Op = Ops[i]; 4823 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4824 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4825 Op.getOperand(0).getValueType() != VT || 4826 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4827 Op.getConstantOperandVal(1) != IdentityIndex) { 4828 IsIdentity = false; 4829 break; 4830 } 4831 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4832 "Unexpected identity source vector for concat of extracts"); 4833 IdentitySrc = Op.getOperand(0); 4834 } 4835 if (IsIdentity) { 4836 assert(IdentitySrc && "Failed to set source vector of extracts"); 4837 return IdentitySrc; 4838 } 4839 4840 // The code below this point is only designed to work for fixed width 4841 // vectors, so we bail out for now. 4842 if (VT.isScalableVector()) 4843 return SDValue(); 4844 4845 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4846 // simplified to one big BUILD_VECTOR. 4847 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4848 EVT SVT = VT.getScalarType(); 4849 SmallVector<SDValue, 16> Elts; 4850 for (SDValue Op : Ops) { 4851 EVT OpVT = Op.getValueType(); 4852 if (Op.isUndef()) 4853 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4854 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4855 Elts.append(Op->op_begin(), Op->op_end()); 4856 else 4857 return SDValue(); 4858 } 4859 4860 // BUILD_VECTOR requires all inputs to be of the same type, find the 4861 // maximum type and extend them all. 4862 for (SDValue Op : Elts) 4863 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4864 4865 if (SVT.bitsGT(VT.getScalarType())) { 4866 for (SDValue &Op : Elts) { 4867 if (Op.isUndef()) 4868 Op = DAG.getUNDEF(SVT); 4869 else 4870 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4871 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4872 : DAG.getSExtOrTrunc(Op, DL, SVT); 4873 } 4874 } 4875 4876 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4877 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4878 return V; 4879 } 4880 4881 /// Gets or creates the specified node. 4882 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4883 FoldingSetNodeID ID; 4884 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4885 void *IP = nullptr; 4886 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4887 return SDValue(E, 0); 4888 4889 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4890 getVTList(VT)); 4891 CSEMap.InsertNode(N, IP); 4892 4893 InsertNode(N); 4894 SDValue V = SDValue(N, 0); 4895 NewSDValueDbgMsg(V, "Creating new node: ", this); 4896 return V; 4897 } 4898 4899 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4900 SDValue Operand) { 4901 SDNodeFlags Flags; 4902 if (Inserter) 4903 Flags = Inserter->getFlags(); 4904 return getNode(Opcode, DL, VT, Operand, Flags); 4905 } 4906 4907 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4908 SDValue Operand, const SDNodeFlags Flags) { 4909 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4910 "Operand is DELETED_NODE!"); 4911 // Constant fold unary operations with an integer constant operand. Even 4912 // opaque constant will be folded, because the folding of unary operations 4913 // doesn't create new constants with different values. Nevertheless, the 4914 // opaque flag is preserved during folding to prevent future folding with 4915 // other constants. 4916 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4917 const APInt &Val = C->getAPIntValue(); 4918 switch (Opcode) { 4919 default: break; 4920 case ISD::SIGN_EXTEND: 4921 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4922 C->isTargetOpcode(), C->isOpaque()); 4923 case ISD::TRUNCATE: 4924 if (C->isOpaque()) 4925 break; 4926 LLVM_FALLTHROUGH; 4927 case ISD::ZERO_EXTEND: 4928 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4929 C->isTargetOpcode(), C->isOpaque()); 4930 case ISD::ANY_EXTEND: 4931 // Some targets like RISCV prefer to sign extend some types. 4932 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4933 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4934 C->isTargetOpcode(), C->isOpaque()); 4935 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4936 C->isTargetOpcode(), C->isOpaque()); 4937 case ISD::UINT_TO_FP: 4938 case ISD::SINT_TO_FP: { 4939 APFloat apf(EVTToAPFloatSemantics(VT), 4940 APInt::getZero(VT.getSizeInBits())); 4941 (void)apf.convertFromAPInt(Val, 4942 Opcode==ISD::SINT_TO_FP, 4943 APFloat::rmNearestTiesToEven); 4944 return getConstantFP(apf, DL, VT); 4945 } 4946 case ISD::BITCAST: 4947 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4948 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4949 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4950 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4951 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4952 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4953 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4954 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4955 break; 4956 case ISD::ABS: 4957 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4958 C->isOpaque()); 4959 case ISD::BITREVERSE: 4960 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4961 C->isOpaque()); 4962 case ISD::BSWAP: 4963 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4964 C->isOpaque()); 4965 case ISD::CTPOP: 4966 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4967 C->isOpaque()); 4968 case ISD::CTLZ: 4969 case ISD::CTLZ_ZERO_UNDEF: 4970 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4971 C->isOpaque()); 4972 case ISD::CTTZ: 4973 case ISD::CTTZ_ZERO_UNDEF: 4974 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4975 C->isOpaque()); 4976 case ISD::FP16_TO_FP: { 4977 bool Ignored; 4978 APFloat FPV(APFloat::IEEEhalf(), 4979 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4980 4981 // This can return overflow, underflow, or inexact; we don't care. 4982 // FIXME need to be more flexible about rounding mode. 4983 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4984 APFloat::rmNearestTiesToEven, &Ignored); 4985 return getConstantFP(FPV, DL, VT); 4986 } 4987 case ISD::STEP_VECTOR: { 4988 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4989 return V; 4990 break; 4991 } 4992 } 4993 } 4994 4995 // Constant fold unary operations with a floating point constant operand. 4996 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4997 APFloat V = C->getValueAPF(); // make copy 4998 switch (Opcode) { 4999 case ISD::FNEG: 5000 V.changeSign(); 5001 return getConstantFP(V, DL, VT); 5002 case ISD::FABS: 5003 V.clearSign(); 5004 return getConstantFP(V, DL, VT); 5005 case ISD::FCEIL: { 5006 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 5007 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5008 return getConstantFP(V, DL, VT); 5009 break; 5010 } 5011 case ISD::FTRUNC: { 5012 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 5013 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5014 return getConstantFP(V, DL, VT); 5015 break; 5016 } 5017 case ISD::FFLOOR: { 5018 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 5019 if (fs == APFloat::opOK || fs == APFloat::opInexact) 5020 return getConstantFP(V, DL, VT); 5021 break; 5022 } 5023 case ISD::FP_EXTEND: { 5024 bool ignored; 5025 // This can return overflow, underflow, or inexact; we don't care. 5026 // FIXME need to be more flexible about rounding mode. 5027 (void)V.convert(EVTToAPFloatSemantics(VT), 5028 APFloat::rmNearestTiesToEven, &ignored); 5029 return getConstantFP(V, DL, VT); 5030 } 5031 case ISD::FP_TO_SINT: 5032 case ISD::FP_TO_UINT: { 5033 bool ignored; 5034 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 5035 // FIXME need to be more flexible about rounding mode. 5036 APFloat::opStatus s = 5037 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 5038 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 5039 break; 5040 return getConstant(IntVal, DL, VT); 5041 } 5042 case ISD::BITCAST: 5043 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 5044 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5045 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 5046 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5047 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 5048 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 5049 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 5050 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5051 break; 5052 case ISD::FP_TO_FP16: { 5053 bool Ignored; 5054 // This can return overflow, underflow, or inexact; we don't care. 5055 // FIXME need to be more flexible about rounding mode. 5056 (void)V.convert(APFloat::IEEEhalf(), 5057 APFloat::rmNearestTiesToEven, &Ignored); 5058 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 5059 } 5060 } 5061 } 5062 5063 // Constant fold unary operations with a vector integer or float operand. 5064 switch (Opcode) { 5065 default: 5066 // FIXME: Entirely reasonable to perform folding of other unary 5067 // operations here as the need arises. 5068 break; 5069 case ISD::FNEG: 5070 case ISD::FABS: 5071 case ISD::FCEIL: 5072 case ISD::FTRUNC: 5073 case ISD::FFLOOR: 5074 case ISD::FP_EXTEND: 5075 case ISD::FP_TO_SINT: 5076 case ISD::FP_TO_UINT: 5077 case ISD::TRUNCATE: 5078 case ISD::ANY_EXTEND: 5079 case ISD::ZERO_EXTEND: 5080 case ISD::SIGN_EXTEND: 5081 case ISD::UINT_TO_FP: 5082 case ISD::SINT_TO_FP: 5083 case ISD::ABS: 5084 case ISD::BITREVERSE: 5085 case ISD::BSWAP: 5086 case ISD::CTLZ: 5087 case ISD::CTLZ_ZERO_UNDEF: 5088 case ISD::CTTZ: 5089 case ISD::CTTZ_ZERO_UNDEF: 5090 case ISD::CTPOP: { 5091 SDValue Ops = {Operand}; 5092 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 5093 return Fold; 5094 } 5095 } 5096 5097 unsigned OpOpcode = Operand.getNode()->getOpcode(); 5098 switch (Opcode) { 5099 case ISD::STEP_VECTOR: 5100 assert(VT.isScalableVector() && 5101 "STEP_VECTOR can only be used with scalable types"); 5102 assert(OpOpcode == ISD::TargetConstant && 5103 VT.getVectorElementType() == Operand.getValueType() && 5104 "Unexpected step operand"); 5105 break; 5106 case ISD::FREEZE: 5107 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5108 if (isGuaranteedNotToBeUndefOrPoison(Operand)) 5109 return Operand; 5110 break; 5111 case ISD::TokenFactor: 5112 case ISD::MERGE_VALUES: 5113 case ISD::CONCAT_VECTORS: 5114 return Operand; // Factor, merge or concat of one node? No need. 5115 case ISD::BUILD_VECTOR: { 5116 // Attempt to simplify BUILD_VECTOR. 5117 SDValue Ops[] = {Operand}; 5118 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5119 return V; 5120 break; 5121 } 5122 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 5123 case ISD::FP_EXTEND: 5124 assert(VT.isFloatingPoint() && 5125 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 5126 if (Operand.getValueType() == VT) return Operand; // noop conversion. 5127 assert((!VT.isVector() || 5128 VT.getVectorElementCount() == 5129 Operand.getValueType().getVectorElementCount()) && 5130 "Vector element count mismatch!"); 5131 assert(Operand.getValueType().bitsLT(VT) && 5132 "Invalid fpext node, dst < src!"); 5133 if (Operand.isUndef()) 5134 return getUNDEF(VT); 5135 break; 5136 case ISD::FP_TO_SINT: 5137 case ISD::FP_TO_UINT: 5138 if (Operand.isUndef()) 5139 return getUNDEF(VT); 5140 break; 5141 case ISD::SINT_TO_FP: 5142 case ISD::UINT_TO_FP: 5143 // [us]itofp(undef) = 0, because the result value is bounded. 5144 if (Operand.isUndef()) 5145 return getConstantFP(0.0, DL, VT); 5146 break; 5147 case ISD::SIGN_EXTEND: 5148 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5149 "Invalid SIGN_EXTEND!"); 5150 assert(VT.isVector() == Operand.getValueType().isVector() && 5151 "SIGN_EXTEND result type type should be vector iff the operand " 5152 "type is vector!"); 5153 if (Operand.getValueType() == VT) return Operand; // noop extension 5154 assert((!VT.isVector() || 5155 VT.getVectorElementCount() == 5156 Operand.getValueType().getVectorElementCount()) && 5157 "Vector element count mismatch!"); 5158 assert(Operand.getValueType().bitsLT(VT) && 5159 "Invalid sext node, dst < src!"); 5160 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5161 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5162 if (OpOpcode == ISD::UNDEF) 5163 // sext(undef) = 0, because the top bits will all be the same. 5164 return getConstant(0, DL, VT); 5165 break; 5166 case ISD::ZERO_EXTEND: 5167 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5168 "Invalid ZERO_EXTEND!"); 5169 assert(VT.isVector() == Operand.getValueType().isVector() && 5170 "ZERO_EXTEND result type type should be vector iff the operand " 5171 "type is vector!"); 5172 if (Operand.getValueType() == VT) return Operand; // noop extension 5173 assert((!VT.isVector() || 5174 VT.getVectorElementCount() == 5175 Operand.getValueType().getVectorElementCount()) && 5176 "Vector element count mismatch!"); 5177 assert(Operand.getValueType().bitsLT(VT) && 5178 "Invalid zext node, dst < src!"); 5179 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5180 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5181 if (OpOpcode == ISD::UNDEF) 5182 // zext(undef) = 0, because the top bits will be zero. 5183 return getConstant(0, DL, VT); 5184 break; 5185 case ISD::ANY_EXTEND: 5186 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5187 "Invalid ANY_EXTEND!"); 5188 assert(VT.isVector() == Operand.getValueType().isVector() && 5189 "ANY_EXTEND result type type should be vector iff the operand " 5190 "type is vector!"); 5191 if (Operand.getValueType() == VT) return Operand; // noop extension 5192 assert((!VT.isVector() || 5193 VT.getVectorElementCount() == 5194 Operand.getValueType().getVectorElementCount()) && 5195 "Vector element count mismatch!"); 5196 assert(Operand.getValueType().bitsLT(VT) && 5197 "Invalid anyext node, dst < src!"); 5198 5199 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5200 OpOpcode == ISD::ANY_EXTEND) 5201 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5202 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5203 if (OpOpcode == ISD::UNDEF) 5204 return getUNDEF(VT); 5205 5206 // (ext (trunc x)) -> x 5207 if (OpOpcode == ISD::TRUNCATE) { 5208 SDValue OpOp = Operand.getOperand(0); 5209 if (OpOp.getValueType() == VT) { 5210 transferDbgValues(Operand, OpOp); 5211 return OpOp; 5212 } 5213 } 5214 break; 5215 case ISD::TRUNCATE: 5216 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5217 "Invalid TRUNCATE!"); 5218 assert(VT.isVector() == Operand.getValueType().isVector() && 5219 "TRUNCATE result type type should be vector iff the operand " 5220 "type is vector!"); 5221 if (Operand.getValueType() == VT) return Operand; // noop truncate 5222 assert((!VT.isVector() || 5223 VT.getVectorElementCount() == 5224 Operand.getValueType().getVectorElementCount()) && 5225 "Vector element count mismatch!"); 5226 assert(Operand.getValueType().bitsGT(VT) && 5227 "Invalid truncate node, src < dst!"); 5228 if (OpOpcode == ISD::TRUNCATE) 5229 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5230 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5231 OpOpcode == ISD::ANY_EXTEND) { 5232 // If the source is smaller than the dest, we still need an extend. 5233 if (Operand.getOperand(0).getValueType().getScalarType() 5234 .bitsLT(VT.getScalarType())) 5235 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5236 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5237 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5238 return Operand.getOperand(0); 5239 } 5240 if (OpOpcode == ISD::UNDEF) 5241 return getUNDEF(VT); 5242 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5243 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5244 break; 5245 case ISD::ANY_EXTEND_VECTOR_INREG: 5246 case ISD::ZERO_EXTEND_VECTOR_INREG: 5247 case ISD::SIGN_EXTEND_VECTOR_INREG: 5248 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5249 assert(Operand.getValueType().bitsLE(VT) && 5250 "The input must be the same size or smaller than the result."); 5251 assert(VT.getVectorMinNumElements() < 5252 Operand.getValueType().getVectorMinNumElements() && 5253 "The destination vector type must have fewer lanes than the input."); 5254 break; 5255 case ISD::ABS: 5256 assert(VT.isInteger() && VT == Operand.getValueType() && 5257 "Invalid ABS!"); 5258 if (OpOpcode == ISD::UNDEF) 5259 return getConstant(0, DL, VT); 5260 break; 5261 case ISD::BSWAP: 5262 assert(VT.isInteger() && VT == Operand.getValueType() && 5263 "Invalid BSWAP!"); 5264 assert((VT.getScalarSizeInBits() % 16 == 0) && 5265 "BSWAP types must be a multiple of 16 bits!"); 5266 if (OpOpcode == ISD::UNDEF) 5267 return getUNDEF(VT); 5268 // bswap(bswap(X)) -> X. 5269 if (OpOpcode == ISD::BSWAP) 5270 return Operand.getOperand(0); 5271 break; 5272 case ISD::BITREVERSE: 5273 assert(VT.isInteger() && VT == Operand.getValueType() && 5274 "Invalid BITREVERSE!"); 5275 if (OpOpcode == ISD::UNDEF) 5276 return getUNDEF(VT); 5277 break; 5278 case ISD::BITCAST: 5279 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5280 "Cannot BITCAST between types of different sizes!"); 5281 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5282 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5283 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5284 if (OpOpcode == ISD::UNDEF) 5285 return getUNDEF(VT); 5286 break; 5287 case ISD::SCALAR_TO_VECTOR: 5288 assert(VT.isVector() && !Operand.getValueType().isVector() && 5289 (VT.getVectorElementType() == Operand.getValueType() || 5290 (VT.getVectorElementType().isInteger() && 5291 Operand.getValueType().isInteger() && 5292 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5293 "Illegal SCALAR_TO_VECTOR node!"); 5294 if (OpOpcode == ISD::UNDEF) 5295 return getUNDEF(VT); 5296 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5297 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5298 isa<ConstantSDNode>(Operand.getOperand(1)) && 5299 Operand.getConstantOperandVal(1) == 0 && 5300 Operand.getOperand(0).getValueType() == VT) 5301 return Operand.getOperand(0); 5302 break; 5303 case ISD::FNEG: 5304 // Negation of an unknown bag of bits is still completely undefined. 5305 if (OpOpcode == ISD::UNDEF) 5306 return getUNDEF(VT); 5307 5308 if (OpOpcode == ISD::FNEG) // --X -> X 5309 return Operand.getOperand(0); 5310 break; 5311 case ISD::FABS: 5312 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5313 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5314 break; 5315 case ISD::VSCALE: 5316 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5317 break; 5318 case ISD::CTPOP: 5319 if (Operand.getValueType().getScalarType() == MVT::i1) 5320 return Operand; 5321 break; 5322 case ISD::CTLZ: 5323 case ISD::CTTZ: 5324 if (Operand.getValueType().getScalarType() == MVT::i1) 5325 return getNOT(DL, Operand, Operand.getValueType()); 5326 break; 5327 case ISD::VECREDUCE_ADD: 5328 if (Operand.getValueType().getScalarType() == MVT::i1) 5329 return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand); 5330 break; 5331 case ISD::VECREDUCE_SMIN: 5332 case ISD::VECREDUCE_UMAX: 5333 if (Operand.getValueType().getScalarType() == MVT::i1) 5334 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5335 break; 5336 case ISD::VECREDUCE_SMAX: 5337 case ISD::VECREDUCE_UMIN: 5338 if (Operand.getValueType().getScalarType() == MVT::i1) 5339 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5340 break; 5341 } 5342 5343 SDNode *N; 5344 SDVTList VTs = getVTList(VT); 5345 SDValue Ops[] = {Operand}; 5346 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5347 FoldingSetNodeID ID; 5348 AddNodeIDNode(ID, Opcode, VTs, Ops); 5349 void *IP = nullptr; 5350 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5351 E->intersectFlagsWith(Flags); 5352 return SDValue(E, 0); 5353 } 5354 5355 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5356 N->setFlags(Flags); 5357 createOperands(N, Ops); 5358 CSEMap.InsertNode(N, IP); 5359 } else { 5360 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5361 createOperands(N, Ops); 5362 } 5363 5364 InsertNode(N); 5365 SDValue V = SDValue(N, 0); 5366 NewSDValueDbgMsg(V, "Creating new node: ", this); 5367 return V; 5368 } 5369 5370 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5371 const APInt &C2) { 5372 switch (Opcode) { 5373 case ISD::ADD: return C1 + C2; 5374 case ISD::SUB: return C1 - C2; 5375 case ISD::MUL: return C1 * C2; 5376 case ISD::AND: return C1 & C2; 5377 case ISD::OR: return C1 | C2; 5378 case ISD::XOR: return C1 ^ C2; 5379 case ISD::SHL: return C1 << C2; 5380 case ISD::SRL: return C1.lshr(C2); 5381 case ISD::SRA: return C1.ashr(C2); 5382 case ISD::ROTL: return C1.rotl(C2); 5383 case ISD::ROTR: return C1.rotr(C2); 5384 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5385 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5386 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5387 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5388 case ISD::SADDSAT: return C1.sadd_sat(C2); 5389 case ISD::UADDSAT: return C1.uadd_sat(C2); 5390 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5391 case ISD::USUBSAT: return C1.usub_sat(C2); 5392 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5393 case ISD::USHLSAT: return C1.ushl_sat(C2); 5394 case ISD::UDIV: 5395 if (!C2.getBoolValue()) 5396 break; 5397 return C1.udiv(C2); 5398 case ISD::UREM: 5399 if (!C2.getBoolValue()) 5400 break; 5401 return C1.urem(C2); 5402 case ISD::SDIV: 5403 if (!C2.getBoolValue()) 5404 break; 5405 return C1.sdiv(C2); 5406 case ISD::SREM: 5407 if (!C2.getBoolValue()) 5408 break; 5409 return C1.srem(C2); 5410 case ISD::MULHS: { 5411 unsigned FullWidth = C1.getBitWidth() * 2; 5412 APInt C1Ext = C1.sext(FullWidth); 5413 APInt C2Ext = C2.sext(FullWidth); 5414 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5415 } 5416 case ISD::MULHU: { 5417 unsigned FullWidth = C1.getBitWidth() * 2; 5418 APInt C1Ext = C1.zext(FullWidth); 5419 APInt C2Ext = C2.zext(FullWidth); 5420 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5421 } 5422 case ISD::AVGFLOORS: { 5423 unsigned FullWidth = C1.getBitWidth() + 1; 5424 APInt C1Ext = C1.sext(FullWidth); 5425 APInt C2Ext = C2.sext(FullWidth); 5426 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5427 } 5428 case ISD::AVGFLOORU: { 5429 unsigned FullWidth = C1.getBitWidth() + 1; 5430 APInt C1Ext = C1.zext(FullWidth); 5431 APInt C2Ext = C2.zext(FullWidth); 5432 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5433 } 5434 case ISD::AVGCEILS: { 5435 unsigned FullWidth = C1.getBitWidth() + 1; 5436 APInt C1Ext = C1.sext(FullWidth); 5437 APInt C2Ext = C2.sext(FullWidth); 5438 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5439 } 5440 case ISD::AVGCEILU: { 5441 unsigned FullWidth = C1.getBitWidth() + 1; 5442 APInt C1Ext = C1.zext(FullWidth); 5443 APInt C2Ext = C2.zext(FullWidth); 5444 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5445 } 5446 } 5447 return llvm::None; 5448 } 5449 5450 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5451 const GlobalAddressSDNode *GA, 5452 const SDNode *N2) { 5453 if (GA->getOpcode() != ISD::GlobalAddress) 5454 return SDValue(); 5455 if (!TLI->isOffsetFoldingLegal(GA)) 5456 return SDValue(); 5457 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5458 if (!C2) 5459 return SDValue(); 5460 int64_t Offset = C2->getSExtValue(); 5461 switch (Opcode) { 5462 case ISD::ADD: break; 5463 case ISD::SUB: Offset = -uint64_t(Offset); break; 5464 default: return SDValue(); 5465 } 5466 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5467 GA->getOffset() + uint64_t(Offset)); 5468 } 5469 5470 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5471 switch (Opcode) { 5472 case ISD::SDIV: 5473 case ISD::UDIV: 5474 case ISD::SREM: 5475 case ISD::UREM: { 5476 // If a divisor is zero/undef or any element of a divisor vector is 5477 // zero/undef, the whole op is undef. 5478 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5479 SDValue Divisor = Ops[1]; 5480 if (Divisor.isUndef() || isNullConstant(Divisor)) 5481 return true; 5482 5483 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5484 llvm::any_of(Divisor->op_values(), 5485 [](SDValue V) { return V.isUndef() || 5486 isNullConstant(V); }); 5487 // TODO: Handle signed overflow. 5488 } 5489 // TODO: Handle oversized shifts. 5490 default: 5491 return false; 5492 } 5493 } 5494 5495 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5496 EVT VT, ArrayRef<SDValue> Ops) { 5497 // If the opcode is a target-specific ISD node, there's nothing we can 5498 // do here and the operand rules may not line up with the below, so 5499 // bail early. 5500 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5501 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5502 // foldCONCAT_VECTORS in getNode before this is called. 5503 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5504 return SDValue(); 5505 5506 unsigned NumOps = Ops.size(); 5507 if (NumOps == 0) 5508 return SDValue(); 5509 5510 if (isUndef(Opcode, Ops)) 5511 return getUNDEF(VT); 5512 5513 // Handle binops special cases. 5514 if (NumOps == 2) { 5515 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5516 return CFP; 5517 5518 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5519 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5520 if (C1->isOpaque() || C2->isOpaque()) 5521 return SDValue(); 5522 5523 Optional<APInt> FoldAttempt = 5524 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5525 if (!FoldAttempt) 5526 return SDValue(); 5527 5528 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5529 assert((!Folded || !VT.isVector()) && 5530 "Can't fold vectors ops with scalar operands"); 5531 return Folded; 5532 } 5533 } 5534 5535 // fold (add Sym, c) -> Sym+c 5536 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5537 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5538 if (TLI->isCommutativeBinOp(Opcode)) 5539 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5540 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5541 } 5542 5543 // This is for vector folding only from here on. 5544 if (!VT.isVector()) 5545 return SDValue(); 5546 5547 ElementCount NumElts = VT.getVectorElementCount(); 5548 5549 // See if we can fold through bitcasted integer ops. 5550 // TODO: Can we handle undef elements? 5551 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5552 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5553 Ops[0].getOpcode() == ISD::BITCAST && 5554 Ops[1].getOpcode() == ISD::BITCAST) { 5555 SDValue N1 = peekThroughBitcasts(Ops[0]); 5556 SDValue N2 = peekThroughBitcasts(Ops[1]); 5557 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5558 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5559 EVT BVVT = N1.getValueType(); 5560 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5561 bool IsLE = getDataLayout().isLittleEndian(); 5562 unsigned EltBits = VT.getScalarSizeInBits(); 5563 SmallVector<APInt> RawBits1, RawBits2; 5564 BitVector UndefElts1, UndefElts2; 5565 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5566 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5567 UndefElts1.none() && UndefElts2.none()) { 5568 SmallVector<APInt> RawBits; 5569 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5570 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5571 if (!Fold) 5572 break; 5573 RawBits.push_back(Fold.getValue()); 5574 } 5575 if (RawBits.size() == NumElts.getFixedValue()) { 5576 // We have constant folded, but we need to cast this again back to 5577 // the original (possibly legalized) type. 5578 SmallVector<APInt> DstBits; 5579 BitVector DstUndefs; 5580 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5581 DstBits, RawBits, DstUndefs, 5582 BitVector(RawBits.size(), false)); 5583 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5584 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5585 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5586 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5587 if (DstUndefs[I]) 5588 continue; 5589 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT); 5590 } 5591 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5592 } 5593 } 5594 } 5595 } 5596 5597 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5598 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5599 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5600 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5601 APInt RHSVal; 5602 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5603 APInt NewStep = Opcode == ISD::MUL 5604 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5605 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5606 return getStepVector(DL, VT, NewStep); 5607 } 5608 } 5609 5610 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5611 return !Op.getValueType().isVector() || 5612 Op.getValueType().getVectorElementCount() == NumElts; 5613 }; 5614 5615 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5616 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5617 Op.getOpcode() == ISD::BUILD_VECTOR || 5618 Op.getOpcode() == ISD::SPLAT_VECTOR; 5619 }; 5620 5621 // All operands must be vector types with the same number of elements as 5622 // the result type and must be either UNDEF or a build/splat vector 5623 // or UNDEF scalars. 5624 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5625 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5626 return SDValue(); 5627 5628 // If we are comparing vectors, then the result needs to be a i1 boolean that 5629 // is then extended back to the legal result type depending on how booleans 5630 // are represented. 5631 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5632 ISD::NodeType ExtendCode = 5633 (Opcode == ISD::SETCC && SVT != VT.getScalarType()) 5634 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT)) 5635 : ISD::SIGN_EXTEND; 5636 5637 // Find legal integer scalar type for constant promotion and 5638 // ensure that its scalar size is at least as large as source. 5639 EVT LegalSVT = VT.getScalarType(); 5640 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5641 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5642 if (LegalSVT.bitsLT(VT.getScalarType())) 5643 return SDValue(); 5644 } 5645 5646 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5647 // only have one operand to check. For fixed-length vector types we may have 5648 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5649 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5650 5651 // Constant fold each scalar lane separately. 5652 SmallVector<SDValue, 4> ScalarResults; 5653 for (unsigned I = 0; I != NumVectorElts; I++) { 5654 SmallVector<SDValue, 4> ScalarOps; 5655 for (SDValue Op : Ops) { 5656 EVT InSVT = Op.getValueType().getScalarType(); 5657 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5658 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5659 if (Op.isUndef()) 5660 ScalarOps.push_back(getUNDEF(InSVT)); 5661 else 5662 ScalarOps.push_back(Op); 5663 continue; 5664 } 5665 5666 SDValue ScalarOp = 5667 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5668 EVT ScalarVT = ScalarOp.getValueType(); 5669 5670 // Build vector (integer) scalar operands may need implicit 5671 // truncation - do this before constant folding. 5672 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) { 5673 // Don't create illegally-typed nodes unless they're constants or undef 5674 // - if we fail to constant fold we can't guarantee the (dead) nodes 5675 // we're creating will be cleaned up before being visited for 5676 // legalization. 5677 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() && 5678 !isa<ConstantSDNode>(ScalarOp) && 5679 TLI->getTypeAction(*getContext(), InSVT) != 5680 TargetLowering::TypeLegal) 5681 return SDValue(); 5682 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5683 } 5684 5685 ScalarOps.push_back(ScalarOp); 5686 } 5687 5688 // Constant fold the scalar operands. 5689 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5690 5691 // Legalize the (integer) scalar constant if necessary. 5692 if (LegalSVT != SVT) 5693 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult); 5694 5695 // Scalar folding only succeeded if the result is a constant or UNDEF. 5696 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5697 ScalarResult.getOpcode() != ISD::ConstantFP) 5698 return SDValue(); 5699 ScalarResults.push_back(ScalarResult); 5700 } 5701 5702 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5703 : getBuildVector(VT, DL, ScalarResults); 5704 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5705 return V; 5706 } 5707 5708 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5709 EVT VT, SDValue N1, SDValue N2) { 5710 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5711 // should. That will require dealing with a potentially non-default 5712 // rounding mode, checking the "opStatus" return value from the APFloat 5713 // math calculations, and possibly other variations. 5714 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5715 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5716 if (N1CFP && N2CFP) { 5717 APFloat C1 = N1CFP->getValueAPF(); // make copy 5718 const APFloat &C2 = N2CFP->getValueAPF(); 5719 switch (Opcode) { 5720 case ISD::FADD: 5721 C1.add(C2, APFloat::rmNearestTiesToEven); 5722 return getConstantFP(C1, DL, VT); 5723 case ISD::FSUB: 5724 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5725 return getConstantFP(C1, DL, VT); 5726 case ISD::FMUL: 5727 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5728 return getConstantFP(C1, DL, VT); 5729 case ISD::FDIV: 5730 C1.divide(C2, APFloat::rmNearestTiesToEven); 5731 return getConstantFP(C1, DL, VT); 5732 case ISD::FREM: 5733 C1.mod(C2); 5734 return getConstantFP(C1, DL, VT); 5735 case ISD::FCOPYSIGN: 5736 C1.copySign(C2); 5737 return getConstantFP(C1, DL, VT); 5738 case ISD::FMINNUM: 5739 return getConstantFP(minnum(C1, C2), DL, VT); 5740 case ISD::FMAXNUM: 5741 return getConstantFP(maxnum(C1, C2), DL, VT); 5742 case ISD::FMINIMUM: 5743 return getConstantFP(minimum(C1, C2), DL, VT); 5744 case ISD::FMAXIMUM: 5745 return getConstantFP(maximum(C1, C2), DL, VT); 5746 default: break; 5747 } 5748 } 5749 if (N1CFP && Opcode == ISD::FP_ROUND) { 5750 APFloat C1 = N1CFP->getValueAPF(); // make copy 5751 bool Unused; 5752 // This can return overflow, underflow, or inexact; we don't care. 5753 // FIXME need to be more flexible about rounding mode. 5754 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5755 &Unused); 5756 return getConstantFP(C1, DL, VT); 5757 } 5758 5759 switch (Opcode) { 5760 case ISD::FSUB: 5761 // -0.0 - undef --> undef (consistent with "fneg undef") 5762 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5763 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5764 return getUNDEF(VT); 5765 LLVM_FALLTHROUGH; 5766 5767 case ISD::FADD: 5768 case ISD::FMUL: 5769 case ISD::FDIV: 5770 case ISD::FREM: 5771 // If both operands are undef, the result is undef. If 1 operand is undef, 5772 // the result is NaN. This should match the behavior of the IR optimizer. 5773 if (N1.isUndef() && N2.isUndef()) 5774 return getUNDEF(VT); 5775 if (N1.isUndef() || N2.isUndef()) 5776 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5777 } 5778 return SDValue(); 5779 } 5780 5781 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5782 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5783 5784 // There's no need to assert on a byte-aligned pointer. All pointers are at 5785 // least byte aligned. 5786 if (A == Align(1)) 5787 return Val; 5788 5789 FoldingSetNodeID ID; 5790 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5791 ID.AddInteger(A.value()); 5792 5793 void *IP = nullptr; 5794 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5795 return SDValue(E, 0); 5796 5797 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5798 Val.getValueType(), A); 5799 createOperands(N, {Val}); 5800 5801 CSEMap.InsertNode(N, IP); 5802 InsertNode(N); 5803 5804 SDValue V(N, 0); 5805 NewSDValueDbgMsg(V, "Creating new node: ", this); 5806 return V; 5807 } 5808 5809 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5810 SDValue N1, SDValue N2) { 5811 SDNodeFlags Flags; 5812 if (Inserter) 5813 Flags = Inserter->getFlags(); 5814 return getNode(Opcode, DL, VT, N1, N2, Flags); 5815 } 5816 5817 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5818 SDValue &N2) const { 5819 if (!TLI->isCommutativeBinOp(Opcode)) 5820 return; 5821 5822 // Canonicalize: 5823 // binop(const, nonconst) -> binop(nonconst, const) 5824 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5825 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5826 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5827 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5828 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5829 std::swap(N1, N2); 5830 5831 // Canonicalize: 5832 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5833 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5834 N2.getOpcode() == ISD::STEP_VECTOR) 5835 std::swap(N1, N2); 5836 } 5837 5838 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5839 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5840 assert(N1.getOpcode() != ISD::DELETED_NODE && 5841 N2.getOpcode() != ISD::DELETED_NODE && 5842 "Operand is DELETED_NODE!"); 5843 5844 canonicalizeCommutativeBinop(Opcode, N1, N2); 5845 5846 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5847 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5848 5849 // Don't allow undefs in vector splats - we might be returning N2 when folding 5850 // to zero etc. 5851 ConstantSDNode *N2CV = 5852 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5853 5854 switch (Opcode) { 5855 default: break; 5856 case ISD::TokenFactor: 5857 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5858 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5859 // Fold trivial token factors. 5860 if (N1.getOpcode() == ISD::EntryToken) return N2; 5861 if (N2.getOpcode() == ISD::EntryToken) return N1; 5862 if (N1 == N2) return N1; 5863 break; 5864 case ISD::BUILD_VECTOR: { 5865 // Attempt to simplify BUILD_VECTOR. 5866 SDValue Ops[] = {N1, N2}; 5867 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5868 return V; 5869 break; 5870 } 5871 case ISD::CONCAT_VECTORS: { 5872 SDValue Ops[] = {N1, N2}; 5873 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5874 return V; 5875 break; 5876 } 5877 case ISD::AND: 5878 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5879 assert(N1.getValueType() == N2.getValueType() && 5880 N1.getValueType() == VT && "Binary operator types must match!"); 5881 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5882 // worth handling here. 5883 if (N2CV && N2CV->isZero()) 5884 return N2; 5885 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5886 return N1; 5887 break; 5888 case ISD::OR: 5889 case ISD::XOR: 5890 case ISD::ADD: 5891 case ISD::SUB: 5892 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5893 assert(N1.getValueType() == N2.getValueType() && 5894 N1.getValueType() == VT && "Binary operator types must match!"); 5895 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5896 // it's worth handling here. 5897 if (N2CV && N2CV->isZero()) 5898 return N1; 5899 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5900 VT.getVectorElementType() == MVT::i1) 5901 return getNode(ISD::XOR, DL, VT, N1, N2); 5902 break; 5903 case ISD::MUL: 5904 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5905 assert(N1.getValueType() == N2.getValueType() && 5906 N1.getValueType() == VT && "Binary operator types must match!"); 5907 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5908 return getNode(ISD::AND, DL, VT, N1, N2); 5909 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5910 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5911 const APInt &N2CImm = N2C->getAPIntValue(); 5912 return getVScale(DL, VT, MulImm * N2CImm); 5913 } 5914 break; 5915 case ISD::UDIV: 5916 case ISD::UREM: 5917 case ISD::MULHU: 5918 case ISD::MULHS: 5919 case ISD::SDIV: 5920 case ISD::SREM: 5921 case ISD::SADDSAT: 5922 case ISD::SSUBSAT: 5923 case ISD::UADDSAT: 5924 case ISD::USUBSAT: 5925 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5926 assert(N1.getValueType() == N2.getValueType() && 5927 N1.getValueType() == VT && "Binary operator types must match!"); 5928 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5929 // fold (add_sat x, y) -> (or x, y) for bool types. 5930 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5931 return getNode(ISD::OR, DL, VT, N1, N2); 5932 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5933 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5934 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5935 } 5936 break; 5937 case ISD::SMIN: 5938 case ISD::UMAX: 5939 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5940 assert(N1.getValueType() == N2.getValueType() && 5941 N1.getValueType() == VT && "Binary operator types must match!"); 5942 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5943 return getNode(ISD::OR, DL, VT, N1, N2); 5944 break; 5945 case ISD::SMAX: 5946 case ISD::UMIN: 5947 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5948 assert(N1.getValueType() == N2.getValueType() && 5949 N1.getValueType() == VT && "Binary operator types must match!"); 5950 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5951 return getNode(ISD::AND, DL, VT, N1, N2); 5952 break; 5953 case ISD::FADD: 5954 case ISD::FSUB: 5955 case ISD::FMUL: 5956 case ISD::FDIV: 5957 case ISD::FREM: 5958 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5959 assert(N1.getValueType() == N2.getValueType() && 5960 N1.getValueType() == VT && "Binary operator types must match!"); 5961 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5962 return V; 5963 break; 5964 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5965 assert(N1.getValueType() == VT && 5966 N1.getValueType().isFloatingPoint() && 5967 N2.getValueType().isFloatingPoint() && 5968 "Invalid FCOPYSIGN!"); 5969 break; 5970 case ISD::SHL: 5971 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5972 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5973 const APInt &ShiftImm = N2C->getAPIntValue(); 5974 return getVScale(DL, VT, MulImm << ShiftImm); 5975 } 5976 LLVM_FALLTHROUGH; 5977 case ISD::SRA: 5978 case ISD::SRL: 5979 if (SDValue V = simplifyShift(N1, N2)) 5980 return V; 5981 LLVM_FALLTHROUGH; 5982 case ISD::ROTL: 5983 case ISD::ROTR: 5984 assert(VT == N1.getValueType() && 5985 "Shift operators return type must be the same as their first arg"); 5986 assert(VT.isInteger() && N2.getValueType().isInteger() && 5987 "Shifts only work on integers"); 5988 assert((!VT.isVector() || VT == N2.getValueType()) && 5989 "Vector shift amounts must be in the same as their first arg"); 5990 // Verify that the shift amount VT is big enough to hold valid shift 5991 // amounts. This catches things like trying to shift an i1024 value by an 5992 // i8, which is easy to fall into in generic code that uses 5993 // TLI.getShiftAmount(). 5994 assert(N2.getValueType().getScalarSizeInBits() >= 5995 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5996 "Invalid use of small shift amount with oversized value!"); 5997 5998 // Always fold shifts of i1 values so the code generator doesn't need to 5999 // handle them. Since we know the size of the shift has to be less than the 6000 // size of the value, the shift/rotate count is guaranteed to be zero. 6001 if (VT == MVT::i1) 6002 return N1; 6003 if (N2CV && N2CV->isZero()) 6004 return N1; 6005 break; 6006 case ISD::FP_ROUND: 6007 assert(VT.isFloatingPoint() && 6008 N1.getValueType().isFloatingPoint() && 6009 VT.bitsLE(N1.getValueType()) && 6010 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 6011 "Invalid FP_ROUND!"); 6012 if (N1.getValueType() == VT) return N1; // noop conversion. 6013 break; 6014 case ISD::AssertSext: 6015 case ISD::AssertZext: { 6016 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6017 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6018 assert(VT.isInteger() && EVT.isInteger() && 6019 "Cannot *_EXTEND_INREG FP types"); 6020 assert(!EVT.isVector() && 6021 "AssertSExt/AssertZExt type should be the vector element type " 6022 "rather than the vector type!"); 6023 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 6024 if (VT.getScalarType() == EVT) return N1; // noop assertion. 6025 break; 6026 } 6027 case ISD::SIGN_EXTEND_INREG: { 6028 EVT EVT = cast<VTSDNode>(N2)->getVT(); 6029 assert(VT == N1.getValueType() && "Not an inreg extend!"); 6030 assert(VT.isInteger() && EVT.isInteger() && 6031 "Cannot *_EXTEND_INREG FP types"); 6032 assert(EVT.isVector() == VT.isVector() && 6033 "SIGN_EXTEND_INREG type should be vector iff the operand " 6034 "type is vector!"); 6035 assert((!EVT.isVector() || 6036 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 6037 "Vector element counts must match in SIGN_EXTEND_INREG"); 6038 assert(EVT.bitsLE(VT) && "Not extending!"); 6039 if (EVT == VT) return N1; // Not actually extending 6040 6041 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 6042 unsigned FromBits = EVT.getScalarSizeInBits(); 6043 Val <<= Val.getBitWidth() - FromBits; 6044 Val.ashrInPlace(Val.getBitWidth() - FromBits); 6045 return getConstant(Val, DL, ConstantVT); 6046 }; 6047 6048 if (N1C) { 6049 const APInt &Val = N1C->getAPIntValue(); 6050 return SignExtendInReg(Val, VT); 6051 } 6052 6053 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 6054 SmallVector<SDValue, 8> Ops; 6055 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 6056 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 6057 SDValue Op = N1.getOperand(i); 6058 if (Op.isUndef()) { 6059 Ops.push_back(getUNDEF(OpVT)); 6060 continue; 6061 } 6062 ConstantSDNode *C = cast<ConstantSDNode>(Op); 6063 APInt Val = C->getAPIntValue(); 6064 Ops.push_back(SignExtendInReg(Val, OpVT)); 6065 } 6066 return getBuildVector(VT, DL, Ops); 6067 } 6068 break; 6069 } 6070 case ISD::FP_TO_SINT_SAT: 6071 case ISD::FP_TO_UINT_SAT: { 6072 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 6073 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 6074 assert(N1.getValueType().isVector() == VT.isVector() && 6075 "FP_TO_*INT_SAT type should be vector iff the operand type is " 6076 "vector!"); 6077 assert((!VT.isVector() || VT.getVectorNumElements() == 6078 N1.getValueType().getVectorNumElements()) && 6079 "Vector element counts must match in FP_TO_*INT_SAT"); 6080 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 6081 "Type to saturate to must be a scalar."); 6082 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 6083 "Not extending!"); 6084 break; 6085 } 6086 case ISD::EXTRACT_VECTOR_ELT: 6087 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 6088 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 6089 element type of the vector."); 6090 6091 // Extract from an undefined value or using an undefined index is undefined. 6092 if (N1.isUndef() || N2.isUndef()) 6093 return getUNDEF(VT); 6094 6095 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 6096 // vectors. For scalable vectors we will provide appropriate support for 6097 // dealing with arbitrary indices. 6098 if (N2C && N1.getValueType().isFixedLengthVector() && 6099 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 6100 return getUNDEF(VT); 6101 6102 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 6103 // expanding copies of large vectors from registers. This only works for 6104 // fixed length vectors, since we need to know the exact number of 6105 // elements. 6106 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 6107 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 6108 unsigned Factor = 6109 N1.getOperand(0).getValueType().getVectorNumElements(); 6110 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 6111 N1.getOperand(N2C->getZExtValue() / Factor), 6112 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 6113 } 6114 6115 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 6116 // lowering is expanding large vector constants. 6117 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 6118 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 6119 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 6120 N1.getValueType().isFixedLengthVector()) && 6121 "BUILD_VECTOR used for scalable vectors"); 6122 unsigned Index = 6123 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 6124 SDValue Elt = N1.getOperand(Index); 6125 6126 if (VT != Elt.getValueType()) 6127 // If the vector element type is not legal, the BUILD_VECTOR operands 6128 // are promoted and implicitly truncated, and the result implicitly 6129 // extended. Make that explicit here. 6130 Elt = getAnyExtOrTrunc(Elt, DL, VT); 6131 6132 return Elt; 6133 } 6134 6135 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 6136 // operations are lowered to scalars. 6137 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 6138 // If the indices are the same, return the inserted element else 6139 // if the indices are known different, extract the element from 6140 // the original vector. 6141 SDValue N1Op2 = N1.getOperand(2); 6142 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 6143 6144 if (N1Op2C && N2C) { 6145 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 6146 if (VT == N1.getOperand(1).getValueType()) 6147 return N1.getOperand(1); 6148 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 6149 } 6150 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 6151 } 6152 } 6153 6154 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 6155 // when vector types are scalarized and v1iX is legal. 6156 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 6157 // Here we are completely ignoring the extract element index (N2), 6158 // which is fine for fixed width vectors, since any index other than 0 6159 // is undefined anyway. However, this cannot be ignored for scalable 6160 // vectors - in theory we could support this, but we don't want to do this 6161 // without a profitability check. 6162 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6163 N1.getValueType().isFixedLengthVector() && 6164 N1.getValueType().getVectorNumElements() == 1) { 6165 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6166 N1.getOperand(1)); 6167 } 6168 break; 6169 case ISD::EXTRACT_ELEMENT: 6170 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6171 assert(!N1.getValueType().isVector() && !VT.isVector() && 6172 (N1.getValueType().isInteger() == VT.isInteger()) && 6173 N1.getValueType() != VT && 6174 "Wrong types for EXTRACT_ELEMENT!"); 6175 6176 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6177 // 64-bit integers into 32-bit parts. Instead of building the extract of 6178 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6179 if (N1.getOpcode() == ISD::BUILD_PAIR) 6180 return N1.getOperand(N2C->getZExtValue()); 6181 6182 // EXTRACT_ELEMENT of a constant int is also very common. 6183 if (N1C) { 6184 unsigned ElementSize = VT.getSizeInBits(); 6185 unsigned Shift = ElementSize * N2C->getZExtValue(); 6186 const APInt &Val = N1C->getAPIntValue(); 6187 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6188 } 6189 break; 6190 case ISD::EXTRACT_SUBVECTOR: { 6191 EVT N1VT = N1.getValueType(); 6192 assert(VT.isVector() && N1VT.isVector() && 6193 "Extract subvector VTs must be vectors!"); 6194 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6195 "Extract subvector VTs must have the same element type!"); 6196 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6197 "Cannot extract a scalable vector from a fixed length vector!"); 6198 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6199 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6200 "Extract subvector must be from larger vector to smaller vector!"); 6201 assert(N2C && "Extract subvector index must be a constant"); 6202 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6203 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6204 N1VT.getVectorMinNumElements()) && 6205 "Extract subvector overflow!"); 6206 assert(N2C->getAPIntValue().getBitWidth() == 6207 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6208 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6209 6210 // Trivial extraction. 6211 if (VT == N1VT) 6212 return N1; 6213 6214 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6215 if (N1.isUndef()) 6216 return getUNDEF(VT); 6217 6218 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6219 // the concat have the same type as the extract. 6220 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6221 VT == N1.getOperand(0).getValueType()) { 6222 unsigned Factor = VT.getVectorMinNumElements(); 6223 return N1.getOperand(N2C->getZExtValue() / Factor); 6224 } 6225 6226 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6227 // during shuffle legalization. 6228 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6229 VT == N1.getOperand(1).getValueType()) 6230 return N1.getOperand(1); 6231 break; 6232 } 6233 } 6234 6235 // Perform trivial constant folding. 6236 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6237 return SV; 6238 6239 // Canonicalize an UNDEF to the RHS, even over a constant. 6240 if (N1.isUndef()) { 6241 if (TLI->isCommutativeBinOp(Opcode)) { 6242 std::swap(N1, N2); 6243 } else { 6244 switch (Opcode) { 6245 case ISD::SUB: 6246 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6247 case ISD::SIGN_EXTEND_INREG: 6248 case ISD::UDIV: 6249 case ISD::SDIV: 6250 case ISD::UREM: 6251 case ISD::SREM: 6252 case ISD::SSUBSAT: 6253 case ISD::USUBSAT: 6254 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6255 } 6256 } 6257 } 6258 6259 // Fold a bunch of operators when the RHS is undef. 6260 if (N2.isUndef()) { 6261 switch (Opcode) { 6262 case ISD::XOR: 6263 if (N1.isUndef()) 6264 // Handle undef ^ undef -> 0 special case. This is a common 6265 // idiom (misuse). 6266 return getConstant(0, DL, VT); 6267 LLVM_FALLTHROUGH; 6268 case ISD::ADD: 6269 case ISD::SUB: 6270 case ISD::UDIV: 6271 case ISD::SDIV: 6272 case ISD::UREM: 6273 case ISD::SREM: 6274 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6275 case ISD::MUL: 6276 case ISD::AND: 6277 case ISD::SSUBSAT: 6278 case ISD::USUBSAT: 6279 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6280 case ISD::OR: 6281 case ISD::SADDSAT: 6282 case ISD::UADDSAT: 6283 return getAllOnesConstant(DL, VT); 6284 } 6285 } 6286 6287 // Memoize this node if possible. 6288 SDNode *N; 6289 SDVTList VTs = getVTList(VT); 6290 SDValue Ops[] = {N1, N2}; 6291 if (VT != MVT::Glue) { 6292 FoldingSetNodeID ID; 6293 AddNodeIDNode(ID, Opcode, VTs, Ops); 6294 void *IP = nullptr; 6295 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6296 E->intersectFlagsWith(Flags); 6297 return SDValue(E, 0); 6298 } 6299 6300 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6301 N->setFlags(Flags); 6302 createOperands(N, Ops); 6303 CSEMap.InsertNode(N, IP); 6304 } else { 6305 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6306 createOperands(N, Ops); 6307 } 6308 6309 InsertNode(N); 6310 SDValue V = SDValue(N, 0); 6311 NewSDValueDbgMsg(V, "Creating new node: ", this); 6312 return V; 6313 } 6314 6315 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6316 SDValue N1, SDValue N2, SDValue N3) { 6317 SDNodeFlags Flags; 6318 if (Inserter) 6319 Flags = Inserter->getFlags(); 6320 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6321 } 6322 6323 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6324 SDValue N1, SDValue N2, SDValue N3, 6325 const SDNodeFlags Flags) { 6326 assert(N1.getOpcode() != ISD::DELETED_NODE && 6327 N2.getOpcode() != ISD::DELETED_NODE && 6328 N3.getOpcode() != ISD::DELETED_NODE && 6329 "Operand is DELETED_NODE!"); 6330 // Perform various simplifications. 6331 switch (Opcode) { 6332 case ISD::FMA: { 6333 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6334 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6335 N3.getValueType() == VT && "FMA types must match!"); 6336 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6337 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6338 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6339 if (N1CFP && N2CFP && N3CFP) { 6340 APFloat V1 = N1CFP->getValueAPF(); 6341 const APFloat &V2 = N2CFP->getValueAPF(); 6342 const APFloat &V3 = N3CFP->getValueAPF(); 6343 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6344 return getConstantFP(V1, DL, VT); 6345 } 6346 break; 6347 } 6348 case ISD::BUILD_VECTOR: { 6349 // Attempt to simplify BUILD_VECTOR. 6350 SDValue Ops[] = {N1, N2, N3}; 6351 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6352 return V; 6353 break; 6354 } 6355 case ISD::CONCAT_VECTORS: { 6356 SDValue Ops[] = {N1, N2, N3}; 6357 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6358 return V; 6359 break; 6360 } 6361 case ISD::SETCC: { 6362 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6363 assert(N1.getValueType() == N2.getValueType() && 6364 "SETCC operands must have the same type!"); 6365 assert(VT.isVector() == N1.getValueType().isVector() && 6366 "SETCC type should be vector iff the operand type is vector!"); 6367 assert((!VT.isVector() || VT.getVectorElementCount() == 6368 N1.getValueType().getVectorElementCount()) && 6369 "SETCC vector element counts must match!"); 6370 // Use FoldSetCC to simplify SETCC's. 6371 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6372 return V; 6373 // Vector constant folding. 6374 SDValue Ops[] = {N1, N2, N3}; 6375 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6376 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6377 return V; 6378 } 6379 break; 6380 } 6381 case ISD::SELECT: 6382 case ISD::VSELECT: 6383 if (SDValue V = simplifySelect(N1, N2, N3)) 6384 return V; 6385 break; 6386 case ISD::VECTOR_SHUFFLE: 6387 llvm_unreachable("should use getVectorShuffle constructor!"); 6388 case ISD::VECTOR_SPLICE: { 6389 if (cast<ConstantSDNode>(N3)->isNullValue()) 6390 return N1; 6391 break; 6392 } 6393 case ISD::INSERT_VECTOR_ELT: { 6394 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6395 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6396 // for scalable vectors where we will generate appropriate code to 6397 // deal with out-of-bounds cases correctly. 6398 if (N3C && N1.getValueType().isFixedLengthVector() && 6399 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6400 return getUNDEF(VT); 6401 6402 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6403 if (N3.isUndef()) 6404 return getUNDEF(VT); 6405 6406 // If the inserted element is an UNDEF, just use the input vector. 6407 if (N2.isUndef()) 6408 return N1; 6409 6410 break; 6411 } 6412 case ISD::INSERT_SUBVECTOR: { 6413 // Inserting undef into undef is still undef. 6414 if (N1.isUndef() && N2.isUndef()) 6415 return getUNDEF(VT); 6416 6417 EVT N2VT = N2.getValueType(); 6418 assert(VT == N1.getValueType() && 6419 "Dest and insert subvector source types must match!"); 6420 assert(VT.isVector() && N2VT.isVector() && 6421 "Insert subvector VTs must be vectors!"); 6422 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6423 "Cannot insert a scalable vector into a fixed length vector!"); 6424 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6425 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6426 "Insert subvector must be from smaller vector to larger vector!"); 6427 assert(isa<ConstantSDNode>(N3) && 6428 "Insert subvector index must be constant"); 6429 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6430 (N2VT.getVectorMinNumElements() + 6431 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6432 VT.getVectorMinNumElements()) && 6433 "Insert subvector overflow!"); 6434 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6435 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6436 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6437 6438 // Trivial insertion. 6439 if (VT == N2VT) 6440 return N2; 6441 6442 // If this is an insert of an extracted vector into an undef vector, we 6443 // can just use the input to the extract. 6444 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6445 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6446 return N2.getOperand(0); 6447 break; 6448 } 6449 case ISD::BITCAST: 6450 // Fold bit_convert nodes from a type to themselves. 6451 if (N1.getValueType() == VT) 6452 return N1; 6453 break; 6454 } 6455 6456 // Memoize node if it doesn't produce a flag. 6457 SDNode *N; 6458 SDVTList VTs = getVTList(VT); 6459 SDValue Ops[] = {N1, N2, N3}; 6460 if (VT != MVT::Glue) { 6461 FoldingSetNodeID ID; 6462 AddNodeIDNode(ID, Opcode, VTs, Ops); 6463 void *IP = nullptr; 6464 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6465 E->intersectFlagsWith(Flags); 6466 return SDValue(E, 0); 6467 } 6468 6469 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6470 N->setFlags(Flags); 6471 createOperands(N, Ops); 6472 CSEMap.InsertNode(N, IP); 6473 } else { 6474 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6475 createOperands(N, Ops); 6476 } 6477 6478 InsertNode(N); 6479 SDValue V = SDValue(N, 0); 6480 NewSDValueDbgMsg(V, "Creating new node: ", this); 6481 return V; 6482 } 6483 6484 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6485 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6486 SDValue Ops[] = { N1, N2, N3, N4 }; 6487 return getNode(Opcode, DL, VT, Ops); 6488 } 6489 6490 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6491 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6492 SDValue N5) { 6493 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6494 return getNode(Opcode, DL, VT, Ops); 6495 } 6496 6497 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6498 /// the incoming stack arguments to be loaded from the stack. 6499 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6500 SmallVector<SDValue, 8> ArgChains; 6501 6502 // Include the original chain at the beginning of the list. When this is 6503 // used by target LowerCall hooks, this helps legalize find the 6504 // CALLSEQ_BEGIN node. 6505 ArgChains.push_back(Chain); 6506 6507 // Add a chain value for each stack argument. 6508 for (SDNode *U : getEntryNode().getNode()->uses()) 6509 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6510 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6511 if (FI->getIndex() < 0) 6512 ArgChains.push_back(SDValue(L, 1)); 6513 6514 // Build a tokenfactor for all the chains. 6515 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6516 } 6517 6518 /// getMemsetValue - Vectorized representation of the memset value 6519 /// operand. 6520 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6521 const SDLoc &dl) { 6522 assert(!Value.isUndef()); 6523 6524 unsigned NumBits = VT.getScalarSizeInBits(); 6525 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6526 assert(C->getAPIntValue().getBitWidth() == 8); 6527 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6528 if (VT.isInteger()) { 6529 bool IsOpaque = VT.getSizeInBits() > 64 || 6530 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6531 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6532 } 6533 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6534 VT); 6535 } 6536 6537 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6538 EVT IntVT = VT.getScalarType(); 6539 if (!IntVT.isInteger()) 6540 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6541 6542 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6543 if (NumBits > 8) { 6544 // Use a multiplication with 0x010101... to extend the input to the 6545 // required length. 6546 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6547 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6548 DAG.getConstant(Magic, dl, IntVT)); 6549 } 6550 6551 if (VT != Value.getValueType() && !VT.isInteger()) 6552 Value = DAG.getBitcast(VT.getScalarType(), Value); 6553 if (VT != Value.getValueType()) 6554 Value = DAG.getSplatBuildVector(VT, dl, Value); 6555 6556 return Value; 6557 } 6558 6559 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6560 /// used when a memcpy is turned into a memset when the source is a constant 6561 /// string ptr. 6562 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6563 const TargetLowering &TLI, 6564 const ConstantDataArraySlice &Slice) { 6565 // Handle vector with all elements zero. 6566 if (Slice.Array == nullptr) { 6567 if (VT.isInteger()) 6568 return DAG.getConstant(0, dl, VT); 6569 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6570 return DAG.getConstantFP(0.0, dl, VT); 6571 if (VT.isVector()) { 6572 unsigned NumElts = VT.getVectorNumElements(); 6573 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6574 return DAG.getNode(ISD::BITCAST, dl, VT, 6575 DAG.getConstant(0, dl, 6576 EVT::getVectorVT(*DAG.getContext(), 6577 EltVT, NumElts))); 6578 } 6579 llvm_unreachable("Expected type!"); 6580 } 6581 6582 assert(!VT.isVector() && "Can't handle vector type here!"); 6583 unsigned NumVTBits = VT.getSizeInBits(); 6584 unsigned NumVTBytes = NumVTBits / 8; 6585 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6586 6587 APInt Val(NumVTBits, 0); 6588 if (DAG.getDataLayout().isLittleEndian()) { 6589 for (unsigned i = 0; i != NumBytes; ++i) 6590 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6591 } else { 6592 for (unsigned i = 0; i != NumBytes; ++i) 6593 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6594 } 6595 6596 // If the "cost" of materializing the integer immediate is less than the cost 6597 // of a load, then it is cost effective to turn the load into the immediate. 6598 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6599 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6600 return DAG.getConstant(Val, dl, VT); 6601 return SDValue(); 6602 } 6603 6604 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6605 const SDLoc &DL, 6606 const SDNodeFlags Flags) { 6607 EVT VT = Base.getValueType(); 6608 SDValue Index; 6609 6610 if (Offset.isScalable()) 6611 Index = getVScale(DL, Base.getValueType(), 6612 APInt(Base.getValueSizeInBits().getFixedSize(), 6613 Offset.getKnownMinSize())); 6614 else 6615 Index = getConstant(Offset.getFixedSize(), DL, VT); 6616 6617 return getMemBasePlusOffset(Base, Index, DL, Flags); 6618 } 6619 6620 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6621 const SDLoc &DL, 6622 const SDNodeFlags Flags) { 6623 assert(Offset.getValueType().isInteger()); 6624 EVT BasePtrVT = Ptr.getValueType(); 6625 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6626 } 6627 6628 /// Returns true if memcpy source is constant data. 6629 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6630 uint64_t SrcDelta = 0; 6631 GlobalAddressSDNode *G = nullptr; 6632 if (Src.getOpcode() == ISD::GlobalAddress) 6633 G = cast<GlobalAddressSDNode>(Src); 6634 else if (Src.getOpcode() == ISD::ADD && 6635 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6636 Src.getOperand(1).getOpcode() == ISD::Constant) { 6637 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6638 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6639 } 6640 if (!G) 6641 return false; 6642 6643 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6644 SrcDelta + G->getOffset()); 6645 } 6646 6647 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6648 SelectionDAG &DAG) { 6649 // On Darwin, -Os means optimize for size without hurting performance, so 6650 // only really optimize for size when -Oz (MinSize) is used. 6651 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6652 return MF.getFunction().hasMinSize(); 6653 return DAG.shouldOptForSize(); 6654 } 6655 6656 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6657 SmallVector<SDValue, 32> &OutChains, unsigned From, 6658 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6659 SmallVector<SDValue, 16> &OutStoreChains) { 6660 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6661 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6662 SmallVector<SDValue, 16> GluedLoadChains; 6663 for (unsigned i = From; i < To; ++i) { 6664 OutChains.push_back(OutLoadChains[i]); 6665 GluedLoadChains.push_back(OutLoadChains[i]); 6666 } 6667 6668 // Chain for all loads. 6669 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6670 GluedLoadChains); 6671 6672 for (unsigned i = From; i < To; ++i) { 6673 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6674 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6675 ST->getBasePtr(), ST->getMemoryVT(), 6676 ST->getMemOperand()); 6677 OutChains.push_back(NewStore); 6678 } 6679 } 6680 6681 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6682 SDValue Chain, SDValue Dst, SDValue Src, 6683 uint64_t Size, Align Alignment, 6684 bool isVol, bool AlwaysInline, 6685 MachinePointerInfo DstPtrInfo, 6686 MachinePointerInfo SrcPtrInfo, 6687 const AAMDNodes &AAInfo) { 6688 // Turn a memcpy of undef to nop. 6689 // FIXME: We need to honor volatile even is Src is undef. 6690 if (Src.isUndef()) 6691 return Chain; 6692 6693 // Expand memcpy to a series of load and store ops if the size operand falls 6694 // below a certain threshold. 6695 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6696 // rather than maybe a humongous number of loads and stores. 6697 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6698 const DataLayout &DL = DAG.getDataLayout(); 6699 LLVMContext &C = *DAG.getContext(); 6700 std::vector<EVT> MemOps; 6701 bool DstAlignCanChange = false; 6702 MachineFunction &MF = DAG.getMachineFunction(); 6703 MachineFrameInfo &MFI = MF.getFrameInfo(); 6704 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6705 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6706 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6707 DstAlignCanChange = true; 6708 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6709 if (!SrcAlign || Alignment > *SrcAlign) 6710 SrcAlign = Alignment; 6711 assert(SrcAlign && "SrcAlign must be set"); 6712 ConstantDataArraySlice Slice; 6713 // If marked as volatile, perform a copy even when marked as constant. 6714 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6715 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6716 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6717 const MemOp Op = isZeroConstant 6718 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6719 /*IsZeroMemset*/ true, isVol) 6720 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6721 *SrcAlign, isVol, CopyFromConstant); 6722 if (!TLI.findOptimalMemOpLowering( 6723 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6724 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6725 return SDValue(); 6726 6727 if (DstAlignCanChange) { 6728 Type *Ty = MemOps[0].getTypeForEVT(C); 6729 Align NewAlign = DL.getABITypeAlign(Ty); 6730 6731 // Don't promote to an alignment that would require dynamic stack 6732 // realignment. 6733 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6734 if (!TRI->hasStackRealignment(MF)) 6735 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6736 NewAlign = NewAlign / 2; 6737 6738 if (NewAlign > Alignment) { 6739 // Give the stack frame object a larger alignment if needed. 6740 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6741 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6742 Alignment = NewAlign; 6743 } 6744 } 6745 6746 // Prepare AAInfo for loads/stores after lowering this memcpy. 6747 AAMDNodes NewAAInfo = AAInfo; 6748 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6749 6750 MachineMemOperand::Flags MMOFlags = 6751 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6752 SmallVector<SDValue, 16> OutLoadChains; 6753 SmallVector<SDValue, 16> OutStoreChains; 6754 SmallVector<SDValue, 32> OutChains; 6755 unsigned NumMemOps = MemOps.size(); 6756 uint64_t SrcOff = 0, DstOff = 0; 6757 for (unsigned i = 0; i != NumMemOps; ++i) { 6758 EVT VT = MemOps[i]; 6759 unsigned VTSize = VT.getSizeInBits() / 8; 6760 SDValue Value, Store; 6761 6762 if (VTSize > Size) { 6763 // Issuing an unaligned load / store pair that overlaps with the previous 6764 // pair. Adjust the offset accordingly. 6765 assert(i == NumMemOps-1 && i != 0); 6766 SrcOff -= VTSize - Size; 6767 DstOff -= VTSize - Size; 6768 } 6769 6770 if (CopyFromConstant && 6771 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6772 // It's unlikely a store of a vector immediate can be done in a single 6773 // instruction. It would require a load from a constantpool first. 6774 // We only handle zero vectors here. 6775 // FIXME: Handle other cases where store of vector immediate is done in 6776 // a single instruction. 6777 ConstantDataArraySlice SubSlice; 6778 if (SrcOff < Slice.Length) { 6779 SubSlice = Slice; 6780 SubSlice.move(SrcOff); 6781 } else { 6782 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6783 SubSlice.Array = nullptr; 6784 SubSlice.Offset = 0; 6785 SubSlice.Length = VTSize; 6786 } 6787 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6788 if (Value.getNode()) { 6789 Store = DAG.getStore( 6790 Chain, dl, Value, 6791 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6792 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6793 OutChains.push_back(Store); 6794 } 6795 } 6796 6797 if (!Store.getNode()) { 6798 // The type might not be legal for the target. This should only happen 6799 // if the type is smaller than a legal type, as on PPC, so the right 6800 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6801 // to Load/Store if NVT==VT. 6802 // FIXME does the case above also need this? 6803 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6804 assert(NVT.bitsGE(VT)); 6805 6806 bool isDereferenceable = 6807 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6808 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6809 if (isDereferenceable) 6810 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6811 6812 Value = DAG.getExtLoad( 6813 ISD::EXTLOAD, dl, NVT, Chain, 6814 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6815 SrcPtrInfo.getWithOffset(SrcOff), VT, 6816 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6817 OutLoadChains.push_back(Value.getValue(1)); 6818 6819 Store = DAG.getTruncStore( 6820 Chain, dl, Value, 6821 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6822 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6823 OutStoreChains.push_back(Store); 6824 } 6825 SrcOff += VTSize; 6826 DstOff += VTSize; 6827 Size -= VTSize; 6828 } 6829 6830 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6831 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6832 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6833 6834 if (NumLdStInMemcpy) { 6835 // It may be that memcpy might be converted to memset if it's memcpy 6836 // of constants. In such a case, we won't have loads and stores, but 6837 // just stores. In the absence of loads, there is nothing to gang up. 6838 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6839 // If target does not care, just leave as it. 6840 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6841 OutChains.push_back(OutLoadChains[i]); 6842 OutChains.push_back(OutStoreChains[i]); 6843 } 6844 } else { 6845 // Ld/St less than/equal limit set by target. 6846 if (NumLdStInMemcpy <= GluedLdStLimit) { 6847 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6848 NumLdStInMemcpy, OutLoadChains, 6849 OutStoreChains); 6850 } else { 6851 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6852 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6853 unsigned GlueIter = 0; 6854 6855 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6856 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6857 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6858 6859 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6860 OutLoadChains, OutStoreChains); 6861 GlueIter += GluedLdStLimit; 6862 } 6863 6864 // Residual ld/st. 6865 if (RemainingLdStInMemcpy) { 6866 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6867 RemainingLdStInMemcpy, OutLoadChains, 6868 OutStoreChains); 6869 } 6870 } 6871 } 6872 } 6873 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6874 } 6875 6876 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6877 SDValue Chain, SDValue Dst, SDValue Src, 6878 uint64_t Size, Align Alignment, 6879 bool isVol, bool AlwaysInline, 6880 MachinePointerInfo DstPtrInfo, 6881 MachinePointerInfo SrcPtrInfo, 6882 const AAMDNodes &AAInfo) { 6883 // Turn a memmove of undef to nop. 6884 // FIXME: We need to honor volatile even is Src is undef. 6885 if (Src.isUndef()) 6886 return Chain; 6887 6888 // Expand memmove to a series of load and store ops if the size operand falls 6889 // below a certain threshold. 6890 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6891 const DataLayout &DL = DAG.getDataLayout(); 6892 LLVMContext &C = *DAG.getContext(); 6893 std::vector<EVT> MemOps; 6894 bool DstAlignCanChange = false; 6895 MachineFunction &MF = DAG.getMachineFunction(); 6896 MachineFrameInfo &MFI = MF.getFrameInfo(); 6897 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6898 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6899 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6900 DstAlignCanChange = true; 6901 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6902 if (!SrcAlign || Alignment > *SrcAlign) 6903 SrcAlign = Alignment; 6904 assert(SrcAlign && "SrcAlign must be set"); 6905 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6906 if (!TLI.findOptimalMemOpLowering( 6907 MemOps, Limit, 6908 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6909 /*IsVolatile*/ true), 6910 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6911 MF.getFunction().getAttributes())) 6912 return SDValue(); 6913 6914 if (DstAlignCanChange) { 6915 Type *Ty = MemOps[0].getTypeForEVT(C); 6916 Align NewAlign = DL.getABITypeAlign(Ty); 6917 if (NewAlign > Alignment) { 6918 // Give the stack frame object a larger alignment if needed. 6919 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6920 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6921 Alignment = NewAlign; 6922 } 6923 } 6924 6925 // Prepare AAInfo for loads/stores after lowering this memmove. 6926 AAMDNodes NewAAInfo = AAInfo; 6927 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6928 6929 MachineMemOperand::Flags MMOFlags = 6930 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6931 uint64_t SrcOff = 0, DstOff = 0; 6932 SmallVector<SDValue, 8> LoadValues; 6933 SmallVector<SDValue, 8> LoadChains; 6934 SmallVector<SDValue, 8> OutChains; 6935 unsigned NumMemOps = MemOps.size(); 6936 for (unsigned i = 0; i < NumMemOps; i++) { 6937 EVT VT = MemOps[i]; 6938 unsigned VTSize = VT.getSizeInBits() / 8; 6939 SDValue Value; 6940 6941 bool isDereferenceable = 6942 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6943 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6944 if (isDereferenceable) 6945 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6946 6947 Value = DAG.getLoad( 6948 VT, dl, Chain, 6949 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6950 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6951 LoadValues.push_back(Value); 6952 LoadChains.push_back(Value.getValue(1)); 6953 SrcOff += VTSize; 6954 } 6955 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6956 OutChains.clear(); 6957 for (unsigned i = 0; i < NumMemOps; i++) { 6958 EVT VT = MemOps[i]; 6959 unsigned VTSize = VT.getSizeInBits() / 8; 6960 SDValue Store; 6961 6962 Store = DAG.getStore( 6963 Chain, dl, LoadValues[i], 6964 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6965 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6966 OutChains.push_back(Store); 6967 DstOff += VTSize; 6968 } 6969 6970 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6971 } 6972 6973 /// Lower the call to 'memset' intrinsic function into a series of store 6974 /// operations. 6975 /// 6976 /// \param DAG Selection DAG where lowered code is placed. 6977 /// \param dl Link to corresponding IR location. 6978 /// \param Chain Control flow dependency. 6979 /// \param Dst Pointer to destination memory location. 6980 /// \param Src Value of byte to write into the memory. 6981 /// \param Size Number of bytes to write. 6982 /// \param Alignment Alignment of the destination in bytes. 6983 /// \param isVol True if destination is volatile. 6984 /// \param DstPtrInfo IR information on the memory pointer. 6985 /// \returns New head in the control flow, if lowering was successful, empty 6986 /// SDValue otherwise. 6987 /// 6988 /// The function tries to replace 'llvm.memset' intrinsic with several store 6989 /// operations and value calculation code. This is usually profitable for small 6990 /// memory size. 6991 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6992 SDValue Chain, SDValue Dst, SDValue Src, 6993 uint64_t Size, Align Alignment, bool isVol, 6994 MachinePointerInfo DstPtrInfo, 6995 const AAMDNodes &AAInfo) { 6996 // Turn a memset of undef to nop. 6997 // FIXME: We need to honor volatile even is Src is undef. 6998 if (Src.isUndef()) 6999 return Chain; 7000 7001 // Expand memset to a series of load/store ops if the size operand 7002 // falls below a certain threshold. 7003 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7004 std::vector<EVT> MemOps; 7005 bool DstAlignCanChange = false; 7006 MachineFunction &MF = DAG.getMachineFunction(); 7007 MachineFrameInfo &MFI = MF.getFrameInfo(); 7008 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 7009 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 7010 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 7011 DstAlignCanChange = true; 7012 bool IsZeroVal = 7013 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 7014 if (!TLI.findOptimalMemOpLowering( 7015 MemOps, TLI.getMaxStoresPerMemset(OptSize), 7016 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 7017 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 7018 return SDValue(); 7019 7020 if (DstAlignCanChange) { 7021 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 7022 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 7023 if (NewAlign > Alignment) { 7024 // Give the stack frame object a larger alignment if needed. 7025 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 7026 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 7027 Alignment = NewAlign; 7028 } 7029 } 7030 7031 SmallVector<SDValue, 8> OutChains; 7032 uint64_t DstOff = 0; 7033 unsigned NumMemOps = MemOps.size(); 7034 7035 // Find the largest store and generate the bit pattern for it. 7036 EVT LargestVT = MemOps[0]; 7037 for (unsigned i = 1; i < NumMemOps; i++) 7038 if (MemOps[i].bitsGT(LargestVT)) 7039 LargestVT = MemOps[i]; 7040 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 7041 7042 // Prepare AAInfo for loads/stores after lowering this memset. 7043 AAMDNodes NewAAInfo = AAInfo; 7044 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 7045 7046 for (unsigned i = 0; i < NumMemOps; i++) { 7047 EVT VT = MemOps[i]; 7048 unsigned VTSize = VT.getSizeInBits() / 8; 7049 if (VTSize > Size) { 7050 // Issuing an unaligned load / store pair that overlaps with the previous 7051 // pair. Adjust the offset accordingly. 7052 assert(i == NumMemOps-1 && i != 0); 7053 DstOff -= VTSize - Size; 7054 } 7055 7056 // If this store is smaller than the largest store see whether we can get 7057 // the smaller value for free with a truncate. 7058 SDValue Value = MemSetValue; 7059 if (VT.bitsLT(LargestVT)) { 7060 if (!LargestVT.isVector() && !VT.isVector() && 7061 TLI.isTruncateFree(LargestVT, VT)) 7062 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 7063 else 7064 Value = getMemsetValue(Src, VT, DAG, dl); 7065 } 7066 assert(Value.getValueType() == VT && "Value with wrong type."); 7067 SDValue Store = DAG.getStore( 7068 Chain, dl, Value, 7069 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 7070 DstPtrInfo.getWithOffset(DstOff), Alignment, 7071 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 7072 NewAAInfo); 7073 OutChains.push_back(Store); 7074 DstOff += VT.getSizeInBits() / 8; 7075 Size -= VTSize; 7076 } 7077 7078 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 7079 } 7080 7081 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 7082 unsigned AS) { 7083 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 7084 // pointer operands can be losslessly bitcasted to pointers of address space 0 7085 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 7086 report_fatal_error("cannot lower memory intrinsic in address space " + 7087 Twine(AS)); 7088 } 7089 } 7090 7091 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 7092 SDValue Src, SDValue Size, Align Alignment, 7093 bool isVol, bool AlwaysInline, bool isTailCall, 7094 MachinePointerInfo DstPtrInfo, 7095 MachinePointerInfo SrcPtrInfo, 7096 const AAMDNodes &AAInfo) { 7097 // Check to see if we should lower the memcpy to loads and stores first. 7098 // For cases within the target-specified limits, this is the best choice. 7099 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7100 if (ConstantSize) { 7101 // Memcpy with size zero? Just return the original chain. 7102 if (ConstantSize->isZero()) 7103 return Chain; 7104 7105 SDValue Result = getMemcpyLoadsAndStores( 7106 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7107 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7108 if (Result.getNode()) 7109 return Result; 7110 } 7111 7112 // Then check to see if we should lower the memcpy with target-specific 7113 // code. If the target chooses to do this, this is the next best. 7114 if (TSI) { 7115 SDValue Result = TSI->EmitTargetCodeForMemcpy( 7116 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 7117 DstPtrInfo, SrcPtrInfo); 7118 if (Result.getNode()) 7119 return Result; 7120 } 7121 7122 // If we really need inline code and the target declined to provide it, 7123 // use a (potentially long) sequence of loads and stores. 7124 if (AlwaysInline) { 7125 assert(ConstantSize && "AlwaysInline requires a constant size!"); 7126 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 7127 ConstantSize->getZExtValue(), Alignment, 7128 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 7129 } 7130 7131 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7132 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7133 7134 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 7135 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 7136 // respect volatile, so they may do things like read or write memory 7137 // beyond the given memory regions. But fixing this isn't easy, and most 7138 // people don't care. 7139 7140 // Emit a library call. 7141 TargetLowering::ArgListTy Args; 7142 TargetLowering::ArgListEntry Entry; 7143 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7144 Entry.Node = Dst; Args.push_back(Entry); 7145 Entry.Node = Src; Args.push_back(Entry); 7146 7147 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7148 Entry.Node = Size; Args.push_back(Entry); 7149 // FIXME: pass in SDLoc 7150 TargetLowering::CallLoweringInfo CLI(*this); 7151 CLI.setDebugLoc(dl) 7152 .setChain(Chain) 7153 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 7154 Dst.getValueType().getTypeForEVT(*getContext()), 7155 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 7156 TLI->getPointerTy(getDataLayout())), 7157 std::move(Args)) 7158 .setDiscardResult() 7159 .setTailCall(isTailCall); 7160 7161 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7162 return CallResult.second; 7163 } 7164 7165 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7166 SDValue Dst, unsigned DstAlign, 7167 SDValue Src, unsigned SrcAlign, 7168 SDValue Size, Type *SizeTy, 7169 unsigned ElemSz, bool isTailCall, 7170 MachinePointerInfo DstPtrInfo, 7171 MachinePointerInfo SrcPtrInfo) { 7172 // Emit a library call. 7173 TargetLowering::ArgListTy Args; 7174 TargetLowering::ArgListEntry Entry; 7175 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7176 Entry.Node = Dst; 7177 Args.push_back(Entry); 7178 7179 Entry.Node = Src; 7180 Args.push_back(Entry); 7181 7182 Entry.Ty = SizeTy; 7183 Entry.Node = Size; 7184 Args.push_back(Entry); 7185 7186 RTLIB::Libcall LibraryCall = 7187 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7188 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7189 report_fatal_error("Unsupported element size"); 7190 7191 TargetLowering::CallLoweringInfo CLI(*this); 7192 CLI.setDebugLoc(dl) 7193 .setChain(Chain) 7194 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7195 Type::getVoidTy(*getContext()), 7196 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7197 TLI->getPointerTy(getDataLayout())), 7198 std::move(Args)) 7199 .setDiscardResult() 7200 .setTailCall(isTailCall); 7201 7202 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7203 return CallResult.second; 7204 } 7205 7206 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7207 SDValue Src, SDValue Size, Align Alignment, 7208 bool isVol, bool isTailCall, 7209 MachinePointerInfo DstPtrInfo, 7210 MachinePointerInfo SrcPtrInfo, 7211 const AAMDNodes &AAInfo) { 7212 // Check to see if we should lower the memmove to loads and stores first. 7213 // For cases within the target-specified limits, this is the best choice. 7214 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7215 if (ConstantSize) { 7216 // Memmove with size zero? Just return the original chain. 7217 if (ConstantSize->isZero()) 7218 return Chain; 7219 7220 SDValue Result = getMemmoveLoadsAndStores( 7221 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7222 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7223 if (Result.getNode()) 7224 return Result; 7225 } 7226 7227 // Then check to see if we should lower the memmove with target-specific 7228 // code. If the target chooses to do this, this is the next best. 7229 if (TSI) { 7230 SDValue Result = 7231 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7232 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7233 if (Result.getNode()) 7234 return Result; 7235 } 7236 7237 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7238 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7239 7240 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7241 // not be safe. See memcpy above for more details. 7242 7243 // Emit a library call. 7244 TargetLowering::ArgListTy Args; 7245 TargetLowering::ArgListEntry Entry; 7246 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7247 Entry.Node = Dst; Args.push_back(Entry); 7248 Entry.Node = Src; Args.push_back(Entry); 7249 7250 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7251 Entry.Node = Size; Args.push_back(Entry); 7252 // FIXME: pass in SDLoc 7253 TargetLowering::CallLoweringInfo CLI(*this); 7254 CLI.setDebugLoc(dl) 7255 .setChain(Chain) 7256 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7257 Dst.getValueType().getTypeForEVT(*getContext()), 7258 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7259 TLI->getPointerTy(getDataLayout())), 7260 std::move(Args)) 7261 .setDiscardResult() 7262 .setTailCall(isTailCall); 7263 7264 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7265 return CallResult.second; 7266 } 7267 7268 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7269 SDValue Dst, unsigned DstAlign, 7270 SDValue Src, unsigned SrcAlign, 7271 SDValue Size, Type *SizeTy, 7272 unsigned ElemSz, bool isTailCall, 7273 MachinePointerInfo DstPtrInfo, 7274 MachinePointerInfo SrcPtrInfo) { 7275 // Emit a library call. 7276 TargetLowering::ArgListTy Args; 7277 TargetLowering::ArgListEntry Entry; 7278 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7279 Entry.Node = Dst; 7280 Args.push_back(Entry); 7281 7282 Entry.Node = Src; 7283 Args.push_back(Entry); 7284 7285 Entry.Ty = SizeTy; 7286 Entry.Node = Size; 7287 Args.push_back(Entry); 7288 7289 RTLIB::Libcall LibraryCall = 7290 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7291 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7292 report_fatal_error("Unsupported element size"); 7293 7294 TargetLowering::CallLoweringInfo CLI(*this); 7295 CLI.setDebugLoc(dl) 7296 .setChain(Chain) 7297 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7298 Type::getVoidTy(*getContext()), 7299 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7300 TLI->getPointerTy(getDataLayout())), 7301 std::move(Args)) 7302 .setDiscardResult() 7303 .setTailCall(isTailCall); 7304 7305 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7306 return CallResult.second; 7307 } 7308 7309 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7310 SDValue Src, SDValue Size, Align Alignment, 7311 bool isVol, bool isTailCall, 7312 MachinePointerInfo DstPtrInfo, 7313 const AAMDNodes &AAInfo) { 7314 // Check to see if we should lower the memset to stores first. 7315 // For cases within the target-specified limits, this is the best choice. 7316 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7317 if (ConstantSize) { 7318 // Memset with size zero? Just return the original chain. 7319 if (ConstantSize->isZero()) 7320 return Chain; 7321 7322 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7323 ConstantSize->getZExtValue(), Alignment, 7324 isVol, DstPtrInfo, AAInfo); 7325 7326 if (Result.getNode()) 7327 return Result; 7328 } 7329 7330 // Then check to see if we should lower the memset with target-specific 7331 // code. If the target chooses to do this, this is the next best. 7332 if (TSI) { 7333 SDValue Result = TSI->EmitTargetCodeForMemset( 7334 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7335 if (Result.getNode()) 7336 return Result; 7337 } 7338 7339 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7340 7341 // Emit a library call. 7342 TargetLowering::ArgListTy Args; 7343 TargetLowering::ArgListEntry Entry; 7344 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7345 Args.push_back(Entry); 7346 Entry.Node = Src; 7347 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7348 Args.push_back(Entry); 7349 Entry.Node = Size; 7350 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7351 Args.push_back(Entry); 7352 7353 // FIXME: pass in SDLoc 7354 TargetLowering::CallLoweringInfo CLI(*this); 7355 CLI.setDebugLoc(dl) 7356 .setChain(Chain) 7357 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7358 Dst.getValueType().getTypeForEVT(*getContext()), 7359 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7360 TLI->getPointerTy(getDataLayout())), 7361 std::move(Args)) 7362 .setDiscardResult() 7363 .setTailCall(isTailCall); 7364 7365 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7366 return CallResult.second; 7367 } 7368 7369 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7370 SDValue Dst, unsigned DstAlign, 7371 SDValue Value, SDValue Size, Type *SizeTy, 7372 unsigned ElemSz, bool isTailCall, 7373 MachinePointerInfo DstPtrInfo) { 7374 // Emit a library call. 7375 TargetLowering::ArgListTy Args; 7376 TargetLowering::ArgListEntry Entry; 7377 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7378 Entry.Node = Dst; 7379 Args.push_back(Entry); 7380 7381 Entry.Ty = Type::getInt8Ty(*getContext()); 7382 Entry.Node = Value; 7383 Args.push_back(Entry); 7384 7385 Entry.Ty = SizeTy; 7386 Entry.Node = Size; 7387 Args.push_back(Entry); 7388 7389 RTLIB::Libcall LibraryCall = 7390 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7391 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7392 report_fatal_error("Unsupported element size"); 7393 7394 TargetLowering::CallLoweringInfo CLI(*this); 7395 CLI.setDebugLoc(dl) 7396 .setChain(Chain) 7397 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7398 Type::getVoidTy(*getContext()), 7399 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7400 TLI->getPointerTy(getDataLayout())), 7401 std::move(Args)) 7402 .setDiscardResult() 7403 .setTailCall(isTailCall); 7404 7405 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7406 return CallResult.second; 7407 } 7408 7409 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7410 SDVTList VTList, ArrayRef<SDValue> Ops, 7411 MachineMemOperand *MMO) { 7412 FoldingSetNodeID ID; 7413 ID.AddInteger(MemVT.getRawBits()); 7414 AddNodeIDNode(ID, Opcode, VTList, Ops); 7415 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7416 ID.AddInteger(MMO->getFlags()); 7417 void* IP = nullptr; 7418 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7419 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7420 return SDValue(E, 0); 7421 } 7422 7423 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7424 VTList, MemVT, MMO); 7425 createOperands(N, Ops); 7426 7427 CSEMap.InsertNode(N, IP); 7428 InsertNode(N); 7429 return SDValue(N, 0); 7430 } 7431 7432 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7433 EVT MemVT, SDVTList VTs, SDValue Chain, 7434 SDValue Ptr, SDValue Cmp, SDValue Swp, 7435 MachineMemOperand *MMO) { 7436 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7437 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7438 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7439 7440 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7441 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7442 } 7443 7444 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7445 SDValue Chain, SDValue Ptr, SDValue Val, 7446 MachineMemOperand *MMO) { 7447 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7448 Opcode == ISD::ATOMIC_LOAD_SUB || 7449 Opcode == ISD::ATOMIC_LOAD_AND || 7450 Opcode == ISD::ATOMIC_LOAD_CLR || 7451 Opcode == ISD::ATOMIC_LOAD_OR || 7452 Opcode == ISD::ATOMIC_LOAD_XOR || 7453 Opcode == ISD::ATOMIC_LOAD_NAND || 7454 Opcode == ISD::ATOMIC_LOAD_MIN || 7455 Opcode == ISD::ATOMIC_LOAD_MAX || 7456 Opcode == ISD::ATOMIC_LOAD_UMIN || 7457 Opcode == ISD::ATOMIC_LOAD_UMAX || 7458 Opcode == ISD::ATOMIC_LOAD_FADD || 7459 Opcode == ISD::ATOMIC_LOAD_FSUB || 7460 Opcode == ISD::ATOMIC_SWAP || 7461 Opcode == ISD::ATOMIC_STORE) && 7462 "Invalid Atomic Op"); 7463 7464 EVT VT = Val.getValueType(); 7465 7466 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7467 getVTList(VT, MVT::Other); 7468 SDValue Ops[] = {Chain, Ptr, Val}; 7469 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7470 } 7471 7472 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7473 EVT VT, SDValue Chain, SDValue Ptr, 7474 MachineMemOperand *MMO) { 7475 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7476 7477 SDVTList VTs = getVTList(VT, MVT::Other); 7478 SDValue Ops[] = {Chain, Ptr}; 7479 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7480 } 7481 7482 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7483 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7484 if (Ops.size() == 1) 7485 return Ops[0]; 7486 7487 SmallVector<EVT, 4> VTs; 7488 VTs.reserve(Ops.size()); 7489 for (const SDValue &Op : Ops) 7490 VTs.push_back(Op.getValueType()); 7491 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7492 } 7493 7494 SDValue SelectionDAG::getMemIntrinsicNode( 7495 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7496 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7497 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7498 if (!Size && MemVT.isScalableVector()) 7499 Size = MemoryLocation::UnknownSize; 7500 else if (!Size) 7501 Size = MemVT.getStoreSize(); 7502 7503 MachineFunction &MF = getMachineFunction(); 7504 MachineMemOperand *MMO = 7505 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7506 7507 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7508 } 7509 7510 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7511 SDVTList VTList, 7512 ArrayRef<SDValue> Ops, EVT MemVT, 7513 MachineMemOperand *MMO) { 7514 assert((Opcode == ISD::INTRINSIC_VOID || 7515 Opcode == ISD::INTRINSIC_W_CHAIN || 7516 Opcode == ISD::PREFETCH || 7517 ((int)Opcode <= std::numeric_limits<int>::max() && 7518 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7519 "Opcode is not a memory-accessing opcode!"); 7520 7521 // Memoize the node unless it returns a flag. 7522 MemIntrinsicSDNode *N; 7523 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7524 FoldingSetNodeID ID; 7525 AddNodeIDNode(ID, Opcode, VTList, Ops); 7526 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7527 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7528 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7529 ID.AddInteger(MMO->getFlags()); 7530 void *IP = nullptr; 7531 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7532 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7533 return SDValue(E, 0); 7534 } 7535 7536 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7537 VTList, MemVT, MMO); 7538 createOperands(N, Ops); 7539 7540 CSEMap.InsertNode(N, IP); 7541 } else { 7542 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7543 VTList, MemVT, MMO); 7544 createOperands(N, Ops); 7545 } 7546 InsertNode(N); 7547 SDValue V(N, 0); 7548 NewSDValueDbgMsg(V, "Creating new node: ", this); 7549 return V; 7550 } 7551 7552 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7553 SDValue Chain, int FrameIndex, 7554 int64_t Size, int64_t Offset) { 7555 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7556 const auto VTs = getVTList(MVT::Other); 7557 SDValue Ops[2] = { 7558 Chain, 7559 getFrameIndex(FrameIndex, 7560 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7561 true)}; 7562 7563 FoldingSetNodeID ID; 7564 AddNodeIDNode(ID, Opcode, VTs, Ops); 7565 ID.AddInteger(FrameIndex); 7566 ID.AddInteger(Size); 7567 ID.AddInteger(Offset); 7568 void *IP = nullptr; 7569 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7570 return SDValue(E, 0); 7571 7572 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7573 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7574 createOperands(N, Ops); 7575 CSEMap.InsertNode(N, IP); 7576 InsertNode(N); 7577 SDValue V(N, 0); 7578 NewSDValueDbgMsg(V, "Creating new node: ", this); 7579 return V; 7580 } 7581 7582 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7583 uint64_t Guid, uint64_t Index, 7584 uint32_t Attr) { 7585 const unsigned Opcode = ISD::PSEUDO_PROBE; 7586 const auto VTs = getVTList(MVT::Other); 7587 SDValue Ops[] = {Chain}; 7588 FoldingSetNodeID ID; 7589 AddNodeIDNode(ID, Opcode, VTs, Ops); 7590 ID.AddInteger(Guid); 7591 ID.AddInteger(Index); 7592 void *IP = nullptr; 7593 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7594 return SDValue(E, 0); 7595 7596 auto *N = newSDNode<PseudoProbeSDNode>( 7597 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7598 createOperands(N, Ops); 7599 CSEMap.InsertNode(N, IP); 7600 InsertNode(N); 7601 SDValue V(N, 0); 7602 NewSDValueDbgMsg(V, "Creating new node: ", this); 7603 return V; 7604 } 7605 7606 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7607 /// MachinePointerInfo record from it. This is particularly useful because the 7608 /// code generator has many cases where it doesn't bother passing in a 7609 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7610 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7611 SelectionDAG &DAG, SDValue Ptr, 7612 int64_t Offset = 0) { 7613 // If this is FI+Offset, we can model it. 7614 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7615 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7616 FI->getIndex(), Offset); 7617 7618 // If this is (FI+Offset1)+Offset2, we can model it. 7619 if (Ptr.getOpcode() != ISD::ADD || 7620 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7621 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7622 return Info; 7623 7624 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7625 return MachinePointerInfo::getFixedStack( 7626 DAG.getMachineFunction(), FI, 7627 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7628 } 7629 7630 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7631 /// MachinePointerInfo record from it. This is particularly useful because the 7632 /// code generator has many cases where it doesn't bother passing in a 7633 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7634 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7635 SelectionDAG &DAG, SDValue Ptr, 7636 SDValue OffsetOp) { 7637 // If the 'Offset' value isn't a constant, we can't handle this. 7638 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7639 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7640 if (OffsetOp.isUndef()) 7641 return InferPointerInfo(Info, DAG, Ptr); 7642 return Info; 7643 } 7644 7645 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7646 EVT VT, const SDLoc &dl, SDValue Chain, 7647 SDValue Ptr, SDValue Offset, 7648 MachinePointerInfo PtrInfo, EVT MemVT, 7649 Align Alignment, 7650 MachineMemOperand::Flags MMOFlags, 7651 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7652 assert(Chain.getValueType() == MVT::Other && 7653 "Invalid chain type"); 7654 7655 MMOFlags |= MachineMemOperand::MOLoad; 7656 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7657 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7658 // clients. 7659 if (PtrInfo.V.isNull()) 7660 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7661 7662 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7663 MachineFunction &MF = getMachineFunction(); 7664 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7665 Alignment, AAInfo, Ranges); 7666 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7667 } 7668 7669 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7670 EVT VT, const SDLoc &dl, SDValue Chain, 7671 SDValue Ptr, SDValue Offset, EVT MemVT, 7672 MachineMemOperand *MMO) { 7673 if (VT == MemVT) { 7674 ExtType = ISD::NON_EXTLOAD; 7675 } else if (ExtType == ISD::NON_EXTLOAD) { 7676 assert(VT == MemVT && "Non-extending load from different memory type!"); 7677 } else { 7678 // Extending load. 7679 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7680 "Should only be an extending load, not truncating!"); 7681 assert(VT.isInteger() == MemVT.isInteger() && 7682 "Cannot convert from FP to Int or Int -> FP!"); 7683 assert(VT.isVector() == MemVT.isVector() && 7684 "Cannot use an ext load to convert to or from a vector!"); 7685 assert((!VT.isVector() || 7686 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7687 "Cannot use an ext load to change the number of vector elements!"); 7688 } 7689 7690 bool Indexed = AM != ISD::UNINDEXED; 7691 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7692 7693 SDVTList VTs = Indexed ? 7694 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7695 SDValue Ops[] = { Chain, Ptr, Offset }; 7696 FoldingSetNodeID ID; 7697 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7698 ID.AddInteger(MemVT.getRawBits()); 7699 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7700 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7701 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7702 ID.AddInteger(MMO->getFlags()); 7703 void *IP = nullptr; 7704 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7705 cast<LoadSDNode>(E)->refineAlignment(MMO); 7706 return SDValue(E, 0); 7707 } 7708 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7709 ExtType, MemVT, MMO); 7710 createOperands(N, Ops); 7711 7712 CSEMap.InsertNode(N, IP); 7713 InsertNode(N); 7714 SDValue V(N, 0); 7715 NewSDValueDbgMsg(V, "Creating new node: ", this); 7716 return V; 7717 } 7718 7719 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7720 SDValue Ptr, MachinePointerInfo PtrInfo, 7721 MaybeAlign Alignment, 7722 MachineMemOperand::Flags MMOFlags, 7723 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7724 SDValue Undef = getUNDEF(Ptr.getValueType()); 7725 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7726 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7727 } 7728 7729 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7730 SDValue Ptr, MachineMemOperand *MMO) { 7731 SDValue Undef = getUNDEF(Ptr.getValueType()); 7732 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7733 VT, MMO); 7734 } 7735 7736 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7737 EVT VT, SDValue Chain, SDValue Ptr, 7738 MachinePointerInfo PtrInfo, EVT MemVT, 7739 MaybeAlign Alignment, 7740 MachineMemOperand::Flags MMOFlags, 7741 const AAMDNodes &AAInfo) { 7742 SDValue Undef = getUNDEF(Ptr.getValueType()); 7743 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7744 MemVT, Alignment, MMOFlags, AAInfo); 7745 } 7746 7747 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7748 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7749 MachineMemOperand *MMO) { 7750 SDValue Undef = getUNDEF(Ptr.getValueType()); 7751 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7752 MemVT, MMO); 7753 } 7754 7755 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7756 SDValue Base, SDValue Offset, 7757 ISD::MemIndexedMode AM) { 7758 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7759 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7760 // Don't propagate the invariant or dereferenceable flags. 7761 auto MMOFlags = 7762 LD->getMemOperand()->getFlags() & 7763 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7764 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7765 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7766 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7767 } 7768 7769 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7770 SDValue Ptr, MachinePointerInfo PtrInfo, 7771 Align Alignment, 7772 MachineMemOperand::Flags MMOFlags, 7773 const AAMDNodes &AAInfo) { 7774 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7775 7776 MMOFlags |= MachineMemOperand::MOStore; 7777 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7778 7779 if (PtrInfo.V.isNull()) 7780 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7781 7782 MachineFunction &MF = getMachineFunction(); 7783 uint64_t Size = 7784 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7785 MachineMemOperand *MMO = 7786 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7787 return getStore(Chain, dl, Val, Ptr, MMO); 7788 } 7789 7790 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7791 SDValue Ptr, MachineMemOperand *MMO) { 7792 assert(Chain.getValueType() == MVT::Other && 7793 "Invalid chain type"); 7794 EVT VT = Val.getValueType(); 7795 SDVTList VTs = getVTList(MVT::Other); 7796 SDValue Undef = getUNDEF(Ptr.getValueType()); 7797 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7798 FoldingSetNodeID ID; 7799 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7800 ID.AddInteger(VT.getRawBits()); 7801 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7802 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7803 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7804 ID.AddInteger(MMO->getFlags()); 7805 void *IP = nullptr; 7806 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7807 cast<StoreSDNode>(E)->refineAlignment(MMO); 7808 return SDValue(E, 0); 7809 } 7810 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7811 ISD::UNINDEXED, false, VT, MMO); 7812 createOperands(N, Ops); 7813 7814 CSEMap.InsertNode(N, IP); 7815 InsertNode(N); 7816 SDValue V(N, 0); 7817 NewSDValueDbgMsg(V, "Creating new node: ", this); 7818 return V; 7819 } 7820 7821 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7822 SDValue Ptr, MachinePointerInfo PtrInfo, 7823 EVT SVT, Align Alignment, 7824 MachineMemOperand::Flags MMOFlags, 7825 const AAMDNodes &AAInfo) { 7826 assert(Chain.getValueType() == MVT::Other && 7827 "Invalid chain type"); 7828 7829 MMOFlags |= MachineMemOperand::MOStore; 7830 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7831 7832 if (PtrInfo.V.isNull()) 7833 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7834 7835 MachineFunction &MF = getMachineFunction(); 7836 MachineMemOperand *MMO = MF.getMachineMemOperand( 7837 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7838 Alignment, AAInfo); 7839 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7840 } 7841 7842 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7843 SDValue Ptr, EVT SVT, 7844 MachineMemOperand *MMO) { 7845 EVT VT = Val.getValueType(); 7846 7847 assert(Chain.getValueType() == MVT::Other && 7848 "Invalid chain type"); 7849 if (VT == SVT) 7850 return getStore(Chain, dl, Val, Ptr, MMO); 7851 7852 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7853 "Should only be a truncating store, not extending!"); 7854 assert(VT.isInteger() == SVT.isInteger() && 7855 "Can't do FP-INT conversion!"); 7856 assert(VT.isVector() == SVT.isVector() && 7857 "Cannot use trunc store to convert to or from a vector!"); 7858 assert((!VT.isVector() || 7859 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7860 "Cannot use trunc store to change the number of vector elements!"); 7861 7862 SDVTList VTs = getVTList(MVT::Other); 7863 SDValue Undef = getUNDEF(Ptr.getValueType()); 7864 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7865 FoldingSetNodeID ID; 7866 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7867 ID.AddInteger(SVT.getRawBits()); 7868 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7869 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7870 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7871 ID.AddInteger(MMO->getFlags()); 7872 void *IP = nullptr; 7873 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7874 cast<StoreSDNode>(E)->refineAlignment(MMO); 7875 return SDValue(E, 0); 7876 } 7877 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7878 ISD::UNINDEXED, true, SVT, MMO); 7879 createOperands(N, Ops); 7880 7881 CSEMap.InsertNode(N, IP); 7882 InsertNode(N); 7883 SDValue V(N, 0); 7884 NewSDValueDbgMsg(V, "Creating new node: ", this); 7885 return V; 7886 } 7887 7888 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7889 SDValue Base, SDValue Offset, 7890 ISD::MemIndexedMode AM) { 7891 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7892 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7893 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7894 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7895 FoldingSetNodeID ID; 7896 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7897 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7898 ID.AddInteger(ST->getRawSubclassData()); 7899 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7900 ID.AddInteger(ST->getMemOperand()->getFlags()); 7901 void *IP = nullptr; 7902 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7903 return SDValue(E, 0); 7904 7905 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7906 ST->isTruncatingStore(), ST->getMemoryVT(), 7907 ST->getMemOperand()); 7908 createOperands(N, Ops); 7909 7910 CSEMap.InsertNode(N, IP); 7911 InsertNode(N); 7912 SDValue V(N, 0); 7913 NewSDValueDbgMsg(V, "Creating new node: ", this); 7914 return V; 7915 } 7916 7917 SDValue SelectionDAG::getLoadVP( 7918 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7919 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7920 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7921 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7922 const MDNode *Ranges, bool IsExpanding) { 7923 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7924 7925 MMOFlags |= MachineMemOperand::MOLoad; 7926 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7927 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7928 // clients. 7929 if (PtrInfo.V.isNull()) 7930 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7931 7932 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7933 MachineFunction &MF = getMachineFunction(); 7934 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7935 Alignment, AAInfo, Ranges); 7936 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7937 MMO, IsExpanding); 7938 } 7939 7940 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7941 ISD::LoadExtType ExtType, EVT VT, 7942 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7943 SDValue Offset, SDValue Mask, SDValue EVL, 7944 EVT MemVT, MachineMemOperand *MMO, 7945 bool IsExpanding) { 7946 bool Indexed = AM != ISD::UNINDEXED; 7947 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7948 7949 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7950 : getVTList(VT, MVT::Other); 7951 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7952 FoldingSetNodeID ID; 7953 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7954 ID.AddInteger(VT.getRawBits()); 7955 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7956 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7957 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7958 ID.AddInteger(MMO->getFlags()); 7959 void *IP = nullptr; 7960 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7961 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7962 return SDValue(E, 0); 7963 } 7964 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7965 ExtType, IsExpanding, MemVT, MMO); 7966 createOperands(N, Ops); 7967 7968 CSEMap.InsertNode(N, IP); 7969 InsertNode(N); 7970 SDValue V(N, 0); 7971 NewSDValueDbgMsg(V, "Creating new node: ", this); 7972 return V; 7973 } 7974 7975 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7976 SDValue Ptr, SDValue Mask, SDValue EVL, 7977 MachinePointerInfo PtrInfo, 7978 MaybeAlign Alignment, 7979 MachineMemOperand::Flags MMOFlags, 7980 const AAMDNodes &AAInfo, const MDNode *Ranges, 7981 bool IsExpanding) { 7982 SDValue Undef = getUNDEF(Ptr.getValueType()); 7983 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7984 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7985 IsExpanding); 7986 } 7987 7988 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7989 SDValue Ptr, SDValue Mask, SDValue EVL, 7990 MachineMemOperand *MMO, bool IsExpanding) { 7991 SDValue Undef = getUNDEF(Ptr.getValueType()); 7992 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7993 Mask, EVL, VT, MMO, IsExpanding); 7994 } 7995 7996 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7997 EVT VT, SDValue Chain, SDValue Ptr, 7998 SDValue Mask, SDValue EVL, 7999 MachinePointerInfo PtrInfo, EVT MemVT, 8000 MaybeAlign Alignment, 8001 MachineMemOperand::Flags MMOFlags, 8002 const AAMDNodes &AAInfo, bool IsExpanding) { 8003 SDValue Undef = getUNDEF(Ptr.getValueType()); 8004 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8005 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 8006 IsExpanding); 8007 } 8008 8009 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 8010 EVT VT, SDValue Chain, SDValue Ptr, 8011 SDValue Mask, SDValue EVL, EVT MemVT, 8012 MachineMemOperand *MMO, bool IsExpanding) { 8013 SDValue Undef = getUNDEF(Ptr.getValueType()); 8014 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 8015 EVL, MemVT, MMO, IsExpanding); 8016 } 8017 8018 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 8019 SDValue Base, SDValue Offset, 8020 ISD::MemIndexedMode AM) { 8021 auto *LD = cast<VPLoadSDNode>(OrigLoad); 8022 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 8023 // Don't propagate the invariant or dereferenceable flags. 8024 auto MMOFlags = 8025 LD->getMemOperand()->getFlags() & 8026 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8027 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 8028 LD->getChain(), Base, Offset, LD->getMask(), 8029 LD->getVectorLength(), LD->getPointerInfo(), 8030 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 8031 nullptr, LD->isExpandingLoad()); 8032 } 8033 8034 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 8035 SDValue Ptr, SDValue Offset, SDValue Mask, 8036 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 8037 ISD::MemIndexedMode AM, bool IsTruncating, 8038 bool IsCompressing) { 8039 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8040 bool Indexed = AM != ISD::UNINDEXED; 8041 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8042 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8043 : getVTList(MVT::Other); 8044 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 8045 FoldingSetNodeID ID; 8046 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8047 ID.AddInteger(MemVT.getRawBits()); 8048 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8049 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8050 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8051 ID.AddInteger(MMO->getFlags()); 8052 void *IP = nullptr; 8053 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8054 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8055 return SDValue(E, 0); 8056 } 8057 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8058 IsTruncating, IsCompressing, MemVT, MMO); 8059 createOperands(N, Ops); 8060 8061 CSEMap.InsertNode(N, IP); 8062 InsertNode(N); 8063 SDValue V(N, 0); 8064 NewSDValueDbgMsg(V, "Creating new node: ", this); 8065 return V; 8066 } 8067 8068 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8069 SDValue Val, SDValue Ptr, SDValue Mask, 8070 SDValue EVL, MachinePointerInfo PtrInfo, 8071 EVT SVT, Align Alignment, 8072 MachineMemOperand::Flags MMOFlags, 8073 const AAMDNodes &AAInfo, 8074 bool IsCompressing) { 8075 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8076 8077 MMOFlags |= MachineMemOperand::MOStore; 8078 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8079 8080 if (PtrInfo.V.isNull()) 8081 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8082 8083 MachineFunction &MF = getMachineFunction(); 8084 MachineMemOperand *MMO = MF.getMachineMemOperand( 8085 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 8086 Alignment, AAInfo); 8087 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 8088 IsCompressing); 8089 } 8090 8091 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 8092 SDValue Val, SDValue Ptr, SDValue Mask, 8093 SDValue EVL, EVT SVT, 8094 MachineMemOperand *MMO, 8095 bool IsCompressing) { 8096 EVT VT = Val.getValueType(); 8097 8098 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8099 if (VT == SVT) 8100 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 8101 EVL, VT, MMO, ISD::UNINDEXED, 8102 /*IsTruncating*/ false, IsCompressing); 8103 8104 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8105 "Should only be a truncating store, not extending!"); 8106 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8107 assert(VT.isVector() == SVT.isVector() && 8108 "Cannot use trunc store to convert to or from a vector!"); 8109 assert((!VT.isVector() || 8110 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8111 "Cannot use trunc store to change the number of vector elements!"); 8112 8113 SDVTList VTs = getVTList(MVT::Other); 8114 SDValue Undef = getUNDEF(Ptr.getValueType()); 8115 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 8116 FoldingSetNodeID ID; 8117 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8118 ID.AddInteger(SVT.getRawBits()); 8119 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 8120 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8121 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8122 ID.AddInteger(MMO->getFlags()); 8123 void *IP = nullptr; 8124 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8125 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 8126 return SDValue(E, 0); 8127 } 8128 auto *N = 8129 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8130 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 8131 createOperands(N, Ops); 8132 8133 CSEMap.InsertNode(N, IP); 8134 InsertNode(N); 8135 SDValue V(N, 0); 8136 NewSDValueDbgMsg(V, "Creating new node: ", this); 8137 return V; 8138 } 8139 8140 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 8141 SDValue Base, SDValue Offset, 8142 ISD::MemIndexedMode AM) { 8143 auto *ST = cast<VPStoreSDNode>(OrigStore); 8144 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 8145 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8146 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 8147 Offset, ST->getMask(), ST->getVectorLength()}; 8148 FoldingSetNodeID ID; 8149 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 8150 ID.AddInteger(ST->getMemoryVT().getRawBits()); 8151 ID.AddInteger(ST->getRawSubclassData()); 8152 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 8153 ID.AddInteger(ST->getMemOperand()->getFlags()); 8154 void *IP = nullptr; 8155 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 8156 return SDValue(E, 0); 8157 8158 auto *N = newSDNode<VPStoreSDNode>( 8159 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 8160 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 8161 createOperands(N, Ops); 8162 8163 CSEMap.InsertNode(N, IP); 8164 InsertNode(N); 8165 SDValue V(N, 0); 8166 NewSDValueDbgMsg(V, "Creating new node: ", this); 8167 return V; 8168 } 8169 8170 SDValue SelectionDAG::getStridedLoadVP( 8171 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8172 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8173 SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 8174 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8175 const MDNode *Ranges, bool IsExpanding) { 8176 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8177 8178 MMOFlags |= MachineMemOperand::MOLoad; 8179 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 8180 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 8181 // clients. 8182 if (PtrInfo.V.isNull()) 8183 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 8184 8185 uint64_t Size = MemoryLocation::UnknownSize; 8186 MachineFunction &MF = getMachineFunction(); 8187 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 8188 Alignment, AAInfo, Ranges); 8189 return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask, 8190 EVL, MemVT, MMO, IsExpanding); 8191 } 8192 8193 SDValue SelectionDAG::getStridedLoadVP( 8194 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, 8195 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, 8196 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) { 8197 bool Indexed = AM != ISD::UNINDEXED; 8198 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 8199 8200 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL}; 8201 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 8202 : getVTList(VT, MVT::Other); 8203 FoldingSetNodeID ID; 8204 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops); 8205 ID.AddInteger(VT.getRawBits()); 8206 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>( 8207 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 8208 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8209 8210 void *IP = nullptr; 8211 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8212 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO); 8213 return SDValue(E, 0); 8214 } 8215 8216 auto *N = 8217 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM, 8218 ExtType, IsExpanding, MemVT, MMO); 8219 createOperands(N, Ops); 8220 CSEMap.InsertNode(N, IP); 8221 InsertNode(N); 8222 SDValue V(N, 0); 8223 NewSDValueDbgMsg(V, "Creating new node: ", this); 8224 return V; 8225 } 8226 8227 SDValue SelectionDAG::getStridedLoadVP( 8228 EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride, 8229 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment, 8230 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8231 const MDNode *Ranges, bool IsExpanding) { 8232 SDValue Undef = getUNDEF(Ptr.getValueType()); 8233 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8234 Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment, 8235 MMOFlags, AAInfo, Ranges, IsExpanding); 8236 } 8237 8238 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain, 8239 SDValue Ptr, SDValue Stride, 8240 SDValue Mask, SDValue EVL, 8241 MachineMemOperand *MMO, 8242 bool IsExpanding) { 8243 SDValue Undef = getUNDEF(Ptr.getValueType()); 8244 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr, 8245 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding); 8246 } 8247 8248 SDValue SelectionDAG::getExtStridedLoadVP( 8249 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8250 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, 8251 MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, 8252 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8253 bool IsExpanding) { 8254 SDValue Undef = getUNDEF(Ptr.getValueType()); 8255 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8256 Stride, Mask, EVL, PtrInfo, MemVT, Alignment, 8257 MMOFlags, AAInfo, nullptr, IsExpanding); 8258 } 8259 8260 SDValue SelectionDAG::getExtStridedLoadVP( 8261 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, 8262 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, 8263 MachineMemOperand *MMO, bool IsExpanding) { 8264 SDValue Undef = getUNDEF(Ptr.getValueType()); 8265 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef, 8266 Stride, Mask, EVL, MemVT, MMO, IsExpanding); 8267 } 8268 8269 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL, 8270 SDValue Base, SDValue Offset, 8271 ISD::MemIndexedMode AM) { 8272 auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad); 8273 assert(SLD->getOffset().isUndef() && 8274 "Strided load is already a indexed load!"); 8275 // Don't propagate the invariant or dereferenceable flags. 8276 auto MMOFlags = 8277 SLD->getMemOperand()->getFlags() & 8278 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 8279 return getStridedLoadVP( 8280 AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(), 8281 Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(), 8282 SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags, 8283 SLD->getAAInfo(), nullptr, SLD->isExpandingLoad()); 8284 } 8285 8286 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL, 8287 SDValue Val, SDValue Ptr, 8288 SDValue Offset, SDValue Stride, 8289 SDValue Mask, SDValue EVL, EVT MemVT, 8290 MachineMemOperand *MMO, 8291 ISD::MemIndexedMode AM, 8292 bool IsTruncating, bool IsCompressing) { 8293 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8294 bool Indexed = AM != ISD::UNINDEXED; 8295 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 8296 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 8297 : getVTList(MVT::Other); 8298 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL}; 8299 FoldingSetNodeID ID; 8300 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8301 ID.AddInteger(MemVT.getRawBits()); 8302 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8303 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8304 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8305 void *IP = nullptr; 8306 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8307 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8308 return SDValue(E, 0); 8309 } 8310 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8311 VTs, AM, IsTruncating, 8312 IsCompressing, MemVT, MMO); 8313 createOperands(N, Ops); 8314 8315 CSEMap.InsertNode(N, IP); 8316 InsertNode(N); 8317 SDValue V(N, 0); 8318 NewSDValueDbgMsg(V, "Creating new node: ", this); 8319 return V; 8320 } 8321 8322 SDValue SelectionDAG::getTruncStridedStoreVP( 8323 SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, 8324 SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, 8325 Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 8326 bool IsCompressing) { 8327 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8328 8329 MMOFlags |= MachineMemOperand::MOStore; 8330 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 8331 8332 if (PtrInfo.V.isNull()) 8333 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 8334 8335 MachineFunction &MF = getMachineFunction(); 8336 MachineMemOperand *MMO = MF.getMachineMemOperand( 8337 PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo); 8338 return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT, 8339 MMO, IsCompressing); 8340 } 8341 8342 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, 8343 SDValue Val, SDValue Ptr, 8344 SDValue Stride, SDValue Mask, 8345 SDValue EVL, EVT SVT, 8346 MachineMemOperand *MMO, 8347 bool IsCompressing) { 8348 EVT VT = Val.getValueType(); 8349 8350 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 8351 if (VT == SVT) 8352 return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()), 8353 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED, 8354 /*IsTruncating*/ false, IsCompressing); 8355 8356 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 8357 "Should only be a truncating store, not extending!"); 8358 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 8359 assert(VT.isVector() == SVT.isVector() && 8360 "Cannot use trunc store to convert to or from a vector!"); 8361 assert((!VT.isVector() || 8362 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 8363 "Cannot use trunc store to change the number of vector elements!"); 8364 8365 SDVTList VTs = getVTList(MVT::Other); 8366 SDValue Undef = getUNDEF(Ptr.getValueType()); 8367 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL}; 8368 FoldingSetNodeID ID; 8369 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8370 ID.AddInteger(SVT.getRawBits()); 8371 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>( 8372 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 8373 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8374 void *IP = nullptr; 8375 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8376 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO); 8377 return SDValue(E, 0); 8378 } 8379 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(), 8380 VTs, ISD::UNINDEXED, true, 8381 IsCompressing, SVT, MMO); 8382 createOperands(N, Ops); 8383 8384 CSEMap.InsertNode(N, IP); 8385 InsertNode(N); 8386 SDValue V(N, 0); 8387 NewSDValueDbgMsg(V, "Creating new node: ", this); 8388 return V; 8389 } 8390 8391 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore, 8392 const SDLoc &DL, SDValue Base, 8393 SDValue Offset, 8394 ISD::MemIndexedMode AM) { 8395 auto *SST = cast<VPStridedStoreSDNode>(OrigStore); 8396 assert(SST->getOffset().isUndef() && 8397 "Strided store is already an indexed store!"); 8398 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 8399 SDValue Ops[] = { 8400 SST->getChain(), SST->getValue(), Base, Offset, SST->getStride(), 8401 SST->getMask(), SST->getVectorLength()}; 8402 FoldingSetNodeID ID; 8403 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops); 8404 ID.AddInteger(SST->getMemoryVT().getRawBits()); 8405 ID.AddInteger(SST->getRawSubclassData()); 8406 ID.AddInteger(SST->getPointerInfo().getAddrSpace()); 8407 void *IP = nullptr; 8408 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8409 return SDValue(E, 0); 8410 8411 auto *N = newSDNode<VPStridedStoreSDNode>( 8412 DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(), 8413 SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand()); 8414 createOperands(N, Ops); 8415 8416 CSEMap.InsertNode(N, IP); 8417 InsertNode(N); 8418 SDValue V(N, 0); 8419 NewSDValueDbgMsg(V, "Creating new node: ", this); 8420 return V; 8421 } 8422 8423 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8424 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8425 ISD::MemIndexType IndexType) { 8426 assert(Ops.size() == 6 && "Incompatible number of operands"); 8427 8428 FoldingSetNodeID ID; 8429 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8430 ID.AddInteger(VT.getRawBits()); 8431 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8432 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8433 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8434 ID.AddInteger(MMO->getFlags()); 8435 void *IP = nullptr; 8436 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8437 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8438 return SDValue(E, 0); 8439 } 8440 8441 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8442 VT, MMO, IndexType); 8443 createOperands(N, Ops); 8444 8445 assert(N->getMask().getValueType().getVectorElementCount() == 8446 N->getValueType(0).getVectorElementCount() && 8447 "Vector width mismatch between mask and data"); 8448 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8449 N->getValueType(0).getVectorElementCount().isScalable() && 8450 "Scalable flags of index and data do not match"); 8451 assert(ElementCount::isKnownGE( 8452 N->getIndex().getValueType().getVectorElementCount(), 8453 N->getValueType(0).getVectorElementCount()) && 8454 "Vector width mismatch between index and data"); 8455 assert(isa<ConstantSDNode>(N->getScale()) && 8456 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8457 "Scale should be a constant power of 2"); 8458 8459 CSEMap.InsertNode(N, IP); 8460 InsertNode(N); 8461 SDValue V(N, 0); 8462 NewSDValueDbgMsg(V, "Creating new node: ", this); 8463 return V; 8464 } 8465 8466 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8467 ArrayRef<SDValue> Ops, 8468 MachineMemOperand *MMO, 8469 ISD::MemIndexType IndexType) { 8470 assert(Ops.size() == 7 && "Incompatible number of operands"); 8471 8472 FoldingSetNodeID ID; 8473 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8474 ID.AddInteger(VT.getRawBits()); 8475 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8476 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8477 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8478 ID.AddInteger(MMO->getFlags()); 8479 void *IP = nullptr; 8480 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8481 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8482 return SDValue(E, 0); 8483 } 8484 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8485 VT, MMO, IndexType); 8486 createOperands(N, Ops); 8487 8488 assert(N->getMask().getValueType().getVectorElementCount() == 8489 N->getValue().getValueType().getVectorElementCount() && 8490 "Vector width mismatch between mask and data"); 8491 assert( 8492 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8493 N->getValue().getValueType().getVectorElementCount().isScalable() && 8494 "Scalable flags of index and data do not match"); 8495 assert(ElementCount::isKnownGE( 8496 N->getIndex().getValueType().getVectorElementCount(), 8497 N->getValue().getValueType().getVectorElementCount()) && 8498 "Vector width mismatch between index and data"); 8499 assert(isa<ConstantSDNode>(N->getScale()) && 8500 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8501 "Scale should be a constant power of 2"); 8502 8503 CSEMap.InsertNode(N, IP); 8504 InsertNode(N); 8505 SDValue V(N, 0); 8506 NewSDValueDbgMsg(V, "Creating new node: ", this); 8507 return V; 8508 } 8509 8510 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8511 SDValue Base, SDValue Offset, SDValue Mask, 8512 SDValue PassThru, EVT MemVT, 8513 MachineMemOperand *MMO, 8514 ISD::MemIndexedMode AM, 8515 ISD::LoadExtType ExtTy, bool isExpanding) { 8516 bool Indexed = AM != ISD::UNINDEXED; 8517 assert((Indexed || Offset.isUndef()) && 8518 "Unindexed masked load with an offset!"); 8519 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8520 : getVTList(VT, MVT::Other); 8521 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8522 FoldingSetNodeID ID; 8523 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8524 ID.AddInteger(MemVT.getRawBits()); 8525 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8526 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8527 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8528 ID.AddInteger(MMO->getFlags()); 8529 void *IP = nullptr; 8530 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8531 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8532 return SDValue(E, 0); 8533 } 8534 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8535 AM, ExtTy, isExpanding, MemVT, MMO); 8536 createOperands(N, Ops); 8537 8538 CSEMap.InsertNode(N, IP); 8539 InsertNode(N); 8540 SDValue V(N, 0); 8541 NewSDValueDbgMsg(V, "Creating new node: ", this); 8542 return V; 8543 } 8544 8545 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8546 SDValue Base, SDValue Offset, 8547 ISD::MemIndexedMode AM) { 8548 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8549 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8550 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8551 Offset, LD->getMask(), LD->getPassThru(), 8552 LD->getMemoryVT(), LD->getMemOperand(), AM, 8553 LD->getExtensionType(), LD->isExpandingLoad()); 8554 } 8555 8556 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8557 SDValue Val, SDValue Base, SDValue Offset, 8558 SDValue Mask, EVT MemVT, 8559 MachineMemOperand *MMO, 8560 ISD::MemIndexedMode AM, bool IsTruncating, 8561 bool IsCompressing) { 8562 assert(Chain.getValueType() == MVT::Other && 8563 "Invalid chain type"); 8564 bool Indexed = AM != ISD::UNINDEXED; 8565 assert((Indexed || Offset.isUndef()) && 8566 "Unindexed masked store with an offset!"); 8567 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8568 : getVTList(MVT::Other); 8569 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8570 FoldingSetNodeID ID; 8571 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8572 ID.AddInteger(MemVT.getRawBits()); 8573 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8574 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8575 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8576 ID.AddInteger(MMO->getFlags()); 8577 void *IP = nullptr; 8578 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8579 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8580 return SDValue(E, 0); 8581 } 8582 auto *N = 8583 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8584 IsTruncating, IsCompressing, MemVT, MMO); 8585 createOperands(N, Ops); 8586 8587 CSEMap.InsertNode(N, IP); 8588 InsertNode(N); 8589 SDValue V(N, 0); 8590 NewSDValueDbgMsg(V, "Creating new node: ", this); 8591 return V; 8592 } 8593 8594 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8595 SDValue Base, SDValue Offset, 8596 ISD::MemIndexedMode AM) { 8597 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8598 assert(ST->getOffset().isUndef() && 8599 "Masked store is already a indexed store!"); 8600 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8601 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8602 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8603 } 8604 8605 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8606 ArrayRef<SDValue> Ops, 8607 MachineMemOperand *MMO, 8608 ISD::MemIndexType IndexType, 8609 ISD::LoadExtType ExtTy) { 8610 assert(Ops.size() == 6 && "Incompatible number of operands"); 8611 8612 FoldingSetNodeID ID; 8613 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8614 ID.AddInteger(MemVT.getRawBits()); 8615 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8616 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8617 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8618 ID.AddInteger(MMO->getFlags()); 8619 void *IP = nullptr; 8620 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8621 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8622 return SDValue(E, 0); 8623 } 8624 8625 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8626 VTs, MemVT, MMO, IndexType, ExtTy); 8627 createOperands(N, Ops); 8628 8629 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8630 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8631 assert(N->getMask().getValueType().getVectorElementCount() == 8632 N->getValueType(0).getVectorElementCount() && 8633 "Vector width mismatch between mask and data"); 8634 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8635 N->getValueType(0).getVectorElementCount().isScalable() && 8636 "Scalable flags of index and data do not match"); 8637 assert(ElementCount::isKnownGE( 8638 N->getIndex().getValueType().getVectorElementCount(), 8639 N->getValueType(0).getVectorElementCount()) && 8640 "Vector width mismatch between index and data"); 8641 assert(isa<ConstantSDNode>(N->getScale()) && 8642 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8643 "Scale should be a constant power of 2"); 8644 8645 CSEMap.InsertNode(N, IP); 8646 InsertNode(N); 8647 SDValue V(N, 0); 8648 NewSDValueDbgMsg(V, "Creating new node: ", this); 8649 return V; 8650 } 8651 8652 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8653 ArrayRef<SDValue> Ops, 8654 MachineMemOperand *MMO, 8655 ISD::MemIndexType IndexType, 8656 bool IsTrunc) { 8657 assert(Ops.size() == 6 && "Incompatible number of operands"); 8658 8659 FoldingSetNodeID ID; 8660 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8661 ID.AddInteger(MemVT.getRawBits()); 8662 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8663 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8664 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8665 ID.AddInteger(MMO->getFlags()); 8666 void *IP = nullptr; 8667 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8668 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8669 return SDValue(E, 0); 8670 } 8671 8672 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8673 VTs, MemVT, MMO, IndexType, IsTrunc); 8674 createOperands(N, Ops); 8675 8676 assert(N->getMask().getValueType().getVectorElementCount() == 8677 N->getValue().getValueType().getVectorElementCount() && 8678 "Vector width mismatch between mask and data"); 8679 assert( 8680 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8681 N->getValue().getValueType().getVectorElementCount().isScalable() && 8682 "Scalable flags of index and data do not match"); 8683 assert(ElementCount::isKnownGE( 8684 N->getIndex().getValueType().getVectorElementCount(), 8685 N->getValue().getValueType().getVectorElementCount()) && 8686 "Vector width mismatch between index and data"); 8687 assert(isa<ConstantSDNode>(N->getScale()) && 8688 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8689 "Scale should be a constant power of 2"); 8690 8691 CSEMap.InsertNode(N, IP); 8692 InsertNode(N); 8693 SDValue V(N, 0); 8694 NewSDValueDbgMsg(V, "Creating new node: ", this); 8695 return V; 8696 } 8697 8698 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8699 // select undef, T, F --> T (if T is a constant), otherwise F 8700 // select, ?, undef, F --> F 8701 // select, ?, T, undef --> T 8702 if (Cond.isUndef()) 8703 return isConstantValueOfAnyType(T) ? T : F; 8704 if (T.isUndef()) 8705 return F; 8706 if (F.isUndef()) 8707 return T; 8708 8709 // select true, T, F --> T 8710 // select false, T, F --> F 8711 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8712 return CondC->isZero() ? F : T; 8713 8714 // TODO: This should simplify VSELECT with constant condition using something 8715 // like this (but check boolean contents to be complete?): 8716 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8717 // return T; 8718 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8719 // return F; 8720 8721 // select ?, T, T --> T 8722 if (T == F) 8723 return T; 8724 8725 return SDValue(); 8726 } 8727 8728 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8729 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8730 if (X.isUndef()) 8731 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8732 // shift X, undef --> undef (because it may shift by the bitwidth) 8733 if (Y.isUndef()) 8734 return getUNDEF(X.getValueType()); 8735 8736 // shift 0, Y --> 0 8737 // shift X, 0 --> X 8738 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8739 return X; 8740 8741 // shift X, C >= bitwidth(X) --> undef 8742 // All vector elements must be too big (or undef) to avoid partial undefs. 8743 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8744 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8745 }; 8746 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8747 return getUNDEF(X.getValueType()); 8748 8749 return SDValue(); 8750 } 8751 8752 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8753 SDNodeFlags Flags) { 8754 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8755 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8756 // operation is poison. That result can be relaxed to undef. 8757 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8758 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8759 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8760 (YC && YC->getValueAPF().isNaN()); 8761 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8762 (YC && YC->getValueAPF().isInfinity()); 8763 8764 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8765 return getUNDEF(X.getValueType()); 8766 8767 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8768 return getUNDEF(X.getValueType()); 8769 8770 if (!YC) 8771 return SDValue(); 8772 8773 // X + -0.0 --> X 8774 if (Opcode == ISD::FADD) 8775 if (YC->getValueAPF().isNegZero()) 8776 return X; 8777 8778 // X - +0.0 --> X 8779 if (Opcode == ISD::FSUB) 8780 if (YC->getValueAPF().isPosZero()) 8781 return X; 8782 8783 // X * 1.0 --> X 8784 // X / 1.0 --> X 8785 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8786 if (YC->getValueAPF().isExactlyValue(1.0)) 8787 return X; 8788 8789 // X * 0.0 --> 0.0 8790 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8791 if (YC->getValueAPF().isZero()) 8792 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8793 8794 return SDValue(); 8795 } 8796 8797 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8798 SDValue Ptr, SDValue SV, unsigned Align) { 8799 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8800 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8801 } 8802 8803 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8804 ArrayRef<SDUse> Ops) { 8805 switch (Ops.size()) { 8806 case 0: return getNode(Opcode, DL, VT); 8807 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8808 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8809 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8810 default: break; 8811 } 8812 8813 // Copy from an SDUse array into an SDValue array for use with 8814 // the regular getNode logic. 8815 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8816 return getNode(Opcode, DL, VT, NewOps); 8817 } 8818 8819 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8820 ArrayRef<SDValue> Ops) { 8821 SDNodeFlags Flags; 8822 if (Inserter) 8823 Flags = Inserter->getFlags(); 8824 return getNode(Opcode, DL, VT, Ops, Flags); 8825 } 8826 8827 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8828 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8829 unsigned NumOps = Ops.size(); 8830 switch (NumOps) { 8831 case 0: return getNode(Opcode, DL, VT); 8832 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8833 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8834 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8835 default: break; 8836 } 8837 8838 #ifndef NDEBUG 8839 for (auto &Op : Ops) 8840 assert(Op.getOpcode() != ISD::DELETED_NODE && 8841 "Operand is DELETED_NODE!"); 8842 #endif 8843 8844 switch (Opcode) { 8845 default: break; 8846 case ISD::BUILD_VECTOR: 8847 // Attempt to simplify BUILD_VECTOR. 8848 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8849 return V; 8850 break; 8851 case ISD::CONCAT_VECTORS: 8852 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8853 return V; 8854 break; 8855 case ISD::SELECT_CC: 8856 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8857 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8858 "LHS and RHS of condition must have same type!"); 8859 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8860 "True and False arms of SelectCC must have same type!"); 8861 assert(Ops[2].getValueType() == VT && 8862 "select_cc node must be of same type as true and false value!"); 8863 break; 8864 case ISD::BR_CC: 8865 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8866 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8867 "LHS/RHS of comparison should match types!"); 8868 break; 8869 case ISD::VP_ADD: 8870 case ISD::VP_SUB: 8871 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR 8872 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8873 Opcode = ISD::VP_XOR; 8874 break; 8875 case ISD::VP_MUL: 8876 // If it is VP_MUL mask operation then turn it to VP_AND 8877 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 8878 Opcode = ISD::VP_AND; 8879 break; 8880 case ISD::VP_REDUCE_MUL: 8881 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND 8882 if (VT == MVT::i1) 8883 Opcode = ISD::VP_REDUCE_AND; 8884 break; 8885 case ISD::VP_REDUCE_ADD: 8886 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR 8887 if (VT == MVT::i1) 8888 Opcode = ISD::VP_REDUCE_XOR; 8889 break; 8890 case ISD::VP_REDUCE_SMAX: 8891 case ISD::VP_REDUCE_UMIN: 8892 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to 8893 // VP_REDUCE_AND. 8894 if (VT == MVT::i1) 8895 Opcode = ISD::VP_REDUCE_AND; 8896 break; 8897 case ISD::VP_REDUCE_SMIN: 8898 case ISD::VP_REDUCE_UMAX: 8899 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to 8900 // VP_REDUCE_OR. 8901 if (VT == MVT::i1) 8902 Opcode = ISD::VP_REDUCE_OR; 8903 break; 8904 } 8905 8906 // Memoize nodes. 8907 SDNode *N; 8908 SDVTList VTs = getVTList(VT); 8909 8910 if (VT != MVT::Glue) { 8911 FoldingSetNodeID ID; 8912 AddNodeIDNode(ID, Opcode, VTs, Ops); 8913 void *IP = nullptr; 8914 8915 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8916 return SDValue(E, 0); 8917 8918 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8919 createOperands(N, Ops); 8920 8921 CSEMap.InsertNode(N, IP); 8922 } else { 8923 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8924 createOperands(N, Ops); 8925 } 8926 8927 N->setFlags(Flags); 8928 InsertNode(N); 8929 SDValue V(N, 0); 8930 NewSDValueDbgMsg(V, "Creating new node: ", this); 8931 return V; 8932 } 8933 8934 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8935 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8936 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8937 } 8938 8939 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8940 ArrayRef<SDValue> Ops) { 8941 SDNodeFlags Flags; 8942 if (Inserter) 8943 Flags = Inserter->getFlags(); 8944 return getNode(Opcode, DL, VTList, Ops, Flags); 8945 } 8946 8947 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8948 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8949 if (VTList.NumVTs == 1) 8950 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags); 8951 8952 #ifndef NDEBUG 8953 for (auto &Op : Ops) 8954 assert(Op.getOpcode() != ISD::DELETED_NODE && 8955 "Operand is DELETED_NODE!"); 8956 #endif 8957 8958 switch (Opcode) { 8959 case ISD::STRICT_FP_EXTEND: 8960 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8961 "Invalid STRICT_FP_EXTEND!"); 8962 assert(VTList.VTs[0].isFloatingPoint() && 8963 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8964 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8965 "STRICT_FP_EXTEND result type should be vector iff the operand " 8966 "type is vector!"); 8967 assert((!VTList.VTs[0].isVector() || 8968 VTList.VTs[0].getVectorNumElements() == 8969 Ops[1].getValueType().getVectorNumElements()) && 8970 "Vector element count mismatch!"); 8971 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8972 "Invalid fpext node, dst <= src!"); 8973 break; 8974 case ISD::STRICT_FP_ROUND: 8975 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8976 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8977 "STRICT_FP_ROUND result type should be vector iff the operand " 8978 "type is vector!"); 8979 assert((!VTList.VTs[0].isVector() || 8980 VTList.VTs[0].getVectorNumElements() == 8981 Ops[1].getValueType().getVectorNumElements()) && 8982 "Vector element count mismatch!"); 8983 assert(VTList.VTs[0].isFloatingPoint() && 8984 Ops[1].getValueType().isFloatingPoint() && 8985 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8986 isa<ConstantSDNode>(Ops[2]) && 8987 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8988 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8989 "Invalid STRICT_FP_ROUND!"); 8990 break; 8991 #if 0 8992 // FIXME: figure out how to safely handle things like 8993 // int foo(int x) { return 1 << (x & 255); } 8994 // int bar() { return foo(256); } 8995 case ISD::SRA_PARTS: 8996 case ISD::SRL_PARTS: 8997 case ISD::SHL_PARTS: 8998 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8999 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 9000 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9001 else if (N3.getOpcode() == ISD::AND) 9002 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 9003 // If the and is only masking out bits that cannot effect the shift, 9004 // eliminate the and. 9005 unsigned NumBits = VT.getScalarSizeInBits()*2; 9006 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 9007 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 9008 } 9009 break; 9010 #endif 9011 } 9012 9013 // Memoize the node unless it returns a flag. 9014 SDNode *N; 9015 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 9016 FoldingSetNodeID ID; 9017 AddNodeIDNode(ID, Opcode, VTList, Ops); 9018 void *IP = nullptr; 9019 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 9020 return SDValue(E, 0); 9021 9022 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9023 createOperands(N, Ops); 9024 CSEMap.InsertNode(N, IP); 9025 } else { 9026 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 9027 createOperands(N, Ops); 9028 } 9029 9030 N->setFlags(Flags); 9031 InsertNode(N); 9032 SDValue V(N, 0); 9033 NewSDValueDbgMsg(V, "Creating new node: ", this); 9034 return V; 9035 } 9036 9037 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 9038 SDVTList VTList) { 9039 return getNode(Opcode, DL, VTList, None); 9040 } 9041 9042 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9043 SDValue N1) { 9044 SDValue Ops[] = { N1 }; 9045 return getNode(Opcode, DL, VTList, Ops); 9046 } 9047 9048 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9049 SDValue N1, SDValue N2) { 9050 SDValue Ops[] = { N1, N2 }; 9051 return getNode(Opcode, DL, VTList, Ops); 9052 } 9053 9054 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9055 SDValue N1, SDValue N2, SDValue N3) { 9056 SDValue Ops[] = { N1, N2, N3 }; 9057 return getNode(Opcode, DL, VTList, Ops); 9058 } 9059 9060 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9061 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 9062 SDValue Ops[] = { N1, N2, N3, N4 }; 9063 return getNode(Opcode, DL, VTList, Ops); 9064 } 9065 9066 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 9067 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 9068 SDValue N5) { 9069 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 9070 return getNode(Opcode, DL, VTList, Ops); 9071 } 9072 9073 SDVTList SelectionDAG::getVTList(EVT VT) { 9074 return makeVTList(SDNode::getValueTypeList(VT), 1); 9075 } 9076 9077 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 9078 FoldingSetNodeID ID; 9079 ID.AddInteger(2U); 9080 ID.AddInteger(VT1.getRawBits()); 9081 ID.AddInteger(VT2.getRawBits()); 9082 9083 void *IP = nullptr; 9084 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9085 if (!Result) { 9086 EVT *Array = Allocator.Allocate<EVT>(2); 9087 Array[0] = VT1; 9088 Array[1] = VT2; 9089 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 9090 VTListMap.InsertNode(Result, IP); 9091 } 9092 return Result->getSDVTList(); 9093 } 9094 9095 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 9096 FoldingSetNodeID ID; 9097 ID.AddInteger(3U); 9098 ID.AddInteger(VT1.getRawBits()); 9099 ID.AddInteger(VT2.getRawBits()); 9100 ID.AddInteger(VT3.getRawBits()); 9101 9102 void *IP = nullptr; 9103 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9104 if (!Result) { 9105 EVT *Array = Allocator.Allocate<EVT>(3); 9106 Array[0] = VT1; 9107 Array[1] = VT2; 9108 Array[2] = VT3; 9109 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 9110 VTListMap.InsertNode(Result, IP); 9111 } 9112 return Result->getSDVTList(); 9113 } 9114 9115 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 9116 FoldingSetNodeID ID; 9117 ID.AddInteger(4U); 9118 ID.AddInteger(VT1.getRawBits()); 9119 ID.AddInteger(VT2.getRawBits()); 9120 ID.AddInteger(VT3.getRawBits()); 9121 ID.AddInteger(VT4.getRawBits()); 9122 9123 void *IP = nullptr; 9124 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9125 if (!Result) { 9126 EVT *Array = Allocator.Allocate<EVT>(4); 9127 Array[0] = VT1; 9128 Array[1] = VT2; 9129 Array[2] = VT3; 9130 Array[3] = VT4; 9131 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 9132 VTListMap.InsertNode(Result, IP); 9133 } 9134 return Result->getSDVTList(); 9135 } 9136 9137 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 9138 unsigned NumVTs = VTs.size(); 9139 FoldingSetNodeID ID; 9140 ID.AddInteger(NumVTs); 9141 for (unsigned index = 0; index < NumVTs; index++) { 9142 ID.AddInteger(VTs[index].getRawBits()); 9143 } 9144 9145 void *IP = nullptr; 9146 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 9147 if (!Result) { 9148 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 9149 llvm::copy(VTs, Array); 9150 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 9151 VTListMap.InsertNode(Result, IP); 9152 } 9153 return Result->getSDVTList(); 9154 } 9155 9156 9157 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 9158 /// specified operands. If the resultant node already exists in the DAG, 9159 /// this does not modify the specified node, instead it returns the node that 9160 /// already exists. If the resultant node does not exist in the DAG, the 9161 /// input node is returned. As a degenerate case, if you specify the same 9162 /// input operands as the node already has, the input node is returned. 9163 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 9164 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 9165 9166 // Check to see if there is no change. 9167 if (Op == N->getOperand(0)) return N; 9168 9169 // See if the modified node already exists. 9170 void *InsertPos = nullptr; 9171 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 9172 return Existing; 9173 9174 // Nope it doesn't. Remove the node from its current place in the maps. 9175 if (InsertPos) 9176 if (!RemoveNodeFromCSEMaps(N)) 9177 InsertPos = nullptr; 9178 9179 // Now we update the operands. 9180 N->OperandList[0].set(Op); 9181 9182 updateDivergence(N); 9183 // If this gets put into a CSE map, add it. 9184 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9185 return N; 9186 } 9187 9188 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 9189 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 9190 9191 // Check to see if there is no change. 9192 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 9193 return N; // No operands changed, just return the input node. 9194 9195 // See if the modified node already exists. 9196 void *InsertPos = nullptr; 9197 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 9198 return Existing; 9199 9200 // Nope it doesn't. Remove the node from its current place in the maps. 9201 if (InsertPos) 9202 if (!RemoveNodeFromCSEMaps(N)) 9203 InsertPos = nullptr; 9204 9205 // Now we update the operands. 9206 if (N->OperandList[0] != Op1) 9207 N->OperandList[0].set(Op1); 9208 if (N->OperandList[1] != Op2) 9209 N->OperandList[1].set(Op2); 9210 9211 updateDivergence(N); 9212 // If this gets put into a CSE map, add it. 9213 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9214 return N; 9215 } 9216 9217 SDNode *SelectionDAG:: 9218 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 9219 SDValue Ops[] = { Op1, Op2, Op3 }; 9220 return UpdateNodeOperands(N, Ops); 9221 } 9222 9223 SDNode *SelectionDAG:: 9224 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9225 SDValue Op3, SDValue Op4) { 9226 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 9227 return UpdateNodeOperands(N, Ops); 9228 } 9229 9230 SDNode *SelectionDAG:: 9231 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 9232 SDValue Op3, SDValue Op4, SDValue Op5) { 9233 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 9234 return UpdateNodeOperands(N, Ops); 9235 } 9236 9237 SDNode *SelectionDAG:: 9238 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 9239 unsigned NumOps = Ops.size(); 9240 assert(N->getNumOperands() == NumOps && 9241 "Update with wrong number of operands"); 9242 9243 // If no operands changed just return the input node. 9244 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 9245 return N; 9246 9247 // See if the modified node already exists. 9248 void *InsertPos = nullptr; 9249 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 9250 return Existing; 9251 9252 // Nope it doesn't. Remove the node from its current place in the maps. 9253 if (InsertPos) 9254 if (!RemoveNodeFromCSEMaps(N)) 9255 InsertPos = nullptr; 9256 9257 // Now we update the operands. 9258 for (unsigned i = 0; i != NumOps; ++i) 9259 if (N->OperandList[i] != Ops[i]) 9260 N->OperandList[i].set(Ops[i]); 9261 9262 updateDivergence(N); 9263 // If this gets put into a CSE map, add it. 9264 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 9265 return N; 9266 } 9267 9268 /// DropOperands - Release the operands and set this node to have 9269 /// zero operands. 9270 void SDNode::DropOperands() { 9271 // Unlike the code in MorphNodeTo that does this, we don't need to 9272 // watch for dead nodes here. 9273 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 9274 SDUse &Use = *I++; 9275 Use.set(SDValue()); 9276 } 9277 } 9278 9279 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 9280 ArrayRef<MachineMemOperand *> NewMemRefs) { 9281 if (NewMemRefs.empty()) { 9282 N->clearMemRefs(); 9283 return; 9284 } 9285 9286 // Check if we can avoid allocating by storing a single reference directly. 9287 if (NewMemRefs.size() == 1) { 9288 N->MemRefs = NewMemRefs[0]; 9289 N->NumMemRefs = 1; 9290 return; 9291 } 9292 9293 MachineMemOperand **MemRefsBuffer = 9294 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 9295 llvm::copy(NewMemRefs, MemRefsBuffer); 9296 N->MemRefs = MemRefsBuffer; 9297 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 9298 } 9299 9300 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 9301 /// machine opcode. 9302 /// 9303 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9304 EVT VT) { 9305 SDVTList VTs = getVTList(VT); 9306 return SelectNodeTo(N, MachineOpc, VTs, None); 9307 } 9308 9309 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9310 EVT VT, SDValue Op1) { 9311 SDVTList VTs = getVTList(VT); 9312 SDValue Ops[] = { Op1 }; 9313 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9314 } 9315 9316 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9317 EVT VT, SDValue Op1, 9318 SDValue Op2) { 9319 SDVTList VTs = getVTList(VT); 9320 SDValue Ops[] = { Op1, Op2 }; 9321 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9322 } 9323 9324 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9325 EVT VT, SDValue Op1, 9326 SDValue Op2, SDValue Op3) { 9327 SDVTList VTs = getVTList(VT); 9328 SDValue Ops[] = { Op1, Op2, Op3 }; 9329 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9330 } 9331 9332 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9333 EVT VT, ArrayRef<SDValue> Ops) { 9334 SDVTList VTs = getVTList(VT); 9335 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9336 } 9337 9338 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9339 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 9340 SDVTList VTs = getVTList(VT1, VT2); 9341 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9342 } 9343 9344 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9345 EVT VT1, EVT VT2) { 9346 SDVTList VTs = getVTList(VT1, VT2); 9347 return SelectNodeTo(N, MachineOpc, VTs, None); 9348 } 9349 9350 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9351 EVT VT1, EVT VT2, EVT VT3, 9352 ArrayRef<SDValue> Ops) { 9353 SDVTList VTs = getVTList(VT1, VT2, VT3); 9354 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9355 } 9356 9357 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9358 EVT VT1, EVT VT2, 9359 SDValue Op1, SDValue Op2) { 9360 SDVTList VTs = getVTList(VT1, VT2); 9361 SDValue Ops[] = { Op1, Op2 }; 9362 return SelectNodeTo(N, MachineOpc, VTs, Ops); 9363 } 9364 9365 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 9366 SDVTList VTs,ArrayRef<SDValue> Ops) { 9367 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 9368 // Reset the NodeID to -1. 9369 New->setNodeId(-1); 9370 if (New != N) { 9371 ReplaceAllUsesWith(N, New); 9372 RemoveDeadNode(N); 9373 } 9374 return New; 9375 } 9376 9377 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 9378 /// the line number information on the merged node since it is not possible to 9379 /// preserve the information that operation is associated with multiple lines. 9380 /// This will make the debugger working better at -O0, were there is a higher 9381 /// probability having other instructions associated with that line. 9382 /// 9383 /// For IROrder, we keep the smaller of the two 9384 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 9385 DebugLoc NLoc = N->getDebugLoc(); 9386 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 9387 N->setDebugLoc(DebugLoc()); 9388 } 9389 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 9390 N->setIROrder(Order); 9391 return N; 9392 } 9393 9394 /// MorphNodeTo - This *mutates* the specified node to have the specified 9395 /// return type, opcode, and operands. 9396 /// 9397 /// Note that MorphNodeTo returns the resultant node. If there is already a 9398 /// node of the specified opcode and operands, it returns that node instead of 9399 /// the current one. Note that the SDLoc need not be the same. 9400 /// 9401 /// Using MorphNodeTo is faster than creating a new node and swapping it in 9402 /// with ReplaceAllUsesWith both because it often avoids allocating a new 9403 /// node, and because it doesn't require CSE recalculation for any of 9404 /// the node's users. 9405 /// 9406 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 9407 /// As a consequence it isn't appropriate to use from within the DAG combiner or 9408 /// the legalizer which maintain worklists that would need to be updated when 9409 /// deleting things. 9410 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 9411 SDVTList VTs, ArrayRef<SDValue> Ops) { 9412 // If an identical node already exists, use it. 9413 void *IP = nullptr; 9414 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 9415 FoldingSetNodeID ID; 9416 AddNodeIDNode(ID, Opc, VTs, Ops); 9417 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 9418 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 9419 } 9420 9421 if (!RemoveNodeFromCSEMaps(N)) 9422 IP = nullptr; 9423 9424 // Start the morphing. 9425 N->NodeType = Opc; 9426 N->ValueList = VTs.VTs; 9427 N->NumValues = VTs.NumVTs; 9428 9429 // Clear the operands list, updating used nodes to remove this from their 9430 // use list. Keep track of any operands that become dead as a result. 9431 SmallPtrSet<SDNode*, 16> DeadNodeSet; 9432 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 9433 SDUse &Use = *I++; 9434 SDNode *Used = Use.getNode(); 9435 Use.set(SDValue()); 9436 if (Used->use_empty()) 9437 DeadNodeSet.insert(Used); 9438 } 9439 9440 // For MachineNode, initialize the memory references information. 9441 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 9442 MN->clearMemRefs(); 9443 9444 // Swap for an appropriately sized array from the recycler. 9445 removeOperands(N); 9446 createOperands(N, Ops); 9447 9448 // Delete any nodes that are still dead after adding the uses for the 9449 // new operands. 9450 if (!DeadNodeSet.empty()) { 9451 SmallVector<SDNode *, 16> DeadNodes; 9452 for (SDNode *N : DeadNodeSet) 9453 if (N->use_empty()) 9454 DeadNodes.push_back(N); 9455 RemoveDeadNodes(DeadNodes); 9456 } 9457 9458 if (IP) 9459 CSEMap.InsertNode(N, IP); // Memoize the new node. 9460 return N; 9461 } 9462 9463 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9464 unsigned OrigOpc = Node->getOpcode(); 9465 unsigned NewOpc; 9466 switch (OrigOpc) { 9467 default: 9468 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9469 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9470 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9471 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9472 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9473 #include "llvm/IR/ConstrainedOps.def" 9474 } 9475 9476 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9477 9478 // We're taking this node out of the chain, so we need to re-link things. 9479 SDValue InputChain = Node->getOperand(0); 9480 SDValue OutputChain = SDValue(Node, 1); 9481 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9482 9483 SmallVector<SDValue, 3> Ops; 9484 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9485 Ops.push_back(Node->getOperand(i)); 9486 9487 SDVTList VTs = getVTList(Node->getValueType(0)); 9488 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9489 9490 // MorphNodeTo can operate in two ways: if an existing node with the 9491 // specified operands exists, it can just return it. Otherwise, it 9492 // updates the node in place to have the requested operands. 9493 if (Res == Node) { 9494 // If we updated the node in place, reset the node ID. To the isel, 9495 // this should be just like a newly allocated machine node. 9496 Res->setNodeId(-1); 9497 } else { 9498 ReplaceAllUsesWith(Node, Res); 9499 RemoveDeadNode(Node); 9500 } 9501 9502 return Res; 9503 } 9504 9505 /// getMachineNode - These are used for target selectors to create a new node 9506 /// with specified return type(s), MachineInstr opcode, and operands. 9507 /// 9508 /// Note that getMachineNode returns the resultant node. If there is already a 9509 /// node of the specified opcode and operands, it returns that node instead of 9510 /// the current one. 9511 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9512 EVT VT) { 9513 SDVTList VTs = getVTList(VT); 9514 return getMachineNode(Opcode, dl, VTs, None); 9515 } 9516 9517 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9518 EVT VT, SDValue Op1) { 9519 SDVTList VTs = getVTList(VT); 9520 SDValue Ops[] = { Op1 }; 9521 return getMachineNode(Opcode, dl, VTs, Ops); 9522 } 9523 9524 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9525 EVT VT, SDValue Op1, SDValue Op2) { 9526 SDVTList VTs = getVTList(VT); 9527 SDValue Ops[] = { Op1, Op2 }; 9528 return getMachineNode(Opcode, dl, VTs, Ops); 9529 } 9530 9531 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9532 EVT VT, SDValue Op1, SDValue Op2, 9533 SDValue Op3) { 9534 SDVTList VTs = getVTList(VT); 9535 SDValue Ops[] = { Op1, Op2, Op3 }; 9536 return getMachineNode(Opcode, dl, VTs, Ops); 9537 } 9538 9539 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9540 EVT VT, ArrayRef<SDValue> Ops) { 9541 SDVTList VTs = getVTList(VT); 9542 return getMachineNode(Opcode, dl, VTs, Ops); 9543 } 9544 9545 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9546 EVT VT1, EVT VT2, SDValue Op1, 9547 SDValue Op2) { 9548 SDVTList VTs = getVTList(VT1, VT2); 9549 SDValue Ops[] = { Op1, Op2 }; 9550 return getMachineNode(Opcode, dl, VTs, Ops); 9551 } 9552 9553 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9554 EVT VT1, EVT VT2, SDValue Op1, 9555 SDValue Op2, SDValue Op3) { 9556 SDVTList VTs = getVTList(VT1, VT2); 9557 SDValue Ops[] = { Op1, Op2, Op3 }; 9558 return getMachineNode(Opcode, dl, VTs, Ops); 9559 } 9560 9561 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9562 EVT VT1, EVT VT2, 9563 ArrayRef<SDValue> Ops) { 9564 SDVTList VTs = getVTList(VT1, VT2); 9565 return getMachineNode(Opcode, dl, VTs, Ops); 9566 } 9567 9568 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9569 EVT VT1, EVT VT2, EVT VT3, 9570 SDValue Op1, SDValue Op2) { 9571 SDVTList VTs = getVTList(VT1, VT2, VT3); 9572 SDValue Ops[] = { Op1, Op2 }; 9573 return getMachineNode(Opcode, dl, VTs, Ops); 9574 } 9575 9576 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9577 EVT VT1, EVT VT2, EVT VT3, 9578 SDValue Op1, SDValue Op2, 9579 SDValue Op3) { 9580 SDVTList VTs = getVTList(VT1, VT2, VT3); 9581 SDValue Ops[] = { Op1, Op2, Op3 }; 9582 return getMachineNode(Opcode, dl, VTs, Ops); 9583 } 9584 9585 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9586 EVT VT1, EVT VT2, EVT VT3, 9587 ArrayRef<SDValue> Ops) { 9588 SDVTList VTs = getVTList(VT1, VT2, VT3); 9589 return getMachineNode(Opcode, dl, VTs, Ops); 9590 } 9591 9592 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9593 ArrayRef<EVT> ResultTys, 9594 ArrayRef<SDValue> Ops) { 9595 SDVTList VTs = getVTList(ResultTys); 9596 return getMachineNode(Opcode, dl, VTs, Ops); 9597 } 9598 9599 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9600 SDVTList VTs, 9601 ArrayRef<SDValue> Ops) { 9602 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9603 MachineSDNode *N; 9604 void *IP = nullptr; 9605 9606 if (DoCSE) { 9607 FoldingSetNodeID ID; 9608 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9609 IP = nullptr; 9610 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9611 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9612 } 9613 } 9614 9615 // Allocate a new MachineSDNode. 9616 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9617 createOperands(N, Ops); 9618 9619 if (DoCSE) 9620 CSEMap.InsertNode(N, IP); 9621 9622 InsertNode(N); 9623 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9624 return N; 9625 } 9626 9627 /// getTargetExtractSubreg - A convenience function for creating 9628 /// TargetOpcode::EXTRACT_SUBREG nodes. 9629 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9630 SDValue Operand) { 9631 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9632 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9633 VT, Operand, SRIdxVal); 9634 return SDValue(Subreg, 0); 9635 } 9636 9637 /// getTargetInsertSubreg - A convenience function for creating 9638 /// TargetOpcode::INSERT_SUBREG nodes. 9639 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9640 SDValue Operand, SDValue Subreg) { 9641 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9642 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9643 VT, Operand, Subreg, SRIdxVal); 9644 return SDValue(Result, 0); 9645 } 9646 9647 /// getNodeIfExists - Get the specified node if it's already available, or 9648 /// else return NULL. 9649 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9650 ArrayRef<SDValue> Ops) { 9651 SDNodeFlags Flags; 9652 if (Inserter) 9653 Flags = Inserter->getFlags(); 9654 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9655 } 9656 9657 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9658 ArrayRef<SDValue> Ops, 9659 const SDNodeFlags Flags) { 9660 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9661 FoldingSetNodeID ID; 9662 AddNodeIDNode(ID, Opcode, VTList, Ops); 9663 void *IP = nullptr; 9664 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9665 E->intersectFlagsWith(Flags); 9666 return E; 9667 } 9668 } 9669 return nullptr; 9670 } 9671 9672 /// doesNodeExist - Check if a node exists without modifying its flags. 9673 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9674 ArrayRef<SDValue> Ops) { 9675 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9676 FoldingSetNodeID ID; 9677 AddNodeIDNode(ID, Opcode, VTList, Ops); 9678 void *IP = nullptr; 9679 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9680 return true; 9681 } 9682 return false; 9683 } 9684 9685 /// getDbgValue - Creates a SDDbgValue node. 9686 /// 9687 /// SDNode 9688 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9689 SDNode *N, unsigned R, bool IsIndirect, 9690 const DebugLoc &DL, unsigned O) { 9691 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9692 "Expected inlined-at fields to agree"); 9693 return new (DbgInfo->getAlloc()) 9694 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9695 {}, IsIndirect, DL, O, 9696 /*IsVariadic=*/false); 9697 } 9698 9699 /// Constant 9700 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9701 DIExpression *Expr, 9702 const Value *C, 9703 const DebugLoc &DL, unsigned O) { 9704 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9705 "Expected inlined-at fields to agree"); 9706 return new (DbgInfo->getAlloc()) 9707 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9708 /*IsIndirect=*/false, DL, O, 9709 /*IsVariadic=*/false); 9710 } 9711 9712 /// FrameIndex 9713 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9714 DIExpression *Expr, unsigned FI, 9715 bool IsIndirect, 9716 const DebugLoc &DL, 9717 unsigned O) { 9718 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9719 "Expected inlined-at fields to agree"); 9720 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9721 } 9722 9723 /// FrameIndex with dependencies 9724 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9725 DIExpression *Expr, unsigned FI, 9726 ArrayRef<SDNode *> Dependencies, 9727 bool IsIndirect, 9728 const DebugLoc &DL, 9729 unsigned O) { 9730 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9731 "Expected inlined-at fields to agree"); 9732 return new (DbgInfo->getAlloc()) 9733 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9734 Dependencies, IsIndirect, DL, O, 9735 /*IsVariadic=*/false); 9736 } 9737 9738 /// VReg 9739 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9740 unsigned VReg, bool IsIndirect, 9741 const DebugLoc &DL, unsigned O) { 9742 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9743 "Expected inlined-at fields to agree"); 9744 return new (DbgInfo->getAlloc()) 9745 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9746 {}, IsIndirect, DL, O, 9747 /*IsVariadic=*/false); 9748 } 9749 9750 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9751 ArrayRef<SDDbgOperand> Locs, 9752 ArrayRef<SDNode *> Dependencies, 9753 bool IsIndirect, const DebugLoc &DL, 9754 unsigned O, bool IsVariadic) { 9755 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9756 "Expected inlined-at fields to agree"); 9757 return new (DbgInfo->getAlloc()) 9758 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9759 DL, O, IsVariadic); 9760 } 9761 9762 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9763 unsigned OffsetInBits, unsigned SizeInBits, 9764 bool InvalidateDbg) { 9765 SDNode *FromNode = From.getNode(); 9766 SDNode *ToNode = To.getNode(); 9767 assert(FromNode && ToNode && "Can't modify dbg values"); 9768 9769 // PR35338 9770 // TODO: assert(From != To && "Redundant dbg value transfer"); 9771 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9772 if (From == To || FromNode == ToNode) 9773 return; 9774 9775 if (!FromNode->getHasDebugValue()) 9776 return; 9777 9778 SDDbgOperand FromLocOp = 9779 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9780 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9781 9782 SmallVector<SDDbgValue *, 2> ClonedDVs; 9783 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9784 if (Dbg->isInvalidated()) 9785 continue; 9786 9787 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9788 9789 // Create a new location ops vector that is equal to the old vector, but 9790 // with each instance of FromLocOp replaced with ToLocOp. 9791 bool Changed = false; 9792 auto NewLocOps = Dbg->copyLocationOps(); 9793 std::replace_if( 9794 NewLocOps.begin(), NewLocOps.end(), 9795 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9796 bool Match = Op == FromLocOp; 9797 Changed |= Match; 9798 return Match; 9799 }, 9800 ToLocOp); 9801 // Ignore this SDDbgValue if we didn't find a matching location. 9802 if (!Changed) 9803 continue; 9804 9805 DIVariable *Var = Dbg->getVariable(); 9806 auto *Expr = Dbg->getExpression(); 9807 // If a fragment is requested, update the expression. 9808 if (SizeInBits) { 9809 // When splitting a larger (e.g., sign-extended) value whose 9810 // lower bits are described with an SDDbgValue, do not attempt 9811 // to transfer the SDDbgValue to the upper bits. 9812 if (auto FI = Expr->getFragmentInfo()) 9813 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9814 continue; 9815 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9816 SizeInBits); 9817 if (!Fragment) 9818 continue; 9819 Expr = *Fragment; 9820 } 9821 9822 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9823 // Clone the SDDbgValue and move it to To. 9824 SDDbgValue *Clone = getDbgValueList( 9825 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9826 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9827 Dbg->isVariadic()); 9828 ClonedDVs.push_back(Clone); 9829 9830 if (InvalidateDbg) { 9831 // Invalidate value and indicate the SDDbgValue should not be emitted. 9832 Dbg->setIsInvalidated(); 9833 Dbg->setIsEmitted(); 9834 } 9835 } 9836 9837 for (SDDbgValue *Dbg : ClonedDVs) { 9838 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9839 "Transferred DbgValues should depend on the new SDNode"); 9840 AddDbgValue(Dbg, false); 9841 } 9842 } 9843 9844 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9845 if (!N.getHasDebugValue()) 9846 return; 9847 9848 SmallVector<SDDbgValue *, 2> ClonedDVs; 9849 for (auto DV : GetDbgValues(&N)) { 9850 if (DV->isInvalidated()) 9851 continue; 9852 switch (N.getOpcode()) { 9853 default: 9854 break; 9855 case ISD::ADD: 9856 SDValue N0 = N.getOperand(0); 9857 SDValue N1 = N.getOperand(1); 9858 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9859 isConstantIntBuildVectorOrConstantInt(N1)) { 9860 uint64_t Offset = N.getConstantOperandVal(1); 9861 9862 // Rewrite an ADD constant node into a DIExpression. Since we are 9863 // performing arithmetic to compute the variable's *value* in the 9864 // DIExpression, we need to mark the expression with a 9865 // DW_OP_stack_value. 9866 auto *DIExpr = DV->getExpression(); 9867 auto NewLocOps = DV->copyLocationOps(); 9868 bool Changed = false; 9869 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9870 // We're not given a ResNo to compare against because the whole 9871 // node is going away. We know that any ISD::ADD only has one 9872 // result, so we can assume any node match is using the result. 9873 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9874 NewLocOps[i].getSDNode() != &N) 9875 continue; 9876 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9877 SmallVector<uint64_t, 3> ExprOps; 9878 DIExpression::appendOffset(ExprOps, Offset); 9879 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9880 Changed = true; 9881 } 9882 (void)Changed; 9883 assert(Changed && "Salvage target doesn't use N"); 9884 9885 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9886 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9887 NewLocOps, AdditionalDependencies, 9888 DV->isIndirect(), DV->getDebugLoc(), 9889 DV->getOrder(), DV->isVariadic()); 9890 ClonedDVs.push_back(Clone); 9891 DV->setIsInvalidated(); 9892 DV->setIsEmitted(); 9893 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9894 N0.getNode()->dumprFull(this); 9895 dbgs() << " into " << *DIExpr << '\n'); 9896 } 9897 } 9898 } 9899 9900 for (SDDbgValue *Dbg : ClonedDVs) { 9901 assert(!Dbg->getSDNodes().empty() && 9902 "Salvaged DbgValue should depend on a new SDNode"); 9903 AddDbgValue(Dbg, false); 9904 } 9905 } 9906 9907 /// Creates a SDDbgLabel node. 9908 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9909 const DebugLoc &DL, unsigned O) { 9910 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9911 "Expected inlined-at fields to agree"); 9912 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9913 } 9914 9915 namespace { 9916 9917 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9918 /// pointed to by a use iterator is deleted, increment the use iterator 9919 /// so that it doesn't dangle. 9920 /// 9921 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9922 SDNode::use_iterator &UI; 9923 SDNode::use_iterator &UE; 9924 9925 void NodeDeleted(SDNode *N, SDNode *E) override { 9926 // Increment the iterator as needed. 9927 while (UI != UE && N == *UI) 9928 ++UI; 9929 } 9930 9931 public: 9932 RAUWUpdateListener(SelectionDAG &d, 9933 SDNode::use_iterator &ui, 9934 SDNode::use_iterator &ue) 9935 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9936 }; 9937 9938 } // end anonymous namespace 9939 9940 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9941 /// This can cause recursive merging of nodes in the DAG. 9942 /// 9943 /// This version assumes From has a single result value. 9944 /// 9945 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9946 SDNode *From = FromN.getNode(); 9947 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9948 "Cannot replace with this method!"); 9949 assert(From != To.getNode() && "Cannot replace uses of with self"); 9950 9951 // Preserve Debug Values 9952 transferDbgValues(FromN, To); 9953 9954 // Iterate over all the existing uses of From. New uses will be added 9955 // to the beginning of the use list, which we avoid visiting. 9956 // This specifically avoids visiting uses of From that arise while the 9957 // replacement is happening, because any such uses would be the result 9958 // of CSE: If an existing node looks like From after one of its operands 9959 // is replaced by To, we don't want to replace of all its users with To 9960 // too. See PR3018 for more info. 9961 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9962 RAUWUpdateListener Listener(*this, UI, UE); 9963 while (UI != UE) { 9964 SDNode *User = *UI; 9965 9966 // This node is about to morph, remove its old self from the CSE maps. 9967 RemoveNodeFromCSEMaps(User); 9968 9969 // A user can appear in a use list multiple times, and when this 9970 // happens the uses are usually next to each other in the list. 9971 // To help reduce the number of CSE recomputations, process all 9972 // the uses of this user that we can find this way. 9973 do { 9974 SDUse &Use = UI.getUse(); 9975 ++UI; 9976 Use.set(To); 9977 if (To->isDivergent() != From->isDivergent()) 9978 updateDivergence(User); 9979 } while (UI != UE && *UI == User); 9980 // Now that we have modified User, add it back to the CSE maps. If it 9981 // already exists there, recursively merge the results together. 9982 AddModifiedNodeToCSEMaps(User); 9983 } 9984 9985 // If we just RAUW'd the root, take note. 9986 if (FromN == getRoot()) 9987 setRoot(To); 9988 } 9989 9990 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9991 /// This can cause recursive merging of nodes in the DAG. 9992 /// 9993 /// This version assumes that for each value of From, there is a 9994 /// corresponding value in To in the same position with the same type. 9995 /// 9996 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9997 #ifndef NDEBUG 9998 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9999 assert((!From->hasAnyUseOfValue(i) || 10000 From->getValueType(i) == To->getValueType(i)) && 10001 "Cannot use this version of ReplaceAllUsesWith!"); 10002 #endif 10003 10004 // Handle the trivial case. 10005 if (From == To) 10006 return; 10007 10008 // Preserve Debug Info. Only do this if there's a use. 10009 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10010 if (From->hasAnyUseOfValue(i)) { 10011 assert((i < To->getNumValues()) && "Invalid To location"); 10012 transferDbgValues(SDValue(From, i), SDValue(To, i)); 10013 } 10014 10015 // Iterate over just the existing users of From. See the comments in 10016 // the ReplaceAllUsesWith above. 10017 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10018 RAUWUpdateListener Listener(*this, UI, UE); 10019 while (UI != UE) { 10020 SDNode *User = *UI; 10021 10022 // This node is about to morph, remove its old self from the CSE maps. 10023 RemoveNodeFromCSEMaps(User); 10024 10025 // A user can appear in a use list multiple times, and when this 10026 // happens the uses are usually next to each other in the list. 10027 // To help reduce the number of CSE recomputations, process all 10028 // the uses of this user that we can find this way. 10029 do { 10030 SDUse &Use = UI.getUse(); 10031 ++UI; 10032 Use.setNode(To); 10033 if (To->isDivergent() != From->isDivergent()) 10034 updateDivergence(User); 10035 } while (UI != UE && *UI == User); 10036 10037 // Now that we have modified User, add it back to the CSE maps. If it 10038 // already exists there, recursively merge the results together. 10039 AddModifiedNodeToCSEMaps(User); 10040 } 10041 10042 // If we just RAUW'd the root, take note. 10043 if (From == getRoot().getNode()) 10044 setRoot(SDValue(To, getRoot().getResNo())); 10045 } 10046 10047 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 10048 /// This can cause recursive merging of nodes in the DAG. 10049 /// 10050 /// This version can replace From with any result values. To must match the 10051 /// number and types of values returned by From. 10052 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 10053 if (From->getNumValues() == 1) // Handle the simple case efficiently. 10054 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 10055 10056 // Preserve Debug Info. 10057 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 10058 transferDbgValues(SDValue(From, i), To[i]); 10059 10060 // Iterate over just the existing users of From. See the comments in 10061 // the ReplaceAllUsesWith above. 10062 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 10063 RAUWUpdateListener Listener(*this, UI, UE); 10064 while (UI != UE) { 10065 SDNode *User = *UI; 10066 10067 // This node is about to morph, remove its old self from the CSE maps. 10068 RemoveNodeFromCSEMaps(User); 10069 10070 // A user can appear in a use list multiple times, and when this happens the 10071 // uses are usually next to each other in the list. To help reduce the 10072 // number of CSE and divergence recomputations, process all the uses of this 10073 // user that we can find this way. 10074 bool To_IsDivergent = false; 10075 do { 10076 SDUse &Use = UI.getUse(); 10077 const SDValue &ToOp = To[Use.getResNo()]; 10078 ++UI; 10079 Use.set(ToOp); 10080 To_IsDivergent |= ToOp->isDivergent(); 10081 } while (UI != UE && *UI == User); 10082 10083 if (To_IsDivergent != From->isDivergent()) 10084 updateDivergence(User); 10085 10086 // Now that we have modified User, add it back to the CSE maps. If it 10087 // already exists there, recursively merge the results together. 10088 AddModifiedNodeToCSEMaps(User); 10089 } 10090 10091 // If we just RAUW'd the root, take note. 10092 if (From == getRoot().getNode()) 10093 setRoot(SDValue(To[getRoot().getResNo()])); 10094 } 10095 10096 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 10097 /// uses of other values produced by From.getNode() alone. The Deleted 10098 /// vector is handled the same way as for ReplaceAllUsesWith. 10099 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 10100 // Handle the really simple, really trivial case efficiently. 10101 if (From == To) return; 10102 10103 // Handle the simple, trivial, case efficiently. 10104 if (From.getNode()->getNumValues() == 1) { 10105 ReplaceAllUsesWith(From, To); 10106 return; 10107 } 10108 10109 // Preserve Debug Info. 10110 transferDbgValues(From, To); 10111 10112 // Iterate over just the existing users of From. See the comments in 10113 // the ReplaceAllUsesWith above. 10114 SDNode::use_iterator UI = From.getNode()->use_begin(), 10115 UE = From.getNode()->use_end(); 10116 RAUWUpdateListener Listener(*this, UI, UE); 10117 while (UI != UE) { 10118 SDNode *User = *UI; 10119 bool UserRemovedFromCSEMaps = false; 10120 10121 // A user can appear in a use list multiple times, and when this 10122 // happens the uses are usually next to each other in the list. 10123 // To help reduce the number of CSE recomputations, process all 10124 // the uses of this user that we can find this way. 10125 do { 10126 SDUse &Use = UI.getUse(); 10127 10128 // Skip uses of different values from the same node. 10129 if (Use.getResNo() != From.getResNo()) { 10130 ++UI; 10131 continue; 10132 } 10133 10134 // If this node hasn't been modified yet, it's still in the CSE maps, 10135 // so remove its old self from the CSE maps. 10136 if (!UserRemovedFromCSEMaps) { 10137 RemoveNodeFromCSEMaps(User); 10138 UserRemovedFromCSEMaps = true; 10139 } 10140 10141 ++UI; 10142 Use.set(To); 10143 if (To->isDivergent() != From->isDivergent()) 10144 updateDivergence(User); 10145 } while (UI != UE && *UI == User); 10146 // We are iterating over all uses of the From node, so if a use 10147 // doesn't use the specific value, no changes are made. 10148 if (!UserRemovedFromCSEMaps) 10149 continue; 10150 10151 // Now that we have modified User, add it back to the CSE maps. If it 10152 // already exists there, recursively merge the results together. 10153 AddModifiedNodeToCSEMaps(User); 10154 } 10155 10156 // If we just RAUW'd the root, take note. 10157 if (From == getRoot()) 10158 setRoot(To); 10159 } 10160 10161 namespace { 10162 10163 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 10164 /// to record information about a use. 10165 struct UseMemo { 10166 SDNode *User; 10167 unsigned Index; 10168 SDUse *Use; 10169 }; 10170 10171 /// operator< - Sort Memos by User. 10172 bool operator<(const UseMemo &L, const UseMemo &R) { 10173 return (intptr_t)L.User < (intptr_t)R.User; 10174 } 10175 10176 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node 10177 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that 10178 /// the node already has been taken care of recursively. 10179 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener { 10180 SmallVector<UseMemo, 4> &Uses; 10181 10182 void NodeDeleted(SDNode *N, SDNode *E) override { 10183 for (UseMemo &Memo : Uses) 10184 if (Memo.User == N) 10185 Memo.User = nullptr; 10186 } 10187 10188 public: 10189 RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses) 10190 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {} 10191 }; 10192 10193 } // end anonymous namespace 10194 10195 bool SelectionDAG::calculateDivergence(SDNode *N) { 10196 if (TLI->isSDNodeAlwaysUniform(N)) { 10197 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 10198 "Conflicting divergence information!"); 10199 return false; 10200 } 10201 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 10202 return true; 10203 for (auto &Op : N->ops()) { 10204 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 10205 return true; 10206 } 10207 return false; 10208 } 10209 10210 void SelectionDAG::updateDivergence(SDNode *N) { 10211 SmallVector<SDNode *, 16> Worklist(1, N); 10212 do { 10213 N = Worklist.pop_back_val(); 10214 bool IsDivergent = calculateDivergence(N); 10215 if (N->SDNodeBits.IsDivergent != IsDivergent) { 10216 N->SDNodeBits.IsDivergent = IsDivergent; 10217 llvm::append_range(Worklist, N->uses()); 10218 } 10219 } while (!Worklist.empty()); 10220 } 10221 10222 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 10223 DenseMap<SDNode *, unsigned> Degree; 10224 Order.reserve(AllNodes.size()); 10225 for (auto &N : allnodes()) { 10226 unsigned NOps = N.getNumOperands(); 10227 Degree[&N] = NOps; 10228 if (0 == NOps) 10229 Order.push_back(&N); 10230 } 10231 for (size_t I = 0; I != Order.size(); ++I) { 10232 SDNode *N = Order[I]; 10233 for (auto U : N->uses()) { 10234 unsigned &UnsortedOps = Degree[U]; 10235 if (0 == --UnsortedOps) 10236 Order.push_back(U); 10237 } 10238 } 10239 } 10240 10241 #ifndef NDEBUG 10242 void SelectionDAG::VerifyDAGDivergence() { 10243 std::vector<SDNode *> TopoOrder; 10244 CreateTopologicalOrder(TopoOrder); 10245 for (auto *N : TopoOrder) { 10246 assert(calculateDivergence(N) == N->isDivergent() && 10247 "Divergence bit inconsistency detected"); 10248 } 10249 } 10250 #endif 10251 10252 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 10253 /// uses of other values produced by From.getNode() alone. The same value 10254 /// may appear in both the From and To list. The Deleted vector is 10255 /// handled the same way as for ReplaceAllUsesWith. 10256 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 10257 const SDValue *To, 10258 unsigned Num){ 10259 // Handle the simple, trivial case efficiently. 10260 if (Num == 1) 10261 return ReplaceAllUsesOfValueWith(*From, *To); 10262 10263 transferDbgValues(*From, *To); 10264 10265 // Read up all the uses and make records of them. This helps 10266 // processing new uses that are introduced during the 10267 // replacement process. 10268 SmallVector<UseMemo, 4> Uses; 10269 for (unsigned i = 0; i != Num; ++i) { 10270 unsigned FromResNo = From[i].getResNo(); 10271 SDNode *FromNode = From[i].getNode(); 10272 for (SDNode::use_iterator UI = FromNode->use_begin(), 10273 E = FromNode->use_end(); UI != E; ++UI) { 10274 SDUse &Use = UI.getUse(); 10275 if (Use.getResNo() == FromResNo) { 10276 UseMemo Memo = { *UI, i, &Use }; 10277 Uses.push_back(Memo); 10278 } 10279 } 10280 } 10281 10282 // Sort the uses, so that all the uses from a given User are together. 10283 llvm::sort(Uses); 10284 RAUOVWUpdateListener Listener(*this, Uses); 10285 10286 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 10287 UseIndex != UseIndexEnd; ) { 10288 // We know that this user uses some value of From. If it is the right 10289 // value, update it. 10290 SDNode *User = Uses[UseIndex].User; 10291 // If the node has been deleted by recursive CSE updates when updating 10292 // another node, then just skip this entry. 10293 if (User == nullptr) { 10294 ++UseIndex; 10295 continue; 10296 } 10297 10298 // This node is about to morph, remove its old self from the CSE maps. 10299 RemoveNodeFromCSEMaps(User); 10300 10301 // The Uses array is sorted, so all the uses for a given User 10302 // are next to each other in the list. 10303 // To help reduce the number of CSE recomputations, process all 10304 // the uses of this user that we can find this way. 10305 do { 10306 unsigned i = Uses[UseIndex].Index; 10307 SDUse &Use = *Uses[UseIndex].Use; 10308 ++UseIndex; 10309 10310 Use.set(To[i]); 10311 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 10312 10313 // Now that we have modified User, add it back to the CSE maps. If it 10314 // already exists there, recursively merge the results together. 10315 AddModifiedNodeToCSEMaps(User); 10316 } 10317 } 10318 10319 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 10320 /// based on their topological order. It returns the maximum id and a vector 10321 /// of the SDNodes* in assigned order by reference. 10322 unsigned SelectionDAG::AssignTopologicalOrder() { 10323 unsigned DAGSize = 0; 10324 10325 // SortedPos tracks the progress of the algorithm. Nodes before it are 10326 // sorted, nodes after it are unsorted. When the algorithm completes 10327 // it is at the end of the list. 10328 allnodes_iterator SortedPos = allnodes_begin(); 10329 10330 // Visit all the nodes. Move nodes with no operands to the front of 10331 // the list immediately. Annotate nodes that do have operands with their 10332 // operand count. Before we do this, the Node Id fields of the nodes 10333 // may contain arbitrary values. After, the Node Id fields for nodes 10334 // before SortedPos will contain the topological sort index, and the 10335 // Node Id fields for nodes At SortedPos and after will contain the 10336 // count of outstanding operands. 10337 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 10338 checkForCycles(&N, this); 10339 unsigned Degree = N.getNumOperands(); 10340 if (Degree == 0) { 10341 // A node with no uses, add it to the result array immediately. 10342 N.setNodeId(DAGSize++); 10343 allnodes_iterator Q(&N); 10344 if (Q != SortedPos) 10345 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 10346 assert(SortedPos != AllNodes.end() && "Overran node list"); 10347 ++SortedPos; 10348 } else { 10349 // Temporarily use the Node Id as scratch space for the degree count. 10350 N.setNodeId(Degree); 10351 } 10352 } 10353 10354 // Visit all the nodes. As we iterate, move nodes into sorted order, 10355 // such that by the time the end is reached all nodes will be sorted. 10356 for (SDNode &Node : allnodes()) { 10357 SDNode *N = &Node; 10358 checkForCycles(N, this); 10359 // N is in sorted position, so all its uses have one less operand 10360 // that needs to be sorted. 10361 for (SDNode *P : N->uses()) { 10362 unsigned Degree = P->getNodeId(); 10363 assert(Degree != 0 && "Invalid node degree"); 10364 --Degree; 10365 if (Degree == 0) { 10366 // All of P's operands are sorted, so P may sorted now. 10367 P->setNodeId(DAGSize++); 10368 if (P->getIterator() != SortedPos) 10369 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 10370 assert(SortedPos != AllNodes.end() && "Overran node list"); 10371 ++SortedPos; 10372 } else { 10373 // Update P's outstanding operand count. 10374 P->setNodeId(Degree); 10375 } 10376 } 10377 if (Node.getIterator() == SortedPos) { 10378 #ifndef NDEBUG 10379 allnodes_iterator I(N); 10380 SDNode *S = &*++I; 10381 dbgs() << "Overran sorted position:\n"; 10382 S->dumprFull(this); dbgs() << "\n"; 10383 dbgs() << "Checking if this is due to cycles\n"; 10384 checkForCycles(this, true); 10385 #endif 10386 llvm_unreachable(nullptr); 10387 } 10388 } 10389 10390 assert(SortedPos == AllNodes.end() && 10391 "Topological sort incomplete!"); 10392 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 10393 "First node in topological sort is not the entry token!"); 10394 assert(AllNodes.front().getNodeId() == 0 && 10395 "First node in topological sort has non-zero id!"); 10396 assert(AllNodes.front().getNumOperands() == 0 && 10397 "First node in topological sort has operands!"); 10398 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 10399 "Last node in topologic sort has unexpected id!"); 10400 assert(AllNodes.back().use_empty() && 10401 "Last node in topologic sort has users!"); 10402 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 10403 return DAGSize; 10404 } 10405 10406 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 10407 /// value is produced by SD. 10408 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 10409 for (SDNode *SD : DB->getSDNodes()) { 10410 if (!SD) 10411 continue; 10412 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 10413 SD->setHasDebugValue(true); 10414 } 10415 DbgInfo->add(DB, isParameter); 10416 } 10417 10418 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 10419 10420 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 10421 SDValue NewMemOpChain) { 10422 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 10423 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 10424 // The new memory operation must have the same position as the old load in 10425 // terms of memory dependency. Create a TokenFactor for the old load and new 10426 // memory operation and update uses of the old load's output chain to use that 10427 // TokenFactor. 10428 if (OldChain == NewMemOpChain || OldChain.use_empty()) 10429 return NewMemOpChain; 10430 10431 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 10432 OldChain, NewMemOpChain); 10433 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 10434 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 10435 return TokenFactor; 10436 } 10437 10438 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 10439 SDValue NewMemOp) { 10440 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 10441 SDValue OldChain = SDValue(OldLoad, 1); 10442 SDValue NewMemOpChain = NewMemOp.getValue(1); 10443 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 10444 } 10445 10446 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 10447 Function **OutFunction) { 10448 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 10449 10450 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 10451 auto *Module = MF->getFunction().getParent(); 10452 auto *Function = Module->getFunction(Symbol); 10453 10454 if (OutFunction != nullptr) 10455 *OutFunction = Function; 10456 10457 if (Function != nullptr) { 10458 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 10459 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 10460 } 10461 10462 std::string ErrorStr; 10463 raw_string_ostream ErrorFormatter(ErrorStr); 10464 ErrorFormatter << "Undefined external symbol "; 10465 ErrorFormatter << '"' << Symbol << '"'; 10466 report_fatal_error(Twine(ErrorFormatter.str())); 10467 } 10468 10469 //===----------------------------------------------------------------------===// 10470 // SDNode Class 10471 //===----------------------------------------------------------------------===// 10472 10473 bool llvm::isNullConstant(SDValue V) { 10474 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10475 return Const != nullptr && Const->isZero(); 10476 } 10477 10478 bool llvm::isNullFPConstant(SDValue V) { 10479 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 10480 return Const != nullptr && Const->isZero() && !Const->isNegative(); 10481 } 10482 10483 bool llvm::isAllOnesConstant(SDValue V) { 10484 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10485 return Const != nullptr && Const->isAllOnes(); 10486 } 10487 10488 bool llvm::isOneConstant(SDValue V) { 10489 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10490 return Const != nullptr && Const->isOne(); 10491 } 10492 10493 bool llvm::isMinSignedConstant(SDValue V) { 10494 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10495 return Const != nullptr && Const->isMinSignedValue(); 10496 } 10497 10498 SDValue llvm::peekThroughBitcasts(SDValue V) { 10499 while (V.getOpcode() == ISD::BITCAST) 10500 V = V.getOperand(0); 10501 return V; 10502 } 10503 10504 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10505 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10506 V = V.getOperand(0); 10507 return V; 10508 } 10509 10510 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10511 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10512 V = V.getOperand(0); 10513 return V; 10514 } 10515 10516 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10517 if (V.getOpcode() != ISD::XOR) 10518 return false; 10519 V = peekThroughBitcasts(V.getOperand(1)); 10520 unsigned NumBits = V.getScalarValueSizeInBits(); 10521 ConstantSDNode *C = 10522 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10523 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10524 } 10525 10526 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10527 bool AllowTruncation) { 10528 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10529 return CN; 10530 10531 // SplatVectors can truncate their operands. Ignore that case here unless 10532 // AllowTruncation is set. 10533 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10534 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10535 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10536 EVT CVT = CN->getValueType(0); 10537 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10538 if (AllowTruncation || CVT == VecEltVT) 10539 return CN; 10540 } 10541 } 10542 10543 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10544 BitVector UndefElements; 10545 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10546 10547 // BuildVectors can truncate their operands. Ignore that case here unless 10548 // AllowTruncation is set. 10549 if (CN && (UndefElements.none() || AllowUndefs)) { 10550 EVT CVT = CN->getValueType(0); 10551 EVT NSVT = N.getValueType().getScalarType(); 10552 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10553 if (AllowTruncation || (CVT == NSVT)) 10554 return CN; 10555 } 10556 } 10557 10558 return nullptr; 10559 } 10560 10561 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10562 bool AllowUndefs, 10563 bool AllowTruncation) { 10564 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10565 return CN; 10566 10567 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10568 BitVector UndefElements; 10569 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10570 10571 // BuildVectors can truncate their operands. Ignore that case here unless 10572 // AllowTruncation is set. 10573 if (CN && (UndefElements.none() || AllowUndefs)) { 10574 EVT CVT = CN->getValueType(0); 10575 EVT NSVT = N.getValueType().getScalarType(); 10576 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10577 if (AllowTruncation || (CVT == NSVT)) 10578 return CN; 10579 } 10580 } 10581 10582 return nullptr; 10583 } 10584 10585 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10586 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10587 return CN; 10588 10589 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10590 BitVector UndefElements; 10591 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10592 if (CN && (UndefElements.none() || AllowUndefs)) 10593 return CN; 10594 } 10595 10596 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10597 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10598 return CN; 10599 10600 return nullptr; 10601 } 10602 10603 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10604 const APInt &DemandedElts, 10605 bool AllowUndefs) { 10606 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10607 return CN; 10608 10609 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10610 BitVector UndefElements; 10611 ConstantFPSDNode *CN = 10612 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10613 if (CN && (UndefElements.none() || AllowUndefs)) 10614 return CN; 10615 } 10616 10617 return nullptr; 10618 } 10619 10620 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10621 // TODO: may want to use peekThroughBitcast() here. 10622 ConstantSDNode *C = 10623 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10624 return C && C->isZero(); 10625 } 10626 10627 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10628 // TODO: may want to use peekThroughBitcast() here. 10629 unsigned BitWidth = N.getScalarValueSizeInBits(); 10630 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10631 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10632 } 10633 10634 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10635 N = peekThroughBitcasts(N); 10636 unsigned BitWidth = N.getScalarValueSizeInBits(); 10637 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10638 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10639 } 10640 10641 HandleSDNode::~HandleSDNode() { 10642 DropOperands(); 10643 } 10644 10645 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10646 const DebugLoc &DL, 10647 const GlobalValue *GA, EVT VT, 10648 int64_t o, unsigned TF) 10649 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10650 TheGlobal = GA; 10651 } 10652 10653 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10654 EVT VT, unsigned SrcAS, 10655 unsigned DestAS) 10656 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10657 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10658 10659 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10660 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10661 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10662 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10663 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10664 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10665 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10666 10667 // We check here that the size of the memory operand fits within the size of 10668 // the MMO. This is because the MMO might indicate only a possible address 10669 // range instead of specifying the affected memory addresses precisely. 10670 // TODO: Make MachineMemOperands aware of scalable vectors. 10671 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10672 "Size mismatch!"); 10673 } 10674 10675 /// Profile - Gather unique data for the node. 10676 /// 10677 void SDNode::Profile(FoldingSetNodeID &ID) const { 10678 AddNodeIDNode(ID, this); 10679 } 10680 10681 namespace { 10682 10683 struct EVTArray { 10684 std::vector<EVT> VTs; 10685 10686 EVTArray() { 10687 VTs.reserve(MVT::VALUETYPE_SIZE); 10688 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10689 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10690 } 10691 }; 10692 10693 } // end anonymous namespace 10694 10695 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10696 static ManagedStatic<EVTArray> SimpleVTArray; 10697 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10698 10699 /// getValueTypeList - Return a pointer to the specified value type. 10700 /// 10701 const EVT *SDNode::getValueTypeList(EVT VT) { 10702 if (VT.isExtended()) { 10703 sys::SmartScopedLock<true> Lock(*VTMutex); 10704 return &(*EVTs->insert(VT).first); 10705 } 10706 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10707 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10708 } 10709 10710 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10711 /// indicated value. This method ignores uses of other values defined by this 10712 /// operation. 10713 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10714 assert(Value < getNumValues() && "Bad value!"); 10715 10716 // TODO: Only iterate over uses of a given value of the node 10717 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10718 if (UI.getUse().getResNo() == Value) { 10719 if (NUses == 0) 10720 return false; 10721 --NUses; 10722 } 10723 } 10724 10725 // Found exactly the right number of uses? 10726 return NUses == 0; 10727 } 10728 10729 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10730 /// value. This method ignores uses of other values defined by this operation. 10731 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10732 assert(Value < getNumValues() && "Bad value!"); 10733 10734 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10735 if (UI.getUse().getResNo() == Value) 10736 return true; 10737 10738 return false; 10739 } 10740 10741 /// isOnlyUserOf - Return true if this node is the only use of N. 10742 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10743 bool Seen = false; 10744 for (const SDNode *User : N->uses()) { 10745 if (User == this) 10746 Seen = true; 10747 else 10748 return false; 10749 } 10750 10751 return Seen; 10752 } 10753 10754 /// Return true if the only users of N are contained in Nodes. 10755 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10756 bool Seen = false; 10757 for (const SDNode *User : N->uses()) { 10758 if (llvm::is_contained(Nodes, User)) 10759 Seen = true; 10760 else 10761 return false; 10762 } 10763 10764 return Seen; 10765 } 10766 10767 /// isOperand - Return true if this node is an operand of N. 10768 bool SDValue::isOperandOf(const SDNode *N) const { 10769 return is_contained(N->op_values(), *this); 10770 } 10771 10772 bool SDNode::isOperandOf(const SDNode *N) const { 10773 return any_of(N->op_values(), 10774 [this](SDValue Op) { return this == Op.getNode(); }); 10775 } 10776 10777 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10778 /// be a chain) reaches the specified operand without crossing any 10779 /// side-effecting instructions on any chain path. In practice, this looks 10780 /// through token factors and non-volatile loads. In order to remain efficient, 10781 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10782 /// 10783 /// Note that we only need to examine chains when we're searching for 10784 /// side-effects; SelectionDAG requires that all side-effects are represented 10785 /// by chains, even if another operand would force a specific ordering. This 10786 /// constraint is necessary to allow transformations like splitting loads. 10787 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10788 unsigned Depth) const { 10789 if (*this == Dest) return true; 10790 10791 // Don't search too deeply, we just want to be able to see through 10792 // TokenFactor's etc. 10793 if (Depth == 0) return false; 10794 10795 // If this is a token factor, all inputs to the TF happen in parallel. 10796 if (getOpcode() == ISD::TokenFactor) { 10797 // First, try a shallow search. 10798 if (is_contained((*this)->ops(), Dest)) { 10799 // We found the chain we want as an operand of this TokenFactor. 10800 // Essentially, we reach the chain without side-effects if we could 10801 // serialize the TokenFactor into a simple chain of operations with 10802 // Dest as the last operation. This is automatically true if the 10803 // chain has one use: there are no other ordering constraints. 10804 // If the chain has more than one use, we give up: some other 10805 // use of Dest might force a side-effect between Dest and the current 10806 // node. 10807 if (Dest.hasOneUse()) 10808 return true; 10809 } 10810 // Next, try a deep search: check whether every operand of the TokenFactor 10811 // reaches Dest. 10812 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10813 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10814 }); 10815 } 10816 10817 // Loads don't have side effects, look through them. 10818 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10819 if (Ld->isUnordered()) 10820 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10821 } 10822 return false; 10823 } 10824 10825 bool SDNode::hasPredecessor(const SDNode *N) const { 10826 SmallPtrSet<const SDNode *, 32> Visited; 10827 SmallVector<const SDNode *, 16> Worklist; 10828 Worklist.push_back(this); 10829 return hasPredecessorHelper(N, Visited, Worklist); 10830 } 10831 10832 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10833 this->Flags.intersectWith(Flags); 10834 } 10835 10836 SDValue 10837 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10838 ArrayRef<ISD::NodeType> CandidateBinOps, 10839 bool AllowPartials) { 10840 // The pattern must end in an extract from index 0. 10841 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10842 !isNullConstant(Extract->getOperand(1))) 10843 return SDValue(); 10844 10845 // Match against one of the candidate binary ops. 10846 SDValue Op = Extract->getOperand(0); 10847 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10848 return Op.getOpcode() == unsigned(BinOp); 10849 })) 10850 return SDValue(); 10851 10852 // Floating-point reductions may require relaxed constraints on the final step 10853 // of the reduction because they may reorder intermediate operations. 10854 unsigned CandidateBinOp = Op.getOpcode(); 10855 if (Op.getValueType().isFloatingPoint()) { 10856 SDNodeFlags Flags = Op->getFlags(); 10857 switch (CandidateBinOp) { 10858 case ISD::FADD: 10859 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10860 return SDValue(); 10861 break; 10862 default: 10863 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10864 } 10865 } 10866 10867 // Matching failed - attempt to see if we did enough stages that a partial 10868 // reduction from a subvector is possible. 10869 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10870 if (!AllowPartials || !Op) 10871 return SDValue(); 10872 EVT OpVT = Op.getValueType(); 10873 EVT OpSVT = OpVT.getScalarType(); 10874 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10875 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10876 return SDValue(); 10877 BinOp = (ISD::NodeType)CandidateBinOp; 10878 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10879 getVectorIdxConstant(0, SDLoc(Op))); 10880 }; 10881 10882 // At each stage, we're looking for something that looks like: 10883 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10884 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10885 // i32 undef, i32 undef, i32 undef, i32 undef> 10886 // %a = binop <8 x i32> %op, %s 10887 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10888 // we expect something like: 10889 // <4,5,6,7,u,u,u,u> 10890 // <2,3,u,u,u,u,u,u> 10891 // <1,u,u,u,u,u,u,u> 10892 // While a partial reduction match would be: 10893 // <2,3,u,u,u,u,u,u> 10894 // <1,u,u,u,u,u,u,u> 10895 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10896 SDValue PrevOp; 10897 for (unsigned i = 0; i < Stages; ++i) { 10898 unsigned MaskEnd = (1 << i); 10899 10900 if (Op.getOpcode() != CandidateBinOp) 10901 return PartialReduction(PrevOp, MaskEnd); 10902 10903 SDValue Op0 = Op.getOperand(0); 10904 SDValue Op1 = Op.getOperand(1); 10905 10906 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10907 if (Shuffle) { 10908 Op = Op1; 10909 } else { 10910 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10911 Op = Op0; 10912 } 10913 10914 // The first operand of the shuffle should be the same as the other operand 10915 // of the binop. 10916 if (!Shuffle || Shuffle->getOperand(0) != Op) 10917 return PartialReduction(PrevOp, MaskEnd); 10918 10919 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10920 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10921 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10922 return PartialReduction(PrevOp, MaskEnd); 10923 10924 PrevOp = Op; 10925 } 10926 10927 // Handle subvector reductions, which tend to appear after the shuffle 10928 // reduction stages. 10929 while (Op.getOpcode() == CandidateBinOp) { 10930 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10931 SDValue Op0 = Op.getOperand(0); 10932 SDValue Op1 = Op.getOperand(1); 10933 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10934 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10935 Op0.getOperand(0) != Op1.getOperand(0)) 10936 break; 10937 SDValue Src = Op0.getOperand(0); 10938 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10939 if (NumSrcElts != (2 * NumElts)) 10940 break; 10941 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10942 Op1.getConstantOperandAPInt(1) == NumElts) && 10943 !(Op1.getConstantOperandAPInt(1) == 0 && 10944 Op0.getConstantOperandAPInt(1) == NumElts)) 10945 break; 10946 Op = Src; 10947 } 10948 10949 BinOp = (ISD::NodeType)CandidateBinOp; 10950 return Op; 10951 } 10952 10953 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10954 assert(N->getNumValues() == 1 && 10955 "Can't unroll a vector with multiple results!"); 10956 10957 EVT VT = N->getValueType(0); 10958 unsigned NE = VT.getVectorNumElements(); 10959 EVT EltVT = VT.getVectorElementType(); 10960 SDLoc dl(N); 10961 10962 SmallVector<SDValue, 8> Scalars; 10963 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10964 10965 // If ResNE is 0, fully unroll the vector op. 10966 if (ResNE == 0) 10967 ResNE = NE; 10968 else if (NE > ResNE) 10969 NE = ResNE; 10970 10971 unsigned i; 10972 for (i= 0; i != NE; ++i) { 10973 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10974 SDValue Operand = N->getOperand(j); 10975 EVT OperandVT = Operand.getValueType(); 10976 if (OperandVT.isVector()) { 10977 // A vector operand; extract a single element. 10978 EVT OperandEltVT = OperandVT.getVectorElementType(); 10979 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10980 Operand, getVectorIdxConstant(i, dl)); 10981 } else { 10982 // A scalar operand; just use it as is. 10983 Operands[j] = Operand; 10984 } 10985 } 10986 10987 switch (N->getOpcode()) { 10988 default: { 10989 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10990 N->getFlags())); 10991 break; 10992 } 10993 case ISD::VSELECT: 10994 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10995 break; 10996 case ISD::SHL: 10997 case ISD::SRA: 10998 case ISD::SRL: 10999 case ISD::ROTL: 11000 case ISD::ROTR: 11001 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 11002 getShiftAmountOperand(Operands[0].getValueType(), 11003 Operands[1]))); 11004 break; 11005 case ISD::SIGN_EXTEND_INREG: { 11006 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 11007 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 11008 Operands[0], 11009 getValueType(ExtVT))); 11010 } 11011 } 11012 } 11013 11014 for (; i < ResNE; ++i) 11015 Scalars.push_back(getUNDEF(EltVT)); 11016 11017 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 11018 return getBuildVector(VecVT, dl, Scalars); 11019 } 11020 11021 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 11022 SDNode *N, unsigned ResNE) { 11023 unsigned Opcode = N->getOpcode(); 11024 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 11025 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 11026 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 11027 "Expected an overflow opcode"); 11028 11029 EVT ResVT = N->getValueType(0); 11030 EVT OvVT = N->getValueType(1); 11031 EVT ResEltVT = ResVT.getVectorElementType(); 11032 EVT OvEltVT = OvVT.getVectorElementType(); 11033 SDLoc dl(N); 11034 11035 // If ResNE is 0, fully unroll the vector op. 11036 unsigned NE = ResVT.getVectorNumElements(); 11037 if (ResNE == 0) 11038 ResNE = NE; 11039 else if (NE > ResNE) 11040 NE = ResNE; 11041 11042 SmallVector<SDValue, 8> LHSScalars; 11043 SmallVector<SDValue, 8> RHSScalars; 11044 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 11045 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 11046 11047 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 11048 SDVTList VTs = getVTList(ResEltVT, SVT); 11049 SmallVector<SDValue, 8> ResScalars; 11050 SmallVector<SDValue, 8> OvScalars; 11051 for (unsigned i = 0; i < NE; ++i) { 11052 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 11053 SDValue Ov = 11054 getSelect(dl, OvEltVT, Res.getValue(1), 11055 getBoolConstant(true, dl, OvEltVT, ResVT), 11056 getConstant(0, dl, OvEltVT)); 11057 11058 ResScalars.push_back(Res); 11059 OvScalars.push_back(Ov); 11060 } 11061 11062 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 11063 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 11064 11065 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 11066 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 11067 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 11068 getBuildVector(NewOvVT, dl, OvScalars)); 11069 } 11070 11071 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 11072 LoadSDNode *Base, 11073 unsigned Bytes, 11074 int Dist) const { 11075 if (LD->isVolatile() || Base->isVolatile()) 11076 return false; 11077 // TODO: probably too restrictive for atomics, revisit 11078 if (!LD->isSimple()) 11079 return false; 11080 if (LD->isIndexed() || Base->isIndexed()) 11081 return false; 11082 if (LD->getChain() != Base->getChain()) 11083 return false; 11084 EVT VT = LD->getValueType(0); 11085 if (VT.getSizeInBits() / 8 != Bytes) 11086 return false; 11087 11088 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 11089 auto LocDecomp = BaseIndexOffset::match(LD, *this); 11090 11091 int64_t Offset = 0; 11092 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 11093 return (Dist * Bytes == Offset); 11094 return false; 11095 } 11096 11097 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 11098 /// if it cannot be inferred. 11099 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 11100 // If this is a GlobalAddress + cst, return the alignment. 11101 const GlobalValue *GV = nullptr; 11102 int64_t GVOffset = 0; 11103 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 11104 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 11105 KnownBits Known(PtrWidth); 11106 llvm::computeKnownBits(GV, Known, getDataLayout()); 11107 unsigned AlignBits = Known.countMinTrailingZeros(); 11108 if (AlignBits) 11109 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 11110 } 11111 11112 // If this is a direct reference to a stack slot, use information about the 11113 // stack slot's alignment. 11114 int FrameIdx = INT_MIN; 11115 int64_t FrameOffset = 0; 11116 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 11117 FrameIdx = FI->getIndex(); 11118 } else if (isBaseWithConstantOffset(Ptr) && 11119 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 11120 // Handle FI+Cst 11121 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 11122 FrameOffset = Ptr.getConstantOperandVal(1); 11123 } 11124 11125 if (FrameIdx != INT_MIN) { 11126 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 11127 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 11128 } 11129 11130 return None; 11131 } 11132 11133 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 11134 /// which is split (or expanded) into two not necessarily identical pieces. 11135 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 11136 // Currently all types are split in half. 11137 EVT LoVT, HiVT; 11138 if (!VT.isVector()) 11139 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 11140 else 11141 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 11142 11143 return std::make_pair(LoVT, HiVT); 11144 } 11145 11146 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 11147 /// type, dependent on an enveloping VT that has been split into two identical 11148 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 11149 std::pair<EVT, EVT> 11150 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 11151 bool *HiIsEmpty) const { 11152 EVT EltTp = VT.getVectorElementType(); 11153 // Examples: 11154 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 11155 // custom VL=9 with enveloping VL=8/8 yields 8/1 11156 // custom VL=10 with enveloping VL=8/8 yields 8/2 11157 // etc. 11158 ElementCount VTNumElts = VT.getVectorElementCount(); 11159 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 11160 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 11161 "Mixing fixed width and scalable vectors when enveloping a type"); 11162 EVT LoVT, HiVT; 11163 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 11164 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11165 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 11166 *HiIsEmpty = false; 11167 } else { 11168 // Flag that hi type has zero storage size, but return split envelop type 11169 // (this would be easier if vector types with zero elements were allowed). 11170 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 11171 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 11172 *HiIsEmpty = true; 11173 } 11174 return std::make_pair(LoVT, HiVT); 11175 } 11176 11177 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 11178 /// low/high part. 11179 std::pair<SDValue, SDValue> 11180 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 11181 const EVT &HiVT) { 11182 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 11183 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 11184 "Splitting vector with an invalid mixture of fixed and scalable " 11185 "vector types"); 11186 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 11187 N.getValueType().getVectorMinNumElements() && 11188 "More vector elements requested than available!"); 11189 SDValue Lo, Hi; 11190 Lo = 11191 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 11192 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 11193 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 11194 // IDX with the runtime scaling factor of the result vector type. For 11195 // fixed-width result vectors, that runtime scaling factor is 1. 11196 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 11197 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 11198 return std::make_pair(Lo, Hi); 11199 } 11200 11201 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 11202 const SDLoc &DL) { 11203 // Split the vector length parameter. 11204 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 11205 EVT VT = N.getValueType(); 11206 assert(VecVT.getVectorElementCount().isKnownEven() && 11207 "Expecting the mask to be an evenly-sized vector"); 11208 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 11209 SDValue HalfNumElts = 11210 VecVT.isFixedLengthVector() 11211 ? getConstant(HalfMinNumElts, DL, VT) 11212 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 11213 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 11214 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 11215 return std::make_pair(Lo, Hi); 11216 } 11217 11218 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 11219 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 11220 EVT VT = N.getValueType(); 11221 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 11222 NextPowerOf2(VT.getVectorNumElements())); 11223 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 11224 getVectorIdxConstant(0, DL)); 11225 } 11226 11227 void SelectionDAG::ExtractVectorElements(SDValue Op, 11228 SmallVectorImpl<SDValue> &Args, 11229 unsigned Start, unsigned Count, 11230 EVT EltVT) { 11231 EVT VT = Op.getValueType(); 11232 if (Count == 0) 11233 Count = VT.getVectorNumElements(); 11234 if (EltVT == EVT()) 11235 EltVT = VT.getVectorElementType(); 11236 SDLoc SL(Op); 11237 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 11238 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 11239 getVectorIdxConstant(i, SL))); 11240 } 11241 } 11242 11243 // getAddressSpace - Return the address space this GlobalAddress belongs to. 11244 unsigned GlobalAddressSDNode::getAddressSpace() const { 11245 return getGlobal()->getType()->getAddressSpace(); 11246 } 11247 11248 Type *ConstantPoolSDNode::getType() const { 11249 if (isMachineConstantPoolEntry()) 11250 return Val.MachineCPVal->getType(); 11251 return Val.ConstVal->getType(); 11252 } 11253 11254 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 11255 unsigned &SplatBitSize, 11256 bool &HasAnyUndefs, 11257 unsigned MinSplatBits, 11258 bool IsBigEndian) const { 11259 EVT VT = getValueType(0); 11260 assert(VT.isVector() && "Expected a vector type"); 11261 unsigned VecWidth = VT.getSizeInBits(); 11262 if (MinSplatBits > VecWidth) 11263 return false; 11264 11265 // FIXME: The widths are based on this node's type, but build vectors can 11266 // truncate their operands. 11267 SplatValue = APInt(VecWidth, 0); 11268 SplatUndef = APInt(VecWidth, 0); 11269 11270 // Get the bits. Bits with undefined values (when the corresponding element 11271 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 11272 // in SplatValue. If any of the values are not constant, give up and return 11273 // false. 11274 unsigned int NumOps = getNumOperands(); 11275 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 11276 unsigned EltWidth = VT.getScalarSizeInBits(); 11277 11278 for (unsigned j = 0; j < NumOps; ++j) { 11279 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 11280 SDValue OpVal = getOperand(i); 11281 unsigned BitPos = j * EltWidth; 11282 11283 if (OpVal.isUndef()) 11284 SplatUndef.setBits(BitPos, BitPos + EltWidth); 11285 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 11286 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 11287 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 11288 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 11289 else 11290 return false; 11291 } 11292 11293 // The build_vector is all constants or undefs. Find the smallest element 11294 // size that splats the vector. 11295 HasAnyUndefs = (SplatUndef != 0); 11296 11297 // FIXME: This does not work for vectors with elements less than 8 bits. 11298 while (VecWidth > 8) { 11299 unsigned HalfSize = VecWidth / 2; 11300 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 11301 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 11302 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 11303 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 11304 11305 // If the two halves do not match (ignoring undef bits), stop here. 11306 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 11307 MinSplatBits > HalfSize) 11308 break; 11309 11310 SplatValue = HighValue | LowValue; 11311 SplatUndef = HighUndef & LowUndef; 11312 11313 VecWidth = HalfSize; 11314 } 11315 11316 SplatBitSize = VecWidth; 11317 return true; 11318 } 11319 11320 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 11321 BitVector *UndefElements) const { 11322 unsigned NumOps = getNumOperands(); 11323 if (UndefElements) { 11324 UndefElements->clear(); 11325 UndefElements->resize(NumOps); 11326 } 11327 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11328 if (!DemandedElts) 11329 return SDValue(); 11330 SDValue Splatted; 11331 for (unsigned i = 0; i != NumOps; ++i) { 11332 if (!DemandedElts[i]) 11333 continue; 11334 SDValue Op = getOperand(i); 11335 if (Op.isUndef()) { 11336 if (UndefElements) 11337 (*UndefElements)[i] = true; 11338 } else if (!Splatted) { 11339 Splatted = Op; 11340 } else if (Splatted != Op) { 11341 return SDValue(); 11342 } 11343 } 11344 11345 if (!Splatted) { 11346 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 11347 assert(getOperand(FirstDemandedIdx).isUndef() && 11348 "Can only have a splat without a constant for all undefs."); 11349 return getOperand(FirstDemandedIdx); 11350 } 11351 11352 return Splatted; 11353 } 11354 11355 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 11356 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11357 return getSplatValue(DemandedElts, UndefElements); 11358 } 11359 11360 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 11361 SmallVectorImpl<SDValue> &Sequence, 11362 BitVector *UndefElements) const { 11363 unsigned NumOps = getNumOperands(); 11364 Sequence.clear(); 11365 if (UndefElements) { 11366 UndefElements->clear(); 11367 UndefElements->resize(NumOps); 11368 } 11369 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 11370 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 11371 return false; 11372 11373 // Set the undefs even if we don't find a sequence (like getSplatValue). 11374 if (UndefElements) 11375 for (unsigned I = 0; I != NumOps; ++I) 11376 if (DemandedElts[I] && getOperand(I).isUndef()) 11377 (*UndefElements)[I] = true; 11378 11379 // Iteratively widen the sequence length looking for repetitions. 11380 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 11381 Sequence.append(SeqLen, SDValue()); 11382 for (unsigned I = 0; I != NumOps; ++I) { 11383 if (!DemandedElts[I]) 11384 continue; 11385 SDValue &SeqOp = Sequence[I % SeqLen]; 11386 SDValue Op = getOperand(I); 11387 if (Op.isUndef()) { 11388 if (!SeqOp) 11389 SeqOp = Op; 11390 continue; 11391 } 11392 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 11393 Sequence.clear(); 11394 break; 11395 } 11396 SeqOp = Op; 11397 } 11398 if (!Sequence.empty()) 11399 return true; 11400 } 11401 11402 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 11403 return false; 11404 } 11405 11406 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 11407 BitVector *UndefElements) const { 11408 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 11409 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 11410 } 11411 11412 ConstantSDNode * 11413 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 11414 BitVector *UndefElements) const { 11415 return dyn_cast_or_null<ConstantSDNode>( 11416 getSplatValue(DemandedElts, UndefElements)); 11417 } 11418 11419 ConstantSDNode * 11420 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 11421 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 11422 } 11423 11424 ConstantFPSDNode * 11425 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 11426 BitVector *UndefElements) const { 11427 return dyn_cast_or_null<ConstantFPSDNode>( 11428 getSplatValue(DemandedElts, UndefElements)); 11429 } 11430 11431 ConstantFPSDNode * 11432 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 11433 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 11434 } 11435 11436 int32_t 11437 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 11438 uint32_t BitWidth) const { 11439 if (ConstantFPSDNode *CN = 11440 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 11441 bool IsExact; 11442 APSInt IntVal(BitWidth); 11443 const APFloat &APF = CN->getValueAPF(); 11444 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 11445 APFloat::opOK || 11446 !IsExact) 11447 return -1; 11448 11449 return IntVal.exactLogBase2(); 11450 } 11451 return -1; 11452 } 11453 11454 bool BuildVectorSDNode::getConstantRawBits( 11455 bool IsLittleEndian, unsigned DstEltSizeInBits, 11456 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 11457 // Early-out if this contains anything but Undef/Constant/ConstantFP. 11458 if (!isConstant()) 11459 return false; 11460 11461 unsigned NumSrcOps = getNumOperands(); 11462 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 11463 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11464 "Invalid bitcast scale"); 11465 11466 // Extract raw src bits. 11467 SmallVector<APInt> SrcBitElements(NumSrcOps, 11468 APInt::getNullValue(SrcEltSizeInBits)); 11469 BitVector SrcUndeElements(NumSrcOps, false); 11470 11471 for (unsigned I = 0; I != NumSrcOps; ++I) { 11472 SDValue Op = getOperand(I); 11473 if (Op.isUndef()) { 11474 SrcUndeElements.set(I); 11475 continue; 11476 } 11477 auto *CInt = dyn_cast<ConstantSDNode>(Op); 11478 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 11479 assert((CInt || CFP) && "Unknown constant"); 11480 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits) 11481 : CFP->getValueAPF().bitcastToAPInt(); 11482 } 11483 11484 // Recast to dst width. 11485 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 11486 SrcBitElements, UndefElements, SrcUndeElements); 11487 return true; 11488 } 11489 11490 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11491 unsigned DstEltSizeInBits, 11492 SmallVectorImpl<APInt> &DstBitElements, 11493 ArrayRef<APInt> SrcBitElements, 11494 BitVector &DstUndefElements, 11495 const BitVector &SrcUndefElements) { 11496 unsigned NumSrcOps = SrcBitElements.size(); 11497 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11498 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11499 "Invalid bitcast scale"); 11500 assert(NumSrcOps == SrcUndefElements.size() && 11501 "Vector size mismatch"); 11502 11503 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11504 DstUndefElements.clear(); 11505 DstUndefElements.resize(NumDstOps, false); 11506 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11507 11508 // Concatenate src elements constant bits together into dst element. 11509 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11510 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11511 for (unsigned I = 0; I != NumDstOps; ++I) { 11512 DstUndefElements.set(I); 11513 APInt &DstBits = DstBitElements[I]; 11514 for (unsigned J = 0; J != Scale; ++J) { 11515 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11516 if (SrcUndefElements[Idx]) 11517 continue; 11518 DstUndefElements.reset(I); 11519 const APInt &SrcBits = SrcBitElements[Idx]; 11520 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11521 "Illegal constant bitwidths"); 11522 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11523 } 11524 } 11525 return; 11526 } 11527 11528 // Split src element constant bits into dst elements. 11529 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11530 for (unsigned I = 0; I != NumSrcOps; ++I) { 11531 if (SrcUndefElements[I]) { 11532 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11533 continue; 11534 } 11535 const APInt &SrcBits = SrcBitElements[I]; 11536 for (unsigned J = 0; J != Scale; ++J) { 11537 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11538 APInt &DstBits = DstBitElements[Idx]; 11539 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11540 } 11541 } 11542 } 11543 11544 bool BuildVectorSDNode::isConstant() const { 11545 for (const SDValue &Op : op_values()) { 11546 unsigned Opc = Op.getOpcode(); 11547 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11548 return false; 11549 } 11550 return true; 11551 } 11552 11553 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11554 // Find the first non-undef value in the shuffle mask. 11555 unsigned i, e; 11556 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11557 /* search */; 11558 11559 // If all elements are undefined, this shuffle can be considered a splat 11560 // (although it should eventually get simplified away completely). 11561 if (i == e) 11562 return true; 11563 11564 // Make sure all remaining elements are either undef or the same as the first 11565 // non-undef value. 11566 for (int Idx = Mask[i]; i != e; ++i) 11567 if (Mask[i] >= 0 && Mask[i] != Idx) 11568 return false; 11569 return true; 11570 } 11571 11572 // Returns the SDNode if it is a constant integer BuildVector 11573 // or constant integer. 11574 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11575 if (isa<ConstantSDNode>(N)) 11576 return N.getNode(); 11577 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11578 return N.getNode(); 11579 // Treat a GlobalAddress supporting constant offset folding as a 11580 // constant integer. 11581 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11582 if (GA->getOpcode() == ISD::GlobalAddress && 11583 TLI->isOffsetFoldingLegal(GA)) 11584 return GA; 11585 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11586 isa<ConstantSDNode>(N.getOperand(0))) 11587 return N.getNode(); 11588 return nullptr; 11589 } 11590 11591 // Returns the SDNode if it is a constant float BuildVector 11592 // or constant float. 11593 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11594 if (isa<ConstantFPSDNode>(N)) 11595 return N.getNode(); 11596 11597 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11598 return N.getNode(); 11599 11600 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11601 isa<ConstantFPSDNode>(N.getOperand(0))) 11602 return N.getNode(); 11603 11604 return nullptr; 11605 } 11606 11607 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11608 assert(!Node->OperandList && "Node already has operands"); 11609 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11610 "too many operands to fit into SDNode"); 11611 SDUse *Ops = OperandRecycler.allocate( 11612 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11613 11614 bool IsDivergent = false; 11615 for (unsigned I = 0; I != Vals.size(); ++I) { 11616 Ops[I].setUser(Node); 11617 Ops[I].setInitial(Vals[I]); 11618 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11619 IsDivergent |= Ops[I].getNode()->isDivergent(); 11620 } 11621 Node->NumOperands = Vals.size(); 11622 Node->OperandList = Ops; 11623 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11624 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11625 Node->SDNodeBits.IsDivergent = IsDivergent; 11626 } 11627 checkForCycles(Node); 11628 } 11629 11630 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11631 SmallVectorImpl<SDValue> &Vals) { 11632 size_t Limit = SDNode::getMaxNumOperands(); 11633 while (Vals.size() > Limit) { 11634 unsigned SliceIdx = Vals.size() - Limit; 11635 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11636 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11637 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11638 Vals.emplace_back(NewTF); 11639 } 11640 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11641 } 11642 11643 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11644 EVT VT, SDNodeFlags Flags) { 11645 switch (Opcode) { 11646 default: 11647 return SDValue(); 11648 case ISD::ADD: 11649 case ISD::OR: 11650 case ISD::XOR: 11651 case ISD::UMAX: 11652 return getConstant(0, DL, VT); 11653 case ISD::MUL: 11654 return getConstant(1, DL, VT); 11655 case ISD::AND: 11656 case ISD::UMIN: 11657 return getAllOnesConstant(DL, VT); 11658 case ISD::SMAX: 11659 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11660 case ISD::SMIN: 11661 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11662 case ISD::FADD: 11663 return getConstantFP(-0.0, DL, VT); 11664 case ISD::FMUL: 11665 return getConstantFP(1.0, DL, VT); 11666 case ISD::FMINNUM: 11667 case ISD::FMAXNUM: { 11668 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11669 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11670 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11671 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11672 APFloat::getLargest(Semantics); 11673 if (Opcode == ISD::FMAXNUM) 11674 NeutralAF.changeSign(); 11675 11676 return getConstantFP(NeutralAF, DL, VT); 11677 } 11678 } 11679 } 11680 11681 #ifndef NDEBUG 11682 static void checkForCyclesHelper(const SDNode *N, 11683 SmallPtrSetImpl<const SDNode*> &Visited, 11684 SmallPtrSetImpl<const SDNode*> &Checked, 11685 const llvm::SelectionDAG *DAG) { 11686 // If this node has already been checked, don't check it again. 11687 if (Checked.count(N)) 11688 return; 11689 11690 // If a node has already been visited on this depth-first walk, reject it as 11691 // a cycle. 11692 if (!Visited.insert(N).second) { 11693 errs() << "Detected cycle in SelectionDAG\n"; 11694 dbgs() << "Offending node:\n"; 11695 N->dumprFull(DAG); dbgs() << "\n"; 11696 abort(); 11697 } 11698 11699 for (const SDValue &Op : N->op_values()) 11700 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11701 11702 Checked.insert(N); 11703 Visited.erase(N); 11704 } 11705 #endif 11706 11707 void llvm::checkForCycles(const llvm::SDNode *N, 11708 const llvm::SelectionDAG *DAG, 11709 bool force) { 11710 #ifndef NDEBUG 11711 bool check = force; 11712 #ifdef EXPENSIVE_CHECKS 11713 check = true; 11714 #endif // EXPENSIVE_CHECKS 11715 if (check) { 11716 assert(N && "Checking nonexistent SDNode"); 11717 SmallPtrSet<const SDNode*, 32> visited; 11718 SmallPtrSet<const SDNode*, 32> checked; 11719 checkForCyclesHelper(N, visited, checked, DAG); 11720 } 11721 #endif // !NDEBUG 11722 } 11723 11724 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11725 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11726 } 11727