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/BlockFrequencyInfo.h" 28 #include "llvm/Analysis/MemoryLocation.h" 29 #include "llvm/Analysis/ProfileSummaryInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/CodeGen/Analysis.h" 32 #include "llvm/CodeGen/FunctionLoweringInfo.h" 33 #include "llvm/CodeGen/ISDOpcodes.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineConstantPool.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineMemOperand.h" 39 #include "llvm/CodeGen/RuntimeLibcalls.h" 40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 41 #include "llvm/CodeGen/SelectionDAGNodes.h" 42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 43 #include "llvm/CodeGen/TargetFrameLowering.h" 44 #include "llvm/CodeGen/TargetLowering.h" 45 #include "llvm/CodeGen/TargetRegisterInfo.h" 46 #include "llvm/CodeGen/TargetSubtargetInfo.h" 47 #include "llvm/CodeGen/ValueTypes.h" 48 #include "llvm/IR/Constant.h" 49 #include "llvm/IR/Constants.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DebugInfoMetadata.h" 52 #include "llvm/IR/DebugLoc.h" 53 #include "llvm/IR/DerivedTypes.h" 54 #include "llvm/IR/Function.h" 55 #include "llvm/IR/GlobalValue.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/IR/Type.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CodeGen.h" 61 #include "llvm/Support/Compiler.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/KnownBits.h" 65 #include "llvm/Support/MachineValueType.h" 66 #include "llvm/Support/ManagedStatic.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/Mutex.h" 69 #include "llvm/Support/raw_ostream.h" 70 #include "llvm/Target/TargetMachine.h" 71 #include "llvm/Target/TargetOptions.h" 72 #include "llvm/Transforms/Utils/SizeOpts.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstdint> 76 #include <cstdlib> 77 #include <limits> 78 #include <set> 79 #include <string> 80 #include <utility> 81 #include <vector> 82 83 using namespace llvm; 84 85 /// makeVTList - Return an instance of the SDVTList struct initialized with the 86 /// specified members. 87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 88 SDVTList Res = {VTs, NumVTs}; 89 return Res; 90 } 91 92 // Default null implementations of the callbacks. 93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 96 97 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 98 99 #define DEBUG_TYPE "selectiondag" 100 101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 102 cl::Hidden, cl::init(true), 103 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 104 105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 106 cl::desc("Number limit for gluing ld/st of memcpy."), 107 cl::Hidden, cl::init(0)); 108 109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 110 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 111 } 112 113 //===----------------------------------------------------------------------===// 114 // ConstantFPSDNode Class 115 //===----------------------------------------------------------------------===// 116 117 /// isExactlyValue - We don't rely on operator== working on double values, as 118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 119 /// As such, this method can be used to do an exact bit-for-bit comparison of 120 /// two floating point values. 121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 122 return getValueAPF().bitwiseIsEqual(V); 123 } 124 125 bool ConstantFPSDNode::isValueValidForType(EVT VT, 126 const APFloat& Val) { 127 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 128 129 // convert modifies in place, so make a copy. 130 APFloat Val2 = APFloat(Val); 131 bool losesInfo; 132 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 133 APFloat::rmNearestTiesToEven, 134 &losesInfo); 135 return !losesInfo; 136 } 137 138 //===----------------------------------------------------------------------===// 139 // ISD Namespace 140 //===----------------------------------------------------------------------===// 141 142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 143 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 144 unsigned EltSize = 145 N->getValueType(0).getVectorElementType().getSizeInBits(); 146 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 147 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize); 148 return true; 149 } 150 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) { 151 SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize); 152 return true; 153 } 154 } 155 156 auto *BV = dyn_cast<BuildVectorSDNode>(N); 157 if (!BV) 158 return false; 159 160 APInt SplatUndef; 161 unsigned SplatBitSize; 162 bool HasUndefs; 163 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 164 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 165 EltSize) && 166 EltSize == SplatBitSize; 167 } 168 169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 170 // specializations of the more general isConstantSplatVector()? 171 172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 173 // Look through a bit convert. 174 while (N->getOpcode() == ISD::BITCAST) 175 N = N->getOperand(0).getNode(); 176 177 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 178 APInt SplatVal; 179 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes(); 180 } 181 182 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 183 184 unsigned i = 0, e = N->getNumOperands(); 185 186 // Skip over all of the undef values. 187 while (i != e && N->getOperand(i).isUndef()) 188 ++i; 189 190 // Do not accept an all-undef vector. 191 if (i == e) return false; 192 193 // Do not accept build_vectors that aren't all constants or which have non-~0 194 // elements. We have to be a bit careful here, as the type of the constant 195 // may not be the same as the type of the vector elements due to type 196 // legalization (the elements are promoted to a legal type for the target and 197 // a vector of a type may be legal when the base element type is not). 198 // We only want to check enough bits to cover the vector elements, because 199 // we care if the resultant vector is all ones, not whether the individual 200 // constants are. 201 SDValue NotZero = N->getOperand(i); 202 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 203 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 204 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 205 return false; 206 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 207 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 208 return false; 209 } else 210 return false; 211 212 // Okay, we have at least one ~0 value, check to see if the rest match or are 213 // undefs. Even with the above element type twiddling, this should be OK, as 214 // the same type legalization should have applied to all the elements. 215 for (++i; i != e; ++i) 216 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 217 return false; 218 return true; 219 } 220 221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 222 // Look through a bit convert. 223 while (N->getOpcode() == ISD::BITCAST) 224 N = N->getOperand(0).getNode(); 225 226 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 227 APInt SplatVal; 228 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero(); 229 } 230 231 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 232 233 bool IsAllUndef = true; 234 for (const SDValue &Op : N->op_values()) { 235 if (Op.isUndef()) 236 continue; 237 IsAllUndef = false; 238 // Do not accept build_vectors that aren't all constants or which have non-0 239 // elements. We have to be a bit careful here, as the type of the constant 240 // may not be the same as the type of the vector elements due to type 241 // legalization (the elements are promoted to a legal type for the target 242 // and a vector of a type may be legal when the base element type is not). 243 // We only want to check enough bits to cover the vector elements, because 244 // we care if the resultant vector is all zeros, not whether the individual 245 // constants are. 246 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 247 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 248 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 249 return false; 250 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 251 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 252 return false; 253 } else 254 return false; 255 } 256 257 // Do not accept an all-undef vector. 258 if (IsAllUndef) 259 return false; 260 return true; 261 } 262 263 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 264 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 265 } 266 267 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 268 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 269 } 270 271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 272 if (N->getOpcode() != ISD::BUILD_VECTOR) 273 return false; 274 275 for (const SDValue &Op : N->op_values()) { 276 if (Op.isUndef()) 277 continue; 278 if (!isa<ConstantSDNode>(Op)) 279 return false; 280 } 281 return true; 282 } 283 284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 285 if (N->getOpcode() != ISD::BUILD_VECTOR) 286 return false; 287 288 for (const SDValue &Op : N->op_values()) { 289 if (Op.isUndef()) 290 continue; 291 if (!isa<ConstantFPSDNode>(Op)) 292 return false; 293 } 294 return true; 295 } 296 297 bool ISD::allOperandsUndef(const SDNode *N) { 298 // Return false if the node has no operands. 299 // This is "logically inconsistent" with the definition of "all" but 300 // is probably the desired behavior. 301 if (N->getNumOperands() == 0) 302 return false; 303 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 304 } 305 306 bool ISD::matchUnaryPredicate(SDValue Op, 307 std::function<bool(ConstantSDNode *)> Match, 308 bool AllowUndefs) { 309 // FIXME: Add support for scalar UNDEF cases? 310 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 311 return Match(Cst); 312 313 // FIXME: Add support for vector UNDEF cases? 314 if (ISD::BUILD_VECTOR != Op.getOpcode() && 315 ISD::SPLAT_VECTOR != Op.getOpcode()) 316 return false; 317 318 EVT SVT = Op.getValueType().getScalarType(); 319 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 320 if (AllowUndefs && Op.getOperand(i).isUndef()) { 321 if (!Match(nullptr)) 322 return false; 323 continue; 324 } 325 326 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 327 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 328 return false; 329 } 330 return true; 331 } 332 333 bool ISD::matchBinaryPredicate( 334 SDValue LHS, SDValue RHS, 335 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 336 bool AllowUndefs, bool AllowTypeMismatch) { 337 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 338 return false; 339 340 // TODO: Add support for scalar UNDEF cases? 341 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 342 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 343 return Match(LHSCst, RHSCst); 344 345 // TODO: Add support for vector UNDEF cases? 346 if (LHS.getOpcode() != RHS.getOpcode() || 347 (LHS.getOpcode() != ISD::BUILD_VECTOR && 348 LHS.getOpcode() != ISD::SPLAT_VECTOR)) 349 return false; 350 351 EVT SVT = LHS.getValueType().getScalarType(); 352 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 353 SDValue LHSOp = LHS.getOperand(i); 354 SDValue RHSOp = RHS.getOperand(i); 355 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 356 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 357 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 358 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 359 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 360 return false; 361 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 362 LHSOp.getValueType() != RHSOp.getValueType())) 363 return false; 364 if (!Match(LHSCst, RHSCst)) 365 return false; 366 } 367 return true; 368 } 369 370 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 371 switch (VecReduceOpcode) { 372 default: 373 llvm_unreachable("Expected VECREDUCE opcode"); 374 case ISD::VECREDUCE_FADD: 375 case ISD::VECREDUCE_SEQ_FADD: 376 case ISD::VP_REDUCE_FADD: 377 case ISD::VP_REDUCE_SEQ_FADD: 378 return ISD::FADD; 379 case ISD::VECREDUCE_FMUL: 380 case ISD::VECREDUCE_SEQ_FMUL: 381 case ISD::VP_REDUCE_FMUL: 382 case ISD::VP_REDUCE_SEQ_FMUL: 383 return ISD::FMUL; 384 case ISD::VECREDUCE_ADD: 385 case ISD::VP_REDUCE_ADD: 386 return ISD::ADD; 387 case ISD::VECREDUCE_MUL: 388 case ISD::VP_REDUCE_MUL: 389 return ISD::MUL; 390 case ISD::VECREDUCE_AND: 391 case ISD::VP_REDUCE_AND: 392 return ISD::AND; 393 case ISD::VECREDUCE_OR: 394 case ISD::VP_REDUCE_OR: 395 return ISD::OR; 396 case ISD::VECREDUCE_XOR: 397 case ISD::VP_REDUCE_XOR: 398 return ISD::XOR; 399 case ISD::VECREDUCE_SMAX: 400 case ISD::VP_REDUCE_SMAX: 401 return ISD::SMAX; 402 case ISD::VECREDUCE_SMIN: 403 case ISD::VP_REDUCE_SMIN: 404 return ISD::SMIN; 405 case ISD::VECREDUCE_UMAX: 406 case ISD::VP_REDUCE_UMAX: 407 return ISD::UMAX; 408 case ISD::VECREDUCE_UMIN: 409 case ISD::VP_REDUCE_UMIN: 410 return ISD::UMIN; 411 case ISD::VECREDUCE_FMAX: 412 case ISD::VP_REDUCE_FMAX: 413 return ISD::FMAXNUM; 414 case ISD::VECREDUCE_FMIN: 415 case ISD::VP_REDUCE_FMIN: 416 return ISD::FMINNUM; 417 } 418 } 419 420 bool ISD::isVPOpcode(unsigned Opcode) { 421 switch (Opcode) { 422 default: 423 return false; 424 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \ 425 case ISD::VPSD: \ 426 return true; 427 #include "llvm/IR/VPIntrinsics.def" 428 } 429 } 430 431 bool ISD::isVPBinaryOp(unsigned Opcode) { 432 switch (Opcode) { 433 default: 434 break; 435 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 436 #define VP_PROPERTY_BINARYOP return true; 437 #define END_REGISTER_VP_SDNODE(VPSD) break; 438 #include "llvm/IR/VPIntrinsics.def" 439 } 440 return false; 441 } 442 443 bool ISD::isVPReduction(unsigned Opcode) { 444 switch (Opcode) { 445 default: 446 break; 447 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD: 448 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true; 449 #define END_REGISTER_VP_SDNODE(VPSD) break; 450 #include "llvm/IR/VPIntrinsics.def" 451 } 452 return false; 453 } 454 455 /// The operand position of the vector mask. 456 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 457 switch (Opcode) { 458 default: 459 return None; 460 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \ 461 case ISD::VPSD: \ 462 return MASKPOS; 463 #include "llvm/IR/VPIntrinsics.def" 464 } 465 } 466 467 /// The operand position of the explicit vector length parameter. 468 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 469 switch (Opcode) { 470 default: 471 return None; 472 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 473 case ISD::VPSD: \ 474 return EVLPOS; 475 #include "llvm/IR/VPIntrinsics.def" 476 } 477 } 478 479 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 480 switch (ExtType) { 481 case ISD::EXTLOAD: 482 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 483 case ISD::SEXTLOAD: 484 return ISD::SIGN_EXTEND; 485 case ISD::ZEXTLOAD: 486 return ISD::ZERO_EXTEND; 487 default: 488 break; 489 } 490 491 llvm_unreachable("Invalid LoadExtType"); 492 } 493 494 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 495 // To perform this operation, we just need to swap the L and G bits of the 496 // operation. 497 unsigned OldL = (Operation >> 2) & 1; 498 unsigned OldG = (Operation >> 1) & 1; 499 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 500 (OldL << 1) | // New G bit 501 (OldG << 2)); // New L bit. 502 } 503 504 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 505 unsigned Operation = Op; 506 if (isIntegerLike) 507 Operation ^= 7; // Flip L, G, E bits, but not U. 508 else 509 Operation ^= 15; // Flip all of the condition bits. 510 511 if (Operation > ISD::SETTRUE2) 512 Operation &= ~8; // Don't let N and U bits get set. 513 514 return ISD::CondCode(Operation); 515 } 516 517 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 518 return getSetCCInverseImpl(Op, Type.isInteger()); 519 } 520 521 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 522 bool isIntegerLike) { 523 return getSetCCInverseImpl(Op, isIntegerLike); 524 } 525 526 /// For an integer comparison, return 1 if the comparison is a signed operation 527 /// and 2 if the result is an unsigned comparison. Return zero if the operation 528 /// does not depend on the sign of the input (setne and seteq). 529 static int isSignedOp(ISD::CondCode Opcode) { 530 switch (Opcode) { 531 default: llvm_unreachable("Illegal integer setcc operation!"); 532 case ISD::SETEQ: 533 case ISD::SETNE: return 0; 534 case ISD::SETLT: 535 case ISD::SETLE: 536 case ISD::SETGT: 537 case ISD::SETGE: return 1; 538 case ISD::SETULT: 539 case ISD::SETULE: 540 case ISD::SETUGT: 541 case ISD::SETUGE: return 2; 542 } 543 } 544 545 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 546 EVT Type) { 547 bool IsInteger = Type.isInteger(); 548 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 549 // Cannot fold a signed integer setcc with an unsigned integer setcc. 550 return ISD::SETCC_INVALID; 551 552 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 553 554 // If the N and U bits get set, then the resultant comparison DOES suddenly 555 // care about orderedness, and it is true when ordered. 556 if (Op > ISD::SETTRUE2) 557 Op &= ~16; // Clear the U bit if the N bit is set. 558 559 // Canonicalize illegal integer setcc's. 560 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 561 Op = ISD::SETNE; 562 563 return ISD::CondCode(Op); 564 } 565 566 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 567 EVT Type) { 568 bool IsInteger = Type.isInteger(); 569 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 570 // Cannot fold a signed setcc with an unsigned setcc. 571 return ISD::SETCC_INVALID; 572 573 // Combine all of the condition bits. 574 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 575 576 // Canonicalize illegal integer setcc's. 577 if (IsInteger) { 578 switch (Result) { 579 default: break; 580 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 581 case ISD::SETOEQ: // SETEQ & SETU[LG]E 582 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 583 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 584 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 585 } 586 } 587 588 return Result; 589 } 590 591 //===----------------------------------------------------------------------===// 592 // SDNode Profile Support 593 //===----------------------------------------------------------------------===// 594 595 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 596 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 597 ID.AddInteger(OpC); 598 } 599 600 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 601 /// solely with their pointer. 602 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 603 ID.AddPointer(VTList.VTs); 604 } 605 606 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 607 static void AddNodeIDOperands(FoldingSetNodeID &ID, 608 ArrayRef<SDValue> Ops) { 609 for (auto& Op : Ops) { 610 ID.AddPointer(Op.getNode()); 611 ID.AddInteger(Op.getResNo()); 612 } 613 } 614 615 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 616 static void AddNodeIDOperands(FoldingSetNodeID &ID, 617 ArrayRef<SDUse> Ops) { 618 for (auto& Op : Ops) { 619 ID.AddPointer(Op.getNode()); 620 ID.AddInteger(Op.getResNo()); 621 } 622 } 623 624 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 625 SDVTList VTList, ArrayRef<SDValue> OpList) { 626 AddNodeIDOpcode(ID, OpC); 627 AddNodeIDValueTypes(ID, VTList); 628 AddNodeIDOperands(ID, OpList); 629 } 630 631 /// If this is an SDNode with special info, add this info to the NodeID data. 632 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 633 switch (N->getOpcode()) { 634 case ISD::TargetExternalSymbol: 635 case ISD::ExternalSymbol: 636 case ISD::MCSymbol: 637 llvm_unreachable("Should only be used on nodes with operands"); 638 default: break; // Normal nodes don't need extra info. 639 case ISD::TargetConstant: 640 case ISD::Constant: { 641 const ConstantSDNode *C = cast<ConstantSDNode>(N); 642 ID.AddPointer(C->getConstantIntValue()); 643 ID.AddBoolean(C->isOpaque()); 644 break; 645 } 646 case ISD::TargetConstantFP: 647 case ISD::ConstantFP: 648 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 649 break; 650 case ISD::TargetGlobalAddress: 651 case ISD::GlobalAddress: 652 case ISD::TargetGlobalTLSAddress: 653 case ISD::GlobalTLSAddress: { 654 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 655 ID.AddPointer(GA->getGlobal()); 656 ID.AddInteger(GA->getOffset()); 657 ID.AddInteger(GA->getTargetFlags()); 658 break; 659 } 660 case ISD::BasicBlock: 661 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 662 break; 663 case ISD::Register: 664 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 665 break; 666 case ISD::RegisterMask: 667 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 668 break; 669 case ISD::SRCVALUE: 670 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 671 break; 672 case ISD::FrameIndex: 673 case ISD::TargetFrameIndex: 674 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 675 break; 676 case ISD::LIFETIME_START: 677 case ISD::LIFETIME_END: 678 if (cast<LifetimeSDNode>(N)->hasOffset()) { 679 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 680 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 681 } 682 break; 683 case ISD::PSEUDO_PROBE: 684 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 685 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 686 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 687 break; 688 case ISD::JumpTable: 689 case ISD::TargetJumpTable: 690 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 691 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 692 break; 693 case ISD::ConstantPool: 694 case ISD::TargetConstantPool: { 695 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 696 ID.AddInteger(CP->getAlign().value()); 697 ID.AddInteger(CP->getOffset()); 698 if (CP->isMachineConstantPoolEntry()) 699 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 700 else 701 ID.AddPointer(CP->getConstVal()); 702 ID.AddInteger(CP->getTargetFlags()); 703 break; 704 } 705 case ISD::TargetIndex: { 706 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 707 ID.AddInteger(TI->getIndex()); 708 ID.AddInteger(TI->getOffset()); 709 ID.AddInteger(TI->getTargetFlags()); 710 break; 711 } 712 case ISD::LOAD: { 713 const LoadSDNode *LD = cast<LoadSDNode>(N); 714 ID.AddInteger(LD->getMemoryVT().getRawBits()); 715 ID.AddInteger(LD->getRawSubclassData()); 716 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 717 break; 718 } 719 case ISD::STORE: { 720 const StoreSDNode *ST = cast<StoreSDNode>(N); 721 ID.AddInteger(ST->getMemoryVT().getRawBits()); 722 ID.AddInteger(ST->getRawSubclassData()); 723 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 724 break; 725 } 726 case ISD::VP_LOAD: { 727 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N); 728 ID.AddInteger(ELD->getMemoryVT().getRawBits()); 729 ID.AddInteger(ELD->getRawSubclassData()); 730 ID.AddInteger(ELD->getPointerInfo().getAddrSpace()); 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 break; 739 } 740 case ISD::VP_GATHER: { 741 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N); 742 ID.AddInteger(EG->getMemoryVT().getRawBits()); 743 ID.AddInteger(EG->getRawSubclassData()); 744 ID.AddInteger(EG->getPointerInfo().getAddrSpace()); 745 break; 746 } 747 case ISD::VP_SCATTER: { 748 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N); 749 ID.AddInteger(ES->getMemoryVT().getRawBits()); 750 ID.AddInteger(ES->getRawSubclassData()); 751 ID.AddInteger(ES->getPointerInfo().getAddrSpace()); 752 break; 753 } 754 case ISD::MLOAD: { 755 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 756 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 757 ID.AddInteger(MLD->getRawSubclassData()); 758 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 759 break; 760 } 761 case ISD::MSTORE: { 762 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 763 ID.AddInteger(MST->getMemoryVT().getRawBits()); 764 ID.AddInteger(MST->getRawSubclassData()); 765 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 766 break; 767 } 768 case ISD::MGATHER: { 769 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 770 ID.AddInteger(MG->getMemoryVT().getRawBits()); 771 ID.AddInteger(MG->getRawSubclassData()); 772 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 773 break; 774 } 775 case ISD::MSCATTER: { 776 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 777 ID.AddInteger(MS->getMemoryVT().getRawBits()); 778 ID.AddInteger(MS->getRawSubclassData()); 779 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 780 break; 781 } 782 case ISD::ATOMIC_CMP_SWAP: 783 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 784 case ISD::ATOMIC_SWAP: 785 case ISD::ATOMIC_LOAD_ADD: 786 case ISD::ATOMIC_LOAD_SUB: 787 case ISD::ATOMIC_LOAD_AND: 788 case ISD::ATOMIC_LOAD_CLR: 789 case ISD::ATOMIC_LOAD_OR: 790 case ISD::ATOMIC_LOAD_XOR: 791 case ISD::ATOMIC_LOAD_NAND: 792 case ISD::ATOMIC_LOAD_MIN: 793 case ISD::ATOMIC_LOAD_MAX: 794 case ISD::ATOMIC_LOAD_UMIN: 795 case ISD::ATOMIC_LOAD_UMAX: 796 case ISD::ATOMIC_LOAD: 797 case ISD::ATOMIC_STORE: { 798 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 799 ID.AddInteger(AT->getMemoryVT().getRawBits()); 800 ID.AddInteger(AT->getRawSubclassData()); 801 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 802 break; 803 } 804 case ISD::PREFETCH: { 805 const MemSDNode *PF = cast<MemSDNode>(N); 806 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 807 break; 808 } 809 case ISD::VECTOR_SHUFFLE: { 810 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 811 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 812 i != e; ++i) 813 ID.AddInteger(SVN->getMaskElt(i)); 814 break; 815 } 816 case ISD::TargetBlockAddress: 817 case ISD::BlockAddress: { 818 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 819 ID.AddPointer(BA->getBlockAddress()); 820 ID.AddInteger(BA->getOffset()); 821 ID.AddInteger(BA->getTargetFlags()); 822 break; 823 } 824 } // end switch (N->getOpcode()) 825 826 // Target specific memory nodes could also have address spaces to check. 827 if (N->isTargetMemoryOpcode()) 828 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 829 } 830 831 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 832 /// data. 833 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 834 AddNodeIDOpcode(ID, N->getOpcode()); 835 // Add the return value info. 836 AddNodeIDValueTypes(ID, N->getVTList()); 837 // Add the operand info. 838 AddNodeIDOperands(ID, N->ops()); 839 840 // Handle SDNode leafs with special info. 841 AddNodeIDCustom(ID, N); 842 } 843 844 //===----------------------------------------------------------------------===// 845 // SelectionDAG Class 846 //===----------------------------------------------------------------------===// 847 848 /// doNotCSE - Return true if CSE should not be performed for this node. 849 static bool doNotCSE(SDNode *N) { 850 if (N->getValueType(0) == MVT::Glue) 851 return true; // Never CSE anything that produces a flag. 852 853 switch (N->getOpcode()) { 854 default: break; 855 case ISD::HANDLENODE: 856 case ISD::EH_LABEL: 857 return true; // Never CSE these nodes. 858 } 859 860 // Check that remaining values produced are not flags. 861 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 862 if (N->getValueType(i) == MVT::Glue) 863 return true; // Never CSE anything that produces a flag. 864 865 return false; 866 } 867 868 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 869 /// SelectionDAG. 870 void SelectionDAG::RemoveDeadNodes() { 871 // Create a dummy node (which is not added to allnodes), that adds a reference 872 // to the root node, preventing it from being deleted. 873 HandleSDNode Dummy(getRoot()); 874 875 SmallVector<SDNode*, 128> DeadNodes; 876 877 // Add all obviously-dead nodes to the DeadNodes worklist. 878 for (SDNode &Node : allnodes()) 879 if (Node.use_empty()) 880 DeadNodes.push_back(&Node); 881 882 RemoveDeadNodes(DeadNodes); 883 884 // If the root changed (e.g. it was a dead load, update the root). 885 setRoot(Dummy.getValue()); 886 } 887 888 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 889 /// given list, and any nodes that become unreachable as a result. 890 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 891 892 // Process the worklist, deleting the nodes and adding their uses to the 893 // worklist. 894 while (!DeadNodes.empty()) { 895 SDNode *N = DeadNodes.pop_back_val(); 896 // Skip to next node if we've already managed to delete the node. This could 897 // happen if replacing a node causes a node previously added to the node to 898 // be deleted. 899 if (N->getOpcode() == ISD::DELETED_NODE) 900 continue; 901 902 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 903 DUL->NodeDeleted(N, nullptr); 904 905 // Take the node out of the appropriate CSE map. 906 RemoveNodeFromCSEMaps(N); 907 908 // Next, brutally remove the operand list. This is safe to do, as there are 909 // no cycles in the graph. 910 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 911 SDUse &Use = *I++; 912 SDNode *Operand = Use.getNode(); 913 Use.set(SDValue()); 914 915 // Now that we removed this operand, see if there are no uses of it left. 916 if (Operand->use_empty()) 917 DeadNodes.push_back(Operand); 918 } 919 920 DeallocateNode(N); 921 } 922 } 923 924 void SelectionDAG::RemoveDeadNode(SDNode *N){ 925 SmallVector<SDNode*, 16> DeadNodes(1, N); 926 927 // Create a dummy node that adds a reference to the root node, preventing 928 // it from being deleted. (This matters if the root is an operand of the 929 // dead node.) 930 HandleSDNode Dummy(getRoot()); 931 932 RemoveDeadNodes(DeadNodes); 933 } 934 935 void SelectionDAG::DeleteNode(SDNode *N) { 936 // First take this out of the appropriate CSE map. 937 RemoveNodeFromCSEMaps(N); 938 939 // Finally, remove uses due to operands of this node, remove from the 940 // AllNodes list, and delete the node. 941 DeleteNodeNotInCSEMaps(N); 942 } 943 944 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 945 assert(N->getIterator() != AllNodes.begin() && 946 "Cannot delete the entry node!"); 947 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 948 949 // Drop all of the operands and decrement used node's use counts. 950 N->DropOperands(); 951 952 DeallocateNode(N); 953 } 954 955 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 956 assert(!(V->isVariadic() && isParameter)); 957 if (isParameter) 958 ByvalParmDbgValues.push_back(V); 959 else 960 DbgValues.push_back(V); 961 for (const SDNode *Node : V->getSDNodes()) 962 if (Node) 963 DbgValMap[Node].push_back(V); 964 } 965 966 void SDDbgInfo::erase(const SDNode *Node) { 967 DbgValMapType::iterator I = DbgValMap.find(Node); 968 if (I == DbgValMap.end()) 969 return; 970 for (auto &Val: I->second) 971 Val->setIsInvalidated(); 972 DbgValMap.erase(I); 973 } 974 975 void SelectionDAG::DeallocateNode(SDNode *N) { 976 // If we have operands, deallocate them. 977 removeOperands(N); 978 979 NodeAllocator.Deallocate(AllNodes.remove(N)); 980 981 // Set the opcode to DELETED_NODE to help catch bugs when node 982 // memory is reallocated. 983 // FIXME: There are places in SDag that have grown a dependency on the opcode 984 // value in the released node. 985 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 986 N->NodeType = ISD::DELETED_NODE; 987 988 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 989 // them and forget about that node. 990 DbgInfo->erase(N); 991 } 992 993 #ifndef NDEBUG 994 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid. 995 static void VerifySDNode(SDNode *N) { 996 switch (N->getOpcode()) { 997 default: 998 break; 999 case ISD::BUILD_PAIR: { 1000 EVT VT = N->getValueType(0); 1001 assert(N->getNumValues() == 1 && "Too many results!"); 1002 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 1003 "Wrong return type!"); 1004 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 1005 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 1006 "Mismatched operand types!"); 1007 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 1008 "Wrong operand type!"); 1009 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 1010 "Wrong return type size"); 1011 break; 1012 } 1013 case ISD::BUILD_VECTOR: { 1014 assert(N->getNumValues() == 1 && "Too many results!"); 1015 assert(N->getValueType(0).isVector() && "Wrong return type!"); 1016 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 1017 "Wrong number of operands!"); 1018 EVT EltVT = N->getValueType(0).getVectorElementType(); 1019 for (const SDUse &Op : N->ops()) { 1020 assert((Op.getValueType() == EltVT || 1021 (EltVT.isInteger() && Op.getValueType().isInteger() && 1022 EltVT.bitsLE(Op.getValueType()))) && 1023 "Wrong operand type!"); 1024 assert(Op.getValueType() == N->getOperand(0).getValueType() && 1025 "Operands must all have the same type"); 1026 } 1027 break; 1028 } 1029 } 1030 } 1031 #endif // NDEBUG 1032 1033 /// Insert a newly allocated node into the DAG. 1034 /// 1035 /// Handles insertion into the all nodes list and CSE map, as well as 1036 /// verification and other common operations when a new node is allocated. 1037 void SelectionDAG::InsertNode(SDNode *N) { 1038 AllNodes.push_back(N); 1039 #ifndef NDEBUG 1040 N->PersistentId = NextPersistentId++; 1041 VerifySDNode(N); 1042 #endif 1043 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1044 DUL->NodeInserted(N); 1045 } 1046 1047 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 1048 /// correspond to it. This is useful when we're about to delete or repurpose 1049 /// the node. We don't want future request for structurally identical nodes 1050 /// to return N anymore. 1051 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 1052 bool Erased = false; 1053 switch (N->getOpcode()) { 1054 case ISD::HANDLENODE: return false; // noop. 1055 case ISD::CONDCODE: 1056 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 1057 "Cond code doesn't exist!"); 1058 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 1059 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 1060 break; 1061 case ISD::ExternalSymbol: 1062 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 1063 break; 1064 case ISD::TargetExternalSymbol: { 1065 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 1066 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 1067 ESN->getSymbol(), ESN->getTargetFlags())); 1068 break; 1069 } 1070 case ISD::MCSymbol: { 1071 auto *MCSN = cast<MCSymbolSDNode>(N); 1072 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1073 break; 1074 } 1075 case ISD::VALUETYPE: { 1076 EVT VT = cast<VTSDNode>(N)->getVT(); 1077 if (VT.isExtended()) { 1078 Erased = ExtendedValueTypeNodes.erase(VT); 1079 } else { 1080 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1081 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1082 } 1083 break; 1084 } 1085 default: 1086 // Remove it from the CSE Map. 1087 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1088 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1089 Erased = CSEMap.RemoveNode(N); 1090 break; 1091 } 1092 #ifndef NDEBUG 1093 // Verify that the node was actually in one of the CSE maps, unless it has a 1094 // flag result (which cannot be CSE'd) or is one of the special cases that are 1095 // not subject to CSE. 1096 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1097 !N->isMachineOpcode() && !doNotCSE(N)) { 1098 N->dump(this); 1099 dbgs() << "\n"; 1100 llvm_unreachable("Node is not in map!"); 1101 } 1102 #endif 1103 return Erased; 1104 } 1105 1106 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1107 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1108 /// node already exists, in which case transfer all its users to the existing 1109 /// node. This transfer can potentially trigger recursive merging. 1110 void 1111 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1112 // For node types that aren't CSE'd, just act as if no identical node 1113 // already exists. 1114 if (!doNotCSE(N)) { 1115 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1116 if (Existing != N) { 1117 // If there was already an existing matching node, use ReplaceAllUsesWith 1118 // to replace the dead one with the existing one. This can cause 1119 // recursive merging of other unrelated nodes down the line. 1120 ReplaceAllUsesWith(N, Existing); 1121 1122 // N is now dead. Inform the listeners and delete it. 1123 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1124 DUL->NodeDeleted(N, Existing); 1125 DeleteNodeNotInCSEMaps(N); 1126 return; 1127 } 1128 } 1129 1130 // If the node doesn't already exist, we updated it. Inform listeners. 1131 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1132 DUL->NodeUpdated(N); 1133 } 1134 1135 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1136 /// were replaced with those specified. If this node is never memoized, 1137 /// return null, otherwise return a pointer to the slot it would take. If a 1138 /// node already exists with these operands, the slot will be non-null. 1139 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1140 void *&InsertPos) { 1141 if (doNotCSE(N)) 1142 return nullptr; 1143 1144 SDValue Ops[] = { Op }; 1145 FoldingSetNodeID ID; 1146 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1147 AddNodeIDCustom(ID, N); 1148 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1149 if (Node) 1150 Node->intersectFlagsWith(N->getFlags()); 1151 return Node; 1152 } 1153 1154 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1155 /// were replaced with those specified. If this node is never memoized, 1156 /// return null, otherwise return a pointer to the slot it would take. If a 1157 /// node already exists with these operands, the slot will be non-null. 1158 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1159 SDValue Op1, SDValue Op2, 1160 void *&InsertPos) { 1161 if (doNotCSE(N)) 1162 return nullptr; 1163 1164 SDValue Ops[] = { Op1, Op2 }; 1165 FoldingSetNodeID ID; 1166 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1167 AddNodeIDCustom(ID, N); 1168 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1169 if (Node) 1170 Node->intersectFlagsWith(N->getFlags()); 1171 return Node; 1172 } 1173 1174 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1175 /// were replaced with those specified. If this node is never memoized, 1176 /// return null, otherwise return a pointer to the slot it would take. If a 1177 /// node already exists with these operands, the slot will be non-null. 1178 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1179 void *&InsertPos) { 1180 if (doNotCSE(N)) 1181 return nullptr; 1182 1183 FoldingSetNodeID ID; 1184 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1185 AddNodeIDCustom(ID, N); 1186 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1187 if (Node) 1188 Node->intersectFlagsWith(N->getFlags()); 1189 return Node; 1190 } 1191 1192 Align SelectionDAG::getEVTAlign(EVT VT) const { 1193 Type *Ty = VT == MVT::iPTR ? 1194 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1195 VT.getTypeForEVT(*getContext()); 1196 1197 return getDataLayout().getABITypeAlign(Ty); 1198 } 1199 1200 // EntryNode could meaningfully have debug info if we can find it... 1201 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1202 : TM(tm), OptLevel(OL), 1203 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1204 Root(getEntryNode()) { 1205 InsertNode(&EntryNode); 1206 DbgInfo = new SDDbgInfo(); 1207 } 1208 1209 void SelectionDAG::init(MachineFunction &NewMF, 1210 OptimizationRemarkEmitter &NewORE, 1211 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1212 LegacyDivergenceAnalysis * Divergence, 1213 ProfileSummaryInfo *PSIin, 1214 BlockFrequencyInfo *BFIin) { 1215 MF = &NewMF; 1216 SDAGISelPass = PassPtr; 1217 ORE = &NewORE; 1218 TLI = getSubtarget().getTargetLowering(); 1219 TSI = getSubtarget().getSelectionDAGInfo(); 1220 LibInfo = LibraryInfo; 1221 Context = &MF->getFunction().getContext(); 1222 DA = Divergence; 1223 PSI = PSIin; 1224 BFI = BFIin; 1225 } 1226 1227 SelectionDAG::~SelectionDAG() { 1228 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1229 allnodes_clear(); 1230 OperandRecycler.clear(OperandAllocator); 1231 delete DbgInfo; 1232 } 1233 1234 bool SelectionDAG::shouldOptForSize() const { 1235 return MF->getFunction().hasOptSize() || 1236 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1237 } 1238 1239 void SelectionDAG::allnodes_clear() { 1240 assert(&*AllNodes.begin() == &EntryNode); 1241 AllNodes.remove(AllNodes.begin()); 1242 while (!AllNodes.empty()) 1243 DeallocateNode(&AllNodes.front()); 1244 #ifndef NDEBUG 1245 NextPersistentId = 0; 1246 #endif 1247 } 1248 1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1250 void *&InsertPos) { 1251 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1252 if (N) { 1253 switch (N->getOpcode()) { 1254 default: break; 1255 case ISD::Constant: 1256 case ISD::ConstantFP: 1257 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1258 "debug location. Use another overload."); 1259 } 1260 } 1261 return N; 1262 } 1263 1264 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1265 const SDLoc &DL, void *&InsertPos) { 1266 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1267 if (N) { 1268 switch (N->getOpcode()) { 1269 case ISD::Constant: 1270 case ISD::ConstantFP: 1271 // Erase debug location from the node if the node is used at several 1272 // different places. Do not propagate one location to all uses as it 1273 // will cause a worse single stepping debugging experience. 1274 if (N->getDebugLoc() != DL.getDebugLoc()) 1275 N->setDebugLoc(DebugLoc()); 1276 break; 1277 default: 1278 // When the node's point of use is located earlier in the instruction 1279 // sequence than its prior point of use, update its debug info to the 1280 // earlier location. 1281 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1282 N->setDebugLoc(DL.getDebugLoc()); 1283 break; 1284 } 1285 } 1286 return N; 1287 } 1288 1289 void SelectionDAG::clear() { 1290 allnodes_clear(); 1291 OperandRecycler.clear(OperandAllocator); 1292 OperandAllocator.Reset(); 1293 CSEMap.clear(); 1294 1295 ExtendedValueTypeNodes.clear(); 1296 ExternalSymbols.clear(); 1297 TargetExternalSymbols.clear(); 1298 MCSymbols.clear(); 1299 SDCallSiteDbgInfo.clear(); 1300 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1301 static_cast<CondCodeSDNode*>(nullptr)); 1302 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1303 static_cast<SDNode*>(nullptr)); 1304 1305 EntryNode.UseList = nullptr; 1306 InsertNode(&EntryNode); 1307 Root = getEntryNode(); 1308 DbgInfo->clear(); 1309 } 1310 1311 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1312 return VT.bitsGT(Op.getValueType()) 1313 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1314 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1315 } 1316 1317 std::pair<SDValue, SDValue> 1318 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1319 const SDLoc &DL, EVT VT) { 1320 assert(!VT.bitsEq(Op.getValueType()) && 1321 "Strict no-op FP extend/round not allowed."); 1322 SDValue Res = 1323 VT.bitsGT(Op.getValueType()) 1324 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1325 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1326 {Chain, Op, getIntPtrConstant(0, DL)}); 1327 1328 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1329 } 1330 1331 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1332 return VT.bitsGT(Op.getValueType()) ? 1333 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1334 getNode(ISD::TRUNCATE, DL, VT, Op); 1335 } 1336 1337 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1338 return VT.bitsGT(Op.getValueType()) ? 1339 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1340 getNode(ISD::TRUNCATE, DL, VT, Op); 1341 } 1342 1343 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1344 return VT.bitsGT(Op.getValueType()) ? 1345 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1346 getNode(ISD::TRUNCATE, DL, VT, Op); 1347 } 1348 1349 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1350 EVT OpVT) { 1351 if (VT.bitsLE(Op.getValueType())) 1352 return getNode(ISD::TRUNCATE, SL, VT, Op); 1353 1354 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1355 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1356 } 1357 1358 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1359 EVT OpVT = Op.getValueType(); 1360 assert(VT.isInteger() && OpVT.isInteger() && 1361 "Cannot getZeroExtendInReg FP types"); 1362 assert(VT.isVector() == OpVT.isVector() && 1363 "getZeroExtendInReg type should be vector iff the operand " 1364 "type is vector!"); 1365 assert((!VT.isVector() || 1366 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1367 "Vector element counts must match in getZeroExtendInReg"); 1368 assert(VT.bitsLE(OpVT) && "Not extending!"); 1369 if (OpVT == VT) 1370 return Op; 1371 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1372 VT.getScalarSizeInBits()); 1373 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1374 } 1375 1376 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1377 // Only unsigned pointer semantics are supported right now. In the future this 1378 // might delegate to TLI to check pointer signedness. 1379 return getZExtOrTrunc(Op, DL, VT); 1380 } 1381 1382 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1383 // Only unsigned pointer semantics are supported right now. In the future this 1384 // might delegate to TLI to check pointer signedness. 1385 return getZeroExtendInReg(Op, DL, VT); 1386 } 1387 1388 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1389 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1390 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT)); 1391 } 1392 1393 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1394 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1395 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1396 } 1397 1398 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1399 EVT OpVT) { 1400 if (!V) 1401 return getConstant(0, DL, VT); 1402 1403 switch (TLI->getBooleanContents(OpVT)) { 1404 case TargetLowering::ZeroOrOneBooleanContent: 1405 case TargetLowering::UndefinedBooleanContent: 1406 return getConstant(1, DL, VT); 1407 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1408 return getAllOnesConstant(DL, VT); 1409 } 1410 llvm_unreachable("Unexpected boolean content enum!"); 1411 } 1412 1413 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1414 bool isT, bool isO) { 1415 EVT EltVT = VT.getScalarType(); 1416 assert((EltVT.getSizeInBits() >= 64 || 1417 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1418 "getConstant with a uint64_t value that doesn't fit in the type!"); 1419 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1420 } 1421 1422 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1423 bool isT, bool isO) { 1424 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1425 } 1426 1427 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1428 EVT VT, bool isT, bool isO) { 1429 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1430 1431 EVT EltVT = VT.getScalarType(); 1432 const ConstantInt *Elt = &Val; 1433 1434 // In some cases the vector type is legal but the element type is illegal and 1435 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1436 // inserted value (the type does not need to match the vector element type). 1437 // Any extra bits introduced will be truncated away. 1438 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1439 TargetLowering::TypePromoteInteger) { 1440 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1441 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1442 Elt = ConstantInt::get(*getContext(), NewVal); 1443 } 1444 // In other cases the element type is illegal and needs to be expanded, for 1445 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1446 // the value into n parts and use a vector type with n-times the elements. 1447 // Then bitcast to the type requested. 1448 // Legalizing constants too early makes the DAGCombiner's job harder so we 1449 // only legalize if the DAG tells us we must produce legal types. 1450 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1451 TLI->getTypeAction(*getContext(), EltVT) == 1452 TargetLowering::TypeExpandInteger) { 1453 const APInt &NewVal = Elt->getValue(); 1454 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1455 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1456 1457 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1458 if (VT.isScalableVector()) { 1459 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1460 "Can only handle an even split!"); 1461 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1462 1463 SmallVector<SDValue, 2> ScalarParts; 1464 for (unsigned i = 0; i != Parts; ++i) 1465 ScalarParts.push_back(getConstant( 1466 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1467 ViaEltVT, isT, isO)); 1468 1469 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1470 } 1471 1472 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1473 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1474 1475 // Check the temporary vector is the correct size. If this fails then 1476 // getTypeToTransformTo() probably returned a type whose size (in bits) 1477 // isn't a power-of-2 factor of the requested type size. 1478 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1479 1480 SmallVector<SDValue, 2> EltParts; 1481 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) 1482 EltParts.push_back(getConstant( 1483 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL, 1484 ViaEltVT, isT, isO)); 1485 1486 // EltParts is currently in little endian order. If we actually want 1487 // big-endian order then reverse it now. 1488 if (getDataLayout().isBigEndian()) 1489 std::reverse(EltParts.begin(), EltParts.end()); 1490 1491 // The elements must be reversed when the element order is different 1492 // to the endianness of the elements (because the BITCAST is itself a 1493 // vector shuffle in this situation). However, we do not need any code to 1494 // perform this reversal because getConstant() is producing a vector 1495 // splat. 1496 // This situation occurs in MIPS MSA. 1497 1498 SmallVector<SDValue, 8> Ops; 1499 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1500 llvm::append_range(Ops, EltParts); 1501 1502 SDValue V = 1503 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1504 return V; 1505 } 1506 1507 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1508 "APInt size does not match type size!"); 1509 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1510 FoldingSetNodeID ID; 1511 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1512 ID.AddPointer(Elt); 1513 ID.AddBoolean(isO); 1514 void *IP = nullptr; 1515 SDNode *N = nullptr; 1516 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1517 if (!VT.isVector()) 1518 return SDValue(N, 0); 1519 1520 if (!N) { 1521 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1522 CSEMap.InsertNode(N, IP); 1523 InsertNode(N); 1524 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1525 } 1526 1527 SDValue Result(N, 0); 1528 if (VT.isScalableVector()) 1529 Result = getSplatVector(VT, DL, Result); 1530 else if (VT.isVector()) 1531 Result = getSplatBuildVector(VT, DL, Result); 1532 1533 return Result; 1534 } 1535 1536 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1537 bool isTarget) { 1538 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1539 } 1540 1541 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1542 const SDLoc &DL, bool LegalTypes) { 1543 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1544 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1545 return getConstant(Val, DL, ShiftVT); 1546 } 1547 1548 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1549 bool isTarget) { 1550 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1551 } 1552 1553 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1554 bool isTarget) { 1555 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1556 } 1557 1558 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1559 EVT VT, bool isTarget) { 1560 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1561 1562 EVT EltVT = VT.getScalarType(); 1563 1564 // Do the map lookup using the actual bit pattern for the floating point 1565 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1566 // we don't have issues with SNANs. 1567 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1568 FoldingSetNodeID ID; 1569 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1570 ID.AddPointer(&V); 1571 void *IP = nullptr; 1572 SDNode *N = nullptr; 1573 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1574 if (!VT.isVector()) 1575 return SDValue(N, 0); 1576 1577 if (!N) { 1578 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1579 CSEMap.InsertNode(N, IP); 1580 InsertNode(N); 1581 } 1582 1583 SDValue Result(N, 0); 1584 if (VT.isScalableVector()) 1585 Result = getSplatVector(VT, DL, Result); 1586 else if (VT.isVector()) 1587 Result = getSplatBuildVector(VT, DL, Result); 1588 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1589 return Result; 1590 } 1591 1592 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1593 bool isTarget) { 1594 EVT EltVT = VT.getScalarType(); 1595 if (EltVT == MVT::f32) 1596 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1597 if (EltVT == MVT::f64) 1598 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1599 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1600 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1601 bool Ignored; 1602 APFloat APF = APFloat(Val); 1603 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1604 &Ignored); 1605 return getConstantFP(APF, DL, VT, isTarget); 1606 } 1607 llvm_unreachable("Unsupported type in getConstantFP"); 1608 } 1609 1610 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1611 EVT VT, int64_t Offset, bool isTargetGA, 1612 unsigned TargetFlags) { 1613 assert((TargetFlags == 0 || isTargetGA) && 1614 "Cannot set target flags on target-independent globals"); 1615 1616 // Truncate (with sign-extension) the offset value to the pointer size. 1617 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1618 if (BitWidth < 64) 1619 Offset = SignExtend64(Offset, BitWidth); 1620 1621 unsigned Opc; 1622 if (GV->isThreadLocal()) 1623 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1624 else 1625 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1626 1627 FoldingSetNodeID ID; 1628 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1629 ID.AddPointer(GV); 1630 ID.AddInteger(Offset); 1631 ID.AddInteger(TargetFlags); 1632 void *IP = nullptr; 1633 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1634 return SDValue(E, 0); 1635 1636 auto *N = newSDNode<GlobalAddressSDNode>( 1637 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1638 CSEMap.InsertNode(N, IP); 1639 InsertNode(N); 1640 return SDValue(N, 0); 1641 } 1642 1643 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1644 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1645 FoldingSetNodeID ID; 1646 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1647 ID.AddInteger(FI); 1648 void *IP = nullptr; 1649 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1650 return SDValue(E, 0); 1651 1652 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1653 CSEMap.InsertNode(N, IP); 1654 InsertNode(N); 1655 return SDValue(N, 0); 1656 } 1657 1658 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1659 unsigned TargetFlags) { 1660 assert((TargetFlags == 0 || isTarget) && 1661 "Cannot set target flags on target-independent jump tables"); 1662 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1663 FoldingSetNodeID ID; 1664 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1665 ID.AddInteger(JTI); 1666 ID.AddInteger(TargetFlags); 1667 void *IP = nullptr; 1668 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1669 return SDValue(E, 0); 1670 1671 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1672 CSEMap.InsertNode(N, IP); 1673 InsertNode(N); 1674 return SDValue(N, 0); 1675 } 1676 1677 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1678 MaybeAlign Alignment, int Offset, 1679 bool isTarget, unsigned TargetFlags) { 1680 assert((TargetFlags == 0 || isTarget) && 1681 "Cannot set target flags on target-independent globals"); 1682 if (!Alignment) 1683 Alignment = shouldOptForSize() 1684 ? getDataLayout().getABITypeAlign(C->getType()) 1685 : getDataLayout().getPrefTypeAlign(C->getType()); 1686 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1687 FoldingSetNodeID ID; 1688 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1689 ID.AddInteger(Alignment->value()); 1690 ID.AddInteger(Offset); 1691 ID.AddPointer(C); 1692 ID.AddInteger(TargetFlags); 1693 void *IP = nullptr; 1694 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1695 return SDValue(E, 0); 1696 1697 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1698 TargetFlags); 1699 CSEMap.InsertNode(N, IP); 1700 InsertNode(N); 1701 SDValue V = SDValue(N, 0); 1702 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1703 return V; 1704 } 1705 1706 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1707 MaybeAlign Alignment, int Offset, 1708 bool isTarget, unsigned TargetFlags) { 1709 assert((TargetFlags == 0 || isTarget) && 1710 "Cannot set target flags on target-independent globals"); 1711 if (!Alignment) 1712 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1713 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1714 FoldingSetNodeID ID; 1715 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1716 ID.AddInteger(Alignment->value()); 1717 ID.AddInteger(Offset); 1718 C->addSelectionDAGCSEId(ID); 1719 ID.AddInteger(TargetFlags); 1720 void *IP = nullptr; 1721 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1722 return SDValue(E, 0); 1723 1724 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1725 TargetFlags); 1726 CSEMap.InsertNode(N, IP); 1727 InsertNode(N); 1728 return SDValue(N, 0); 1729 } 1730 1731 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1732 unsigned TargetFlags) { 1733 FoldingSetNodeID ID; 1734 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1735 ID.AddInteger(Index); 1736 ID.AddInteger(Offset); 1737 ID.AddInteger(TargetFlags); 1738 void *IP = nullptr; 1739 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1740 return SDValue(E, 0); 1741 1742 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1743 CSEMap.InsertNode(N, IP); 1744 InsertNode(N); 1745 return SDValue(N, 0); 1746 } 1747 1748 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1749 FoldingSetNodeID ID; 1750 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1751 ID.AddPointer(MBB); 1752 void *IP = nullptr; 1753 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1754 return SDValue(E, 0); 1755 1756 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1757 CSEMap.InsertNode(N, IP); 1758 InsertNode(N); 1759 return SDValue(N, 0); 1760 } 1761 1762 SDValue SelectionDAG::getValueType(EVT VT) { 1763 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1764 ValueTypeNodes.size()) 1765 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1766 1767 SDNode *&N = VT.isExtended() ? 1768 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1769 1770 if (N) return SDValue(N, 0); 1771 N = newSDNode<VTSDNode>(VT); 1772 InsertNode(N); 1773 return SDValue(N, 0); 1774 } 1775 1776 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1777 SDNode *&N = ExternalSymbols[Sym]; 1778 if (N) return SDValue(N, 0); 1779 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1780 InsertNode(N); 1781 return SDValue(N, 0); 1782 } 1783 1784 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1785 SDNode *&N = MCSymbols[Sym]; 1786 if (N) 1787 return SDValue(N, 0); 1788 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1789 InsertNode(N); 1790 return SDValue(N, 0); 1791 } 1792 1793 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1794 unsigned TargetFlags) { 1795 SDNode *&N = 1796 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1797 if (N) return SDValue(N, 0); 1798 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1799 InsertNode(N); 1800 return SDValue(N, 0); 1801 } 1802 1803 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1804 if ((unsigned)Cond >= CondCodeNodes.size()) 1805 CondCodeNodes.resize(Cond+1); 1806 1807 if (!CondCodeNodes[Cond]) { 1808 auto *N = newSDNode<CondCodeSDNode>(Cond); 1809 CondCodeNodes[Cond] = N; 1810 InsertNode(N); 1811 } 1812 1813 return SDValue(CondCodeNodes[Cond], 0); 1814 } 1815 1816 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) { 1817 APInt One(ResVT.getScalarSizeInBits(), 1); 1818 return getStepVector(DL, ResVT, One); 1819 } 1820 1821 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) { 1822 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth()); 1823 if (ResVT.isScalableVector()) 1824 return getNode( 1825 ISD::STEP_VECTOR, DL, ResVT, 1826 getTargetConstant(StepVal, DL, ResVT.getVectorElementType())); 1827 1828 SmallVector<SDValue, 16> OpsStepConstants; 1829 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1830 OpsStepConstants.push_back( 1831 getConstant(StepVal * i, DL, ResVT.getVectorElementType())); 1832 return getBuildVector(ResVT, DL, OpsStepConstants); 1833 } 1834 1835 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1836 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1837 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1838 std::swap(N1, N2); 1839 ShuffleVectorSDNode::commuteMask(M); 1840 } 1841 1842 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1843 SDValue N2, ArrayRef<int> Mask) { 1844 assert(VT.getVectorNumElements() == Mask.size() && 1845 "Must have the same number of vector elements as mask elements!"); 1846 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1847 "Invalid VECTOR_SHUFFLE"); 1848 1849 // Canonicalize shuffle undef, undef -> undef 1850 if (N1.isUndef() && N2.isUndef()) 1851 return getUNDEF(VT); 1852 1853 // Validate that all indices in Mask are within the range of the elements 1854 // input to the shuffle. 1855 int NElts = Mask.size(); 1856 assert(llvm::all_of(Mask, 1857 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1858 "Index out of range"); 1859 1860 // Copy the mask so we can do any needed cleanup. 1861 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1862 1863 // Canonicalize shuffle v, v -> v, undef 1864 if (N1 == N2) { 1865 N2 = getUNDEF(VT); 1866 for (int i = 0; i != NElts; ++i) 1867 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1868 } 1869 1870 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1871 if (N1.isUndef()) 1872 commuteShuffle(N1, N2, MaskVec); 1873 1874 if (TLI->hasVectorBlend()) { 1875 // If shuffling a splat, try to blend the splat instead. We do this here so 1876 // that even when this arises during lowering we don't have to re-handle it. 1877 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1878 BitVector UndefElements; 1879 SDValue Splat = BV->getSplatValue(&UndefElements); 1880 if (!Splat) 1881 return; 1882 1883 for (int i = 0; i < NElts; ++i) { 1884 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1885 continue; 1886 1887 // If this input comes from undef, mark it as such. 1888 if (UndefElements[MaskVec[i] - Offset]) { 1889 MaskVec[i] = -1; 1890 continue; 1891 } 1892 1893 // If we can blend a non-undef lane, use that instead. 1894 if (!UndefElements[i]) 1895 MaskVec[i] = i + Offset; 1896 } 1897 }; 1898 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1899 BlendSplat(N1BV, 0); 1900 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1901 BlendSplat(N2BV, NElts); 1902 } 1903 1904 // Canonicalize all index into lhs, -> shuffle lhs, undef 1905 // Canonicalize all index into rhs, -> shuffle rhs, undef 1906 bool AllLHS = true, AllRHS = true; 1907 bool N2Undef = N2.isUndef(); 1908 for (int i = 0; i != NElts; ++i) { 1909 if (MaskVec[i] >= NElts) { 1910 if (N2Undef) 1911 MaskVec[i] = -1; 1912 else 1913 AllLHS = false; 1914 } else if (MaskVec[i] >= 0) { 1915 AllRHS = false; 1916 } 1917 } 1918 if (AllLHS && AllRHS) 1919 return getUNDEF(VT); 1920 if (AllLHS && !N2Undef) 1921 N2 = getUNDEF(VT); 1922 if (AllRHS) { 1923 N1 = getUNDEF(VT); 1924 commuteShuffle(N1, N2, MaskVec); 1925 } 1926 // Reset our undef status after accounting for the mask. 1927 N2Undef = N2.isUndef(); 1928 // Re-check whether both sides ended up undef. 1929 if (N1.isUndef() && N2Undef) 1930 return getUNDEF(VT); 1931 1932 // If Identity shuffle return that node. 1933 bool Identity = true, AllSame = true; 1934 for (int i = 0; i != NElts; ++i) { 1935 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1936 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1937 } 1938 if (Identity && NElts) 1939 return N1; 1940 1941 // Shuffling a constant splat doesn't change the result. 1942 if (N2Undef) { 1943 SDValue V = N1; 1944 1945 // Look through any bitcasts. We check that these don't change the number 1946 // (and size) of elements and just changes their types. 1947 while (V.getOpcode() == ISD::BITCAST) 1948 V = V->getOperand(0); 1949 1950 // A splat should always show up as a build vector node. 1951 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1952 BitVector UndefElements; 1953 SDValue Splat = BV->getSplatValue(&UndefElements); 1954 // If this is a splat of an undef, shuffling it is also undef. 1955 if (Splat && Splat.isUndef()) 1956 return getUNDEF(VT); 1957 1958 bool SameNumElts = 1959 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1960 1961 // We only have a splat which can skip shuffles if there is a splatted 1962 // value and no undef lanes rearranged by the shuffle. 1963 if (Splat && UndefElements.none()) { 1964 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1965 // number of elements match or the value splatted is a zero constant. 1966 if (SameNumElts) 1967 return N1; 1968 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1969 if (C->isZero()) 1970 return N1; 1971 } 1972 1973 // If the shuffle itself creates a splat, build the vector directly. 1974 if (AllSame && SameNumElts) { 1975 EVT BuildVT = BV->getValueType(0); 1976 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1977 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1978 1979 // We may have jumped through bitcasts, so the type of the 1980 // BUILD_VECTOR may not match the type of the shuffle. 1981 if (BuildVT != VT) 1982 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1983 return NewBV; 1984 } 1985 } 1986 } 1987 1988 FoldingSetNodeID ID; 1989 SDValue Ops[2] = { N1, N2 }; 1990 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1991 for (int i = 0; i != NElts; ++i) 1992 ID.AddInteger(MaskVec[i]); 1993 1994 void* IP = nullptr; 1995 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1996 return SDValue(E, 0); 1997 1998 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1999 // SDNode doesn't have access to it. This memory will be "leaked" when 2000 // the node is deallocated, but recovered when the NodeAllocator is released. 2001 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 2002 llvm::copy(MaskVec, MaskAlloc); 2003 2004 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 2005 dl.getDebugLoc(), MaskAlloc); 2006 createOperands(N, Ops); 2007 2008 CSEMap.InsertNode(N, IP); 2009 InsertNode(N); 2010 SDValue V = SDValue(N, 0); 2011 NewSDValueDbgMsg(V, "Creating new node: ", this); 2012 return V; 2013 } 2014 2015 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 2016 EVT VT = SV.getValueType(0); 2017 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 2018 ShuffleVectorSDNode::commuteMask(MaskVec); 2019 2020 SDValue Op0 = SV.getOperand(0); 2021 SDValue Op1 = SV.getOperand(1); 2022 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 2023 } 2024 2025 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 2026 FoldingSetNodeID ID; 2027 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 2028 ID.AddInteger(RegNo); 2029 void *IP = nullptr; 2030 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2031 return SDValue(E, 0); 2032 2033 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 2034 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 2035 CSEMap.InsertNode(N, IP); 2036 InsertNode(N); 2037 return SDValue(N, 0); 2038 } 2039 2040 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 2041 FoldingSetNodeID ID; 2042 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 2043 ID.AddPointer(RegMask); 2044 void *IP = nullptr; 2045 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2046 return SDValue(E, 0); 2047 2048 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 2049 CSEMap.InsertNode(N, IP); 2050 InsertNode(N); 2051 return SDValue(N, 0); 2052 } 2053 2054 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 2055 MCSymbol *Label) { 2056 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 2057 } 2058 2059 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 2060 SDValue Root, MCSymbol *Label) { 2061 FoldingSetNodeID ID; 2062 SDValue Ops[] = { Root }; 2063 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 2064 ID.AddPointer(Label); 2065 void *IP = nullptr; 2066 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2067 return SDValue(E, 0); 2068 2069 auto *N = 2070 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 2071 createOperands(N, Ops); 2072 2073 CSEMap.InsertNode(N, IP); 2074 InsertNode(N); 2075 return SDValue(N, 0); 2076 } 2077 2078 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2079 int64_t Offset, bool isTarget, 2080 unsigned TargetFlags) { 2081 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2082 2083 FoldingSetNodeID ID; 2084 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2085 ID.AddPointer(BA); 2086 ID.AddInteger(Offset); 2087 ID.AddInteger(TargetFlags); 2088 void *IP = nullptr; 2089 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2090 return SDValue(E, 0); 2091 2092 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2093 CSEMap.InsertNode(N, IP); 2094 InsertNode(N); 2095 return SDValue(N, 0); 2096 } 2097 2098 SDValue SelectionDAG::getSrcValue(const Value *V) { 2099 FoldingSetNodeID ID; 2100 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2101 ID.AddPointer(V); 2102 2103 void *IP = nullptr; 2104 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2105 return SDValue(E, 0); 2106 2107 auto *N = newSDNode<SrcValueSDNode>(V); 2108 CSEMap.InsertNode(N, IP); 2109 InsertNode(N); 2110 return SDValue(N, 0); 2111 } 2112 2113 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2114 FoldingSetNodeID ID; 2115 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2116 ID.AddPointer(MD); 2117 2118 void *IP = nullptr; 2119 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2120 return SDValue(E, 0); 2121 2122 auto *N = newSDNode<MDNodeSDNode>(MD); 2123 CSEMap.InsertNode(N, IP); 2124 InsertNode(N); 2125 return SDValue(N, 0); 2126 } 2127 2128 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2129 if (VT == V.getValueType()) 2130 return V; 2131 2132 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2133 } 2134 2135 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2136 unsigned SrcAS, unsigned DestAS) { 2137 SDValue Ops[] = {Ptr}; 2138 FoldingSetNodeID ID; 2139 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2140 ID.AddInteger(SrcAS); 2141 ID.AddInteger(DestAS); 2142 2143 void *IP = nullptr; 2144 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2145 return SDValue(E, 0); 2146 2147 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2148 VT, SrcAS, DestAS); 2149 createOperands(N, Ops); 2150 2151 CSEMap.InsertNode(N, IP); 2152 InsertNode(N); 2153 return SDValue(N, 0); 2154 } 2155 2156 SDValue SelectionDAG::getFreeze(SDValue V) { 2157 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2158 } 2159 2160 /// getShiftAmountOperand - Return the specified value casted to 2161 /// the target's desired shift amount type. 2162 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2163 EVT OpTy = Op.getValueType(); 2164 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2165 if (OpTy == ShTy || OpTy.isVector()) return Op; 2166 2167 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2168 } 2169 2170 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2171 SDLoc dl(Node); 2172 const TargetLowering &TLI = getTargetLoweringInfo(); 2173 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2174 EVT VT = Node->getValueType(0); 2175 SDValue Tmp1 = Node->getOperand(0); 2176 SDValue Tmp2 = Node->getOperand(1); 2177 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2178 2179 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2180 Tmp2, MachinePointerInfo(V)); 2181 SDValue VAList = VAListLoad; 2182 2183 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2184 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2185 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2186 2187 VAList = 2188 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2189 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2190 } 2191 2192 // Increment the pointer, VAList, to the next vaarg 2193 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2194 getConstant(getDataLayout().getTypeAllocSize( 2195 VT.getTypeForEVT(*getContext())), 2196 dl, VAList.getValueType())); 2197 // Store the incremented VAList to the legalized pointer 2198 Tmp1 = 2199 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2200 // Load the actual argument out of the pointer VAList 2201 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2202 } 2203 2204 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2205 SDLoc dl(Node); 2206 const TargetLowering &TLI = getTargetLoweringInfo(); 2207 // This defaults to loading a pointer from the input and storing it to the 2208 // output, returning the chain. 2209 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2210 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2211 SDValue Tmp1 = 2212 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2213 Node->getOperand(2), MachinePointerInfo(VS)); 2214 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2215 MachinePointerInfo(VD)); 2216 } 2217 2218 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2219 const DataLayout &DL = getDataLayout(); 2220 Type *Ty = VT.getTypeForEVT(*getContext()); 2221 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2222 2223 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2224 return RedAlign; 2225 2226 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2227 const Align StackAlign = TFI->getStackAlign(); 2228 2229 // See if we can choose a smaller ABI alignment in cases where it's an 2230 // illegal vector type that will get broken down. 2231 if (RedAlign > StackAlign) { 2232 EVT IntermediateVT; 2233 MVT RegisterVT; 2234 unsigned NumIntermediates; 2235 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2236 NumIntermediates, RegisterVT); 2237 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2238 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2239 if (RedAlign2 < RedAlign) 2240 RedAlign = RedAlign2; 2241 } 2242 2243 return RedAlign; 2244 } 2245 2246 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2247 MachineFrameInfo &MFI = MF->getFrameInfo(); 2248 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2249 int StackID = 0; 2250 if (Bytes.isScalable()) 2251 StackID = TFI->getStackIDForScalableVectors(); 2252 // The stack id gives an indication of whether the object is scalable or 2253 // not, so it's safe to pass in the minimum size here. 2254 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2255 false, nullptr, StackID); 2256 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2257 } 2258 2259 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2260 Type *Ty = VT.getTypeForEVT(*getContext()); 2261 Align StackAlign = 2262 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2263 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2264 } 2265 2266 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2267 TypeSize VT1Size = VT1.getStoreSize(); 2268 TypeSize VT2Size = VT2.getStoreSize(); 2269 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2270 "Don't know how to choose the maximum size when creating a stack " 2271 "temporary"); 2272 TypeSize Bytes = 2273 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2274 2275 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2276 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2277 const DataLayout &DL = getDataLayout(); 2278 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2279 return CreateStackTemporary(Bytes, Align); 2280 } 2281 2282 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2283 ISD::CondCode Cond, const SDLoc &dl) { 2284 EVT OpVT = N1.getValueType(); 2285 2286 // These setcc operations always fold. 2287 switch (Cond) { 2288 default: break; 2289 case ISD::SETFALSE: 2290 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2291 case ISD::SETTRUE: 2292 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2293 2294 case ISD::SETOEQ: 2295 case ISD::SETOGT: 2296 case ISD::SETOGE: 2297 case ISD::SETOLT: 2298 case ISD::SETOLE: 2299 case ISD::SETONE: 2300 case ISD::SETO: 2301 case ISD::SETUO: 2302 case ISD::SETUEQ: 2303 case ISD::SETUNE: 2304 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2305 break; 2306 } 2307 2308 if (OpVT.isInteger()) { 2309 // For EQ and NE, we can always pick a value for the undef to make the 2310 // predicate pass or fail, so we can return undef. 2311 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2312 // icmp eq/ne X, undef -> undef. 2313 if ((N1.isUndef() || N2.isUndef()) && 2314 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2315 return getUNDEF(VT); 2316 2317 // If both operands are undef, we can return undef for int comparison. 2318 // icmp undef, undef -> undef. 2319 if (N1.isUndef() && N2.isUndef()) 2320 return getUNDEF(VT); 2321 2322 // icmp X, X -> true/false 2323 // icmp X, undef -> true/false because undef could be X. 2324 if (N1 == N2) 2325 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2326 } 2327 2328 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2329 const APInt &C2 = N2C->getAPIntValue(); 2330 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2331 const APInt &C1 = N1C->getAPIntValue(); 2332 2333 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)), 2334 dl, VT, OpVT); 2335 } 2336 } 2337 2338 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2339 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2340 2341 if (N1CFP && N2CFP) { 2342 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2343 switch (Cond) { 2344 default: break; 2345 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2346 return getUNDEF(VT); 2347 LLVM_FALLTHROUGH; 2348 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2349 OpVT); 2350 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2351 return getUNDEF(VT); 2352 LLVM_FALLTHROUGH; 2353 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2354 R==APFloat::cmpLessThan, dl, VT, 2355 OpVT); 2356 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2357 return getUNDEF(VT); 2358 LLVM_FALLTHROUGH; 2359 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2360 OpVT); 2361 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2362 return getUNDEF(VT); 2363 LLVM_FALLTHROUGH; 2364 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2365 VT, OpVT); 2366 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2367 return getUNDEF(VT); 2368 LLVM_FALLTHROUGH; 2369 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2370 R==APFloat::cmpEqual, dl, VT, 2371 OpVT); 2372 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2373 return getUNDEF(VT); 2374 LLVM_FALLTHROUGH; 2375 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2376 R==APFloat::cmpEqual, dl, VT, OpVT); 2377 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2378 OpVT); 2379 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2380 OpVT); 2381 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2382 R==APFloat::cmpEqual, dl, VT, 2383 OpVT); 2384 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2385 OpVT); 2386 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2387 R==APFloat::cmpLessThan, dl, VT, 2388 OpVT); 2389 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2390 R==APFloat::cmpUnordered, dl, VT, 2391 OpVT); 2392 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2393 VT, OpVT); 2394 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2395 OpVT); 2396 } 2397 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2398 // Ensure that the constant occurs on the RHS. 2399 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2400 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2401 return SDValue(); 2402 return getSetCC(dl, VT, N2, N1, SwappedCond); 2403 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2404 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2405 // If an operand is known to be a nan (or undef that could be a nan), we can 2406 // fold it. 2407 // Choosing NaN for the undef will always make unordered comparison succeed 2408 // and ordered comparison fails. 2409 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2410 switch (ISD::getUnorderedFlavor(Cond)) { 2411 default: 2412 llvm_unreachable("Unknown flavor!"); 2413 case 0: // Known false. 2414 return getBoolConstant(false, dl, VT, OpVT); 2415 case 1: // Known true. 2416 return getBoolConstant(true, dl, VT, OpVT); 2417 case 2: // Undefined. 2418 return getUNDEF(VT); 2419 } 2420 } 2421 2422 // Could not fold it. 2423 return SDValue(); 2424 } 2425 2426 /// See if the specified operand can be simplified with the knowledge that only 2427 /// the bits specified by DemandedBits are used. 2428 /// TODO: really we should be making this into the DAG equivalent of 2429 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2430 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2431 EVT VT = V.getValueType(); 2432 2433 if (VT.isScalableVector()) 2434 return SDValue(); 2435 2436 APInt DemandedElts = VT.isVector() 2437 ? APInt::getAllOnes(VT.getVectorNumElements()) 2438 : APInt(1, 1); 2439 return GetDemandedBits(V, DemandedBits, DemandedElts); 2440 } 2441 2442 /// See if the specified operand can be simplified with the knowledge that only 2443 /// the bits specified by DemandedBits are used in the elements specified by 2444 /// DemandedElts. 2445 /// TODO: really we should be making this into the DAG equivalent of 2446 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2447 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2448 const APInt &DemandedElts) { 2449 switch (V.getOpcode()) { 2450 default: 2451 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2452 *this); 2453 case ISD::Constant: { 2454 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2455 APInt NewVal = CVal & DemandedBits; 2456 if (NewVal != CVal) 2457 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2458 break; 2459 } 2460 case ISD::SRL: 2461 // Only look at single-use SRLs. 2462 if (!V.getNode()->hasOneUse()) 2463 break; 2464 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2465 // See if we can recursively simplify the LHS. 2466 unsigned Amt = RHSC->getZExtValue(); 2467 2468 // Watch out for shift count overflow though. 2469 if (Amt >= DemandedBits.getBitWidth()) 2470 break; 2471 APInt SrcDemandedBits = DemandedBits << Amt; 2472 if (SDValue SimplifyLHS = 2473 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2474 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2475 V.getOperand(1)); 2476 } 2477 break; 2478 } 2479 return SDValue(); 2480 } 2481 2482 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2483 /// use this predicate to simplify operations downstream. 2484 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2485 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2486 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2487 } 2488 2489 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2490 /// this predicate to simplify operations downstream. Mask is known to be zero 2491 /// for bits that V cannot have. 2492 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2493 unsigned Depth) const { 2494 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2495 } 2496 2497 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2498 /// DemandedElts. We use this predicate to simplify operations downstream. 2499 /// Mask is known to be zero for bits that V cannot have. 2500 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2501 const APInt &DemandedElts, 2502 unsigned Depth) const { 2503 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2504 } 2505 2506 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2507 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2508 unsigned Depth) const { 2509 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2510 } 2511 2512 /// isSplatValue - Return true if the vector V has the same value 2513 /// across all DemandedElts. For scalable vectors it does not make 2514 /// sense to specify which elements are demanded or undefined, therefore 2515 /// they are simply ignored. 2516 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2517 APInt &UndefElts, unsigned Depth) const { 2518 unsigned Opcode = V.getOpcode(); 2519 EVT VT = V.getValueType(); 2520 assert(VT.isVector() && "Vector type expected"); 2521 2522 if (!VT.isScalableVector() && !DemandedElts) 2523 return false; // No demanded elts, better to assume we don't know anything. 2524 2525 if (Depth >= MaxRecursionDepth) 2526 return false; // Limit search depth. 2527 2528 // Deal with some common cases here that work for both fixed and scalable 2529 // vector types. 2530 switch (Opcode) { 2531 case ISD::SPLAT_VECTOR: 2532 UndefElts = V.getOperand(0).isUndef() 2533 ? APInt::getAllOnes(DemandedElts.getBitWidth()) 2534 : APInt(DemandedElts.getBitWidth(), 0); 2535 return true; 2536 case ISD::ADD: 2537 case ISD::SUB: 2538 case ISD::AND: 2539 case ISD::XOR: 2540 case ISD::OR: { 2541 APInt UndefLHS, UndefRHS; 2542 SDValue LHS = V.getOperand(0); 2543 SDValue RHS = V.getOperand(1); 2544 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2545 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2546 UndefElts = UndefLHS | UndefRHS; 2547 return true; 2548 } 2549 return false; 2550 } 2551 case ISD::ABS: 2552 case ISD::TRUNCATE: 2553 case ISD::SIGN_EXTEND: 2554 case ISD::ZERO_EXTEND: 2555 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2556 default: 2557 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 2558 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 2559 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth); 2560 break; 2561 } 2562 2563 // We don't support other cases than those above for scalable vectors at 2564 // the moment. 2565 if (VT.isScalableVector()) 2566 return false; 2567 2568 unsigned NumElts = VT.getVectorNumElements(); 2569 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2570 UndefElts = APInt::getZero(NumElts); 2571 2572 switch (Opcode) { 2573 case ISD::BUILD_VECTOR: { 2574 SDValue Scl; 2575 for (unsigned i = 0; i != NumElts; ++i) { 2576 SDValue Op = V.getOperand(i); 2577 if (Op.isUndef()) { 2578 UndefElts.setBit(i); 2579 continue; 2580 } 2581 if (!DemandedElts[i]) 2582 continue; 2583 if (Scl && Scl != Op) 2584 return false; 2585 Scl = Op; 2586 } 2587 return true; 2588 } 2589 case ISD::VECTOR_SHUFFLE: { 2590 // Check if this is a shuffle node doing a splat. 2591 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2592 int SplatIndex = -1; 2593 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2594 for (int i = 0; i != (int)NumElts; ++i) { 2595 int M = Mask[i]; 2596 if (M < 0) { 2597 UndefElts.setBit(i); 2598 continue; 2599 } 2600 if (!DemandedElts[i]) 2601 continue; 2602 if (0 <= SplatIndex && SplatIndex != M) 2603 return false; 2604 SplatIndex = M; 2605 } 2606 return true; 2607 } 2608 case ISD::EXTRACT_SUBVECTOR: { 2609 // Offset the demanded elts by the subvector index. 2610 SDValue Src = V.getOperand(0); 2611 // We don't support scalable vectors at the moment. 2612 if (Src.getValueType().isScalableVector()) 2613 return false; 2614 uint64_t Idx = V.getConstantOperandVal(1); 2615 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2616 APInt UndefSrcElts; 2617 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2618 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2619 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2620 return true; 2621 } 2622 break; 2623 } 2624 case ISD::ANY_EXTEND_VECTOR_INREG: 2625 case ISD::SIGN_EXTEND_VECTOR_INREG: 2626 case ISD::ZERO_EXTEND_VECTOR_INREG: { 2627 // Widen the demanded elts by the src element count. 2628 SDValue Src = V.getOperand(0); 2629 // We don't support scalable vectors at the moment. 2630 if (Src.getValueType().isScalableVector()) 2631 return false; 2632 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2633 APInt UndefSrcElts; 2634 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 2635 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2636 UndefElts = UndefSrcElts.truncOrSelf(NumElts); 2637 return true; 2638 } 2639 break; 2640 } 2641 } 2642 2643 return false; 2644 } 2645 2646 /// Helper wrapper to main isSplatValue function. 2647 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const { 2648 EVT VT = V.getValueType(); 2649 assert(VT.isVector() && "Vector type expected"); 2650 2651 APInt UndefElts; 2652 APInt DemandedElts; 2653 2654 // For now we don't support this with scalable vectors. 2655 if (!VT.isScalableVector()) 2656 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2657 return isSplatValue(V, DemandedElts, UndefElts) && 2658 (AllowUndefs || !UndefElts); 2659 } 2660 2661 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2662 V = peekThroughExtractSubvectors(V); 2663 2664 EVT VT = V.getValueType(); 2665 unsigned Opcode = V.getOpcode(); 2666 switch (Opcode) { 2667 default: { 2668 APInt UndefElts; 2669 APInt DemandedElts; 2670 2671 if (!VT.isScalableVector()) 2672 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements()); 2673 2674 if (isSplatValue(V, DemandedElts, UndefElts)) { 2675 if (VT.isScalableVector()) { 2676 // DemandedElts and UndefElts are ignored for scalable vectors, since 2677 // the only supported cases are SPLAT_VECTOR nodes. 2678 SplatIdx = 0; 2679 } else { 2680 // Handle case where all demanded elements are UNDEF. 2681 if (DemandedElts.isSubsetOf(UndefElts)) { 2682 SplatIdx = 0; 2683 return getUNDEF(VT); 2684 } 2685 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2686 } 2687 return V; 2688 } 2689 break; 2690 } 2691 case ISD::SPLAT_VECTOR: 2692 SplatIdx = 0; 2693 return V; 2694 case ISD::VECTOR_SHUFFLE: { 2695 if (VT.isScalableVector()) 2696 return SDValue(); 2697 2698 // Check if this is a shuffle node doing a splat. 2699 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2700 // getTargetVShiftNode currently struggles without the splat source. 2701 auto *SVN = cast<ShuffleVectorSDNode>(V); 2702 if (!SVN->isSplat()) 2703 break; 2704 int Idx = SVN->getSplatIndex(); 2705 int NumElts = V.getValueType().getVectorNumElements(); 2706 SplatIdx = Idx % NumElts; 2707 return V.getOperand(Idx / NumElts); 2708 } 2709 } 2710 2711 return SDValue(); 2712 } 2713 2714 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) { 2715 int SplatIdx; 2716 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) { 2717 EVT SVT = SrcVector.getValueType().getScalarType(); 2718 EVT LegalSVT = SVT; 2719 if (LegalTypes && !TLI->isTypeLegal(SVT)) { 2720 if (!SVT.isInteger()) 2721 return SDValue(); 2722 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 2723 if (LegalSVT.bitsLT(SVT)) 2724 return SDValue(); 2725 } 2726 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector, 2727 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2728 } 2729 return SDValue(); 2730 } 2731 2732 const APInt * 2733 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2734 const APInt &DemandedElts) const { 2735 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2736 V.getOpcode() == ISD::SRA) && 2737 "Unknown shift node"); 2738 unsigned BitWidth = V.getScalarValueSizeInBits(); 2739 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2740 // Shifting more than the bitwidth is not valid. 2741 const APInt &ShAmt = SA->getAPIntValue(); 2742 if (ShAmt.ult(BitWidth)) 2743 return &ShAmt; 2744 } 2745 return nullptr; 2746 } 2747 2748 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2749 SDValue V, const APInt &DemandedElts) const { 2750 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2751 V.getOpcode() == ISD::SRA) && 2752 "Unknown shift node"); 2753 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2754 return ValidAmt; 2755 unsigned BitWidth = V.getScalarValueSizeInBits(); 2756 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2757 if (!BV) 2758 return nullptr; 2759 const APInt *MinShAmt = nullptr; 2760 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2761 if (!DemandedElts[i]) 2762 continue; 2763 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2764 if (!SA) 2765 return nullptr; 2766 // Shifting more than the bitwidth is not valid. 2767 const APInt &ShAmt = SA->getAPIntValue(); 2768 if (ShAmt.uge(BitWidth)) 2769 return nullptr; 2770 if (MinShAmt && MinShAmt->ule(ShAmt)) 2771 continue; 2772 MinShAmt = &ShAmt; 2773 } 2774 return MinShAmt; 2775 } 2776 2777 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2778 SDValue V, const APInt &DemandedElts) const { 2779 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2780 V.getOpcode() == ISD::SRA) && 2781 "Unknown shift node"); 2782 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2783 return ValidAmt; 2784 unsigned BitWidth = V.getScalarValueSizeInBits(); 2785 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2786 if (!BV) 2787 return nullptr; 2788 const APInt *MaxShAmt = nullptr; 2789 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2790 if (!DemandedElts[i]) 2791 continue; 2792 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2793 if (!SA) 2794 return nullptr; 2795 // Shifting more than the bitwidth is not valid. 2796 const APInt &ShAmt = SA->getAPIntValue(); 2797 if (ShAmt.uge(BitWidth)) 2798 return nullptr; 2799 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2800 continue; 2801 MaxShAmt = &ShAmt; 2802 } 2803 return MaxShAmt; 2804 } 2805 2806 /// Determine which bits of Op are known to be either zero or one and return 2807 /// them in Known. For vectors, the known bits are those that are shared by 2808 /// every vector element. 2809 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2810 EVT VT = Op.getValueType(); 2811 2812 // TOOD: Until we have a plan for how to represent demanded elements for 2813 // scalable vectors, we can just bail out for now. 2814 if (Op.getValueType().isScalableVector()) { 2815 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2816 return KnownBits(BitWidth); 2817 } 2818 2819 APInt DemandedElts = VT.isVector() 2820 ? APInt::getAllOnes(VT.getVectorNumElements()) 2821 : APInt(1, 1); 2822 return computeKnownBits(Op, DemandedElts, Depth); 2823 } 2824 2825 /// Determine which bits of Op are known to be either zero or one and return 2826 /// them in Known. The DemandedElts argument allows us to only collect the known 2827 /// bits that are shared by the requested vector elements. 2828 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2829 unsigned Depth) const { 2830 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2831 2832 KnownBits Known(BitWidth); // Don't know anything. 2833 2834 // TOOD: Until we have a plan for how to represent demanded elements for 2835 // scalable vectors, we can just bail out for now. 2836 if (Op.getValueType().isScalableVector()) 2837 return Known; 2838 2839 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2840 // We know all of the bits for a constant! 2841 return KnownBits::makeConstant(C->getAPIntValue()); 2842 } 2843 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2844 // We know all of the bits for a constant fp! 2845 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2846 } 2847 2848 if (Depth >= MaxRecursionDepth) 2849 return Known; // Limit search depth. 2850 2851 KnownBits Known2; 2852 unsigned NumElts = DemandedElts.getBitWidth(); 2853 assert((!Op.getValueType().isVector() || 2854 NumElts == Op.getValueType().getVectorNumElements()) && 2855 "Unexpected vector size"); 2856 2857 if (!DemandedElts) 2858 return Known; // No demanded elts, better to assume we don't know anything. 2859 2860 unsigned Opcode = Op.getOpcode(); 2861 switch (Opcode) { 2862 case ISD::BUILD_VECTOR: 2863 // Collect the known bits that are shared by every demanded vector element. 2864 Known.Zero.setAllBits(); Known.One.setAllBits(); 2865 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2866 if (!DemandedElts[i]) 2867 continue; 2868 2869 SDValue SrcOp = Op.getOperand(i); 2870 Known2 = computeKnownBits(SrcOp, Depth + 1); 2871 2872 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2873 if (SrcOp.getValueSizeInBits() != BitWidth) { 2874 assert(SrcOp.getValueSizeInBits() > BitWidth && 2875 "Expected BUILD_VECTOR implicit truncation"); 2876 Known2 = Known2.trunc(BitWidth); 2877 } 2878 2879 // Known bits are the values that are shared by every demanded element. 2880 Known = KnownBits::commonBits(Known, Known2); 2881 2882 // If we don't know any bits, early out. 2883 if (Known.isUnknown()) 2884 break; 2885 } 2886 break; 2887 case ISD::VECTOR_SHUFFLE: { 2888 // Collect the known bits that are shared by every vector element referenced 2889 // by the shuffle. 2890 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2891 Known.Zero.setAllBits(); Known.One.setAllBits(); 2892 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2893 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2894 for (unsigned i = 0; i != NumElts; ++i) { 2895 if (!DemandedElts[i]) 2896 continue; 2897 2898 int M = SVN->getMaskElt(i); 2899 if (M < 0) { 2900 // For UNDEF elements, we don't know anything about the common state of 2901 // the shuffle result. 2902 Known.resetAll(); 2903 DemandedLHS.clearAllBits(); 2904 DemandedRHS.clearAllBits(); 2905 break; 2906 } 2907 2908 if ((unsigned)M < NumElts) 2909 DemandedLHS.setBit((unsigned)M % NumElts); 2910 else 2911 DemandedRHS.setBit((unsigned)M % NumElts); 2912 } 2913 // Known bits are the values that are shared by every demanded element. 2914 if (!!DemandedLHS) { 2915 SDValue LHS = Op.getOperand(0); 2916 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2917 Known = KnownBits::commonBits(Known, Known2); 2918 } 2919 // If we don't know any bits, early out. 2920 if (Known.isUnknown()) 2921 break; 2922 if (!!DemandedRHS) { 2923 SDValue RHS = Op.getOperand(1); 2924 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2925 Known = KnownBits::commonBits(Known, Known2); 2926 } 2927 break; 2928 } 2929 case ISD::CONCAT_VECTORS: { 2930 // Split DemandedElts and test each of the demanded subvectors. 2931 Known.Zero.setAllBits(); Known.One.setAllBits(); 2932 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2933 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2934 unsigned NumSubVectors = Op.getNumOperands(); 2935 for (unsigned i = 0; i != NumSubVectors; ++i) { 2936 APInt DemandedSub = 2937 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 2938 if (!!DemandedSub) { 2939 SDValue Sub = Op.getOperand(i); 2940 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2941 Known = KnownBits::commonBits(Known, Known2); 2942 } 2943 // If we don't know any bits, early out. 2944 if (Known.isUnknown()) 2945 break; 2946 } 2947 break; 2948 } 2949 case ISD::INSERT_SUBVECTOR: { 2950 // Demand any elements from the subvector and the remainder from the src its 2951 // inserted into. 2952 SDValue Src = Op.getOperand(0); 2953 SDValue Sub = Op.getOperand(1); 2954 uint64_t Idx = Op.getConstantOperandVal(2); 2955 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2956 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2957 APInt DemandedSrcElts = DemandedElts; 2958 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 2959 2960 Known.One.setAllBits(); 2961 Known.Zero.setAllBits(); 2962 if (!!DemandedSubElts) { 2963 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2964 if (Known.isUnknown()) 2965 break; // early-out. 2966 } 2967 if (!!DemandedSrcElts) { 2968 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2969 Known = KnownBits::commonBits(Known, Known2); 2970 } 2971 break; 2972 } 2973 case ISD::EXTRACT_SUBVECTOR: { 2974 // Offset the demanded elts by the subvector index. 2975 SDValue Src = Op.getOperand(0); 2976 // Bail until we can represent demanded elements for scalable vectors. 2977 if (Src.getValueType().isScalableVector()) 2978 break; 2979 uint64_t Idx = Op.getConstantOperandVal(1); 2980 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2981 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2982 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2983 break; 2984 } 2985 case ISD::SCALAR_TO_VECTOR: { 2986 // We know about scalar_to_vector as much as we know about it source, 2987 // which becomes the first element of otherwise unknown vector. 2988 if (DemandedElts != 1) 2989 break; 2990 2991 SDValue N0 = Op.getOperand(0); 2992 Known = computeKnownBits(N0, Depth + 1); 2993 if (N0.getValueSizeInBits() != BitWidth) 2994 Known = Known.trunc(BitWidth); 2995 2996 break; 2997 } 2998 case ISD::BITCAST: { 2999 SDValue N0 = Op.getOperand(0); 3000 EVT SubVT = N0.getValueType(); 3001 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 3002 3003 // Ignore bitcasts from unsupported types. 3004 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 3005 break; 3006 3007 // Fast handling of 'identity' bitcasts. 3008 if (BitWidth == SubBitWidth) { 3009 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 3010 break; 3011 } 3012 3013 bool IsLE = getDataLayout().isLittleEndian(); 3014 3015 // Bitcast 'small element' vector to 'large element' scalar/vector. 3016 if ((BitWidth % SubBitWidth) == 0) { 3017 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 3018 3019 // Collect known bits for the (larger) output by collecting the known 3020 // bits from each set of sub elements and shift these into place. 3021 // We need to separately call computeKnownBits for each set of 3022 // sub elements as the knownbits for each is likely to be different. 3023 unsigned SubScale = BitWidth / SubBitWidth; 3024 APInt SubDemandedElts(NumElts * SubScale, 0); 3025 for (unsigned i = 0; i != NumElts; ++i) 3026 if (DemandedElts[i]) 3027 SubDemandedElts.setBit(i * SubScale); 3028 3029 for (unsigned i = 0; i != SubScale; ++i) { 3030 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 3031 Depth + 1); 3032 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 3033 Known.insertBits(Known2, SubBitWidth * Shifts); 3034 } 3035 } 3036 3037 // Bitcast 'large element' scalar/vector to 'small element' vector. 3038 if ((SubBitWidth % BitWidth) == 0) { 3039 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 3040 3041 // Collect known bits for the (smaller) output by collecting the known 3042 // bits from the overlapping larger input elements and extracting the 3043 // sub sections we actually care about. 3044 unsigned SubScale = SubBitWidth / BitWidth; 3045 APInt SubDemandedElts = 3046 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale); 3047 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 3048 3049 Known.Zero.setAllBits(); Known.One.setAllBits(); 3050 for (unsigned i = 0; i != NumElts; ++i) 3051 if (DemandedElts[i]) { 3052 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 3053 unsigned Offset = (Shifts % SubScale) * BitWidth; 3054 Known = KnownBits::commonBits(Known, 3055 Known2.extractBits(BitWidth, Offset)); 3056 // If we don't know any bits, early out. 3057 if (Known.isUnknown()) 3058 break; 3059 } 3060 } 3061 break; 3062 } 3063 case ISD::AND: 3064 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3065 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3066 3067 Known &= Known2; 3068 break; 3069 case ISD::OR: 3070 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3071 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3072 3073 Known |= Known2; 3074 break; 3075 case ISD::XOR: 3076 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3077 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3078 3079 Known ^= Known2; 3080 break; 3081 case ISD::MUL: { 3082 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3083 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3084 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3085 // TODO: SelfMultiply can be poison, but not undef. 3086 if (SelfMultiply) 3087 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison( 3088 Op.getOperand(0), DemandedElts, false, Depth + 1); 3089 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3090 break; 3091 } 3092 case ISD::MULHU: { 3093 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3094 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3095 Known = KnownBits::mulhu(Known, Known2); 3096 break; 3097 } 3098 case ISD::MULHS: { 3099 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3100 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3101 Known = KnownBits::mulhs(Known, Known2); 3102 break; 3103 } 3104 case ISD::UMUL_LOHI: { 3105 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3106 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3107 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3108 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3109 if (Op.getResNo() == 0) 3110 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3111 else 3112 Known = KnownBits::mulhu(Known, Known2); 3113 break; 3114 } 3115 case ISD::SMUL_LOHI: { 3116 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3117 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3118 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3119 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3120 if (Op.getResNo() == 0) 3121 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3122 else 3123 Known = KnownBits::mulhs(Known, Known2); 3124 break; 3125 } 3126 case ISD::UDIV: { 3127 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3128 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3129 Known = KnownBits::udiv(Known, Known2); 3130 break; 3131 } 3132 case ISD::SELECT: 3133 case ISD::VSELECT: 3134 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3135 // If we don't know any bits, early out. 3136 if (Known.isUnknown()) 3137 break; 3138 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3139 3140 // Only known if known in both the LHS and RHS. 3141 Known = KnownBits::commonBits(Known, Known2); 3142 break; 3143 case ISD::SELECT_CC: 3144 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3145 // If we don't know any bits, early out. 3146 if (Known.isUnknown()) 3147 break; 3148 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3149 3150 // Only known if known in both the LHS and RHS. 3151 Known = KnownBits::commonBits(Known, Known2); 3152 break; 3153 case ISD::SMULO: 3154 case ISD::UMULO: 3155 if (Op.getResNo() != 1) 3156 break; 3157 // The boolean result conforms to getBooleanContents. 3158 // If we know the result of a setcc has the top bits zero, use this info. 3159 // We know that we have an integer-based boolean since these operations 3160 // are only available for integer. 3161 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3162 TargetLowering::ZeroOrOneBooleanContent && 3163 BitWidth > 1) 3164 Known.Zero.setBitsFrom(1); 3165 break; 3166 case ISD::SETCC: 3167 case ISD::STRICT_FSETCC: 3168 case ISD::STRICT_FSETCCS: { 3169 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3170 // If we know the result of a setcc has the top bits zero, use this info. 3171 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3172 TargetLowering::ZeroOrOneBooleanContent && 3173 BitWidth > 1) 3174 Known.Zero.setBitsFrom(1); 3175 break; 3176 } 3177 case ISD::SHL: 3178 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3179 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3180 Known = KnownBits::shl(Known, Known2); 3181 3182 // Minimum shift low bits are known zero. 3183 if (const APInt *ShMinAmt = 3184 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3185 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3186 break; 3187 case ISD::SRL: 3188 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3189 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3190 Known = KnownBits::lshr(Known, Known2); 3191 3192 // Minimum shift high bits are known zero. 3193 if (const APInt *ShMinAmt = 3194 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3195 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3196 break; 3197 case ISD::SRA: 3198 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3199 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3200 Known = KnownBits::ashr(Known, Known2); 3201 // TODO: Add minimum shift high known sign bits. 3202 break; 3203 case ISD::FSHL: 3204 case ISD::FSHR: 3205 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3206 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3207 3208 // For fshl, 0-shift returns the 1st arg. 3209 // For fshr, 0-shift returns the 2nd arg. 3210 if (Amt == 0) { 3211 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3212 DemandedElts, Depth + 1); 3213 break; 3214 } 3215 3216 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3217 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3218 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3219 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3220 if (Opcode == ISD::FSHL) { 3221 Known.One <<= Amt; 3222 Known.Zero <<= Amt; 3223 Known2.One.lshrInPlace(BitWidth - Amt); 3224 Known2.Zero.lshrInPlace(BitWidth - Amt); 3225 } else { 3226 Known.One <<= BitWidth - Amt; 3227 Known.Zero <<= BitWidth - Amt; 3228 Known2.One.lshrInPlace(Amt); 3229 Known2.Zero.lshrInPlace(Amt); 3230 } 3231 Known.One |= Known2.One; 3232 Known.Zero |= Known2.Zero; 3233 } 3234 break; 3235 case ISD::SIGN_EXTEND_INREG: { 3236 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3237 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3238 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3239 break; 3240 } 3241 case ISD::CTTZ: 3242 case ISD::CTTZ_ZERO_UNDEF: { 3243 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3244 // If we have a known 1, its position is our upper bound. 3245 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3246 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3247 Known.Zero.setBitsFrom(LowBits); 3248 break; 3249 } 3250 case ISD::CTLZ: 3251 case ISD::CTLZ_ZERO_UNDEF: { 3252 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3253 // If we have a known 1, its position is our upper bound. 3254 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3255 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3256 Known.Zero.setBitsFrom(LowBits); 3257 break; 3258 } 3259 case ISD::CTPOP: { 3260 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3261 // If we know some of the bits are zero, they can't be one. 3262 unsigned PossibleOnes = Known2.countMaxPopulation(); 3263 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3264 break; 3265 } 3266 case ISD::PARITY: { 3267 // Parity returns 0 everywhere but the LSB. 3268 Known.Zero.setBitsFrom(1); 3269 break; 3270 } 3271 case ISD::LOAD: { 3272 LoadSDNode *LD = cast<LoadSDNode>(Op); 3273 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3274 if (ISD::isNON_EXTLoad(LD) && Cst) { 3275 // Determine any common known bits from the loaded constant pool value. 3276 Type *CstTy = Cst->getType(); 3277 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3278 // If its a vector splat, then we can (quickly) reuse the scalar path. 3279 // NOTE: We assume all elements match and none are UNDEF. 3280 if (CstTy->isVectorTy()) { 3281 if (const Constant *Splat = Cst->getSplatValue()) { 3282 Cst = Splat; 3283 CstTy = Cst->getType(); 3284 } 3285 } 3286 // TODO - do we need to handle different bitwidths? 3287 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3288 // Iterate across all vector elements finding common known bits. 3289 Known.One.setAllBits(); 3290 Known.Zero.setAllBits(); 3291 for (unsigned i = 0; i != NumElts; ++i) { 3292 if (!DemandedElts[i]) 3293 continue; 3294 if (Constant *Elt = Cst->getAggregateElement(i)) { 3295 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3296 const APInt &Value = CInt->getValue(); 3297 Known.One &= Value; 3298 Known.Zero &= ~Value; 3299 continue; 3300 } 3301 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3302 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3303 Known.One &= Value; 3304 Known.Zero &= ~Value; 3305 continue; 3306 } 3307 } 3308 Known.One.clearAllBits(); 3309 Known.Zero.clearAllBits(); 3310 break; 3311 } 3312 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3313 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3314 Known = KnownBits::makeConstant(CInt->getValue()); 3315 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3316 Known = 3317 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3318 } 3319 } 3320 } 3321 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3322 // If this is a ZEXTLoad and we are looking at the loaded value. 3323 EVT VT = LD->getMemoryVT(); 3324 unsigned MemBits = VT.getScalarSizeInBits(); 3325 Known.Zero.setBitsFrom(MemBits); 3326 } else if (const MDNode *Ranges = LD->getRanges()) { 3327 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3328 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3329 } 3330 break; 3331 } 3332 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3333 EVT InVT = Op.getOperand(0).getValueType(); 3334 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3335 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3336 Known = Known.zext(BitWidth); 3337 break; 3338 } 3339 case ISD::ZERO_EXTEND: { 3340 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3341 Known = Known.zext(BitWidth); 3342 break; 3343 } 3344 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3345 EVT InVT = Op.getOperand(0).getValueType(); 3346 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3347 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3348 // If the sign bit is known to be zero or one, then sext will extend 3349 // it to the top bits, else it will just zext. 3350 Known = Known.sext(BitWidth); 3351 break; 3352 } 3353 case ISD::SIGN_EXTEND: { 3354 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3355 // If the sign bit is known to be zero or one, then sext will extend 3356 // it to the top bits, else it will just zext. 3357 Known = Known.sext(BitWidth); 3358 break; 3359 } 3360 case ISD::ANY_EXTEND_VECTOR_INREG: { 3361 EVT InVT = Op.getOperand(0).getValueType(); 3362 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3363 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3364 Known = Known.anyext(BitWidth); 3365 break; 3366 } 3367 case ISD::ANY_EXTEND: { 3368 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3369 Known = Known.anyext(BitWidth); 3370 break; 3371 } 3372 case ISD::TRUNCATE: { 3373 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3374 Known = Known.trunc(BitWidth); 3375 break; 3376 } 3377 case ISD::AssertZext: { 3378 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3379 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3380 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3381 Known.Zero |= (~InMask); 3382 Known.One &= (~Known.Zero); 3383 break; 3384 } 3385 case ISD::AssertAlign: { 3386 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3387 assert(LogOfAlign != 0); 3388 3389 // TODO: Should use maximum with source 3390 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3391 // well as clearing one bits. 3392 Known.Zero.setLowBits(LogOfAlign); 3393 Known.One.clearLowBits(LogOfAlign); 3394 break; 3395 } 3396 case ISD::FGETSIGN: 3397 // All bits are zero except the low bit. 3398 Known.Zero.setBitsFrom(1); 3399 break; 3400 case ISD::USUBO: 3401 case ISD::SSUBO: 3402 if (Op.getResNo() == 1) { 3403 // If we know the result of a setcc has the top bits zero, use this info. 3404 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3405 TargetLowering::ZeroOrOneBooleanContent && 3406 BitWidth > 1) 3407 Known.Zero.setBitsFrom(1); 3408 break; 3409 } 3410 LLVM_FALLTHROUGH; 3411 case ISD::SUB: 3412 case ISD::SUBC: { 3413 assert(Op.getResNo() == 0 && 3414 "We only compute knownbits for the difference here."); 3415 3416 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3417 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3418 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3419 Known, Known2); 3420 break; 3421 } 3422 case ISD::UADDO: 3423 case ISD::SADDO: 3424 case ISD::ADDCARRY: 3425 if (Op.getResNo() == 1) { 3426 // If we know the result of a setcc has the top bits zero, use this info. 3427 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3428 TargetLowering::ZeroOrOneBooleanContent && 3429 BitWidth > 1) 3430 Known.Zero.setBitsFrom(1); 3431 break; 3432 } 3433 LLVM_FALLTHROUGH; 3434 case ISD::ADD: 3435 case ISD::ADDC: 3436 case ISD::ADDE: { 3437 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3438 3439 // With ADDE and ADDCARRY, a carry bit may be added in. 3440 KnownBits Carry(1); 3441 if (Opcode == ISD::ADDE) 3442 // Can't track carry from glue, set carry to unknown. 3443 Carry.resetAll(); 3444 else if (Opcode == ISD::ADDCARRY) 3445 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3446 // the trouble (how often will we find a known carry bit). And I haven't 3447 // tested this very much yet, but something like this might work: 3448 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3449 // Carry = Carry.zextOrTrunc(1, false); 3450 Carry.resetAll(); 3451 else 3452 Carry.setAllZero(); 3453 3454 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3455 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3456 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3457 break; 3458 } 3459 case ISD::SREM: { 3460 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3461 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3462 Known = KnownBits::srem(Known, Known2); 3463 break; 3464 } 3465 case ISD::UREM: { 3466 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3467 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3468 Known = KnownBits::urem(Known, Known2); 3469 break; 3470 } 3471 case ISD::EXTRACT_ELEMENT: { 3472 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3473 const unsigned Index = Op.getConstantOperandVal(1); 3474 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3475 3476 // Remove low part of known bits mask 3477 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3478 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3479 3480 // Remove high part of known bit mask 3481 Known = Known.trunc(EltBitWidth); 3482 break; 3483 } 3484 case ISD::EXTRACT_VECTOR_ELT: { 3485 SDValue InVec = Op.getOperand(0); 3486 SDValue EltNo = Op.getOperand(1); 3487 EVT VecVT = InVec.getValueType(); 3488 // computeKnownBits not yet implemented for scalable vectors. 3489 if (VecVT.isScalableVector()) 3490 break; 3491 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3492 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3493 3494 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3495 // anything about the extended bits. 3496 if (BitWidth > EltBitWidth) 3497 Known = Known.trunc(EltBitWidth); 3498 3499 // If we know the element index, just demand that vector element, else for 3500 // an unknown element index, ignore DemandedElts and demand them all. 3501 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3502 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3503 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3504 DemandedSrcElts = 3505 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3506 3507 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3508 if (BitWidth > EltBitWidth) 3509 Known = Known.anyext(BitWidth); 3510 break; 3511 } 3512 case ISD::INSERT_VECTOR_ELT: { 3513 // If we know the element index, split the demand between the 3514 // source vector and the inserted element, otherwise assume we need 3515 // the original demanded vector elements and the value. 3516 SDValue InVec = Op.getOperand(0); 3517 SDValue InVal = Op.getOperand(1); 3518 SDValue EltNo = Op.getOperand(2); 3519 bool DemandedVal = true; 3520 APInt DemandedVecElts = DemandedElts; 3521 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3522 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3523 unsigned EltIdx = CEltNo->getZExtValue(); 3524 DemandedVal = !!DemandedElts[EltIdx]; 3525 DemandedVecElts.clearBit(EltIdx); 3526 } 3527 Known.One.setAllBits(); 3528 Known.Zero.setAllBits(); 3529 if (DemandedVal) { 3530 Known2 = computeKnownBits(InVal, Depth + 1); 3531 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3532 } 3533 if (!!DemandedVecElts) { 3534 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3535 Known = KnownBits::commonBits(Known, Known2); 3536 } 3537 break; 3538 } 3539 case ISD::BITREVERSE: { 3540 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3541 Known = Known2.reverseBits(); 3542 break; 3543 } 3544 case ISD::BSWAP: { 3545 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3546 Known = Known2.byteSwap(); 3547 break; 3548 } 3549 case ISD::ABS: { 3550 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3551 Known = Known2.abs(); 3552 break; 3553 } 3554 case ISD::USUBSAT: { 3555 // The result of usubsat will never be larger than the LHS. 3556 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3557 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3558 break; 3559 } 3560 case ISD::UMIN: { 3561 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3562 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3563 Known = KnownBits::umin(Known, Known2); 3564 break; 3565 } 3566 case ISD::UMAX: { 3567 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3568 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3569 Known = KnownBits::umax(Known, Known2); 3570 break; 3571 } 3572 case ISD::SMIN: 3573 case ISD::SMAX: { 3574 // If we have a clamp pattern, we know that the number of sign bits will be 3575 // the minimum of the clamp min/max range. 3576 bool IsMax = (Opcode == ISD::SMAX); 3577 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3578 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3579 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3580 CstHigh = 3581 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3582 if (CstLow && CstHigh) { 3583 if (!IsMax) 3584 std::swap(CstLow, CstHigh); 3585 3586 const APInt &ValueLow = CstLow->getAPIntValue(); 3587 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3588 if (ValueLow.sle(ValueHigh)) { 3589 unsigned LowSignBits = ValueLow.getNumSignBits(); 3590 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3591 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3592 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3593 Known.One.setHighBits(MinSignBits); 3594 break; 3595 } 3596 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3597 Known.Zero.setHighBits(MinSignBits); 3598 break; 3599 } 3600 } 3601 } 3602 3603 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3604 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3605 if (IsMax) 3606 Known = KnownBits::smax(Known, Known2); 3607 else 3608 Known = KnownBits::smin(Known, Known2); 3609 break; 3610 } 3611 case ISD::FP_TO_UINT_SAT: { 3612 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3613 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3614 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3615 break; 3616 } 3617 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3618 if (Op.getResNo() == 1) { 3619 // The boolean result conforms to getBooleanContents. 3620 // If we know the result of a setcc has the top bits zero, use this info. 3621 // We know that we have an integer-based boolean since these operations 3622 // are only available for integer. 3623 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3624 TargetLowering::ZeroOrOneBooleanContent && 3625 BitWidth > 1) 3626 Known.Zero.setBitsFrom(1); 3627 break; 3628 } 3629 LLVM_FALLTHROUGH; 3630 case ISD::ATOMIC_CMP_SWAP: 3631 case ISD::ATOMIC_SWAP: 3632 case ISD::ATOMIC_LOAD_ADD: 3633 case ISD::ATOMIC_LOAD_SUB: 3634 case ISD::ATOMIC_LOAD_AND: 3635 case ISD::ATOMIC_LOAD_CLR: 3636 case ISD::ATOMIC_LOAD_OR: 3637 case ISD::ATOMIC_LOAD_XOR: 3638 case ISD::ATOMIC_LOAD_NAND: 3639 case ISD::ATOMIC_LOAD_MIN: 3640 case ISD::ATOMIC_LOAD_MAX: 3641 case ISD::ATOMIC_LOAD_UMIN: 3642 case ISD::ATOMIC_LOAD_UMAX: 3643 case ISD::ATOMIC_LOAD: { 3644 unsigned MemBits = 3645 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3646 // If we are looking at the loaded value. 3647 if (Op.getResNo() == 0) { 3648 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3649 Known.Zero.setBitsFrom(MemBits); 3650 } 3651 break; 3652 } 3653 case ISD::FrameIndex: 3654 case ISD::TargetFrameIndex: 3655 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3656 Known, getMachineFunction()); 3657 break; 3658 3659 default: 3660 if (Opcode < ISD::BUILTIN_OP_END) 3661 break; 3662 LLVM_FALLTHROUGH; 3663 case ISD::INTRINSIC_WO_CHAIN: 3664 case ISD::INTRINSIC_W_CHAIN: 3665 case ISD::INTRINSIC_VOID: 3666 // Allow the target to implement this method for its nodes. 3667 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3668 break; 3669 } 3670 3671 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3672 return Known; 3673 } 3674 3675 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3676 SDValue N1) const { 3677 // X + 0 never overflow 3678 if (isNullConstant(N1)) 3679 return OFK_Never; 3680 3681 KnownBits N1Known = computeKnownBits(N1); 3682 if (N1Known.Zero.getBoolValue()) { 3683 KnownBits N0Known = computeKnownBits(N0); 3684 3685 bool overflow; 3686 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3687 if (!overflow) 3688 return OFK_Never; 3689 } 3690 3691 // mulhi + 1 never overflow 3692 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3693 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3694 return OFK_Never; 3695 3696 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3697 KnownBits N0Known = computeKnownBits(N0); 3698 3699 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3700 return OFK_Never; 3701 } 3702 3703 return OFK_Sometime; 3704 } 3705 3706 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3707 EVT OpVT = Val.getValueType(); 3708 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3709 3710 // Is the constant a known power of 2? 3711 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3712 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3713 3714 // A left-shift of a constant one will have exactly one bit set because 3715 // shifting the bit off the end is undefined. 3716 if (Val.getOpcode() == ISD::SHL) { 3717 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3718 if (C && C->getAPIntValue() == 1) 3719 return true; 3720 } 3721 3722 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3723 // one bit set. 3724 if (Val.getOpcode() == ISD::SRL) { 3725 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3726 if (C && C->getAPIntValue().isSignMask()) 3727 return true; 3728 } 3729 3730 // Are all operands of a build vector constant powers of two? 3731 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3732 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3733 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3734 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3735 return false; 3736 })) 3737 return true; 3738 3739 // Is the operand of a splat vector a constant power of two? 3740 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3741 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3742 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3743 return true; 3744 3745 // More could be done here, though the above checks are enough 3746 // to handle some common cases. 3747 3748 // Fall back to computeKnownBits to catch other known cases. 3749 KnownBits Known = computeKnownBits(Val); 3750 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3751 } 3752 3753 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3754 EVT VT = Op.getValueType(); 3755 3756 // TODO: Assume we don't know anything for now. 3757 if (VT.isScalableVector()) 3758 return 1; 3759 3760 APInt DemandedElts = VT.isVector() 3761 ? APInt::getAllOnes(VT.getVectorNumElements()) 3762 : APInt(1, 1); 3763 return ComputeNumSignBits(Op, DemandedElts, Depth); 3764 } 3765 3766 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3767 unsigned Depth) const { 3768 EVT VT = Op.getValueType(); 3769 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3770 unsigned VTBits = VT.getScalarSizeInBits(); 3771 unsigned NumElts = DemandedElts.getBitWidth(); 3772 unsigned Tmp, Tmp2; 3773 unsigned FirstAnswer = 1; 3774 3775 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3776 const APInt &Val = C->getAPIntValue(); 3777 return Val.getNumSignBits(); 3778 } 3779 3780 if (Depth >= MaxRecursionDepth) 3781 return 1; // Limit search depth. 3782 3783 if (!DemandedElts || VT.isScalableVector()) 3784 return 1; // No demanded elts, better to assume we don't know anything. 3785 3786 unsigned Opcode = Op.getOpcode(); 3787 switch (Opcode) { 3788 default: break; 3789 case ISD::AssertSext: 3790 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3791 return VTBits-Tmp+1; 3792 case ISD::AssertZext: 3793 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3794 return VTBits-Tmp; 3795 3796 case ISD::BUILD_VECTOR: 3797 Tmp = VTBits; 3798 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3799 if (!DemandedElts[i]) 3800 continue; 3801 3802 SDValue SrcOp = Op.getOperand(i); 3803 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3804 3805 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3806 if (SrcOp.getValueSizeInBits() != VTBits) { 3807 assert(SrcOp.getValueSizeInBits() > VTBits && 3808 "Expected BUILD_VECTOR implicit truncation"); 3809 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3810 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3811 } 3812 Tmp = std::min(Tmp, Tmp2); 3813 } 3814 return Tmp; 3815 3816 case ISD::VECTOR_SHUFFLE: { 3817 // Collect the minimum number of sign bits that are shared by every vector 3818 // element referenced by the shuffle. 3819 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3820 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3821 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3822 for (unsigned i = 0; i != NumElts; ++i) { 3823 int M = SVN->getMaskElt(i); 3824 if (!DemandedElts[i]) 3825 continue; 3826 // For UNDEF elements, we don't know anything about the common state of 3827 // the shuffle result. 3828 if (M < 0) 3829 return 1; 3830 if ((unsigned)M < NumElts) 3831 DemandedLHS.setBit((unsigned)M % NumElts); 3832 else 3833 DemandedRHS.setBit((unsigned)M % NumElts); 3834 } 3835 Tmp = std::numeric_limits<unsigned>::max(); 3836 if (!!DemandedLHS) 3837 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3838 if (!!DemandedRHS) { 3839 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3840 Tmp = std::min(Tmp, Tmp2); 3841 } 3842 // If we don't know anything, early out and try computeKnownBits fall-back. 3843 if (Tmp == 1) 3844 break; 3845 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3846 return Tmp; 3847 } 3848 3849 case ISD::BITCAST: { 3850 SDValue N0 = Op.getOperand(0); 3851 EVT SrcVT = N0.getValueType(); 3852 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3853 3854 // Ignore bitcasts from unsupported types.. 3855 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3856 break; 3857 3858 // Fast handling of 'identity' bitcasts. 3859 if (VTBits == SrcBits) 3860 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3861 3862 bool IsLE = getDataLayout().isLittleEndian(); 3863 3864 // Bitcast 'large element' scalar/vector to 'small element' vector. 3865 if ((SrcBits % VTBits) == 0) { 3866 assert(VT.isVector() && "Expected bitcast to vector"); 3867 3868 unsigned Scale = SrcBits / VTBits; 3869 APInt SrcDemandedElts = 3870 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3871 3872 // Fast case - sign splat can be simply split across the small elements. 3873 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3874 if (Tmp == SrcBits) 3875 return VTBits; 3876 3877 // Slow case - determine how far the sign extends into each sub-element. 3878 Tmp2 = VTBits; 3879 for (unsigned i = 0; i != NumElts; ++i) 3880 if (DemandedElts[i]) { 3881 unsigned SubOffset = i % Scale; 3882 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3883 SubOffset = SubOffset * VTBits; 3884 if (Tmp <= SubOffset) 3885 return 1; 3886 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3887 } 3888 return Tmp2; 3889 } 3890 break; 3891 } 3892 3893 case ISD::FP_TO_SINT_SAT: 3894 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 3895 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3896 return VTBits - Tmp + 1; 3897 case ISD::SIGN_EXTEND: 3898 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3899 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3900 case ISD::SIGN_EXTEND_INREG: 3901 // Max of the input and what this extends. 3902 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3903 Tmp = VTBits-Tmp+1; 3904 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3905 return std::max(Tmp, Tmp2); 3906 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3907 SDValue Src = Op.getOperand(0); 3908 EVT SrcVT = Src.getValueType(); 3909 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3910 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3911 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3912 } 3913 case ISD::SRA: 3914 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3915 // SRA X, C -> adds C sign bits. 3916 if (const APInt *ShAmt = 3917 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3918 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3919 return Tmp; 3920 case ISD::SHL: 3921 if (const APInt *ShAmt = 3922 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3923 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3924 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3925 if (ShAmt->ult(Tmp)) 3926 return Tmp - ShAmt->getZExtValue(); 3927 } 3928 break; 3929 case ISD::AND: 3930 case ISD::OR: 3931 case ISD::XOR: // NOT is handled here. 3932 // Logical binary ops preserve the number of sign bits at the worst. 3933 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3934 if (Tmp != 1) { 3935 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3936 FirstAnswer = std::min(Tmp, Tmp2); 3937 // We computed what we know about the sign bits as our first 3938 // answer. Now proceed to the generic code that uses 3939 // computeKnownBits, and pick whichever answer is better. 3940 } 3941 break; 3942 3943 case ISD::SELECT: 3944 case ISD::VSELECT: 3945 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3946 if (Tmp == 1) return 1; // Early out. 3947 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3948 return std::min(Tmp, Tmp2); 3949 case ISD::SELECT_CC: 3950 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3951 if (Tmp == 1) return 1; // Early out. 3952 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3953 return std::min(Tmp, Tmp2); 3954 3955 case ISD::SMIN: 3956 case ISD::SMAX: { 3957 // If we have a clamp pattern, we know that the number of sign bits will be 3958 // the minimum of the clamp min/max range. 3959 bool IsMax = (Opcode == ISD::SMAX); 3960 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3961 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3962 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3963 CstHigh = 3964 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3965 if (CstLow && CstHigh) { 3966 if (!IsMax) 3967 std::swap(CstLow, CstHigh); 3968 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3969 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3970 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3971 return std::min(Tmp, Tmp2); 3972 } 3973 } 3974 3975 // Fallback - just get the minimum number of sign bits of the operands. 3976 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3977 if (Tmp == 1) 3978 return 1; // Early out. 3979 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3980 return std::min(Tmp, Tmp2); 3981 } 3982 case ISD::UMIN: 3983 case ISD::UMAX: 3984 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3985 if (Tmp == 1) 3986 return 1; // Early out. 3987 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3988 return std::min(Tmp, Tmp2); 3989 case ISD::SADDO: 3990 case ISD::UADDO: 3991 case ISD::SSUBO: 3992 case ISD::USUBO: 3993 case ISD::SMULO: 3994 case ISD::UMULO: 3995 if (Op.getResNo() != 1) 3996 break; 3997 // The boolean result conforms to getBooleanContents. Fall through. 3998 // If setcc returns 0/-1, all bits are sign bits. 3999 // We know that we have an integer-based boolean since these operations 4000 // are only available for integer. 4001 if (TLI->getBooleanContents(VT.isVector(), false) == 4002 TargetLowering::ZeroOrNegativeOneBooleanContent) 4003 return VTBits; 4004 break; 4005 case ISD::SETCC: 4006 case ISD::STRICT_FSETCC: 4007 case ISD::STRICT_FSETCCS: { 4008 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4009 // If setcc returns 0/-1, all bits are sign bits. 4010 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4011 TargetLowering::ZeroOrNegativeOneBooleanContent) 4012 return VTBits; 4013 break; 4014 } 4015 case ISD::ROTL: 4016 case ISD::ROTR: 4017 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4018 4019 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4020 if (Tmp == VTBits) 4021 return VTBits; 4022 4023 if (ConstantSDNode *C = 4024 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4025 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4026 4027 // Handle rotate right by N like a rotate left by 32-N. 4028 if (Opcode == ISD::ROTR) 4029 RotAmt = (VTBits - RotAmt) % VTBits; 4030 4031 // If we aren't rotating out all of the known-in sign bits, return the 4032 // number that are left. This handles rotl(sext(x), 1) for example. 4033 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4034 } 4035 break; 4036 case ISD::ADD: 4037 case ISD::ADDC: 4038 // Add can have at most one carry bit. Thus we know that the output 4039 // is, at worst, one more bit than the inputs. 4040 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4041 if (Tmp == 1) return 1; // Early out. 4042 4043 // Special case decrementing a value (ADD X, -1): 4044 if (ConstantSDNode *CRHS = 4045 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4046 if (CRHS->isAllOnes()) { 4047 KnownBits Known = 4048 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4049 4050 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4051 // sign bits set. 4052 if ((Known.Zero | 1).isAllOnes()) 4053 return VTBits; 4054 4055 // If we are subtracting one from a positive number, there is no carry 4056 // out of the result. 4057 if (Known.isNonNegative()) 4058 return Tmp; 4059 } 4060 4061 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4062 if (Tmp2 == 1) return 1; // Early out. 4063 return std::min(Tmp, Tmp2) - 1; 4064 case ISD::SUB: 4065 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4066 if (Tmp2 == 1) return 1; // Early out. 4067 4068 // Handle NEG. 4069 if (ConstantSDNode *CLHS = 4070 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4071 if (CLHS->isZero()) { 4072 KnownBits Known = 4073 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4074 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4075 // sign bits set. 4076 if ((Known.Zero | 1).isAllOnes()) 4077 return VTBits; 4078 4079 // If the input is known to be positive (the sign bit is known clear), 4080 // the output of the NEG has the same number of sign bits as the input. 4081 if (Known.isNonNegative()) 4082 return Tmp2; 4083 4084 // Otherwise, we treat this like a SUB. 4085 } 4086 4087 // Sub can have at most one carry bit. Thus we know that the output 4088 // is, at worst, one more bit than the inputs. 4089 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4090 if (Tmp == 1) return 1; // Early out. 4091 return std::min(Tmp, Tmp2) - 1; 4092 case ISD::MUL: { 4093 // The output of the Mul can be at most twice the valid bits in the inputs. 4094 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4095 if (SignBitsOp0 == 1) 4096 break; 4097 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4098 if (SignBitsOp1 == 1) 4099 break; 4100 unsigned OutValidBits = 4101 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4102 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4103 } 4104 case ISD::SREM: 4105 // The sign bit is the LHS's sign bit, except when the result of the 4106 // remainder is zero. The magnitude of the result should be less than or 4107 // equal to the magnitude of the LHS. Therefore, the result should have 4108 // at least as many sign bits as the left hand side. 4109 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4110 case ISD::TRUNCATE: { 4111 // Check if the sign bits of source go down as far as the truncated value. 4112 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4113 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4114 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4115 return NumSrcSignBits - (NumSrcBits - VTBits); 4116 break; 4117 } 4118 case ISD::EXTRACT_ELEMENT: { 4119 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4120 const int BitWidth = Op.getValueSizeInBits(); 4121 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4122 4123 // Get reverse index (starting from 1), Op1 value indexes elements from 4124 // little end. Sign starts at big end. 4125 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4126 4127 // If the sign portion ends in our element the subtraction gives correct 4128 // result. Otherwise it gives either negative or > bitwidth result 4129 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4130 } 4131 case ISD::INSERT_VECTOR_ELT: { 4132 // If we know the element index, split the demand between the 4133 // source vector and the inserted element, otherwise assume we need 4134 // the original demanded vector elements and the value. 4135 SDValue InVec = Op.getOperand(0); 4136 SDValue InVal = Op.getOperand(1); 4137 SDValue EltNo = Op.getOperand(2); 4138 bool DemandedVal = true; 4139 APInt DemandedVecElts = DemandedElts; 4140 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4141 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4142 unsigned EltIdx = CEltNo->getZExtValue(); 4143 DemandedVal = !!DemandedElts[EltIdx]; 4144 DemandedVecElts.clearBit(EltIdx); 4145 } 4146 Tmp = std::numeric_limits<unsigned>::max(); 4147 if (DemandedVal) { 4148 // TODO - handle implicit truncation of inserted elements. 4149 if (InVal.getScalarValueSizeInBits() != VTBits) 4150 break; 4151 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4152 Tmp = std::min(Tmp, Tmp2); 4153 } 4154 if (!!DemandedVecElts) { 4155 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4156 Tmp = std::min(Tmp, Tmp2); 4157 } 4158 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4159 return Tmp; 4160 } 4161 case ISD::EXTRACT_VECTOR_ELT: { 4162 SDValue InVec = Op.getOperand(0); 4163 SDValue EltNo = Op.getOperand(1); 4164 EVT VecVT = InVec.getValueType(); 4165 // ComputeNumSignBits not yet implemented for scalable vectors. 4166 if (VecVT.isScalableVector()) 4167 break; 4168 const unsigned BitWidth = Op.getValueSizeInBits(); 4169 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4170 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4171 4172 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4173 // anything about sign bits. But if the sizes match we can derive knowledge 4174 // about sign bits from the vector operand. 4175 if (BitWidth != EltBitWidth) 4176 break; 4177 4178 // If we know the element index, just demand that vector element, else for 4179 // an unknown element index, ignore DemandedElts and demand them all. 4180 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4181 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4182 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4183 DemandedSrcElts = 4184 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4185 4186 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4187 } 4188 case ISD::EXTRACT_SUBVECTOR: { 4189 // Offset the demanded elts by the subvector index. 4190 SDValue Src = Op.getOperand(0); 4191 // Bail until we can represent demanded elements for scalable vectors. 4192 if (Src.getValueType().isScalableVector()) 4193 break; 4194 uint64_t Idx = Op.getConstantOperandVal(1); 4195 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4196 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4197 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4198 } 4199 case ISD::CONCAT_VECTORS: { 4200 // Determine the minimum number of sign bits across all demanded 4201 // elts of the input vectors. Early out if the result is already 1. 4202 Tmp = std::numeric_limits<unsigned>::max(); 4203 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4204 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4205 unsigned NumSubVectors = Op.getNumOperands(); 4206 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4207 APInt DemandedSub = 4208 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4209 if (!DemandedSub) 4210 continue; 4211 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4212 Tmp = std::min(Tmp, Tmp2); 4213 } 4214 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4215 return Tmp; 4216 } 4217 case ISD::INSERT_SUBVECTOR: { 4218 // Demand any elements from the subvector and the remainder from the src its 4219 // inserted into. 4220 SDValue Src = Op.getOperand(0); 4221 SDValue Sub = Op.getOperand(1); 4222 uint64_t Idx = Op.getConstantOperandVal(2); 4223 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4224 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4225 APInt DemandedSrcElts = DemandedElts; 4226 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4227 4228 Tmp = std::numeric_limits<unsigned>::max(); 4229 if (!!DemandedSubElts) { 4230 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4231 if (Tmp == 1) 4232 return 1; // early-out 4233 } 4234 if (!!DemandedSrcElts) { 4235 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4236 Tmp = std::min(Tmp, Tmp2); 4237 } 4238 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4239 return Tmp; 4240 } 4241 case ISD::ATOMIC_CMP_SWAP: 4242 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4243 case ISD::ATOMIC_SWAP: 4244 case ISD::ATOMIC_LOAD_ADD: 4245 case ISD::ATOMIC_LOAD_SUB: 4246 case ISD::ATOMIC_LOAD_AND: 4247 case ISD::ATOMIC_LOAD_CLR: 4248 case ISD::ATOMIC_LOAD_OR: 4249 case ISD::ATOMIC_LOAD_XOR: 4250 case ISD::ATOMIC_LOAD_NAND: 4251 case ISD::ATOMIC_LOAD_MIN: 4252 case ISD::ATOMIC_LOAD_MAX: 4253 case ISD::ATOMIC_LOAD_UMIN: 4254 case ISD::ATOMIC_LOAD_UMAX: 4255 case ISD::ATOMIC_LOAD: { 4256 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4257 // If we are looking at the loaded value. 4258 if (Op.getResNo() == 0) { 4259 if (Tmp == VTBits) 4260 return 1; // early-out 4261 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4262 return VTBits - Tmp + 1; 4263 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4264 return VTBits - Tmp; 4265 } 4266 break; 4267 } 4268 } 4269 4270 // If we are looking at the loaded value of the SDNode. 4271 if (Op.getResNo() == 0) { 4272 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4273 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4274 unsigned ExtType = LD->getExtensionType(); 4275 switch (ExtType) { 4276 default: break; 4277 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4278 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4279 return VTBits - Tmp + 1; 4280 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4281 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4282 return VTBits - Tmp; 4283 case ISD::NON_EXTLOAD: 4284 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4285 // We only need to handle vectors - computeKnownBits should handle 4286 // scalar cases. 4287 Type *CstTy = Cst->getType(); 4288 if (CstTy->isVectorTy() && 4289 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4290 VTBits == CstTy->getScalarSizeInBits()) { 4291 Tmp = VTBits; 4292 for (unsigned i = 0; i != NumElts; ++i) { 4293 if (!DemandedElts[i]) 4294 continue; 4295 if (Constant *Elt = Cst->getAggregateElement(i)) { 4296 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4297 const APInt &Value = CInt->getValue(); 4298 Tmp = std::min(Tmp, Value.getNumSignBits()); 4299 continue; 4300 } 4301 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4302 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4303 Tmp = std::min(Tmp, Value.getNumSignBits()); 4304 continue; 4305 } 4306 } 4307 // Unknown type. Conservatively assume no bits match sign bit. 4308 return 1; 4309 } 4310 return Tmp; 4311 } 4312 } 4313 break; 4314 } 4315 } 4316 } 4317 4318 // Allow the target to implement this method for its nodes. 4319 if (Opcode >= ISD::BUILTIN_OP_END || 4320 Opcode == ISD::INTRINSIC_WO_CHAIN || 4321 Opcode == ISD::INTRINSIC_W_CHAIN || 4322 Opcode == ISD::INTRINSIC_VOID) { 4323 unsigned NumBits = 4324 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4325 if (NumBits > 1) 4326 FirstAnswer = std::max(FirstAnswer, NumBits); 4327 } 4328 4329 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4330 // use this information. 4331 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4332 return std::max(FirstAnswer, Known.countMinSignBits()); 4333 } 4334 4335 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4336 unsigned Depth) const { 4337 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4338 return Op.getScalarValueSizeInBits() - SignBits + 1; 4339 } 4340 4341 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4342 const APInt &DemandedElts, 4343 unsigned Depth) const { 4344 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4345 return Op.getScalarValueSizeInBits() - SignBits + 1; 4346 } 4347 4348 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4349 unsigned Depth) const { 4350 // Early out for FREEZE. 4351 if (Op.getOpcode() == ISD::FREEZE) 4352 return true; 4353 4354 // TODO: Assume we don't know anything for now. 4355 EVT VT = Op.getValueType(); 4356 if (VT.isScalableVector()) 4357 return false; 4358 4359 APInt DemandedElts = VT.isVector() 4360 ? APInt::getAllOnes(VT.getVectorNumElements()) 4361 : APInt(1, 1); 4362 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4363 } 4364 4365 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4366 const APInt &DemandedElts, 4367 bool PoisonOnly, 4368 unsigned Depth) const { 4369 unsigned Opcode = Op.getOpcode(); 4370 4371 // Early out for FREEZE. 4372 if (Opcode == ISD::FREEZE) 4373 return true; 4374 4375 if (Depth >= MaxRecursionDepth) 4376 return false; // Limit search depth. 4377 4378 if (isIntOrFPConstant(Op)) 4379 return true; 4380 4381 switch (Opcode) { 4382 case ISD::UNDEF: 4383 return PoisonOnly; 4384 4385 case ISD::BUILD_VECTOR: 4386 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4387 // this shouldn't affect the result. 4388 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4389 if (!DemandedElts[i]) 4390 continue; 4391 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4392 Depth + 1)) 4393 return false; 4394 } 4395 return true; 4396 4397 // TODO: Search for noundef attributes from library functions. 4398 4399 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4400 4401 default: 4402 // Allow the target to implement this method for its nodes. 4403 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4404 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4405 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4406 Op, DemandedElts, *this, PoisonOnly, Depth); 4407 break; 4408 } 4409 4410 return false; 4411 } 4412 4413 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4414 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4415 !isa<ConstantSDNode>(Op.getOperand(1))) 4416 return false; 4417 4418 if (Op.getOpcode() == ISD::OR && 4419 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4420 return false; 4421 4422 return true; 4423 } 4424 4425 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4426 // If we're told that NaNs won't happen, assume they won't. 4427 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4428 return true; 4429 4430 if (Depth >= MaxRecursionDepth) 4431 return false; // Limit search depth. 4432 4433 // TODO: Handle vectors. 4434 // If the value is a constant, we can obviously see if it is a NaN or not. 4435 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4436 return !C->getValueAPF().isNaN() || 4437 (SNaN && !C->getValueAPF().isSignaling()); 4438 } 4439 4440 unsigned Opcode = Op.getOpcode(); 4441 switch (Opcode) { 4442 case ISD::FADD: 4443 case ISD::FSUB: 4444 case ISD::FMUL: 4445 case ISD::FDIV: 4446 case ISD::FREM: 4447 case ISD::FSIN: 4448 case ISD::FCOS: { 4449 if (SNaN) 4450 return true; 4451 // TODO: Need isKnownNeverInfinity 4452 return false; 4453 } 4454 case ISD::FCANONICALIZE: 4455 case ISD::FEXP: 4456 case ISD::FEXP2: 4457 case ISD::FTRUNC: 4458 case ISD::FFLOOR: 4459 case ISD::FCEIL: 4460 case ISD::FROUND: 4461 case ISD::FROUNDEVEN: 4462 case ISD::FRINT: 4463 case ISD::FNEARBYINT: { 4464 if (SNaN) 4465 return true; 4466 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4467 } 4468 case ISD::FABS: 4469 case ISD::FNEG: 4470 case ISD::FCOPYSIGN: { 4471 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4472 } 4473 case ISD::SELECT: 4474 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4475 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4476 case ISD::FP_EXTEND: 4477 case ISD::FP_ROUND: { 4478 if (SNaN) 4479 return true; 4480 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4481 } 4482 case ISD::SINT_TO_FP: 4483 case ISD::UINT_TO_FP: 4484 return true; 4485 case ISD::FMA: 4486 case ISD::FMAD: { 4487 if (SNaN) 4488 return true; 4489 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4490 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4491 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4492 } 4493 case ISD::FSQRT: // Need is known positive 4494 case ISD::FLOG: 4495 case ISD::FLOG2: 4496 case ISD::FLOG10: 4497 case ISD::FPOWI: 4498 case ISD::FPOW: { 4499 if (SNaN) 4500 return true; 4501 // TODO: Refine on operand 4502 return false; 4503 } 4504 case ISD::FMINNUM: 4505 case ISD::FMAXNUM: { 4506 // Only one needs to be known not-nan, since it will be returned if the 4507 // other ends up being one. 4508 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4509 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4510 } 4511 case ISD::FMINNUM_IEEE: 4512 case ISD::FMAXNUM_IEEE: { 4513 if (SNaN) 4514 return true; 4515 // This can return a NaN if either operand is an sNaN, or if both operands 4516 // are NaN. 4517 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4518 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4519 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4520 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4521 } 4522 case ISD::FMINIMUM: 4523 case ISD::FMAXIMUM: { 4524 // TODO: Does this quiet or return the origina NaN as-is? 4525 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4526 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4527 } 4528 case ISD::EXTRACT_VECTOR_ELT: { 4529 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4530 } 4531 default: 4532 if (Opcode >= ISD::BUILTIN_OP_END || 4533 Opcode == ISD::INTRINSIC_WO_CHAIN || 4534 Opcode == ISD::INTRINSIC_W_CHAIN || 4535 Opcode == ISD::INTRINSIC_VOID) { 4536 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4537 } 4538 4539 return false; 4540 } 4541 } 4542 4543 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4544 assert(Op.getValueType().isFloatingPoint() && 4545 "Floating point type expected"); 4546 4547 // If the value is a constant, we can obviously see if it is a zero or not. 4548 // TODO: Add BuildVector support. 4549 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4550 return !C->isZero(); 4551 return false; 4552 } 4553 4554 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4555 assert(!Op.getValueType().isFloatingPoint() && 4556 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4557 4558 // If the value is a constant, we can obviously see if it is a zero or not. 4559 if (ISD::matchUnaryPredicate(Op, 4560 [](ConstantSDNode *C) { return !C->isZero(); })) 4561 return true; 4562 4563 // TODO: Recognize more cases here. 4564 switch (Op.getOpcode()) { 4565 default: break; 4566 case ISD::OR: 4567 if (isKnownNeverZero(Op.getOperand(1)) || 4568 isKnownNeverZero(Op.getOperand(0))) 4569 return true; 4570 break; 4571 } 4572 4573 return false; 4574 } 4575 4576 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4577 // Check the obvious case. 4578 if (A == B) return true; 4579 4580 // For for negative and positive zero. 4581 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4582 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4583 if (CA->isZero() && CB->isZero()) return true; 4584 4585 // Otherwise they may not be equal. 4586 return false; 4587 } 4588 4589 // FIXME: unify with llvm::haveNoCommonBitsSet. 4590 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4591 assert(A.getValueType() == B.getValueType() && 4592 "Values must have the same type"); 4593 // Match masked merge pattern (X & ~M) op (Y & M) 4594 if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) { 4595 auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) { 4596 if (isBitwiseNot(NotM, true)) { 4597 SDValue NotOperand = NotM->getOperand(0); 4598 return NotOperand == And->getOperand(0) || 4599 NotOperand == And->getOperand(1); 4600 } 4601 return false; 4602 }; 4603 if (MatchNoCommonBitsPattern(A->getOperand(0), B) || 4604 MatchNoCommonBitsPattern(A->getOperand(1), B) || 4605 MatchNoCommonBitsPattern(B->getOperand(0), A) || 4606 MatchNoCommonBitsPattern(B->getOperand(1), A)) 4607 return true; 4608 } 4609 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4610 computeKnownBits(B)); 4611 } 4612 4613 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4614 SelectionDAG &DAG) { 4615 if (cast<ConstantSDNode>(Step)->isZero()) 4616 return DAG.getConstant(0, DL, VT); 4617 4618 return SDValue(); 4619 } 4620 4621 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4622 ArrayRef<SDValue> Ops, 4623 SelectionDAG &DAG) { 4624 int NumOps = Ops.size(); 4625 assert(NumOps != 0 && "Can't build an empty vector!"); 4626 assert(!VT.isScalableVector() && 4627 "BUILD_VECTOR cannot be used with scalable types"); 4628 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4629 "Incorrect element count in BUILD_VECTOR!"); 4630 4631 // BUILD_VECTOR of UNDEFs is UNDEF. 4632 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4633 return DAG.getUNDEF(VT); 4634 4635 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4636 SDValue IdentitySrc; 4637 bool IsIdentity = true; 4638 for (int i = 0; i != NumOps; ++i) { 4639 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4640 Ops[i].getOperand(0).getValueType() != VT || 4641 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4642 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4643 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4644 IsIdentity = false; 4645 break; 4646 } 4647 IdentitySrc = Ops[i].getOperand(0); 4648 } 4649 if (IsIdentity) 4650 return IdentitySrc; 4651 4652 return SDValue(); 4653 } 4654 4655 /// Try to simplify vector concatenation to an input value, undef, or build 4656 /// vector. 4657 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4658 ArrayRef<SDValue> Ops, 4659 SelectionDAG &DAG) { 4660 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4661 assert(llvm::all_of(Ops, 4662 [Ops](SDValue Op) { 4663 return Ops[0].getValueType() == Op.getValueType(); 4664 }) && 4665 "Concatenation of vectors with inconsistent value types!"); 4666 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4667 VT.getVectorElementCount() && 4668 "Incorrect element count in vector concatenation!"); 4669 4670 if (Ops.size() == 1) 4671 return Ops[0]; 4672 4673 // Concat of UNDEFs is UNDEF. 4674 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4675 return DAG.getUNDEF(VT); 4676 4677 // Scan the operands and look for extract operations from a single source 4678 // that correspond to insertion at the same location via this concatenation: 4679 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4680 SDValue IdentitySrc; 4681 bool IsIdentity = true; 4682 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4683 SDValue Op = Ops[i]; 4684 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4685 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4686 Op.getOperand(0).getValueType() != VT || 4687 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4688 Op.getConstantOperandVal(1) != IdentityIndex) { 4689 IsIdentity = false; 4690 break; 4691 } 4692 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4693 "Unexpected identity source vector for concat of extracts"); 4694 IdentitySrc = Op.getOperand(0); 4695 } 4696 if (IsIdentity) { 4697 assert(IdentitySrc && "Failed to set source vector of extracts"); 4698 return IdentitySrc; 4699 } 4700 4701 // The code below this point is only designed to work for fixed width 4702 // vectors, so we bail out for now. 4703 if (VT.isScalableVector()) 4704 return SDValue(); 4705 4706 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4707 // simplified to one big BUILD_VECTOR. 4708 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4709 EVT SVT = VT.getScalarType(); 4710 SmallVector<SDValue, 16> Elts; 4711 for (SDValue Op : Ops) { 4712 EVT OpVT = Op.getValueType(); 4713 if (Op.isUndef()) 4714 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4715 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4716 Elts.append(Op->op_begin(), Op->op_end()); 4717 else 4718 return SDValue(); 4719 } 4720 4721 // BUILD_VECTOR requires all inputs to be of the same type, find the 4722 // maximum type and extend them all. 4723 for (SDValue Op : Elts) 4724 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4725 4726 if (SVT.bitsGT(VT.getScalarType())) { 4727 for (SDValue &Op : Elts) { 4728 if (Op.isUndef()) 4729 Op = DAG.getUNDEF(SVT); 4730 else 4731 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4732 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4733 : DAG.getSExtOrTrunc(Op, DL, SVT); 4734 } 4735 } 4736 4737 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4738 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4739 return V; 4740 } 4741 4742 /// Gets or creates the specified node. 4743 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4744 FoldingSetNodeID ID; 4745 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4746 void *IP = nullptr; 4747 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4748 return SDValue(E, 0); 4749 4750 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4751 getVTList(VT)); 4752 CSEMap.InsertNode(N, IP); 4753 4754 InsertNode(N); 4755 SDValue V = SDValue(N, 0); 4756 NewSDValueDbgMsg(V, "Creating new node: ", this); 4757 return V; 4758 } 4759 4760 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4761 SDValue Operand) { 4762 SDNodeFlags Flags; 4763 if (Inserter) 4764 Flags = Inserter->getFlags(); 4765 return getNode(Opcode, DL, VT, Operand, Flags); 4766 } 4767 4768 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4769 SDValue Operand, const SDNodeFlags Flags) { 4770 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4771 "Operand is DELETED_NODE!"); 4772 // Constant fold unary operations with an integer constant operand. Even 4773 // opaque constant will be folded, because the folding of unary operations 4774 // doesn't create new constants with different values. Nevertheless, the 4775 // opaque flag is preserved during folding to prevent future folding with 4776 // other constants. 4777 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4778 const APInt &Val = C->getAPIntValue(); 4779 switch (Opcode) { 4780 default: break; 4781 case ISD::SIGN_EXTEND: 4782 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4783 C->isTargetOpcode(), C->isOpaque()); 4784 case ISD::TRUNCATE: 4785 if (C->isOpaque()) 4786 break; 4787 LLVM_FALLTHROUGH; 4788 case ISD::ZERO_EXTEND: 4789 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4790 C->isTargetOpcode(), C->isOpaque()); 4791 case ISD::ANY_EXTEND: 4792 // Some targets like RISCV prefer to sign extend some types. 4793 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4794 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4795 C->isTargetOpcode(), C->isOpaque()); 4796 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4797 C->isTargetOpcode(), C->isOpaque()); 4798 case ISD::UINT_TO_FP: 4799 case ISD::SINT_TO_FP: { 4800 APFloat apf(EVTToAPFloatSemantics(VT), 4801 APInt::getZero(VT.getSizeInBits())); 4802 (void)apf.convertFromAPInt(Val, 4803 Opcode==ISD::SINT_TO_FP, 4804 APFloat::rmNearestTiesToEven); 4805 return getConstantFP(apf, DL, VT); 4806 } 4807 case ISD::BITCAST: 4808 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4809 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4810 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4811 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4812 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4813 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4814 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4815 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4816 break; 4817 case ISD::ABS: 4818 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4819 C->isOpaque()); 4820 case ISD::BITREVERSE: 4821 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4822 C->isOpaque()); 4823 case ISD::BSWAP: 4824 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4825 C->isOpaque()); 4826 case ISD::CTPOP: 4827 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4828 C->isOpaque()); 4829 case ISD::CTLZ: 4830 case ISD::CTLZ_ZERO_UNDEF: 4831 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4832 C->isOpaque()); 4833 case ISD::CTTZ: 4834 case ISD::CTTZ_ZERO_UNDEF: 4835 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4836 C->isOpaque()); 4837 case ISD::FP16_TO_FP: { 4838 bool Ignored; 4839 APFloat FPV(APFloat::IEEEhalf(), 4840 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4841 4842 // This can return overflow, underflow, or inexact; we don't care. 4843 // FIXME need to be more flexible about rounding mode. 4844 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4845 APFloat::rmNearestTiesToEven, &Ignored); 4846 return getConstantFP(FPV, DL, VT); 4847 } 4848 case ISD::STEP_VECTOR: { 4849 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4850 return V; 4851 break; 4852 } 4853 } 4854 } 4855 4856 // Constant fold unary operations with a floating point constant operand. 4857 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4858 APFloat V = C->getValueAPF(); // make copy 4859 switch (Opcode) { 4860 case ISD::FNEG: 4861 V.changeSign(); 4862 return getConstantFP(V, DL, VT); 4863 case ISD::FABS: 4864 V.clearSign(); 4865 return getConstantFP(V, DL, VT); 4866 case ISD::FCEIL: { 4867 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4868 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4869 return getConstantFP(V, DL, VT); 4870 break; 4871 } 4872 case ISD::FTRUNC: { 4873 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4874 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4875 return getConstantFP(V, DL, VT); 4876 break; 4877 } 4878 case ISD::FFLOOR: { 4879 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4880 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4881 return getConstantFP(V, DL, VT); 4882 break; 4883 } 4884 case ISD::FP_EXTEND: { 4885 bool ignored; 4886 // This can return overflow, underflow, or inexact; we don't care. 4887 // FIXME need to be more flexible about rounding mode. 4888 (void)V.convert(EVTToAPFloatSemantics(VT), 4889 APFloat::rmNearestTiesToEven, &ignored); 4890 return getConstantFP(V, DL, VT); 4891 } 4892 case ISD::FP_TO_SINT: 4893 case ISD::FP_TO_UINT: { 4894 bool ignored; 4895 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4896 // FIXME need to be more flexible about rounding mode. 4897 APFloat::opStatus s = 4898 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4899 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4900 break; 4901 return getConstant(IntVal, DL, VT); 4902 } 4903 case ISD::BITCAST: 4904 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4905 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4906 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4907 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4908 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4909 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4910 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4911 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4912 break; 4913 case ISD::FP_TO_FP16: { 4914 bool Ignored; 4915 // This can return overflow, underflow, or inexact; we don't care. 4916 // FIXME need to be more flexible about rounding mode. 4917 (void)V.convert(APFloat::IEEEhalf(), 4918 APFloat::rmNearestTiesToEven, &Ignored); 4919 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4920 } 4921 } 4922 } 4923 4924 // Constant fold unary operations with a vector integer or float operand. 4925 switch (Opcode) { 4926 default: 4927 // FIXME: Entirely reasonable to perform folding of other unary 4928 // operations here as the need arises. 4929 break; 4930 case ISD::FNEG: 4931 case ISD::FABS: 4932 case ISD::FCEIL: 4933 case ISD::FTRUNC: 4934 case ISD::FFLOOR: 4935 case ISD::FP_EXTEND: 4936 case ISD::FP_TO_SINT: 4937 case ISD::FP_TO_UINT: 4938 case ISD::TRUNCATE: 4939 case ISD::ANY_EXTEND: 4940 case ISD::ZERO_EXTEND: 4941 case ISD::SIGN_EXTEND: 4942 case ISD::UINT_TO_FP: 4943 case ISD::SINT_TO_FP: 4944 case ISD::ABS: 4945 case ISD::BITREVERSE: 4946 case ISD::BSWAP: 4947 case ISD::CTLZ: 4948 case ISD::CTLZ_ZERO_UNDEF: 4949 case ISD::CTTZ: 4950 case ISD::CTTZ_ZERO_UNDEF: 4951 case ISD::CTPOP: { 4952 SDValue Ops = {Operand}; 4953 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 4954 return Fold; 4955 } 4956 } 4957 4958 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4959 switch (Opcode) { 4960 case ISD::STEP_VECTOR: 4961 assert(VT.isScalableVector() && 4962 "STEP_VECTOR can only be used with scalable types"); 4963 assert(OpOpcode == ISD::TargetConstant && 4964 VT.getVectorElementType() == Operand.getValueType() && 4965 "Unexpected step operand"); 4966 break; 4967 case ISD::FREEZE: 4968 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4969 break; 4970 case ISD::TokenFactor: 4971 case ISD::MERGE_VALUES: 4972 case ISD::CONCAT_VECTORS: 4973 return Operand; // Factor, merge or concat of one node? No need. 4974 case ISD::BUILD_VECTOR: { 4975 // Attempt to simplify BUILD_VECTOR. 4976 SDValue Ops[] = {Operand}; 4977 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4978 return V; 4979 break; 4980 } 4981 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4982 case ISD::FP_EXTEND: 4983 assert(VT.isFloatingPoint() && 4984 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4985 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4986 assert((!VT.isVector() || 4987 VT.getVectorElementCount() == 4988 Operand.getValueType().getVectorElementCount()) && 4989 "Vector element count mismatch!"); 4990 assert(Operand.getValueType().bitsLT(VT) && 4991 "Invalid fpext node, dst < src!"); 4992 if (Operand.isUndef()) 4993 return getUNDEF(VT); 4994 break; 4995 case ISD::FP_TO_SINT: 4996 case ISD::FP_TO_UINT: 4997 if (Operand.isUndef()) 4998 return getUNDEF(VT); 4999 break; 5000 case ISD::SINT_TO_FP: 5001 case ISD::UINT_TO_FP: 5002 // [us]itofp(undef) = 0, because the result value is bounded. 5003 if (Operand.isUndef()) 5004 return getConstantFP(0.0, DL, VT); 5005 break; 5006 case ISD::SIGN_EXTEND: 5007 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5008 "Invalid SIGN_EXTEND!"); 5009 assert(VT.isVector() == Operand.getValueType().isVector() && 5010 "SIGN_EXTEND result type type should be vector iff the operand " 5011 "type is vector!"); 5012 if (Operand.getValueType() == VT) return Operand; // noop extension 5013 assert((!VT.isVector() || 5014 VT.getVectorElementCount() == 5015 Operand.getValueType().getVectorElementCount()) && 5016 "Vector element count mismatch!"); 5017 assert(Operand.getValueType().bitsLT(VT) && 5018 "Invalid sext node, dst < src!"); 5019 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5020 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5021 if (OpOpcode == ISD::UNDEF) 5022 // sext(undef) = 0, because the top bits will all be the same. 5023 return getConstant(0, DL, VT); 5024 break; 5025 case ISD::ZERO_EXTEND: 5026 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5027 "Invalid ZERO_EXTEND!"); 5028 assert(VT.isVector() == Operand.getValueType().isVector() && 5029 "ZERO_EXTEND result type type should be vector iff the operand " 5030 "type is vector!"); 5031 if (Operand.getValueType() == VT) return Operand; // noop extension 5032 assert((!VT.isVector() || 5033 VT.getVectorElementCount() == 5034 Operand.getValueType().getVectorElementCount()) && 5035 "Vector element count mismatch!"); 5036 assert(Operand.getValueType().bitsLT(VT) && 5037 "Invalid zext node, dst < src!"); 5038 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5039 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5040 if (OpOpcode == ISD::UNDEF) 5041 // zext(undef) = 0, because the top bits will be zero. 5042 return getConstant(0, DL, VT); 5043 break; 5044 case ISD::ANY_EXTEND: 5045 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5046 "Invalid ANY_EXTEND!"); 5047 assert(VT.isVector() == Operand.getValueType().isVector() && 5048 "ANY_EXTEND result type type should be vector iff the operand " 5049 "type is vector!"); 5050 if (Operand.getValueType() == VT) return Operand; // noop extension 5051 assert((!VT.isVector() || 5052 VT.getVectorElementCount() == 5053 Operand.getValueType().getVectorElementCount()) && 5054 "Vector element count mismatch!"); 5055 assert(Operand.getValueType().bitsLT(VT) && 5056 "Invalid anyext node, dst < src!"); 5057 5058 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5059 OpOpcode == ISD::ANY_EXTEND) 5060 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5061 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5062 if (OpOpcode == ISD::UNDEF) 5063 return getUNDEF(VT); 5064 5065 // (ext (trunc x)) -> x 5066 if (OpOpcode == ISD::TRUNCATE) { 5067 SDValue OpOp = Operand.getOperand(0); 5068 if (OpOp.getValueType() == VT) { 5069 transferDbgValues(Operand, OpOp); 5070 return OpOp; 5071 } 5072 } 5073 break; 5074 case ISD::TRUNCATE: 5075 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5076 "Invalid TRUNCATE!"); 5077 assert(VT.isVector() == Operand.getValueType().isVector() && 5078 "TRUNCATE result type type should be vector iff the operand " 5079 "type is vector!"); 5080 if (Operand.getValueType() == VT) return Operand; // noop truncate 5081 assert((!VT.isVector() || 5082 VT.getVectorElementCount() == 5083 Operand.getValueType().getVectorElementCount()) && 5084 "Vector element count mismatch!"); 5085 assert(Operand.getValueType().bitsGT(VT) && 5086 "Invalid truncate node, src < dst!"); 5087 if (OpOpcode == ISD::TRUNCATE) 5088 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5089 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5090 OpOpcode == ISD::ANY_EXTEND) { 5091 // If the source is smaller than the dest, we still need an extend. 5092 if (Operand.getOperand(0).getValueType().getScalarType() 5093 .bitsLT(VT.getScalarType())) 5094 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5095 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5096 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5097 return Operand.getOperand(0); 5098 } 5099 if (OpOpcode == ISD::UNDEF) 5100 return getUNDEF(VT); 5101 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5102 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5103 break; 5104 case ISD::ANY_EXTEND_VECTOR_INREG: 5105 case ISD::ZERO_EXTEND_VECTOR_INREG: 5106 case ISD::SIGN_EXTEND_VECTOR_INREG: 5107 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5108 assert(Operand.getValueType().bitsLE(VT) && 5109 "The input must be the same size or smaller than the result."); 5110 assert(VT.getVectorMinNumElements() < 5111 Operand.getValueType().getVectorMinNumElements() && 5112 "The destination vector type must have fewer lanes than the input."); 5113 break; 5114 case ISD::ABS: 5115 assert(VT.isInteger() && VT == Operand.getValueType() && 5116 "Invalid ABS!"); 5117 if (OpOpcode == ISD::UNDEF) 5118 return getUNDEF(VT); 5119 break; 5120 case ISD::BSWAP: 5121 assert(VT.isInteger() && VT == Operand.getValueType() && 5122 "Invalid BSWAP!"); 5123 assert((VT.getScalarSizeInBits() % 16 == 0) && 5124 "BSWAP types must be a multiple of 16 bits!"); 5125 if (OpOpcode == ISD::UNDEF) 5126 return getUNDEF(VT); 5127 // bswap(bswap(X)) -> X. 5128 if (OpOpcode == ISD::BSWAP) 5129 return Operand.getOperand(0); 5130 break; 5131 case ISD::BITREVERSE: 5132 assert(VT.isInteger() && VT == Operand.getValueType() && 5133 "Invalid BITREVERSE!"); 5134 if (OpOpcode == ISD::UNDEF) 5135 return getUNDEF(VT); 5136 break; 5137 case ISD::BITCAST: 5138 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5139 "Cannot BITCAST between types of different sizes!"); 5140 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5141 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5142 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5143 if (OpOpcode == ISD::UNDEF) 5144 return getUNDEF(VT); 5145 break; 5146 case ISD::SCALAR_TO_VECTOR: 5147 assert(VT.isVector() && !Operand.getValueType().isVector() && 5148 (VT.getVectorElementType() == Operand.getValueType() || 5149 (VT.getVectorElementType().isInteger() && 5150 Operand.getValueType().isInteger() && 5151 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5152 "Illegal SCALAR_TO_VECTOR node!"); 5153 if (OpOpcode == ISD::UNDEF) 5154 return getUNDEF(VT); 5155 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5156 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5157 isa<ConstantSDNode>(Operand.getOperand(1)) && 5158 Operand.getConstantOperandVal(1) == 0 && 5159 Operand.getOperand(0).getValueType() == VT) 5160 return Operand.getOperand(0); 5161 break; 5162 case ISD::FNEG: 5163 // Negation of an unknown bag of bits is still completely undefined. 5164 if (OpOpcode == ISD::UNDEF) 5165 return getUNDEF(VT); 5166 5167 if (OpOpcode == ISD::FNEG) // --X -> X 5168 return Operand.getOperand(0); 5169 break; 5170 case ISD::FABS: 5171 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5172 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5173 break; 5174 case ISD::VSCALE: 5175 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5176 break; 5177 case ISD::CTPOP: 5178 if (Operand.getValueType().getScalarType() == MVT::i1) 5179 return Operand; 5180 break; 5181 case ISD::CTLZ: 5182 case ISD::CTTZ: 5183 if (Operand.getValueType().getScalarType() == MVT::i1) 5184 return getNOT(DL, Operand, Operand.getValueType()); 5185 break; 5186 case ISD::VECREDUCE_SMIN: 5187 case ISD::VECREDUCE_UMAX: 5188 if (Operand.getValueType().getScalarType() == MVT::i1) 5189 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5190 break; 5191 case ISD::VECREDUCE_SMAX: 5192 case ISD::VECREDUCE_UMIN: 5193 if (Operand.getValueType().getScalarType() == MVT::i1) 5194 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5195 break; 5196 } 5197 5198 SDNode *N; 5199 SDVTList VTs = getVTList(VT); 5200 SDValue Ops[] = {Operand}; 5201 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5202 FoldingSetNodeID ID; 5203 AddNodeIDNode(ID, Opcode, VTs, Ops); 5204 void *IP = nullptr; 5205 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5206 E->intersectFlagsWith(Flags); 5207 return SDValue(E, 0); 5208 } 5209 5210 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5211 N->setFlags(Flags); 5212 createOperands(N, Ops); 5213 CSEMap.InsertNode(N, IP); 5214 } else { 5215 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5216 createOperands(N, Ops); 5217 } 5218 5219 InsertNode(N); 5220 SDValue V = SDValue(N, 0); 5221 NewSDValueDbgMsg(V, "Creating new node: ", this); 5222 return V; 5223 } 5224 5225 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5226 const APInt &C2) { 5227 switch (Opcode) { 5228 case ISD::ADD: return C1 + C2; 5229 case ISD::SUB: return C1 - C2; 5230 case ISD::MUL: return C1 * C2; 5231 case ISD::AND: return C1 & C2; 5232 case ISD::OR: return C1 | C2; 5233 case ISD::XOR: return C1 ^ C2; 5234 case ISD::SHL: return C1 << C2; 5235 case ISD::SRL: return C1.lshr(C2); 5236 case ISD::SRA: return C1.ashr(C2); 5237 case ISD::ROTL: return C1.rotl(C2); 5238 case ISD::ROTR: return C1.rotr(C2); 5239 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5240 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5241 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5242 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5243 case ISD::SADDSAT: return C1.sadd_sat(C2); 5244 case ISD::UADDSAT: return C1.uadd_sat(C2); 5245 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5246 case ISD::USUBSAT: return C1.usub_sat(C2); 5247 case ISD::SSHLSAT: return C1.sshl_sat(C2); 5248 case ISD::USHLSAT: return C1.ushl_sat(C2); 5249 case ISD::UDIV: 5250 if (!C2.getBoolValue()) 5251 break; 5252 return C1.udiv(C2); 5253 case ISD::UREM: 5254 if (!C2.getBoolValue()) 5255 break; 5256 return C1.urem(C2); 5257 case ISD::SDIV: 5258 if (!C2.getBoolValue()) 5259 break; 5260 return C1.sdiv(C2); 5261 case ISD::SREM: 5262 if (!C2.getBoolValue()) 5263 break; 5264 return C1.srem(C2); 5265 case ISD::MULHS: { 5266 unsigned FullWidth = C1.getBitWidth() * 2; 5267 APInt C1Ext = C1.sext(FullWidth); 5268 APInt C2Ext = C2.sext(FullWidth); 5269 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5270 } 5271 case ISD::MULHU: { 5272 unsigned FullWidth = C1.getBitWidth() * 2; 5273 APInt C1Ext = C1.zext(FullWidth); 5274 APInt C2Ext = C2.zext(FullWidth); 5275 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5276 } 5277 case ISD::AVGFLOORS: { 5278 unsigned FullWidth = C1.getBitWidth() + 1; 5279 APInt C1Ext = C1.sext(FullWidth); 5280 APInt C2Ext = C2.sext(FullWidth); 5281 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5282 } 5283 case ISD::AVGFLOORU: { 5284 unsigned FullWidth = C1.getBitWidth() + 1; 5285 APInt C1Ext = C1.zext(FullWidth); 5286 APInt C2Ext = C2.zext(FullWidth); 5287 return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1); 5288 } 5289 case ISD::AVGCEILS: { 5290 unsigned FullWidth = C1.getBitWidth() + 1; 5291 APInt C1Ext = C1.sext(FullWidth); 5292 APInt C2Ext = C2.sext(FullWidth); 5293 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5294 } 5295 case ISD::AVGCEILU: { 5296 unsigned FullWidth = C1.getBitWidth() + 1; 5297 APInt C1Ext = C1.zext(FullWidth); 5298 APInt C2Ext = C2.zext(FullWidth); 5299 return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1); 5300 } 5301 } 5302 return llvm::None; 5303 } 5304 5305 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5306 const GlobalAddressSDNode *GA, 5307 const SDNode *N2) { 5308 if (GA->getOpcode() != ISD::GlobalAddress) 5309 return SDValue(); 5310 if (!TLI->isOffsetFoldingLegal(GA)) 5311 return SDValue(); 5312 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5313 if (!C2) 5314 return SDValue(); 5315 int64_t Offset = C2->getSExtValue(); 5316 switch (Opcode) { 5317 case ISD::ADD: break; 5318 case ISD::SUB: Offset = -uint64_t(Offset); break; 5319 default: return SDValue(); 5320 } 5321 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5322 GA->getOffset() + uint64_t(Offset)); 5323 } 5324 5325 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5326 switch (Opcode) { 5327 case ISD::SDIV: 5328 case ISD::UDIV: 5329 case ISD::SREM: 5330 case ISD::UREM: { 5331 // If a divisor is zero/undef or any element of a divisor vector is 5332 // zero/undef, the whole op is undef. 5333 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5334 SDValue Divisor = Ops[1]; 5335 if (Divisor.isUndef() || isNullConstant(Divisor)) 5336 return true; 5337 5338 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5339 llvm::any_of(Divisor->op_values(), 5340 [](SDValue V) { return V.isUndef() || 5341 isNullConstant(V); }); 5342 // TODO: Handle signed overflow. 5343 } 5344 // TODO: Handle oversized shifts. 5345 default: 5346 return false; 5347 } 5348 } 5349 5350 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5351 EVT VT, ArrayRef<SDValue> Ops) { 5352 // If the opcode is a target-specific ISD node, there's nothing we can 5353 // do here and the operand rules may not line up with the below, so 5354 // bail early. 5355 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5356 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5357 // foldCONCAT_VECTORS in getNode before this is called. 5358 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5359 return SDValue(); 5360 5361 unsigned NumOps = Ops.size(); 5362 if (NumOps == 0) 5363 return SDValue(); 5364 5365 if (isUndef(Opcode, Ops)) 5366 return getUNDEF(VT); 5367 5368 // Handle binops special cases. 5369 if (NumOps == 2) { 5370 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5371 return CFP; 5372 5373 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5374 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5375 if (C1->isOpaque() || C2->isOpaque()) 5376 return SDValue(); 5377 5378 Optional<APInt> FoldAttempt = 5379 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5380 if (!FoldAttempt) 5381 return SDValue(); 5382 5383 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5384 assert((!Folded || !VT.isVector()) && 5385 "Can't fold vectors ops with scalar operands"); 5386 return Folded; 5387 } 5388 } 5389 5390 // fold (add Sym, c) -> Sym+c 5391 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5392 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5393 if (TLI->isCommutativeBinOp(Opcode)) 5394 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5395 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5396 } 5397 5398 // This is for vector folding only from here on. 5399 if (!VT.isVector()) 5400 return SDValue(); 5401 5402 ElementCount NumElts = VT.getVectorElementCount(); 5403 5404 // See if we can fold through bitcasted integer ops. 5405 // TODO: Can we handle undef elements? 5406 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5407 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5408 Ops[0].getOpcode() == ISD::BITCAST && 5409 Ops[1].getOpcode() == ISD::BITCAST) { 5410 SDValue N1 = peekThroughBitcasts(Ops[0]); 5411 SDValue N2 = peekThroughBitcasts(Ops[1]); 5412 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5413 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5414 EVT BVVT = N1.getValueType(); 5415 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5416 bool IsLE = getDataLayout().isLittleEndian(); 5417 unsigned EltBits = VT.getScalarSizeInBits(); 5418 SmallVector<APInt> RawBits1, RawBits2; 5419 BitVector UndefElts1, UndefElts2; 5420 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5421 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5422 UndefElts1.none() && UndefElts2.none()) { 5423 SmallVector<APInt> RawBits; 5424 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5425 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5426 if (!Fold) 5427 break; 5428 RawBits.push_back(Fold.getValue()); 5429 } 5430 if (RawBits.size() == NumElts.getFixedValue()) { 5431 // We have constant folded, but we need to cast this again back to 5432 // the original (possibly legalized) type. 5433 SmallVector<APInt> DstBits; 5434 BitVector DstUndefs; 5435 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5436 DstBits, RawBits, DstUndefs, 5437 BitVector(RawBits.size(), false)); 5438 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5439 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5440 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5441 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5442 if (DstUndefs[I]) 5443 continue; 5444 Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT); 5445 } 5446 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5447 } 5448 } 5449 } 5450 } 5451 5452 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5453 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5454 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5455 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5456 APInt RHSVal; 5457 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5458 APInt NewStep = Opcode == ISD::MUL 5459 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5460 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5461 return getStepVector(DL, VT, NewStep); 5462 } 5463 } 5464 5465 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5466 return !Op.getValueType().isVector() || 5467 Op.getValueType().getVectorElementCount() == NumElts; 5468 }; 5469 5470 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5471 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5472 Op.getOpcode() == ISD::BUILD_VECTOR || 5473 Op.getOpcode() == ISD::SPLAT_VECTOR; 5474 }; 5475 5476 // All operands must be vector types with the same number of elements as 5477 // the result type and must be either UNDEF or a build/splat vector 5478 // or UNDEF scalars. 5479 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5480 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5481 return SDValue(); 5482 5483 // If we are comparing vectors, then the result needs to be a i1 boolean 5484 // that is then sign-extended back to the legal result type. 5485 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5486 5487 // Find legal integer scalar type for constant promotion and 5488 // ensure that its scalar size is at least as large as source. 5489 EVT LegalSVT = VT.getScalarType(); 5490 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5491 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5492 if (LegalSVT.bitsLT(VT.getScalarType())) 5493 return SDValue(); 5494 } 5495 5496 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5497 // only have one operand to check. For fixed-length vector types we may have 5498 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5499 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5500 5501 // Constant fold each scalar lane separately. 5502 SmallVector<SDValue, 4> ScalarResults; 5503 for (unsigned I = 0; I != NumVectorElts; I++) { 5504 SmallVector<SDValue, 4> ScalarOps; 5505 for (SDValue Op : Ops) { 5506 EVT InSVT = Op.getValueType().getScalarType(); 5507 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5508 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5509 if (Op.isUndef()) 5510 ScalarOps.push_back(getUNDEF(InSVT)); 5511 else 5512 ScalarOps.push_back(Op); 5513 continue; 5514 } 5515 5516 SDValue ScalarOp = 5517 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5518 EVT ScalarVT = ScalarOp.getValueType(); 5519 5520 // Build vector (integer) scalar operands may need implicit 5521 // truncation - do this before constant folding. 5522 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5523 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5524 5525 ScalarOps.push_back(ScalarOp); 5526 } 5527 5528 // Constant fold the scalar operands. 5529 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5530 5531 // Legalize the (integer) scalar constant if necessary. 5532 if (LegalSVT != SVT) 5533 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5534 5535 // Scalar folding only succeeded if the result is a constant or UNDEF. 5536 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5537 ScalarResult.getOpcode() != ISD::ConstantFP) 5538 return SDValue(); 5539 ScalarResults.push_back(ScalarResult); 5540 } 5541 5542 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5543 : getBuildVector(VT, DL, ScalarResults); 5544 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5545 return V; 5546 } 5547 5548 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5549 EVT VT, SDValue N1, SDValue N2) { 5550 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5551 // should. That will require dealing with a potentially non-default 5552 // rounding mode, checking the "opStatus" return value from the APFloat 5553 // math calculations, and possibly other variations. 5554 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5555 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5556 if (N1CFP && N2CFP) { 5557 APFloat C1 = N1CFP->getValueAPF(); // make copy 5558 const APFloat &C2 = N2CFP->getValueAPF(); 5559 switch (Opcode) { 5560 case ISD::FADD: 5561 C1.add(C2, APFloat::rmNearestTiesToEven); 5562 return getConstantFP(C1, DL, VT); 5563 case ISD::FSUB: 5564 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5565 return getConstantFP(C1, DL, VT); 5566 case ISD::FMUL: 5567 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5568 return getConstantFP(C1, DL, VT); 5569 case ISD::FDIV: 5570 C1.divide(C2, APFloat::rmNearestTiesToEven); 5571 return getConstantFP(C1, DL, VT); 5572 case ISD::FREM: 5573 C1.mod(C2); 5574 return getConstantFP(C1, DL, VT); 5575 case ISD::FCOPYSIGN: 5576 C1.copySign(C2); 5577 return getConstantFP(C1, DL, VT); 5578 case ISD::FMINNUM: 5579 return getConstantFP(minnum(C1, C2), DL, VT); 5580 case ISD::FMAXNUM: 5581 return getConstantFP(maxnum(C1, C2), DL, VT); 5582 case ISD::FMINIMUM: 5583 return getConstantFP(minimum(C1, C2), DL, VT); 5584 case ISD::FMAXIMUM: 5585 return getConstantFP(maximum(C1, C2), DL, VT); 5586 default: break; 5587 } 5588 } 5589 if (N1CFP && Opcode == ISD::FP_ROUND) { 5590 APFloat C1 = N1CFP->getValueAPF(); // make copy 5591 bool Unused; 5592 // This can return overflow, underflow, or inexact; we don't care. 5593 // FIXME need to be more flexible about rounding mode. 5594 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5595 &Unused); 5596 return getConstantFP(C1, DL, VT); 5597 } 5598 5599 switch (Opcode) { 5600 case ISD::FSUB: 5601 // -0.0 - undef --> undef (consistent with "fneg undef") 5602 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5603 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5604 return getUNDEF(VT); 5605 LLVM_FALLTHROUGH; 5606 5607 case ISD::FADD: 5608 case ISD::FMUL: 5609 case ISD::FDIV: 5610 case ISD::FREM: 5611 // If both operands are undef, the result is undef. If 1 operand is undef, 5612 // the result is NaN. This should match the behavior of the IR optimizer. 5613 if (N1.isUndef() && N2.isUndef()) 5614 return getUNDEF(VT); 5615 if (N1.isUndef() || N2.isUndef()) 5616 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5617 } 5618 return SDValue(); 5619 } 5620 5621 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5622 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5623 5624 // There's no need to assert on a byte-aligned pointer. All pointers are at 5625 // least byte aligned. 5626 if (A == Align(1)) 5627 return Val; 5628 5629 FoldingSetNodeID ID; 5630 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5631 ID.AddInteger(A.value()); 5632 5633 void *IP = nullptr; 5634 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5635 return SDValue(E, 0); 5636 5637 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5638 Val.getValueType(), A); 5639 createOperands(N, {Val}); 5640 5641 CSEMap.InsertNode(N, IP); 5642 InsertNode(N); 5643 5644 SDValue V(N, 0); 5645 NewSDValueDbgMsg(V, "Creating new node: ", this); 5646 return V; 5647 } 5648 5649 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5650 SDValue N1, SDValue N2) { 5651 SDNodeFlags Flags; 5652 if (Inserter) 5653 Flags = Inserter->getFlags(); 5654 return getNode(Opcode, DL, VT, N1, N2, Flags); 5655 } 5656 5657 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, 5658 SDValue &N2) const { 5659 if (!TLI->isCommutativeBinOp(Opcode)) 5660 return; 5661 5662 // Canonicalize: 5663 // binop(const, nonconst) -> binop(nonconst, const) 5664 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5665 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5666 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5667 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5668 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5669 std::swap(N1, N2); 5670 5671 // Canonicalize: 5672 // binop(splat(x), step_vector) -> binop(step_vector, splat(x)) 5673 else if (N1.getOpcode() == ISD::SPLAT_VECTOR && 5674 N2.getOpcode() == ISD::STEP_VECTOR) 5675 std::swap(N1, N2); 5676 } 5677 5678 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5679 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5680 assert(N1.getOpcode() != ISD::DELETED_NODE && 5681 N2.getOpcode() != ISD::DELETED_NODE && 5682 "Operand is DELETED_NODE!"); 5683 5684 canonicalizeCommutativeBinop(Opcode, N1, N2); 5685 5686 auto *N1C = dyn_cast<ConstantSDNode>(N1); 5687 auto *N2C = dyn_cast<ConstantSDNode>(N2); 5688 5689 // Don't allow undefs in vector splats - we might be returning N2 when folding 5690 // to zero etc. 5691 ConstantSDNode *N2CV = 5692 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true); 5693 5694 switch (Opcode) { 5695 default: break; 5696 case ISD::TokenFactor: 5697 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5698 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5699 // Fold trivial token factors. 5700 if (N1.getOpcode() == ISD::EntryToken) return N2; 5701 if (N2.getOpcode() == ISD::EntryToken) return N1; 5702 if (N1 == N2) return N1; 5703 break; 5704 case ISD::BUILD_VECTOR: { 5705 // Attempt to simplify BUILD_VECTOR. 5706 SDValue Ops[] = {N1, N2}; 5707 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5708 return V; 5709 break; 5710 } 5711 case ISD::CONCAT_VECTORS: { 5712 SDValue Ops[] = {N1, N2}; 5713 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5714 return V; 5715 break; 5716 } 5717 case ISD::AND: 5718 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5719 assert(N1.getValueType() == N2.getValueType() && 5720 N1.getValueType() == VT && "Binary operator types must match!"); 5721 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5722 // worth handling here. 5723 if (N2CV && N2CV->isZero()) 5724 return N2; 5725 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X 5726 return N1; 5727 break; 5728 case ISD::OR: 5729 case ISD::XOR: 5730 case ISD::ADD: 5731 case ISD::SUB: 5732 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5733 assert(N1.getValueType() == N2.getValueType() && 5734 N1.getValueType() == VT && "Binary operator types must match!"); 5735 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5736 // it's worth handling here. 5737 if (N2CV && N2CV->isZero()) 5738 return N1; 5739 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5740 VT.getVectorElementType() == MVT::i1) 5741 return getNode(ISD::XOR, DL, VT, N1, N2); 5742 break; 5743 case ISD::MUL: 5744 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5745 assert(N1.getValueType() == N2.getValueType() && 5746 N1.getValueType() == VT && "Binary operator types must match!"); 5747 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5748 return getNode(ISD::AND, DL, VT, N1, N2); 5749 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5750 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5751 const APInt &N2CImm = N2C->getAPIntValue(); 5752 return getVScale(DL, VT, MulImm * N2CImm); 5753 } 5754 break; 5755 case ISD::UDIV: 5756 case ISD::UREM: 5757 case ISD::MULHU: 5758 case ISD::MULHS: 5759 case ISD::SDIV: 5760 case ISD::SREM: 5761 case ISD::SADDSAT: 5762 case ISD::SSUBSAT: 5763 case ISD::UADDSAT: 5764 case ISD::USUBSAT: 5765 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5766 assert(N1.getValueType() == N2.getValueType() && 5767 N1.getValueType() == VT && "Binary operator types must match!"); 5768 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5769 // fold (add_sat x, y) -> (or x, y) for bool types. 5770 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5771 return getNode(ISD::OR, DL, VT, N1, N2); 5772 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5773 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5774 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5775 } 5776 break; 5777 case ISD::SMIN: 5778 case ISD::UMAX: 5779 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5780 assert(N1.getValueType() == N2.getValueType() && 5781 N1.getValueType() == VT && "Binary operator types must match!"); 5782 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5783 return getNode(ISD::OR, DL, VT, N1, N2); 5784 break; 5785 case ISD::SMAX: 5786 case ISD::UMIN: 5787 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5788 assert(N1.getValueType() == N2.getValueType() && 5789 N1.getValueType() == VT && "Binary operator types must match!"); 5790 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5791 return getNode(ISD::AND, DL, VT, N1, N2); 5792 break; 5793 case ISD::FADD: 5794 case ISD::FSUB: 5795 case ISD::FMUL: 5796 case ISD::FDIV: 5797 case ISD::FREM: 5798 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5799 assert(N1.getValueType() == N2.getValueType() && 5800 N1.getValueType() == VT && "Binary operator types must match!"); 5801 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5802 return V; 5803 break; 5804 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5805 assert(N1.getValueType() == VT && 5806 N1.getValueType().isFloatingPoint() && 5807 N2.getValueType().isFloatingPoint() && 5808 "Invalid FCOPYSIGN!"); 5809 break; 5810 case ISD::SHL: 5811 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5812 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5813 const APInt &ShiftImm = N2C->getAPIntValue(); 5814 return getVScale(DL, VT, MulImm << ShiftImm); 5815 } 5816 LLVM_FALLTHROUGH; 5817 case ISD::SRA: 5818 case ISD::SRL: 5819 if (SDValue V = simplifyShift(N1, N2)) 5820 return V; 5821 LLVM_FALLTHROUGH; 5822 case ISD::ROTL: 5823 case ISD::ROTR: 5824 assert(VT == N1.getValueType() && 5825 "Shift operators return type must be the same as their first arg"); 5826 assert(VT.isInteger() && N2.getValueType().isInteger() && 5827 "Shifts only work on integers"); 5828 assert((!VT.isVector() || VT == N2.getValueType()) && 5829 "Vector shift amounts must be in the same as their first arg"); 5830 // Verify that the shift amount VT is big enough to hold valid shift 5831 // amounts. This catches things like trying to shift an i1024 value by an 5832 // i8, which is easy to fall into in generic code that uses 5833 // TLI.getShiftAmount(). 5834 assert(N2.getValueType().getScalarSizeInBits() >= 5835 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5836 "Invalid use of small shift amount with oversized value!"); 5837 5838 // Always fold shifts of i1 values so the code generator doesn't need to 5839 // handle them. Since we know the size of the shift has to be less than the 5840 // size of the value, the shift/rotate count is guaranteed to be zero. 5841 if (VT == MVT::i1) 5842 return N1; 5843 if (N2CV && N2CV->isZero()) 5844 return N1; 5845 break; 5846 case ISD::FP_ROUND: 5847 assert(VT.isFloatingPoint() && 5848 N1.getValueType().isFloatingPoint() && 5849 VT.bitsLE(N1.getValueType()) && 5850 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5851 "Invalid FP_ROUND!"); 5852 if (N1.getValueType() == VT) return N1; // noop conversion. 5853 break; 5854 case ISD::AssertSext: 5855 case ISD::AssertZext: { 5856 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5857 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5858 assert(VT.isInteger() && EVT.isInteger() && 5859 "Cannot *_EXTEND_INREG FP types"); 5860 assert(!EVT.isVector() && 5861 "AssertSExt/AssertZExt type should be the vector element type " 5862 "rather than the vector type!"); 5863 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5864 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5865 break; 5866 } 5867 case ISD::SIGN_EXTEND_INREG: { 5868 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5869 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5870 assert(VT.isInteger() && EVT.isInteger() && 5871 "Cannot *_EXTEND_INREG FP types"); 5872 assert(EVT.isVector() == VT.isVector() && 5873 "SIGN_EXTEND_INREG type should be vector iff the operand " 5874 "type is vector!"); 5875 assert((!EVT.isVector() || 5876 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5877 "Vector element counts must match in SIGN_EXTEND_INREG"); 5878 assert(EVT.bitsLE(VT) && "Not extending!"); 5879 if (EVT == VT) return N1; // Not actually extending 5880 5881 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5882 unsigned FromBits = EVT.getScalarSizeInBits(); 5883 Val <<= Val.getBitWidth() - FromBits; 5884 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5885 return getConstant(Val, DL, ConstantVT); 5886 }; 5887 5888 if (N1C) { 5889 const APInt &Val = N1C->getAPIntValue(); 5890 return SignExtendInReg(Val, VT); 5891 } 5892 5893 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5894 SmallVector<SDValue, 8> Ops; 5895 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5896 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5897 SDValue Op = N1.getOperand(i); 5898 if (Op.isUndef()) { 5899 Ops.push_back(getUNDEF(OpVT)); 5900 continue; 5901 } 5902 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5903 APInt Val = C->getAPIntValue(); 5904 Ops.push_back(SignExtendInReg(Val, OpVT)); 5905 } 5906 return getBuildVector(VT, DL, Ops); 5907 } 5908 break; 5909 } 5910 case ISD::FP_TO_SINT_SAT: 5911 case ISD::FP_TO_UINT_SAT: { 5912 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 5913 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 5914 assert(N1.getValueType().isVector() == VT.isVector() && 5915 "FP_TO_*INT_SAT type should be vector iff the operand type is " 5916 "vector!"); 5917 assert((!VT.isVector() || VT.getVectorNumElements() == 5918 N1.getValueType().getVectorNumElements()) && 5919 "Vector element counts must match in FP_TO_*INT_SAT"); 5920 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 5921 "Type to saturate to must be a scalar."); 5922 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 5923 "Not extending!"); 5924 break; 5925 } 5926 case ISD::EXTRACT_VECTOR_ELT: 5927 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5928 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5929 element type of the vector."); 5930 5931 // Extract from an undefined value or using an undefined index is undefined. 5932 if (N1.isUndef() || N2.isUndef()) 5933 return getUNDEF(VT); 5934 5935 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5936 // vectors. For scalable vectors we will provide appropriate support for 5937 // dealing with arbitrary indices. 5938 if (N2C && N1.getValueType().isFixedLengthVector() && 5939 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5940 return getUNDEF(VT); 5941 5942 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5943 // expanding copies of large vectors from registers. This only works for 5944 // fixed length vectors, since we need to know the exact number of 5945 // elements. 5946 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5947 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5948 unsigned Factor = 5949 N1.getOperand(0).getValueType().getVectorNumElements(); 5950 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5951 N1.getOperand(N2C->getZExtValue() / Factor), 5952 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5953 } 5954 5955 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5956 // lowering is expanding large vector constants. 5957 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5958 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5959 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5960 N1.getValueType().isFixedLengthVector()) && 5961 "BUILD_VECTOR used for scalable vectors"); 5962 unsigned Index = 5963 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5964 SDValue Elt = N1.getOperand(Index); 5965 5966 if (VT != Elt.getValueType()) 5967 // If the vector element type is not legal, the BUILD_VECTOR operands 5968 // are promoted and implicitly truncated, and the result implicitly 5969 // extended. Make that explicit here. 5970 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5971 5972 return Elt; 5973 } 5974 5975 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5976 // operations are lowered to scalars. 5977 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5978 // If the indices are the same, return the inserted element else 5979 // if the indices are known different, extract the element from 5980 // the original vector. 5981 SDValue N1Op2 = N1.getOperand(2); 5982 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5983 5984 if (N1Op2C && N2C) { 5985 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5986 if (VT == N1.getOperand(1).getValueType()) 5987 return N1.getOperand(1); 5988 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5989 } 5990 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5991 } 5992 } 5993 5994 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5995 // when vector types are scalarized and v1iX is legal. 5996 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5997 // Here we are completely ignoring the extract element index (N2), 5998 // which is fine for fixed width vectors, since any index other than 0 5999 // is undefined anyway. However, this cannot be ignored for scalable 6000 // vectors - in theory we could support this, but we don't want to do this 6001 // without a profitability check. 6002 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6003 N1.getValueType().isFixedLengthVector() && 6004 N1.getValueType().getVectorNumElements() == 1) { 6005 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 6006 N1.getOperand(1)); 6007 } 6008 break; 6009 case ISD::EXTRACT_ELEMENT: 6010 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 6011 assert(!N1.getValueType().isVector() && !VT.isVector() && 6012 (N1.getValueType().isInteger() == VT.isInteger()) && 6013 N1.getValueType() != VT && 6014 "Wrong types for EXTRACT_ELEMENT!"); 6015 6016 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 6017 // 64-bit integers into 32-bit parts. Instead of building the extract of 6018 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 6019 if (N1.getOpcode() == ISD::BUILD_PAIR) 6020 return N1.getOperand(N2C->getZExtValue()); 6021 6022 // EXTRACT_ELEMENT of a constant int is also very common. 6023 if (N1C) { 6024 unsigned ElementSize = VT.getSizeInBits(); 6025 unsigned Shift = ElementSize * N2C->getZExtValue(); 6026 const APInt &Val = N1C->getAPIntValue(); 6027 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 6028 } 6029 break; 6030 case ISD::EXTRACT_SUBVECTOR: { 6031 EVT N1VT = N1.getValueType(); 6032 assert(VT.isVector() && N1VT.isVector() && 6033 "Extract subvector VTs must be vectors!"); 6034 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 6035 "Extract subvector VTs must have the same element type!"); 6036 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 6037 "Cannot extract a scalable vector from a fixed length vector!"); 6038 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6039 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 6040 "Extract subvector must be from larger vector to smaller vector!"); 6041 assert(N2C && "Extract subvector index must be a constant"); 6042 assert((VT.isScalableVector() != N1VT.isScalableVector() || 6043 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 6044 N1VT.getVectorMinNumElements()) && 6045 "Extract subvector overflow!"); 6046 assert(N2C->getAPIntValue().getBitWidth() == 6047 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6048 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6049 6050 // Trivial extraction. 6051 if (VT == N1VT) 6052 return N1; 6053 6054 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6055 if (N1.isUndef()) 6056 return getUNDEF(VT); 6057 6058 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6059 // the concat have the same type as the extract. 6060 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6061 VT == N1.getOperand(0).getValueType()) { 6062 unsigned Factor = VT.getVectorMinNumElements(); 6063 return N1.getOperand(N2C->getZExtValue() / Factor); 6064 } 6065 6066 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6067 // during shuffle legalization. 6068 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6069 VT == N1.getOperand(1).getValueType()) 6070 return N1.getOperand(1); 6071 break; 6072 } 6073 } 6074 6075 // Perform trivial constant folding. 6076 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6077 return SV; 6078 6079 // Canonicalize an UNDEF to the RHS, even over a constant. 6080 if (N1.isUndef()) { 6081 if (TLI->isCommutativeBinOp(Opcode)) { 6082 std::swap(N1, N2); 6083 } else { 6084 switch (Opcode) { 6085 case ISD::SIGN_EXTEND_INREG: 6086 case ISD::SUB: 6087 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6088 case ISD::UDIV: 6089 case ISD::SDIV: 6090 case ISD::UREM: 6091 case ISD::SREM: 6092 case ISD::SSUBSAT: 6093 case ISD::USUBSAT: 6094 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6095 } 6096 } 6097 } 6098 6099 // Fold a bunch of operators when the RHS is undef. 6100 if (N2.isUndef()) { 6101 switch (Opcode) { 6102 case ISD::XOR: 6103 if (N1.isUndef()) 6104 // Handle undef ^ undef -> 0 special case. This is a common 6105 // idiom (misuse). 6106 return getConstant(0, DL, VT); 6107 LLVM_FALLTHROUGH; 6108 case ISD::ADD: 6109 case ISD::SUB: 6110 case ISD::UDIV: 6111 case ISD::SDIV: 6112 case ISD::UREM: 6113 case ISD::SREM: 6114 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6115 case ISD::MUL: 6116 case ISD::AND: 6117 case ISD::SSUBSAT: 6118 case ISD::USUBSAT: 6119 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6120 case ISD::OR: 6121 case ISD::SADDSAT: 6122 case ISD::UADDSAT: 6123 return getAllOnesConstant(DL, VT); 6124 } 6125 } 6126 6127 // Memoize this node if possible. 6128 SDNode *N; 6129 SDVTList VTs = getVTList(VT); 6130 SDValue Ops[] = {N1, N2}; 6131 if (VT != MVT::Glue) { 6132 FoldingSetNodeID ID; 6133 AddNodeIDNode(ID, Opcode, VTs, Ops); 6134 void *IP = nullptr; 6135 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6136 E->intersectFlagsWith(Flags); 6137 return SDValue(E, 0); 6138 } 6139 6140 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6141 N->setFlags(Flags); 6142 createOperands(N, Ops); 6143 CSEMap.InsertNode(N, IP); 6144 } else { 6145 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6146 createOperands(N, Ops); 6147 } 6148 6149 InsertNode(N); 6150 SDValue V = SDValue(N, 0); 6151 NewSDValueDbgMsg(V, "Creating new node: ", this); 6152 return V; 6153 } 6154 6155 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6156 SDValue N1, SDValue N2, SDValue N3) { 6157 SDNodeFlags Flags; 6158 if (Inserter) 6159 Flags = Inserter->getFlags(); 6160 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6161 } 6162 6163 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6164 SDValue N1, SDValue N2, SDValue N3, 6165 const SDNodeFlags Flags) { 6166 assert(N1.getOpcode() != ISD::DELETED_NODE && 6167 N2.getOpcode() != ISD::DELETED_NODE && 6168 N3.getOpcode() != ISD::DELETED_NODE && 6169 "Operand is DELETED_NODE!"); 6170 // Perform various simplifications. 6171 switch (Opcode) { 6172 case ISD::FMA: { 6173 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6174 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6175 N3.getValueType() == VT && "FMA types must match!"); 6176 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6177 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6178 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6179 if (N1CFP && N2CFP && N3CFP) { 6180 APFloat V1 = N1CFP->getValueAPF(); 6181 const APFloat &V2 = N2CFP->getValueAPF(); 6182 const APFloat &V3 = N3CFP->getValueAPF(); 6183 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6184 return getConstantFP(V1, DL, VT); 6185 } 6186 break; 6187 } 6188 case ISD::BUILD_VECTOR: { 6189 // Attempt to simplify BUILD_VECTOR. 6190 SDValue Ops[] = {N1, N2, N3}; 6191 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6192 return V; 6193 break; 6194 } 6195 case ISD::CONCAT_VECTORS: { 6196 SDValue Ops[] = {N1, N2, N3}; 6197 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6198 return V; 6199 break; 6200 } 6201 case ISD::SETCC: { 6202 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6203 assert(N1.getValueType() == N2.getValueType() && 6204 "SETCC operands must have the same type!"); 6205 assert(VT.isVector() == N1.getValueType().isVector() && 6206 "SETCC type should be vector iff the operand type is vector!"); 6207 assert((!VT.isVector() || VT.getVectorElementCount() == 6208 N1.getValueType().getVectorElementCount()) && 6209 "SETCC vector element counts must match!"); 6210 // Use FoldSetCC to simplify SETCC's. 6211 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6212 return V; 6213 // Vector constant folding. 6214 SDValue Ops[] = {N1, N2, N3}; 6215 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6216 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6217 return V; 6218 } 6219 break; 6220 } 6221 case ISD::SELECT: 6222 case ISD::VSELECT: 6223 if (SDValue V = simplifySelect(N1, N2, N3)) 6224 return V; 6225 break; 6226 case ISD::VECTOR_SHUFFLE: 6227 llvm_unreachable("should use getVectorShuffle constructor!"); 6228 case ISD::VECTOR_SPLICE: { 6229 if (cast<ConstantSDNode>(N3)->isNullValue()) 6230 return N1; 6231 break; 6232 } 6233 case ISD::INSERT_VECTOR_ELT: { 6234 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6235 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6236 // for scalable vectors where we will generate appropriate code to 6237 // deal with out-of-bounds cases correctly. 6238 if (N3C && N1.getValueType().isFixedLengthVector() && 6239 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6240 return getUNDEF(VT); 6241 6242 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6243 if (N3.isUndef()) 6244 return getUNDEF(VT); 6245 6246 // If the inserted element is an UNDEF, just use the input vector. 6247 if (N2.isUndef()) 6248 return N1; 6249 6250 break; 6251 } 6252 case ISD::INSERT_SUBVECTOR: { 6253 // Inserting undef into undef is still undef. 6254 if (N1.isUndef() && N2.isUndef()) 6255 return getUNDEF(VT); 6256 6257 EVT N2VT = N2.getValueType(); 6258 assert(VT == N1.getValueType() && 6259 "Dest and insert subvector source types must match!"); 6260 assert(VT.isVector() && N2VT.isVector() && 6261 "Insert subvector VTs must be vectors!"); 6262 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6263 "Cannot insert a scalable vector into a fixed length vector!"); 6264 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6265 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6266 "Insert subvector must be from smaller vector to larger vector!"); 6267 assert(isa<ConstantSDNode>(N3) && 6268 "Insert subvector index must be constant"); 6269 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6270 (N2VT.getVectorMinNumElements() + 6271 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6272 VT.getVectorMinNumElements()) && 6273 "Insert subvector overflow!"); 6274 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6275 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6276 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6277 6278 // Trivial insertion. 6279 if (VT == N2VT) 6280 return N2; 6281 6282 // If this is an insert of an extracted vector into an undef vector, we 6283 // can just use the input to the extract. 6284 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6285 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6286 return N2.getOperand(0); 6287 break; 6288 } 6289 case ISD::BITCAST: 6290 // Fold bit_convert nodes from a type to themselves. 6291 if (N1.getValueType() == VT) 6292 return N1; 6293 break; 6294 } 6295 6296 // Memoize node if it doesn't produce a flag. 6297 SDNode *N; 6298 SDVTList VTs = getVTList(VT); 6299 SDValue Ops[] = {N1, N2, N3}; 6300 if (VT != MVT::Glue) { 6301 FoldingSetNodeID ID; 6302 AddNodeIDNode(ID, Opcode, VTs, Ops); 6303 void *IP = nullptr; 6304 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6305 E->intersectFlagsWith(Flags); 6306 return SDValue(E, 0); 6307 } 6308 6309 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6310 N->setFlags(Flags); 6311 createOperands(N, Ops); 6312 CSEMap.InsertNode(N, IP); 6313 } else { 6314 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6315 createOperands(N, Ops); 6316 } 6317 6318 InsertNode(N); 6319 SDValue V = SDValue(N, 0); 6320 NewSDValueDbgMsg(V, "Creating new node: ", this); 6321 return V; 6322 } 6323 6324 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6325 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6326 SDValue Ops[] = { N1, N2, N3, N4 }; 6327 return getNode(Opcode, DL, VT, Ops); 6328 } 6329 6330 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6331 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6332 SDValue N5) { 6333 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6334 return getNode(Opcode, DL, VT, Ops); 6335 } 6336 6337 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6338 /// the incoming stack arguments to be loaded from the stack. 6339 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6340 SmallVector<SDValue, 8> ArgChains; 6341 6342 // Include the original chain at the beginning of the list. When this is 6343 // used by target LowerCall hooks, this helps legalize find the 6344 // CALLSEQ_BEGIN node. 6345 ArgChains.push_back(Chain); 6346 6347 // Add a chain value for each stack argument. 6348 for (SDNode *U : getEntryNode().getNode()->uses()) 6349 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6350 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6351 if (FI->getIndex() < 0) 6352 ArgChains.push_back(SDValue(L, 1)); 6353 6354 // Build a tokenfactor for all the chains. 6355 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6356 } 6357 6358 /// getMemsetValue - Vectorized representation of the memset value 6359 /// operand. 6360 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6361 const SDLoc &dl) { 6362 assert(!Value.isUndef()); 6363 6364 unsigned NumBits = VT.getScalarSizeInBits(); 6365 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6366 assert(C->getAPIntValue().getBitWidth() == 8); 6367 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6368 if (VT.isInteger()) { 6369 bool IsOpaque = VT.getSizeInBits() > 64 || 6370 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6371 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6372 } 6373 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6374 VT); 6375 } 6376 6377 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6378 EVT IntVT = VT.getScalarType(); 6379 if (!IntVT.isInteger()) 6380 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6381 6382 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6383 if (NumBits > 8) { 6384 // Use a multiplication with 0x010101... to extend the input to the 6385 // required length. 6386 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6387 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6388 DAG.getConstant(Magic, dl, IntVT)); 6389 } 6390 6391 if (VT != Value.getValueType() && !VT.isInteger()) 6392 Value = DAG.getBitcast(VT.getScalarType(), Value); 6393 if (VT != Value.getValueType()) 6394 Value = DAG.getSplatBuildVector(VT, dl, Value); 6395 6396 return Value; 6397 } 6398 6399 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6400 /// used when a memcpy is turned into a memset when the source is a constant 6401 /// string ptr. 6402 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6403 const TargetLowering &TLI, 6404 const ConstantDataArraySlice &Slice) { 6405 // Handle vector with all elements zero. 6406 if (Slice.Array == nullptr) { 6407 if (VT.isInteger()) 6408 return DAG.getConstant(0, dl, VT); 6409 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6410 return DAG.getConstantFP(0.0, dl, VT); 6411 if (VT.isVector()) { 6412 unsigned NumElts = VT.getVectorNumElements(); 6413 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6414 return DAG.getNode(ISD::BITCAST, dl, VT, 6415 DAG.getConstant(0, dl, 6416 EVT::getVectorVT(*DAG.getContext(), 6417 EltVT, NumElts))); 6418 } 6419 llvm_unreachable("Expected type!"); 6420 } 6421 6422 assert(!VT.isVector() && "Can't handle vector type here!"); 6423 unsigned NumVTBits = VT.getSizeInBits(); 6424 unsigned NumVTBytes = NumVTBits / 8; 6425 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6426 6427 APInt Val(NumVTBits, 0); 6428 if (DAG.getDataLayout().isLittleEndian()) { 6429 for (unsigned i = 0; i != NumBytes; ++i) 6430 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6431 } else { 6432 for (unsigned i = 0; i != NumBytes; ++i) 6433 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6434 } 6435 6436 // If the "cost" of materializing the integer immediate is less than the cost 6437 // of a load, then it is cost effective to turn the load into the immediate. 6438 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6439 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6440 return DAG.getConstant(Val, dl, VT); 6441 return SDValue(); 6442 } 6443 6444 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6445 const SDLoc &DL, 6446 const SDNodeFlags Flags) { 6447 EVT VT = Base.getValueType(); 6448 SDValue Index; 6449 6450 if (Offset.isScalable()) 6451 Index = getVScale(DL, Base.getValueType(), 6452 APInt(Base.getValueSizeInBits().getFixedSize(), 6453 Offset.getKnownMinSize())); 6454 else 6455 Index = getConstant(Offset.getFixedSize(), DL, VT); 6456 6457 return getMemBasePlusOffset(Base, Index, DL, Flags); 6458 } 6459 6460 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6461 const SDLoc &DL, 6462 const SDNodeFlags Flags) { 6463 assert(Offset.getValueType().isInteger()); 6464 EVT BasePtrVT = Ptr.getValueType(); 6465 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6466 } 6467 6468 /// Returns true if memcpy source is constant data. 6469 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6470 uint64_t SrcDelta = 0; 6471 GlobalAddressSDNode *G = nullptr; 6472 if (Src.getOpcode() == ISD::GlobalAddress) 6473 G = cast<GlobalAddressSDNode>(Src); 6474 else if (Src.getOpcode() == ISD::ADD && 6475 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6476 Src.getOperand(1).getOpcode() == ISD::Constant) { 6477 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6478 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6479 } 6480 if (!G) 6481 return false; 6482 6483 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6484 SrcDelta + G->getOffset()); 6485 } 6486 6487 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6488 SelectionDAG &DAG) { 6489 // On Darwin, -Os means optimize for size without hurting performance, so 6490 // only really optimize for size when -Oz (MinSize) is used. 6491 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6492 return MF.getFunction().hasMinSize(); 6493 return DAG.shouldOptForSize(); 6494 } 6495 6496 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6497 SmallVector<SDValue, 32> &OutChains, unsigned From, 6498 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6499 SmallVector<SDValue, 16> &OutStoreChains) { 6500 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6501 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6502 SmallVector<SDValue, 16> GluedLoadChains; 6503 for (unsigned i = From; i < To; ++i) { 6504 OutChains.push_back(OutLoadChains[i]); 6505 GluedLoadChains.push_back(OutLoadChains[i]); 6506 } 6507 6508 // Chain for all loads. 6509 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6510 GluedLoadChains); 6511 6512 for (unsigned i = From; i < To; ++i) { 6513 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6514 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6515 ST->getBasePtr(), ST->getMemoryVT(), 6516 ST->getMemOperand()); 6517 OutChains.push_back(NewStore); 6518 } 6519 } 6520 6521 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6522 SDValue Chain, SDValue Dst, SDValue Src, 6523 uint64_t Size, Align Alignment, 6524 bool isVol, bool AlwaysInline, 6525 MachinePointerInfo DstPtrInfo, 6526 MachinePointerInfo SrcPtrInfo, 6527 const AAMDNodes &AAInfo) { 6528 // Turn a memcpy of undef to nop. 6529 // FIXME: We need to honor volatile even is Src is undef. 6530 if (Src.isUndef()) 6531 return Chain; 6532 6533 // Expand memcpy to a series of load and store ops if the size operand falls 6534 // below a certain threshold. 6535 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6536 // rather than maybe a humongous number of loads and stores. 6537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6538 const DataLayout &DL = DAG.getDataLayout(); 6539 LLVMContext &C = *DAG.getContext(); 6540 std::vector<EVT> MemOps; 6541 bool DstAlignCanChange = false; 6542 MachineFunction &MF = DAG.getMachineFunction(); 6543 MachineFrameInfo &MFI = MF.getFrameInfo(); 6544 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6545 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6546 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6547 DstAlignCanChange = true; 6548 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6549 if (!SrcAlign || Alignment > *SrcAlign) 6550 SrcAlign = Alignment; 6551 assert(SrcAlign && "SrcAlign must be set"); 6552 ConstantDataArraySlice Slice; 6553 // If marked as volatile, perform a copy even when marked as constant. 6554 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6555 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6556 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6557 const MemOp Op = isZeroConstant 6558 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6559 /*IsZeroMemset*/ true, isVol) 6560 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6561 *SrcAlign, isVol, CopyFromConstant); 6562 if (!TLI.findOptimalMemOpLowering( 6563 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6564 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6565 return SDValue(); 6566 6567 if (DstAlignCanChange) { 6568 Type *Ty = MemOps[0].getTypeForEVT(C); 6569 Align NewAlign = DL.getABITypeAlign(Ty); 6570 6571 // Don't promote to an alignment that would require dynamic stack 6572 // realignment. 6573 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6574 if (!TRI->hasStackRealignment(MF)) 6575 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6576 NewAlign = NewAlign / 2; 6577 6578 if (NewAlign > Alignment) { 6579 // Give the stack frame object a larger alignment if needed. 6580 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6581 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6582 Alignment = NewAlign; 6583 } 6584 } 6585 6586 // Prepare AAInfo for loads/stores after lowering this memcpy. 6587 AAMDNodes NewAAInfo = AAInfo; 6588 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6589 6590 MachineMemOperand::Flags MMOFlags = 6591 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6592 SmallVector<SDValue, 16> OutLoadChains; 6593 SmallVector<SDValue, 16> OutStoreChains; 6594 SmallVector<SDValue, 32> OutChains; 6595 unsigned NumMemOps = MemOps.size(); 6596 uint64_t SrcOff = 0, DstOff = 0; 6597 for (unsigned i = 0; i != NumMemOps; ++i) { 6598 EVT VT = MemOps[i]; 6599 unsigned VTSize = VT.getSizeInBits() / 8; 6600 SDValue Value, Store; 6601 6602 if (VTSize > Size) { 6603 // Issuing an unaligned load / store pair that overlaps with the previous 6604 // pair. Adjust the offset accordingly. 6605 assert(i == NumMemOps-1 && i != 0); 6606 SrcOff -= VTSize - Size; 6607 DstOff -= VTSize - Size; 6608 } 6609 6610 if (CopyFromConstant && 6611 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6612 // It's unlikely a store of a vector immediate can be done in a single 6613 // instruction. It would require a load from a constantpool first. 6614 // We only handle zero vectors here. 6615 // FIXME: Handle other cases where store of vector immediate is done in 6616 // a single instruction. 6617 ConstantDataArraySlice SubSlice; 6618 if (SrcOff < Slice.Length) { 6619 SubSlice = Slice; 6620 SubSlice.move(SrcOff); 6621 } else { 6622 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6623 SubSlice.Array = nullptr; 6624 SubSlice.Offset = 0; 6625 SubSlice.Length = VTSize; 6626 } 6627 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6628 if (Value.getNode()) { 6629 Store = DAG.getStore( 6630 Chain, dl, Value, 6631 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6632 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6633 OutChains.push_back(Store); 6634 } 6635 } 6636 6637 if (!Store.getNode()) { 6638 // The type might not be legal for the target. This should only happen 6639 // if the type is smaller than a legal type, as on PPC, so the right 6640 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6641 // to Load/Store if NVT==VT. 6642 // FIXME does the case above also need this? 6643 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6644 assert(NVT.bitsGE(VT)); 6645 6646 bool isDereferenceable = 6647 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6648 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6649 if (isDereferenceable) 6650 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6651 6652 Value = DAG.getExtLoad( 6653 ISD::EXTLOAD, dl, NVT, Chain, 6654 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6655 SrcPtrInfo.getWithOffset(SrcOff), VT, 6656 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6657 OutLoadChains.push_back(Value.getValue(1)); 6658 6659 Store = DAG.getTruncStore( 6660 Chain, dl, Value, 6661 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6662 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6663 OutStoreChains.push_back(Store); 6664 } 6665 SrcOff += VTSize; 6666 DstOff += VTSize; 6667 Size -= VTSize; 6668 } 6669 6670 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6671 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6672 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6673 6674 if (NumLdStInMemcpy) { 6675 // It may be that memcpy might be converted to memset if it's memcpy 6676 // of constants. In such a case, we won't have loads and stores, but 6677 // just stores. In the absence of loads, there is nothing to gang up. 6678 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6679 // If target does not care, just leave as it. 6680 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6681 OutChains.push_back(OutLoadChains[i]); 6682 OutChains.push_back(OutStoreChains[i]); 6683 } 6684 } else { 6685 // Ld/St less than/equal limit set by target. 6686 if (NumLdStInMemcpy <= GluedLdStLimit) { 6687 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6688 NumLdStInMemcpy, OutLoadChains, 6689 OutStoreChains); 6690 } else { 6691 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6692 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6693 unsigned GlueIter = 0; 6694 6695 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6696 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6697 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6698 6699 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6700 OutLoadChains, OutStoreChains); 6701 GlueIter += GluedLdStLimit; 6702 } 6703 6704 // Residual ld/st. 6705 if (RemainingLdStInMemcpy) { 6706 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6707 RemainingLdStInMemcpy, OutLoadChains, 6708 OutStoreChains); 6709 } 6710 } 6711 } 6712 } 6713 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6714 } 6715 6716 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6717 SDValue Chain, SDValue Dst, SDValue Src, 6718 uint64_t Size, Align Alignment, 6719 bool isVol, bool AlwaysInline, 6720 MachinePointerInfo DstPtrInfo, 6721 MachinePointerInfo SrcPtrInfo, 6722 const AAMDNodes &AAInfo) { 6723 // Turn a memmove of undef to nop. 6724 // FIXME: We need to honor volatile even is Src is undef. 6725 if (Src.isUndef()) 6726 return Chain; 6727 6728 // Expand memmove to a series of load and store ops if the size operand falls 6729 // below a certain threshold. 6730 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6731 const DataLayout &DL = DAG.getDataLayout(); 6732 LLVMContext &C = *DAG.getContext(); 6733 std::vector<EVT> MemOps; 6734 bool DstAlignCanChange = false; 6735 MachineFunction &MF = DAG.getMachineFunction(); 6736 MachineFrameInfo &MFI = MF.getFrameInfo(); 6737 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6738 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6739 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6740 DstAlignCanChange = true; 6741 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6742 if (!SrcAlign || Alignment > *SrcAlign) 6743 SrcAlign = Alignment; 6744 assert(SrcAlign && "SrcAlign must be set"); 6745 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6746 if (!TLI.findOptimalMemOpLowering( 6747 MemOps, Limit, 6748 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6749 /*IsVolatile*/ true), 6750 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6751 MF.getFunction().getAttributes())) 6752 return SDValue(); 6753 6754 if (DstAlignCanChange) { 6755 Type *Ty = MemOps[0].getTypeForEVT(C); 6756 Align NewAlign = DL.getABITypeAlign(Ty); 6757 if (NewAlign > Alignment) { 6758 // Give the stack frame object a larger alignment if needed. 6759 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6760 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6761 Alignment = NewAlign; 6762 } 6763 } 6764 6765 // Prepare AAInfo for loads/stores after lowering this memmove. 6766 AAMDNodes NewAAInfo = AAInfo; 6767 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6768 6769 MachineMemOperand::Flags MMOFlags = 6770 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6771 uint64_t SrcOff = 0, DstOff = 0; 6772 SmallVector<SDValue, 8> LoadValues; 6773 SmallVector<SDValue, 8> LoadChains; 6774 SmallVector<SDValue, 8> OutChains; 6775 unsigned NumMemOps = MemOps.size(); 6776 for (unsigned i = 0; i < NumMemOps; i++) { 6777 EVT VT = MemOps[i]; 6778 unsigned VTSize = VT.getSizeInBits() / 8; 6779 SDValue Value; 6780 6781 bool isDereferenceable = 6782 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6783 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6784 if (isDereferenceable) 6785 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6786 6787 Value = DAG.getLoad( 6788 VT, dl, Chain, 6789 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6790 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6791 LoadValues.push_back(Value); 6792 LoadChains.push_back(Value.getValue(1)); 6793 SrcOff += VTSize; 6794 } 6795 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6796 OutChains.clear(); 6797 for (unsigned i = 0; i < NumMemOps; i++) { 6798 EVT VT = MemOps[i]; 6799 unsigned VTSize = VT.getSizeInBits() / 8; 6800 SDValue Store; 6801 6802 Store = DAG.getStore( 6803 Chain, dl, LoadValues[i], 6804 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6805 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6806 OutChains.push_back(Store); 6807 DstOff += VTSize; 6808 } 6809 6810 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6811 } 6812 6813 /// Lower the call to 'memset' intrinsic function into a series of store 6814 /// operations. 6815 /// 6816 /// \param DAG Selection DAG where lowered code is placed. 6817 /// \param dl Link to corresponding IR location. 6818 /// \param Chain Control flow dependency. 6819 /// \param Dst Pointer to destination memory location. 6820 /// \param Src Value of byte to write into the memory. 6821 /// \param Size Number of bytes to write. 6822 /// \param Alignment Alignment of the destination in bytes. 6823 /// \param isVol True if destination is volatile. 6824 /// \param DstPtrInfo IR information on the memory pointer. 6825 /// \returns New head in the control flow, if lowering was successful, empty 6826 /// SDValue otherwise. 6827 /// 6828 /// The function tries to replace 'llvm.memset' intrinsic with several store 6829 /// operations and value calculation code. This is usually profitable for small 6830 /// memory size. 6831 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6832 SDValue Chain, SDValue Dst, SDValue Src, 6833 uint64_t Size, Align Alignment, bool isVol, 6834 MachinePointerInfo DstPtrInfo, 6835 const AAMDNodes &AAInfo) { 6836 // Turn a memset of undef to nop. 6837 // FIXME: We need to honor volatile even is Src is undef. 6838 if (Src.isUndef()) 6839 return Chain; 6840 6841 // Expand memset to a series of load/store ops if the size operand 6842 // falls below a certain threshold. 6843 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6844 std::vector<EVT> MemOps; 6845 bool DstAlignCanChange = false; 6846 MachineFunction &MF = DAG.getMachineFunction(); 6847 MachineFrameInfo &MFI = MF.getFrameInfo(); 6848 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6849 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6850 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6851 DstAlignCanChange = true; 6852 bool IsZeroVal = 6853 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6854 if (!TLI.findOptimalMemOpLowering( 6855 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6856 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6857 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6858 return SDValue(); 6859 6860 if (DstAlignCanChange) { 6861 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6862 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6863 if (NewAlign > Alignment) { 6864 // Give the stack frame object a larger alignment if needed. 6865 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6866 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6867 Alignment = NewAlign; 6868 } 6869 } 6870 6871 SmallVector<SDValue, 8> OutChains; 6872 uint64_t DstOff = 0; 6873 unsigned NumMemOps = MemOps.size(); 6874 6875 // Find the largest store and generate the bit pattern for it. 6876 EVT LargestVT = MemOps[0]; 6877 for (unsigned i = 1; i < NumMemOps; i++) 6878 if (MemOps[i].bitsGT(LargestVT)) 6879 LargestVT = MemOps[i]; 6880 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6881 6882 // Prepare AAInfo for loads/stores after lowering this memset. 6883 AAMDNodes NewAAInfo = AAInfo; 6884 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6885 6886 for (unsigned i = 0; i < NumMemOps; i++) { 6887 EVT VT = MemOps[i]; 6888 unsigned VTSize = VT.getSizeInBits() / 8; 6889 if (VTSize > Size) { 6890 // Issuing an unaligned load / store pair that overlaps with the previous 6891 // pair. Adjust the offset accordingly. 6892 assert(i == NumMemOps-1 && i != 0); 6893 DstOff -= VTSize - Size; 6894 } 6895 6896 // If this store is smaller than the largest store see whether we can get 6897 // the smaller value for free with a truncate. 6898 SDValue Value = MemSetValue; 6899 if (VT.bitsLT(LargestVT)) { 6900 if (!LargestVT.isVector() && !VT.isVector() && 6901 TLI.isTruncateFree(LargestVT, VT)) 6902 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6903 else 6904 Value = getMemsetValue(Src, VT, DAG, dl); 6905 } 6906 assert(Value.getValueType() == VT && "Value with wrong type."); 6907 SDValue Store = DAG.getStore( 6908 Chain, dl, Value, 6909 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6910 DstPtrInfo.getWithOffset(DstOff), Alignment, 6911 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 6912 NewAAInfo); 6913 OutChains.push_back(Store); 6914 DstOff += VT.getSizeInBits() / 8; 6915 Size -= VTSize; 6916 } 6917 6918 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6919 } 6920 6921 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6922 unsigned AS) { 6923 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6924 // pointer operands can be losslessly bitcasted to pointers of address space 0 6925 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6926 report_fatal_error("cannot lower memory intrinsic in address space " + 6927 Twine(AS)); 6928 } 6929 } 6930 6931 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6932 SDValue Src, SDValue Size, Align Alignment, 6933 bool isVol, bool AlwaysInline, bool isTailCall, 6934 MachinePointerInfo DstPtrInfo, 6935 MachinePointerInfo SrcPtrInfo, 6936 const AAMDNodes &AAInfo) { 6937 // Check to see if we should lower the memcpy to loads and stores first. 6938 // For cases within the target-specified limits, this is the best choice. 6939 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6940 if (ConstantSize) { 6941 // Memcpy with size zero? Just return the original chain. 6942 if (ConstantSize->isZero()) 6943 return Chain; 6944 6945 SDValue Result = getMemcpyLoadsAndStores( 6946 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6947 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6948 if (Result.getNode()) 6949 return Result; 6950 } 6951 6952 // Then check to see if we should lower the memcpy with target-specific 6953 // code. If the target chooses to do this, this is the next best. 6954 if (TSI) { 6955 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6956 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6957 DstPtrInfo, SrcPtrInfo); 6958 if (Result.getNode()) 6959 return Result; 6960 } 6961 6962 // If we really need inline code and the target declined to provide it, 6963 // use a (potentially long) sequence of loads and stores. 6964 if (AlwaysInline) { 6965 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6966 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6967 ConstantSize->getZExtValue(), Alignment, 6968 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 6969 } 6970 6971 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6972 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6973 6974 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6975 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6976 // respect volatile, so they may do things like read or write memory 6977 // beyond the given memory regions. But fixing this isn't easy, and most 6978 // people don't care. 6979 6980 // Emit a library call. 6981 TargetLowering::ArgListTy Args; 6982 TargetLowering::ArgListEntry Entry; 6983 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6984 Entry.Node = Dst; Args.push_back(Entry); 6985 Entry.Node = Src; Args.push_back(Entry); 6986 6987 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6988 Entry.Node = Size; Args.push_back(Entry); 6989 // FIXME: pass in SDLoc 6990 TargetLowering::CallLoweringInfo CLI(*this); 6991 CLI.setDebugLoc(dl) 6992 .setChain(Chain) 6993 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6994 Dst.getValueType().getTypeForEVT(*getContext()), 6995 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6996 TLI->getPointerTy(getDataLayout())), 6997 std::move(Args)) 6998 .setDiscardResult() 6999 .setTailCall(isTailCall); 7000 7001 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7002 return CallResult.second; 7003 } 7004 7005 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 7006 SDValue Dst, unsigned DstAlign, 7007 SDValue Src, unsigned SrcAlign, 7008 SDValue Size, Type *SizeTy, 7009 unsigned ElemSz, bool isTailCall, 7010 MachinePointerInfo DstPtrInfo, 7011 MachinePointerInfo SrcPtrInfo) { 7012 // Emit a library call. 7013 TargetLowering::ArgListTy Args; 7014 TargetLowering::ArgListEntry Entry; 7015 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7016 Entry.Node = Dst; 7017 Args.push_back(Entry); 7018 7019 Entry.Node = Src; 7020 Args.push_back(Entry); 7021 7022 Entry.Ty = SizeTy; 7023 Entry.Node = Size; 7024 Args.push_back(Entry); 7025 7026 RTLIB::Libcall LibraryCall = 7027 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7028 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7029 report_fatal_error("Unsupported element size"); 7030 7031 TargetLowering::CallLoweringInfo CLI(*this); 7032 CLI.setDebugLoc(dl) 7033 .setChain(Chain) 7034 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7035 Type::getVoidTy(*getContext()), 7036 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7037 TLI->getPointerTy(getDataLayout())), 7038 std::move(Args)) 7039 .setDiscardResult() 7040 .setTailCall(isTailCall); 7041 7042 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7043 return CallResult.second; 7044 } 7045 7046 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 7047 SDValue Src, SDValue Size, Align Alignment, 7048 bool isVol, bool isTailCall, 7049 MachinePointerInfo DstPtrInfo, 7050 MachinePointerInfo SrcPtrInfo, 7051 const AAMDNodes &AAInfo) { 7052 // Check to see if we should lower the memmove to loads and stores first. 7053 // For cases within the target-specified limits, this is the best choice. 7054 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7055 if (ConstantSize) { 7056 // Memmove with size zero? Just return the original chain. 7057 if (ConstantSize->isZero()) 7058 return Chain; 7059 7060 SDValue Result = getMemmoveLoadsAndStores( 7061 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7062 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7063 if (Result.getNode()) 7064 return Result; 7065 } 7066 7067 // Then check to see if we should lower the memmove with target-specific 7068 // code. If the target chooses to do this, this is the next best. 7069 if (TSI) { 7070 SDValue Result = 7071 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7072 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7073 if (Result.getNode()) 7074 return Result; 7075 } 7076 7077 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7078 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7079 7080 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7081 // not be safe. See memcpy above for more details. 7082 7083 // Emit a library call. 7084 TargetLowering::ArgListTy Args; 7085 TargetLowering::ArgListEntry Entry; 7086 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7087 Entry.Node = Dst; Args.push_back(Entry); 7088 Entry.Node = Src; Args.push_back(Entry); 7089 7090 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7091 Entry.Node = Size; Args.push_back(Entry); 7092 // FIXME: pass in SDLoc 7093 TargetLowering::CallLoweringInfo CLI(*this); 7094 CLI.setDebugLoc(dl) 7095 .setChain(Chain) 7096 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7097 Dst.getValueType().getTypeForEVT(*getContext()), 7098 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7099 TLI->getPointerTy(getDataLayout())), 7100 std::move(Args)) 7101 .setDiscardResult() 7102 .setTailCall(isTailCall); 7103 7104 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7105 return CallResult.second; 7106 } 7107 7108 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7109 SDValue Dst, unsigned DstAlign, 7110 SDValue Src, unsigned SrcAlign, 7111 SDValue Size, Type *SizeTy, 7112 unsigned ElemSz, bool isTailCall, 7113 MachinePointerInfo DstPtrInfo, 7114 MachinePointerInfo SrcPtrInfo) { 7115 // Emit a library call. 7116 TargetLowering::ArgListTy Args; 7117 TargetLowering::ArgListEntry Entry; 7118 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7119 Entry.Node = Dst; 7120 Args.push_back(Entry); 7121 7122 Entry.Node = Src; 7123 Args.push_back(Entry); 7124 7125 Entry.Ty = SizeTy; 7126 Entry.Node = Size; 7127 Args.push_back(Entry); 7128 7129 RTLIB::Libcall LibraryCall = 7130 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7131 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7132 report_fatal_error("Unsupported element size"); 7133 7134 TargetLowering::CallLoweringInfo CLI(*this); 7135 CLI.setDebugLoc(dl) 7136 .setChain(Chain) 7137 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7138 Type::getVoidTy(*getContext()), 7139 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7140 TLI->getPointerTy(getDataLayout())), 7141 std::move(Args)) 7142 .setDiscardResult() 7143 .setTailCall(isTailCall); 7144 7145 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7146 return CallResult.second; 7147 } 7148 7149 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7150 SDValue Src, SDValue Size, Align Alignment, 7151 bool isVol, bool isTailCall, 7152 MachinePointerInfo DstPtrInfo, 7153 const AAMDNodes &AAInfo) { 7154 // Check to see if we should lower the memset to stores first. 7155 // For cases within the target-specified limits, this is the best choice. 7156 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7157 if (ConstantSize) { 7158 // Memset with size zero? Just return the original chain. 7159 if (ConstantSize->isZero()) 7160 return Chain; 7161 7162 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7163 ConstantSize->getZExtValue(), Alignment, 7164 isVol, DstPtrInfo, AAInfo); 7165 7166 if (Result.getNode()) 7167 return Result; 7168 } 7169 7170 // Then check to see if we should lower the memset with target-specific 7171 // code. If the target chooses to do this, this is the next best. 7172 if (TSI) { 7173 SDValue Result = TSI->EmitTargetCodeForMemset( 7174 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7175 if (Result.getNode()) 7176 return Result; 7177 } 7178 7179 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7180 7181 // Emit a library call. 7182 TargetLowering::ArgListTy Args; 7183 TargetLowering::ArgListEntry Entry; 7184 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7185 Args.push_back(Entry); 7186 Entry.Node = Src; 7187 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7188 Args.push_back(Entry); 7189 Entry.Node = Size; 7190 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7191 Args.push_back(Entry); 7192 7193 // FIXME: pass in SDLoc 7194 TargetLowering::CallLoweringInfo CLI(*this); 7195 CLI.setDebugLoc(dl) 7196 .setChain(Chain) 7197 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7198 Dst.getValueType().getTypeForEVT(*getContext()), 7199 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7200 TLI->getPointerTy(getDataLayout())), 7201 std::move(Args)) 7202 .setDiscardResult() 7203 .setTailCall(isTailCall); 7204 7205 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7206 return CallResult.second; 7207 } 7208 7209 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7210 SDValue Dst, unsigned DstAlign, 7211 SDValue Value, SDValue Size, Type *SizeTy, 7212 unsigned ElemSz, bool isTailCall, 7213 MachinePointerInfo DstPtrInfo) { 7214 // Emit a library call. 7215 TargetLowering::ArgListTy Args; 7216 TargetLowering::ArgListEntry Entry; 7217 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7218 Entry.Node = Dst; 7219 Args.push_back(Entry); 7220 7221 Entry.Ty = Type::getInt8Ty(*getContext()); 7222 Entry.Node = Value; 7223 Args.push_back(Entry); 7224 7225 Entry.Ty = SizeTy; 7226 Entry.Node = Size; 7227 Args.push_back(Entry); 7228 7229 RTLIB::Libcall LibraryCall = 7230 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7231 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7232 report_fatal_error("Unsupported element size"); 7233 7234 TargetLowering::CallLoweringInfo CLI(*this); 7235 CLI.setDebugLoc(dl) 7236 .setChain(Chain) 7237 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7238 Type::getVoidTy(*getContext()), 7239 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7240 TLI->getPointerTy(getDataLayout())), 7241 std::move(Args)) 7242 .setDiscardResult() 7243 .setTailCall(isTailCall); 7244 7245 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7246 return CallResult.second; 7247 } 7248 7249 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7250 SDVTList VTList, ArrayRef<SDValue> Ops, 7251 MachineMemOperand *MMO) { 7252 FoldingSetNodeID ID; 7253 ID.AddInteger(MemVT.getRawBits()); 7254 AddNodeIDNode(ID, Opcode, VTList, Ops); 7255 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7256 void* IP = nullptr; 7257 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7258 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7259 return SDValue(E, 0); 7260 } 7261 7262 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7263 VTList, MemVT, MMO); 7264 createOperands(N, Ops); 7265 7266 CSEMap.InsertNode(N, IP); 7267 InsertNode(N); 7268 return SDValue(N, 0); 7269 } 7270 7271 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7272 EVT MemVT, SDVTList VTs, SDValue Chain, 7273 SDValue Ptr, SDValue Cmp, SDValue Swp, 7274 MachineMemOperand *MMO) { 7275 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7276 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7277 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7278 7279 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7280 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7281 } 7282 7283 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7284 SDValue Chain, SDValue Ptr, SDValue Val, 7285 MachineMemOperand *MMO) { 7286 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7287 Opcode == ISD::ATOMIC_LOAD_SUB || 7288 Opcode == ISD::ATOMIC_LOAD_AND || 7289 Opcode == ISD::ATOMIC_LOAD_CLR || 7290 Opcode == ISD::ATOMIC_LOAD_OR || 7291 Opcode == ISD::ATOMIC_LOAD_XOR || 7292 Opcode == ISD::ATOMIC_LOAD_NAND || 7293 Opcode == ISD::ATOMIC_LOAD_MIN || 7294 Opcode == ISD::ATOMIC_LOAD_MAX || 7295 Opcode == ISD::ATOMIC_LOAD_UMIN || 7296 Opcode == ISD::ATOMIC_LOAD_UMAX || 7297 Opcode == ISD::ATOMIC_LOAD_FADD || 7298 Opcode == ISD::ATOMIC_LOAD_FSUB || 7299 Opcode == ISD::ATOMIC_SWAP || 7300 Opcode == ISD::ATOMIC_STORE) && 7301 "Invalid Atomic Op"); 7302 7303 EVT VT = Val.getValueType(); 7304 7305 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7306 getVTList(VT, MVT::Other); 7307 SDValue Ops[] = {Chain, Ptr, Val}; 7308 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7309 } 7310 7311 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7312 EVT VT, SDValue Chain, SDValue Ptr, 7313 MachineMemOperand *MMO) { 7314 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7315 7316 SDVTList VTs = getVTList(VT, MVT::Other); 7317 SDValue Ops[] = {Chain, Ptr}; 7318 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7319 } 7320 7321 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7322 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7323 if (Ops.size() == 1) 7324 return Ops[0]; 7325 7326 SmallVector<EVT, 4> VTs; 7327 VTs.reserve(Ops.size()); 7328 for (const SDValue &Op : Ops) 7329 VTs.push_back(Op.getValueType()); 7330 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7331 } 7332 7333 SDValue SelectionDAG::getMemIntrinsicNode( 7334 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7335 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7336 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7337 if (!Size && MemVT.isScalableVector()) 7338 Size = MemoryLocation::UnknownSize; 7339 else if (!Size) 7340 Size = MemVT.getStoreSize(); 7341 7342 MachineFunction &MF = getMachineFunction(); 7343 MachineMemOperand *MMO = 7344 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7345 7346 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7347 } 7348 7349 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7350 SDVTList VTList, 7351 ArrayRef<SDValue> Ops, EVT MemVT, 7352 MachineMemOperand *MMO) { 7353 assert((Opcode == ISD::INTRINSIC_VOID || 7354 Opcode == ISD::INTRINSIC_W_CHAIN || 7355 Opcode == ISD::PREFETCH || 7356 ((int)Opcode <= std::numeric_limits<int>::max() && 7357 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7358 "Opcode is not a memory-accessing opcode!"); 7359 7360 // Memoize the node unless it returns a flag. 7361 MemIntrinsicSDNode *N; 7362 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7363 FoldingSetNodeID ID; 7364 AddNodeIDNode(ID, Opcode, VTList, Ops); 7365 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7366 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7367 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7368 void *IP = nullptr; 7369 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7370 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7371 return SDValue(E, 0); 7372 } 7373 7374 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7375 VTList, MemVT, MMO); 7376 createOperands(N, Ops); 7377 7378 CSEMap.InsertNode(N, IP); 7379 } else { 7380 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7381 VTList, MemVT, MMO); 7382 createOperands(N, Ops); 7383 } 7384 InsertNode(N); 7385 SDValue V(N, 0); 7386 NewSDValueDbgMsg(V, "Creating new node: ", this); 7387 return V; 7388 } 7389 7390 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7391 SDValue Chain, int FrameIndex, 7392 int64_t Size, int64_t Offset) { 7393 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7394 const auto VTs = getVTList(MVT::Other); 7395 SDValue Ops[2] = { 7396 Chain, 7397 getFrameIndex(FrameIndex, 7398 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7399 true)}; 7400 7401 FoldingSetNodeID ID; 7402 AddNodeIDNode(ID, Opcode, VTs, Ops); 7403 ID.AddInteger(FrameIndex); 7404 ID.AddInteger(Size); 7405 ID.AddInteger(Offset); 7406 void *IP = nullptr; 7407 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7408 return SDValue(E, 0); 7409 7410 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7411 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7412 createOperands(N, Ops); 7413 CSEMap.InsertNode(N, IP); 7414 InsertNode(N); 7415 SDValue V(N, 0); 7416 NewSDValueDbgMsg(V, "Creating new node: ", this); 7417 return V; 7418 } 7419 7420 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7421 uint64_t Guid, uint64_t Index, 7422 uint32_t Attr) { 7423 const unsigned Opcode = ISD::PSEUDO_PROBE; 7424 const auto VTs = getVTList(MVT::Other); 7425 SDValue Ops[] = {Chain}; 7426 FoldingSetNodeID ID; 7427 AddNodeIDNode(ID, Opcode, VTs, Ops); 7428 ID.AddInteger(Guid); 7429 ID.AddInteger(Index); 7430 void *IP = nullptr; 7431 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7432 return SDValue(E, 0); 7433 7434 auto *N = newSDNode<PseudoProbeSDNode>( 7435 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7436 createOperands(N, Ops); 7437 CSEMap.InsertNode(N, IP); 7438 InsertNode(N); 7439 SDValue V(N, 0); 7440 NewSDValueDbgMsg(V, "Creating new node: ", this); 7441 return V; 7442 } 7443 7444 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7445 /// MachinePointerInfo record from it. This is particularly useful because the 7446 /// code generator has many cases where it doesn't bother passing in a 7447 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7448 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7449 SelectionDAG &DAG, SDValue Ptr, 7450 int64_t Offset = 0) { 7451 // If this is FI+Offset, we can model it. 7452 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7453 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7454 FI->getIndex(), Offset); 7455 7456 // If this is (FI+Offset1)+Offset2, we can model it. 7457 if (Ptr.getOpcode() != ISD::ADD || 7458 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7459 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7460 return Info; 7461 7462 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7463 return MachinePointerInfo::getFixedStack( 7464 DAG.getMachineFunction(), FI, 7465 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7466 } 7467 7468 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7469 /// MachinePointerInfo record from it. This is particularly useful because the 7470 /// code generator has many cases where it doesn't bother passing in a 7471 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7472 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7473 SelectionDAG &DAG, SDValue Ptr, 7474 SDValue OffsetOp) { 7475 // If the 'Offset' value isn't a constant, we can't handle this. 7476 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7477 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7478 if (OffsetOp.isUndef()) 7479 return InferPointerInfo(Info, DAG, Ptr); 7480 return Info; 7481 } 7482 7483 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7484 EVT VT, const SDLoc &dl, SDValue Chain, 7485 SDValue Ptr, SDValue Offset, 7486 MachinePointerInfo PtrInfo, EVT MemVT, 7487 Align Alignment, 7488 MachineMemOperand::Flags MMOFlags, 7489 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7490 assert(Chain.getValueType() == MVT::Other && 7491 "Invalid chain type"); 7492 7493 MMOFlags |= MachineMemOperand::MOLoad; 7494 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7495 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7496 // clients. 7497 if (PtrInfo.V.isNull()) 7498 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7499 7500 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7501 MachineFunction &MF = getMachineFunction(); 7502 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7503 Alignment, AAInfo, Ranges); 7504 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7505 } 7506 7507 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7508 EVT VT, const SDLoc &dl, SDValue Chain, 7509 SDValue Ptr, SDValue Offset, EVT MemVT, 7510 MachineMemOperand *MMO) { 7511 if (VT == MemVT) { 7512 ExtType = ISD::NON_EXTLOAD; 7513 } else if (ExtType == ISD::NON_EXTLOAD) { 7514 assert(VT == MemVT && "Non-extending load from different memory type!"); 7515 } else { 7516 // Extending load. 7517 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7518 "Should only be an extending load, not truncating!"); 7519 assert(VT.isInteger() == MemVT.isInteger() && 7520 "Cannot convert from FP to Int or Int -> FP!"); 7521 assert(VT.isVector() == MemVT.isVector() && 7522 "Cannot use an ext load to convert to or from a vector!"); 7523 assert((!VT.isVector() || 7524 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7525 "Cannot use an ext load to change the number of vector elements!"); 7526 } 7527 7528 bool Indexed = AM != ISD::UNINDEXED; 7529 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7530 7531 SDVTList VTs = Indexed ? 7532 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7533 SDValue Ops[] = { Chain, Ptr, Offset }; 7534 FoldingSetNodeID ID; 7535 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7536 ID.AddInteger(MemVT.getRawBits()); 7537 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7538 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7539 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7540 void *IP = nullptr; 7541 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7542 cast<LoadSDNode>(E)->refineAlignment(MMO); 7543 return SDValue(E, 0); 7544 } 7545 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7546 ExtType, MemVT, MMO); 7547 createOperands(N, Ops); 7548 7549 CSEMap.InsertNode(N, IP); 7550 InsertNode(N); 7551 SDValue V(N, 0); 7552 NewSDValueDbgMsg(V, "Creating new node: ", this); 7553 return V; 7554 } 7555 7556 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7557 SDValue Ptr, MachinePointerInfo PtrInfo, 7558 MaybeAlign Alignment, 7559 MachineMemOperand::Flags MMOFlags, 7560 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7561 SDValue Undef = getUNDEF(Ptr.getValueType()); 7562 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7563 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7564 } 7565 7566 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7567 SDValue Ptr, MachineMemOperand *MMO) { 7568 SDValue Undef = getUNDEF(Ptr.getValueType()); 7569 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7570 VT, MMO); 7571 } 7572 7573 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7574 EVT VT, SDValue Chain, SDValue Ptr, 7575 MachinePointerInfo PtrInfo, EVT MemVT, 7576 MaybeAlign Alignment, 7577 MachineMemOperand::Flags MMOFlags, 7578 const AAMDNodes &AAInfo) { 7579 SDValue Undef = getUNDEF(Ptr.getValueType()); 7580 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7581 MemVT, Alignment, MMOFlags, AAInfo); 7582 } 7583 7584 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7585 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7586 MachineMemOperand *MMO) { 7587 SDValue Undef = getUNDEF(Ptr.getValueType()); 7588 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7589 MemVT, MMO); 7590 } 7591 7592 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7593 SDValue Base, SDValue Offset, 7594 ISD::MemIndexedMode AM) { 7595 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7596 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7597 // Don't propagate the invariant or dereferenceable flags. 7598 auto MMOFlags = 7599 LD->getMemOperand()->getFlags() & 7600 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7601 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7602 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7603 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7604 } 7605 7606 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7607 SDValue Ptr, MachinePointerInfo PtrInfo, 7608 Align Alignment, 7609 MachineMemOperand::Flags MMOFlags, 7610 const AAMDNodes &AAInfo) { 7611 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7612 7613 MMOFlags |= MachineMemOperand::MOStore; 7614 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7615 7616 if (PtrInfo.V.isNull()) 7617 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7618 7619 MachineFunction &MF = getMachineFunction(); 7620 uint64_t Size = 7621 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7622 MachineMemOperand *MMO = 7623 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7624 return getStore(Chain, dl, Val, Ptr, MMO); 7625 } 7626 7627 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7628 SDValue Ptr, MachineMemOperand *MMO) { 7629 assert(Chain.getValueType() == MVT::Other && 7630 "Invalid chain type"); 7631 EVT VT = Val.getValueType(); 7632 SDVTList VTs = getVTList(MVT::Other); 7633 SDValue Undef = getUNDEF(Ptr.getValueType()); 7634 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7635 FoldingSetNodeID ID; 7636 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7637 ID.AddInteger(VT.getRawBits()); 7638 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7639 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7640 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7641 void *IP = nullptr; 7642 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7643 cast<StoreSDNode>(E)->refineAlignment(MMO); 7644 return SDValue(E, 0); 7645 } 7646 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7647 ISD::UNINDEXED, false, VT, MMO); 7648 createOperands(N, Ops); 7649 7650 CSEMap.InsertNode(N, IP); 7651 InsertNode(N); 7652 SDValue V(N, 0); 7653 NewSDValueDbgMsg(V, "Creating new node: ", this); 7654 return V; 7655 } 7656 7657 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7658 SDValue Ptr, MachinePointerInfo PtrInfo, 7659 EVT SVT, Align Alignment, 7660 MachineMemOperand::Flags MMOFlags, 7661 const AAMDNodes &AAInfo) { 7662 assert(Chain.getValueType() == MVT::Other && 7663 "Invalid chain type"); 7664 7665 MMOFlags |= MachineMemOperand::MOStore; 7666 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7667 7668 if (PtrInfo.V.isNull()) 7669 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7670 7671 MachineFunction &MF = getMachineFunction(); 7672 MachineMemOperand *MMO = MF.getMachineMemOperand( 7673 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7674 Alignment, AAInfo); 7675 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7676 } 7677 7678 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7679 SDValue Ptr, EVT SVT, 7680 MachineMemOperand *MMO) { 7681 EVT VT = Val.getValueType(); 7682 7683 assert(Chain.getValueType() == MVT::Other && 7684 "Invalid chain type"); 7685 if (VT == SVT) 7686 return getStore(Chain, dl, Val, Ptr, MMO); 7687 7688 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7689 "Should only be a truncating store, not extending!"); 7690 assert(VT.isInteger() == SVT.isInteger() && 7691 "Can't do FP-INT conversion!"); 7692 assert(VT.isVector() == SVT.isVector() && 7693 "Cannot use trunc store to convert to or from a vector!"); 7694 assert((!VT.isVector() || 7695 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7696 "Cannot use trunc store to change the number of vector elements!"); 7697 7698 SDVTList VTs = getVTList(MVT::Other); 7699 SDValue Undef = getUNDEF(Ptr.getValueType()); 7700 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7701 FoldingSetNodeID ID; 7702 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7703 ID.AddInteger(SVT.getRawBits()); 7704 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7705 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7706 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7707 void *IP = nullptr; 7708 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7709 cast<StoreSDNode>(E)->refineAlignment(MMO); 7710 return SDValue(E, 0); 7711 } 7712 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7713 ISD::UNINDEXED, true, SVT, MMO); 7714 createOperands(N, Ops); 7715 7716 CSEMap.InsertNode(N, IP); 7717 InsertNode(N); 7718 SDValue V(N, 0); 7719 NewSDValueDbgMsg(V, "Creating new node: ", this); 7720 return V; 7721 } 7722 7723 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7724 SDValue Base, SDValue Offset, 7725 ISD::MemIndexedMode AM) { 7726 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7727 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7728 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7729 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7730 FoldingSetNodeID ID; 7731 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7732 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7733 ID.AddInteger(ST->getRawSubclassData()); 7734 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7735 void *IP = nullptr; 7736 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7737 return SDValue(E, 0); 7738 7739 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7740 ST->isTruncatingStore(), ST->getMemoryVT(), 7741 ST->getMemOperand()); 7742 createOperands(N, Ops); 7743 7744 CSEMap.InsertNode(N, IP); 7745 InsertNode(N); 7746 SDValue V(N, 0); 7747 NewSDValueDbgMsg(V, "Creating new node: ", this); 7748 return V; 7749 } 7750 7751 SDValue SelectionDAG::getLoadVP( 7752 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7753 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7754 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7755 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7756 const MDNode *Ranges, bool IsExpanding) { 7757 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7758 7759 MMOFlags |= MachineMemOperand::MOLoad; 7760 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7761 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7762 // clients. 7763 if (PtrInfo.V.isNull()) 7764 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7765 7766 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7767 MachineFunction &MF = getMachineFunction(); 7768 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7769 Alignment, AAInfo, Ranges); 7770 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7771 MMO, IsExpanding); 7772 } 7773 7774 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7775 ISD::LoadExtType ExtType, EVT VT, 7776 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7777 SDValue Offset, SDValue Mask, SDValue EVL, 7778 EVT MemVT, MachineMemOperand *MMO, 7779 bool IsExpanding) { 7780 bool Indexed = AM != ISD::UNINDEXED; 7781 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7782 7783 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7784 : getVTList(VT, MVT::Other); 7785 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7786 FoldingSetNodeID ID; 7787 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7788 ID.AddInteger(VT.getRawBits()); 7789 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7790 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7791 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7792 void *IP = nullptr; 7793 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7794 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7795 return SDValue(E, 0); 7796 } 7797 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7798 ExtType, IsExpanding, MemVT, MMO); 7799 createOperands(N, Ops); 7800 7801 CSEMap.InsertNode(N, IP); 7802 InsertNode(N); 7803 SDValue V(N, 0); 7804 NewSDValueDbgMsg(V, "Creating new node: ", this); 7805 return V; 7806 } 7807 7808 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7809 SDValue Ptr, SDValue Mask, SDValue EVL, 7810 MachinePointerInfo PtrInfo, 7811 MaybeAlign Alignment, 7812 MachineMemOperand::Flags MMOFlags, 7813 const AAMDNodes &AAInfo, const MDNode *Ranges, 7814 bool IsExpanding) { 7815 SDValue Undef = getUNDEF(Ptr.getValueType()); 7816 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7817 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7818 IsExpanding); 7819 } 7820 7821 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7822 SDValue Ptr, SDValue Mask, SDValue EVL, 7823 MachineMemOperand *MMO, bool IsExpanding) { 7824 SDValue Undef = getUNDEF(Ptr.getValueType()); 7825 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7826 Mask, EVL, VT, MMO, IsExpanding); 7827 } 7828 7829 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7830 EVT VT, SDValue Chain, SDValue Ptr, 7831 SDValue Mask, SDValue EVL, 7832 MachinePointerInfo PtrInfo, EVT MemVT, 7833 MaybeAlign Alignment, 7834 MachineMemOperand::Flags MMOFlags, 7835 const AAMDNodes &AAInfo, bool IsExpanding) { 7836 SDValue Undef = getUNDEF(Ptr.getValueType()); 7837 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7838 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7839 IsExpanding); 7840 } 7841 7842 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7843 EVT VT, SDValue Chain, SDValue Ptr, 7844 SDValue Mask, SDValue EVL, EVT MemVT, 7845 MachineMemOperand *MMO, bool IsExpanding) { 7846 SDValue Undef = getUNDEF(Ptr.getValueType()); 7847 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7848 EVL, MemVT, MMO, IsExpanding); 7849 } 7850 7851 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7852 SDValue Base, SDValue Offset, 7853 ISD::MemIndexedMode AM) { 7854 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7855 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7856 // Don't propagate the invariant or dereferenceable flags. 7857 auto MMOFlags = 7858 LD->getMemOperand()->getFlags() & 7859 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7860 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7861 LD->getChain(), Base, Offset, LD->getMask(), 7862 LD->getVectorLength(), LD->getPointerInfo(), 7863 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7864 nullptr, LD->isExpandingLoad()); 7865 } 7866 7867 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7868 SDValue Ptr, SDValue Offset, SDValue Mask, 7869 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 7870 ISD::MemIndexedMode AM, bool IsTruncating, 7871 bool IsCompressing) { 7872 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7873 bool Indexed = AM != ISD::UNINDEXED; 7874 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 7875 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 7876 : getVTList(MVT::Other); 7877 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 7878 FoldingSetNodeID ID; 7879 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7880 ID.AddInteger(MemVT.getRawBits()); 7881 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7882 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7883 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7884 void *IP = nullptr; 7885 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7886 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7887 return SDValue(E, 0); 7888 } 7889 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7890 IsTruncating, IsCompressing, MemVT, MMO); 7891 createOperands(N, Ops); 7892 7893 CSEMap.InsertNode(N, IP); 7894 InsertNode(N); 7895 SDValue V(N, 0); 7896 NewSDValueDbgMsg(V, "Creating new node: ", this); 7897 return V; 7898 } 7899 7900 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7901 SDValue Val, SDValue Ptr, SDValue Mask, 7902 SDValue EVL, MachinePointerInfo PtrInfo, 7903 EVT SVT, Align Alignment, 7904 MachineMemOperand::Flags MMOFlags, 7905 const AAMDNodes &AAInfo, 7906 bool IsCompressing) { 7907 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7908 7909 MMOFlags |= MachineMemOperand::MOStore; 7910 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7911 7912 if (PtrInfo.V.isNull()) 7913 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7914 7915 MachineFunction &MF = getMachineFunction(); 7916 MachineMemOperand *MMO = MF.getMachineMemOperand( 7917 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7918 Alignment, AAInfo); 7919 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 7920 IsCompressing); 7921 } 7922 7923 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7924 SDValue Val, SDValue Ptr, SDValue Mask, 7925 SDValue EVL, EVT SVT, 7926 MachineMemOperand *MMO, 7927 bool IsCompressing) { 7928 EVT VT = Val.getValueType(); 7929 7930 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7931 if (VT == SVT) 7932 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 7933 EVL, VT, MMO, ISD::UNINDEXED, 7934 /*IsTruncating*/ false, IsCompressing); 7935 7936 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7937 "Should only be a truncating store, not extending!"); 7938 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 7939 assert(VT.isVector() == SVT.isVector() && 7940 "Cannot use trunc store to convert to or from a vector!"); 7941 assert((!VT.isVector() || 7942 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7943 "Cannot use trunc store to change the number of vector elements!"); 7944 7945 SDVTList VTs = getVTList(MVT::Other); 7946 SDValue Undef = getUNDEF(Ptr.getValueType()); 7947 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 7948 FoldingSetNodeID ID; 7949 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7950 ID.AddInteger(SVT.getRawBits()); 7951 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7952 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 7953 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7954 void *IP = nullptr; 7955 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7956 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7957 return SDValue(E, 0); 7958 } 7959 auto *N = 7960 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7961 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 7962 createOperands(N, Ops); 7963 7964 CSEMap.InsertNode(N, IP); 7965 InsertNode(N); 7966 SDValue V(N, 0); 7967 NewSDValueDbgMsg(V, "Creating new node: ", this); 7968 return V; 7969 } 7970 7971 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 7972 SDValue Base, SDValue Offset, 7973 ISD::MemIndexedMode AM) { 7974 auto *ST = cast<VPStoreSDNode>(OrigStore); 7975 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 7976 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7977 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 7978 Offset, ST->getMask(), ST->getVectorLength()}; 7979 FoldingSetNodeID ID; 7980 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7981 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7982 ID.AddInteger(ST->getRawSubclassData()); 7983 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7984 void *IP = nullptr; 7985 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7986 return SDValue(E, 0); 7987 7988 auto *N = newSDNode<VPStoreSDNode>( 7989 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 7990 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 7991 createOperands(N, Ops); 7992 7993 CSEMap.InsertNode(N, IP); 7994 InsertNode(N); 7995 SDValue V(N, 0); 7996 NewSDValueDbgMsg(V, "Creating new node: ", this); 7997 return V; 7998 } 7999 8000 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8001 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 8002 ISD::MemIndexType IndexType) { 8003 assert(Ops.size() == 6 && "Incompatible number of operands"); 8004 8005 FoldingSetNodeID ID; 8006 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 8007 ID.AddInteger(VT.getRawBits()); 8008 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 8009 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8010 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8011 void *IP = nullptr; 8012 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8013 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 8014 return SDValue(E, 0); 8015 } 8016 8017 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8018 VT, MMO, IndexType); 8019 createOperands(N, Ops); 8020 8021 assert(N->getMask().getValueType().getVectorElementCount() == 8022 N->getValueType(0).getVectorElementCount() && 8023 "Vector width mismatch between mask and data"); 8024 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8025 N->getValueType(0).getVectorElementCount().isScalable() && 8026 "Scalable flags of index and data do not match"); 8027 assert(ElementCount::isKnownGE( 8028 N->getIndex().getValueType().getVectorElementCount(), 8029 N->getValueType(0).getVectorElementCount()) && 8030 "Vector width mismatch between index and data"); 8031 assert(isa<ConstantSDNode>(N->getScale()) && 8032 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8033 "Scale should be a constant power of 2"); 8034 8035 CSEMap.InsertNode(N, IP); 8036 InsertNode(N); 8037 SDValue V(N, 0); 8038 NewSDValueDbgMsg(V, "Creating new node: ", this); 8039 return V; 8040 } 8041 8042 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 8043 ArrayRef<SDValue> Ops, 8044 MachineMemOperand *MMO, 8045 ISD::MemIndexType IndexType) { 8046 assert(Ops.size() == 7 && "Incompatible number of operands"); 8047 8048 FoldingSetNodeID ID; 8049 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8050 ID.AddInteger(VT.getRawBits()); 8051 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8052 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8053 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8054 void *IP = nullptr; 8055 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8056 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8057 return SDValue(E, 0); 8058 } 8059 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8060 VT, MMO, IndexType); 8061 createOperands(N, Ops); 8062 8063 assert(N->getMask().getValueType().getVectorElementCount() == 8064 N->getValue().getValueType().getVectorElementCount() && 8065 "Vector width mismatch between mask and data"); 8066 assert( 8067 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8068 N->getValue().getValueType().getVectorElementCount().isScalable() && 8069 "Scalable flags of index and data do not match"); 8070 assert(ElementCount::isKnownGE( 8071 N->getIndex().getValueType().getVectorElementCount(), 8072 N->getValue().getValueType().getVectorElementCount()) && 8073 "Vector width mismatch between index and data"); 8074 assert(isa<ConstantSDNode>(N->getScale()) && 8075 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8076 "Scale should be a constant power of 2"); 8077 8078 CSEMap.InsertNode(N, IP); 8079 InsertNode(N); 8080 SDValue V(N, 0); 8081 NewSDValueDbgMsg(V, "Creating new node: ", this); 8082 return V; 8083 } 8084 8085 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8086 SDValue Base, SDValue Offset, SDValue Mask, 8087 SDValue PassThru, EVT MemVT, 8088 MachineMemOperand *MMO, 8089 ISD::MemIndexedMode AM, 8090 ISD::LoadExtType ExtTy, bool isExpanding) { 8091 bool Indexed = AM != ISD::UNINDEXED; 8092 assert((Indexed || Offset.isUndef()) && 8093 "Unindexed masked load with an offset!"); 8094 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8095 : getVTList(VT, MVT::Other); 8096 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8097 FoldingSetNodeID ID; 8098 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8099 ID.AddInteger(MemVT.getRawBits()); 8100 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8101 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8102 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8103 void *IP = nullptr; 8104 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8105 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8106 return SDValue(E, 0); 8107 } 8108 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8109 AM, ExtTy, isExpanding, MemVT, MMO); 8110 createOperands(N, Ops); 8111 8112 CSEMap.InsertNode(N, IP); 8113 InsertNode(N); 8114 SDValue V(N, 0); 8115 NewSDValueDbgMsg(V, "Creating new node: ", this); 8116 return V; 8117 } 8118 8119 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8120 SDValue Base, SDValue Offset, 8121 ISD::MemIndexedMode AM) { 8122 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8123 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8124 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8125 Offset, LD->getMask(), LD->getPassThru(), 8126 LD->getMemoryVT(), LD->getMemOperand(), AM, 8127 LD->getExtensionType(), LD->isExpandingLoad()); 8128 } 8129 8130 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8131 SDValue Val, SDValue Base, SDValue Offset, 8132 SDValue Mask, EVT MemVT, 8133 MachineMemOperand *MMO, 8134 ISD::MemIndexedMode AM, bool IsTruncating, 8135 bool IsCompressing) { 8136 assert(Chain.getValueType() == MVT::Other && 8137 "Invalid chain type"); 8138 bool Indexed = AM != ISD::UNINDEXED; 8139 assert((Indexed || Offset.isUndef()) && 8140 "Unindexed masked store with an offset!"); 8141 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8142 : getVTList(MVT::Other); 8143 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8144 FoldingSetNodeID ID; 8145 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8146 ID.AddInteger(MemVT.getRawBits()); 8147 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8148 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8149 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8150 void *IP = nullptr; 8151 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8152 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8153 return SDValue(E, 0); 8154 } 8155 auto *N = 8156 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8157 IsTruncating, IsCompressing, MemVT, MMO); 8158 createOperands(N, Ops); 8159 8160 CSEMap.InsertNode(N, IP); 8161 InsertNode(N); 8162 SDValue V(N, 0); 8163 NewSDValueDbgMsg(V, "Creating new node: ", this); 8164 return V; 8165 } 8166 8167 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8168 SDValue Base, SDValue Offset, 8169 ISD::MemIndexedMode AM) { 8170 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8171 assert(ST->getOffset().isUndef() && 8172 "Masked store is already a indexed store!"); 8173 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8174 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8175 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8176 } 8177 8178 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8179 ArrayRef<SDValue> Ops, 8180 MachineMemOperand *MMO, 8181 ISD::MemIndexType IndexType, 8182 ISD::LoadExtType ExtTy) { 8183 assert(Ops.size() == 6 && "Incompatible number of operands"); 8184 8185 FoldingSetNodeID ID; 8186 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8187 ID.AddInteger(MemVT.getRawBits()); 8188 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8189 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8190 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8191 void *IP = nullptr; 8192 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8193 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8194 return SDValue(E, 0); 8195 } 8196 8197 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8198 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8199 VTs, MemVT, MMO, IndexType, ExtTy); 8200 createOperands(N, Ops); 8201 8202 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8203 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8204 assert(N->getMask().getValueType().getVectorElementCount() == 8205 N->getValueType(0).getVectorElementCount() && 8206 "Vector width mismatch between mask and data"); 8207 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8208 N->getValueType(0).getVectorElementCount().isScalable() && 8209 "Scalable flags of index and data do not match"); 8210 assert(ElementCount::isKnownGE( 8211 N->getIndex().getValueType().getVectorElementCount(), 8212 N->getValueType(0).getVectorElementCount()) && 8213 "Vector width mismatch between index and data"); 8214 assert(isa<ConstantSDNode>(N->getScale()) && 8215 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8216 "Scale should be a constant power of 2"); 8217 8218 CSEMap.InsertNode(N, IP); 8219 InsertNode(N); 8220 SDValue V(N, 0); 8221 NewSDValueDbgMsg(V, "Creating new node: ", this); 8222 return V; 8223 } 8224 8225 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8226 ArrayRef<SDValue> Ops, 8227 MachineMemOperand *MMO, 8228 ISD::MemIndexType IndexType, 8229 bool IsTrunc) { 8230 assert(Ops.size() == 6 && "Incompatible number of operands"); 8231 8232 FoldingSetNodeID ID; 8233 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8234 ID.AddInteger(MemVT.getRawBits()); 8235 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8236 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8237 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8238 void *IP = nullptr; 8239 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8240 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8241 return SDValue(E, 0); 8242 } 8243 8244 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8245 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8246 VTs, MemVT, MMO, IndexType, IsTrunc); 8247 createOperands(N, Ops); 8248 8249 assert(N->getMask().getValueType().getVectorElementCount() == 8250 N->getValue().getValueType().getVectorElementCount() && 8251 "Vector width mismatch between mask and data"); 8252 assert( 8253 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8254 N->getValue().getValueType().getVectorElementCount().isScalable() && 8255 "Scalable flags of index and data do not match"); 8256 assert(ElementCount::isKnownGE( 8257 N->getIndex().getValueType().getVectorElementCount(), 8258 N->getValue().getValueType().getVectorElementCount()) && 8259 "Vector width mismatch between index and data"); 8260 assert(isa<ConstantSDNode>(N->getScale()) && 8261 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8262 "Scale should be a constant power of 2"); 8263 8264 CSEMap.InsertNode(N, IP); 8265 InsertNode(N); 8266 SDValue V(N, 0); 8267 NewSDValueDbgMsg(V, "Creating new node: ", this); 8268 return V; 8269 } 8270 8271 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8272 // select undef, T, F --> T (if T is a constant), otherwise F 8273 // select, ?, undef, F --> F 8274 // select, ?, T, undef --> T 8275 if (Cond.isUndef()) 8276 return isConstantValueOfAnyType(T) ? T : F; 8277 if (T.isUndef()) 8278 return F; 8279 if (F.isUndef()) 8280 return T; 8281 8282 // select true, T, F --> T 8283 // select false, T, F --> F 8284 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8285 return CondC->isZero() ? F : T; 8286 8287 // TODO: This should simplify VSELECT with constant condition using something 8288 // like this (but check boolean contents to be complete?): 8289 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8290 // return T; 8291 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8292 // return F; 8293 8294 // select ?, T, T --> T 8295 if (T == F) 8296 return T; 8297 8298 return SDValue(); 8299 } 8300 8301 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8302 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8303 if (X.isUndef()) 8304 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8305 // shift X, undef --> undef (because it may shift by the bitwidth) 8306 if (Y.isUndef()) 8307 return getUNDEF(X.getValueType()); 8308 8309 // shift 0, Y --> 0 8310 // shift X, 0 --> X 8311 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8312 return X; 8313 8314 // shift X, C >= bitwidth(X) --> undef 8315 // All vector elements must be too big (or undef) to avoid partial undefs. 8316 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8317 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8318 }; 8319 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8320 return getUNDEF(X.getValueType()); 8321 8322 return SDValue(); 8323 } 8324 8325 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8326 SDNodeFlags Flags) { 8327 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8328 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8329 // operation is poison. That result can be relaxed to undef. 8330 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8331 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8332 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8333 (YC && YC->getValueAPF().isNaN()); 8334 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8335 (YC && YC->getValueAPF().isInfinity()); 8336 8337 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8338 return getUNDEF(X.getValueType()); 8339 8340 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8341 return getUNDEF(X.getValueType()); 8342 8343 if (!YC) 8344 return SDValue(); 8345 8346 // X + -0.0 --> X 8347 if (Opcode == ISD::FADD) 8348 if (YC->getValueAPF().isNegZero()) 8349 return X; 8350 8351 // X - +0.0 --> X 8352 if (Opcode == ISD::FSUB) 8353 if (YC->getValueAPF().isPosZero()) 8354 return X; 8355 8356 // X * 1.0 --> X 8357 // X / 1.0 --> X 8358 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8359 if (YC->getValueAPF().isExactlyValue(1.0)) 8360 return X; 8361 8362 // X * 0.0 --> 0.0 8363 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8364 if (YC->getValueAPF().isZero()) 8365 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8366 8367 return SDValue(); 8368 } 8369 8370 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8371 SDValue Ptr, SDValue SV, unsigned Align) { 8372 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8373 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8374 } 8375 8376 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8377 ArrayRef<SDUse> Ops) { 8378 switch (Ops.size()) { 8379 case 0: return getNode(Opcode, DL, VT); 8380 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8381 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8382 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8383 default: break; 8384 } 8385 8386 // Copy from an SDUse array into an SDValue array for use with 8387 // the regular getNode logic. 8388 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8389 return getNode(Opcode, DL, VT, NewOps); 8390 } 8391 8392 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8393 ArrayRef<SDValue> Ops) { 8394 SDNodeFlags Flags; 8395 if (Inserter) 8396 Flags = Inserter->getFlags(); 8397 return getNode(Opcode, DL, VT, Ops, Flags); 8398 } 8399 8400 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8401 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8402 unsigned NumOps = Ops.size(); 8403 switch (NumOps) { 8404 case 0: return getNode(Opcode, DL, VT); 8405 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8406 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8407 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8408 default: break; 8409 } 8410 8411 #ifndef NDEBUG 8412 for (auto &Op : Ops) 8413 assert(Op.getOpcode() != ISD::DELETED_NODE && 8414 "Operand is DELETED_NODE!"); 8415 #endif 8416 8417 switch (Opcode) { 8418 default: break; 8419 case ISD::BUILD_VECTOR: 8420 // Attempt to simplify BUILD_VECTOR. 8421 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8422 return V; 8423 break; 8424 case ISD::CONCAT_VECTORS: 8425 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8426 return V; 8427 break; 8428 case ISD::SELECT_CC: 8429 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8430 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8431 "LHS and RHS of condition must have same type!"); 8432 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8433 "True and False arms of SelectCC must have same type!"); 8434 assert(Ops[2].getValueType() == VT && 8435 "select_cc node must be of same type as true and false value!"); 8436 break; 8437 case ISD::BR_CC: 8438 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8439 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8440 "LHS/RHS of comparison should match types!"); 8441 break; 8442 } 8443 8444 // Memoize nodes. 8445 SDNode *N; 8446 SDVTList VTs = getVTList(VT); 8447 8448 if (VT != MVT::Glue) { 8449 FoldingSetNodeID ID; 8450 AddNodeIDNode(ID, Opcode, VTs, Ops); 8451 void *IP = nullptr; 8452 8453 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8454 return SDValue(E, 0); 8455 8456 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8457 createOperands(N, Ops); 8458 8459 CSEMap.InsertNode(N, IP); 8460 } else { 8461 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8462 createOperands(N, Ops); 8463 } 8464 8465 N->setFlags(Flags); 8466 InsertNode(N); 8467 SDValue V(N, 0); 8468 NewSDValueDbgMsg(V, "Creating new node: ", this); 8469 return V; 8470 } 8471 8472 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8473 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8474 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8475 } 8476 8477 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8478 ArrayRef<SDValue> Ops) { 8479 SDNodeFlags Flags; 8480 if (Inserter) 8481 Flags = Inserter->getFlags(); 8482 return getNode(Opcode, DL, VTList, Ops, Flags); 8483 } 8484 8485 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8486 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8487 if (VTList.NumVTs == 1) 8488 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8489 8490 #ifndef NDEBUG 8491 for (auto &Op : Ops) 8492 assert(Op.getOpcode() != ISD::DELETED_NODE && 8493 "Operand is DELETED_NODE!"); 8494 #endif 8495 8496 switch (Opcode) { 8497 case ISD::STRICT_FP_EXTEND: 8498 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8499 "Invalid STRICT_FP_EXTEND!"); 8500 assert(VTList.VTs[0].isFloatingPoint() && 8501 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8502 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8503 "STRICT_FP_EXTEND result type should be vector iff the operand " 8504 "type is vector!"); 8505 assert((!VTList.VTs[0].isVector() || 8506 VTList.VTs[0].getVectorNumElements() == 8507 Ops[1].getValueType().getVectorNumElements()) && 8508 "Vector element count mismatch!"); 8509 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8510 "Invalid fpext node, dst <= src!"); 8511 break; 8512 case ISD::STRICT_FP_ROUND: 8513 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8514 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8515 "STRICT_FP_ROUND result type should be vector iff the operand " 8516 "type is vector!"); 8517 assert((!VTList.VTs[0].isVector() || 8518 VTList.VTs[0].getVectorNumElements() == 8519 Ops[1].getValueType().getVectorNumElements()) && 8520 "Vector element count mismatch!"); 8521 assert(VTList.VTs[0].isFloatingPoint() && 8522 Ops[1].getValueType().isFloatingPoint() && 8523 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8524 isa<ConstantSDNode>(Ops[2]) && 8525 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8526 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8527 "Invalid STRICT_FP_ROUND!"); 8528 break; 8529 #if 0 8530 // FIXME: figure out how to safely handle things like 8531 // int foo(int x) { return 1 << (x & 255); } 8532 // int bar() { return foo(256); } 8533 case ISD::SRA_PARTS: 8534 case ISD::SRL_PARTS: 8535 case ISD::SHL_PARTS: 8536 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8537 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8538 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8539 else if (N3.getOpcode() == ISD::AND) 8540 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8541 // If the and is only masking out bits that cannot effect the shift, 8542 // eliminate the and. 8543 unsigned NumBits = VT.getScalarSizeInBits()*2; 8544 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8545 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8546 } 8547 break; 8548 #endif 8549 } 8550 8551 // Memoize the node unless it returns a flag. 8552 SDNode *N; 8553 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8554 FoldingSetNodeID ID; 8555 AddNodeIDNode(ID, Opcode, VTList, Ops); 8556 void *IP = nullptr; 8557 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8558 return SDValue(E, 0); 8559 8560 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8561 createOperands(N, Ops); 8562 CSEMap.InsertNode(N, IP); 8563 } else { 8564 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8565 createOperands(N, Ops); 8566 } 8567 8568 N->setFlags(Flags); 8569 InsertNode(N); 8570 SDValue V(N, 0); 8571 NewSDValueDbgMsg(V, "Creating new node: ", this); 8572 return V; 8573 } 8574 8575 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8576 SDVTList VTList) { 8577 return getNode(Opcode, DL, VTList, None); 8578 } 8579 8580 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8581 SDValue N1) { 8582 SDValue Ops[] = { N1 }; 8583 return getNode(Opcode, DL, VTList, Ops); 8584 } 8585 8586 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8587 SDValue N1, SDValue N2) { 8588 SDValue Ops[] = { N1, N2 }; 8589 return getNode(Opcode, DL, VTList, Ops); 8590 } 8591 8592 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8593 SDValue N1, SDValue N2, SDValue N3) { 8594 SDValue Ops[] = { N1, N2, N3 }; 8595 return getNode(Opcode, DL, VTList, Ops); 8596 } 8597 8598 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8599 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8600 SDValue Ops[] = { N1, N2, N3, N4 }; 8601 return getNode(Opcode, DL, VTList, Ops); 8602 } 8603 8604 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8605 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8606 SDValue N5) { 8607 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8608 return getNode(Opcode, DL, VTList, Ops); 8609 } 8610 8611 SDVTList SelectionDAG::getVTList(EVT VT) { 8612 return makeVTList(SDNode::getValueTypeList(VT), 1); 8613 } 8614 8615 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8616 FoldingSetNodeID ID; 8617 ID.AddInteger(2U); 8618 ID.AddInteger(VT1.getRawBits()); 8619 ID.AddInteger(VT2.getRawBits()); 8620 8621 void *IP = nullptr; 8622 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8623 if (!Result) { 8624 EVT *Array = Allocator.Allocate<EVT>(2); 8625 Array[0] = VT1; 8626 Array[1] = VT2; 8627 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8628 VTListMap.InsertNode(Result, IP); 8629 } 8630 return Result->getSDVTList(); 8631 } 8632 8633 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 8634 FoldingSetNodeID ID; 8635 ID.AddInteger(3U); 8636 ID.AddInteger(VT1.getRawBits()); 8637 ID.AddInteger(VT2.getRawBits()); 8638 ID.AddInteger(VT3.getRawBits()); 8639 8640 void *IP = nullptr; 8641 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8642 if (!Result) { 8643 EVT *Array = Allocator.Allocate<EVT>(3); 8644 Array[0] = VT1; 8645 Array[1] = VT2; 8646 Array[2] = VT3; 8647 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 8648 VTListMap.InsertNode(Result, IP); 8649 } 8650 return Result->getSDVTList(); 8651 } 8652 8653 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 8654 FoldingSetNodeID ID; 8655 ID.AddInteger(4U); 8656 ID.AddInteger(VT1.getRawBits()); 8657 ID.AddInteger(VT2.getRawBits()); 8658 ID.AddInteger(VT3.getRawBits()); 8659 ID.AddInteger(VT4.getRawBits()); 8660 8661 void *IP = nullptr; 8662 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8663 if (!Result) { 8664 EVT *Array = Allocator.Allocate<EVT>(4); 8665 Array[0] = VT1; 8666 Array[1] = VT2; 8667 Array[2] = VT3; 8668 Array[3] = VT4; 8669 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 8670 VTListMap.InsertNode(Result, IP); 8671 } 8672 return Result->getSDVTList(); 8673 } 8674 8675 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 8676 unsigned NumVTs = VTs.size(); 8677 FoldingSetNodeID ID; 8678 ID.AddInteger(NumVTs); 8679 for (unsigned index = 0; index < NumVTs; index++) { 8680 ID.AddInteger(VTs[index].getRawBits()); 8681 } 8682 8683 void *IP = nullptr; 8684 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8685 if (!Result) { 8686 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 8687 llvm::copy(VTs, Array); 8688 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 8689 VTListMap.InsertNode(Result, IP); 8690 } 8691 return Result->getSDVTList(); 8692 } 8693 8694 8695 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 8696 /// specified operands. If the resultant node already exists in the DAG, 8697 /// this does not modify the specified node, instead it returns the node that 8698 /// already exists. If the resultant node does not exist in the DAG, the 8699 /// input node is returned. As a degenerate case, if you specify the same 8700 /// input operands as the node already has, the input node is returned. 8701 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 8702 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 8703 8704 // Check to see if there is no change. 8705 if (Op == N->getOperand(0)) return N; 8706 8707 // See if the modified node already exists. 8708 void *InsertPos = nullptr; 8709 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 8710 return Existing; 8711 8712 // Nope it doesn't. Remove the node from its current place in the maps. 8713 if (InsertPos) 8714 if (!RemoveNodeFromCSEMaps(N)) 8715 InsertPos = nullptr; 8716 8717 // Now we update the operands. 8718 N->OperandList[0].set(Op); 8719 8720 updateDivergence(N); 8721 // If this gets put into a CSE map, add it. 8722 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8723 return N; 8724 } 8725 8726 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 8727 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 8728 8729 // Check to see if there is no change. 8730 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 8731 return N; // No operands changed, just return the input node. 8732 8733 // See if the modified node already exists. 8734 void *InsertPos = nullptr; 8735 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 8736 return Existing; 8737 8738 // Nope it doesn't. Remove the node from its current place in the maps. 8739 if (InsertPos) 8740 if (!RemoveNodeFromCSEMaps(N)) 8741 InsertPos = nullptr; 8742 8743 // Now we update the operands. 8744 if (N->OperandList[0] != Op1) 8745 N->OperandList[0].set(Op1); 8746 if (N->OperandList[1] != Op2) 8747 N->OperandList[1].set(Op2); 8748 8749 updateDivergence(N); 8750 // If this gets put into a CSE map, add it. 8751 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8752 return N; 8753 } 8754 8755 SDNode *SelectionDAG:: 8756 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 8757 SDValue Ops[] = { Op1, Op2, Op3 }; 8758 return UpdateNodeOperands(N, Ops); 8759 } 8760 8761 SDNode *SelectionDAG:: 8762 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8763 SDValue Op3, SDValue Op4) { 8764 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 8765 return UpdateNodeOperands(N, Ops); 8766 } 8767 8768 SDNode *SelectionDAG:: 8769 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8770 SDValue Op3, SDValue Op4, SDValue Op5) { 8771 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 8772 return UpdateNodeOperands(N, Ops); 8773 } 8774 8775 SDNode *SelectionDAG:: 8776 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 8777 unsigned NumOps = Ops.size(); 8778 assert(N->getNumOperands() == NumOps && 8779 "Update with wrong number of operands"); 8780 8781 // If no operands changed just return the input node. 8782 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 8783 return N; 8784 8785 // See if the modified node already exists. 8786 void *InsertPos = nullptr; 8787 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8788 return Existing; 8789 8790 // Nope it doesn't. Remove the node from its current place in the maps. 8791 if (InsertPos) 8792 if (!RemoveNodeFromCSEMaps(N)) 8793 InsertPos = nullptr; 8794 8795 // Now we update the operands. 8796 for (unsigned i = 0; i != NumOps; ++i) 8797 if (N->OperandList[i] != Ops[i]) 8798 N->OperandList[i].set(Ops[i]); 8799 8800 updateDivergence(N); 8801 // If this gets put into a CSE map, add it. 8802 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8803 return N; 8804 } 8805 8806 /// DropOperands - Release the operands and set this node to have 8807 /// zero operands. 8808 void SDNode::DropOperands() { 8809 // Unlike the code in MorphNodeTo that does this, we don't need to 8810 // watch for dead nodes here. 8811 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8812 SDUse &Use = *I++; 8813 Use.set(SDValue()); 8814 } 8815 } 8816 8817 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8818 ArrayRef<MachineMemOperand *> NewMemRefs) { 8819 if (NewMemRefs.empty()) { 8820 N->clearMemRefs(); 8821 return; 8822 } 8823 8824 // Check if we can avoid allocating by storing a single reference directly. 8825 if (NewMemRefs.size() == 1) { 8826 N->MemRefs = NewMemRefs[0]; 8827 N->NumMemRefs = 1; 8828 return; 8829 } 8830 8831 MachineMemOperand **MemRefsBuffer = 8832 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8833 llvm::copy(NewMemRefs, MemRefsBuffer); 8834 N->MemRefs = MemRefsBuffer; 8835 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8836 } 8837 8838 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8839 /// machine opcode. 8840 /// 8841 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8842 EVT VT) { 8843 SDVTList VTs = getVTList(VT); 8844 return SelectNodeTo(N, MachineOpc, VTs, None); 8845 } 8846 8847 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8848 EVT VT, SDValue Op1) { 8849 SDVTList VTs = getVTList(VT); 8850 SDValue Ops[] = { Op1 }; 8851 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8852 } 8853 8854 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8855 EVT VT, SDValue Op1, 8856 SDValue Op2) { 8857 SDVTList VTs = getVTList(VT); 8858 SDValue Ops[] = { Op1, Op2 }; 8859 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8860 } 8861 8862 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8863 EVT VT, SDValue Op1, 8864 SDValue Op2, SDValue Op3) { 8865 SDVTList VTs = getVTList(VT); 8866 SDValue Ops[] = { Op1, Op2, Op3 }; 8867 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8868 } 8869 8870 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8871 EVT VT, ArrayRef<SDValue> Ops) { 8872 SDVTList VTs = getVTList(VT); 8873 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8874 } 8875 8876 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8877 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8878 SDVTList VTs = getVTList(VT1, VT2); 8879 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8880 } 8881 8882 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8883 EVT VT1, EVT VT2) { 8884 SDVTList VTs = getVTList(VT1, VT2); 8885 return SelectNodeTo(N, MachineOpc, VTs, None); 8886 } 8887 8888 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8889 EVT VT1, EVT VT2, EVT VT3, 8890 ArrayRef<SDValue> Ops) { 8891 SDVTList VTs = getVTList(VT1, VT2, VT3); 8892 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8893 } 8894 8895 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8896 EVT VT1, EVT VT2, 8897 SDValue Op1, SDValue Op2) { 8898 SDVTList VTs = getVTList(VT1, VT2); 8899 SDValue Ops[] = { Op1, Op2 }; 8900 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8901 } 8902 8903 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8904 SDVTList VTs,ArrayRef<SDValue> Ops) { 8905 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8906 // Reset the NodeID to -1. 8907 New->setNodeId(-1); 8908 if (New != N) { 8909 ReplaceAllUsesWith(N, New); 8910 RemoveDeadNode(N); 8911 } 8912 return New; 8913 } 8914 8915 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8916 /// the line number information on the merged node since it is not possible to 8917 /// preserve the information that operation is associated with multiple lines. 8918 /// This will make the debugger working better at -O0, were there is a higher 8919 /// probability having other instructions associated with that line. 8920 /// 8921 /// For IROrder, we keep the smaller of the two 8922 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8923 DebugLoc NLoc = N->getDebugLoc(); 8924 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8925 N->setDebugLoc(DebugLoc()); 8926 } 8927 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8928 N->setIROrder(Order); 8929 return N; 8930 } 8931 8932 /// MorphNodeTo - This *mutates* the specified node to have the specified 8933 /// return type, opcode, and operands. 8934 /// 8935 /// Note that MorphNodeTo returns the resultant node. If there is already a 8936 /// node of the specified opcode and operands, it returns that node instead of 8937 /// the current one. Note that the SDLoc need not be the same. 8938 /// 8939 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8940 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8941 /// node, and because it doesn't require CSE recalculation for any of 8942 /// the node's users. 8943 /// 8944 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8945 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8946 /// the legalizer which maintain worklists that would need to be updated when 8947 /// deleting things. 8948 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8949 SDVTList VTs, ArrayRef<SDValue> Ops) { 8950 // If an identical node already exists, use it. 8951 void *IP = nullptr; 8952 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8953 FoldingSetNodeID ID; 8954 AddNodeIDNode(ID, Opc, VTs, Ops); 8955 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8956 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8957 } 8958 8959 if (!RemoveNodeFromCSEMaps(N)) 8960 IP = nullptr; 8961 8962 // Start the morphing. 8963 N->NodeType = Opc; 8964 N->ValueList = VTs.VTs; 8965 N->NumValues = VTs.NumVTs; 8966 8967 // Clear the operands list, updating used nodes to remove this from their 8968 // use list. Keep track of any operands that become dead as a result. 8969 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8970 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8971 SDUse &Use = *I++; 8972 SDNode *Used = Use.getNode(); 8973 Use.set(SDValue()); 8974 if (Used->use_empty()) 8975 DeadNodeSet.insert(Used); 8976 } 8977 8978 // For MachineNode, initialize the memory references information. 8979 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8980 MN->clearMemRefs(); 8981 8982 // Swap for an appropriately sized array from the recycler. 8983 removeOperands(N); 8984 createOperands(N, Ops); 8985 8986 // Delete any nodes that are still dead after adding the uses for the 8987 // new operands. 8988 if (!DeadNodeSet.empty()) { 8989 SmallVector<SDNode *, 16> DeadNodes; 8990 for (SDNode *N : DeadNodeSet) 8991 if (N->use_empty()) 8992 DeadNodes.push_back(N); 8993 RemoveDeadNodes(DeadNodes); 8994 } 8995 8996 if (IP) 8997 CSEMap.InsertNode(N, IP); // Memoize the new node. 8998 return N; 8999 } 9000 9001 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 9002 unsigned OrigOpc = Node->getOpcode(); 9003 unsigned NewOpc; 9004 switch (OrigOpc) { 9005 default: 9006 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 9007 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9008 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 9009 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 9010 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 9011 #include "llvm/IR/ConstrainedOps.def" 9012 } 9013 9014 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 9015 9016 // We're taking this node out of the chain, so we need to re-link things. 9017 SDValue InputChain = Node->getOperand(0); 9018 SDValue OutputChain = SDValue(Node, 1); 9019 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 9020 9021 SmallVector<SDValue, 3> Ops; 9022 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 9023 Ops.push_back(Node->getOperand(i)); 9024 9025 SDVTList VTs = getVTList(Node->getValueType(0)); 9026 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 9027 9028 // MorphNodeTo can operate in two ways: if an existing node with the 9029 // specified operands exists, it can just return it. Otherwise, it 9030 // updates the node in place to have the requested operands. 9031 if (Res == Node) { 9032 // If we updated the node in place, reset the node ID. To the isel, 9033 // this should be just like a newly allocated machine node. 9034 Res->setNodeId(-1); 9035 } else { 9036 ReplaceAllUsesWith(Node, Res); 9037 RemoveDeadNode(Node); 9038 } 9039 9040 return Res; 9041 } 9042 9043 /// getMachineNode - These are used for target selectors to create a new node 9044 /// with specified return type(s), MachineInstr opcode, and operands. 9045 /// 9046 /// Note that getMachineNode returns the resultant node. If there is already a 9047 /// node of the specified opcode and operands, it returns that node instead of 9048 /// the current one. 9049 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9050 EVT VT) { 9051 SDVTList VTs = getVTList(VT); 9052 return getMachineNode(Opcode, dl, VTs, None); 9053 } 9054 9055 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9056 EVT VT, SDValue Op1) { 9057 SDVTList VTs = getVTList(VT); 9058 SDValue Ops[] = { Op1 }; 9059 return getMachineNode(Opcode, dl, VTs, Ops); 9060 } 9061 9062 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9063 EVT VT, SDValue Op1, SDValue Op2) { 9064 SDVTList VTs = getVTList(VT); 9065 SDValue Ops[] = { Op1, Op2 }; 9066 return getMachineNode(Opcode, dl, VTs, Ops); 9067 } 9068 9069 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9070 EVT VT, SDValue Op1, SDValue Op2, 9071 SDValue Op3) { 9072 SDVTList VTs = getVTList(VT); 9073 SDValue Ops[] = { Op1, Op2, Op3 }; 9074 return getMachineNode(Opcode, dl, VTs, Ops); 9075 } 9076 9077 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9078 EVT VT, ArrayRef<SDValue> Ops) { 9079 SDVTList VTs = getVTList(VT); 9080 return getMachineNode(Opcode, dl, VTs, Ops); 9081 } 9082 9083 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9084 EVT VT1, EVT VT2, SDValue Op1, 9085 SDValue Op2) { 9086 SDVTList VTs = getVTList(VT1, VT2); 9087 SDValue Ops[] = { Op1, Op2 }; 9088 return getMachineNode(Opcode, dl, VTs, Ops); 9089 } 9090 9091 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9092 EVT VT1, EVT VT2, SDValue Op1, 9093 SDValue Op2, SDValue Op3) { 9094 SDVTList VTs = getVTList(VT1, VT2); 9095 SDValue Ops[] = { Op1, Op2, Op3 }; 9096 return getMachineNode(Opcode, dl, VTs, Ops); 9097 } 9098 9099 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9100 EVT VT1, EVT VT2, 9101 ArrayRef<SDValue> Ops) { 9102 SDVTList VTs = getVTList(VT1, VT2); 9103 return getMachineNode(Opcode, dl, VTs, Ops); 9104 } 9105 9106 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9107 EVT VT1, EVT VT2, EVT VT3, 9108 SDValue Op1, SDValue Op2) { 9109 SDVTList VTs = getVTList(VT1, VT2, VT3); 9110 SDValue Ops[] = { Op1, Op2 }; 9111 return getMachineNode(Opcode, dl, VTs, Ops); 9112 } 9113 9114 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9115 EVT VT1, EVT VT2, EVT VT3, 9116 SDValue Op1, SDValue Op2, 9117 SDValue Op3) { 9118 SDVTList VTs = getVTList(VT1, VT2, VT3); 9119 SDValue Ops[] = { Op1, Op2, Op3 }; 9120 return getMachineNode(Opcode, dl, VTs, Ops); 9121 } 9122 9123 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9124 EVT VT1, EVT VT2, EVT VT3, 9125 ArrayRef<SDValue> Ops) { 9126 SDVTList VTs = getVTList(VT1, VT2, VT3); 9127 return getMachineNode(Opcode, dl, VTs, Ops); 9128 } 9129 9130 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9131 ArrayRef<EVT> ResultTys, 9132 ArrayRef<SDValue> Ops) { 9133 SDVTList VTs = getVTList(ResultTys); 9134 return getMachineNode(Opcode, dl, VTs, Ops); 9135 } 9136 9137 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9138 SDVTList VTs, 9139 ArrayRef<SDValue> Ops) { 9140 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9141 MachineSDNode *N; 9142 void *IP = nullptr; 9143 9144 if (DoCSE) { 9145 FoldingSetNodeID ID; 9146 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9147 IP = nullptr; 9148 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9149 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9150 } 9151 } 9152 9153 // Allocate a new MachineSDNode. 9154 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9155 createOperands(N, Ops); 9156 9157 if (DoCSE) 9158 CSEMap.InsertNode(N, IP); 9159 9160 InsertNode(N); 9161 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9162 return N; 9163 } 9164 9165 /// getTargetExtractSubreg - A convenience function for creating 9166 /// TargetOpcode::EXTRACT_SUBREG nodes. 9167 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9168 SDValue Operand) { 9169 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9170 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9171 VT, Operand, SRIdxVal); 9172 return SDValue(Subreg, 0); 9173 } 9174 9175 /// getTargetInsertSubreg - A convenience function for creating 9176 /// TargetOpcode::INSERT_SUBREG nodes. 9177 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9178 SDValue Operand, SDValue Subreg) { 9179 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9180 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9181 VT, Operand, Subreg, SRIdxVal); 9182 return SDValue(Result, 0); 9183 } 9184 9185 /// getNodeIfExists - Get the specified node if it's already available, or 9186 /// else return NULL. 9187 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9188 ArrayRef<SDValue> Ops) { 9189 SDNodeFlags Flags; 9190 if (Inserter) 9191 Flags = Inserter->getFlags(); 9192 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9193 } 9194 9195 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9196 ArrayRef<SDValue> Ops, 9197 const SDNodeFlags Flags) { 9198 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9199 FoldingSetNodeID ID; 9200 AddNodeIDNode(ID, Opcode, VTList, Ops); 9201 void *IP = nullptr; 9202 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9203 E->intersectFlagsWith(Flags); 9204 return E; 9205 } 9206 } 9207 return nullptr; 9208 } 9209 9210 /// doesNodeExist - Check if a node exists without modifying its flags. 9211 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9212 ArrayRef<SDValue> Ops) { 9213 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9214 FoldingSetNodeID ID; 9215 AddNodeIDNode(ID, Opcode, VTList, Ops); 9216 void *IP = nullptr; 9217 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9218 return true; 9219 } 9220 return false; 9221 } 9222 9223 /// getDbgValue - Creates a SDDbgValue node. 9224 /// 9225 /// SDNode 9226 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9227 SDNode *N, unsigned R, bool IsIndirect, 9228 const DebugLoc &DL, unsigned O) { 9229 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9230 "Expected inlined-at fields to agree"); 9231 return new (DbgInfo->getAlloc()) 9232 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9233 {}, IsIndirect, DL, O, 9234 /*IsVariadic=*/false); 9235 } 9236 9237 /// Constant 9238 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9239 DIExpression *Expr, 9240 const Value *C, 9241 const DebugLoc &DL, unsigned O) { 9242 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9243 "Expected inlined-at fields to agree"); 9244 return new (DbgInfo->getAlloc()) 9245 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9246 /*IsIndirect=*/false, DL, O, 9247 /*IsVariadic=*/false); 9248 } 9249 9250 /// FrameIndex 9251 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9252 DIExpression *Expr, unsigned FI, 9253 bool IsIndirect, 9254 const DebugLoc &DL, 9255 unsigned O) { 9256 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9257 "Expected inlined-at fields to agree"); 9258 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9259 } 9260 9261 /// FrameIndex with dependencies 9262 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9263 DIExpression *Expr, unsigned FI, 9264 ArrayRef<SDNode *> Dependencies, 9265 bool IsIndirect, 9266 const DebugLoc &DL, 9267 unsigned O) { 9268 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9269 "Expected inlined-at fields to agree"); 9270 return new (DbgInfo->getAlloc()) 9271 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9272 Dependencies, IsIndirect, DL, O, 9273 /*IsVariadic=*/false); 9274 } 9275 9276 /// VReg 9277 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9278 unsigned VReg, bool IsIndirect, 9279 const DebugLoc &DL, unsigned O) { 9280 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9281 "Expected inlined-at fields to agree"); 9282 return new (DbgInfo->getAlloc()) 9283 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9284 {}, IsIndirect, DL, O, 9285 /*IsVariadic=*/false); 9286 } 9287 9288 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9289 ArrayRef<SDDbgOperand> Locs, 9290 ArrayRef<SDNode *> Dependencies, 9291 bool IsIndirect, const DebugLoc &DL, 9292 unsigned O, bool IsVariadic) { 9293 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9294 "Expected inlined-at fields to agree"); 9295 return new (DbgInfo->getAlloc()) 9296 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9297 DL, O, IsVariadic); 9298 } 9299 9300 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9301 unsigned OffsetInBits, unsigned SizeInBits, 9302 bool InvalidateDbg) { 9303 SDNode *FromNode = From.getNode(); 9304 SDNode *ToNode = To.getNode(); 9305 assert(FromNode && ToNode && "Can't modify dbg values"); 9306 9307 // PR35338 9308 // TODO: assert(From != To && "Redundant dbg value transfer"); 9309 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9310 if (From == To || FromNode == ToNode) 9311 return; 9312 9313 if (!FromNode->getHasDebugValue()) 9314 return; 9315 9316 SDDbgOperand FromLocOp = 9317 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9318 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9319 9320 SmallVector<SDDbgValue *, 2> ClonedDVs; 9321 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9322 if (Dbg->isInvalidated()) 9323 continue; 9324 9325 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9326 9327 // Create a new location ops vector that is equal to the old vector, but 9328 // with each instance of FromLocOp replaced with ToLocOp. 9329 bool Changed = false; 9330 auto NewLocOps = Dbg->copyLocationOps(); 9331 std::replace_if( 9332 NewLocOps.begin(), NewLocOps.end(), 9333 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9334 bool Match = Op == FromLocOp; 9335 Changed |= Match; 9336 return Match; 9337 }, 9338 ToLocOp); 9339 // Ignore this SDDbgValue if we didn't find a matching location. 9340 if (!Changed) 9341 continue; 9342 9343 DIVariable *Var = Dbg->getVariable(); 9344 auto *Expr = Dbg->getExpression(); 9345 // If a fragment is requested, update the expression. 9346 if (SizeInBits) { 9347 // When splitting a larger (e.g., sign-extended) value whose 9348 // lower bits are described with an SDDbgValue, do not attempt 9349 // to transfer the SDDbgValue to the upper bits. 9350 if (auto FI = Expr->getFragmentInfo()) 9351 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9352 continue; 9353 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9354 SizeInBits); 9355 if (!Fragment) 9356 continue; 9357 Expr = *Fragment; 9358 } 9359 9360 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9361 // Clone the SDDbgValue and move it to To. 9362 SDDbgValue *Clone = getDbgValueList( 9363 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9364 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9365 Dbg->isVariadic()); 9366 ClonedDVs.push_back(Clone); 9367 9368 if (InvalidateDbg) { 9369 // Invalidate value and indicate the SDDbgValue should not be emitted. 9370 Dbg->setIsInvalidated(); 9371 Dbg->setIsEmitted(); 9372 } 9373 } 9374 9375 for (SDDbgValue *Dbg : ClonedDVs) { 9376 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9377 "Transferred DbgValues should depend on the new SDNode"); 9378 AddDbgValue(Dbg, false); 9379 } 9380 } 9381 9382 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9383 if (!N.getHasDebugValue()) 9384 return; 9385 9386 SmallVector<SDDbgValue *, 2> ClonedDVs; 9387 for (auto DV : GetDbgValues(&N)) { 9388 if (DV->isInvalidated()) 9389 continue; 9390 switch (N.getOpcode()) { 9391 default: 9392 break; 9393 case ISD::ADD: 9394 SDValue N0 = N.getOperand(0); 9395 SDValue N1 = N.getOperand(1); 9396 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9397 isConstantIntBuildVectorOrConstantInt(N1)) { 9398 uint64_t Offset = N.getConstantOperandVal(1); 9399 9400 // Rewrite an ADD constant node into a DIExpression. Since we are 9401 // performing arithmetic to compute the variable's *value* in the 9402 // DIExpression, we need to mark the expression with a 9403 // DW_OP_stack_value. 9404 auto *DIExpr = DV->getExpression(); 9405 auto NewLocOps = DV->copyLocationOps(); 9406 bool Changed = false; 9407 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9408 // We're not given a ResNo to compare against because the whole 9409 // node is going away. We know that any ISD::ADD only has one 9410 // result, so we can assume any node match is using the result. 9411 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9412 NewLocOps[i].getSDNode() != &N) 9413 continue; 9414 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9415 SmallVector<uint64_t, 3> ExprOps; 9416 DIExpression::appendOffset(ExprOps, Offset); 9417 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9418 Changed = true; 9419 } 9420 (void)Changed; 9421 assert(Changed && "Salvage target doesn't use N"); 9422 9423 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9424 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9425 NewLocOps, AdditionalDependencies, 9426 DV->isIndirect(), DV->getDebugLoc(), 9427 DV->getOrder(), DV->isVariadic()); 9428 ClonedDVs.push_back(Clone); 9429 DV->setIsInvalidated(); 9430 DV->setIsEmitted(); 9431 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9432 N0.getNode()->dumprFull(this); 9433 dbgs() << " into " << *DIExpr << '\n'); 9434 } 9435 } 9436 } 9437 9438 for (SDDbgValue *Dbg : ClonedDVs) { 9439 assert(!Dbg->getSDNodes().empty() && 9440 "Salvaged DbgValue should depend on a new SDNode"); 9441 AddDbgValue(Dbg, false); 9442 } 9443 } 9444 9445 /// Creates a SDDbgLabel node. 9446 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9447 const DebugLoc &DL, unsigned O) { 9448 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9449 "Expected inlined-at fields to agree"); 9450 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9451 } 9452 9453 namespace { 9454 9455 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9456 /// pointed to by a use iterator is deleted, increment the use iterator 9457 /// so that it doesn't dangle. 9458 /// 9459 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9460 SDNode::use_iterator &UI; 9461 SDNode::use_iterator &UE; 9462 9463 void NodeDeleted(SDNode *N, SDNode *E) override { 9464 // Increment the iterator as needed. 9465 while (UI != UE && N == *UI) 9466 ++UI; 9467 } 9468 9469 public: 9470 RAUWUpdateListener(SelectionDAG &d, 9471 SDNode::use_iterator &ui, 9472 SDNode::use_iterator &ue) 9473 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9474 }; 9475 9476 } // end anonymous namespace 9477 9478 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9479 /// This can cause recursive merging of nodes in the DAG. 9480 /// 9481 /// This version assumes From has a single result value. 9482 /// 9483 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9484 SDNode *From = FromN.getNode(); 9485 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9486 "Cannot replace with this method!"); 9487 assert(From != To.getNode() && "Cannot replace uses of with self"); 9488 9489 // Preserve Debug Values 9490 transferDbgValues(FromN, To); 9491 9492 // Iterate over all the existing uses of From. New uses will be added 9493 // to the beginning of the use list, which we avoid visiting. 9494 // This specifically avoids visiting uses of From that arise while the 9495 // replacement is happening, because any such uses would be the result 9496 // of CSE: If an existing node looks like From after one of its operands 9497 // is replaced by To, we don't want to replace of all its users with To 9498 // too. See PR3018 for more info. 9499 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9500 RAUWUpdateListener Listener(*this, UI, UE); 9501 while (UI != UE) { 9502 SDNode *User = *UI; 9503 9504 // This node is about to morph, remove its old self from the CSE maps. 9505 RemoveNodeFromCSEMaps(User); 9506 9507 // A user can appear in a use list multiple times, and when this 9508 // happens the uses are usually next to each other in the list. 9509 // To help reduce the number of CSE recomputations, process all 9510 // the uses of this user that we can find this way. 9511 do { 9512 SDUse &Use = UI.getUse(); 9513 ++UI; 9514 Use.set(To); 9515 if (To->isDivergent() != From->isDivergent()) 9516 updateDivergence(User); 9517 } while (UI != UE && *UI == User); 9518 // Now that we have modified User, add it back to the CSE maps. If it 9519 // already exists there, recursively merge the results together. 9520 AddModifiedNodeToCSEMaps(User); 9521 } 9522 9523 // If we just RAUW'd the root, take note. 9524 if (FromN == getRoot()) 9525 setRoot(To); 9526 } 9527 9528 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9529 /// This can cause recursive merging of nodes in the DAG. 9530 /// 9531 /// This version assumes that for each value of From, there is a 9532 /// corresponding value in To in the same position with the same type. 9533 /// 9534 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9535 #ifndef NDEBUG 9536 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9537 assert((!From->hasAnyUseOfValue(i) || 9538 From->getValueType(i) == To->getValueType(i)) && 9539 "Cannot use this version of ReplaceAllUsesWith!"); 9540 #endif 9541 9542 // Handle the trivial case. 9543 if (From == To) 9544 return; 9545 9546 // Preserve Debug Info. Only do this if there's a use. 9547 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9548 if (From->hasAnyUseOfValue(i)) { 9549 assert((i < To->getNumValues()) && "Invalid To location"); 9550 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9551 } 9552 9553 // Iterate over just the existing users of From. See the comments in 9554 // the ReplaceAllUsesWith above. 9555 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9556 RAUWUpdateListener Listener(*this, UI, UE); 9557 while (UI != UE) { 9558 SDNode *User = *UI; 9559 9560 // This node is about to morph, remove its old self from the CSE maps. 9561 RemoveNodeFromCSEMaps(User); 9562 9563 // A user can appear in a use list multiple times, and when this 9564 // happens the uses are usually next to each other in the list. 9565 // To help reduce the number of CSE recomputations, process all 9566 // the uses of this user that we can find this way. 9567 do { 9568 SDUse &Use = UI.getUse(); 9569 ++UI; 9570 Use.setNode(To); 9571 if (To->isDivergent() != From->isDivergent()) 9572 updateDivergence(User); 9573 } while (UI != UE && *UI == User); 9574 9575 // Now that we have modified User, add it back to the CSE maps. If it 9576 // already exists there, recursively merge the results together. 9577 AddModifiedNodeToCSEMaps(User); 9578 } 9579 9580 // If we just RAUW'd the root, take note. 9581 if (From == getRoot().getNode()) 9582 setRoot(SDValue(To, getRoot().getResNo())); 9583 } 9584 9585 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9586 /// This can cause recursive merging of nodes in the DAG. 9587 /// 9588 /// This version can replace From with any result values. To must match the 9589 /// number and types of values returned by From. 9590 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9591 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9592 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9593 9594 // Preserve Debug Info. 9595 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9596 transferDbgValues(SDValue(From, i), To[i]); 9597 9598 // Iterate over just the existing users of From. See the comments in 9599 // the ReplaceAllUsesWith above. 9600 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9601 RAUWUpdateListener Listener(*this, UI, UE); 9602 while (UI != UE) { 9603 SDNode *User = *UI; 9604 9605 // This node is about to morph, remove its old self from the CSE maps. 9606 RemoveNodeFromCSEMaps(User); 9607 9608 // A user can appear in a use list multiple times, and when this happens the 9609 // uses are usually next to each other in the list. To help reduce the 9610 // number of CSE and divergence recomputations, process all the uses of this 9611 // user that we can find this way. 9612 bool To_IsDivergent = false; 9613 do { 9614 SDUse &Use = UI.getUse(); 9615 const SDValue &ToOp = To[Use.getResNo()]; 9616 ++UI; 9617 Use.set(ToOp); 9618 To_IsDivergent |= ToOp->isDivergent(); 9619 } while (UI != UE && *UI == User); 9620 9621 if (To_IsDivergent != From->isDivergent()) 9622 updateDivergence(User); 9623 9624 // Now that we have modified User, add it back to the CSE maps. If it 9625 // already exists there, recursively merge the results together. 9626 AddModifiedNodeToCSEMaps(User); 9627 } 9628 9629 // If we just RAUW'd the root, take note. 9630 if (From == getRoot().getNode()) 9631 setRoot(SDValue(To[getRoot().getResNo()])); 9632 } 9633 9634 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 9635 /// uses of other values produced by From.getNode() alone. The Deleted 9636 /// vector is handled the same way as for ReplaceAllUsesWith. 9637 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 9638 // Handle the really simple, really trivial case efficiently. 9639 if (From == To) return; 9640 9641 // Handle the simple, trivial, case efficiently. 9642 if (From.getNode()->getNumValues() == 1) { 9643 ReplaceAllUsesWith(From, To); 9644 return; 9645 } 9646 9647 // Preserve Debug Info. 9648 transferDbgValues(From, To); 9649 9650 // Iterate over just the existing users of From. See the comments in 9651 // the ReplaceAllUsesWith above. 9652 SDNode::use_iterator UI = From.getNode()->use_begin(), 9653 UE = From.getNode()->use_end(); 9654 RAUWUpdateListener Listener(*this, UI, UE); 9655 while (UI != UE) { 9656 SDNode *User = *UI; 9657 bool UserRemovedFromCSEMaps = false; 9658 9659 // A user can appear in a use list multiple times, and when this 9660 // happens the uses are usually next to each other in the list. 9661 // To help reduce the number of CSE recomputations, process all 9662 // the uses of this user that we can find this way. 9663 do { 9664 SDUse &Use = UI.getUse(); 9665 9666 // Skip uses of different values from the same node. 9667 if (Use.getResNo() != From.getResNo()) { 9668 ++UI; 9669 continue; 9670 } 9671 9672 // If this node hasn't been modified yet, it's still in the CSE maps, 9673 // so remove its old self from the CSE maps. 9674 if (!UserRemovedFromCSEMaps) { 9675 RemoveNodeFromCSEMaps(User); 9676 UserRemovedFromCSEMaps = true; 9677 } 9678 9679 ++UI; 9680 Use.set(To); 9681 if (To->isDivergent() != From->isDivergent()) 9682 updateDivergence(User); 9683 } while (UI != UE && *UI == User); 9684 // We are iterating over all uses of the From node, so if a use 9685 // doesn't use the specific value, no changes are made. 9686 if (!UserRemovedFromCSEMaps) 9687 continue; 9688 9689 // Now that we have modified User, add it back to the CSE maps. If it 9690 // already exists there, recursively merge the results together. 9691 AddModifiedNodeToCSEMaps(User); 9692 } 9693 9694 // If we just RAUW'd the root, take note. 9695 if (From == getRoot()) 9696 setRoot(To); 9697 } 9698 9699 namespace { 9700 9701 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 9702 /// to record information about a use. 9703 struct UseMemo { 9704 SDNode *User; 9705 unsigned Index; 9706 SDUse *Use; 9707 }; 9708 9709 /// operator< - Sort Memos by User. 9710 bool operator<(const UseMemo &L, const UseMemo &R) { 9711 return (intptr_t)L.User < (intptr_t)R.User; 9712 } 9713 9714 } // end anonymous namespace 9715 9716 bool SelectionDAG::calculateDivergence(SDNode *N) { 9717 if (TLI->isSDNodeAlwaysUniform(N)) { 9718 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 9719 "Conflicting divergence information!"); 9720 return false; 9721 } 9722 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 9723 return true; 9724 for (auto &Op : N->ops()) { 9725 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 9726 return true; 9727 } 9728 return false; 9729 } 9730 9731 void SelectionDAG::updateDivergence(SDNode *N) { 9732 SmallVector<SDNode *, 16> Worklist(1, N); 9733 do { 9734 N = Worklist.pop_back_val(); 9735 bool IsDivergent = calculateDivergence(N); 9736 if (N->SDNodeBits.IsDivergent != IsDivergent) { 9737 N->SDNodeBits.IsDivergent = IsDivergent; 9738 llvm::append_range(Worklist, N->uses()); 9739 } 9740 } while (!Worklist.empty()); 9741 } 9742 9743 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 9744 DenseMap<SDNode *, unsigned> Degree; 9745 Order.reserve(AllNodes.size()); 9746 for (auto &N : allnodes()) { 9747 unsigned NOps = N.getNumOperands(); 9748 Degree[&N] = NOps; 9749 if (0 == NOps) 9750 Order.push_back(&N); 9751 } 9752 for (size_t I = 0; I != Order.size(); ++I) { 9753 SDNode *N = Order[I]; 9754 for (auto U : N->uses()) { 9755 unsigned &UnsortedOps = Degree[U]; 9756 if (0 == --UnsortedOps) 9757 Order.push_back(U); 9758 } 9759 } 9760 } 9761 9762 #ifndef NDEBUG 9763 void SelectionDAG::VerifyDAGDivergence() { 9764 std::vector<SDNode *> TopoOrder; 9765 CreateTopologicalOrder(TopoOrder); 9766 for (auto *N : TopoOrder) { 9767 assert(calculateDivergence(N) == N->isDivergent() && 9768 "Divergence bit inconsistency detected"); 9769 } 9770 } 9771 #endif 9772 9773 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 9774 /// uses of other values produced by From.getNode() alone. The same value 9775 /// may appear in both the From and To list. The Deleted vector is 9776 /// handled the same way as for ReplaceAllUsesWith. 9777 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 9778 const SDValue *To, 9779 unsigned Num){ 9780 // Handle the simple, trivial case efficiently. 9781 if (Num == 1) 9782 return ReplaceAllUsesOfValueWith(*From, *To); 9783 9784 transferDbgValues(*From, *To); 9785 9786 // Read up all the uses and make records of them. This helps 9787 // processing new uses that are introduced during the 9788 // replacement process. 9789 SmallVector<UseMemo, 4> Uses; 9790 for (unsigned i = 0; i != Num; ++i) { 9791 unsigned FromResNo = From[i].getResNo(); 9792 SDNode *FromNode = From[i].getNode(); 9793 for (SDNode::use_iterator UI = FromNode->use_begin(), 9794 E = FromNode->use_end(); UI != E; ++UI) { 9795 SDUse &Use = UI.getUse(); 9796 if (Use.getResNo() == FromResNo) { 9797 UseMemo Memo = { *UI, i, &Use }; 9798 Uses.push_back(Memo); 9799 } 9800 } 9801 } 9802 9803 // Sort the uses, so that all the uses from a given User are together. 9804 llvm::sort(Uses); 9805 9806 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 9807 UseIndex != UseIndexEnd; ) { 9808 // We know that this user uses some value of From. If it is the right 9809 // value, update it. 9810 SDNode *User = Uses[UseIndex].User; 9811 9812 // This node is about to morph, remove its old self from the CSE maps. 9813 RemoveNodeFromCSEMaps(User); 9814 9815 // The Uses array is sorted, so all the uses for a given User 9816 // are next to each other in the list. 9817 // To help reduce the number of CSE recomputations, process all 9818 // the uses of this user that we can find this way. 9819 do { 9820 unsigned i = Uses[UseIndex].Index; 9821 SDUse &Use = *Uses[UseIndex].Use; 9822 ++UseIndex; 9823 9824 Use.set(To[i]); 9825 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 9826 9827 // Now that we have modified User, add it back to the CSE maps. If it 9828 // already exists there, recursively merge the results together. 9829 AddModifiedNodeToCSEMaps(User); 9830 } 9831 } 9832 9833 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 9834 /// based on their topological order. It returns the maximum id and a vector 9835 /// of the SDNodes* in assigned order by reference. 9836 unsigned SelectionDAG::AssignTopologicalOrder() { 9837 unsigned DAGSize = 0; 9838 9839 // SortedPos tracks the progress of the algorithm. Nodes before it are 9840 // sorted, nodes after it are unsorted. When the algorithm completes 9841 // it is at the end of the list. 9842 allnodes_iterator SortedPos = allnodes_begin(); 9843 9844 // Visit all the nodes. Move nodes with no operands to the front of 9845 // the list immediately. Annotate nodes that do have operands with their 9846 // operand count. Before we do this, the Node Id fields of the nodes 9847 // may contain arbitrary values. After, the Node Id fields for nodes 9848 // before SortedPos will contain the topological sort index, and the 9849 // Node Id fields for nodes At SortedPos and after will contain the 9850 // count of outstanding operands. 9851 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 9852 checkForCycles(&N, this); 9853 unsigned Degree = N.getNumOperands(); 9854 if (Degree == 0) { 9855 // A node with no uses, add it to the result array immediately. 9856 N.setNodeId(DAGSize++); 9857 allnodes_iterator Q(&N); 9858 if (Q != SortedPos) 9859 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 9860 assert(SortedPos != AllNodes.end() && "Overran node list"); 9861 ++SortedPos; 9862 } else { 9863 // Temporarily use the Node Id as scratch space for the degree count. 9864 N.setNodeId(Degree); 9865 } 9866 } 9867 9868 // Visit all the nodes. As we iterate, move nodes into sorted order, 9869 // such that by the time the end is reached all nodes will be sorted. 9870 for (SDNode &Node : allnodes()) { 9871 SDNode *N = &Node; 9872 checkForCycles(N, this); 9873 // N is in sorted position, so all its uses have one less operand 9874 // that needs to be sorted. 9875 for (SDNode *P : N->uses()) { 9876 unsigned Degree = P->getNodeId(); 9877 assert(Degree != 0 && "Invalid node degree"); 9878 --Degree; 9879 if (Degree == 0) { 9880 // All of P's operands are sorted, so P may sorted now. 9881 P->setNodeId(DAGSize++); 9882 if (P->getIterator() != SortedPos) 9883 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9884 assert(SortedPos != AllNodes.end() && "Overran node list"); 9885 ++SortedPos; 9886 } else { 9887 // Update P's outstanding operand count. 9888 P->setNodeId(Degree); 9889 } 9890 } 9891 if (Node.getIterator() == SortedPos) { 9892 #ifndef NDEBUG 9893 allnodes_iterator I(N); 9894 SDNode *S = &*++I; 9895 dbgs() << "Overran sorted position:\n"; 9896 S->dumprFull(this); dbgs() << "\n"; 9897 dbgs() << "Checking if this is due to cycles\n"; 9898 checkForCycles(this, true); 9899 #endif 9900 llvm_unreachable(nullptr); 9901 } 9902 } 9903 9904 assert(SortedPos == AllNodes.end() && 9905 "Topological sort incomplete!"); 9906 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9907 "First node in topological sort is not the entry token!"); 9908 assert(AllNodes.front().getNodeId() == 0 && 9909 "First node in topological sort has non-zero id!"); 9910 assert(AllNodes.front().getNumOperands() == 0 && 9911 "First node in topological sort has operands!"); 9912 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9913 "Last node in topologic sort has unexpected id!"); 9914 assert(AllNodes.back().use_empty() && 9915 "Last node in topologic sort has users!"); 9916 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9917 return DAGSize; 9918 } 9919 9920 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9921 /// value is produced by SD. 9922 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 9923 for (SDNode *SD : DB->getSDNodes()) { 9924 if (!SD) 9925 continue; 9926 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9927 SD->setHasDebugValue(true); 9928 } 9929 DbgInfo->add(DB, isParameter); 9930 } 9931 9932 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 9933 9934 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9935 SDValue NewMemOpChain) { 9936 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9937 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9938 // The new memory operation must have the same position as the old load in 9939 // terms of memory dependency. Create a TokenFactor for the old load and new 9940 // memory operation and update uses of the old load's output chain to use that 9941 // TokenFactor. 9942 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9943 return NewMemOpChain; 9944 9945 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9946 OldChain, NewMemOpChain); 9947 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9948 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9949 return TokenFactor; 9950 } 9951 9952 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9953 SDValue NewMemOp) { 9954 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9955 SDValue OldChain = SDValue(OldLoad, 1); 9956 SDValue NewMemOpChain = NewMemOp.getValue(1); 9957 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9958 } 9959 9960 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9961 Function **OutFunction) { 9962 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9963 9964 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9965 auto *Module = MF->getFunction().getParent(); 9966 auto *Function = Module->getFunction(Symbol); 9967 9968 if (OutFunction != nullptr) 9969 *OutFunction = Function; 9970 9971 if (Function != nullptr) { 9972 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9973 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9974 } 9975 9976 std::string ErrorStr; 9977 raw_string_ostream ErrorFormatter(ErrorStr); 9978 ErrorFormatter << "Undefined external symbol "; 9979 ErrorFormatter << '"' << Symbol << '"'; 9980 report_fatal_error(Twine(ErrorFormatter.str())); 9981 } 9982 9983 //===----------------------------------------------------------------------===// 9984 // SDNode Class 9985 //===----------------------------------------------------------------------===// 9986 9987 bool llvm::isNullConstant(SDValue V) { 9988 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9989 return Const != nullptr && Const->isZero(); 9990 } 9991 9992 bool llvm::isNullFPConstant(SDValue V) { 9993 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9994 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9995 } 9996 9997 bool llvm::isAllOnesConstant(SDValue V) { 9998 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9999 return Const != nullptr && Const->isAllOnes(); 10000 } 10001 10002 bool llvm::isOneConstant(SDValue V) { 10003 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 10004 return Const != nullptr && Const->isOne(); 10005 } 10006 10007 SDValue llvm::peekThroughBitcasts(SDValue V) { 10008 while (V.getOpcode() == ISD::BITCAST) 10009 V = V.getOperand(0); 10010 return V; 10011 } 10012 10013 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 10014 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 10015 V = V.getOperand(0); 10016 return V; 10017 } 10018 10019 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 10020 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 10021 V = V.getOperand(0); 10022 return V; 10023 } 10024 10025 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 10026 if (V.getOpcode() != ISD::XOR) 10027 return false; 10028 V = peekThroughBitcasts(V.getOperand(1)); 10029 unsigned NumBits = V.getScalarValueSizeInBits(); 10030 ConstantSDNode *C = 10031 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 10032 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 10033 } 10034 10035 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 10036 bool AllowTruncation) { 10037 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10038 return CN; 10039 10040 // SplatVectors can truncate their operands. Ignore that case here unless 10041 // AllowTruncation is set. 10042 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 10043 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 10044 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 10045 EVT CVT = CN->getValueType(0); 10046 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 10047 if (AllowTruncation || CVT == VecEltVT) 10048 return CN; 10049 } 10050 } 10051 10052 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10053 BitVector UndefElements; 10054 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10055 10056 // BuildVectors can truncate their operands. Ignore that case here unless 10057 // AllowTruncation is set. 10058 if (CN && (UndefElements.none() || AllowUndefs)) { 10059 EVT CVT = CN->getValueType(0); 10060 EVT NSVT = N.getValueType().getScalarType(); 10061 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10062 if (AllowTruncation || (CVT == NSVT)) 10063 return CN; 10064 } 10065 } 10066 10067 return nullptr; 10068 } 10069 10070 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10071 bool AllowUndefs, 10072 bool AllowTruncation) { 10073 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10074 return CN; 10075 10076 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10077 BitVector UndefElements; 10078 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10079 10080 // BuildVectors can truncate their operands. Ignore that case here unless 10081 // AllowTruncation is set. 10082 if (CN && (UndefElements.none() || AllowUndefs)) { 10083 EVT CVT = CN->getValueType(0); 10084 EVT NSVT = N.getValueType().getScalarType(); 10085 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10086 if (AllowTruncation || (CVT == NSVT)) 10087 return CN; 10088 } 10089 } 10090 10091 return nullptr; 10092 } 10093 10094 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10095 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10096 return CN; 10097 10098 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10099 BitVector UndefElements; 10100 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10101 if (CN && (UndefElements.none() || AllowUndefs)) 10102 return CN; 10103 } 10104 10105 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10106 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10107 return CN; 10108 10109 return nullptr; 10110 } 10111 10112 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10113 const APInt &DemandedElts, 10114 bool AllowUndefs) { 10115 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10116 return CN; 10117 10118 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10119 BitVector UndefElements; 10120 ConstantFPSDNode *CN = 10121 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10122 if (CN && (UndefElements.none() || AllowUndefs)) 10123 return CN; 10124 } 10125 10126 return nullptr; 10127 } 10128 10129 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10130 // TODO: may want to use peekThroughBitcast() here. 10131 ConstantSDNode *C = 10132 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10133 return C && C->isZero(); 10134 } 10135 10136 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10137 // TODO: may want to use peekThroughBitcast() here. 10138 unsigned BitWidth = N.getScalarValueSizeInBits(); 10139 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10140 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10141 } 10142 10143 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10144 N = peekThroughBitcasts(N); 10145 unsigned BitWidth = N.getScalarValueSizeInBits(); 10146 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10147 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10148 } 10149 10150 HandleSDNode::~HandleSDNode() { 10151 DropOperands(); 10152 } 10153 10154 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10155 const DebugLoc &DL, 10156 const GlobalValue *GA, EVT VT, 10157 int64_t o, unsigned TF) 10158 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10159 TheGlobal = GA; 10160 } 10161 10162 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10163 EVT VT, unsigned SrcAS, 10164 unsigned DestAS) 10165 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10166 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10167 10168 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10169 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10170 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10171 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10172 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10173 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10174 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10175 10176 // We check here that the size of the memory operand fits within the size of 10177 // the MMO. This is because the MMO might indicate only a possible address 10178 // range instead of specifying the affected memory addresses precisely. 10179 // TODO: Make MachineMemOperands aware of scalable vectors. 10180 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10181 "Size mismatch!"); 10182 } 10183 10184 /// Profile - Gather unique data for the node. 10185 /// 10186 void SDNode::Profile(FoldingSetNodeID &ID) const { 10187 AddNodeIDNode(ID, this); 10188 } 10189 10190 namespace { 10191 10192 struct EVTArray { 10193 std::vector<EVT> VTs; 10194 10195 EVTArray() { 10196 VTs.reserve(MVT::VALUETYPE_SIZE); 10197 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10198 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10199 } 10200 }; 10201 10202 } // end anonymous namespace 10203 10204 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10205 static ManagedStatic<EVTArray> SimpleVTArray; 10206 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10207 10208 /// getValueTypeList - Return a pointer to the specified value type. 10209 /// 10210 const EVT *SDNode::getValueTypeList(EVT VT) { 10211 if (VT.isExtended()) { 10212 sys::SmartScopedLock<true> Lock(*VTMutex); 10213 return &(*EVTs->insert(VT).first); 10214 } 10215 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10216 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10217 } 10218 10219 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10220 /// indicated value. This method ignores uses of other values defined by this 10221 /// operation. 10222 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10223 assert(Value < getNumValues() && "Bad value!"); 10224 10225 // TODO: Only iterate over uses of a given value of the node 10226 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10227 if (UI.getUse().getResNo() == Value) { 10228 if (NUses == 0) 10229 return false; 10230 --NUses; 10231 } 10232 } 10233 10234 // Found exactly the right number of uses? 10235 return NUses == 0; 10236 } 10237 10238 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10239 /// value. This method ignores uses of other values defined by this operation. 10240 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10241 assert(Value < getNumValues() && "Bad value!"); 10242 10243 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10244 if (UI.getUse().getResNo() == Value) 10245 return true; 10246 10247 return false; 10248 } 10249 10250 /// isOnlyUserOf - Return true if this node is the only use of N. 10251 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10252 bool Seen = false; 10253 for (const SDNode *User : N->uses()) { 10254 if (User == this) 10255 Seen = true; 10256 else 10257 return false; 10258 } 10259 10260 return Seen; 10261 } 10262 10263 /// Return true if the only users of N are contained in Nodes. 10264 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10265 bool Seen = false; 10266 for (const SDNode *User : N->uses()) { 10267 if (llvm::is_contained(Nodes, User)) 10268 Seen = true; 10269 else 10270 return false; 10271 } 10272 10273 return Seen; 10274 } 10275 10276 /// isOperand - Return true if this node is an operand of N. 10277 bool SDValue::isOperandOf(const SDNode *N) const { 10278 return is_contained(N->op_values(), *this); 10279 } 10280 10281 bool SDNode::isOperandOf(const SDNode *N) const { 10282 return any_of(N->op_values(), 10283 [this](SDValue Op) { return this == Op.getNode(); }); 10284 } 10285 10286 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10287 /// be a chain) reaches the specified operand without crossing any 10288 /// side-effecting instructions on any chain path. In practice, this looks 10289 /// through token factors and non-volatile loads. In order to remain efficient, 10290 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10291 /// 10292 /// Note that we only need to examine chains when we're searching for 10293 /// side-effects; SelectionDAG requires that all side-effects are represented 10294 /// by chains, even if another operand would force a specific ordering. This 10295 /// constraint is necessary to allow transformations like splitting loads. 10296 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10297 unsigned Depth) const { 10298 if (*this == Dest) return true; 10299 10300 // Don't search too deeply, we just want to be able to see through 10301 // TokenFactor's etc. 10302 if (Depth == 0) return false; 10303 10304 // If this is a token factor, all inputs to the TF happen in parallel. 10305 if (getOpcode() == ISD::TokenFactor) { 10306 // First, try a shallow search. 10307 if (is_contained((*this)->ops(), Dest)) { 10308 // We found the chain we want as an operand of this TokenFactor. 10309 // Essentially, we reach the chain without side-effects if we could 10310 // serialize the TokenFactor into a simple chain of operations with 10311 // Dest as the last operation. This is automatically true if the 10312 // chain has one use: there are no other ordering constraints. 10313 // If the chain has more than one use, we give up: some other 10314 // use of Dest might force a side-effect between Dest and the current 10315 // node. 10316 if (Dest.hasOneUse()) 10317 return true; 10318 } 10319 // Next, try a deep search: check whether every operand of the TokenFactor 10320 // reaches Dest. 10321 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10322 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10323 }); 10324 } 10325 10326 // Loads don't have side effects, look through them. 10327 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10328 if (Ld->isUnordered()) 10329 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10330 } 10331 return false; 10332 } 10333 10334 bool SDNode::hasPredecessor(const SDNode *N) const { 10335 SmallPtrSet<const SDNode *, 32> Visited; 10336 SmallVector<const SDNode *, 16> Worklist; 10337 Worklist.push_back(this); 10338 return hasPredecessorHelper(N, Visited, Worklist); 10339 } 10340 10341 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10342 this->Flags.intersectWith(Flags); 10343 } 10344 10345 SDValue 10346 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10347 ArrayRef<ISD::NodeType> CandidateBinOps, 10348 bool AllowPartials) { 10349 // The pattern must end in an extract from index 0. 10350 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10351 !isNullConstant(Extract->getOperand(1))) 10352 return SDValue(); 10353 10354 // Match against one of the candidate binary ops. 10355 SDValue Op = Extract->getOperand(0); 10356 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10357 return Op.getOpcode() == unsigned(BinOp); 10358 })) 10359 return SDValue(); 10360 10361 // Floating-point reductions may require relaxed constraints on the final step 10362 // of the reduction because they may reorder intermediate operations. 10363 unsigned CandidateBinOp = Op.getOpcode(); 10364 if (Op.getValueType().isFloatingPoint()) { 10365 SDNodeFlags Flags = Op->getFlags(); 10366 switch (CandidateBinOp) { 10367 case ISD::FADD: 10368 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10369 return SDValue(); 10370 break; 10371 default: 10372 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10373 } 10374 } 10375 10376 // Matching failed - attempt to see if we did enough stages that a partial 10377 // reduction from a subvector is possible. 10378 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10379 if (!AllowPartials || !Op) 10380 return SDValue(); 10381 EVT OpVT = Op.getValueType(); 10382 EVT OpSVT = OpVT.getScalarType(); 10383 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10384 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10385 return SDValue(); 10386 BinOp = (ISD::NodeType)CandidateBinOp; 10387 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10388 getVectorIdxConstant(0, SDLoc(Op))); 10389 }; 10390 10391 // At each stage, we're looking for something that looks like: 10392 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10393 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10394 // i32 undef, i32 undef, i32 undef, i32 undef> 10395 // %a = binop <8 x i32> %op, %s 10396 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10397 // we expect something like: 10398 // <4,5,6,7,u,u,u,u> 10399 // <2,3,u,u,u,u,u,u> 10400 // <1,u,u,u,u,u,u,u> 10401 // While a partial reduction match would be: 10402 // <2,3,u,u,u,u,u,u> 10403 // <1,u,u,u,u,u,u,u> 10404 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10405 SDValue PrevOp; 10406 for (unsigned i = 0; i < Stages; ++i) { 10407 unsigned MaskEnd = (1 << i); 10408 10409 if (Op.getOpcode() != CandidateBinOp) 10410 return PartialReduction(PrevOp, MaskEnd); 10411 10412 SDValue Op0 = Op.getOperand(0); 10413 SDValue Op1 = Op.getOperand(1); 10414 10415 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10416 if (Shuffle) { 10417 Op = Op1; 10418 } else { 10419 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10420 Op = Op0; 10421 } 10422 10423 // The first operand of the shuffle should be the same as the other operand 10424 // of the binop. 10425 if (!Shuffle || Shuffle->getOperand(0) != Op) 10426 return PartialReduction(PrevOp, MaskEnd); 10427 10428 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10429 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10430 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10431 return PartialReduction(PrevOp, MaskEnd); 10432 10433 PrevOp = Op; 10434 } 10435 10436 // Handle subvector reductions, which tend to appear after the shuffle 10437 // reduction stages. 10438 while (Op.getOpcode() == CandidateBinOp) { 10439 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10440 SDValue Op0 = Op.getOperand(0); 10441 SDValue Op1 = Op.getOperand(1); 10442 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10443 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10444 Op0.getOperand(0) != Op1.getOperand(0)) 10445 break; 10446 SDValue Src = Op0.getOperand(0); 10447 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10448 if (NumSrcElts != (2 * NumElts)) 10449 break; 10450 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10451 Op1.getConstantOperandAPInt(1) == NumElts) && 10452 !(Op1.getConstantOperandAPInt(1) == 0 && 10453 Op0.getConstantOperandAPInt(1) == NumElts)) 10454 break; 10455 Op = Src; 10456 } 10457 10458 BinOp = (ISD::NodeType)CandidateBinOp; 10459 return Op; 10460 } 10461 10462 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10463 assert(N->getNumValues() == 1 && 10464 "Can't unroll a vector with multiple results!"); 10465 10466 EVT VT = N->getValueType(0); 10467 unsigned NE = VT.getVectorNumElements(); 10468 EVT EltVT = VT.getVectorElementType(); 10469 SDLoc dl(N); 10470 10471 SmallVector<SDValue, 8> Scalars; 10472 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10473 10474 // If ResNE is 0, fully unroll the vector op. 10475 if (ResNE == 0) 10476 ResNE = NE; 10477 else if (NE > ResNE) 10478 NE = ResNE; 10479 10480 unsigned i; 10481 for (i= 0; i != NE; ++i) { 10482 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10483 SDValue Operand = N->getOperand(j); 10484 EVT OperandVT = Operand.getValueType(); 10485 if (OperandVT.isVector()) { 10486 // A vector operand; extract a single element. 10487 EVT OperandEltVT = OperandVT.getVectorElementType(); 10488 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10489 Operand, getVectorIdxConstant(i, dl)); 10490 } else { 10491 // A scalar operand; just use it as is. 10492 Operands[j] = Operand; 10493 } 10494 } 10495 10496 switch (N->getOpcode()) { 10497 default: { 10498 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10499 N->getFlags())); 10500 break; 10501 } 10502 case ISD::VSELECT: 10503 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10504 break; 10505 case ISD::SHL: 10506 case ISD::SRA: 10507 case ISD::SRL: 10508 case ISD::ROTL: 10509 case ISD::ROTR: 10510 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10511 getShiftAmountOperand(Operands[0].getValueType(), 10512 Operands[1]))); 10513 break; 10514 case ISD::SIGN_EXTEND_INREG: { 10515 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10516 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10517 Operands[0], 10518 getValueType(ExtVT))); 10519 } 10520 } 10521 } 10522 10523 for (; i < ResNE; ++i) 10524 Scalars.push_back(getUNDEF(EltVT)); 10525 10526 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10527 return getBuildVector(VecVT, dl, Scalars); 10528 } 10529 10530 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10531 SDNode *N, unsigned ResNE) { 10532 unsigned Opcode = N->getOpcode(); 10533 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10534 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10535 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10536 "Expected an overflow opcode"); 10537 10538 EVT ResVT = N->getValueType(0); 10539 EVT OvVT = N->getValueType(1); 10540 EVT ResEltVT = ResVT.getVectorElementType(); 10541 EVT OvEltVT = OvVT.getVectorElementType(); 10542 SDLoc dl(N); 10543 10544 // If ResNE is 0, fully unroll the vector op. 10545 unsigned NE = ResVT.getVectorNumElements(); 10546 if (ResNE == 0) 10547 ResNE = NE; 10548 else if (NE > ResNE) 10549 NE = ResNE; 10550 10551 SmallVector<SDValue, 8> LHSScalars; 10552 SmallVector<SDValue, 8> RHSScalars; 10553 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10554 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10555 10556 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10557 SDVTList VTs = getVTList(ResEltVT, SVT); 10558 SmallVector<SDValue, 8> ResScalars; 10559 SmallVector<SDValue, 8> OvScalars; 10560 for (unsigned i = 0; i < NE; ++i) { 10561 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10562 SDValue Ov = 10563 getSelect(dl, OvEltVT, Res.getValue(1), 10564 getBoolConstant(true, dl, OvEltVT, ResVT), 10565 getConstant(0, dl, OvEltVT)); 10566 10567 ResScalars.push_back(Res); 10568 OvScalars.push_back(Ov); 10569 } 10570 10571 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10572 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10573 10574 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10575 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10576 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10577 getBuildVector(NewOvVT, dl, OvScalars)); 10578 } 10579 10580 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10581 LoadSDNode *Base, 10582 unsigned Bytes, 10583 int Dist) const { 10584 if (LD->isVolatile() || Base->isVolatile()) 10585 return false; 10586 // TODO: probably too restrictive for atomics, revisit 10587 if (!LD->isSimple()) 10588 return false; 10589 if (LD->isIndexed() || Base->isIndexed()) 10590 return false; 10591 if (LD->getChain() != Base->getChain()) 10592 return false; 10593 EVT VT = LD->getValueType(0); 10594 if (VT.getSizeInBits() / 8 != Bytes) 10595 return false; 10596 10597 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10598 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10599 10600 int64_t Offset = 0; 10601 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 10602 return (Dist * Bytes == Offset); 10603 return false; 10604 } 10605 10606 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 10607 /// if it cannot be inferred. 10608 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 10609 // If this is a GlobalAddress + cst, return the alignment. 10610 const GlobalValue *GV = nullptr; 10611 int64_t GVOffset = 0; 10612 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 10613 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 10614 KnownBits Known(PtrWidth); 10615 llvm::computeKnownBits(GV, Known, getDataLayout()); 10616 unsigned AlignBits = Known.countMinTrailingZeros(); 10617 if (AlignBits) 10618 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 10619 } 10620 10621 // If this is a direct reference to a stack slot, use information about the 10622 // stack slot's alignment. 10623 int FrameIdx = INT_MIN; 10624 int64_t FrameOffset = 0; 10625 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 10626 FrameIdx = FI->getIndex(); 10627 } else if (isBaseWithConstantOffset(Ptr) && 10628 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 10629 // Handle FI+Cst 10630 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 10631 FrameOffset = Ptr.getConstantOperandVal(1); 10632 } 10633 10634 if (FrameIdx != INT_MIN) { 10635 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 10636 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 10637 } 10638 10639 return None; 10640 } 10641 10642 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 10643 /// which is split (or expanded) into two not necessarily identical pieces. 10644 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 10645 // Currently all types are split in half. 10646 EVT LoVT, HiVT; 10647 if (!VT.isVector()) 10648 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 10649 else 10650 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 10651 10652 return std::make_pair(LoVT, HiVT); 10653 } 10654 10655 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 10656 /// type, dependent on an enveloping VT that has been split into two identical 10657 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 10658 std::pair<EVT, EVT> 10659 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 10660 bool *HiIsEmpty) const { 10661 EVT EltTp = VT.getVectorElementType(); 10662 // Examples: 10663 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 10664 // custom VL=9 with enveloping VL=8/8 yields 8/1 10665 // custom VL=10 with enveloping VL=8/8 yields 8/2 10666 // etc. 10667 ElementCount VTNumElts = VT.getVectorElementCount(); 10668 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 10669 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 10670 "Mixing fixed width and scalable vectors when enveloping a type"); 10671 EVT LoVT, HiVT; 10672 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 10673 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 10674 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 10675 *HiIsEmpty = false; 10676 } else { 10677 // Flag that hi type has zero storage size, but return split envelop type 10678 // (this would be easier if vector types with zero elements were allowed). 10679 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 10680 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 10681 *HiIsEmpty = true; 10682 } 10683 return std::make_pair(LoVT, HiVT); 10684 } 10685 10686 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 10687 /// low/high part. 10688 std::pair<SDValue, SDValue> 10689 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 10690 const EVT &HiVT) { 10691 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 10692 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 10693 "Splitting vector with an invalid mixture of fixed and scalable " 10694 "vector types"); 10695 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 10696 N.getValueType().getVectorMinNumElements() && 10697 "More vector elements requested than available!"); 10698 SDValue Lo, Hi; 10699 Lo = 10700 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 10701 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 10702 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 10703 // IDX with the runtime scaling factor of the result vector type. For 10704 // fixed-width result vectors, that runtime scaling factor is 1. 10705 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 10706 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 10707 return std::make_pair(Lo, Hi); 10708 } 10709 10710 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 10711 const SDLoc &DL) { 10712 // Split the vector length parameter. 10713 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 10714 EVT VT = N.getValueType(); 10715 assert(VecVT.getVectorElementCount().isKnownEven() && 10716 "Expecting the mask to be an evenly-sized vector"); 10717 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 10718 SDValue HalfNumElts = 10719 VecVT.isFixedLengthVector() 10720 ? getConstant(HalfMinNumElts, DL, VT) 10721 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 10722 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 10723 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 10724 return std::make_pair(Lo, Hi); 10725 } 10726 10727 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 10728 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 10729 EVT VT = N.getValueType(); 10730 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 10731 NextPowerOf2(VT.getVectorNumElements())); 10732 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 10733 getVectorIdxConstant(0, DL)); 10734 } 10735 10736 void SelectionDAG::ExtractVectorElements(SDValue Op, 10737 SmallVectorImpl<SDValue> &Args, 10738 unsigned Start, unsigned Count, 10739 EVT EltVT) { 10740 EVT VT = Op.getValueType(); 10741 if (Count == 0) 10742 Count = VT.getVectorNumElements(); 10743 if (EltVT == EVT()) 10744 EltVT = VT.getVectorElementType(); 10745 SDLoc SL(Op); 10746 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 10747 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 10748 getVectorIdxConstant(i, SL))); 10749 } 10750 } 10751 10752 // getAddressSpace - Return the address space this GlobalAddress belongs to. 10753 unsigned GlobalAddressSDNode::getAddressSpace() const { 10754 return getGlobal()->getType()->getAddressSpace(); 10755 } 10756 10757 Type *ConstantPoolSDNode::getType() const { 10758 if (isMachineConstantPoolEntry()) 10759 return Val.MachineCPVal->getType(); 10760 return Val.ConstVal->getType(); 10761 } 10762 10763 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 10764 unsigned &SplatBitSize, 10765 bool &HasAnyUndefs, 10766 unsigned MinSplatBits, 10767 bool IsBigEndian) const { 10768 EVT VT = getValueType(0); 10769 assert(VT.isVector() && "Expected a vector type"); 10770 unsigned VecWidth = VT.getSizeInBits(); 10771 if (MinSplatBits > VecWidth) 10772 return false; 10773 10774 // FIXME: The widths are based on this node's type, but build vectors can 10775 // truncate their operands. 10776 SplatValue = APInt(VecWidth, 0); 10777 SplatUndef = APInt(VecWidth, 0); 10778 10779 // Get the bits. Bits with undefined values (when the corresponding element 10780 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 10781 // in SplatValue. If any of the values are not constant, give up and return 10782 // false. 10783 unsigned int NumOps = getNumOperands(); 10784 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 10785 unsigned EltWidth = VT.getScalarSizeInBits(); 10786 10787 for (unsigned j = 0; j < NumOps; ++j) { 10788 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 10789 SDValue OpVal = getOperand(i); 10790 unsigned BitPos = j * EltWidth; 10791 10792 if (OpVal.isUndef()) 10793 SplatUndef.setBits(BitPos, BitPos + EltWidth); 10794 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 10795 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 10796 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 10797 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 10798 else 10799 return false; 10800 } 10801 10802 // The build_vector is all constants or undefs. Find the smallest element 10803 // size that splats the vector. 10804 HasAnyUndefs = (SplatUndef != 0); 10805 10806 // FIXME: This does not work for vectors with elements less than 8 bits. 10807 while (VecWidth > 8) { 10808 unsigned HalfSize = VecWidth / 2; 10809 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 10810 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 10811 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 10812 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 10813 10814 // If the two halves do not match (ignoring undef bits), stop here. 10815 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 10816 MinSplatBits > HalfSize) 10817 break; 10818 10819 SplatValue = HighValue | LowValue; 10820 SplatUndef = HighUndef & LowUndef; 10821 10822 VecWidth = HalfSize; 10823 } 10824 10825 SplatBitSize = VecWidth; 10826 return true; 10827 } 10828 10829 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 10830 BitVector *UndefElements) const { 10831 unsigned NumOps = getNumOperands(); 10832 if (UndefElements) { 10833 UndefElements->clear(); 10834 UndefElements->resize(NumOps); 10835 } 10836 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10837 if (!DemandedElts) 10838 return SDValue(); 10839 SDValue Splatted; 10840 for (unsigned i = 0; i != NumOps; ++i) { 10841 if (!DemandedElts[i]) 10842 continue; 10843 SDValue Op = getOperand(i); 10844 if (Op.isUndef()) { 10845 if (UndefElements) 10846 (*UndefElements)[i] = true; 10847 } else if (!Splatted) { 10848 Splatted = Op; 10849 } else if (Splatted != Op) { 10850 return SDValue(); 10851 } 10852 } 10853 10854 if (!Splatted) { 10855 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 10856 assert(getOperand(FirstDemandedIdx).isUndef() && 10857 "Can only have a splat without a constant for all undefs."); 10858 return getOperand(FirstDemandedIdx); 10859 } 10860 10861 return Splatted; 10862 } 10863 10864 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 10865 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10866 return getSplatValue(DemandedElts, UndefElements); 10867 } 10868 10869 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 10870 SmallVectorImpl<SDValue> &Sequence, 10871 BitVector *UndefElements) const { 10872 unsigned NumOps = getNumOperands(); 10873 Sequence.clear(); 10874 if (UndefElements) { 10875 UndefElements->clear(); 10876 UndefElements->resize(NumOps); 10877 } 10878 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10879 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10880 return false; 10881 10882 // Set the undefs even if we don't find a sequence (like getSplatValue). 10883 if (UndefElements) 10884 for (unsigned I = 0; I != NumOps; ++I) 10885 if (DemandedElts[I] && getOperand(I).isUndef()) 10886 (*UndefElements)[I] = true; 10887 10888 // Iteratively widen the sequence length looking for repetitions. 10889 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10890 Sequence.append(SeqLen, SDValue()); 10891 for (unsigned I = 0; I != NumOps; ++I) { 10892 if (!DemandedElts[I]) 10893 continue; 10894 SDValue &SeqOp = Sequence[I % SeqLen]; 10895 SDValue Op = getOperand(I); 10896 if (Op.isUndef()) { 10897 if (!SeqOp) 10898 SeqOp = Op; 10899 continue; 10900 } 10901 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10902 Sequence.clear(); 10903 break; 10904 } 10905 SeqOp = Op; 10906 } 10907 if (!Sequence.empty()) 10908 return true; 10909 } 10910 10911 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10912 return false; 10913 } 10914 10915 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10916 BitVector *UndefElements) const { 10917 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10918 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10919 } 10920 10921 ConstantSDNode * 10922 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10923 BitVector *UndefElements) const { 10924 return dyn_cast_or_null<ConstantSDNode>( 10925 getSplatValue(DemandedElts, UndefElements)); 10926 } 10927 10928 ConstantSDNode * 10929 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10930 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10931 } 10932 10933 ConstantFPSDNode * 10934 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10935 BitVector *UndefElements) const { 10936 return dyn_cast_or_null<ConstantFPSDNode>( 10937 getSplatValue(DemandedElts, UndefElements)); 10938 } 10939 10940 ConstantFPSDNode * 10941 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10942 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10943 } 10944 10945 int32_t 10946 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10947 uint32_t BitWidth) const { 10948 if (ConstantFPSDNode *CN = 10949 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10950 bool IsExact; 10951 APSInt IntVal(BitWidth); 10952 const APFloat &APF = CN->getValueAPF(); 10953 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10954 APFloat::opOK || 10955 !IsExact) 10956 return -1; 10957 10958 return IntVal.exactLogBase2(); 10959 } 10960 return -1; 10961 } 10962 10963 bool BuildVectorSDNode::getConstantRawBits( 10964 bool IsLittleEndian, unsigned DstEltSizeInBits, 10965 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 10966 // Early-out if this contains anything but Undef/Constant/ConstantFP. 10967 if (!isConstant()) 10968 return false; 10969 10970 unsigned NumSrcOps = getNumOperands(); 10971 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 10972 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 10973 "Invalid bitcast scale"); 10974 10975 // Extract raw src bits. 10976 SmallVector<APInt> SrcBitElements(NumSrcOps, 10977 APInt::getNullValue(SrcEltSizeInBits)); 10978 BitVector SrcUndeElements(NumSrcOps, false); 10979 10980 for (unsigned I = 0; I != NumSrcOps; ++I) { 10981 SDValue Op = getOperand(I); 10982 if (Op.isUndef()) { 10983 SrcUndeElements.set(I); 10984 continue; 10985 } 10986 auto *CInt = dyn_cast<ConstantSDNode>(Op); 10987 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 10988 assert((CInt || CFP) && "Unknown constant"); 10989 SrcBitElements[I] = 10990 CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits) 10991 : CFP->getValueAPF().bitcastToAPInt(); 10992 } 10993 10994 // Recast to dst width. 10995 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 10996 SrcBitElements, UndefElements, SrcUndeElements); 10997 return true; 10998 } 10999 11000 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 11001 unsigned DstEltSizeInBits, 11002 SmallVectorImpl<APInt> &DstBitElements, 11003 ArrayRef<APInt> SrcBitElements, 11004 BitVector &DstUndefElements, 11005 const BitVector &SrcUndefElements) { 11006 unsigned NumSrcOps = SrcBitElements.size(); 11007 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 11008 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 11009 "Invalid bitcast scale"); 11010 assert(NumSrcOps == SrcUndefElements.size() && 11011 "Vector size mismatch"); 11012 11013 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 11014 DstUndefElements.clear(); 11015 DstUndefElements.resize(NumDstOps, false); 11016 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 11017 11018 // Concatenate src elements constant bits together into dst element. 11019 if (SrcEltSizeInBits <= DstEltSizeInBits) { 11020 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 11021 for (unsigned I = 0; I != NumDstOps; ++I) { 11022 DstUndefElements.set(I); 11023 APInt &DstBits = DstBitElements[I]; 11024 for (unsigned J = 0; J != Scale; ++J) { 11025 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11026 if (SrcUndefElements[Idx]) 11027 continue; 11028 DstUndefElements.reset(I); 11029 const APInt &SrcBits = SrcBitElements[Idx]; 11030 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 11031 "Illegal constant bitwidths"); 11032 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 11033 } 11034 } 11035 return; 11036 } 11037 11038 // Split src element constant bits into dst elements. 11039 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 11040 for (unsigned I = 0; I != NumSrcOps; ++I) { 11041 if (SrcUndefElements[I]) { 11042 DstUndefElements.set(I * Scale, (I + 1) * Scale); 11043 continue; 11044 } 11045 const APInt &SrcBits = SrcBitElements[I]; 11046 for (unsigned J = 0; J != Scale; ++J) { 11047 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 11048 APInt &DstBits = DstBitElements[Idx]; 11049 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11050 } 11051 } 11052 } 11053 11054 bool BuildVectorSDNode::isConstant() const { 11055 for (const SDValue &Op : op_values()) { 11056 unsigned Opc = Op.getOpcode(); 11057 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11058 return false; 11059 } 11060 return true; 11061 } 11062 11063 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11064 // Find the first non-undef value in the shuffle mask. 11065 unsigned i, e; 11066 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11067 /* search */; 11068 11069 // If all elements are undefined, this shuffle can be considered a splat 11070 // (although it should eventually get simplified away completely). 11071 if (i == e) 11072 return true; 11073 11074 // Make sure all remaining elements are either undef or the same as the first 11075 // non-undef value. 11076 for (int Idx = Mask[i]; i != e; ++i) 11077 if (Mask[i] >= 0 && Mask[i] != Idx) 11078 return false; 11079 return true; 11080 } 11081 11082 // Returns the SDNode if it is a constant integer BuildVector 11083 // or constant integer. 11084 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11085 if (isa<ConstantSDNode>(N)) 11086 return N.getNode(); 11087 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11088 return N.getNode(); 11089 // Treat a GlobalAddress supporting constant offset folding as a 11090 // constant integer. 11091 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11092 if (GA->getOpcode() == ISD::GlobalAddress && 11093 TLI->isOffsetFoldingLegal(GA)) 11094 return GA; 11095 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11096 isa<ConstantSDNode>(N.getOperand(0))) 11097 return N.getNode(); 11098 return nullptr; 11099 } 11100 11101 // Returns the SDNode if it is a constant float BuildVector 11102 // or constant float. 11103 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11104 if (isa<ConstantFPSDNode>(N)) 11105 return N.getNode(); 11106 11107 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11108 return N.getNode(); 11109 11110 return nullptr; 11111 } 11112 11113 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11114 assert(!Node->OperandList && "Node already has operands"); 11115 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11116 "too many operands to fit into SDNode"); 11117 SDUse *Ops = OperandRecycler.allocate( 11118 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11119 11120 bool IsDivergent = false; 11121 for (unsigned I = 0; I != Vals.size(); ++I) { 11122 Ops[I].setUser(Node); 11123 Ops[I].setInitial(Vals[I]); 11124 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11125 IsDivergent |= Ops[I].getNode()->isDivergent(); 11126 } 11127 Node->NumOperands = Vals.size(); 11128 Node->OperandList = Ops; 11129 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11130 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11131 Node->SDNodeBits.IsDivergent = IsDivergent; 11132 } 11133 checkForCycles(Node); 11134 } 11135 11136 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11137 SmallVectorImpl<SDValue> &Vals) { 11138 size_t Limit = SDNode::getMaxNumOperands(); 11139 while (Vals.size() > Limit) { 11140 unsigned SliceIdx = Vals.size() - Limit; 11141 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11142 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11143 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11144 Vals.emplace_back(NewTF); 11145 } 11146 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11147 } 11148 11149 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11150 EVT VT, SDNodeFlags Flags) { 11151 switch (Opcode) { 11152 default: 11153 return SDValue(); 11154 case ISD::ADD: 11155 case ISD::OR: 11156 case ISD::XOR: 11157 case ISD::UMAX: 11158 return getConstant(0, DL, VT); 11159 case ISD::MUL: 11160 return getConstant(1, DL, VT); 11161 case ISD::AND: 11162 case ISD::UMIN: 11163 return getAllOnesConstant(DL, VT); 11164 case ISD::SMAX: 11165 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11166 case ISD::SMIN: 11167 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11168 case ISD::FADD: 11169 return getConstantFP(-0.0, DL, VT); 11170 case ISD::FMUL: 11171 return getConstantFP(1.0, DL, VT); 11172 case ISD::FMINNUM: 11173 case ISD::FMAXNUM: { 11174 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11175 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11176 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11177 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11178 APFloat::getLargest(Semantics); 11179 if (Opcode == ISD::FMAXNUM) 11180 NeutralAF.changeSign(); 11181 11182 return getConstantFP(NeutralAF, DL, VT); 11183 } 11184 } 11185 } 11186 11187 #ifndef NDEBUG 11188 static void checkForCyclesHelper(const SDNode *N, 11189 SmallPtrSetImpl<const SDNode*> &Visited, 11190 SmallPtrSetImpl<const SDNode*> &Checked, 11191 const llvm::SelectionDAG *DAG) { 11192 // If this node has already been checked, don't check it again. 11193 if (Checked.count(N)) 11194 return; 11195 11196 // If a node has already been visited on this depth-first walk, reject it as 11197 // a cycle. 11198 if (!Visited.insert(N).second) { 11199 errs() << "Detected cycle in SelectionDAG\n"; 11200 dbgs() << "Offending node:\n"; 11201 N->dumprFull(DAG); dbgs() << "\n"; 11202 abort(); 11203 } 11204 11205 for (const SDValue &Op : N->op_values()) 11206 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11207 11208 Checked.insert(N); 11209 Visited.erase(N); 11210 } 11211 #endif 11212 11213 void llvm::checkForCycles(const llvm::SDNode *N, 11214 const llvm::SelectionDAG *DAG, 11215 bool force) { 11216 #ifndef NDEBUG 11217 bool check = force; 11218 #ifdef EXPENSIVE_CHECKS 11219 check = true; 11220 #endif // EXPENSIVE_CHECKS 11221 if (check) { 11222 assert(N && "Checking nonexistent SDNode"); 11223 SmallPtrSet<const SDNode*, 32> visited; 11224 SmallPtrSet<const SDNode*, 32> checked; 11225 checkForCyclesHelper(N, visited, checked, DAG); 11226 } 11227 #endif // !NDEBUG 11228 } 11229 11230 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11231 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11232 } 11233