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, 0); 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 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3086 break; 3087 } 3088 case ISD::MULHU: { 3089 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3090 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3091 Known = KnownBits::mulhu(Known, Known2); 3092 break; 3093 } 3094 case ISD::MULHS: { 3095 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3096 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3097 Known = KnownBits::mulhs(Known, Known2); 3098 break; 3099 } 3100 case ISD::UMUL_LOHI: { 3101 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3102 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3103 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3104 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3105 if (Op.getResNo() == 0) 3106 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3107 else 3108 Known = KnownBits::mulhu(Known, Known2); 3109 break; 3110 } 3111 case ISD::SMUL_LOHI: { 3112 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3113 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3114 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3115 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1); 3116 if (Op.getResNo() == 0) 3117 Known = KnownBits::mul(Known, Known2, SelfMultiply); 3118 else 3119 Known = KnownBits::mulhs(Known, Known2); 3120 break; 3121 } 3122 case ISD::UDIV: { 3123 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3124 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3125 Known = KnownBits::udiv(Known, Known2); 3126 break; 3127 } 3128 case ISD::SELECT: 3129 case ISD::VSELECT: 3130 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3131 // If we don't know any bits, early out. 3132 if (Known.isUnknown()) 3133 break; 3134 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3135 3136 // Only known if known in both the LHS and RHS. 3137 Known = KnownBits::commonBits(Known, Known2); 3138 break; 3139 case ISD::SELECT_CC: 3140 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3141 // If we don't know any bits, early out. 3142 if (Known.isUnknown()) 3143 break; 3144 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3145 3146 // Only known if known in both the LHS and RHS. 3147 Known = KnownBits::commonBits(Known, Known2); 3148 break; 3149 case ISD::SMULO: 3150 case ISD::UMULO: 3151 if (Op.getResNo() != 1) 3152 break; 3153 // The boolean result conforms to getBooleanContents. 3154 // If we know the result of a setcc has the top bits zero, use this info. 3155 // We know that we have an integer-based boolean since these operations 3156 // are only available for integer. 3157 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3158 TargetLowering::ZeroOrOneBooleanContent && 3159 BitWidth > 1) 3160 Known.Zero.setBitsFrom(1); 3161 break; 3162 case ISD::SETCC: 3163 case ISD::STRICT_FSETCC: 3164 case ISD::STRICT_FSETCCS: { 3165 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3166 // If we know the result of a setcc has the top bits zero, use this info. 3167 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3168 TargetLowering::ZeroOrOneBooleanContent && 3169 BitWidth > 1) 3170 Known.Zero.setBitsFrom(1); 3171 break; 3172 } 3173 case ISD::SHL: 3174 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3175 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3176 Known = KnownBits::shl(Known, Known2); 3177 3178 // Minimum shift low bits are known zero. 3179 if (const APInt *ShMinAmt = 3180 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3181 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3182 break; 3183 case ISD::SRL: 3184 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3185 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3186 Known = KnownBits::lshr(Known, Known2); 3187 3188 // Minimum shift high bits are known zero. 3189 if (const APInt *ShMinAmt = 3190 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3191 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3192 break; 3193 case ISD::SRA: 3194 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3195 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3196 Known = KnownBits::ashr(Known, Known2); 3197 // TODO: Add minimum shift high known sign bits. 3198 break; 3199 case ISD::FSHL: 3200 case ISD::FSHR: 3201 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3202 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3203 3204 // For fshl, 0-shift returns the 1st arg. 3205 // For fshr, 0-shift returns the 2nd arg. 3206 if (Amt == 0) { 3207 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3208 DemandedElts, Depth + 1); 3209 break; 3210 } 3211 3212 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3213 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3214 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3215 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3216 if (Opcode == ISD::FSHL) { 3217 Known.One <<= Amt; 3218 Known.Zero <<= Amt; 3219 Known2.One.lshrInPlace(BitWidth - Amt); 3220 Known2.Zero.lshrInPlace(BitWidth - Amt); 3221 } else { 3222 Known.One <<= BitWidth - Amt; 3223 Known.Zero <<= BitWidth - Amt; 3224 Known2.One.lshrInPlace(Amt); 3225 Known2.Zero.lshrInPlace(Amt); 3226 } 3227 Known.One |= Known2.One; 3228 Known.Zero |= Known2.Zero; 3229 } 3230 break; 3231 case ISD::SIGN_EXTEND_INREG: { 3232 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3233 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3234 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3235 break; 3236 } 3237 case ISD::CTTZ: 3238 case ISD::CTTZ_ZERO_UNDEF: { 3239 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3240 // If we have a known 1, its position is our upper bound. 3241 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3242 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3243 Known.Zero.setBitsFrom(LowBits); 3244 break; 3245 } 3246 case ISD::CTLZ: 3247 case ISD::CTLZ_ZERO_UNDEF: { 3248 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3249 // If we have a known 1, its position is our upper bound. 3250 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3251 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3252 Known.Zero.setBitsFrom(LowBits); 3253 break; 3254 } 3255 case ISD::CTPOP: { 3256 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3257 // If we know some of the bits are zero, they can't be one. 3258 unsigned PossibleOnes = Known2.countMaxPopulation(); 3259 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3260 break; 3261 } 3262 case ISD::PARITY: { 3263 // Parity returns 0 everywhere but the LSB. 3264 Known.Zero.setBitsFrom(1); 3265 break; 3266 } 3267 case ISD::LOAD: { 3268 LoadSDNode *LD = cast<LoadSDNode>(Op); 3269 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3270 if (ISD::isNON_EXTLoad(LD) && Cst) { 3271 // Determine any common known bits from the loaded constant pool value. 3272 Type *CstTy = Cst->getType(); 3273 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3274 // If its a vector splat, then we can (quickly) reuse the scalar path. 3275 // NOTE: We assume all elements match and none are UNDEF. 3276 if (CstTy->isVectorTy()) { 3277 if (const Constant *Splat = Cst->getSplatValue()) { 3278 Cst = Splat; 3279 CstTy = Cst->getType(); 3280 } 3281 } 3282 // TODO - do we need to handle different bitwidths? 3283 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3284 // Iterate across all vector elements finding common known bits. 3285 Known.One.setAllBits(); 3286 Known.Zero.setAllBits(); 3287 for (unsigned i = 0; i != NumElts; ++i) { 3288 if (!DemandedElts[i]) 3289 continue; 3290 if (Constant *Elt = Cst->getAggregateElement(i)) { 3291 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3292 const APInt &Value = CInt->getValue(); 3293 Known.One &= Value; 3294 Known.Zero &= ~Value; 3295 continue; 3296 } 3297 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3298 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3299 Known.One &= Value; 3300 Known.Zero &= ~Value; 3301 continue; 3302 } 3303 } 3304 Known.One.clearAllBits(); 3305 Known.Zero.clearAllBits(); 3306 break; 3307 } 3308 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3309 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3310 Known = KnownBits::makeConstant(CInt->getValue()); 3311 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3312 Known = 3313 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3314 } 3315 } 3316 } 3317 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3318 // If this is a ZEXTLoad and we are looking at the loaded value. 3319 EVT VT = LD->getMemoryVT(); 3320 unsigned MemBits = VT.getScalarSizeInBits(); 3321 Known.Zero.setBitsFrom(MemBits); 3322 } else if (const MDNode *Ranges = LD->getRanges()) { 3323 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3324 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3325 } 3326 break; 3327 } 3328 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3329 EVT InVT = Op.getOperand(0).getValueType(); 3330 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3331 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3332 Known = Known.zext(BitWidth); 3333 break; 3334 } 3335 case ISD::ZERO_EXTEND: { 3336 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3337 Known = Known.zext(BitWidth); 3338 break; 3339 } 3340 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3341 EVT InVT = Op.getOperand(0).getValueType(); 3342 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3343 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3344 // If the sign bit is known to be zero or one, then sext will extend 3345 // it to the top bits, else it will just zext. 3346 Known = Known.sext(BitWidth); 3347 break; 3348 } 3349 case ISD::SIGN_EXTEND: { 3350 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3351 // If the sign bit is known to be zero or one, then sext will extend 3352 // it to the top bits, else it will just zext. 3353 Known = Known.sext(BitWidth); 3354 break; 3355 } 3356 case ISD::ANY_EXTEND_VECTOR_INREG: { 3357 EVT InVT = Op.getOperand(0).getValueType(); 3358 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3359 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3360 Known = Known.anyext(BitWidth); 3361 break; 3362 } 3363 case ISD::ANY_EXTEND: { 3364 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3365 Known = Known.anyext(BitWidth); 3366 break; 3367 } 3368 case ISD::TRUNCATE: { 3369 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3370 Known = Known.trunc(BitWidth); 3371 break; 3372 } 3373 case ISD::AssertZext: { 3374 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3375 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3376 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3377 Known.Zero |= (~InMask); 3378 Known.One &= (~Known.Zero); 3379 break; 3380 } 3381 case ISD::AssertAlign: { 3382 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3383 assert(LogOfAlign != 0); 3384 3385 // TODO: Should use maximum with source 3386 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3387 // well as clearing one bits. 3388 Known.Zero.setLowBits(LogOfAlign); 3389 Known.One.clearLowBits(LogOfAlign); 3390 break; 3391 } 3392 case ISD::FGETSIGN: 3393 // All bits are zero except the low bit. 3394 Known.Zero.setBitsFrom(1); 3395 break; 3396 case ISD::USUBO: 3397 case ISD::SSUBO: 3398 if (Op.getResNo() == 1) { 3399 // If we know the result of a setcc has the top bits zero, use this info. 3400 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3401 TargetLowering::ZeroOrOneBooleanContent && 3402 BitWidth > 1) 3403 Known.Zero.setBitsFrom(1); 3404 break; 3405 } 3406 LLVM_FALLTHROUGH; 3407 case ISD::SUB: 3408 case ISD::SUBC: { 3409 assert(Op.getResNo() == 0 && 3410 "We only compute knownbits for the difference here."); 3411 3412 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3413 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3414 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3415 Known, Known2); 3416 break; 3417 } 3418 case ISD::UADDO: 3419 case ISD::SADDO: 3420 case ISD::ADDCARRY: 3421 if (Op.getResNo() == 1) { 3422 // If we know the result of a setcc has the top bits zero, use this info. 3423 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3424 TargetLowering::ZeroOrOneBooleanContent && 3425 BitWidth > 1) 3426 Known.Zero.setBitsFrom(1); 3427 break; 3428 } 3429 LLVM_FALLTHROUGH; 3430 case ISD::ADD: 3431 case ISD::ADDC: 3432 case ISD::ADDE: { 3433 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3434 3435 // With ADDE and ADDCARRY, a carry bit may be added in. 3436 KnownBits Carry(1); 3437 if (Opcode == ISD::ADDE) 3438 // Can't track carry from glue, set carry to unknown. 3439 Carry.resetAll(); 3440 else if (Opcode == ISD::ADDCARRY) 3441 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3442 // the trouble (how often will we find a known carry bit). And I haven't 3443 // tested this very much yet, but something like this might work: 3444 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3445 // Carry = Carry.zextOrTrunc(1, false); 3446 Carry.resetAll(); 3447 else 3448 Carry.setAllZero(); 3449 3450 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3451 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3452 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3453 break; 3454 } 3455 case ISD::SREM: { 3456 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3457 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3458 Known = KnownBits::srem(Known, Known2); 3459 break; 3460 } 3461 case ISD::UREM: { 3462 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3463 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3464 Known = KnownBits::urem(Known, Known2); 3465 break; 3466 } 3467 case ISD::EXTRACT_ELEMENT: { 3468 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3469 const unsigned Index = Op.getConstantOperandVal(1); 3470 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3471 3472 // Remove low part of known bits mask 3473 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3474 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3475 3476 // Remove high part of known bit mask 3477 Known = Known.trunc(EltBitWidth); 3478 break; 3479 } 3480 case ISD::EXTRACT_VECTOR_ELT: { 3481 SDValue InVec = Op.getOperand(0); 3482 SDValue EltNo = Op.getOperand(1); 3483 EVT VecVT = InVec.getValueType(); 3484 // computeKnownBits not yet implemented for scalable vectors. 3485 if (VecVT.isScalableVector()) 3486 break; 3487 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3488 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3489 3490 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3491 // anything about the extended bits. 3492 if (BitWidth > EltBitWidth) 3493 Known = Known.trunc(EltBitWidth); 3494 3495 // If we know the element index, just demand that vector element, else for 3496 // an unknown element index, ignore DemandedElts and demand them all. 3497 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 3498 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3499 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3500 DemandedSrcElts = 3501 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3502 3503 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3504 if (BitWidth > EltBitWidth) 3505 Known = Known.anyext(BitWidth); 3506 break; 3507 } 3508 case ISD::INSERT_VECTOR_ELT: { 3509 // If we know the element index, split the demand between the 3510 // source vector and the inserted element, otherwise assume we need 3511 // the original demanded vector elements and the value. 3512 SDValue InVec = Op.getOperand(0); 3513 SDValue InVal = Op.getOperand(1); 3514 SDValue EltNo = Op.getOperand(2); 3515 bool DemandedVal = true; 3516 APInt DemandedVecElts = DemandedElts; 3517 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3518 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3519 unsigned EltIdx = CEltNo->getZExtValue(); 3520 DemandedVal = !!DemandedElts[EltIdx]; 3521 DemandedVecElts.clearBit(EltIdx); 3522 } 3523 Known.One.setAllBits(); 3524 Known.Zero.setAllBits(); 3525 if (DemandedVal) { 3526 Known2 = computeKnownBits(InVal, Depth + 1); 3527 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3528 } 3529 if (!!DemandedVecElts) { 3530 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3531 Known = KnownBits::commonBits(Known, Known2); 3532 } 3533 break; 3534 } 3535 case ISD::BITREVERSE: { 3536 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3537 Known = Known2.reverseBits(); 3538 break; 3539 } 3540 case ISD::BSWAP: { 3541 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3542 Known = Known2.byteSwap(); 3543 break; 3544 } 3545 case ISD::ABS: { 3546 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3547 Known = Known2.abs(); 3548 break; 3549 } 3550 case ISD::USUBSAT: { 3551 // The result of usubsat will never be larger than the LHS. 3552 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3553 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3554 break; 3555 } 3556 case ISD::UMIN: { 3557 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3558 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3559 Known = KnownBits::umin(Known, Known2); 3560 break; 3561 } 3562 case ISD::UMAX: { 3563 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3564 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3565 Known = KnownBits::umax(Known, Known2); 3566 break; 3567 } 3568 case ISD::SMIN: 3569 case ISD::SMAX: { 3570 // If we have a clamp pattern, we know that the number of sign bits will be 3571 // the minimum of the clamp min/max range. 3572 bool IsMax = (Opcode == ISD::SMAX); 3573 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3574 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3575 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3576 CstHigh = 3577 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3578 if (CstLow && CstHigh) { 3579 if (!IsMax) 3580 std::swap(CstLow, CstHigh); 3581 3582 const APInt &ValueLow = CstLow->getAPIntValue(); 3583 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3584 if (ValueLow.sle(ValueHigh)) { 3585 unsigned LowSignBits = ValueLow.getNumSignBits(); 3586 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3587 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3588 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3589 Known.One.setHighBits(MinSignBits); 3590 break; 3591 } 3592 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3593 Known.Zero.setHighBits(MinSignBits); 3594 break; 3595 } 3596 } 3597 } 3598 3599 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3600 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3601 if (IsMax) 3602 Known = KnownBits::smax(Known, Known2); 3603 else 3604 Known = KnownBits::smin(Known, Known2); 3605 break; 3606 } 3607 case ISD::FP_TO_UINT_SAT: { 3608 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT. 3609 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3610 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits()); 3611 break; 3612 } 3613 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3614 if (Op.getResNo() == 1) { 3615 // The boolean result conforms to getBooleanContents. 3616 // If we know the result of a setcc has the top bits zero, use this info. 3617 // We know that we have an integer-based boolean since these operations 3618 // are only available for integer. 3619 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3620 TargetLowering::ZeroOrOneBooleanContent && 3621 BitWidth > 1) 3622 Known.Zero.setBitsFrom(1); 3623 break; 3624 } 3625 LLVM_FALLTHROUGH; 3626 case ISD::ATOMIC_CMP_SWAP: 3627 case ISD::ATOMIC_SWAP: 3628 case ISD::ATOMIC_LOAD_ADD: 3629 case ISD::ATOMIC_LOAD_SUB: 3630 case ISD::ATOMIC_LOAD_AND: 3631 case ISD::ATOMIC_LOAD_CLR: 3632 case ISD::ATOMIC_LOAD_OR: 3633 case ISD::ATOMIC_LOAD_XOR: 3634 case ISD::ATOMIC_LOAD_NAND: 3635 case ISD::ATOMIC_LOAD_MIN: 3636 case ISD::ATOMIC_LOAD_MAX: 3637 case ISD::ATOMIC_LOAD_UMIN: 3638 case ISD::ATOMIC_LOAD_UMAX: 3639 case ISD::ATOMIC_LOAD: { 3640 unsigned MemBits = 3641 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 3642 // If we are looking at the loaded value. 3643 if (Op.getResNo() == 0) { 3644 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 3645 Known.Zero.setBitsFrom(MemBits); 3646 } 3647 break; 3648 } 3649 case ISD::FrameIndex: 3650 case ISD::TargetFrameIndex: 3651 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3652 Known, getMachineFunction()); 3653 break; 3654 3655 default: 3656 if (Opcode < ISD::BUILTIN_OP_END) 3657 break; 3658 LLVM_FALLTHROUGH; 3659 case ISD::INTRINSIC_WO_CHAIN: 3660 case ISD::INTRINSIC_W_CHAIN: 3661 case ISD::INTRINSIC_VOID: 3662 // Allow the target to implement this method for its nodes. 3663 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3664 break; 3665 } 3666 3667 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3668 return Known; 3669 } 3670 3671 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3672 SDValue N1) const { 3673 // X + 0 never overflow 3674 if (isNullConstant(N1)) 3675 return OFK_Never; 3676 3677 KnownBits N1Known = computeKnownBits(N1); 3678 if (N1Known.Zero.getBoolValue()) { 3679 KnownBits N0Known = computeKnownBits(N0); 3680 3681 bool overflow; 3682 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3683 if (!overflow) 3684 return OFK_Never; 3685 } 3686 3687 // mulhi + 1 never overflow 3688 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3689 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3690 return OFK_Never; 3691 3692 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3693 KnownBits N0Known = computeKnownBits(N0); 3694 3695 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3696 return OFK_Never; 3697 } 3698 3699 return OFK_Sometime; 3700 } 3701 3702 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3703 EVT OpVT = Val.getValueType(); 3704 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3705 3706 // Is the constant a known power of 2? 3707 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3708 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3709 3710 // A left-shift of a constant one will have exactly one bit set because 3711 // shifting the bit off the end is undefined. 3712 if (Val.getOpcode() == ISD::SHL) { 3713 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3714 if (C && C->getAPIntValue() == 1) 3715 return true; 3716 } 3717 3718 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3719 // one bit set. 3720 if (Val.getOpcode() == ISD::SRL) { 3721 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3722 if (C && C->getAPIntValue().isSignMask()) 3723 return true; 3724 } 3725 3726 // Are all operands of a build vector constant powers of two? 3727 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3728 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3729 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3730 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3731 return false; 3732 })) 3733 return true; 3734 3735 // Is the operand of a splat vector a constant power of two? 3736 if (Val.getOpcode() == ISD::SPLAT_VECTOR) 3737 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0))) 3738 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2()) 3739 return true; 3740 3741 // More could be done here, though the above checks are enough 3742 // to handle some common cases. 3743 3744 // Fall back to computeKnownBits to catch other known cases. 3745 KnownBits Known = computeKnownBits(Val); 3746 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3747 } 3748 3749 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3750 EVT VT = Op.getValueType(); 3751 3752 // TODO: Assume we don't know anything for now. 3753 if (VT.isScalableVector()) 3754 return 1; 3755 3756 APInt DemandedElts = VT.isVector() 3757 ? APInt::getAllOnes(VT.getVectorNumElements()) 3758 : APInt(1, 1); 3759 return ComputeNumSignBits(Op, DemandedElts, Depth); 3760 } 3761 3762 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3763 unsigned Depth) const { 3764 EVT VT = Op.getValueType(); 3765 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3766 unsigned VTBits = VT.getScalarSizeInBits(); 3767 unsigned NumElts = DemandedElts.getBitWidth(); 3768 unsigned Tmp, Tmp2; 3769 unsigned FirstAnswer = 1; 3770 3771 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3772 const APInt &Val = C->getAPIntValue(); 3773 return Val.getNumSignBits(); 3774 } 3775 3776 if (Depth >= MaxRecursionDepth) 3777 return 1; // Limit search depth. 3778 3779 if (!DemandedElts || VT.isScalableVector()) 3780 return 1; // No demanded elts, better to assume we don't know anything. 3781 3782 unsigned Opcode = Op.getOpcode(); 3783 switch (Opcode) { 3784 default: break; 3785 case ISD::AssertSext: 3786 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3787 return VTBits-Tmp+1; 3788 case ISD::AssertZext: 3789 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3790 return VTBits-Tmp; 3791 3792 case ISD::BUILD_VECTOR: 3793 Tmp = VTBits; 3794 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3795 if (!DemandedElts[i]) 3796 continue; 3797 3798 SDValue SrcOp = Op.getOperand(i); 3799 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3800 3801 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3802 if (SrcOp.getValueSizeInBits() != VTBits) { 3803 assert(SrcOp.getValueSizeInBits() > VTBits && 3804 "Expected BUILD_VECTOR implicit truncation"); 3805 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3806 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3807 } 3808 Tmp = std::min(Tmp, Tmp2); 3809 } 3810 return Tmp; 3811 3812 case ISD::VECTOR_SHUFFLE: { 3813 // Collect the minimum number of sign bits that are shared by every vector 3814 // element referenced by the shuffle. 3815 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3816 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3817 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3818 for (unsigned i = 0; i != NumElts; ++i) { 3819 int M = SVN->getMaskElt(i); 3820 if (!DemandedElts[i]) 3821 continue; 3822 // For UNDEF elements, we don't know anything about the common state of 3823 // the shuffle result. 3824 if (M < 0) 3825 return 1; 3826 if ((unsigned)M < NumElts) 3827 DemandedLHS.setBit((unsigned)M % NumElts); 3828 else 3829 DemandedRHS.setBit((unsigned)M % NumElts); 3830 } 3831 Tmp = std::numeric_limits<unsigned>::max(); 3832 if (!!DemandedLHS) 3833 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3834 if (!!DemandedRHS) { 3835 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3836 Tmp = std::min(Tmp, Tmp2); 3837 } 3838 // If we don't know anything, early out and try computeKnownBits fall-back. 3839 if (Tmp == 1) 3840 break; 3841 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3842 return Tmp; 3843 } 3844 3845 case ISD::BITCAST: { 3846 SDValue N0 = Op.getOperand(0); 3847 EVT SrcVT = N0.getValueType(); 3848 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3849 3850 // Ignore bitcasts from unsupported types.. 3851 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3852 break; 3853 3854 // Fast handling of 'identity' bitcasts. 3855 if (VTBits == SrcBits) 3856 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3857 3858 bool IsLE = getDataLayout().isLittleEndian(); 3859 3860 // Bitcast 'large element' scalar/vector to 'small element' vector. 3861 if ((SrcBits % VTBits) == 0) { 3862 assert(VT.isVector() && "Expected bitcast to vector"); 3863 3864 unsigned Scale = SrcBits / VTBits; 3865 APInt SrcDemandedElts = 3866 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale); 3867 3868 // Fast case - sign splat can be simply split across the small elements. 3869 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3870 if (Tmp == SrcBits) 3871 return VTBits; 3872 3873 // Slow case - determine how far the sign extends into each sub-element. 3874 Tmp2 = VTBits; 3875 for (unsigned i = 0; i != NumElts; ++i) 3876 if (DemandedElts[i]) { 3877 unsigned SubOffset = i % Scale; 3878 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3879 SubOffset = SubOffset * VTBits; 3880 if (Tmp <= SubOffset) 3881 return 1; 3882 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3883 } 3884 return Tmp2; 3885 } 3886 break; 3887 } 3888 3889 case ISD::FP_TO_SINT_SAT: 3890 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT. 3891 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3892 return VTBits - Tmp + 1; 3893 case ISD::SIGN_EXTEND: 3894 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3895 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3896 case ISD::SIGN_EXTEND_INREG: 3897 // Max of the input and what this extends. 3898 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3899 Tmp = VTBits-Tmp+1; 3900 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3901 return std::max(Tmp, Tmp2); 3902 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3903 SDValue Src = Op.getOperand(0); 3904 EVT SrcVT = Src.getValueType(); 3905 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3906 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3907 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3908 } 3909 case ISD::SRA: 3910 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3911 // SRA X, C -> adds C sign bits. 3912 if (const APInt *ShAmt = 3913 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3914 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3915 return Tmp; 3916 case ISD::SHL: 3917 if (const APInt *ShAmt = 3918 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3919 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3920 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3921 if (ShAmt->ult(Tmp)) 3922 return Tmp - ShAmt->getZExtValue(); 3923 } 3924 break; 3925 case ISD::AND: 3926 case ISD::OR: 3927 case ISD::XOR: // NOT is handled here. 3928 // Logical binary ops preserve the number of sign bits at the worst. 3929 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3930 if (Tmp != 1) { 3931 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3932 FirstAnswer = std::min(Tmp, Tmp2); 3933 // We computed what we know about the sign bits as our first 3934 // answer. Now proceed to the generic code that uses 3935 // computeKnownBits, and pick whichever answer is better. 3936 } 3937 break; 3938 3939 case ISD::SELECT: 3940 case ISD::VSELECT: 3941 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3942 if (Tmp == 1) return 1; // Early out. 3943 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3944 return std::min(Tmp, Tmp2); 3945 case ISD::SELECT_CC: 3946 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3947 if (Tmp == 1) return 1; // Early out. 3948 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3949 return std::min(Tmp, Tmp2); 3950 3951 case ISD::SMIN: 3952 case ISD::SMAX: { 3953 // If we have a clamp pattern, we know that the number of sign bits will be 3954 // the minimum of the clamp min/max range. 3955 bool IsMax = (Opcode == ISD::SMAX); 3956 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3957 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3958 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3959 CstHigh = 3960 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3961 if (CstLow && CstHigh) { 3962 if (!IsMax) 3963 std::swap(CstLow, CstHigh); 3964 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3965 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3966 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3967 return std::min(Tmp, Tmp2); 3968 } 3969 } 3970 3971 // Fallback - just get the minimum number of sign bits of the operands. 3972 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3973 if (Tmp == 1) 3974 return 1; // Early out. 3975 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3976 return std::min(Tmp, Tmp2); 3977 } 3978 case ISD::UMIN: 3979 case ISD::UMAX: 3980 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3981 if (Tmp == 1) 3982 return 1; // Early out. 3983 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3984 return std::min(Tmp, Tmp2); 3985 case ISD::SADDO: 3986 case ISD::UADDO: 3987 case ISD::SSUBO: 3988 case ISD::USUBO: 3989 case ISD::SMULO: 3990 case ISD::UMULO: 3991 if (Op.getResNo() != 1) 3992 break; 3993 // The boolean result conforms to getBooleanContents. Fall through. 3994 // If setcc returns 0/-1, all bits are sign bits. 3995 // We know that we have an integer-based boolean since these operations 3996 // are only available for integer. 3997 if (TLI->getBooleanContents(VT.isVector(), false) == 3998 TargetLowering::ZeroOrNegativeOneBooleanContent) 3999 return VTBits; 4000 break; 4001 case ISD::SETCC: 4002 case ISD::STRICT_FSETCC: 4003 case ISD::STRICT_FSETCCS: { 4004 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 4005 // If setcc returns 0/-1, all bits are sign bits. 4006 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 4007 TargetLowering::ZeroOrNegativeOneBooleanContent) 4008 return VTBits; 4009 break; 4010 } 4011 case ISD::ROTL: 4012 case ISD::ROTR: 4013 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4014 4015 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 4016 if (Tmp == VTBits) 4017 return VTBits; 4018 4019 if (ConstantSDNode *C = 4020 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 4021 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 4022 4023 // Handle rotate right by N like a rotate left by 32-N. 4024 if (Opcode == ISD::ROTR) 4025 RotAmt = (VTBits - RotAmt) % VTBits; 4026 4027 // If we aren't rotating out all of the known-in sign bits, return the 4028 // number that are left. This handles rotl(sext(x), 1) for example. 4029 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 4030 } 4031 break; 4032 case ISD::ADD: 4033 case ISD::ADDC: 4034 // Add can have at most one carry bit. Thus we know that the output 4035 // is, at worst, one more bit than the inputs. 4036 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4037 if (Tmp == 1) return 1; // Early out. 4038 4039 // Special case decrementing a value (ADD X, -1): 4040 if (ConstantSDNode *CRHS = 4041 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 4042 if (CRHS->isAllOnes()) { 4043 KnownBits Known = 4044 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 4045 4046 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4047 // sign bits set. 4048 if ((Known.Zero | 1).isAllOnes()) 4049 return VTBits; 4050 4051 // If we are subtracting one from a positive number, there is no carry 4052 // out of the result. 4053 if (Known.isNonNegative()) 4054 return Tmp; 4055 } 4056 4057 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4058 if (Tmp2 == 1) return 1; // Early out. 4059 return std::min(Tmp, Tmp2) - 1; 4060 case ISD::SUB: 4061 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 4062 if (Tmp2 == 1) return 1; // Early out. 4063 4064 // Handle NEG. 4065 if (ConstantSDNode *CLHS = 4066 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 4067 if (CLHS->isZero()) { 4068 KnownBits Known = 4069 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 4070 // If the input is known to be 0 or 1, the output is 0/-1, which is all 4071 // sign bits set. 4072 if ((Known.Zero | 1).isAllOnes()) 4073 return VTBits; 4074 4075 // If the input is known to be positive (the sign bit is known clear), 4076 // the output of the NEG has the same number of sign bits as the input. 4077 if (Known.isNonNegative()) 4078 return Tmp2; 4079 4080 // Otherwise, we treat this like a SUB. 4081 } 4082 4083 // Sub can have at most one carry bit. Thus we know that the output 4084 // is, at worst, one more bit than the inputs. 4085 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4086 if (Tmp == 1) return 1; // Early out. 4087 return std::min(Tmp, Tmp2) - 1; 4088 case ISD::MUL: { 4089 // The output of the Mul can be at most twice the valid bits in the inputs. 4090 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4091 if (SignBitsOp0 == 1) 4092 break; 4093 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 4094 if (SignBitsOp1 == 1) 4095 break; 4096 unsigned OutValidBits = 4097 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 4098 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 4099 } 4100 case ISD::SREM: 4101 // The sign bit is the LHS's sign bit, except when the result of the 4102 // remainder is zero. The magnitude of the result should be less than or 4103 // equal to the magnitude of the LHS. Therefore, the result should have 4104 // at least as many sign bits as the left hand side. 4105 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 4106 case ISD::TRUNCATE: { 4107 // Check if the sign bits of source go down as far as the truncated value. 4108 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 4109 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 4110 if (NumSrcSignBits > (NumSrcBits - VTBits)) 4111 return NumSrcSignBits - (NumSrcBits - VTBits); 4112 break; 4113 } 4114 case ISD::EXTRACT_ELEMENT: { 4115 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 4116 const int BitWidth = Op.getValueSizeInBits(); 4117 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 4118 4119 // Get reverse index (starting from 1), Op1 value indexes elements from 4120 // little end. Sign starts at big end. 4121 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 4122 4123 // If the sign portion ends in our element the subtraction gives correct 4124 // result. Otherwise it gives either negative or > bitwidth result 4125 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 4126 } 4127 case ISD::INSERT_VECTOR_ELT: { 4128 // If we know the element index, split the demand between the 4129 // source vector and the inserted element, otherwise assume we need 4130 // the original demanded vector elements and the value. 4131 SDValue InVec = Op.getOperand(0); 4132 SDValue InVal = Op.getOperand(1); 4133 SDValue EltNo = Op.getOperand(2); 4134 bool DemandedVal = true; 4135 APInt DemandedVecElts = DemandedElts; 4136 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 4137 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 4138 unsigned EltIdx = CEltNo->getZExtValue(); 4139 DemandedVal = !!DemandedElts[EltIdx]; 4140 DemandedVecElts.clearBit(EltIdx); 4141 } 4142 Tmp = std::numeric_limits<unsigned>::max(); 4143 if (DemandedVal) { 4144 // TODO - handle implicit truncation of inserted elements. 4145 if (InVal.getScalarValueSizeInBits() != VTBits) 4146 break; 4147 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4148 Tmp = std::min(Tmp, Tmp2); 4149 } 4150 if (!!DemandedVecElts) { 4151 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4152 Tmp = std::min(Tmp, Tmp2); 4153 } 4154 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4155 return Tmp; 4156 } 4157 case ISD::EXTRACT_VECTOR_ELT: { 4158 SDValue InVec = Op.getOperand(0); 4159 SDValue EltNo = Op.getOperand(1); 4160 EVT VecVT = InVec.getValueType(); 4161 // ComputeNumSignBits not yet implemented for scalable vectors. 4162 if (VecVT.isScalableVector()) 4163 break; 4164 const unsigned BitWidth = Op.getValueSizeInBits(); 4165 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4166 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4167 4168 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4169 // anything about sign bits. But if the sizes match we can derive knowledge 4170 // about sign bits from the vector operand. 4171 if (BitWidth != EltBitWidth) 4172 break; 4173 4174 // If we know the element index, just demand that vector element, else for 4175 // an unknown element index, ignore DemandedElts and demand them all. 4176 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts); 4177 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4178 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4179 DemandedSrcElts = 4180 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4181 4182 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4183 } 4184 case ISD::EXTRACT_SUBVECTOR: { 4185 // Offset the demanded elts by the subvector index. 4186 SDValue Src = Op.getOperand(0); 4187 // Bail until we can represent demanded elements for scalable vectors. 4188 if (Src.getValueType().isScalableVector()) 4189 break; 4190 uint64_t Idx = Op.getConstantOperandVal(1); 4191 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4192 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4193 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4194 } 4195 case ISD::CONCAT_VECTORS: { 4196 // Determine the minimum number of sign bits across all demanded 4197 // elts of the input vectors. Early out if the result is already 1. 4198 Tmp = std::numeric_limits<unsigned>::max(); 4199 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4200 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4201 unsigned NumSubVectors = Op.getNumOperands(); 4202 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4203 APInt DemandedSub = 4204 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts); 4205 if (!DemandedSub) 4206 continue; 4207 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4208 Tmp = std::min(Tmp, Tmp2); 4209 } 4210 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4211 return Tmp; 4212 } 4213 case ISD::INSERT_SUBVECTOR: { 4214 // Demand any elements from the subvector and the remainder from the src its 4215 // inserted into. 4216 SDValue Src = Op.getOperand(0); 4217 SDValue Sub = Op.getOperand(1); 4218 uint64_t Idx = Op.getConstantOperandVal(2); 4219 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4220 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4221 APInt DemandedSrcElts = DemandedElts; 4222 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx); 4223 4224 Tmp = std::numeric_limits<unsigned>::max(); 4225 if (!!DemandedSubElts) { 4226 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4227 if (Tmp == 1) 4228 return 1; // early-out 4229 } 4230 if (!!DemandedSrcElts) { 4231 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4232 Tmp = std::min(Tmp, Tmp2); 4233 } 4234 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4235 return Tmp; 4236 } 4237 case ISD::ATOMIC_CMP_SWAP: 4238 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 4239 case ISD::ATOMIC_SWAP: 4240 case ISD::ATOMIC_LOAD_ADD: 4241 case ISD::ATOMIC_LOAD_SUB: 4242 case ISD::ATOMIC_LOAD_AND: 4243 case ISD::ATOMIC_LOAD_CLR: 4244 case ISD::ATOMIC_LOAD_OR: 4245 case ISD::ATOMIC_LOAD_XOR: 4246 case ISD::ATOMIC_LOAD_NAND: 4247 case ISD::ATOMIC_LOAD_MIN: 4248 case ISD::ATOMIC_LOAD_MAX: 4249 case ISD::ATOMIC_LOAD_UMIN: 4250 case ISD::ATOMIC_LOAD_UMAX: 4251 case ISD::ATOMIC_LOAD: { 4252 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits(); 4253 // If we are looking at the loaded value. 4254 if (Op.getResNo() == 0) { 4255 if (Tmp == VTBits) 4256 return 1; // early-out 4257 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND) 4258 return VTBits - Tmp + 1; 4259 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND) 4260 return VTBits - Tmp; 4261 } 4262 break; 4263 } 4264 } 4265 4266 // If we are looking at the loaded value of the SDNode. 4267 if (Op.getResNo() == 0) { 4268 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4269 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4270 unsigned ExtType = LD->getExtensionType(); 4271 switch (ExtType) { 4272 default: break; 4273 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4274 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4275 return VTBits - Tmp + 1; 4276 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4277 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4278 return VTBits - Tmp; 4279 case ISD::NON_EXTLOAD: 4280 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4281 // We only need to handle vectors - computeKnownBits should handle 4282 // scalar cases. 4283 Type *CstTy = Cst->getType(); 4284 if (CstTy->isVectorTy() && 4285 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() && 4286 VTBits == CstTy->getScalarSizeInBits()) { 4287 Tmp = VTBits; 4288 for (unsigned i = 0; i != NumElts; ++i) { 4289 if (!DemandedElts[i]) 4290 continue; 4291 if (Constant *Elt = Cst->getAggregateElement(i)) { 4292 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4293 const APInt &Value = CInt->getValue(); 4294 Tmp = std::min(Tmp, Value.getNumSignBits()); 4295 continue; 4296 } 4297 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4298 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4299 Tmp = std::min(Tmp, Value.getNumSignBits()); 4300 continue; 4301 } 4302 } 4303 // Unknown type. Conservatively assume no bits match sign bit. 4304 return 1; 4305 } 4306 return Tmp; 4307 } 4308 } 4309 break; 4310 } 4311 } 4312 } 4313 4314 // Allow the target to implement this method for its nodes. 4315 if (Opcode >= ISD::BUILTIN_OP_END || 4316 Opcode == ISD::INTRINSIC_WO_CHAIN || 4317 Opcode == ISD::INTRINSIC_W_CHAIN || 4318 Opcode == ISD::INTRINSIC_VOID) { 4319 unsigned NumBits = 4320 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4321 if (NumBits > 1) 4322 FirstAnswer = std::max(FirstAnswer, NumBits); 4323 } 4324 4325 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4326 // use this information. 4327 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4328 return std::max(FirstAnswer, Known.countMinSignBits()); 4329 } 4330 4331 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4332 unsigned Depth) const { 4333 unsigned SignBits = ComputeNumSignBits(Op, Depth); 4334 return Op.getScalarValueSizeInBits() - SignBits + 1; 4335 } 4336 4337 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op, 4338 const APInt &DemandedElts, 4339 unsigned Depth) const { 4340 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth); 4341 return Op.getScalarValueSizeInBits() - SignBits + 1; 4342 } 4343 4344 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly, 4345 unsigned Depth) const { 4346 // Early out for FREEZE. 4347 if (Op.getOpcode() == ISD::FREEZE) 4348 return true; 4349 4350 // TODO: Assume we don't know anything for now. 4351 EVT VT = Op.getValueType(); 4352 if (VT.isScalableVector()) 4353 return false; 4354 4355 APInt DemandedElts = VT.isVector() 4356 ? APInt::getAllOnes(VT.getVectorNumElements()) 4357 : APInt(1, 1); 4358 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth); 4359 } 4360 4361 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, 4362 const APInt &DemandedElts, 4363 bool PoisonOnly, 4364 unsigned Depth) const { 4365 unsigned Opcode = Op.getOpcode(); 4366 4367 // Early out for FREEZE. 4368 if (Opcode == ISD::FREEZE) 4369 return true; 4370 4371 if (Depth >= MaxRecursionDepth) 4372 return false; // Limit search depth. 4373 4374 if (isIntOrFPConstant(Op)) 4375 return true; 4376 4377 switch (Opcode) { 4378 case ISD::UNDEF: 4379 return PoisonOnly; 4380 4381 case ISD::BUILD_VECTOR: 4382 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements - 4383 // this shouldn't affect the result. 4384 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) { 4385 if (!DemandedElts[i]) 4386 continue; 4387 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly, 4388 Depth + 1)) 4389 return false; 4390 } 4391 return true; 4392 4393 // TODO: Search for noundef attributes from library functions. 4394 4395 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef. 4396 4397 default: 4398 // Allow the target to implement this method for its nodes. 4399 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN || 4400 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) 4401 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode( 4402 Op, DemandedElts, *this, PoisonOnly, Depth); 4403 break; 4404 } 4405 4406 return false; 4407 } 4408 4409 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4410 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4411 !isa<ConstantSDNode>(Op.getOperand(1))) 4412 return false; 4413 4414 if (Op.getOpcode() == ISD::OR && 4415 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4416 return false; 4417 4418 return true; 4419 } 4420 4421 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4422 // If we're told that NaNs won't happen, assume they won't. 4423 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4424 return true; 4425 4426 if (Depth >= MaxRecursionDepth) 4427 return false; // Limit search depth. 4428 4429 // TODO: Handle vectors. 4430 // If the value is a constant, we can obviously see if it is a NaN or not. 4431 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4432 return !C->getValueAPF().isNaN() || 4433 (SNaN && !C->getValueAPF().isSignaling()); 4434 } 4435 4436 unsigned Opcode = Op.getOpcode(); 4437 switch (Opcode) { 4438 case ISD::FADD: 4439 case ISD::FSUB: 4440 case ISD::FMUL: 4441 case ISD::FDIV: 4442 case ISD::FREM: 4443 case ISD::FSIN: 4444 case ISD::FCOS: { 4445 if (SNaN) 4446 return true; 4447 // TODO: Need isKnownNeverInfinity 4448 return false; 4449 } 4450 case ISD::FCANONICALIZE: 4451 case ISD::FEXP: 4452 case ISD::FEXP2: 4453 case ISD::FTRUNC: 4454 case ISD::FFLOOR: 4455 case ISD::FCEIL: 4456 case ISD::FROUND: 4457 case ISD::FROUNDEVEN: 4458 case ISD::FRINT: 4459 case ISD::FNEARBYINT: { 4460 if (SNaN) 4461 return true; 4462 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4463 } 4464 case ISD::FABS: 4465 case ISD::FNEG: 4466 case ISD::FCOPYSIGN: { 4467 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4468 } 4469 case ISD::SELECT: 4470 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4471 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4472 case ISD::FP_EXTEND: 4473 case ISD::FP_ROUND: { 4474 if (SNaN) 4475 return true; 4476 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4477 } 4478 case ISD::SINT_TO_FP: 4479 case ISD::UINT_TO_FP: 4480 return true; 4481 case ISD::FMA: 4482 case ISD::FMAD: { 4483 if (SNaN) 4484 return true; 4485 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4486 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4487 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4488 } 4489 case ISD::FSQRT: // Need is known positive 4490 case ISD::FLOG: 4491 case ISD::FLOG2: 4492 case ISD::FLOG10: 4493 case ISD::FPOWI: 4494 case ISD::FPOW: { 4495 if (SNaN) 4496 return true; 4497 // TODO: Refine on operand 4498 return false; 4499 } 4500 case ISD::FMINNUM: 4501 case ISD::FMAXNUM: { 4502 // Only one needs to be known not-nan, since it will be returned if the 4503 // other ends up being one. 4504 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4505 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4506 } 4507 case ISD::FMINNUM_IEEE: 4508 case ISD::FMAXNUM_IEEE: { 4509 if (SNaN) 4510 return true; 4511 // This can return a NaN if either operand is an sNaN, or if both operands 4512 // are NaN. 4513 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4514 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4515 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4516 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4517 } 4518 case ISD::FMINIMUM: 4519 case ISD::FMAXIMUM: { 4520 // TODO: Does this quiet or return the origina NaN as-is? 4521 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4522 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4523 } 4524 case ISD::EXTRACT_VECTOR_ELT: { 4525 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4526 } 4527 default: 4528 if (Opcode >= ISD::BUILTIN_OP_END || 4529 Opcode == ISD::INTRINSIC_WO_CHAIN || 4530 Opcode == ISD::INTRINSIC_W_CHAIN || 4531 Opcode == ISD::INTRINSIC_VOID) { 4532 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4533 } 4534 4535 return false; 4536 } 4537 } 4538 4539 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4540 assert(Op.getValueType().isFloatingPoint() && 4541 "Floating point type expected"); 4542 4543 // If the value is a constant, we can obviously see if it is a zero or not. 4544 // TODO: Add BuildVector support. 4545 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4546 return !C->isZero(); 4547 return false; 4548 } 4549 4550 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4551 assert(!Op.getValueType().isFloatingPoint() && 4552 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4553 4554 // If the value is a constant, we can obviously see if it is a zero or not. 4555 if (ISD::matchUnaryPredicate(Op, 4556 [](ConstantSDNode *C) { return !C->isZero(); })) 4557 return true; 4558 4559 // TODO: Recognize more cases here. 4560 switch (Op.getOpcode()) { 4561 default: break; 4562 case ISD::OR: 4563 if (isKnownNeverZero(Op.getOperand(1)) || 4564 isKnownNeverZero(Op.getOperand(0))) 4565 return true; 4566 break; 4567 } 4568 4569 return false; 4570 } 4571 4572 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4573 // Check the obvious case. 4574 if (A == B) return true; 4575 4576 // For for negative and positive zero. 4577 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4578 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4579 if (CA->isZero() && CB->isZero()) return true; 4580 4581 // Otherwise they may not be equal. 4582 return false; 4583 } 4584 4585 // FIXME: unify with llvm::haveNoCommonBitsSet. 4586 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4587 assert(A.getValueType() == B.getValueType() && 4588 "Values must have the same type"); 4589 // Match masked merge pattern (X & ~M) op (Y & M) 4590 if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) { 4591 auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) { 4592 if (isBitwiseNot(NotM, true)) { 4593 SDValue NotOperand = NotM->getOperand(0); 4594 return NotOperand == And->getOperand(0) || 4595 NotOperand == And->getOperand(1); 4596 } 4597 return false; 4598 }; 4599 if (MatchNoCommonBitsPattern(A->getOperand(0), B) || 4600 MatchNoCommonBitsPattern(A->getOperand(1), B) || 4601 MatchNoCommonBitsPattern(B->getOperand(0), A) || 4602 MatchNoCommonBitsPattern(B->getOperand(1), A)) 4603 return true; 4604 } 4605 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A), 4606 computeKnownBits(B)); 4607 } 4608 4609 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4610 SelectionDAG &DAG) { 4611 if (cast<ConstantSDNode>(Step)->isZero()) 4612 return DAG.getConstant(0, DL, VT); 4613 4614 return SDValue(); 4615 } 4616 4617 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4618 ArrayRef<SDValue> Ops, 4619 SelectionDAG &DAG) { 4620 int NumOps = Ops.size(); 4621 assert(NumOps != 0 && "Can't build an empty vector!"); 4622 assert(!VT.isScalableVector() && 4623 "BUILD_VECTOR cannot be used with scalable types"); 4624 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4625 "Incorrect element count in BUILD_VECTOR!"); 4626 4627 // BUILD_VECTOR of UNDEFs is UNDEF. 4628 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4629 return DAG.getUNDEF(VT); 4630 4631 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4632 SDValue IdentitySrc; 4633 bool IsIdentity = true; 4634 for (int i = 0; i != NumOps; ++i) { 4635 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4636 Ops[i].getOperand(0).getValueType() != VT || 4637 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4638 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4639 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4640 IsIdentity = false; 4641 break; 4642 } 4643 IdentitySrc = Ops[i].getOperand(0); 4644 } 4645 if (IsIdentity) 4646 return IdentitySrc; 4647 4648 return SDValue(); 4649 } 4650 4651 /// Try to simplify vector concatenation to an input value, undef, or build 4652 /// vector. 4653 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4654 ArrayRef<SDValue> Ops, 4655 SelectionDAG &DAG) { 4656 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4657 assert(llvm::all_of(Ops, 4658 [Ops](SDValue Op) { 4659 return Ops[0].getValueType() == Op.getValueType(); 4660 }) && 4661 "Concatenation of vectors with inconsistent value types!"); 4662 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4663 VT.getVectorElementCount() && 4664 "Incorrect element count in vector concatenation!"); 4665 4666 if (Ops.size() == 1) 4667 return Ops[0]; 4668 4669 // Concat of UNDEFs is UNDEF. 4670 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4671 return DAG.getUNDEF(VT); 4672 4673 // Scan the operands and look for extract operations from a single source 4674 // that correspond to insertion at the same location via this concatenation: 4675 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4676 SDValue IdentitySrc; 4677 bool IsIdentity = true; 4678 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4679 SDValue Op = Ops[i]; 4680 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4681 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4682 Op.getOperand(0).getValueType() != VT || 4683 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4684 Op.getConstantOperandVal(1) != IdentityIndex) { 4685 IsIdentity = false; 4686 break; 4687 } 4688 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4689 "Unexpected identity source vector for concat of extracts"); 4690 IdentitySrc = Op.getOperand(0); 4691 } 4692 if (IsIdentity) { 4693 assert(IdentitySrc && "Failed to set source vector of extracts"); 4694 return IdentitySrc; 4695 } 4696 4697 // The code below this point is only designed to work for fixed width 4698 // vectors, so we bail out for now. 4699 if (VT.isScalableVector()) 4700 return SDValue(); 4701 4702 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4703 // simplified to one big BUILD_VECTOR. 4704 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4705 EVT SVT = VT.getScalarType(); 4706 SmallVector<SDValue, 16> Elts; 4707 for (SDValue Op : Ops) { 4708 EVT OpVT = Op.getValueType(); 4709 if (Op.isUndef()) 4710 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4711 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4712 Elts.append(Op->op_begin(), Op->op_end()); 4713 else 4714 return SDValue(); 4715 } 4716 4717 // BUILD_VECTOR requires all inputs to be of the same type, find the 4718 // maximum type and extend them all. 4719 for (SDValue Op : Elts) 4720 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4721 4722 if (SVT.bitsGT(VT.getScalarType())) { 4723 for (SDValue &Op : Elts) { 4724 if (Op.isUndef()) 4725 Op = DAG.getUNDEF(SVT); 4726 else 4727 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4728 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4729 : DAG.getSExtOrTrunc(Op, DL, SVT); 4730 } 4731 } 4732 4733 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4734 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4735 return V; 4736 } 4737 4738 /// Gets or creates the specified node. 4739 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4740 FoldingSetNodeID ID; 4741 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4742 void *IP = nullptr; 4743 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4744 return SDValue(E, 0); 4745 4746 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4747 getVTList(VT)); 4748 CSEMap.InsertNode(N, IP); 4749 4750 InsertNode(N); 4751 SDValue V = SDValue(N, 0); 4752 NewSDValueDbgMsg(V, "Creating new node: ", this); 4753 return V; 4754 } 4755 4756 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4757 SDValue Operand) { 4758 SDNodeFlags Flags; 4759 if (Inserter) 4760 Flags = Inserter->getFlags(); 4761 return getNode(Opcode, DL, VT, Operand, Flags); 4762 } 4763 4764 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4765 SDValue Operand, const SDNodeFlags Flags) { 4766 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4767 "Operand is DELETED_NODE!"); 4768 // Constant fold unary operations with an integer constant operand. Even 4769 // opaque constant will be folded, because the folding of unary operations 4770 // doesn't create new constants with different values. Nevertheless, the 4771 // opaque flag is preserved during folding to prevent future folding with 4772 // other constants. 4773 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4774 const APInt &Val = C->getAPIntValue(); 4775 switch (Opcode) { 4776 default: break; 4777 case ISD::SIGN_EXTEND: 4778 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4779 C->isTargetOpcode(), C->isOpaque()); 4780 case ISD::TRUNCATE: 4781 if (C->isOpaque()) 4782 break; 4783 LLVM_FALLTHROUGH; 4784 case ISD::ZERO_EXTEND: 4785 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4786 C->isTargetOpcode(), C->isOpaque()); 4787 case ISD::ANY_EXTEND: 4788 // Some targets like RISCV prefer to sign extend some types. 4789 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT)) 4790 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4791 C->isTargetOpcode(), C->isOpaque()); 4792 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4793 C->isTargetOpcode(), C->isOpaque()); 4794 case ISD::UINT_TO_FP: 4795 case ISD::SINT_TO_FP: { 4796 APFloat apf(EVTToAPFloatSemantics(VT), 4797 APInt::getZero(VT.getSizeInBits())); 4798 (void)apf.convertFromAPInt(Val, 4799 Opcode==ISD::SINT_TO_FP, 4800 APFloat::rmNearestTiesToEven); 4801 return getConstantFP(apf, DL, VT); 4802 } 4803 case ISD::BITCAST: 4804 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4805 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4806 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4807 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4808 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4809 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4810 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4811 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4812 break; 4813 case ISD::ABS: 4814 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4815 C->isOpaque()); 4816 case ISD::BITREVERSE: 4817 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4818 C->isOpaque()); 4819 case ISD::BSWAP: 4820 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4821 C->isOpaque()); 4822 case ISD::CTPOP: 4823 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4824 C->isOpaque()); 4825 case ISD::CTLZ: 4826 case ISD::CTLZ_ZERO_UNDEF: 4827 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4828 C->isOpaque()); 4829 case ISD::CTTZ: 4830 case ISD::CTTZ_ZERO_UNDEF: 4831 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4832 C->isOpaque()); 4833 case ISD::FP16_TO_FP: { 4834 bool Ignored; 4835 APFloat FPV(APFloat::IEEEhalf(), 4836 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4837 4838 // This can return overflow, underflow, or inexact; we don't care. 4839 // FIXME need to be more flexible about rounding mode. 4840 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4841 APFloat::rmNearestTiesToEven, &Ignored); 4842 return getConstantFP(FPV, DL, VT); 4843 } 4844 case ISD::STEP_VECTOR: { 4845 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4846 return V; 4847 break; 4848 } 4849 } 4850 } 4851 4852 // Constant fold unary operations with a floating point constant operand. 4853 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4854 APFloat V = C->getValueAPF(); // make copy 4855 switch (Opcode) { 4856 case ISD::FNEG: 4857 V.changeSign(); 4858 return getConstantFP(V, DL, VT); 4859 case ISD::FABS: 4860 V.clearSign(); 4861 return getConstantFP(V, DL, VT); 4862 case ISD::FCEIL: { 4863 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4864 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4865 return getConstantFP(V, DL, VT); 4866 break; 4867 } 4868 case ISD::FTRUNC: { 4869 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4870 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4871 return getConstantFP(V, DL, VT); 4872 break; 4873 } 4874 case ISD::FFLOOR: { 4875 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4876 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4877 return getConstantFP(V, DL, VT); 4878 break; 4879 } 4880 case ISD::FP_EXTEND: { 4881 bool ignored; 4882 // This can return overflow, underflow, or inexact; we don't care. 4883 // FIXME need to be more flexible about rounding mode. 4884 (void)V.convert(EVTToAPFloatSemantics(VT), 4885 APFloat::rmNearestTiesToEven, &ignored); 4886 return getConstantFP(V, DL, VT); 4887 } 4888 case ISD::FP_TO_SINT: 4889 case ISD::FP_TO_UINT: { 4890 bool ignored; 4891 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4892 // FIXME need to be more flexible about rounding mode. 4893 APFloat::opStatus s = 4894 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4895 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4896 break; 4897 return getConstant(IntVal, DL, VT); 4898 } 4899 case ISD::BITCAST: 4900 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4901 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4902 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16) 4903 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4904 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4905 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4906 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4907 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4908 break; 4909 case ISD::FP_TO_FP16: { 4910 bool Ignored; 4911 // This can return overflow, underflow, or inexact; we don't care. 4912 // FIXME need to be more flexible about rounding mode. 4913 (void)V.convert(APFloat::IEEEhalf(), 4914 APFloat::rmNearestTiesToEven, &Ignored); 4915 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4916 } 4917 } 4918 } 4919 4920 // Constant fold unary operations with a vector integer or float operand. 4921 switch (Opcode) { 4922 default: 4923 // FIXME: Entirely reasonable to perform folding of other unary 4924 // operations here as the need arises. 4925 break; 4926 case ISD::FNEG: 4927 case ISD::FABS: 4928 case ISD::FCEIL: 4929 case ISD::FTRUNC: 4930 case ISD::FFLOOR: 4931 case ISD::FP_EXTEND: 4932 case ISD::FP_TO_SINT: 4933 case ISD::FP_TO_UINT: 4934 case ISD::TRUNCATE: 4935 case ISD::ANY_EXTEND: 4936 case ISD::ZERO_EXTEND: 4937 case ISD::SIGN_EXTEND: 4938 case ISD::UINT_TO_FP: 4939 case ISD::SINT_TO_FP: 4940 case ISD::ABS: 4941 case ISD::BITREVERSE: 4942 case ISD::BSWAP: 4943 case ISD::CTLZ: 4944 case ISD::CTLZ_ZERO_UNDEF: 4945 case ISD::CTTZ: 4946 case ISD::CTTZ_ZERO_UNDEF: 4947 case ISD::CTPOP: { 4948 SDValue Ops = {Operand}; 4949 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops)) 4950 return Fold; 4951 } 4952 } 4953 4954 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4955 switch (Opcode) { 4956 case ISD::STEP_VECTOR: 4957 assert(VT.isScalableVector() && 4958 "STEP_VECTOR can only be used with scalable types"); 4959 assert(OpOpcode == ISD::TargetConstant && 4960 VT.getVectorElementType() == Operand.getValueType() && 4961 "Unexpected step operand"); 4962 break; 4963 case ISD::FREEZE: 4964 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4965 break; 4966 case ISD::TokenFactor: 4967 case ISD::MERGE_VALUES: 4968 case ISD::CONCAT_VECTORS: 4969 return Operand; // Factor, merge or concat of one node? No need. 4970 case ISD::BUILD_VECTOR: { 4971 // Attempt to simplify BUILD_VECTOR. 4972 SDValue Ops[] = {Operand}; 4973 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4974 return V; 4975 break; 4976 } 4977 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4978 case ISD::FP_EXTEND: 4979 assert(VT.isFloatingPoint() && 4980 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4981 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4982 assert((!VT.isVector() || 4983 VT.getVectorElementCount() == 4984 Operand.getValueType().getVectorElementCount()) && 4985 "Vector element count mismatch!"); 4986 assert(Operand.getValueType().bitsLT(VT) && 4987 "Invalid fpext node, dst < src!"); 4988 if (Operand.isUndef()) 4989 return getUNDEF(VT); 4990 break; 4991 case ISD::FP_TO_SINT: 4992 case ISD::FP_TO_UINT: 4993 if (Operand.isUndef()) 4994 return getUNDEF(VT); 4995 break; 4996 case ISD::SINT_TO_FP: 4997 case ISD::UINT_TO_FP: 4998 // [us]itofp(undef) = 0, because the result value is bounded. 4999 if (Operand.isUndef()) 5000 return getConstantFP(0.0, DL, VT); 5001 break; 5002 case ISD::SIGN_EXTEND: 5003 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5004 "Invalid SIGN_EXTEND!"); 5005 assert(VT.isVector() == Operand.getValueType().isVector() && 5006 "SIGN_EXTEND result type type should be vector iff the operand " 5007 "type is vector!"); 5008 if (Operand.getValueType() == VT) return Operand; // noop extension 5009 assert((!VT.isVector() || 5010 VT.getVectorElementCount() == 5011 Operand.getValueType().getVectorElementCount()) && 5012 "Vector element count mismatch!"); 5013 assert(Operand.getValueType().bitsLT(VT) && 5014 "Invalid sext node, dst < src!"); 5015 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 5016 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5017 if (OpOpcode == ISD::UNDEF) 5018 // sext(undef) = 0, because the top bits will all be the same. 5019 return getConstant(0, DL, VT); 5020 break; 5021 case ISD::ZERO_EXTEND: 5022 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5023 "Invalid ZERO_EXTEND!"); 5024 assert(VT.isVector() == Operand.getValueType().isVector() && 5025 "ZERO_EXTEND result type type should be vector iff the operand " 5026 "type is vector!"); 5027 if (Operand.getValueType() == VT) return Operand; // noop extension 5028 assert((!VT.isVector() || 5029 VT.getVectorElementCount() == 5030 Operand.getValueType().getVectorElementCount()) && 5031 "Vector element count mismatch!"); 5032 assert(Operand.getValueType().bitsLT(VT) && 5033 "Invalid zext node, dst < src!"); 5034 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 5035 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 5036 if (OpOpcode == ISD::UNDEF) 5037 // zext(undef) = 0, because the top bits will be zero. 5038 return getConstant(0, DL, VT); 5039 break; 5040 case ISD::ANY_EXTEND: 5041 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5042 "Invalid ANY_EXTEND!"); 5043 assert(VT.isVector() == Operand.getValueType().isVector() && 5044 "ANY_EXTEND result type type should be vector iff the operand " 5045 "type is vector!"); 5046 if (Operand.getValueType() == VT) return Operand; // noop extension 5047 assert((!VT.isVector() || 5048 VT.getVectorElementCount() == 5049 Operand.getValueType().getVectorElementCount()) && 5050 "Vector element count mismatch!"); 5051 assert(Operand.getValueType().bitsLT(VT) && 5052 "Invalid anyext node, dst < src!"); 5053 5054 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5055 OpOpcode == ISD::ANY_EXTEND) 5056 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 5057 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5058 if (OpOpcode == ISD::UNDEF) 5059 return getUNDEF(VT); 5060 5061 // (ext (trunc x)) -> x 5062 if (OpOpcode == ISD::TRUNCATE) { 5063 SDValue OpOp = Operand.getOperand(0); 5064 if (OpOp.getValueType() == VT) { 5065 transferDbgValues(Operand, OpOp); 5066 return OpOp; 5067 } 5068 } 5069 break; 5070 case ISD::TRUNCATE: 5071 assert(VT.isInteger() && Operand.getValueType().isInteger() && 5072 "Invalid TRUNCATE!"); 5073 assert(VT.isVector() == Operand.getValueType().isVector() && 5074 "TRUNCATE result type type should be vector iff the operand " 5075 "type is vector!"); 5076 if (Operand.getValueType() == VT) return Operand; // noop truncate 5077 assert((!VT.isVector() || 5078 VT.getVectorElementCount() == 5079 Operand.getValueType().getVectorElementCount()) && 5080 "Vector element count mismatch!"); 5081 assert(Operand.getValueType().bitsGT(VT) && 5082 "Invalid truncate node, src < dst!"); 5083 if (OpOpcode == ISD::TRUNCATE) 5084 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5085 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 5086 OpOpcode == ISD::ANY_EXTEND) { 5087 // If the source is smaller than the dest, we still need an extend. 5088 if (Operand.getOperand(0).getValueType().getScalarType() 5089 .bitsLT(VT.getScalarType())) 5090 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 5091 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 5092 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 5093 return Operand.getOperand(0); 5094 } 5095 if (OpOpcode == ISD::UNDEF) 5096 return getUNDEF(VT); 5097 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes) 5098 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0)); 5099 break; 5100 case ISD::ANY_EXTEND_VECTOR_INREG: 5101 case ISD::ZERO_EXTEND_VECTOR_INREG: 5102 case ISD::SIGN_EXTEND_VECTOR_INREG: 5103 assert(VT.isVector() && "This DAG node is restricted to vector types."); 5104 assert(Operand.getValueType().bitsLE(VT) && 5105 "The input must be the same size or smaller than the result."); 5106 assert(VT.getVectorMinNumElements() < 5107 Operand.getValueType().getVectorMinNumElements() && 5108 "The destination vector type must have fewer lanes than the input."); 5109 break; 5110 case ISD::ABS: 5111 assert(VT.isInteger() && VT == Operand.getValueType() && 5112 "Invalid ABS!"); 5113 if (OpOpcode == ISD::UNDEF) 5114 return getUNDEF(VT); 5115 break; 5116 case ISD::BSWAP: 5117 assert(VT.isInteger() && VT == Operand.getValueType() && 5118 "Invalid BSWAP!"); 5119 assert((VT.getScalarSizeInBits() % 16 == 0) && 5120 "BSWAP types must be a multiple of 16 bits!"); 5121 if (OpOpcode == ISD::UNDEF) 5122 return getUNDEF(VT); 5123 // bswap(bswap(X)) -> X. 5124 if (OpOpcode == ISD::BSWAP) 5125 return Operand.getOperand(0); 5126 break; 5127 case ISD::BITREVERSE: 5128 assert(VT.isInteger() && VT == Operand.getValueType() && 5129 "Invalid BITREVERSE!"); 5130 if (OpOpcode == ISD::UNDEF) 5131 return getUNDEF(VT); 5132 break; 5133 case ISD::BITCAST: 5134 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 5135 "Cannot BITCAST between types of different sizes!"); 5136 if (VT == Operand.getValueType()) return Operand; // noop conversion. 5137 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 5138 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 5139 if (OpOpcode == ISD::UNDEF) 5140 return getUNDEF(VT); 5141 break; 5142 case ISD::SCALAR_TO_VECTOR: 5143 assert(VT.isVector() && !Operand.getValueType().isVector() && 5144 (VT.getVectorElementType() == Operand.getValueType() || 5145 (VT.getVectorElementType().isInteger() && 5146 Operand.getValueType().isInteger() && 5147 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 5148 "Illegal SCALAR_TO_VECTOR node!"); 5149 if (OpOpcode == ISD::UNDEF) 5150 return getUNDEF(VT); 5151 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 5152 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 5153 isa<ConstantSDNode>(Operand.getOperand(1)) && 5154 Operand.getConstantOperandVal(1) == 0 && 5155 Operand.getOperand(0).getValueType() == VT) 5156 return Operand.getOperand(0); 5157 break; 5158 case ISD::FNEG: 5159 // Negation of an unknown bag of bits is still completely undefined. 5160 if (OpOpcode == ISD::UNDEF) 5161 return getUNDEF(VT); 5162 5163 if (OpOpcode == ISD::FNEG) // --X -> X 5164 return Operand.getOperand(0); 5165 break; 5166 case ISD::FABS: 5167 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 5168 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 5169 break; 5170 case ISD::VSCALE: 5171 assert(VT == Operand.getValueType() && "Unexpected VT!"); 5172 break; 5173 case ISD::CTPOP: 5174 if (Operand.getValueType().getScalarType() == MVT::i1) 5175 return Operand; 5176 break; 5177 case ISD::CTLZ: 5178 case ISD::CTTZ: 5179 if (Operand.getValueType().getScalarType() == MVT::i1) 5180 return getNOT(DL, Operand, Operand.getValueType()); 5181 break; 5182 case ISD::VECREDUCE_SMIN: 5183 case ISD::VECREDUCE_UMAX: 5184 if (Operand.getValueType().getScalarType() == MVT::i1) 5185 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 5186 break; 5187 case ISD::VECREDUCE_SMAX: 5188 case ISD::VECREDUCE_UMIN: 5189 if (Operand.getValueType().getScalarType() == MVT::i1) 5190 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 5191 break; 5192 } 5193 5194 SDNode *N; 5195 SDVTList VTs = getVTList(VT); 5196 SDValue Ops[] = {Operand}; 5197 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 5198 FoldingSetNodeID ID; 5199 AddNodeIDNode(ID, Opcode, VTs, Ops); 5200 void *IP = nullptr; 5201 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5202 E->intersectFlagsWith(Flags); 5203 return SDValue(E, 0); 5204 } 5205 5206 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5207 N->setFlags(Flags); 5208 createOperands(N, Ops); 5209 CSEMap.InsertNode(N, IP); 5210 } else { 5211 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5212 createOperands(N, Ops); 5213 } 5214 5215 InsertNode(N); 5216 SDValue V = SDValue(N, 0); 5217 NewSDValueDbgMsg(V, "Creating new node: ", this); 5218 return V; 5219 } 5220 5221 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 5222 const APInt &C2) { 5223 switch (Opcode) { 5224 case ISD::ADD: return C1 + C2; 5225 case ISD::SUB: return C1 - C2; 5226 case ISD::MUL: return C1 * C2; 5227 case ISD::AND: return C1 & C2; 5228 case ISD::OR: return C1 | C2; 5229 case ISD::XOR: return C1 ^ C2; 5230 case ISD::SHL: return C1 << C2; 5231 case ISD::SRL: return C1.lshr(C2); 5232 case ISD::SRA: return C1.ashr(C2); 5233 case ISD::ROTL: return C1.rotl(C2); 5234 case ISD::ROTR: return C1.rotr(C2); 5235 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 5236 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 5237 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 5238 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 5239 case ISD::SADDSAT: return C1.sadd_sat(C2); 5240 case ISD::UADDSAT: return C1.uadd_sat(C2); 5241 case ISD::SSUBSAT: return C1.ssub_sat(C2); 5242 case ISD::USUBSAT: return C1.usub_sat(C2); 5243 case ISD::UDIV: 5244 if (!C2.getBoolValue()) 5245 break; 5246 return C1.udiv(C2); 5247 case ISD::UREM: 5248 if (!C2.getBoolValue()) 5249 break; 5250 return C1.urem(C2); 5251 case ISD::SDIV: 5252 if (!C2.getBoolValue()) 5253 break; 5254 return C1.sdiv(C2); 5255 case ISD::SREM: 5256 if (!C2.getBoolValue()) 5257 break; 5258 return C1.srem(C2); 5259 case ISD::MULHS: { 5260 unsigned FullWidth = C1.getBitWidth() * 2; 5261 APInt C1Ext = C1.sext(FullWidth); 5262 APInt C2Ext = C2.sext(FullWidth); 5263 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5264 } 5265 case ISD::MULHU: { 5266 unsigned FullWidth = C1.getBitWidth() * 2; 5267 APInt C1Ext = C1.zext(FullWidth); 5268 APInt C2Ext = C2.zext(FullWidth); 5269 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth()); 5270 } 5271 } 5272 return llvm::None; 5273 } 5274 5275 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5276 const GlobalAddressSDNode *GA, 5277 const SDNode *N2) { 5278 if (GA->getOpcode() != ISD::GlobalAddress) 5279 return SDValue(); 5280 if (!TLI->isOffsetFoldingLegal(GA)) 5281 return SDValue(); 5282 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5283 if (!C2) 5284 return SDValue(); 5285 int64_t Offset = C2->getSExtValue(); 5286 switch (Opcode) { 5287 case ISD::ADD: break; 5288 case ISD::SUB: Offset = -uint64_t(Offset); break; 5289 default: return SDValue(); 5290 } 5291 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5292 GA->getOffset() + uint64_t(Offset)); 5293 } 5294 5295 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5296 switch (Opcode) { 5297 case ISD::SDIV: 5298 case ISD::UDIV: 5299 case ISD::SREM: 5300 case ISD::UREM: { 5301 // If a divisor is zero/undef or any element of a divisor vector is 5302 // zero/undef, the whole op is undef. 5303 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5304 SDValue Divisor = Ops[1]; 5305 if (Divisor.isUndef() || isNullConstant(Divisor)) 5306 return true; 5307 5308 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5309 llvm::any_of(Divisor->op_values(), 5310 [](SDValue V) { return V.isUndef() || 5311 isNullConstant(V); }); 5312 // TODO: Handle signed overflow. 5313 } 5314 // TODO: Handle oversized shifts. 5315 default: 5316 return false; 5317 } 5318 } 5319 5320 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5321 EVT VT, ArrayRef<SDValue> Ops) { 5322 // If the opcode is a target-specific ISD node, there's nothing we can 5323 // do here and the operand rules may not line up with the below, so 5324 // bail early. 5325 // We can't create a scalar CONCAT_VECTORS so skip it. It will break 5326 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by 5327 // foldCONCAT_VECTORS in getNode before this is called. 5328 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS) 5329 return SDValue(); 5330 5331 unsigned NumOps = Ops.size(); 5332 if (NumOps == 0) 5333 return SDValue(); 5334 5335 if (isUndef(Opcode, Ops)) 5336 return getUNDEF(VT); 5337 5338 // Handle binops special cases. 5339 if (NumOps == 2) { 5340 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1])) 5341 return CFP; 5342 5343 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) { 5344 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) { 5345 if (C1->isOpaque() || C2->isOpaque()) 5346 return SDValue(); 5347 5348 Optional<APInt> FoldAttempt = 5349 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5350 if (!FoldAttempt) 5351 return SDValue(); 5352 5353 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5354 assert((!Folded || !VT.isVector()) && 5355 "Can't fold vectors ops with scalar operands"); 5356 return Folded; 5357 } 5358 } 5359 5360 // fold (add Sym, c) -> Sym+c 5361 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0])) 5362 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode()); 5363 if (TLI->isCommutativeBinOp(Opcode)) 5364 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1])) 5365 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode()); 5366 } 5367 5368 // This is for vector folding only from here on. 5369 if (!VT.isVector()) 5370 return SDValue(); 5371 5372 ElementCount NumElts = VT.getVectorElementCount(); 5373 5374 // See if we can fold through bitcasted integer ops. 5375 // TODO: Can we handle undef elements? 5376 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() && 5377 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT && 5378 Ops[0].getOpcode() == ISD::BITCAST && 5379 Ops[1].getOpcode() == ISD::BITCAST) { 5380 SDValue N1 = peekThroughBitcasts(Ops[0]); 5381 SDValue N2 = peekThroughBitcasts(Ops[1]); 5382 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5383 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5384 EVT BVVT = N1.getValueType(); 5385 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) { 5386 bool IsLE = getDataLayout().isLittleEndian(); 5387 unsigned EltBits = VT.getScalarSizeInBits(); 5388 SmallVector<APInt> RawBits1, RawBits2; 5389 BitVector UndefElts1, UndefElts2; 5390 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) && 5391 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) && 5392 UndefElts1.none() && UndefElts2.none()) { 5393 SmallVector<APInt> RawBits; 5394 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) { 5395 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]); 5396 if (!Fold) 5397 break; 5398 RawBits.push_back(Fold.getValue()); 5399 } 5400 if (RawBits.size() == NumElts.getFixedValue()) { 5401 // We have constant folded, but we need to cast this again back to 5402 // the original (possibly legalized) type. 5403 SmallVector<APInt> DstBits; 5404 BitVector DstUndefs; 5405 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(), 5406 DstBits, RawBits, DstUndefs, 5407 BitVector(RawBits.size(), false)); 5408 EVT BVEltVT = BV1->getOperand(0).getValueType(); 5409 unsigned BVEltBits = BVEltVT.getSizeInBits(); 5410 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT)); 5411 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) { 5412 if (DstUndefs[I]) 5413 continue; 5414 Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT); 5415 } 5416 return getBitcast(VT, getBuildVector(BVVT, DL, Ops)); 5417 } 5418 } 5419 } 5420 } 5421 5422 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 5423 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1)) 5424 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) && 5425 Ops[0].getOpcode() == ISD::STEP_VECTOR) { 5426 APInt RHSVal; 5427 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) { 5428 APInt NewStep = Opcode == ISD::MUL 5429 ? Ops[0].getConstantOperandAPInt(0) * RHSVal 5430 : Ops[0].getConstantOperandAPInt(0) << RHSVal; 5431 return getStepVector(DL, VT, NewStep); 5432 } 5433 } 5434 5435 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) { 5436 return !Op.getValueType().isVector() || 5437 Op.getValueType().getVectorElementCount() == NumElts; 5438 }; 5439 5440 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) { 5441 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE || 5442 Op.getOpcode() == ISD::BUILD_VECTOR || 5443 Op.getOpcode() == ISD::SPLAT_VECTOR; 5444 }; 5445 5446 // All operands must be vector types with the same number of elements as 5447 // the result type and must be either UNDEF or a build/splat vector 5448 // or UNDEF scalars. 5449 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) || 5450 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5451 return SDValue(); 5452 5453 // If we are comparing vectors, then the result needs to be a i1 boolean 5454 // that is then sign-extended back to the legal result type. 5455 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5456 5457 // Find legal integer scalar type for constant promotion and 5458 // ensure that its scalar size is at least as large as source. 5459 EVT LegalSVT = VT.getScalarType(); 5460 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5461 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5462 if (LegalSVT.bitsLT(VT.getScalarType())) 5463 return SDValue(); 5464 } 5465 5466 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We 5467 // only have one operand to check. For fixed-length vector types we may have 5468 // a combination of BUILD_VECTOR and SPLAT_VECTOR. 5469 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue(); 5470 5471 // Constant fold each scalar lane separately. 5472 SmallVector<SDValue, 4> ScalarResults; 5473 for (unsigned I = 0; I != NumVectorElts; I++) { 5474 SmallVector<SDValue, 4> ScalarOps; 5475 for (SDValue Op : Ops) { 5476 EVT InSVT = Op.getValueType().getScalarType(); 5477 if (Op.getOpcode() != ISD::BUILD_VECTOR && 5478 Op.getOpcode() != ISD::SPLAT_VECTOR) { 5479 if (Op.isUndef()) 5480 ScalarOps.push_back(getUNDEF(InSVT)); 5481 else 5482 ScalarOps.push_back(Op); 5483 continue; 5484 } 5485 5486 SDValue ScalarOp = 5487 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I); 5488 EVT ScalarVT = ScalarOp.getValueType(); 5489 5490 // Build vector (integer) scalar operands may need implicit 5491 // truncation - do this before constant folding. 5492 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5493 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5494 5495 ScalarOps.push_back(ScalarOp); 5496 } 5497 5498 // Constant fold the scalar operands. 5499 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps); 5500 5501 // Legalize the (integer) scalar constant if necessary. 5502 if (LegalSVT != SVT) 5503 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5504 5505 // Scalar folding only succeeded if the result is a constant or UNDEF. 5506 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5507 ScalarResult.getOpcode() != ISD::ConstantFP) 5508 return SDValue(); 5509 ScalarResults.push_back(ScalarResult); 5510 } 5511 5512 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0]) 5513 : getBuildVector(VT, DL, ScalarResults); 5514 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5515 return V; 5516 } 5517 5518 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5519 EVT VT, SDValue N1, SDValue N2) { 5520 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5521 // should. That will require dealing with a potentially non-default 5522 // rounding mode, checking the "opStatus" return value from the APFloat 5523 // math calculations, and possibly other variations. 5524 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false); 5525 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false); 5526 if (N1CFP && N2CFP) { 5527 APFloat C1 = N1CFP->getValueAPF(); // make copy 5528 const APFloat &C2 = N2CFP->getValueAPF(); 5529 switch (Opcode) { 5530 case ISD::FADD: 5531 C1.add(C2, APFloat::rmNearestTiesToEven); 5532 return getConstantFP(C1, DL, VT); 5533 case ISD::FSUB: 5534 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5535 return getConstantFP(C1, DL, VT); 5536 case ISD::FMUL: 5537 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5538 return getConstantFP(C1, DL, VT); 5539 case ISD::FDIV: 5540 C1.divide(C2, APFloat::rmNearestTiesToEven); 5541 return getConstantFP(C1, DL, VT); 5542 case ISD::FREM: 5543 C1.mod(C2); 5544 return getConstantFP(C1, DL, VT); 5545 case ISD::FCOPYSIGN: 5546 C1.copySign(C2); 5547 return getConstantFP(C1, DL, VT); 5548 case ISD::FMINNUM: 5549 return getConstantFP(minnum(C1, C2), DL, VT); 5550 case ISD::FMAXNUM: 5551 return getConstantFP(maxnum(C1, C2), DL, VT); 5552 case ISD::FMINIMUM: 5553 return getConstantFP(minimum(C1, C2), DL, VT); 5554 case ISD::FMAXIMUM: 5555 return getConstantFP(maximum(C1, C2), DL, VT); 5556 default: break; 5557 } 5558 } 5559 if (N1CFP && Opcode == ISD::FP_ROUND) { 5560 APFloat C1 = N1CFP->getValueAPF(); // make copy 5561 bool Unused; 5562 // This can return overflow, underflow, or inexact; we don't care. 5563 // FIXME need to be more flexible about rounding mode. 5564 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5565 &Unused); 5566 return getConstantFP(C1, DL, VT); 5567 } 5568 5569 switch (Opcode) { 5570 case ISD::FSUB: 5571 // -0.0 - undef --> undef (consistent with "fneg undef") 5572 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true)) 5573 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef()) 5574 return getUNDEF(VT); 5575 LLVM_FALLTHROUGH; 5576 5577 case ISD::FADD: 5578 case ISD::FMUL: 5579 case ISD::FDIV: 5580 case ISD::FREM: 5581 // If both operands are undef, the result is undef. If 1 operand is undef, 5582 // the result is NaN. This should match the behavior of the IR optimizer. 5583 if (N1.isUndef() && N2.isUndef()) 5584 return getUNDEF(VT); 5585 if (N1.isUndef() || N2.isUndef()) 5586 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5587 } 5588 return SDValue(); 5589 } 5590 5591 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5592 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5593 5594 // There's no need to assert on a byte-aligned pointer. All pointers are at 5595 // least byte aligned. 5596 if (A == Align(1)) 5597 return Val; 5598 5599 FoldingSetNodeID ID; 5600 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5601 ID.AddInteger(A.value()); 5602 5603 void *IP = nullptr; 5604 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5605 return SDValue(E, 0); 5606 5607 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5608 Val.getValueType(), A); 5609 createOperands(N, {Val}); 5610 5611 CSEMap.InsertNode(N, IP); 5612 InsertNode(N); 5613 5614 SDValue V(N, 0); 5615 NewSDValueDbgMsg(V, "Creating new node: ", this); 5616 return V; 5617 } 5618 5619 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5620 SDValue N1, SDValue N2) { 5621 SDNodeFlags Flags; 5622 if (Inserter) 5623 Flags = Inserter->getFlags(); 5624 return getNode(Opcode, DL, VT, N1, N2, Flags); 5625 } 5626 5627 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5628 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5629 assert(N1.getOpcode() != ISD::DELETED_NODE && 5630 N2.getOpcode() != ISD::DELETED_NODE && 5631 "Operand is DELETED_NODE!"); 5632 // Canonicalize constant to RHS if commutative. 5633 if (TLI->isCommutativeBinOp(Opcode)) { 5634 bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1); 5635 bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2); 5636 bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1); 5637 bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2); 5638 if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP)) 5639 std::swap(N1, N2); 5640 } 5641 5642 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5643 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5644 5645 switch (Opcode) { 5646 default: break; 5647 case ISD::TokenFactor: 5648 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5649 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5650 // Fold trivial token factors. 5651 if (N1.getOpcode() == ISD::EntryToken) return N2; 5652 if (N2.getOpcode() == ISD::EntryToken) return N1; 5653 if (N1 == N2) return N1; 5654 break; 5655 case ISD::BUILD_VECTOR: { 5656 // Attempt to simplify BUILD_VECTOR. 5657 SDValue Ops[] = {N1, N2}; 5658 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5659 return V; 5660 break; 5661 } 5662 case ISD::CONCAT_VECTORS: { 5663 SDValue Ops[] = {N1, N2}; 5664 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5665 return V; 5666 break; 5667 } 5668 case ISD::AND: 5669 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5670 assert(N1.getValueType() == N2.getValueType() && 5671 N1.getValueType() == VT && "Binary operator types must match!"); 5672 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5673 // worth handling here. 5674 if (N2C && N2C->isZero()) 5675 return N2; 5676 if (N2C && N2C->isAllOnes()) // X & -1 -> X 5677 return N1; 5678 break; 5679 case ISD::OR: 5680 case ISD::XOR: 5681 case ISD::ADD: 5682 case ISD::SUB: 5683 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5684 assert(N1.getValueType() == N2.getValueType() && 5685 N1.getValueType() == VT && "Binary operator types must match!"); 5686 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5687 // it's worth handling here. 5688 if (N2C && N2C->isZero()) 5689 return N1; 5690 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5691 VT.getVectorElementType() == MVT::i1) 5692 return getNode(ISD::XOR, DL, VT, N1, N2); 5693 break; 5694 case ISD::MUL: 5695 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5696 assert(N1.getValueType() == N2.getValueType() && 5697 N1.getValueType() == VT && "Binary operator types must match!"); 5698 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5699 return getNode(ISD::AND, DL, VT, N1, N2); 5700 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5701 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5702 const APInt &N2CImm = N2C->getAPIntValue(); 5703 return getVScale(DL, VT, MulImm * N2CImm); 5704 } 5705 break; 5706 case ISD::UDIV: 5707 case ISD::UREM: 5708 case ISD::MULHU: 5709 case ISD::MULHS: 5710 case ISD::SDIV: 5711 case ISD::SREM: 5712 case ISD::SADDSAT: 5713 case ISD::SSUBSAT: 5714 case ISD::UADDSAT: 5715 case ISD::USUBSAT: 5716 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5717 assert(N1.getValueType() == N2.getValueType() && 5718 N1.getValueType() == VT && "Binary operator types must match!"); 5719 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5720 // fold (add_sat x, y) -> (or x, y) for bool types. 5721 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5722 return getNode(ISD::OR, DL, VT, N1, N2); 5723 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5724 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5725 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5726 } 5727 break; 5728 case ISD::SMIN: 5729 case ISD::UMAX: 5730 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5731 assert(N1.getValueType() == N2.getValueType() && 5732 N1.getValueType() == VT && "Binary operator types must match!"); 5733 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5734 return getNode(ISD::OR, DL, VT, N1, N2); 5735 break; 5736 case ISD::SMAX: 5737 case ISD::UMIN: 5738 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5739 assert(N1.getValueType() == N2.getValueType() && 5740 N1.getValueType() == VT && "Binary operator types must match!"); 5741 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5742 return getNode(ISD::AND, DL, VT, N1, N2); 5743 break; 5744 case ISD::FADD: 5745 case ISD::FSUB: 5746 case ISD::FMUL: 5747 case ISD::FDIV: 5748 case ISD::FREM: 5749 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5750 assert(N1.getValueType() == N2.getValueType() && 5751 N1.getValueType() == VT && "Binary operator types must match!"); 5752 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5753 return V; 5754 break; 5755 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5756 assert(N1.getValueType() == VT && 5757 N1.getValueType().isFloatingPoint() && 5758 N2.getValueType().isFloatingPoint() && 5759 "Invalid FCOPYSIGN!"); 5760 break; 5761 case ISD::SHL: 5762 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5763 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5764 const APInt &ShiftImm = N2C->getAPIntValue(); 5765 return getVScale(DL, VT, MulImm << ShiftImm); 5766 } 5767 LLVM_FALLTHROUGH; 5768 case ISD::SRA: 5769 case ISD::SRL: 5770 if (SDValue V = simplifyShift(N1, N2)) 5771 return V; 5772 LLVM_FALLTHROUGH; 5773 case ISD::ROTL: 5774 case ISD::ROTR: 5775 assert(VT == N1.getValueType() && 5776 "Shift operators return type must be the same as their first arg"); 5777 assert(VT.isInteger() && N2.getValueType().isInteger() && 5778 "Shifts only work on integers"); 5779 assert((!VT.isVector() || VT == N2.getValueType()) && 5780 "Vector shift amounts must be in the same as their first arg"); 5781 // Verify that the shift amount VT is big enough to hold valid shift 5782 // amounts. This catches things like trying to shift an i1024 value by an 5783 // i8, which is easy to fall into in generic code that uses 5784 // TLI.getShiftAmount(). 5785 assert(N2.getValueType().getScalarSizeInBits() >= 5786 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5787 "Invalid use of small shift amount with oversized value!"); 5788 5789 // Always fold shifts of i1 values so the code generator doesn't need to 5790 // handle them. Since we know the size of the shift has to be less than the 5791 // size of the value, the shift/rotate count is guaranteed to be zero. 5792 if (VT == MVT::i1) 5793 return N1; 5794 if (N2C && N2C->isZero()) 5795 return N1; 5796 break; 5797 case ISD::FP_ROUND: 5798 assert(VT.isFloatingPoint() && 5799 N1.getValueType().isFloatingPoint() && 5800 VT.bitsLE(N1.getValueType()) && 5801 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5802 "Invalid FP_ROUND!"); 5803 if (N1.getValueType() == VT) return N1; // noop conversion. 5804 break; 5805 case ISD::AssertSext: 5806 case ISD::AssertZext: { 5807 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5808 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5809 assert(VT.isInteger() && EVT.isInteger() && 5810 "Cannot *_EXTEND_INREG FP types"); 5811 assert(!EVT.isVector() && 5812 "AssertSExt/AssertZExt type should be the vector element type " 5813 "rather than the vector type!"); 5814 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5815 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5816 break; 5817 } 5818 case ISD::SIGN_EXTEND_INREG: { 5819 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5820 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5821 assert(VT.isInteger() && EVT.isInteger() && 5822 "Cannot *_EXTEND_INREG FP types"); 5823 assert(EVT.isVector() == VT.isVector() && 5824 "SIGN_EXTEND_INREG type should be vector iff the operand " 5825 "type is vector!"); 5826 assert((!EVT.isVector() || 5827 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5828 "Vector element counts must match in SIGN_EXTEND_INREG"); 5829 assert(EVT.bitsLE(VT) && "Not extending!"); 5830 if (EVT == VT) return N1; // Not actually extending 5831 5832 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5833 unsigned FromBits = EVT.getScalarSizeInBits(); 5834 Val <<= Val.getBitWidth() - FromBits; 5835 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5836 return getConstant(Val, DL, ConstantVT); 5837 }; 5838 5839 if (N1C) { 5840 const APInt &Val = N1C->getAPIntValue(); 5841 return SignExtendInReg(Val, VT); 5842 } 5843 5844 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5845 SmallVector<SDValue, 8> Ops; 5846 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5847 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5848 SDValue Op = N1.getOperand(i); 5849 if (Op.isUndef()) { 5850 Ops.push_back(getUNDEF(OpVT)); 5851 continue; 5852 } 5853 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5854 APInt Val = C->getAPIntValue(); 5855 Ops.push_back(SignExtendInReg(Val, OpVT)); 5856 } 5857 return getBuildVector(VT, DL, Ops); 5858 } 5859 break; 5860 } 5861 case ISD::FP_TO_SINT_SAT: 5862 case ISD::FP_TO_UINT_SAT: { 5863 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() && 5864 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT"); 5865 assert(N1.getValueType().isVector() == VT.isVector() && 5866 "FP_TO_*INT_SAT type should be vector iff the operand type is " 5867 "vector!"); 5868 assert((!VT.isVector() || VT.getVectorNumElements() == 5869 N1.getValueType().getVectorNumElements()) && 5870 "Vector element counts must match in FP_TO_*INT_SAT"); 5871 assert(!cast<VTSDNode>(N2)->getVT().isVector() && 5872 "Type to saturate to must be a scalar."); 5873 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) && 5874 "Not extending!"); 5875 break; 5876 } 5877 case ISD::EXTRACT_VECTOR_ELT: 5878 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5879 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5880 element type of the vector."); 5881 5882 // Extract from an undefined value or using an undefined index is undefined. 5883 if (N1.isUndef() || N2.isUndef()) 5884 return getUNDEF(VT); 5885 5886 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5887 // vectors. For scalable vectors we will provide appropriate support for 5888 // dealing with arbitrary indices. 5889 if (N2C && N1.getValueType().isFixedLengthVector() && 5890 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5891 return getUNDEF(VT); 5892 5893 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5894 // expanding copies of large vectors from registers. This only works for 5895 // fixed length vectors, since we need to know the exact number of 5896 // elements. 5897 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5898 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5899 unsigned Factor = 5900 N1.getOperand(0).getValueType().getVectorNumElements(); 5901 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5902 N1.getOperand(N2C->getZExtValue() / Factor), 5903 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5904 } 5905 5906 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5907 // lowering is expanding large vector constants. 5908 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5909 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5910 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5911 N1.getValueType().isFixedLengthVector()) && 5912 "BUILD_VECTOR used for scalable vectors"); 5913 unsigned Index = 5914 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5915 SDValue Elt = N1.getOperand(Index); 5916 5917 if (VT != Elt.getValueType()) 5918 // If the vector element type is not legal, the BUILD_VECTOR operands 5919 // are promoted and implicitly truncated, and the result implicitly 5920 // extended. Make that explicit here. 5921 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5922 5923 return Elt; 5924 } 5925 5926 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5927 // operations are lowered to scalars. 5928 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5929 // If the indices are the same, return the inserted element else 5930 // if the indices are known different, extract the element from 5931 // the original vector. 5932 SDValue N1Op2 = N1.getOperand(2); 5933 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5934 5935 if (N1Op2C && N2C) { 5936 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5937 if (VT == N1.getOperand(1).getValueType()) 5938 return N1.getOperand(1); 5939 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5940 } 5941 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5942 } 5943 } 5944 5945 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5946 // when vector types are scalarized and v1iX is legal. 5947 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5948 // Here we are completely ignoring the extract element index (N2), 5949 // which is fine for fixed width vectors, since any index other than 0 5950 // is undefined anyway. However, this cannot be ignored for scalable 5951 // vectors - in theory we could support this, but we don't want to do this 5952 // without a profitability check. 5953 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5954 N1.getValueType().isFixedLengthVector() && 5955 N1.getValueType().getVectorNumElements() == 1) { 5956 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5957 N1.getOperand(1)); 5958 } 5959 break; 5960 case ISD::EXTRACT_ELEMENT: 5961 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5962 assert(!N1.getValueType().isVector() && !VT.isVector() && 5963 (N1.getValueType().isInteger() == VT.isInteger()) && 5964 N1.getValueType() != VT && 5965 "Wrong types for EXTRACT_ELEMENT!"); 5966 5967 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5968 // 64-bit integers into 32-bit parts. Instead of building the extract of 5969 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5970 if (N1.getOpcode() == ISD::BUILD_PAIR) 5971 return N1.getOperand(N2C->getZExtValue()); 5972 5973 // EXTRACT_ELEMENT of a constant int is also very common. 5974 if (N1C) { 5975 unsigned ElementSize = VT.getSizeInBits(); 5976 unsigned Shift = ElementSize * N2C->getZExtValue(); 5977 const APInt &Val = N1C->getAPIntValue(); 5978 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 5979 } 5980 break; 5981 case ISD::EXTRACT_SUBVECTOR: { 5982 EVT N1VT = N1.getValueType(); 5983 assert(VT.isVector() && N1VT.isVector() && 5984 "Extract subvector VTs must be vectors!"); 5985 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5986 "Extract subvector VTs must have the same element type!"); 5987 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5988 "Cannot extract a scalable vector from a fixed length vector!"); 5989 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5990 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5991 "Extract subvector must be from larger vector to smaller vector!"); 5992 assert(N2C && "Extract subvector index must be a constant"); 5993 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5994 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5995 N1VT.getVectorMinNumElements()) && 5996 "Extract subvector overflow!"); 5997 assert(N2C->getAPIntValue().getBitWidth() == 5998 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5999 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 6000 6001 // Trivial extraction. 6002 if (VT == N1VT) 6003 return N1; 6004 6005 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 6006 if (N1.isUndef()) 6007 return getUNDEF(VT); 6008 6009 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 6010 // the concat have the same type as the extract. 6011 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 6012 VT == N1.getOperand(0).getValueType()) { 6013 unsigned Factor = VT.getVectorMinNumElements(); 6014 return N1.getOperand(N2C->getZExtValue() / Factor); 6015 } 6016 6017 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 6018 // during shuffle legalization. 6019 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 6020 VT == N1.getOperand(1).getValueType()) 6021 return N1.getOperand(1); 6022 break; 6023 } 6024 } 6025 6026 // Perform trivial constant folding. 6027 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 6028 return SV; 6029 6030 // Canonicalize an UNDEF to the RHS, even over a constant. 6031 if (N1.isUndef()) { 6032 if (TLI->isCommutativeBinOp(Opcode)) { 6033 std::swap(N1, N2); 6034 } else { 6035 switch (Opcode) { 6036 case ISD::SIGN_EXTEND_INREG: 6037 case ISD::SUB: 6038 return getUNDEF(VT); // fold op(undef, arg2) -> undef 6039 case ISD::UDIV: 6040 case ISD::SDIV: 6041 case ISD::UREM: 6042 case ISD::SREM: 6043 case ISD::SSUBSAT: 6044 case ISD::USUBSAT: 6045 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 6046 } 6047 } 6048 } 6049 6050 // Fold a bunch of operators when the RHS is undef. 6051 if (N2.isUndef()) { 6052 switch (Opcode) { 6053 case ISD::XOR: 6054 if (N1.isUndef()) 6055 // Handle undef ^ undef -> 0 special case. This is a common 6056 // idiom (misuse). 6057 return getConstant(0, DL, VT); 6058 LLVM_FALLTHROUGH; 6059 case ISD::ADD: 6060 case ISD::SUB: 6061 case ISD::UDIV: 6062 case ISD::SDIV: 6063 case ISD::UREM: 6064 case ISD::SREM: 6065 return getUNDEF(VT); // fold op(arg1, undef) -> undef 6066 case ISD::MUL: 6067 case ISD::AND: 6068 case ISD::SSUBSAT: 6069 case ISD::USUBSAT: 6070 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 6071 case ISD::OR: 6072 case ISD::SADDSAT: 6073 case ISD::UADDSAT: 6074 return getAllOnesConstant(DL, VT); 6075 } 6076 } 6077 6078 // Memoize this node if possible. 6079 SDNode *N; 6080 SDVTList VTs = getVTList(VT); 6081 SDValue Ops[] = {N1, N2}; 6082 if (VT != MVT::Glue) { 6083 FoldingSetNodeID ID; 6084 AddNodeIDNode(ID, Opcode, VTs, Ops); 6085 void *IP = nullptr; 6086 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6087 E->intersectFlagsWith(Flags); 6088 return SDValue(E, 0); 6089 } 6090 6091 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6092 N->setFlags(Flags); 6093 createOperands(N, Ops); 6094 CSEMap.InsertNode(N, IP); 6095 } else { 6096 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6097 createOperands(N, Ops); 6098 } 6099 6100 InsertNode(N); 6101 SDValue V = SDValue(N, 0); 6102 NewSDValueDbgMsg(V, "Creating new node: ", this); 6103 return V; 6104 } 6105 6106 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6107 SDValue N1, SDValue N2, SDValue N3) { 6108 SDNodeFlags Flags; 6109 if (Inserter) 6110 Flags = Inserter->getFlags(); 6111 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 6112 } 6113 6114 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6115 SDValue N1, SDValue N2, SDValue N3, 6116 const SDNodeFlags Flags) { 6117 assert(N1.getOpcode() != ISD::DELETED_NODE && 6118 N2.getOpcode() != ISD::DELETED_NODE && 6119 N3.getOpcode() != ISD::DELETED_NODE && 6120 "Operand is DELETED_NODE!"); 6121 // Perform various simplifications. 6122 switch (Opcode) { 6123 case ISD::FMA: { 6124 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 6125 assert(N1.getValueType() == VT && N2.getValueType() == VT && 6126 N3.getValueType() == VT && "FMA types must match!"); 6127 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 6128 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 6129 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 6130 if (N1CFP && N2CFP && N3CFP) { 6131 APFloat V1 = N1CFP->getValueAPF(); 6132 const APFloat &V2 = N2CFP->getValueAPF(); 6133 const APFloat &V3 = N3CFP->getValueAPF(); 6134 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 6135 return getConstantFP(V1, DL, VT); 6136 } 6137 break; 6138 } 6139 case ISD::BUILD_VECTOR: { 6140 // Attempt to simplify BUILD_VECTOR. 6141 SDValue Ops[] = {N1, N2, N3}; 6142 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 6143 return V; 6144 break; 6145 } 6146 case ISD::CONCAT_VECTORS: { 6147 SDValue Ops[] = {N1, N2, N3}; 6148 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 6149 return V; 6150 break; 6151 } 6152 case ISD::SETCC: { 6153 assert(VT.isInteger() && "SETCC result type must be an integer!"); 6154 assert(N1.getValueType() == N2.getValueType() && 6155 "SETCC operands must have the same type!"); 6156 assert(VT.isVector() == N1.getValueType().isVector() && 6157 "SETCC type should be vector iff the operand type is vector!"); 6158 assert((!VT.isVector() || VT.getVectorElementCount() == 6159 N1.getValueType().getVectorElementCount()) && 6160 "SETCC vector element counts must match!"); 6161 // Use FoldSetCC to simplify SETCC's. 6162 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 6163 return V; 6164 // Vector constant folding. 6165 SDValue Ops[] = {N1, N2, N3}; 6166 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) { 6167 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 6168 return V; 6169 } 6170 break; 6171 } 6172 case ISD::SELECT: 6173 case ISD::VSELECT: 6174 if (SDValue V = simplifySelect(N1, N2, N3)) 6175 return V; 6176 break; 6177 case ISD::VECTOR_SHUFFLE: 6178 llvm_unreachable("should use getVectorShuffle constructor!"); 6179 case ISD::VECTOR_SPLICE: { 6180 if (cast<ConstantSDNode>(N3)->isNullValue()) 6181 return N1; 6182 break; 6183 } 6184 case ISD::INSERT_VECTOR_ELT: { 6185 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 6186 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 6187 // for scalable vectors where we will generate appropriate code to 6188 // deal with out-of-bounds cases correctly. 6189 if (N3C && N1.getValueType().isFixedLengthVector() && 6190 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 6191 return getUNDEF(VT); 6192 6193 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 6194 if (N3.isUndef()) 6195 return getUNDEF(VT); 6196 6197 // If the inserted element is an UNDEF, just use the input vector. 6198 if (N2.isUndef()) 6199 return N1; 6200 6201 break; 6202 } 6203 case ISD::INSERT_SUBVECTOR: { 6204 // Inserting undef into undef is still undef. 6205 if (N1.isUndef() && N2.isUndef()) 6206 return getUNDEF(VT); 6207 6208 EVT N2VT = N2.getValueType(); 6209 assert(VT == N1.getValueType() && 6210 "Dest and insert subvector source types must match!"); 6211 assert(VT.isVector() && N2VT.isVector() && 6212 "Insert subvector VTs must be vectors!"); 6213 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 6214 "Cannot insert a scalable vector into a fixed length vector!"); 6215 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6216 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 6217 "Insert subvector must be from smaller vector to larger vector!"); 6218 assert(isa<ConstantSDNode>(N3) && 6219 "Insert subvector index must be constant"); 6220 assert((VT.isScalableVector() != N2VT.isScalableVector() || 6221 (N2VT.getVectorMinNumElements() + 6222 cast<ConstantSDNode>(N3)->getZExtValue()) <= 6223 VT.getVectorMinNumElements()) && 6224 "Insert subvector overflow!"); 6225 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 6226 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 6227 "Constant index for INSERT_SUBVECTOR has an invalid size"); 6228 6229 // Trivial insertion. 6230 if (VT == N2VT) 6231 return N2; 6232 6233 // If this is an insert of an extracted vector into an undef vector, we 6234 // can just use the input to the extract. 6235 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 6236 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 6237 return N2.getOperand(0); 6238 break; 6239 } 6240 case ISD::BITCAST: 6241 // Fold bit_convert nodes from a type to themselves. 6242 if (N1.getValueType() == VT) 6243 return N1; 6244 break; 6245 } 6246 6247 // Memoize node if it doesn't produce a flag. 6248 SDNode *N; 6249 SDVTList VTs = getVTList(VT); 6250 SDValue Ops[] = {N1, N2, N3}; 6251 if (VT != MVT::Glue) { 6252 FoldingSetNodeID ID; 6253 AddNodeIDNode(ID, Opcode, VTs, Ops); 6254 void *IP = nullptr; 6255 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 6256 E->intersectFlagsWith(Flags); 6257 return SDValue(E, 0); 6258 } 6259 6260 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6261 N->setFlags(Flags); 6262 createOperands(N, Ops); 6263 CSEMap.InsertNode(N, IP); 6264 } else { 6265 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 6266 createOperands(N, Ops); 6267 } 6268 6269 InsertNode(N); 6270 SDValue V = SDValue(N, 0); 6271 NewSDValueDbgMsg(V, "Creating new node: ", this); 6272 return V; 6273 } 6274 6275 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6276 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 6277 SDValue Ops[] = { N1, N2, N3, N4 }; 6278 return getNode(Opcode, DL, VT, Ops); 6279 } 6280 6281 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6282 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6283 SDValue N5) { 6284 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6285 return getNode(Opcode, DL, VT, Ops); 6286 } 6287 6288 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6289 /// the incoming stack arguments to be loaded from the stack. 6290 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6291 SmallVector<SDValue, 8> ArgChains; 6292 6293 // Include the original chain at the beginning of the list. When this is 6294 // used by target LowerCall hooks, this helps legalize find the 6295 // CALLSEQ_BEGIN node. 6296 ArgChains.push_back(Chain); 6297 6298 // Add a chain value for each stack argument. 6299 for (SDNode *U : getEntryNode().getNode()->uses()) 6300 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U)) 6301 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6302 if (FI->getIndex() < 0) 6303 ArgChains.push_back(SDValue(L, 1)); 6304 6305 // Build a tokenfactor for all the chains. 6306 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6307 } 6308 6309 /// getMemsetValue - Vectorized representation of the memset value 6310 /// operand. 6311 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6312 const SDLoc &dl) { 6313 assert(!Value.isUndef()); 6314 6315 unsigned NumBits = VT.getScalarSizeInBits(); 6316 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6317 assert(C->getAPIntValue().getBitWidth() == 8); 6318 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6319 if (VT.isInteger()) { 6320 bool IsOpaque = VT.getSizeInBits() > 64 || 6321 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6322 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6323 } 6324 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6325 VT); 6326 } 6327 6328 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6329 EVT IntVT = VT.getScalarType(); 6330 if (!IntVT.isInteger()) 6331 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6332 6333 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6334 if (NumBits > 8) { 6335 // Use a multiplication with 0x010101... to extend the input to the 6336 // required length. 6337 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6338 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6339 DAG.getConstant(Magic, dl, IntVT)); 6340 } 6341 6342 if (VT != Value.getValueType() && !VT.isInteger()) 6343 Value = DAG.getBitcast(VT.getScalarType(), Value); 6344 if (VT != Value.getValueType()) 6345 Value = DAG.getSplatBuildVector(VT, dl, Value); 6346 6347 return Value; 6348 } 6349 6350 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6351 /// used when a memcpy is turned into a memset when the source is a constant 6352 /// string ptr. 6353 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6354 const TargetLowering &TLI, 6355 const ConstantDataArraySlice &Slice) { 6356 // Handle vector with all elements zero. 6357 if (Slice.Array == nullptr) { 6358 if (VT.isInteger()) 6359 return DAG.getConstant(0, dl, VT); 6360 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6361 return DAG.getConstantFP(0.0, dl, VT); 6362 if (VT.isVector()) { 6363 unsigned NumElts = VT.getVectorNumElements(); 6364 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6365 return DAG.getNode(ISD::BITCAST, dl, VT, 6366 DAG.getConstant(0, dl, 6367 EVT::getVectorVT(*DAG.getContext(), 6368 EltVT, NumElts))); 6369 } 6370 llvm_unreachable("Expected type!"); 6371 } 6372 6373 assert(!VT.isVector() && "Can't handle vector type here!"); 6374 unsigned NumVTBits = VT.getSizeInBits(); 6375 unsigned NumVTBytes = NumVTBits / 8; 6376 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6377 6378 APInt Val(NumVTBits, 0); 6379 if (DAG.getDataLayout().isLittleEndian()) { 6380 for (unsigned i = 0; i != NumBytes; ++i) 6381 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6382 } else { 6383 for (unsigned i = 0; i != NumBytes; ++i) 6384 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6385 } 6386 6387 // If the "cost" of materializing the integer immediate is less than the cost 6388 // of a load, then it is cost effective to turn the load into the immediate. 6389 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6390 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6391 return DAG.getConstant(Val, dl, VT); 6392 return SDValue(); 6393 } 6394 6395 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6396 const SDLoc &DL, 6397 const SDNodeFlags Flags) { 6398 EVT VT = Base.getValueType(); 6399 SDValue Index; 6400 6401 if (Offset.isScalable()) 6402 Index = getVScale(DL, Base.getValueType(), 6403 APInt(Base.getValueSizeInBits().getFixedSize(), 6404 Offset.getKnownMinSize())); 6405 else 6406 Index = getConstant(Offset.getFixedSize(), DL, VT); 6407 6408 return getMemBasePlusOffset(Base, Index, DL, Flags); 6409 } 6410 6411 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6412 const SDLoc &DL, 6413 const SDNodeFlags Flags) { 6414 assert(Offset.getValueType().isInteger()); 6415 EVT BasePtrVT = Ptr.getValueType(); 6416 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6417 } 6418 6419 /// Returns true if memcpy source is constant data. 6420 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6421 uint64_t SrcDelta = 0; 6422 GlobalAddressSDNode *G = nullptr; 6423 if (Src.getOpcode() == ISD::GlobalAddress) 6424 G = cast<GlobalAddressSDNode>(Src); 6425 else if (Src.getOpcode() == ISD::ADD && 6426 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6427 Src.getOperand(1).getOpcode() == ISD::Constant) { 6428 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6429 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6430 } 6431 if (!G) 6432 return false; 6433 6434 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6435 SrcDelta + G->getOffset()); 6436 } 6437 6438 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6439 SelectionDAG &DAG) { 6440 // On Darwin, -Os means optimize for size without hurting performance, so 6441 // only really optimize for size when -Oz (MinSize) is used. 6442 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6443 return MF.getFunction().hasMinSize(); 6444 return DAG.shouldOptForSize(); 6445 } 6446 6447 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6448 SmallVector<SDValue, 32> &OutChains, unsigned From, 6449 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6450 SmallVector<SDValue, 16> &OutStoreChains) { 6451 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6452 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6453 SmallVector<SDValue, 16> GluedLoadChains; 6454 for (unsigned i = From; i < To; ++i) { 6455 OutChains.push_back(OutLoadChains[i]); 6456 GluedLoadChains.push_back(OutLoadChains[i]); 6457 } 6458 6459 // Chain for all loads. 6460 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6461 GluedLoadChains); 6462 6463 for (unsigned i = From; i < To; ++i) { 6464 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6465 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6466 ST->getBasePtr(), ST->getMemoryVT(), 6467 ST->getMemOperand()); 6468 OutChains.push_back(NewStore); 6469 } 6470 } 6471 6472 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6473 SDValue Chain, SDValue Dst, SDValue Src, 6474 uint64_t Size, Align Alignment, 6475 bool isVol, bool AlwaysInline, 6476 MachinePointerInfo DstPtrInfo, 6477 MachinePointerInfo SrcPtrInfo, 6478 const AAMDNodes &AAInfo) { 6479 // Turn a memcpy of undef to nop. 6480 // FIXME: We need to honor volatile even is Src is undef. 6481 if (Src.isUndef()) 6482 return Chain; 6483 6484 // Expand memcpy to a series of load and store ops if the size operand falls 6485 // below a certain threshold. 6486 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6487 // rather than maybe a humongous number of loads and stores. 6488 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6489 const DataLayout &DL = DAG.getDataLayout(); 6490 LLVMContext &C = *DAG.getContext(); 6491 std::vector<EVT> MemOps; 6492 bool DstAlignCanChange = false; 6493 MachineFunction &MF = DAG.getMachineFunction(); 6494 MachineFrameInfo &MFI = MF.getFrameInfo(); 6495 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6496 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6497 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6498 DstAlignCanChange = true; 6499 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6500 if (!SrcAlign || Alignment > *SrcAlign) 6501 SrcAlign = Alignment; 6502 assert(SrcAlign && "SrcAlign must be set"); 6503 ConstantDataArraySlice Slice; 6504 // If marked as volatile, perform a copy even when marked as constant. 6505 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6506 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6507 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6508 const MemOp Op = isZeroConstant 6509 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6510 /*IsZeroMemset*/ true, isVol) 6511 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6512 *SrcAlign, isVol, CopyFromConstant); 6513 if (!TLI.findOptimalMemOpLowering( 6514 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6515 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6516 return SDValue(); 6517 6518 if (DstAlignCanChange) { 6519 Type *Ty = MemOps[0].getTypeForEVT(C); 6520 Align NewAlign = DL.getABITypeAlign(Ty); 6521 6522 // Don't promote to an alignment that would require dynamic stack 6523 // realignment. 6524 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6525 if (!TRI->hasStackRealignment(MF)) 6526 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6527 NewAlign = NewAlign / 2; 6528 6529 if (NewAlign > Alignment) { 6530 // Give the stack frame object a larger alignment if needed. 6531 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6532 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6533 Alignment = NewAlign; 6534 } 6535 } 6536 6537 // Prepare AAInfo for loads/stores after lowering this memcpy. 6538 AAMDNodes NewAAInfo = AAInfo; 6539 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6540 6541 MachineMemOperand::Flags MMOFlags = 6542 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6543 SmallVector<SDValue, 16> OutLoadChains; 6544 SmallVector<SDValue, 16> OutStoreChains; 6545 SmallVector<SDValue, 32> OutChains; 6546 unsigned NumMemOps = MemOps.size(); 6547 uint64_t SrcOff = 0, DstOff = 0; 6548 for (unsigned i = 0; i != NumMemOps; ++i) { 6549 EVT VT = MemOps[i]; 6550 unsigned VTSize = VT.getSizeInBits() / 8; 6551 SDValue Value, Store; 6552 6553 if (VTSize > Size) { 6554 // Issuing an unaligned load / store pair that overlaps with the previous 6555 // pair. Adjust the offset accordingly. 6556 assert(i == NumMemOps-1 && i != 0); 6557 SrcOff -= VTSize - Size; 6558 DstOff -= VTSize - Size; 6559 } 6560 6561 if (CopyFromConstant && 6562 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6563 // It's unlikely a store of a vector immediate can be done in a single 6564 // instruction. It would require a load from a constantpool first. 6565 // We only handle zero vectors here. 6566 // FIXME: Handle other cases where store of vector immediate is done in 6567 // a single instruction. 6568 ConstantDataArraySlice SubSlice; 6569 if (SrcOff < Slice.Length) { 6570 SubSlice = Slice; 6571 SubSlice.move(SrcOff); 6572 } else { 6573 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6574 SubSlice.Array = nullptr; 6575 SubSlice.Offset = 0; 6576 SubSlice.Length = VTSize; 6577 } 6578 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6579 if (Value.getNode()) { 6580 Store = DAG.getStore( 6581 Chain, dl, Value, 6582 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6583 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6584 OutChains.push_back(Store); 6585 } 6586 } 6587 6588 if (!Store.getNode()) { 6589 // The type might not be legal for the target. This should only happen 6590 // if the type is smaller than a legal type, as on PPC, so the right 6591 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6592 // to Load/Store if NVT==VT. 6593 // FIXME does the case above also need this? 6594 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6595 assert(NVT.bitsGE(VT)); 6596 6597 bool isDereferenceable = 6598 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6599 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6600 if (isDereferenceable) 6601 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6602 6603 Value = DAG.getExtLoad( 6604 ISD::EXTLOAD, dl, NVT, Chain, 6605 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6606 SrcPtrInfo.getWithOffset(SrcOff), VT, 6607 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo); 6608 OutLoadChains.push_back(Value.getValue(1)); 6609 6610 Store = DAG.getTruncStore( 6611 Chain, dl, Value, 6612 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6613 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo); 6614 OutStoreChains.push_back(Store); 6615 } 6616 SrcOff += VTSize; 6617 DstOff += VTSize; 6618 Size -= VTSize; 6619 } 6620 6621 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6622 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6623 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6624 6625 if (NumLdStInMemcpy) { 6626 // It may be that memcpy might be converted to memset if it's memcpy 6627 // of constants. In such a case, we won't have loads and stores, but 6628 // just stores. In the absence of loads, there is nothing to gang up. 6629 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6630 // If target does not care, just leave as it. 6631 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6632 OutChains.push_back(OutLoadChains[i]); 6633 OutChains.push_back(OutStoreChains[i]); 6634 } 6635 } else { 6636 // Ld/St less than/equal limit set by target. 6637 if (NumLdStInMemcpy <= GluedLdStLimit) { 6638 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6639 NumLdStInMemcpy, OutLoadChains, 6640 OutStoreChains); 6641 } else { 6642 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6643 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6644 unsigned GlueIter = 0; 6645 6646 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6647 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6648 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6649 6650 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6651 OutLoadChains, OutStoreChains); 6652 GlueIter += GluedLdStLimit; 6653 } 6654 6655 // Residual ld/st. 6656 if (RemainingLdStInMemcpy) { 6657 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6658 RemainingLdStInMemcpy, OutLoadChains, 6659 OutStoreChains); 6660 } 6661 } 6662 } 6663 } 6664 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6665 } 6666 6667 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6668 SDValue Chain, SDValue Dst, SDValue Src, 6669 uint64_t Size, Align Alignment, 6670 bool isVol, bool AlwaysInline, 6671 MachinePointerInfo DstPtrInfo, 6672 MachinePointerInfo SrcPtrInfo, 6673 const AAMDNodes &AAInfo) { 6674 // Turn a memmove of undef to nop. 6675 // FIXME: We need to honor volatile even is Src is undef. 6676 if (Src.isUndef()) 6677 return Chain; 6678 6679 // Expand memmove to a series of load and store ops if the size operand falls 6680 // below a certain threshold. 6681 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6682 const DataLayout &DL = DAG.getDataLayout(); 6683 LLVMContext &C = *DAG.getContext(); 6684 std::vector<EVT> MemOps; 6685 bool DstAlignCanChange = false; 6686 MachineFunction &MF = DAG.getMachineFunction(); 6687 MachineFrameInfo &MFI = MF.getFrameInfo(); 6688 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6689 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6690 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6691 DstAlignCanChange = true; 6692 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6693 if (!SrcAlign || Alignment > *SrcAlign) 6694 SrcAlign = Alignment; 6695 assert(SrcAlign && "SrcAlign must be set"); 6696 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6697 if (!TLI.findOptimalMemOpLowering( 6698 MemOps, Limit, 6699 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6700 /*IsVolatile*/ true), 6701 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6702 MF.getFunction().getAttributes())) 6703 return SDValue(); 6704 6705 if (DstAlignCanChange) { 6706 Type *Ty = MemOps[0].getTypeForEVT(C); 6707 Align NewAlign = DL.getABITypeAlign(Ty); 6708 if (NewAlign > Alignment) { 6709 // Give the stack frame object a larger alignment if needed. 6710 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6711 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6712 Alignment = NewAlign; 6713 } 6714 } 6715 6716 // Prepare AAInfo for loads/stores after lowering this memmove. 6717 AAMDNodes NewAAInfo = AAInfo; 6718 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6719 6720 MachineMemOperand::Flags MMOFlags = 6721 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6722 uint64_t SrcOff = 0, DstOff = 0; 6723 SmallVector<SDValue, 8> LoadValues; 6724 SmallVector<SDValue, 8> LoadChains; 6725 SmallVector<SDValue, 8> OutChains; 6726 unsigned NumMemOps = MemOps.size(); 6727 for (unsigned i = 0; i < NumMemOps; i++) { 6728 EVT VT = MemOps[i]; 6729 unsigned VTSize = VT.getSizeInBits() / 8; 6730 SDValue Value; 6731 6732 bool isDereferenceable = 6733 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6734 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6735 if (isDereferenceable) 6736 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6737 6738 Value = DAG.getLoad( 6739 VT, dl, Chain, 6740 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6741 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo); 6742 LoadValues.push_back(Value); 6743 LoadChains.push_back(Value.getValue(1)); 6744 SrcOff += VTSize; 6745 } 6746 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6747 OutChains.clear(); 6748 for (unsigned i = 0; i < NumMemOps; i++) { 6749 EVT VT = MemOps[i]; 6750 unsigned VTSize = VT.getSizeInBits() / 8; 6751 SDValue Store; 6752 6753 Store = DAG.getStore( 6754 Chain, dl, LoadValues[i], 6755 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6756 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo); 6757 OutChains.push_back(Store); 6758 DstOff += VTSize; 6759 } 6760 6761 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6762 } 6763 6764 /// Lower the call to 'memset' intrinsic function into a series of store 6765 /// operations. 6766 /// 6767 /// \param DAG Selection DAG where lowered code is placed. 6768 /// \param dl Link to corresponding IR location. 6769 /// \param Chain Control flow dependency. 6770 /// \param Dst Pointer to destination memory location. 6771 /// \param Src Value of byte to write into the memory. 6772 /// \param Size Number of bytes to write. 6773 /// \param Alignment Alignment of the destination in bytes. 6774 /// \param isVol True if destination is volatile. 6775 /// \param DstPtrInfo IR information on the memory pointer. 6776 /// \returns New head in the control flow, if lowering was successful, empty 6777 /// SDValue otherwise. 6778 /// 6779 /// The function tries to replace 'llvm.memset' intrinsic with several store 6780 /// operations and value calculation code. This is usually profitable for small 6781 /// memory size. 6782 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6783 SDValue Chain, SDValue Dst, SDValue Src, 6784 uint64_t Size, Align Alignment, bool isVol, 6785 MachinePointerInfo DstPtrInfo, 6786 const AAMDNodes &AAInfo) { 6787 // Turn a memset of undef to nop. 6788 // FIXME: We need to honor volatile even is Src is undef. 6789 if (Src.isUndef()) 6790 return Chain; 6791 6792 // Expand memset to a series of load/store ops if the size operand 6793 // falls below a certain threshold. 6794 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6795 std::vector<EVT> MemOps; 6796 bool DstAlignCanChange = false; 6797 MachineFunction &MF = DAG.getMachineFunction(); 6798 MachineFrameInfo &MFI = MF.getFrameInfo(); 6799 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6800 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6801 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6802 DstAlignCanChange = true; 6803 bool IsZeroVal = 6804 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero(); 6805 if (!TLI.findOptimalMemOpLowering( 6806 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6807 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6808 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6809 return SDValue(); 6810 6811 if (DstAlignCanChange) { 6812 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6813 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6814 if (NewAlign > Alignment) { 6815 // Give the stack frame object a larger alignment if needed. 6816 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6817 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6818 Alignment = NewAlign; 6819 } 6820 } 6821 6822 SmallVector<SDValue, 8> OutChains; 6823 uint64_t DstOff = 0; 6824 unsigned NumMemOps = MemOps.size(); 6825 6826 // Find the largest store and generate the bit pattern for it. 6827 EVT LargestVT = MemOps[0]; 6828 for (unsigned i = 1; i < NumMemOps; i++) 6829 if (MemOps[i].bitsGT(LargestVT)) 6830 LargestVT = MemOps[i]; 6831 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6832 6833 // Prepare AAInfo for loads/stores after lowering this memset. 6834 AAMDNodes NewAAInfo = AAInfo; 6835 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr; 6836 6837 for (unsigned i = 0; i < NumMemOps; i++) { 6838 EVT VT = MemOps[i]; 6839 unsigned VTSize = VT.getSizeInBits() / 8; 6840 if (VTSize > Size) { 6841 // Issuing an unaligned load / store pair that overlaps with the previous 6842 // pair. Adjust the offset accordingly. 6843 assert(i == NumMemOps-1 && i != 0); 6844 DstOff -= VTSize - Size; 6845 } 6846 6847 // If this store is smaller than the largest store see whether we can get 6848 // the smaller value for free with a truncate. 6849 SDValue Value = MemSetValue; 6850 if (VT.bitsLT(LargestVT)) { 6851 if (!LargestVT.isVector() && !VT.isVector() && 6852 TLI.isTruncateFree(LargestVT, VT)) 6853 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6854 else 6855 Value = getMemsetValue(Src, VT, DAG, dl); 6856 } 6857 assert(Value.getValueType() == VT && "Value with wrong type."); 6858 SDValue Store = DAG.getStore( 6859 Chain, dl, Value, 6860 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6861 DstPtrInfo.getWithOffset(DstOff), Alignment, 6862 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone, 6863 NewAAInfo); 6864 OutChains.push_back(Store); 6865 DstOff += VT.getSizeInBits() / 8; 6866 Size -= VTSize; 6867 } 6868 6869 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6870 } 6871 6872 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6873 unsigned AS) { 6874 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6875 // pointer operands can be losslessly bitcasted to pointers of address space 0 6876 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6877 report_fatal_error("cannot lower memory intrinsic in address space " + 6878 Twine(AS)); 6879 } 6880 } 6881 6882 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6883 SDValue Src, SDValue Size, Align Alignment, 6884 bool isVol, bool AlwaysInline, bool isTailCall, 6885 MachinePointerInfo DstPtrInfo, 6886 MachinePointerInfo SrcPtrInfo, 6887 const AAMDNodes &AAInfo) { 6888 // Check to see if we should lower the memcpy to loads and stores first. 6889 // For cases within the target-specified limits, this is the best choice. 6890 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6891 if (ConstantSize) { 6892 // Memcpy with size zero? Just return the original chain. 6893 if (ConstantSize->isZero()) 6894 return Chain; 6895 6896 SDValue Result = getMemcpyLoadsAndStores( 6897 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6898 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 6899 if (Result.getNode()) 6900 return Result; 6901 } 6902 6903 // Then check to see if we should lower the memcpy with target-specific 6904 // code. If the target chooses to do this, this is the next best. 6905 if (TSI) { 6906 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6907 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6908 DstPtrInfo, SrcPtrInfo); 6909 if (Result.getNode()) 6910 return Result; 6911 } 6912 6913 // If we really need inline code and the target declined to provide it, 6914 // use a (potentially long) sequence of loads and stores. 6915 if (AlwaysInline) { 6916 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6917 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6918 ConstantSize->getZExtValue(), Alignment, 6919 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo); 6920 } 6921 6922 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6923 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6924 6925 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6926 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6927 // respect volatile, so they may do things like read or write memory 6928 // beyond the given memory regions. But fixing this isn't easy, and most 6929 // people don't care. 6930 6931 // Emit a library call. 6932 TargetLowering::ArgListTy Args; 6933 TargetLowering::ArgListEntry Entry; 6934 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6935 Entry.Node = Dst; Args.push_back(Entry); 6936 Entry.Node = Src; Args.push_back(Entry); 6937 6938 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6939 Entry.Node = Size; Args.push_back(Entry); 6940 // FIXME: pass in SDLoc 6941 TargetLowering::CallLoweringInfo CLI(*this); 6942 CLI.setDebugLoc(dl) 6943 .setChain(Chain) 6944 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6945 Dst.getValueType().getTypeForEVT(*getContext()), 6946 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6947 TLI->getPointerTy(getDataLayout())), 6948 std::move(Args)) 6949 .setDiscardResult() 6950 .setTailCall(isTailCall); 6951 6952 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6953 return CallResult.second; 6954 } 6955 6956 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6957 SDValue Dst, unsigned DstAlign, 6958 SDValue Src, unsigned SrcAlign, 6959 SDValue Size, Type *SizeTy, 6960 unsigned ElemSz, bool isTailCall, 6961 MachinePointerInfo DstPtrInfo, 6962 MachinePointerInfo SrcPtrInfo) { 6963 // Emit a library call. 6964 TargetLowering::ArgListTy Args; 6965 TargetLowering::ArgListEntry Entry; 6966 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6967 Entry.Node = Dst; 6968 Args.push_back(Entry); 6969 6970 Entry.Node = Src; 6971 Args.push_back(Entry); 6972 6973 Entry.Ty = SizeTy; 6974 Entry.Node = Size; 6975 Args.push_back(Entry); 6976 6977 RTLIB::Libcall LibraryCall = 6978 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6979 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6980 report_fatal_error("Unsupported element size"); 6981 6982 TargetLowering::CallLoweringInfo CLI(*this); 6983 CLI.setDebugLoc(dl) 6984 .setChain(Chain) 6985 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6986 Type::getVoidTy(*getContext()), 6987 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6988 TLI->getPointerTy(getDataLayout())), 6989 std::move(Args)) 6990 .setDiscardResult() 6991 .setTailCall(isTailCall); 6992 6993 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6994 return CallResult.second; 6995 } 6996 6997 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6998 SDValue Src, SDValue Size, Align Alignment, 6999 bool isVol, bool isTailCall, 7000 MachinePointerInfo DstPtrInfo, 7001 MachinePointerInfo SrcPtrInfo, 7002 const AAMDNodes &AAInfo) { 7003 // Check to see if we should lower the memmove to loads and stores first. 7004 // For cases within the target-specified limits, this is the best choice. 7005 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7006 if (ConstantSize) { 7007 // Memmove with size zero? Just return the original chain. 7008 if (ConstantSize->isZero()) 7009 return Chain; 7010 7011 SDValue Result = getMemmoveLoadsAndStores( 7012 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 7013 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo); 7014 if (Result.getNode()) 7015 return Result; 7016 } 7017 7018 // Then check to see if we should lower the memmove with target-specific 7019 // code. If the target chooses to do this, this is the next best. 7020 if (TSI) { 7021 SDValue Result = 7022 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 7023 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 7024 if (Result.getNode()) 7025 return Result; 7026 } 7027 7028 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7029 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 7030 7031 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 7032 // not be safe. See memcpy above for more details. 7033 7034 // Emit a library call. 7035 TargetLowering::ArgListTy Args; 7036 TargetLowering::ArgListEntry Entry; 7037 Entry.Ty = Type::getInt8PtrTy(*getContext()); 7038 Entry.Node = Dst; Args.push_back(Entry); 7039 Entry.Node = Src; Args.push_back(Entry); 7040 7041 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7042 Entry.Node = Size; Args.push_back(Entry); 7043 // FIXME: pass in SDLoc 7044 TargetLowering::CallLoweringInfo CLI(*this); 7045 CLI.setDebugLoc(dl) 7046 .setChain(Chain) 7047 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 7048 Dst.getValueType().getTypeForEVT(*getContext()), 7049 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 7050 TLI->getPointerTy(getDataLayout())), 7051 std::move(Args)) 7052 .setDiscardResult() 7053 .setTailCall(isTailCall); 7054 7055 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7056 return CallResult.second; 7057 } 7058 7059 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 7060 SDValue Dst, unsigned DstAlign, 7061 SDValue Src, unsigned SrcAlign, 7062 SDValue Size, Type *SizeTy, 7063 unsigned ElemSz, bool isTailCall, 7064 MachinePointerInfo DstPtrInfo, 7065 MachinePointerInfo SrcPtrInfo) { 7066 // Emit a library call. 7067 TargetLowering::ArgListTy Args; 7068 TargetLowering::ArgListEntry Entry; 7069 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7070 Entry.Node = Dst; 7071 Args.push_back(Entry); 7072 7073 Entry.Node = Src; 7074 Args.push_back(Entry); 7075 7076 Entry.Ty = SizeTy; 7077 Entry.Node = Size; 7078 Args.push_back(Entry); 7079 7080 RTLIB::Libcall LibraryCall = 7081 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7082 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7083 report_fatal_error("Unsupported element size"); 7084 7085 TargetLowering::CallLoweringInfo CLI(*this); 7086 CLI.setDebugLoc(dl) 7087 .setChain(Chain) 7088 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7089 Type::getVoidTy(*getContext()), 7090 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7091 TLI->getPointerTy(getDataLayout())), 7092 std::move(Args)) 7093 .setDiscardResult() 7094 .setTailCall(isTailCall); 7095 7096 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7097 return CallResult.second; 7098 } 7099 7100 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 7101 SDValue Src, SDValue Size, Align Alignment, 7102 bool isVol, bool isTailCall, 7103 MachinePointerInfo DstPtrInfo, 7104 const AAMDNodes &AAInfo) { 7105 // Check to see if we should lower the memset to stores first. 7106 // For cases within the target-specified limits, this is the best choice. 7107 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 7108 if (ConstantSize) { 7109 // Memset with size zero? Just return the original chain. 7110 if (ConstantSize->isZero()) 7111 return Chain; 7112 7113 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 7114 ConstantSize->getZExtValue(), Alignment, 7115 isVol, DstPtrInfo, AAInfo); 7116 7117 if (Result.getNode()) 7118 return Result; 7119 } 7120 7121 // Then check to see if we should lower the memset with target-specific 7122 // code. If the target chooses to do this, this is the next best. 7123 if (TSI) { 7124 SDValue Result = TSI->EmitTargetCodeForMemset( 7125 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 7126 if (Result.getNode()) 7127 return Result; 7128 } 7129 7130 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 7131 7132 // Emit a library call. 7133 TargetLowering::ArgListTy Args; 7134 TargetLowering::ArgListEntry Entry; 7135 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 7136 Args.push_back(Entry); 7137 Entry.Node = Src; 7138 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 7139 Args.push_back(Entry); 7140 Entry.Node = Size; 7141 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7142 Args.push_back(Entry); 7143 7144 // FIXME: pass in SDLoc 7145 TargetLowering::CallLoweringInfo CLI(*this); 7146 CLI.setDebugLoc(dl) 7147 .setChain(Chain) 7148 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 7149 Dst.getValueType().getTypeForEVT(*getContext()), 7150 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 7151 TLI->getPointerTy(getDataLayout())), 7152 std::move(Args)) 7153 .setDiscardResult() 7154 .setTailCall(isTailCall); 7155 7156 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 7157 return CallResult.second; 7158 } 7159 7160 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 7161 SDValue Dst, unsigned DstAlign, 7162 SDValue Value, SDValue Size, Type *SizeTy, 7163 unsigned ElemSz, bool isTailCall, 7164 MachinePointerInfo DstPtrInfo) { 7165 // Emit a library call. 7166 TargetLowering::ArgListTy Args; 7167 TargetLowering::ArgListEntry Entry; 7168 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 7169 Entry.Node = Dst; 7170 Args.push_back(Entry); 7171 7172 Entry.Ty = Type::getInt8Ty(*getContext()); 7173 Entry.Node = Value; 7174 Args.push_back(Entry); 7175 7176 Entry.Ty = SizeTy; 7177 Entry.Node = Size; 7178 Args.push_back(Entry); 7179 7180 RTLIB::Libcall LibraryCall = 7181 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 7182 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 7183 report_fatal_error("Unsupported element size"); 7184 7185 TargetLowering::CallLoweringInfo CLI(*this); 7186 CLI.setDebugLoc(dl) 7187 .setChain(Chain) 7188 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 7189 Type::getVoidTy(*getContext()), 7190 getExternalSymbol(TLI->getLibcallName(LibraryCall), 7191 TLI->getPointerTy(getDataLayout())), 7192 std::move(Args)) 7193 .setDiscardResult() 7194 .setTailCall(isTailCall); 7195 7196 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 7197 return CallResult.second; 7198 } 7199 7200 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7201 SDVTList VTList, ArrayRef<SDValue> Ops, 7202 MachineMemOperand *MMO) { 7203 FoldingSetNodeID ID; 7204 ID.AddInteger(MemVT.getRawBits()); 7205 AddNodeIDNode(ID, Opcode, VTList, Ops); 7206 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7207 void* IP = nullptr; 7208 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7209 cast<AtomicSDNode>(E)->refineAlignment(MMO); 7210 return SDValue(E, 0); 7211 } 7212 7213 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7214 VTList, MemVT, MMO); 7215 createOperands(N, Ops); 7216 7217 CSEMap.InsertNode(N, IP); 7218 InsertNode(N); 7219 return SDValue(N, 0); 7220 } 7221 7222 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 7223 EVT MemVT, SDVTList VTs, SDValue Chain, 7224 SDValue Ptr, SDValue Cmp, SDValue Swp, 7225 MachineMemOperand *MMO) { 7226 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 7227 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 7228 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 7229 7230 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 7231 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7232 } 7233 7234 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7235 SDValue Chain, SDValue Ptr, SDValue Val, 7236 MachineMemOperand *MMO) { 7237 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 7238 Opcode == ISD::ATOMIC_LOAD_SUB || 7239 Opcode == ISD::ATOMIC_LOAD_AND || 7240 Opcode == ISD::ATOMIC_LOAD_CLR || 7241 Opcode == ISD::ATOMIC_LOAD_OR || 7242 Opcode == ISD::ATOMIC_LOAD_XOR || 7243 Opcode == ISD::ATOMIC_LOAD_NAND || 7244 Opcode == ISD::ATOMIC_LOAD_MIN || 7245 Opcode == ISD::ATOMIC_LOAD_MAX || 7246 Opcode == ISD::ATOMIC_LOAD_UMIN || 7247 Opcode == ISD::ATOMIC_LOAD_UMAX || 7248 Opcode == ISD::ATOMIC_LOAD_FADD || 7249 Opcode == ISD::ATOMIC_LOAD_FSUB || 7250 Opcode == ISD::ATOMIC_SWAP || 7251 Opcode == ISD::ATOMIC_STORE) && 7252 "Invalid Atomic Op"); 7253 7254 EVT VT = Val.getValueType(); 7255 7256 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 7257 getVTList(VT, MVT::Other); 7258 SDValue Ops[] = {Chain, Ptr, Val}; 7259 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7260 } 7261 7262 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 7263 EVT VT, SDValue Chain, SDValue Ptr, 7264 MachineMemOperand *MMO) { 7265 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 7266 7267 SDVTList VTs = getVTList(VT, MVT::Other); 7268 SDValue Ops[] = {Chain, Ptr}; 7269 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 7270 } 7271 7272 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 7273 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 7274 if (Ops.size() == 1) 7275 return Ops[0]; 7276 7277 SmallVector<EVT, 4> VTs; 7278 VTs.reserve(Ops.size()); 7279 for (const SDValue &Op : Ops) 7280 VTs.push_back(Op.getValueType()); 7281 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 7282 } 7283 7284 SDValue SelectionDAG::getMemIntrinsicNode( 7285 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 7286 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 7287 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 7288 if (!Size && MemVT.isScalableVector()) 7289 Size = MemoryLocation::UnknownSize; 7290 else if (!Size) 7291 Size = MemVT.getStoreSize(); 7292 7293 MachineFunction &MF = getMachineFunction(); 7294 MachineMemOperand *MMO = 7295 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 7296 7297 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7298 } 7299 7300 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7301 SDVTList VTList, 7302 ArrayRef<SDValue> Ops, EVT MemVT, 7303 MachineMemOperand *MMO) { 7304 assert((Opcode == ISD::INTRINSIC_VOID || 7305 Opcode == ISD::INTRINSIC_W_CHAIN || 7306 Opcode == ISD::PREFETCH || 7307 ((int)Opcode <= std::numeric_limits<int>::max() && 7308 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7309 "Opcode is not a memory-accessing opcode!"); 7310 7311 // Memoize the node unless it returns a flag. 7312 MemIntrinsicSDNode *N; 7313 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7314 FoldingSetNodeID ID; 7315 AddNodeIDNode(ID, Opcode, VTList, Ops); 7316 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7317 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7318 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7319 void *IP = nullptr; 7320 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7321 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7322 return SDValue(E, 0); 7323 } 7324 7325 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7326 VTList, MemVT, MMO); 7327 createOperands(N, Ops); 7328 7329 CSEMap.InsertNode(N, IP); 7330 } else { 7331 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7332 VTList, MemVT, MMO); 7333 createOperands(N, Ops); 7334 } 7335 InsertNode(N); 7336 SDValue V(N, 0); 7337 NewSDValueDbgMsg(V, "Creating new node: ", this); 7338 return V; 7339 } 7340 7341 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7342 SDValue Chain, int FrameIndex, 7343 int64_t Size, int64_t Offset) { 7344 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7345 const auto VTs = getVTList(MVT::Other); 7346 SDValue Ops[2] = { 7347 Chain, 7348 getFrameIndex(FrameIndex, 7349 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7350 true)}; 7351 7352 FoldingSetNodeID ID; 7353 AddNodeIDNode(ID, Opcode, VTs, Ops); 7354 ID.AddInteger(FrameIndex); 7355 ID.AddInteger(Size); 7356 ID.AddInteger(Offset); 7357 void *IP = nullptr; 7358 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7359 return SDValue(E, 0); 7360 7361 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7362 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7363 createOperands(N, Ops); 7364 CSEMap.InsertNode(N, IP); 7365 InsertNode(N); 7366 SDValue V(N, 0); 7367 NewSDValueDbgMsg(V, "Creating new node: ", this); 7368 return V; 7369 } 7370 7371 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7372 uint64_t Guid, uint64_t Index, 7373 uint32_t Attr) { 7374 const unsigned Opcode = ISD::PSEUDO_PROBE; 7375 const auto VTs = getVTList(MVT::Other); 7376 SDValue Ops[] = {Chain}; 7377 FoldingSetNodeID ID; 7378 AddNodeIDNode(ID, Opcode, VTs, Ops); 7379 ID.AddInteger(Guid); 7380 ID.AddInteger(Index); 7381 void *IP = nullptr; 7382 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7383 return SDValue(E, 0); 7384 7385 auto *N = newSDNode<PseudoProbeSDNode>( 7386 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7387 createOperands(N, Ops); 7388 CSEMap.InsertNode(N, IP); 7389 InsertNode(N); 7390 SDValue V(N, 0); 7391 NewSDValueDbgMsg(V, "Creating new node: ", this); 7392 return V; 7393 } 7394 7395 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7396 /// MachinePointerInfo record from it. This is particularly useful because the 7397 /// code generator has many cases where it doesn't bother passing in a 7398 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7399 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7400 SelectionDAG &DAG, SDValue Ptr, 7401 int64_t Offset = 0) { 7402 // If this is FI+Offset, we can model it. 7403 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7404 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7405 FI->getIndex(), Offset); 7406 7407 // If this is (FI+Offset1)+Offset2, we can model it. 7408 if (Ptr.getOpcode() != ISD::ADD || 7409 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7410 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7411 return Info; 7412 7413 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7414 return MachinePointerInfo::getFixedStack( 7415 DAG.getMachineFunction(), FI, 7416 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7417 } 7418 7419 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7420 /// MachinePointerInfo record from it. This is particularly useful because the 7421 /// code generator has many cases where it doesn't bother passing in a 7422 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7423 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7424 SelectionDAG &DAG, SDValue Ptr, 7425 SDValue OffsetOp) { 7426 // If the 'Offset' value isn't a constant, we can't handle this. 7427 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7428 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7429 if (OffsetOp.isUndef()) 7430 return InferPointerInfo(Info, DAG, Ptr); 7431 return Info; 7432 } 7433 7434 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7435 EVT VT, const SDLoc &dl, SDValue Chain, 7436 SDValue Ptr, SDValue Offset, 7437 MachinePointerInfo PtrInfo, EVT MemVT, 7438 Align Alignment, 7439 MachineMemOperand::Flags MMOFlags, 7440 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7441 assert(Chain.getValueType() == MVT::Other && 7442 "Invalid chain type"); 7443 7444 MMOFlags |= MachineMemOperand::MOLoad; 7445 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7446 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7447 // clients. 7448 if (PtrInfo.V.isNull()) 7449 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7450 7451 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7452 MachineFunction &MF = getMachineFunction(); 7453 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7454 Alignment, AAInfo, Ranges); 7455 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7456 } 7457 7458 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7459 EVT VT, const SDLoc &dl, SDValue Chain, 7460 SDValue Ptr, SDValue Offset, EVT MemVT, 7461 MachineMemOperand *MMO) { 7462 if (VT == MemVT) { 7463 ExtType = ISD::NON_EXTLOAD; 7464 } else if (ExtType == ISD::NON_EXTLOAD) { 7465 assert(VT == MemVT && "Non-extending load from different memory type!"); 7466 } else { 7467 // Extending load. 7468 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7469 "Should only be an extending load, not truncating!"); 7470 assert(VT.isInteger() == MemVT.isInteger() && 7471 "Cannot convert from FP to Int or Int -> FP!"); 7472 assert(VT.isVector() == MemVT.isVector() && 7473 "Cannot use an ext load to convert to or from a vector!"); 7474 assert((!VT.isVector() || 7475 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7476 "Cannot use an ext load to change the number of vector elements!"); 7477 } 7478 7479 bool Indexed = AM != ISD::UNINDEXED; 7480 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7481 7482 SDVTList VTs = Indexed ? 7483 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7484 SDValue Ops[] = { Chain, Ptr, Offset }; 7485 FoldingSetNodeID ID; 7486 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7487 ID.AddInteger(MemVT.getRawBits()); 7488 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7489 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7490 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7491 void *IP = nullptr; 7492 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7493 cast<LoadSDNode>(E)->refineAlignment(MMO); 7494 return SDValue(E, 0); 7495 } 7496 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7497 ExtType, MemVT, MMO); 7498 createOperands(N, Ops); 7499 7500 CSEMap.InsertNode(N, IP); 7501 InsertNode(N); 7502 SDValue V(N, 0); 7503 NewSDValueDbgMsg(V, "Creating new node: ", this); 7504 return V; 7505 } 7506 7507 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7508 SDValue Ptr, MachinePointerInfo PtrInfo, 7509 MaybeAlign Alignment, 7510 MachineMemOperand::Flags MMOFlags, 7511 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7512 SDValue Undef = getUNDEF(Ptr.getValueType()); 7513 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7514 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7515 } 7516 7517 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7518 SDValue Ptr, MachineMemOperand *MMO) { 7519 SDValue Undef = getUNDEF(Ptr.getValueType()); 7520 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7521 VT, MMO); 7522 } 7523 7524 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7525 EVT VT, SDValue Chain, SDValue Ptr, 7526 MachinePointerInfo PtrInfo, EVT MemVT, 7527 MaybeAlign Alignment, 7528 MachineMemOperand::Flags MMOFlags, 7529 const AAMDNodes &AAInfo) { 7530 SDValue Undef = getUNDEF(Ptr.getValueType()); 7531 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7532 MemVT, Alignment, MMOFlags, AAInfo); 7533 } 7534 7535 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7536 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7537 MachineMemOperand *MMO) { 7538 SDValue Undef = getUNDEF(Ptr.getValueType()); 7539 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7540 MemVT, MMO); 7541 } 7542 7543 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7544 SDValue Base, SDValue Offset, 7545 ISD::MemIndexedMode AM) { 7546 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7547 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7548 // Don't propagate the invariant or dereferenceable flags. 7549 auto MMOFlags = 7550 LD->getMemOperand()->getFlags() & 7551 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7552 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7553 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7554 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7555 } 7556 7557 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7558 SDValue Ptr, MachinePointerInfo PtrInfo, 7559 Align Alignment, 7560 MachineMemOperand::Flags MMOFlags, 7561 const AAMDNodes &AAInfo) { 7562 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7563 7564 MMOFlags |= MachineMemOperand::MOStore; 7565 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7566 7567 if (PtrInfo.V.isNull()) 7568 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7569 7570 MachineFunction &MF = getMachineFunction(); 7571 uint64_t Size = 7572 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7573 MachineMemOperand *MMO = 7574 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7575 return getStore(Chain, dl, Val, Ptr, MMO); 7576 } 7577 7578 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7579 SDValue Ptr, MachineMemOperand *MMO) { 7580 assert(Chain.getValueType() == MVT::Other && 7581 "Invalid chain type"); 7582 EVT VT = Val.getValueType(); 7583 SDVTList VTs = getVTList(MVT::Other); 7584 SDValue Undef = getUNDEF(Ptr.getValueType()); 7585 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7586 FoldingSetNodeID ID; 7587 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7588 ID.AddInteger(VT.getRawBits()); 7589 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7590 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7591 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7592 void *IP = nullptr; 7593 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7594 cast<StoreSDNode>(E)->refineAlignment(MMO); 7595 return SDValue(E, 0); 7596 } 7597 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7598 ISD::UNINDEXED, false, VT, MMO); 7599 createOperands(N, Ops); 7600 7601 CSEMap.InsertNode(N, IP); 7602 InsertNode(N); 7603 SDValue V(N, 0); 7604 NewSDValueDbgMsg(V, "Creating new node: ", this); 7605 return V; 7606 } 7607 7608 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7609 SDValue Ptr, MachinePointerInfo PtrInfo, 7610 EVT SVT, Align Alignment, 7611 MachineMemOperand::Flags MMOFlags, 7612 const AAMDNodes &AAInfo) { 7613 assert(Chain.getValueType() == MVT::Other && 7614 "Invalid chain type"); 7615 7616 MMOFlags |= MachineMemOperand::MOStore; 7617 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7618 7619 if (PtrInfo.V.isNull()) 7620 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7621 7622 MachineFunction &MF = getMachineFunction(); 7623 MachineMemOperand *MMO = MF.getMachineMemOperand( 7624 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7625 Alignment, AAInfo); 7626 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7627 } 7628 7629 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7630 SDValue Ptr, EVT SVT, 7631 MachineMemOperand *MMO) { 7632 EVT VT = Val.getValueType(); 7633 7634 assert(Chain.getValueType() == MVT::Other && 7635 "Invalid chain type"); 7636 if (VT == SVT) 7637 return getStore(Chain, dl, Val, Ptr, MMO); 7638 7639 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7640 "Should only be a truncating store, not extending!"); 7641 assert(VT.isInteger() == SVT.isInteger() && 7642 "Can't do FP-INT conversion!"); 7643 assert(VT.isVector() == SVT.isVector() && 7644 "Cannot use trunc store to convert to or from a vector!"); 7645 assert((!VT.isVector() || 7646 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7647 "Cannot use trunc store to change the number of vector elements!"); 7648 7649 SDVTList VTs = getVTList(MVT::Other); 7650 SDValue Undef = getUNDEF(Ptr.getValueType()); 7651 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7652 FoldingSetNodeID ID; 7653 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7654 ID.AddInteger(SVT.getRawBits()); 7655 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7656 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7657 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7658 void *IP = nullptr; 7659 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7660 cast<StoreSDNode>(E)->refineAlignment(MMO); 7661 return SDValue(E, 0); 7662 } 7663 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7664 ISD::UNINDEXED, true, SVT, MMO); 7665 createOperands(N, Ops); 7666 7667 CSEMap.InsertNode(N, IP); 7668 InsertNode(N); 7669 SDValue V(N, 0); 7670 NewSDValueDbgMsg(V, "Creating new node: ", this); 7671 return V; 7672 } 7673 7674 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7675 SDValue Base, SDValue Offset, 7676 ISD::MemIndexedMode AM) { 7677 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7678 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7679 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7680 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7681 FoldingSetNodeID ID; 7682 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7683 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7684 ID.AddInteger(ST->getRawSubclassData()); 7685 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7686 void *IP = nullptr; 7687 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7688 return SDValue(E, 0); 7689 7690 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7691 ST->isTruncatingStore(), ST->getMemoryVT(), 7692 ST->getMemOperand()); 7693 createOperands(N, Ops); 7694 7695 CSEMap.InsertNode(N, IP); 7696 InsertNode(N); 7697 SDValue V(N, 0); 7698 NewSDValueDbgMsg(V, "Creating new node: ", this); 7699 return V; 7700 } 7701 7702 SDValue SelectionDAG::getLoadVP( 7703 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, 7704 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, 7705 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, 7706 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, 7707 const MDNode *Ranges, bool IsExpanding) { 7708 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7709 7710 MMOFlags |= MachineMemOperand::MOLoad; 7711 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7712 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7713 // clients. 7714 if (PtrInfo.V.isNull()) 7715 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7716 7717 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7718 MachineFunction &MF = getMachineFunction(); 7719 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7720 Alignment, AAInfo, Ranges); 7721 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT, 7722 MMO, IsExpanding); 7723 } 7724 7725 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM, 7726 ISD::LoadExtType ExtType, EVT VT, 7727 const SDLoc &dl, SDValue Chain, SDValue Ptr, 7728 SDValue Offset, SDValue Mask, SDValue EVL, 7729 EVT MemVT, MachineMemOperand *MMO, 7730 bool IsExpanding) { 7731 bool Indexed = AM != ISD::UNINDEXED; 7732 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7733 7734 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other) 7735 : getVTList(VT, MVT::Other); 7736 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL}; 7737 FoldingSetNodeID ID; 7738 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops); 7739 ID.AddInteger(VT.getRawBits()); 7740 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>( 7741 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO)); 7742 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7743 void *IP = nullptr; 7744 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7745 cast<VPLoadSDNode>(E)->refineAlignment(MMO); 7746 return SDValue(E, 0); 7747 } 7748 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7749 ExtType, IsExpanding, MemVT, MMO); 7750 createOperands(N, Ops); 7751 7752 CSEMap.InsertNode(N, IP); 7753 InsertNode(N); 7754 SDValue V(N, 0); 7755 NewSDValueDbgMsg(V, "Creating new node: ", this); 7756 return V; 7757 } 7758 7759 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7760 SDValue Ptr, SDValue Mask, SDValue EVL, 7761 MachinePointerInfo PtrInfo, 7762 MaybeAlign Alignment, 7763 MachineMemOperand::Flags MMOFlags, 7764 const AAMDNodes &AAInfo, const MDNode *Ranges, 7765 bool IsExpanding) { 7766 SDValue Undef = getUNDEF(Ptr.getValueType()); 7767 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7768 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges, 7769 IsExpanding); 7770 } 7771 7772 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain, 7773 SDValue Ptr, SDValue Mask, SDValue EVL, 7774 MachineMemOperand *MMO, bool IsExpanding) { 7775 SDValue Undef = getUNDEF(Ptr.getValueType()); 7776 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7777 Mask, EVL, VT, MMO, IsExpanding); 7778 } 7779 7780 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7781 EVT VT, SDValue Chain, SDValue Ptr, 7782 SDValue Mask, SDValue EVL, 7783 MachinePointerInfo PtrInfo, EVT MemVT, 7784 MaybeAlign Alignment, 7785 MachineMemOperand::Flags MMOFlags, 7786 const AAMDNodes &AAInfo, bool IsExpanding) { 7787 SDValue Undef = getUNDEF(Ptr.getValueType()); 7788 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7789 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr, 7790 IsExpanding); 7791 } 7792 7793 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, 7794 EVT VT, SDValue Chain, SDValue Ptr, 7795 SDValue Mask, SDValue EVL, EVT MemVT, 7796 MachineMemOperand *MMO, bool IsExpanding) { 7797 SDValue Undef = getUNDEF(Ptr.getValueType()); 7798 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask, 7799 EVL, MemVT, MMO, IsExpanding); 7800 } 7801 7802 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, 7803 SDValue Base, SDValue Offset, 7804 ISD::MemIndexedMode AM) { 7805 auto *LD = cast<VPLoadSDNode>(OrigLoad); 7806 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7807 // Don't propagate the invariant or dereferenceable flags. 7808 auto MMOFlags = 7809 LD->getMemOperand()->getFlags() & 7810 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7811 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7812 LD->getChain(), Base, Offset, LD->getMask(), 7813 LD->getVectorLength(), LD->getPointerInfo(), 7814 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(), 7815 nullptr, LD->isExpandingLoad()); 7816 } 7817 7818 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, 7819 SDValue Ptr, SDValue Offset, SDValue Mask, 7820 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, 7821 ISD::MemIndexedMode AM, bool IsTruncating, 7822 bool IsCompressing) { 7823 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7824 bool Indexed = AM != ISD::UNINDEXED; 7825 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!"); 7826 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other) 7827 : getVTList(MVT::Other); 7828 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL}; 7829 FoldingSetNodeID ID; 7830 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7831 ID.AddInteger(MemVT.getRawBits()); 7832 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7833 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7834 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7835 void *IP = nullptr; 7836 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7837 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7838 return SDValue(E, 0); 7839 } 7840 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7841 IsTruncating, IsCompressing, MemVT, MMO); 7842 createOperands(N, Ops); 7843 7844 CSEMap.InsertNode(N, IP); 7845 InsertNode(N); 7846 SDValue V(N, 0); 7847 NewSDValueDbgMsg(V, "Creating new node: ", this); 7848 return V; 7849 } 7850 7851 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7852 SDValue Val, SDValue Ptr, SDValue Mask, 7853 SDValue EVL, MachinePointerInfo PtrInfo, 7854 EVT SVT, Align Alignment, 7855 MachineMemOperand::Flags MMOFlags, 7856 const AAMDNodes &AAInfo, 7857 bool IsCompressing) { 7858 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7859 7860 MMOFlags |= MachineMemOperand::MOStore; 7861 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7862 7863 if (PtrInfo.V.isNull()) 7864 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7865 7866 MachineFunction &MF = getMachineFunction(); 7867 MachineMemOperand *MMO = MF.getMachineMemOperand( 7868 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7869 Alignment, AAInfo); 7870 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO, 7871 IsCompressing); 7872 } 7873 7874 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl, 7875 SDValue Val, SDValue Ptr, SDValue Mask, 7876 SDValue EVL, EVT SVT, 7877 MachineMemOperand *MMO, 7878 bool IsCompressing) { 7879 EVT VT = Val.getValueType(); 7880 7881 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7882 if (VT == SVT) 7883 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask, 7884 EVL, VT, MMO, ISD::UNINDEXED, 7885 /*IsTruncating*/ false, IsCompressing); 7886 7887 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7888 "Should only be a truncating store, not extending!"); 7889 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!"); 7890 assert(VT.isVector() == SVT.isVector() && 7891 "Cannot use trunc store to convert to or from a vector!"); 7892 assert((!VT.isVector() || 7893 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7894 "Cannot use trunc store to change the number of vector elements!"); 7895 7896 SDVTList VTs = getVTList(MVT::Other); 7897 SDValue Undef = getUNDEF(Ptr.getValueType()); 7898 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL}; 7899 FoldingSetNodeID ID; 7900 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7901 ID.AddInteger(SVT.getRawBits()); 7902 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>( 7903 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO)); 7904 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7905 void *IP = nullptr; 7906 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7907 cast<VPStoreSDNode>(E)->refineAlignment(MMO); 7908 return SDValue(E, 0); 7909 } 7910 auto *N = 7911 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7912 ISD::UNINDEXED, true, IsCompressing, SVT, MMO); 7913 createOperands(N, Ops); 7914 7915 CSEMap.InsertNode(N, IP); 7916 InsertNode(N); 7917 SDValue V(N, 0); 7918 NewSDValueDbgMsg(V, "Creating new node: ", this); 7919 return V; 7920 } 7921 7922 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, 7923 SDValue Base, SDValue Offset, 7924 ISD::MemIndexedMode AM) { 7925 auto *ST = cast<VPStoreSDNode>(OrigStore); 7926 assert(ST->getOffset().isUndef() && "Store is already an indexed store!"); 7927 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7928 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base, 7929 Offset, ST->getMask(), ST->getVectorLength()}; 7930 FoldingSetNodeID ID; 7931 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops); 7932 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7933 ID.AddInteger(ST->getRawSubclassData()); 7934 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7935 void *IP = nullptr; 7936 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7937 return SDValue(E, 0); 7938 7939 auto *N = newSDNode<VPStoreSDNode>( 7940 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(), 7941 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand()); 7942 createOperands(N, Ops); 7943 7944 CSEMap.InsertNode(N, IP); 7945 InsertNode(N); 7946 SDValue V(N, 0); 7947 NewSDValueDbgMsg(V, "Creating new node: ", this); 7948 return V; 7949 } 7950 7951 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, 7952 ArrayRef<SDValue> Ops, MachineMemOperand *MMO, 7953 ISD::MemIndexType IndexType) { 7954 assert(Ops.size() == 6 && "Incompatible number of operands"); 7955 7956 FoldingSetNodeID ID; 7957 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops); 7958 ID.AddInteger(VT.getRawBits()); 7959 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>( 7960 dl.getIROrder(), VTs, VT, MMO, IndexType)); 7961 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7962 void *IP = nullptr; 7963 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7964 cast<VPGatherSDNode>(E)->refineAlignment(MMO); 7965 return SDValue(E, 0); 7966 } 7967 7968 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7969 VT, MMO, IndexType); 7970 createOperands(N, Ops); 7971 7972 assert(N->getMask().getValueType().getVectorElementCount() == 7973 N->getValueType(0).getVectorElementCount() && 7974 "Vector width mismatch between mask and data"); 7975 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7976 N->getValueType(0).getVectorElementCount().isScalable() && 7977 "Scalable flags of index and data do not match"); 7978 assert(ElementCount::isKnownGE( 7979 N->getIndex().getValueType().getVectorElementCount(), 7980 N->getValueType(0).getVectorElementCount()) && 7981 "Vector width mismatch between index and data"); 7982 assert(isa<ConstantSDNode>(N->getScale()) && 7983 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7984 "Scale should be a constant power of 2"); 7985 7986 CSEMap.InsertNode(N, IP); 7987 InsertNode(N); 7988 SDValue V(N, 0); 7989 NewSDValueDbgMsg(V, "Creating new node: ", this); 7990 return V; 7991 } 7992 7993 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, 7994 ArrayRef<SDValue> Ops, 7995 MachineMemOperand *MMO, 7996 ISD::MemIndexType IndexType) { 7997 assert(Ops.size() == 7 && "Incompatible number of operands"); 7998 7999 FoldingSetNodeID ID; 8000 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops); 8001 ID.AddInteger(VT.getRawBits()); 8002 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>( 8003 dl.getIROrder(), VTs, VT, MMO, IndexType)); 8004 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8005 void *IP = nullptr; 8006 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8007 cast<VPScatterSDNode>(E)->refineAlignment(MMO); 8008 return SDValue(E, 0); 8009 } 8010 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8011 VT, MMO, IndexType); 8012 createOperands(N, Ops); 8013 8014 assert(N->getMask().getValueType().getVectorElementCount() == 8015 N->getValue().getValueType().getVectorElementCount() && 8016 "Vector width mismatch between mask and data"); 8017 assert( 8018 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8019 N->getValue().getValueType().getVectorElementCount().isScalable() && 8020 "Scalable flags of index and data do not match"); 8021 assert(ElementCount::isKnownGE( 8022 N->getIndex().getValueType().getVectorElementCount(), 8023 N->getValue().getValueType().getVectorElementCount()) && 8024 "Vector width mismatch between index and data"); 8025 assert(isa<ConstantSDNode>(N->getScale()) && 8026 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8027 "Scale should be a constant power of 2"); 8028 8029 CSEMap.InsertNode(N, IP); 8030 InsertNode(N); 8031 SDValue V(N, 0); 8032 NewSDValueDbgMsg(V, "Creating new node: ", this); 8033 return V; 8034 } 8035 8036 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 8037 SDValue Base, SDValue Offset, SDValue Mask, 8038 SDValue PassThru, EVT MemVT, 8039 MachineMemOperand *MMO, 8040 ISD::MemIndexedMode AM, 8041 ISD::LoadExtType ExtTy, bool isExpanding) { 8042 bool Indexed = AM != ISD::UNINDEXED; 8043 assert((Indexed || Offset.isUndef()) && 8044 "Unindexed masked load with an offset!"); 8045 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 8046 : getVTList(VT, MVT::Other); 8047 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 8048 FoldingSetNodeID ID; 8049 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 8050 ID.AddInteger(MemVT.getRawBits()); 8051 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 8052 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 8053 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8054 void *IP = nullptr; 8055 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8056 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 8057 return SDValue(E, 0); 8058 } 8059 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 8060 AM, ExtTy, isExpanding, MemVT, MMO); 8061 createOperands(N, Ops); 8062 8063 CSEMap.InsertNode(N, IP); 8064 InsertNode(N); 8065 SDValue V(N, 0); 8066 NewSDValueDbgMsg(V, "Creating new node: ", this); 8067 return V; 8068 } 8069 8070 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 8071 SDValue Base, SDValue Offset, 8072 ISD::MemIndexedMode AM) { 8073 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 8074 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 8075 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 8076 Offset, LD->getMask(), LD->getPassThru(), 8077 LD->getMemoryVT(), LD->getMemOperand(), AM, 8078 LD->getExtensionType(), LD->isExpandingLoad()); 8079 } 8080 8081 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 8082 SDValue Val, SDValue Base, SDValue Offset, 8083 SDValue Mask, EVT MemVT, 8084 MachineMemOperand *MMO, 8085 ISD::MemIndexedMode AM, bool IsTruncating, 8086 bool IsCompressing) { 8087 assert(Chain.getValueType() == MVT::Other && 8088 "Invalid chain type"); 8089 bool Indexed = AM != ISD::UNINDEXED; 8090 assert((Indexed || Offset.isUndef()) && 8091 "Unindexed masked store with an offset!"); 8092 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 8093 : getVTList(MVT::Other); 8094 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 8095 FoldingSetNodeID ID; 8096 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 8097 ID.AddInteger(MemVT.getRawBits()); 8098 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 8099 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 8100 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8101 void *IP = nullptr; 8102 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8103 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 8104 return SDValue(E, 0); 8105 } 8106 auto *N = 8107 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 8108 IsTruncating, IsCompressing, MemVT, MMO); 8109 createOperands(N, Ops); 8110 8111 CSEMap.InsertNode(N, IP); 8112 InsertNode(N); 8113 SDValue V(N, 0); 8114 NewSDValueDbgMsg(V, "Creating new node: ", this); 8115 return V; 8116 } 8117 8118 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 8119 SDValue Base, SDValue Offset, 8120 ISD::MemIndexedMode AM) { 8121 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 8122 assert(ST->getOffset().isUndef() && 8123 "Masked store is already a indexed store!"); 8124 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 8125 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 8126 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 8127 } 8128 8129 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8130 ArrayRef<SDValue> Ops, 8131 MachineMemOperand *MMO, 8132 ISD::MemIndexType IndexType, 8133 ISD::LoadExtType ExtTy) { 8134 assert(Ops.size() == 6 && "Incompatible number of operands"); 8135 8136 FoldingSetNodeID ID; 8137 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 8138 ID.AddInteger(MemVT.getRawBits()); 8139 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 8140 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy)); 8141 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8142 void *IP = nullptr; 8143 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8144 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 8145 return SDValue(E, 0); 8146 } 8147 8148 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8149 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8150 VTs, MemVT, MMO, IndexType, ExtTy); 8151 createOperands(N, Ops); 8152 8153 assert(N->getPassThru().getValueType() == N->getValueType(0) && 8154 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 8155 assert(N->getMask().getValueType().getVectorElementCount() == 8156 N->getValueType(0).getVectorElementCount() && 8157 "Vector width mismatch between mask and data"); 8158 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 8159 N->getValueType(0).getVectorElementCount().isScalable() && 8160 "Scalable flags of index and data do not match"); 8161 assert(ElementCount::isKnownGE( 8162 N->getIndex().getValueType().getVectorElementCount(), 8163 N->getValueType(0).getVectorElementCount()) && 8164 "Vector width mismatch between index and data"); 8165 assert(isa<ConstantSDNode>(N->getScale()) && 8166 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8167 "Scale should be a constant power of 2"); 8168 8169 CSEMap.InsertNode(N, IP); 8170 InsertNode(N); 8171 SDValue V(N, 0); 8172 NewSDValueDbgMsg(V, "Creating new node: ", this); 8173 return V; 8174 } 8175 8176 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, 8177 ArrayRef<SDValue> Ops, 8178 MachineMemOperand *MMO, 8179 ISD::MemIndexType IndexType, 8180 bool IsTrunc) { 8181 assert(Ops.size() == 6 && "Incompatible number of operands"); 8182 8183 FoldingSetNodeID ID; 8184 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 8185 ID.AddInteger(MemVT.getRawBits()); 8186 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 8187 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc)); 8188 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 8189 void *IP = nullptr; 8190 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 8191 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 8192 return SDValue(E, 0); 8193 } 8194 8195 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]); 8196 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 8197 VTs, MemVT, MMO, IndexType, IsTrunc); 8198 createOperands(N, Ops); 8199 8200 assert(N->getMask().getValueType().getVectorElementCount() == 8201 N->getValue().getValueType().getVectorElementCount() && 8202 "Vector width mismatch between mask and data"); 8203 assert( 8204 N->getIndex().getValueType().getVectorElementCount().isScalable() == 8205 N->getValue().getValueType().getVectorElementCount().isScalable() && 8206 "Scalable flags of index and data do not match"); 8207 assert(ElementCount::isKnownGE( 8208 N->getIndex().getValueType().getVectorElementCount(), 8209 N->getValue().getValueType().getVectorElementCount()) && 8210 "Vector width mismatch between index and data"); 8211 assert(isa<ConstantSDNode>(N->getScale()) && 8212 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 8213 "Scale should be a constant power of 2"); 8214 8215 CSEMap.InsertNode(N, IP); 8216 InsertNode(N); 8217 SDValue V(N, 0); 8218 NewSDValueDbgMsg(V, "Creating new node: ", this); 8219 return V; 8220 } 8221 8222 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 8223 // select undef, T, F --> T (if T is a constant), otherwise F 8224 // select, ?, undef, F --> F 8225 // select, ?, T, undef --> T 8226 if (Cond.isUndef()) 8227 return isConstantValueOfAnyType(T) ? T : F; 8228 if (T.isUndef()) 8229 return F; 8230 if (F.isUndef()) 8231 return T; 8232 8233 // select true, T, F --> T 8234 // select false, T, F --> F 8235 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 8236 return CondC->isZero() ? F : T; 8237 8238 // TODO: This should simplify VSELECT with constant condition using something 8239 // like this (but check boolean contents to be complete?): 8240 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 8241 // return T; 8242 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 8243 // return F; 8244 8245 // select ?, T, T --> T 8246 if (T == F) 8247 return T; 8248 8249 return SDValue(); 8250 } 8251 8252 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 8253 // shift undef, Y --> 0 (can always assume that the undef value is 0) 8254 if (X.isUndef()) 8255 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 8256 // shift X, undef --> undef (because it may shift by the bitwidth) 8257 if (Y.isUndef()) 8258 return getUNDEF(X.getValueType()); 8259 8260 // shift 0, Y --> 0 8261 // shift X, 0 --> X 8262 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 8263 return X; 8264 8265 // shift X, C >= bitwidth(X) --> undef 8266 // All vector elements must be too big (or undef) to avoid partial undefs. 8267 auto isShiftTooBig = [X](ConstantSDNode *Val) { 8268 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 8269 }; 8270 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 8271 return getUNDEF(X.getValueType()); 8272 8273 return SDValue(); 8274 } 8275 8276 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 8277 SDNodeFlags Flags) { 8278 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 8279 // (an undef operand can be chosen to be Nan/Inf), then the result of this 8280 // operation is poison. That result can be relaxed to undef. 8281 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 8282 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 8283 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 8284 (YC && YC->getValueAPF().isNaN()); 8285 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 8286 (YC && YC->getValueAPF().isInfinity()); 8287 8288 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 8289 return getUNDEF(X.getValueType()); 8290 8291 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 8292 return getUNDEF(X.getValueType()); 8293 8294 if (!YC) 8295 return SDValue(); 8296 8297 // X + -0.0 --> X 8298 if (Opcode == ISD::FADD) 8299 if (YC->getValueAPF().isNegZero()) 8300 return X; 8301 8302 // X - +0.0 --> X 8303 if (Opcode == ISD::FSUB) 8304 if (YC->getValueAPF().isPosZero()) 8305 return X; 8306 8307 // X * 1.0 --> X 8308 // X / 1.0 --> X 8309 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 8310 if (YC->getValueAPF().isExactlyValue(1.0)) 8311 return X; 8312 8313 // X * 0.0 --> 0.0 8314 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 8315 if (YC->getValueAPF().isZero()) 8316 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 8317 8318 return SDValue(); 8319 } 8320 8321 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 8322 SDValue Ptr, SDValue SV, unsigned Align) { 8323 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 8324 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 8325 } 8326 8327 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8328 ArrayRef<SDUse> Ops) { 8329 switch (Ops.size()) { 8330 case 0: return getNode(Opcode, DL, VT); 8331 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 8332 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 8333 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 8334 default: break; 8335 } 8336 8337 // Copy from an SDUse array into an SDValue array for use with 8338 // the regular getNode logic. 8339 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 8340 return getNode(Opcode, DL, VT, NewOps); 8341 } 8342 8343 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8344 ArrayRef<SDValue> Ops) { 8345 SDNodeFlags Flags; 8346 if (Inserter) 8347 Flags = Inserter->getFlags(); 8348 return getNode(Opcode, DL, VT, Ops, Flags); 8349 } 8350 8351 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 8352 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8353 unsigned NumOps = Ops.size(); 8354 switch (NumOps) { 8355 case 0: return getNode(Opcode, DL, VT); 8356 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 8357 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 8358 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 8359 default: break; 8360 } 8361 8362 #ifndef NDEBUG 8363 for (auto &Op : Ops) 8364 assert(Op.getOpcode() != ISD::DELETED_NODE && 8365 "Operand is DELETED_NODE!"); 8366 #endif 8367 8368 switch (Opcode) { 8369 default: break; 8370 case ISD::BUILD_VECTOR: 8371 // Attempt to simplify BUILD_VECTOR. 8372 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 8373 return V; 8374 break; 8375 case ISD::CONCAT_VECTORS: 8376 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 8377 return V; 8378 break; 8379 case ISD::SELECT_CC: 8380 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 8381 assert(Ops[0].getValueType() == Ops[1].getValueType() && 8382 "LHS and RHS of condition must have same type!"); 8383 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8384 "True and False arms of SelectCC must have same type!"); 8385 assert(Ops[2].getValueType() == VT && 8386 "select_cc node must be of same type as true and false value!"); 8387 break; 8388 case ISD::BR_CC: 8389 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 8390 assert(Ops[2].getValueType() == Ops[3].getValueType() && 8391 "LHS/RHS of comparison should match types!"); 8392 break; 8393 } 8394 8395 // Memoize nodes. 8396 SDNode *N; 8397 SDVTList VTs = getVTList(VT); 8398 8399 if (VT != MVT::Glue) { 8400 FoldingSetNodeID ID; 8401 AddNodeIDNode(ID, Opcode, VTs, Ops); 8402 void *IP = nullptr; 8403 8404 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8405 return SDValue(E, 0); 8406 8407 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8408 createOperands(N, Ops); 8409 8410 CSEMap.InsertNode(N, IP); 8411 } else { 8412 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8413 createOperands(N, Ops); 8414 } 8415 8416 N->setFlags(Flags); 8417 InsertNode(N); 8418 SDValue V(N, 0); 8419 NewSDValueDbgMsg(V, "Creating new node: ", this); 8420 return V; 8421 } 8422 8423 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8424 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 8425 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 8426 } 8427 8428 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8429 ArrayRef<SDValue> Ops) { 8430 SDNodeFlags Flags; 8431 if (Inserter) 8432 Flags = Inserter->getFlags(); 8433 return getNode(Opcode, DL, VTList, Ops, Flags); 8434 } 8435 8436 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8437 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 8438 if (VTList.NumVTs == 1) 8439 return getNode(Opcode, DL, VTList.VTs[0], Ops); 8440 8441 #ifndef NDEBUG 8442 for (auto &Op : Ops) 8443 assert(Op.getOpcode() != ISD::DELETED_NODE && 8444 "Operand is DELETED_NODE!"); 8445 #endif 8446 8447 switch (Opcode) { 8448 case ISD::STRICT_FP_EXTEND: 8449 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 8450 "Invalid STRICT_FP_EXTEND!"); 8451 assert(VTList.VTs[0].isFloatingPoint() && 8452 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 8453 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8454 "STRICT_FP_EXTEND result type should be vector iff the operand " 8455 "type is vector!"); 8456 assert((!VTList.VTs[0].isVector() || 8457 VTList.VTs[0].getVectorNumElements() == 8458 Ops[1].getValueType().getVectorNumElements()) && 8459 "Vector element count mismatch!"); 8460 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 8461 "Invalid fpext node, dst <= src!"); 8462 break; 8463 case ISD::STRICT_FP_ROUND: 8464 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 8465 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 8466 "STRICT_FP_ROUND result type should be vector iff the operand " 8467 "type is vector!"); 8468 assert((!VTList.VTs[0].isVector() || 8469 VTList.VTs[0].getVectorNumElements() == 8470 Ops[1].getValueType().getVectorNumElements()) && 8471 "Vector element count mismatch!"); 8472 assert(VTList.VTs[0].isFloatingPoint() && 8473 Ops[1].getValueType().isFloatingPoint() && 8474 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 8475 isa<ConstantSDNode>(Ops[2]) && 8476 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 8477 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 8478 "Invalid STRICT_FP_ROUND!"); 8479 break; 8480 #if 0 8481 // FIXME: figure out how to safely handle things like 8482 // int foo(int x) { return 1 << (x & 255); } 8483 // int bar() { return foo(256); } 8484 case ISD::SRA_PARTS: 8485 case ISD::SRL_PARTS: 8486 case ISD::SHL_PARTS: 8487 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 8488 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 8489 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8490 else if (N3.getOpcode() == ISD::AND) 8491 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 8492 // If the and is only masking out bits that cannot effect the shift, 8493 // eliminate the and. 8494 unsigned NumBits = VT.getScalarSizeInBits()*2; 8495 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 8496 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 8497 } 8498 break; 8499 #endif 8500 } 8501 8502 // Memoize the node unless it returns a flag. 8503 SDNode *N; 8504 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 8505 FoldingSetNodeID ID; 8506 AddNodeIDNode(ID, Opcode, VTList, Ops); 8507 void *IP = nullptr; 8508 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 8509 return SDValue(E, 0); 8510 8511 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8512 createOperands(N, Ops); 8513 CSEMap.InsertNode(N, IP); 8514 } else { 8515 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 8516 createOperands(N, Ops); 8517 } 8518 8519 N->setFlags(Flags); 8520 InsertNode(N); 8521 SDValue V(N, 0); 8522 NewSDValueDbgMsg(V, "Creating new node: ", this); 8523 return V; 8524 } 8525 8526 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 8527 SDVTList VTList) { 8528 return getNode(Opcode, DL, VTList, None); 8529 } 8530 8531 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8532 SDValue N1) { 8533 SDValue Ops[] = { N1 }; 8534 return getNode(Opcode, DL, VTList, Ops); 8535 } 8536 8537 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8538 SDValue N1, SDValue N2) { 8539 SDValue Ops[] = { N1, N2 }; 8540 return getNode(Opcode, DL, VTList, Ops); 8541 } 8542 8543 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8544 SDValue N1, SDValue N2, SDValue N3) { 8545 SDValue Ops[] = { N1, N2, N3 }; 8546 return getNode(Opcode, DL, VTList, Ops); 8547 } 8548 8549 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8550 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 8551 SDValue Ops[] = { N1, N2, N3, N4 }; 8552 return getNode(Opcode, DL, VTList, Ops); 8553 } 8554 8555 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 8556 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 8557 SDValue N5) { 8558 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 8559 return getNode(Opcode, DL, VTList, Ops); 8560 } 8561 8562 SDVTList SelectionDAG::getVTList(EVT VT) { 8563 return makeVTList(SDNode::getValueTypeList(VT), 1); 8564 } 8565 8566 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 8567 FoldingSetNodeID ID; 8568 ID.AddInteger(2U); 8569 ID.AddInteger(VT1.getRawBits()); 8570 ID.AddInteger(VT2.getRawBits()); 8571 8572 void *IP = nullptr; 8573 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8574 if (!Result) { 8575 EVT *Array = Allocator.Allocate<EVT>(2); 8576 Array[0] = VT1; 8577 Array[1] = VT2; 8578 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 8579 VTListMap.InsertNode(Result, IP); 8580 } 8581 return Result->getSDVTList(); 8582 } 8583 8584 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 8585 FoldingSetNodeID ID; 8586 ID.AddInteger(3U); 8587 ID.AddInteger(VT1.getRawBits()); 8588 ID.AddInteger(VT2.getRawBits()); 8589 ID.AddInteger(VT3.getRawBits()); 8590 8591 void *IP = nullptr; 8592 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8593 if (!Result) { 8594 EVT *Array = Allocator.Allocate<EVT>(3); 8595 Array[0] = VT1; 8596 Array[1] = VT2; 8597 Array[2] = VT3; 8598 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 8599 VTListMap.InsertNode(Result, IP); 8600 } 8601 return Result->getSDVTList(); 8602 } 8603 8604 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 8605 FoldingSetNodeID ID; 8606 ID.AddInteger(4U); 8607 ID.AddInteger(VT1.getRawBits()); 8608 ID.AddInteger(VT2.getRawBits()); 8609 ID.AddInteger(VT3.getRawBits()); 8610 ID.AddInteger(VT4.getRawBits()); 8611 8612 void *IP = nullptr; 8613 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8614 if (!Result) { 8615 EVT *Array = Allocator.Allocate<EVT>(4); 8616 Array[0] = VT1; 8617 Array[1] = VT2; 8618 Array[2] = VT3; 8619 Array[3] = VT4; 8620 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 8621 VTListMap.InsertNode(Result, IP); 8622 } 8623 return Result->getSDVTList(); 8624 } 8625 8626 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 8627 unsigned NumVTs = VTs.size(); 8628 FoldingSetNodeID ID; 8629 ID.AddInteger(NumVTs); 8630 for (unsigned index = 0; index < NumVTs; index++) { 8631 ID.AddInteger(VTs[index].getRawBits()); 8632 } 8633 8634 void *IP = nullptr; 8635 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8636 if (!Result) { 8637 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 8638 llvm::copy(VTs, Array); 8639 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 8640 VTListMap.InsertNode(Result, IP); 8641 } 8642 return Result->getSDVTList(); 8643 } 8644 8645 8646 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 8647 /// specified operands. If the resultant node already exists in the DAG, 8648 /// this does not modify the specified node, instead it returns the node that 8649 /// already exists. If the resultant node does not exist in the DAG, the 8650 /// input node is returned. As a degenerate case, if you specify the same 8651 /// input operands as the node already has, the input node is returned. 8652 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 8653 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 8654 8655 // Check to see if there is no change. 8656 if (Op == N->getOperand(0)) return N; 8657 8658 // See if the modified node already exists. 8659 void *InsertPos = nullptr; 8660 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 8661 return Existing; 8662 8663 // Nope it doesn't. Remove the node from its current place in the maps. 8664 if (InsertPos) 8665 if (!RemoveNodeFromCSEMaps(N)) 8666 InsertPos = nullptr; 8667 8668 // Now we update the operands. 8669 N->OperandList[0].set(Op); 8670 8671 updateDivergence(N); 8672 // If this gets put into a CSE map, add it. 8673 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8674 return N; 8675 } 8676 8677 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 8678 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 8679 8680 // Check to see if there is no change. 8681 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 8682 return N; // No operands changed, just return the input node. 8683 8684 // See if the modified node already exists. 8685 void *InsertPos = nullptr; 8686 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 8687 return Existing; 8688 8689 // Nope it doesn't. Remove the node from its current place in the maps. 8690 if (InsertPos) 8691 if (!RemoveNodeFromCSEMaps(N)) 8692 InsertPos = nullptr; 8693 8694 // Now we update the operands. 8695 if (N->OperandList[0] != Op1) 8696 N->OperandList[0].set(Op1); 8697 if (N->OperandList[1] != Op2) 8698 N->OperandList[1].set(Op2); 8699 8700 updateDivergence(N); 8701 // If this gets put into a CSE map, add it. 8702 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8703 return N; 8704 } 8705 8706 SDNode *SelectionDAG:: 8707 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 8708 SDValue Ops[] = { Op1, Op2, Op3 }; 8709 return UpdateNodeOperands(N, Ops); 8710 } 8711 8712 SDNode *SelectionDAG:: 8713 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8714 SDValue Op3, SDValue Op4) { 8715 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 8716 return UpdateNodeOperands(N, Ops); 8717 } 8718 8719 SDNode *SelectionDAG:: 8720 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8721 SDValue Op3, SDValue Op4, SDValue Op5) { 8722 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 8723 return UpdateNodeOperands(N, Ops); 8724 } 8725 8726 SDNode *SelectionDAG:: 8727 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 8728 unsigned NumOps = Ops.size(); 8729 assert(N->getNumOperands() == NumOps && 8730 "Update with wrong number of operands"); 8731 8732 // If no operands changed just return the input node. 8733 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 8734 return N; 8735 8736 // See if the modified node already exists. 8737 void *InsertPos = nullptr; 8738 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8739 return Existing; 8740 8741 // Nope it doesn't. Remove the node from its current place in the maps. 8742 if (InsertPos) 8743 if (!RemoveNodeFromCSEMaps(N)) 8744 InsertPos = nullptr; 8745 8746 // Now we update the operands. 8747 for (unsigned i = 0; i != NumOps; ++i) 8748 if (N->OperandList[i] != Ops[i]) 8749 N->OperandList[i].set(Ops[i]); 8750 8751 updateDivergence(N); 8752 // If this gets put into a CSE map, add it. 8753 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8754 return N; 8755 } 8756 8757 /// DropOperands - Release the operands and set this node to have 8758 /// zero operands. 8759 void SDNode::DropOperands() { 8760 // Unlike the code in MorphNodeTo that does this, we don't need to 8761 // watch for dead nodes here. 8762 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8763 SDUse &Use = *I++; 8764 Use.set(SDValue()); 8765 } 8766 } 8767 8768 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8769 ArrayRef<MachineMemOperand *> NewMemRefs) { 8770 if (NewMemRefs.empty()) { 8771 N->clearMemRefs(); 8772 return; 8773 } 8774 8775 // Check if we can avoid allocating by storing a single reference directly. 8776 if (NewMemRefs.size() == 1) { 8777 N->MemRefs = NewMemRefs[0]; 8778 N->NumMemRefs = 1; 8779 return; 8780 } 8781 8782 MachineMemOperand **MemRefsBuffer = 8783 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8784 llvm::copy(NewMemRefs, MemRefsBuffer); 8785 N->MemRefs = MemRefsBuffer; 8786 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8787 } 8788 8789 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8790 /// machine opcode. 8791 /// 8792 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8793 EVT VT) { 8794 SDVTList VTs = getVTList(VT); 8795 return SelectNodeTo(N, MachineOpc, VTs, None); 8796 } 8797 8798 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8799 EVT VT, SDValue Op1) { 8800 SDVTList VTs = getVTList(VT); 8801 SDValue Ops[] = { Op1 }; 8802 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8803 } 8804 8805 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8806 EVT VT, SDValue Op1, 8807 SDValue Op2) { 8808 SDVTList VTs = getVTList(VT); 8809 SDValue Ops[] = { Op1, Op2 }; 8810 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8811 } 8812 8813 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8814 EVT VT, SDValue Op1, 8815 SDValue Op2, SDValue Op3) { 8816 SDVTList VTs = getVTList(VT); 8817 SDValue Ops[] = { Op1, Op2, Op3 }; 8818 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8819 } 8820 8821 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8822 EVT VT, ArrayRef<SDValue> Ops) { 8823 SDVTList VTs = getVTList(VT); 8824 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8825 } 8826 8827 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8828 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8829 SDVTList VTs = getVTList(VT1, VT2); 8830 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8831 } 8832 8833 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8834 EVT VT1, EVT VT2) { 8835 SDVTList VTs = getVTList(VT1, VT2); 8836 return SelectNodeTo(N, MachineOpc, VTs, None); 8837 } 8838 8839 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8840 EVT VT1, EVT VT2, EVT VT3, 8841 ArrayRef<SDValue> Ops) { 8842 SDVTList VTs = getVTList(VT1, VT2, VT3); 8843 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8844 } 8845 8846 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8847 EVT VT1, EVT VT2, 8848 SDValue Op1, SDValue Op2) { 8849 SDVTList VTs = getVTList(VT1, VT2); 8850 SDValue Ops[] = { Op1, Op2 }; 8851 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8852 } 8853 8854 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8855 SDVTList VTs,ArrayRef<SDValue> Ops) { 8856 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8857 // Reset the NodeID to -1. 8858 New->setNodeId(-1); 8859 if (New != N) { 8860 ReplaceAllUsesWith(N, New); 8861 RemoveDeadNode(N); 8862 } 8863 return New; 8864 } 8865 8866 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8867 /// the line number information on the merged node since it is not possible to 8868 /// preserve the information that operation is associated with multiple lines. 8869 /// This will make the debugger working better at -O0, were there is a higher 8870 /// probability having other instructions associated with that line. 8871 /// 8872 /// For IROrder, we keep the smaller of the two 8873 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8874 DebugLoc NLoc = N->getDebugLoc(); 8875 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8876 N->setDebugLoc(DebugLoc()); 8877 } 8878 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8879 N->setIROrder(Order); 8880 return N; 8881 } 8882 8883 /// MorphNodeTo - This *mutates* the specified node to have the specified 8884 /// return type, opcode, and operands. 8885 /// 8886 /// Note that MorphNodeTo returns the resultant node. If there is already a 8887 /// node of the specified opcode and operands, it returns that node instead of 8888 /// the current one. Note that the SDLoc need not be the same. 8889 /// 8890 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8891 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8892 /// node, and because it doesn't require CSE recalculation for any of 8893 /// the node's users. 8894 /// 8895 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8896 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8897 /// the legalizer which maintain worklists that would need to be updated when 8898 /// deleting things. 8899 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8900 SDVTList VTs, ArrayRef<SDValue> Ops) { 8901 // If an identical node already exists, use it. 8902 void *IP = nullptr; 8903 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8904 FoldingSetNodeID ID; 8905 AddNodeIDNode(ID, Opc, VTs, Ops); 8906 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8907 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8908 } 8909 8910 if (!RemoveNodeFromCSEMaps(N)) 8911 IP = nullptr; 8912 8913 // Start the morphing. 8914 N->NodeType = Opc; 8915 N->ValueList = VTs.VTs; 8916 N->NumValues = VTs.NumVTs; 8917 8918 // Clear the operands list, updating used nodes to remove this from their 8919 // use list. Keep track of any operands that become dead as a result. 8920 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8921 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8922 SDUse &Use = *I++; 8923 SDNode *Used = Use.getNode(); 8924 Use.set(SDValue()); 8925 if (Used->use_empty()) 8926 DeadNodeSet.insert(Used); 8927 } 8928 8929 // For MachineNode, initialize the memory references information. 8930 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8931 MN->clearMemRefs(); 8932 8933 // Swap for an appropriately sized array from the recycler. 8934 removeOperands(N); 8935 createOperands(N, Ops); 8936 8937 // Delete any nodes that are still dead after adding the uses for the 8938 // new operands. 8939 if (!DeadNodeSet.empty()) { 8940 SmallVector<SDNode *, 16> DeadNodes; 8941 for (SDNode *N : DeadNodeSet) 8942 if (N->use_empty()) 8943 DeadNodes.push_back(N); 8944 RemoveDeadNodes(DeadNodes); 8945 } 8946 8947 if (IP) 8948 CSEMap.InsertNode(N, IP); // Memoize the new node. 8949 return N; 8950 } 8951 8952 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8953 unsigned OrigOpc = Node->getOpcode(); 8954 unsigned NewOpc; 8955 switch (OrigOpc) { 8956 default: 8957 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8958 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8959 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8960 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8961 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8962 #include "llvm/IR/ConstrainedOps.def" 8963 } 8964 8965 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8966 8967 // We're taking this node out of the chain, so we need to re-link things. 8968 SDValue InputChain = Node->getOperand(0); 8969 SDValue OutputChain = SDValue(Node, 1); 8970 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8971 8972 SmallVector<SDValue, 3> Ops; 8973 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8974 Ops.push_back(Node->getOperand(i)); 8975 8976 SDVTList VTs = getVTList(Node->getValueType(0)); 8977 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8978 8979 // MorphNodeTo can operate in two ways: if an existing node with the 8980 // specified operands exists, it can just return it. Otherwise, it 8981 // updates the node in place to have the requested operands. 8982 if (Res == Node) { 8983 // If we updated the node in place, reset the node ID. To the isel, 8984 // this should be just like a newly allocated machine node. 8985 Res->setNodeId(-1); 8986 } else { 8987 ReplaceAllUsesWith(Node, Res); 8988 RemoveDeadNode(Node); 8989 } 8990 8991 return Res; 8992 } 8993 8994 /// getMachineNode - These are used for target selectors to create a new node 8995 /// with specified return type(s), MachineInstr opcode, and operands. 8996 /// 8997 /// Note that getMachineNode returns the resultant node. If there is already a 8998 /// node of the specified opcode and operands, it returns that node instead of 8999 /// the current one. 9000 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9001 EVT VT) { 9002 SDVTList VTs = getVTList(VT); 9003 return getMachineNode(Opcode, dl, VTs, None); 9004 } 9005 9006 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9007 EVT VT, SDValue Op1) { 9008 SDVTList VTs = getVTList(VT); 9009 SDValue Ops[] = { Op1 }; 9010 return getMachineNode(Opcode, dl, VTs, Ops); 9011 } 9012 9013 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9014 EVT VT, SDValue Op1, SDValue Op2) { 9015 SDVTList VTs = getVTList(VT); 9016 SDValue Ops[] = { Op1, Op2 }; 9017 return getMachineNode(Opcode, dl, VTs, Ops); 9018 } 9019 9020 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9021 EVT VT, SDValue Op1, SDValue Op2, 9022 SDValue Op3) { 9023 SDVTList VTs = getVTList(VT); 9024 SDValue Ops[] = { Op1, Op2, Op3 }; 9025 return getMachineNode(Opcode, dl, VTs, Ops); 9026 } 9027 9028 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9029 EVT VT, ArrayRef<SDValue> Ops) { 9030 SDVTList VTs = getVTList(VT); 9031 return getMachineNode(Opcode, dl, VTs, Ops); 9032 } 9033 9034 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9035 EVT VT1, EVT VT2, SDValue Op1, 9036 SDValue Op2) { 9037 SDVTList VTs = getVTList(VT1, VT2); 9038 SDValue Ops[] = { Op1, Op2 }; 9039 return getMachineNode(Opcode, dl, VTs, Ops); 9040 } 9041 9042 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9043 EVT VT1, EVT VT2, SDValue Op1, 9044 SDValue Op2, SDValue Op3) { 9045 SDVTList VTs = getVTList(VT1, VT2); 9046 SDValue Ops[] = { Op1, Op2, Op3 }; 9047 return getMachineNode(Opcode, dl, VTs, Ops); 9048 } 9049 9050 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9051 EVT VT1, EVT VT2, 9052 ArrayRef<SDValue> Ops) { 9053 SDVTList VTs = getVTList(VT1, VT2); 9054 return getMachineNode(Opcode, dl, VTs, Ops); 9055 } 9056 9057 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9058 EVT VT1, EVT VT2, EVT VT3, 9059 SDValue Op1, SDValue Op2) { 9060 SDVTList VTs = getVTList(VT1, VT2, VT3); 9061 SDValue Ops[] = { Op1, Op2 }; 9062 return getMachineNode(Opcode, dl, VTs, Ops); 9063 } 9064 9065 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9066 EVT VT1, EVT VT2, EVT VT3, 9067 SDValue Op1, SDValue Op2, 9068 SDValue Op3) { 9069 SDVTList VTs = getVTList(VT1, VT2, VT3); 9070 SDValue Ops[] = { Op1, Op2, Op3 }; 9071 return getMachineNode(Opcode, dl, VTs, Ops); 9072 } 9073 9074 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9075 EVT VT1, EVT VT2, EVT VT3, 9076 ArrayRef<SDValue> Ops) { 9077 SDVTList VTs = getVTList(VT1, VT2, VT3); 9078 return getMachineNode(Opcode, dl, VTs, Ops); 9079 } 9080 9081 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 9082 ArrayRef<EVT> ResultTys, 9083 ArrayRef<SDValue> Ops) { 9084 SDVTList VTs = getVTList(ResultTys); 9085 return getMachineNode(Opcode, dl, VTs, Ops); 9086 } 9087 9088 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 9089 SDVTList VTs, 9090 ArrayRef<SDValue> Ops) { 9091 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 9092 MachineSDNode *N; 9093 void *IP = nullptr; 9094 9095 if (DoCSE) { 9096 FoldingSetNodeID ID; 9097 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 9098 IP = nullptr; 9099 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 9100 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 9101 } 9102 } 9103 9104 // Allocate a new MachineSDNode. 9105 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 9106 createOperands(N, Ops); 9107 9108 if (DoCSE) 9109 CSEMap.InsertNode(N, IP); 9110 9111 InsertNode(N); 9112 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 9113 return N; 9114 } 9115 9116 /// getTargetExtractSubreg - A convenience function for creating 9117 /// TargetOpcode::EXTRACT_SUBREG nodes. 9118 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9119 SDValue Operand) { 9120 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9121 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 9122 VT, Operand, SRIdxVal); 9123 return SDValue(Subreg, 0); 9124 } 9125 9126 /// getTargetInsertSubreg - A convenience function for creating 9127 /// TargetOpcode::INSERT_SUBREG nodes. 9128 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 9129 SDValue Operand, SDValue Subreg) { 9130 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 9131 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 9132 VT, Operand, Subreg, SRIdxVal); 9133 return SDValue(Result, 0); 9134 } 9135 9136 /// getNodeIfExists - Get the specified node if it's already available, or 9137 /// else return NULL. 9138 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9139 ArrayRef<SDValue> Ops) { 9140 SDNodeFlags Flags; 9141 if (Inserter) 9142 Flags = Inserter->getFlags(); 9143 return getNodeIfExists(Opcode, VTList, Ops, Flags); 9144 } 9145 9146 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 9147 ArrayRef<SDValue> Ops, 9148 const SDNodeFlags Flags) { 9149 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9150 FoldingSetNodeID ID; 9151 AddNodeIDNode(ID, Opcode, VTList, Ops); 9152 void *IP = nullptr; 9153 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 9154 E->intersectFlagsWith(Flags); 9155 return E; 9156 } 9157 } 9158 return nullptr; 9159 } 9160 9161 /// doesNodeExist - Check if a node exists without modifying its flags. 9162 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 9163 ArrayRef<SDValue> Ops) { 9164 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 9165 FoldingSetNodeID ID; 9166 AddNodeIDNode(ID, Opcode, VTList, Ops); 9167 void *IP = nullptr; 9168 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 9169 return true; 9170 } 9171 return false; 9172 } 9173 9174 /// getDbgValue - Creates a SDDbgValue node. 9175 /// 9176 /// SDNode 9177 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 9178 SDNode *N, unsigned R, bool IsIndirect, 9179 const DebugLoc &DL, unsigned O) { 9180 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9181 "Expected inlined-at fields to agree"); 9182 return new (DbgInfo->getAlloc()) 9183 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R), 9184 {}, IsIndirect, DL, O, 9185 /*IsVariadic=*/false); 9186 } 9187 9188 /// Constant 9189 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 9190 DIExpression *Expr, 9191 const Value *C, 9192 const DebugLoc &DL, unsigned O) { 9193 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9194 "Expected inlined-at fields to agree"); 9195 return new (DbgInfo->getAlloc()) 9196 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {}, 9197 /*IsIndirect=*/false, DL, O, 9198 /*IsVariadic=*/false); 9199 } 9200 9201 /// FrameIndex 9202 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9203 DIExpression *Expr, unsigned FI, 9204 bool IsIndirect, 9205 const DebugLoc &DL, 9206 unsigned O) { 9207 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9208 "Expected inlined-at fields to agree"); 9209 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 9210 } 9211 9212 /// FrameIndex with dependencies 9213 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 9214 DIExpression *Expr, unsigned FI, 9215 ArrayRef<SDNode *> Dependencies, 9216 bool IsIndirect, 9217 const DebugLoc &DL, 9218 unsigned O) { 9219 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9220 "Expected inlined-at fields to agree"); 9221 return new (DbgInfo->getAlloc()) 9222 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI), 9223 Dependencies, IsIndirect, DL, O, 9224 /*IsVariadic=*/false); 9225 } 9226 9227 /// VReg 9228 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 9229 unsigned VReg, bool IsIndirect, 9230 const DebugLoc &DL, unsigned O) { 9231 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9232 "Expected inlined-at fields to agree"); 9233 return new (DbgInfo->getAlloc()) 9234 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg), 9235 {}, IsIndirect, DL, O, 9236 /*IsVariadic=*/false); 9237 } 9238 9239 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 9240 ArrayRef<SDDbgOperand> Locs, 9241 ArrayRef<SDNode *> Dependencies, 9242 bool IsIndirect, const DebugLoc &DL, 9243 unsigned O, bool IsVariadic) { 9244 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 9245 "Expected inlined-at fields to agree"); 9246 return new (DbgInfo->getAlloc()) 9247 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect, 9248 DL, O, IsVariadic); 9249 } 9250 9251 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 9252 unsigned OffsetInBits, unsigned SizeInBits, 9253 bool InvalidateDbg) { 9254 SDNode *FromNode = From.getNode(); 9255 SDNode *ToNode = To.getNode(); 9256 assert(FromNode && ToNode && "Can't modify dbg values"); 9257 9258 // PR35338 9259 // TODO: assert(From != To && "Redundant dbg value transfer"); 9260 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 9261 if (From == To || FromNode == ToNode) 9262 return; 9263 9264 if (!FromNode->getHasDebugValue()) 9265 return; 9266 9267 SDDbgOperand FromLocOp = 9268 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 9269 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 9270 9271 SmallVector<SDDbgValue *, 2> ClonedDVs; 9272 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 9273 if (Dbg->isInvalidated()) 9274 continue; 9275 9276 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 9277 9278 // Create a new location ops vector that is equal to the old vector, but 9279 // with each instance of FromLocOp replaced with ToLocOp. 9280 bool Changed = false; 9281 auto NewLocOps = Dbg->copyLocationOps(); 9282 std::replace_if( 9283 NewLocOps.begin(), NewLocOps.end(), 9284 [&Changed, FromLocOp](const SDDbgOperand &Op) { 9285 bool Match = Op == FromLocOp; 9286 Changed |= Match; 9287 return Match; 9288 }, 9289 ToLocOp); 9290 // Ignore this SDDbgValue if we didn't find a matching location. 9291 if (!Changed) 9292 continue; 9293 9294 DIVariable *Var = Dbg->getVariable(); 9295 auto *Expr = Dbg->getExpression(); 9296 // If a fragment is requested, update the expression. 9297 if (SizeInBits) { 9298 // When splitting a larger (e.g., sign-extended) value whose 9299 // lower bits are described with an SDDbgValue, do not attempt 9300 // to transfer the SDDbgValue to the upper bits. 9301 if (auto FI = Expr->getFragmentInfo()) 9302 if (OffsetInBits + SizeInBits > FI->SizeInBits) 9303 continue; 9304 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 9305 SizeInBits); 9306 if (!Fragment) 9307 continue; 9308 Expr = *Fragment; 9309 } 9310 9311 auto AdditionalDependencies = Dbg->getAdditionalDependencies(); 9312 // Clone the SDDbgValue and move it to To. 9313 SDDbgValue *Clone = getDbgValueList( 9314 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(), 9315 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 9316 Dbg->isVariadic()); 9317 ClonedDVs.push_back(Clone); 9318 9319 if (InvalidateDbg) { 9320 // Invalidate value and indicate the SDDbgValue should not be emitted. 9321 Dbg->setIsInvalidated(); 9322 Dbg->setIsEmitted(); 9323 } 9324 } 9325 9326 for (SDDbgValue *Dbg : ClonedDVs) { 9327 assert(is_contained(Dbg->getSDNodes(), ToNode) && 9328 "Transferred DbgValues should depend on the new SDNode"); 9329 AddDbgValue(Dbg, false); 9330 } 9331 } 9332 9333 void SelectionDAG::salvageDebugInfo(SDNode &N) { 9334 if (!N.getHasDebugValue()) 9335 return; 9336 9337 SmallVector<SDDbgValue *, 2> ClonedDVs; 9338 for (auto DV : GetDbgValues(&N)) { 9339 if (DV->isInvalidated()) 9340 continue; 9341 switch (N.getOpcode()) { 9342 default: 9343 break; 9344 case ISD::ADD: 9345 SDValue N0 = N.getOperand(0); 9346 SDValue N1 = N.getOperand(1); 9347 if (!isConstantIntBuildVectorOrConstantInt(N0) && 9348 isConstantIntBuildVectorOrConstantInt(N1)) { 9349 uint64_t Offset = N.getConstantOperandVal(1); 9350 9351 // Rewrite an ADD constant node into a DIExpression. Since we are 9352 // performing arithmetic to compute the variable's *value* in the 9353 // DIExpression, we need to mark the expression with a 9354 // DW_OP_stack_value. 9355 auto *DIExpr = DV->getExpression(); 9356 auto NewLocOps = DV->copyLocationOps(); 9357 bool Changed = false; 9358 for (size_t i = 0; i < NewLocOps.size(); ++i) { 9359 // We're not given a ResNo to compare against because the whole 9360 // node is going away. We know that any ISD::ADD only has one 9361 // result, so we can assume any node match is using the result. 9362 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 9363 NewLocOps[i].getSDNode() != &N) 9364 continue; 9365 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 9366 SmallVector<uint64_t, 3> ExprOps; 9367 DIExpression::appendOffset(ExprOps, Offset); 9368 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 9369 Changed = true; 9370 } 9371 (void)Changed; 9372 assert(Changed && "Salvage target doesn't use N"); 9373 9374 auto AdditionalDependencies = DV->getAdditionalDependencies(); 9375 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 9376 NewLocOps, AdditionalDependencies, 9377 DV->isIndirect(), DV->getDebugLoc(), 9378 DV->getOrder(), DV->isVariadic()); 9379 ClonedDVs.push_back(Clone); 9380 DV->setIsInvalidated(); 9381 DV->setIsEmitted(); 9382 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 9383 N0.getNode()->dumprFull(this); 9384 dbgs() << " into " << *DIExpr << '\n'); 9385 } 9386 } 9387 } 9388 9389 for (SDDbgValue *Dbg : ClonedDVs) { 9390 assert(!Dbg->getSDNodes().empty() && 9391 "Salvaged DbgValue should depend on a new SDNode"); 9392 AddDbgValue(Dbg, false); 9393 } 9394 } 9395 9396 /// Creates a SDDbgLabel node. 9397 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 9398 const DebugLoc &DL, unsigned O) { 9399 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 9400 "Expected inlined-at fields to agree"); 9401 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 9402 } 9403 9404 namespace { 9405 9406 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 9407 /// pointed to by a use iterator is deleted, increment the use iterator 9408 /// so that it doesn't dangle. 9409 /// 9410 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 9411 SDNode::use_iterator &UI; 9412 SDNode::use_iterator &UE; 9413 9414 void NodeDeleted(SDNode *N, SDNode *E) override { 9415 // Increment the iterator as needed. 9416 while (UI != UE && N == *UI) 9417 ++UI; 9418 } 9419 9420 public: 9421 RAUWUpdateListener(SelectionDAG &d, 9422 SDNode::use_iterator &ui, 9423 SDNode::use_iterator &ue) 9424 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 9425 }; 9426 9427 } // end anonymous namespace 9428 9429 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9430 /// This can cause recursive merging of nodes in the DAG. 9431 /// 9432 /// This version assumes From has a single result value. 9433 /// 9434 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 9435 SDNode *From = FromN.getNode(); 9436 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 9437 "Cannot replace with this method!"); 9438 assert(From != To.getNode() && "Cannot replace uses of with self"); 9439 9440 // Preserve Debug Values 9441 transferDbgValues(FromN, To); 9442 9443 // Iterate over all the existing uses of From. New uses will be added 9444 // to the beginning of the use list, which we avoid visiting. 9445 // This specifically avoids visiting uses of From that arise while the 9446 // replacement is happening, because any such uses would be the result 9447 // of CSE: If an existing node looks like From after one of its operands 9448 // is replaced by To, we don't want to replace of all its users with To 9449 // too. See PR3018 for more info. 9450 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9451 RAUWUpdateListener Listener(*this, UI, UE); 9452 while (UI != UE) { 9453 SDNode *User = *UI; 9454 9455 // This node is about to morph, remove its old self from the CSE maps. 9456 RemoveNodeFromCSEMaps(User); 9457 9458 // A user can appear in a use list multiple times, and when this 9459 // happens the uses are usually next to each other in the list. 9460 // To help reduce the number of CSE recomputations, process all 9461 // the uses of this user that we can find this way. 9462 do { 9463 SDUse &Use = UI.getUse(); 9464 ++UI; 9465 Use.set(To); 9466 if (To->isDivergent() != From->isDivergent()) 9467 updateDivergence(User); 9468 } while (UI != UE && *UI == User); 9469 // Now that we have modified User, add it back to the CSE maps. If it 9470 // already exists there, recursively merge the results together. 9471 AddModifiedNodeToCSEMaps(User); 9472 } 9473 9474 // If we just RAUW'd the root, take note. 9475 if (FromN == getRoot()) 9476 setRoot(To); 9477 } 9478 9479 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9480 /// This can cause recursive merging of nodes in the DAG. 9481 /// 9482 /// This version assumes that for each value of From, there is a 9483 /// corresponding value in To in the same position with the same type. 9484 /// 9485 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 9486 #ifndef NDEBUG 9487 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9488 assert((!From->hasAnyUseOfValue(i) || 9489 From->getValueType(i) == To->getValueType(i)) && 9490 "Cannot use this version of ReplaceAllUsesWith!"); 9491 #endif 9492 9493 // Handle the trivial case. 9494 if (From == To) 9495 return; 9496 9497 // Preserve Debug Info. Only do this if there's a use. 9498 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9499 if (From->hasAnyUseOfValue(i)) { 9500 assert((i < To->getNumValues()) && "Invalid To location"); 9501 transferDbgValues(SDValue(From, i), SDValue(To, i)); 9502 } 9503 9504 // Iterate over just the existing users of From. See the comments in 9505 // the ReplaceAllUsesWith above. 9506 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9507 RAUWUpdateListener Listener(*this, UI, UE); 9508 while (UI != UE) { 9509 SDNode *User = *UI; 9510 9511 // This node is about to morph, remove its old self from the CSE maps. 9512 RemoveNodeFromCSEMaps(User); 9513 9514 // A user can appear in a use list multiple times, and when this 9515 // happens the uses are usually next to each other in the list. 9516 // To help reduce the number of CSE recomputations, process all 9517 // the uses of this user that we can find this way. 9518 do { 9519 SDUse &Use = UI.getUse(); 9520 ++UI; 9521 Use.setNode(To); 9522 if (To->isDivergent() != From->isDivergent()) 9523 updateDivergence(User); 9524 } while (UI != UE && *UI == User); 9525 9526 // Now that we have modified User, add it back to the CSE maps. If it 9527 // already exists there, recursively merge the results together. 9528 AddModifiedNodeToCSEMaps(User); 9529 } 9530 9531 // If we just RAUW'd the root, take note. 9532 if (From == getRoot().getNode()) 9533 setRoot(SDValue(To, getRoot().getResNo())); 9534 } 9535 9536 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 9537 /// This can cause recursive merging of nodes in the DAG. 9538 /// 9539 /// This version can replace From with any result values. To must match the 9540 /// number and types of values returned by From. 9541 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 9542 if (From->getNumValues() == 1) // Handle the simple case efficiently. 9543 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 9544 9545 // Preserve Debug Info. 9546 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 9547 transferDbgValues(SDValue(From, i), To[i]); 9548 9549 // Iterate over just the existing users of From. See the comments in 9550 // the ReplaceAllUsesWith above. 9551 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 9552 RAUWUpdateListener Listener(*this, UI, UE); 9553 while (UI != UE) { 9554 SDNode *User = *UI; 9555 9556 // This node is about to morph, remove its old self from the CSE maps. 9557 RemoveNodeFromCSEMaps(User); 9558 9559 // A user can appear in a use list multiple times, and when this happens the 9560 // uses are usually next to each other in the list. To help reduce the 9561 // number of CSE and divergence recomputations, process all the uses of this 9562 // user that we can find this way. 9563 bool To_IsDivergent = false; 9564 do { 9565 SDUse &Use = UI.getUse(); 9566 const SDValue &ToOp = To[Use.getResNo()]; 9567 ++UI; 9568 Use.set(ToOp); 9569 To_IsDivergent |= ToOp->isDivergent(); 9570 } while (UI != UE && *UI == User); 9571 9572 if (To_IsDivergent != From->isDivergent()) 9573 updateDivergence(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 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 9586 /// uses of other values produced by From.getNode() alone. The Deleted 9587 /// vector is handled the same way as for ReplaceAllUsesWith. 9588 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 9589 // Handle the really simple, really trivial case efficiently. 9590 if (From == To) return; 9591 9592 // Handle the simple, trivial, case efficiently. 9593 if (From.getNode()->getNumValues() == 1) { 9594 ReplaceAllUsesWith(From, To); 9595 return; 9596 } 9597 9598 // Preserve Debug Info. 9599 transferDbgValues(From, To); 9600 9601 // Iterate over just the existing users of From. See the comments in 9602 // the ReplaceAllUsesWith above. 9603 SDNode::use_iterator UI = From.getNode()->use_begin(), 9604 UE = From.getNode()->use_end(); 9605 RAUWUpdateListener Listener(*this, UI, UE); 9606 while (UI != UE) { 9607 SDNode *User = *UI; 9608 bool UserRemovedFromCSEMaps = false; 9609 9610 // A user can appear in a use list multiple times, and when this 9611 // happens the uses are usually next to each other in the list. 9612 // To help reduce the number of CSE recomputations, process all 9613 // the uses of this user that we can find this way. 9614 do { 9615 SDUse &Use = UI.getUse(); 9616 9617 // Skip uses of different values from the same node. 9618 if (Use.getResNo() != From.getResNo()) { 9619 ++UI; 9620 continue; 9621 } 9622 9623 // If this node hasn't been modified yet, it's still in the CSE maps, 9624 // so remove its old self from the CSE maps. 9625 if (!UserRemovedFromCSEMaps) { 9626 RemoveNodeFromCSEMaps(User); 9627 UserRemovedFromCSEMaps = true; 9628 } 9629 9630 ++UI; 9631 Use.set(To); 9632 if (To->isDivergent() != From->isDivergent()) 9633 updateDivergence(User); 9634 } while (UI != UE && *UI == User); 9635 // We are iterating over all uses of the From node, so if a use 9636 // doesn't use the specific value, no changes are made. 9637 if (!UserRemovedFromCSEMaps) 9638 continue; 9639 9640 // Now that we have modified User, add it back to the CSE maps. If it 9641 // already exists there, recursively merge the results together. 9642 AddModifiedNodeToCSEMaps(User); 9643 } 9644 9645 // If we just RAUW'd the root, take note. 9646 if (From == getRoot()) 9647 setRoot(To); 9648 } 9649 9650 namespace { 9651 9652 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 9653 /// to record information about a use. 9654 struct UseMemo { 9655 SDNode *User; 9656 unsigned Index; 9657 SDUse *Use; 9658 }; 9659 9660 /// operator< - Sort Memos by User. 9661 bool operator<(const UseMemo &L, const UseMemo &R) { 9662 return (intptr_t)L.User < (intptr_t)R.User; 9663 } 9664 9665 } // end anonymous namespace 9666 9667 bool SelectionDAG::calculateDivergence(SDNode *N) { 9668 if (TLI->isSDNodeAlwaysUniform(N)) { 9669 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 9670 "Conflicting divergence information!"); 9671 return false; 9672 } 9673 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 9674 return true; 9675 for (auto &Op : N->ops()) { 9676 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 9677 return true; 9678 } 9679 return false; 9680 } 9681 9682 void SelectionDAG::updateDivergence(SDNode *N) { 9683 SmallVector<SDNode *, 16> Worklist(1, N); 9684 do { 9685 N = Worklist.pop_back_val(); 9686 bool IsDivergent = calculateDivergence(N); 9687 if (N->SDNodeBits.IsDivergent != IsDivergent) { 9688 N->SDNodeBits.IsDivergent = IsDivergent; 9689 llvm::append_range(Worklist, N->uses()); 9690 } 9691 } while (!Worklist.empty()); 9692 } 9693 9694 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 9695 DenseMap<SDNode *, unsigned> Degree; 9696 Order.reserve(AllNodes.size()); 9697 for (auto &N : allnodes()) { 9698 unsigned NOps = N.getNumOperands(); 9699 Degree[&N] = NOps; 9700 if (0 == NOps) 9701 Order.push_back(&N); 9702 } 9703 for (size_t I = 0; I != Order.size(); ++I) { 9704 SDNode *N = Order[I]; 9705 for (auto U : N->uses()) { 9706 unsigned &UnsortedOps = Degree[U]; 9707 if (0 == --UnsortedOps) 9708 Order.push_back(U); 9709 } 9710 } 9711 } 9712 9713 #ifndef NDEBUG 9714 void SelectionDAG::VerifyDAGDivergence() { 9715 std::vector<SDNode *> TopoOrder; 9716 CreateTopologicalOrder(TopoOrder); 9717 for (auto *N : TopoOrder) { 9718 assert(calculateDivergence(N) == N->isDivergent() && 9719 "Divergence bit inconsistency detected"); 9720 } 9721 } 9722 #endif 9723 9724 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 9725 /// uses of other values produced by From.getNode() alone. The same value 9726 /// may appear in both the From and To list. The Deleted vector is 9727 /// handled the same way as for ReplaceAllUsesWith. 9728 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 9729 const SDValue *To, 9730 unsigned Num){ 9731 // Handle the simple, trivial case efficiently. 9732 if (Num == 1) 9733 return ReplaceAllUsesOfValueWith(*From, *To); 9734 9735 transferDbgValues(*From, *To); 9736 9737 // Read up all the uses and make records of them. This helps 9738 // processing new uses that are introduced during the 9739 // replacement process. 9740 SmallVector<UseMemo, 4> Uses; 9741 for (unsigned i = 0; i != Num; ++i) { 9742 unsigned FromResNo = From[i].getResNo(); 9743 SDNode *FromNode = From[i].getNode(); 9744 for (SDNode::use_iterator UI = FromNode->use_begin(), 9745 E = FromNode->use_end(); UI != E; ++UI) { 9746 SDUse &Use = UI.getUse(); 9747 if (Use.getResNo() == FromResNo) { 9748 UseMemo Memo = { *UI, i, &Use }; 9749 Uses.push_back(Memo); 9750 } 9751 } 9752 } 9753 9754 // Sort the uses, so that all the uses from a given User are together. 9755 llvm::sort(Uses); 9756 9757 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 9758 UseIndex != UseIndexEnd; ) { 9759 // We know that this user uses some value of From. If it is the right 9760 // value, update it. 9761 SDNode *User = Uses[UseIndex].User; 9762 9763 // This node is about to morph, remove its old self from the CSE maps. 9764 RemoveNodeFromCSEMaps(User); 9765 9766 // The Uses array is sorted, so all the uses for a given User 9767 // are next to each other in the list. 9768 // To help reduce the number of CSE recomputations, process all 9769 // the uses of this user that we can find this way. 9770 do { 9771 unsigned i = Uses[UseIndex].Index; 9772 SDUse &Use = *Uses[UseIndex].Use; 9773 ++UseIndex; 9774 9775 Use.set(To[i]); 9776 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 9777 9778 // Now that we have modified User, add it back to the CSE maps. If it 9779 // already exists there, recursively merge the results together. 9780 AddModifiedNodeToCSEMaps(User); 9781 } 9782 } 9783 9784 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 9785 /// based on their topological order. It returns the maximum id and a vector 9786 /// of the SDNodes* in assigned order by reference. 9787 unsigned SelectionDAG::AssignTopologicalOrder() { 9788 unsigned DAGSize = 0; 9789 9790 // SortedPos tracks the progress of the algorithm. Nodes before it are 9791 // sorted, nodes after it are unsorted. When the algorithm completes 9792 // it is at the end of the list. 9793 allnodes_iterator SortedPos = allnodes_begin(); 9794 9795 // Visit all the nodes. Move nodes with no operands to the front of 9796 // the list immediately. Annotate nodes that do have operands with their 9797 // operand count. Before we do this, the Node Id fields of the nodes 9798 // may contain arbitrary values. After, the Node Id fields for nodes 9799 // before SortedPos will contain the topological sort index, and the 9800 // Node Id fields for nodes At SortedPos and after will contain the 9801 // count of outstanding operands. 9802 for (SDNode &N : llvm::make_early_inc_range(allnodes())) { 9803 checkForCycles(&N, this); 9804 unsigned Degree = N.getNumOperands(); 9805 if (Degree == 0) { 9806 // A node with no uses, add it to the result array immediately. 9807 N.setNodeId(DAGSize++); 9808 allnodes_iterator Q(&N); 9809 if (Q != SortedPos) 9810 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 9811 assert(SortedPos != AllNodes.end() && "Overran node list"); 9812 ++SortedPos; 9813 } else { 9814 // Temporarily use the Node Id as scratch space for the degree count. 9815 N.setNodeId(Degree); 9816 } 9817 } 9818 9819 // Visit all the nodes. As we iterate, move nodes into sorted order, 9820 // such that by the time the end is reached all nodes will be sorted. 9821 for (SDNode &Node : allnodes()) { 9822 SDNode *N = &Node; 9823 checkForCycles(N, this); 9824 // N is in sorted position, so all its uses have one less operand 9825 // that needs to be sorted. 9826 for (SDNode *P : N->uses()) { 9827 unsigned Degree = P->getNodeId(); 9828 assert(Degree != 0 && "Invalid node degree"); 9829 --Degree; 9830 if (Degree == 0) { 9831 // All of P's operands are sorted, so P may sorted now. 9832 P->setNodeId(DAGSize++); 9833 if (P->getIterator() != SortedPos) 9834 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9835 assert(SortedPos != AllNodes.end() && "Overran node list"); 9836 ++SortedPos; 9837 } else { 9838 // Update P's outstanding operand count. 9839 P->setNodeId(Degree); 9840 } 9841 } 9842 if (Node.getIterator() == SortedPos) { 9843 #ifndef NDEBUG 9844 allnodes_iterator I(N); 9845 SDNode *S = &*++I; 9846 dbgs() << "Overran sorted position:\n"; 9847 S->dumprFull(this); dbgs() << "\n"; 9848 dbgs() << "Checking if this is due to cycles\n"; 9849 checkForCycles(this, true); 9850 #endif 9851 llvm_unreachable(nullptr); 9852 } 9853 } 9854 9855 assert(SortedPos == AllNodes.end() && 9856 "Topological sort incomplete!"); 9857 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9858 "First node in topological sort is not the entry token!"); 9859 assert(AllNodes.front().getNodeId() == 0 && 9860 "First node in topological sort has non-zero id!"); 9861 assert(AllNodes.front().getNumOperands() == 0 && 9862 "First node in topological sort has operands!"); 9863 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9864 "Last node in topologic sort has unexpected id!"); 9865 assert(AllNodes.back().use_empty() && 9866 "Last node in topologic sort has users!"); 9867 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9868 return DAGSize; 9869 } 9870 9871 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9872 /// value is produced by SD. 9873 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 9874 for (SDNode *SD : DB->getSDNodes()) { 9875 if (!SD) 9876 continue; 9877 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9878 SD->setHasDebugValue(true); 9879 } 9880 DbgInfo->add(DB, isParameter); 9881 } 9882 9883 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 9884 9885 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9886 SDValue NewMemOpChain) { 9887 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9888 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9889 // The new memory operation must have the same position as the old load in 9890 // terms of memory dependency. Create a TokenFactor for the old load and new 9891 // memory operation and update uses of the old load's output chain to use that 9892 // TokenFactor. 9893 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9894 return NewMemOpChain; 9895 9896 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9897 OldChain, NewMemOpChain); 9898 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9899 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9900 return TokenFactor; 9901 } 9902 9903 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9904 SDValue NewMemOp) { 9905 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9906 SDValue OldChain = SDValue(OldLoad, 1); 9907 SDValue NewMemOpChain = NewMemOp.getValue(1); 9908 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9909 } 9910 9911 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9912 Function **OutFunction) { 9913 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9914 9915 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9916 auto *Module = MF->getFunction().getParent(); 9917 auto *Function = Module->getFunction(Symbol); 9918 9919 if (OutFunction != nullptr) 9920 *OutFunction = Function; 9921 9922 if (Function != nullptr) { 9923 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9924 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9925 } 9926 9927 std::string ErrorStr; 9928 raw_string_ostream ErrorFormatter(ErrorStr); 9929 ErrorFormatter << "Undefined external symbol "; 9930 ErrorFormatter << '"' << Symbol << '"'; 9931 report_fatal_error(Twine(ErrorFormatter.str())); 9932 } 9933 9934 //===----------------------------------------------------------------------===// 9935 // SDNode Class 9936 //===----------------------------------------------------------------------===// 9937 9938 bool llvm::isNullConstant(SDValue V) { 9939 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9940 return Const != nullptr && Const->isZero(); 9941 } 9942 9943 bool llvm::isNullFPConstant(SDValue V) { 9944 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9945 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9946 } 9947 9948 bool llvm::isAllOnesConstant(SDValue V) { 9949 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9950 return Const != nullptr && Const->isAllOnes(); 9951 } 9952 9953 bool llvm::isOneConstant(SDValue V) { 9954 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9955 return Const != nullptr && Const->isOne(); 9956 } 9957 9958 SDValue llvm::peekThroughBitcasts(SDValue V) { 9959 while (V.getOpcode() == ISD::BITCAST) 9960 V = V.getOperand(0); 9961 return V; 9962 } 9963 9964 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9965 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9966 V = V.getOperand(0); 9967 return V; 9968 } 9969 9970 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9971 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9972 V = V.getOperand(0); 9973 return V; 9974 } 9975 9976 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9977 if (V.getOpcode() != ISD::XOR) 9978 return false; 9979 V = peekThroughBitcasts(V.getOperand(1)); 9980 unsigned NumBits = V.getScalarValueSizeInBits(); 9981 ConstantSDNode *C = 9982 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 9983 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 9984 } 9985 9986 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 9987 bool AllowTruncation) { 9988 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9989 return CN; 9990 9991 // SplatVectors can truncate their operands. Ignore that case here unless 9992 // AllowTruncation is set. 9993 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 9994 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 9995 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9996 EVT CVT = CN->getValueType(0); 9997 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 9998 if (AllowTruncation || CVT == VecEltVT) 9999 return CN; 10000 } 10001 } 10002 10003 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10004 BitVector UndefElements; 10005 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 10006 10007 // BuildVectors can truncate their operands. Ignore that case here unless 10008 // AllowTruncation is set. 10009 if (CN && (UndefElements.none() || AllowUndefs)) { 10010 EVT CVT = CN->getValueType(0); 10011 EVT NSVT = N.getValueType().getScalarType(); 10012 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10013 if (AllowTruncation || (CVT == NSVT)) 10014 return CN; 10015 } 10016 } 10017 10018 return nullptr; 10019 } 10020 10021 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 10022 bool AllowUndefs, 10023 bool AllowTruncation) { 10024 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 10025 return CN; 10026 10027 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10028 BitVector UndefElements; 10029 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 10030 10031 // BuildVectors can truncate their operands. Ignore that case here unless 10032 // AllowTruncation is set. 10033 if (CN && (UndefElements.none() || AllowUndefs)) { 10034 EVT CVT = CN->getValueType(0); 10035 EVT NSVT = N.getValueType().getScalarType(); 10036 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 10037 if (AllowTruncation || (CVT == NSVT)) 10038 return CN; 10039 } 10040 } 10041 10042 return nullptr; 10043 } 10044 10045 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 10046 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10047 return CN; 10048 10049 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10050 BitVector UndefElements; 10051 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 10052 if (CN && (UndefElements.none() || AllowUndefs)) 10053 return CN; 10054 } 10055 10056 if (N.getOpcode() == ISD::SPLAT_VECTOR) 10057 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 10058 return CN; 10059 10060 return nullptr; 10061 } 10062 10063 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 10064 const APInt &DemandedElts, 10065 bool AllowUndefs) { 10066 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 10067 return CN; 10068 10069 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 10070 BitVector UndefElements; 10071 ConstantFPSDNode *CN = 10072 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 10073 if (CN && (UndefElements.none() || AllowUndefs)) 10074 return CN; 10075 } 10076 10077 return nullptr; 10078 } 10079 10080 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 10081 // TODO: may want to use peekThroughBitcast() here. 10082 ConstantSDNode *C = 10083 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true); 10084 return C && C->isZero(); 10085 } 10086 10087 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 10088 // TODO: may want to use peekThroughBitcast() here. 10089 unsigned BitWidth = N.getScalarValueSizeInBits(); 10090 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10091 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 10092 } 10093 10094 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 10095 N = peekThroughBitcasts(N); 10096 unsigned BitWidth = N.getScalarValueSizeInBits(); 10097 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 10098 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth; 10099 } 10100 10101 HandleSDNode::~HandleSDNode() { 10102 DropOperands(); 10103 } 10104 10105 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 10106 const DebugLoc &DL, 10107 const GlobalValue *GA, EVT VT, 10108 int64_t o, unsigned TF) 10109 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 10110 TheGlobal = GA; 10111 } 10112 10113 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 10114 EVT VT, unsigned SrcAS, 10115 unsigned DestAS) 10116 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 10117 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 10118 10119 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 10120 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 10121 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 10122 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 10123 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 10124 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 10125 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 10126 10127 // We check here that the size of the memory operand fits within the size of 10128 // the MMO. This is because the MMO might indicate only a possible address 10129 // range instead of specifying the affected memory addresses precisely. 10130 // TODO: Make MachineMemOperands aware of scalable vectors. 10131 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 10132 "Size mismatch!"); 10133 } 10134 10135 /// Profile - Gather unique data for the node. 10136 /// 10137 void SDNode::Profile(FoldingSetNodeID &ID) const { 10138 AddNodeIDNode(ID, this); 10139 } 10140 10141 namespace { 10142 10143 struct EVTArray { 10144 std::vector<EVT> VTs; 10145 10146 EVTArray() { 10147 VTs.reserve(MVT::VALUETYPE_SIZE); 10148 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i) 10149 VTs.push_back(MVT((MVT::SimpleValueType)i)); 10150 } 10151 }; 10152 10153 } // end anonymous namespace 10154 10155 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 10156 static ManagedStatic<EVTArray> SimpleVTArray; 10157 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 10158 10159 /// getValueTypeList - Return a pointer to the specified value type. 10160 /// 10161 const EVT *SDNode::getValueTypeList(EVT VT) { 10162 if (VT.isExtended()) { 10163 sys::SmartScopedLock<true> Lock(*VTMutex); 10164 return &(*EVTs->insert(VT).first); 10165 } 10166 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!"); 10167 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 10168 } 10169 10170 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 10171 /// indicated value. This method ignores uses of other values defined by this 10172 /// operation. 10173 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 10174 assert(Value < getNumValues() && "Bad value!"); 10175 10176 // TODO: Only iterate over uses of a given value of the node 10177 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 10178 if (UI.getUse().getResNo() == Value) { 10179 if (NUses == 0) 10180 return false; 10181 --NUses; 10182 } 10183 } 10184 10185 // Found exactly the right number of uses? 10186 return NUses == 0; 10187 } 10188 10189 /// hasAnyUseOfValue - Return true if there are any use of the indicated 10190 /// value. This method ignores uses of other values defined by this operation. 10191 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 10192 assert(Value < getNumValues() && "Bad value!"); 10193 10194 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 10195 if (UI.getUse().getResNo() == Value) 10196 return true; 10197 10198 return false; 10199 } 10200 10201 /// isOnlyUserOf - Return true if this node is the only use of N. 10202 bool SDNode::isOnlyUserOf(const SDNode *N) const { 10203 bool Seen = false; 10204 for (const SDNode *User : N->uses()) { 10205 if (User == this) 10206 Seen = true; 10207 else 10208 return false; 10209 } 10210 10211 return Seen; 10212 } 10213 10214 /// Return true if the only users of N are contained in Nodes. 10215 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 10216 bool Seen = false; 10217 for (const SDNode *User : N->uses()) { 10218 if (llvm::is_contained(Nodes, User)) 10219 Seen = true; 10220 else 10221 return false; 10222 } 10223 10224 return Seen; 10225 } 10226 10227 /// isOperand - Return true if this node is an operand of N. 10228 bool SDValue::isOperandOf(const SDNode *N) const { 10229 return is_contained(N->op_values(), *this); 10230 } 10231 10232 bool SDNode::isOperandOf(const SDNode *N) const { 10233 return any_of(N->op_values(), 10234 [this](SDValue Op) { return this == Op.getNode(); }); 10235 } 10236 10237 /// reachesChainWithoutSideEffects - Return true if this operand (which must 10238 /// be a chain) reaches the specified operand without crossing any 10239 /// side-effecting instructions on any chain path. In practice, this looks 10240 /// through token factors and non-volatile loads. In order to remain efficient, 10241 /// this only looks a couple of nodes in, it does not do an exhaustive search. 10242 /// 10243 /// Note that we only need to examine chains when we're searching for 10244 /// side-effects; SelectionDAG requires that all side-effects are represented 10245 /// by chains, even if another operand would force a specific ordering. This 10246 /// constraint is necessary to allow transformations like splitting loads. 10247 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 10248 unsigned Depth) const { 10249 if (*this == Dest) return true; 10250 10251 // Don't search too deeply, we just want to be able to see through 10252 // TokenFactor's etc. 10253 if (Depth == 0) return false; 10254 10255 // If this is a token factor, all inputs to the TF happen in parallel. 10256 if (getOpcode() == ISD::TokenFactor) { 10257 // First, try a shallow search. 10258 if (is_contained((*this)->ops(), Dest)) { 10259 // We found the chain we want as an operand of this TokenFactor. 10260 // Essentially, we reach the chain without side-effects if we could 10261 // serialize the TokenFactor into a simple chain of operations with 10262 // Dest as the last operation. This is automatically true if the 10263 // chain has one use: there are no other ordering constraints. 10264 // If the chain has more than one use, we give up: some other 10265 // use of Dest might force a side-effect between Dest and the current 10266 // node. 10267 if (Dest.hasOneUse()) 10268 return true; 10269 } 10270 // Next, try a deep search: check whether every operand of the TokenFactor 10271 // reaches Dest. 10272 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 10273 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 10274 }); 10275 } 10276 10277 // Loads don't have side effects, look through them. 10278 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 10279 if (Ld->isUnordered()) 10280 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 10281 } 10282 return false; 10283 } 10284 10285 bool SDNode::hasPredecessor(const SDNode *N) const { 10286 SmallPtrSet<const SDNode *, 32> Visited; 10287 SmallVector<const SDNode *, 16> Worklist; 10288 Worklist.push_back(this); 10289 return hasPredecessorHelper(N, Visited, Worklist); 10290 } 10291 10292 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 10293 this->Flags.intersectWith(Flags); 10294 } 10295 10296 SDValue 10297 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 10298 ArrayRef<ISD::NodeType> CandidateBinOps, 10299 bool AllowPartials) { 10300 // The pattern must end in an extract from index 0. 10301 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10302 !isNullConstant(Extract->getOperand(1))) 10303 return SDValue(); 10304 10305 // Match against one of the candidate binary ops. 10306 SDValue Op = Extract->getOperand(0); 10307 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 10308 return Op.getOpcode() == unsigned(BinOp); 10309 })) 10310 return SDValue(); 10311 10312 // Floating-point reductions may require relaxed constraints on the final step 10313 // of the reduction because they may reorder intermediate operations. 10314 unsigned CandidateBinOp = Op.getOpcode(); 10315 if (Op.getValueType().isFloatingPoint()) { 10316 SDNodeFlags Flags = Op->getFlags(); 10317 switch (CandidateBinOp) { 10318 case ISD::FADD: 10319 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 10320 return SDValue(); 10321 break; 10322 default: 10323 llvm_unreachable("Unhandled FP opcode for binop reduction"); 10324 } 10325 } 10326 10327 // Matching failed - attempt to see if we did enough stages that a partial 10328 // reduction from a subvector is possible. 10329 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 10330 if (!AllowPartials || !Op) 10331 return SDValue(); 10332 EVT OpVT = Op.getValueType(); 10333 EVT OpSVT = OpVT.getScalarType(); 10334 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 10335 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 10336 return SDValue(); 10337 BinOp = (ISD::NodeType)CandidateBinOp; 10338 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 10339 getVectorIdxConstant(0, SDLoc(Op))); 10340 }; 10341 10342 // At each stage, we're looking for something that looks like: 10343 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 10344 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 10345 // i32 undef, i32 undef, i32 undef, i32 undef> 10346 // %a = binop <8 x i32> %op, %s 10347 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 10348 // we expect something like: 10349 // <4,5,6,7,u,u,u,u> 10350 // <2,3,u,u,u,u,u,u> 10351 // <1,u,u,u,u,u,u,u> 10352 // While a partial reduction match would be: 10353 // <2,3,u,u,u,u,u,u> 10354 // <1,u,u,u,u,u,u,u> 10355 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 10356 SDValue PrevOp; 10357 for (unsigned i = 0; i < Stages; ++i) { 10358 unsigned MaskEnd = (1 << i); 10359 10360 if (Op.getOpcode() != CandidateBinOp) 10361 return PartialReduction(PrevOp, MaskEnd); 10362 10363 SDValue Op0 = Op.getOperand(0); 10364 SDValue Op1 = Op.getOperand(1); 10365 10366 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 10367 if (Shuffle) { 10368 Op = Op1; 10369 } else { 10370 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 10371 Op = Op0; 10372 } 10373 10374 // The first operand of the shuffle should be the same as the other operand 10375 // of the binop. 10376 if (!Shuffle || Shuffle->getOperand(0) != Op) 10377 return PartialReduction(PrevOp, MaskEnd); 10378 10379 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 10380 for (int Index = 0; Index < (int)MaskEnd; ++Index) 10381 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 10382 return PartialReduction(PrevOp, MaskEnd); 10383 10384 PrevOp = Op; 10385 } 10386 10387 // Handle subvector reductions, which tend to appear after the shuffle 10388 // reduction stages. 10389 while (Op.getOpcode() == CandidateBinOp) { 10390 unsigned NumElts = Op.getValueType().getVectorNumElements(); 10391 SDValue Op0 = Op.getOperand(0); 10392 SDValue Op1 = Op.getOperand(1); 10393 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10394 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 10395 Op0.getOperand(0) != Op1.getOperand(0)) 10396 break; 10397 SDValue Src = Op0.getOperand(0); 10398 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 10399 if (NumSrcElts != (2 * NumElts)) 10400 break; 10401 if (!(Op0.getConstantOperandAPInt(1) == 0 && 10402 Op1.getConstantOperandAPInt(1) == NumElts) && 10403 !(Op1.getConstantOperandAPInt(1) == 0 && 10404 Op0.getConstantOperandAPInt(1) == NumElts)) 10405 break; 10406 Op = Src; 10407 } 10408 10409 BinOp = (ISD::NodeType)CandidateBinOp; 10410 return Op; 10411 } 10412 10413 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 10414 assert(N->getNumValues() == 1 && 10415 "Can't unroll a vector with multiple results!"); 10416 10417 EVT VT = N->getValueType(0); 10418 unsigned NE = VT.getVectorNumElements(); 10419 EVT EltVT = VT.getVectorElementType(); 10420 SDLoc dl(N); 10421 10422 SmallVector<SDValue, 8> Scalars; 10423 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 10424 10425 // If ResNE is 0, fully unroll the vector op. 10426 if (ResNE == 0) 10427 ResNE = NE; 10428 else if (NE > ResNE) 10429 NE = ResNE; 10430 10431 unsigned i; 10432 for (i= 0; i != NE; ++i) { 10433 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 10434 SDValue Operand = N->getOperand(j); 10435 EVT OperandVT = Operand.getValueType(); 10436 if (OperandVT.isVector()) { 10437 // A vector operand; extract a single element. 10438 EVT OperandEltVT = OperandVT.getVectorElementType(); 10439 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 10440 Operand, getVectorIdxConstant(i, dl)); 10441 } else { 10442 // A scalar operand; just use it as is. 10443 Operands[j] = Operand; 10444 } 10445 } 10446 10447 switch (N->getOpcode()) { 10448 default: { 10449 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 10450 N->getFlags())); 10451 break; 10452 } 10453 case ISD::VSELECT: 10454 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 10455 break; 10456 case ISD::SHL: 10457 case ISD::SRA: 10458 case ISD::SRL: 10459 case ISD::ROTL: 10460 case ISD::ROTR: 10461 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 10462 getShiftAmountOperand(Operands[0].getValueType(), 10463 Operands[1]))); 10464 break; 10465 case ISD::SIGN_EXTEND_INREG: { 10466 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 10467 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 10468 Operands[0], 10469 getValueType(ExtVT))); 10470 } 10471 } 10472 } 10473 10474 for (; i < ResNE; ++i) 10475 Scalars.push_back(getUNDEF(EltVT)); 10476 10477 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 10478 return getBuildVector(VecVT, dl, Scalars); 10479 } 10480 10481 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 10482 SDNode *N, unsigned ResNE) { 10483 unsigned Opcode = N->getOpcode(); 10484 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 10485 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 10486 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 10487 "Expected an overflow opcode"); 10488 10489 EVT ResVT = N->getValueType(0); 10490 EVT OvVT = N->getValueType(1); 10491 EVT ResEltVT = ResVT.getVectorElementType(); 10492 EVT OvEltVT = OvVT.getVectorElementType(); 10493 SDLoc dl(N); 10494 10495 // If ResNE is 0, fully unroll the vector op. 10496 unsigned NE = ResVT.getVectorNumElements(); 10497 if (ResNE == 0) 10498 ResNE = NE; 10499 else if (NE > ResNE) 10500 NE = ResNE; 10501 10502 SmallVector<SDValue, 8> LHSScalars; 10503 SmallVector<SDValue, 8> RHSScalars; 10504 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 10505 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 10506 10507 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 10508 SDVTList VTs = getVTList(ResEltVT, SVT); 10509 SmallVector<SDValue, 8> ResScalars; 10510 SmallVector<SDValue, 8> OvScalars; 10511 for (unsigned i = 0; i < NE; ++i) { 10512 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 10513 SDValue Ov = 10514 getSelect(dl, OvEltVT, Res.getValue(1), 10515 getBoolConstant(true, dl, OvEltVT, ResVT), 10516 getConstant(0, dl, OvEltVT)); 10517 10518 ResScalars.push_back(Res); 10519 OvScalars.push_back(Ov); 10520 } 10521 10522 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 10523 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 10524 10525 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 10526 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 10527 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 10528 getBuildVector(NewOvVT, dl, OvScalars)); 10529 } 10530 10531 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 10532 LoadSDNode *Base, 10533 unsigned Bytes, 10534 int Dist) const { 10535 if (LD->isVolatile() || Base->isVolatile()) 10536 return false; 10537 // TODO: probably too restrictive for atomics, revisit 10538 if (!LD->isSimple()) 10539 return false; 10540 if (LD->isIndexed() || Base->isIndexed()) 10541 return false; 10542 if (LD->getChain() != Base->getChain()) 10543 return false; 10544 EVT VT = LD->getValueType(0); 10545 if (VT.getSizeInBits() / 8 != Bytes) 10546 return false; 10547 10548 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 10549 auto LocDecomp = BaseIndexOffset::match(LD, *this); 10550 10551 int64_t Offset = 0; 10552 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 10553 return (Dist * Bytes == Offset); 10554 return false; 10555 } 10556 10557 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 10558 /// if it cannot be inferred. 10559 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 10560 // If this is a GlobalAddress + cst, return the alignment. 10561 const GlobalValue *GV = nullptr; 10562 int64_t GVOffset = 0; 10563 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 10564 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 10565 KnownBits Known(PtrWidth); 10566 llvm::computeKnownBits(GV, Known, getDataLayout()); 10567 unsigned AlignBits = Known.countMinTrailingZeros(); 10568 if (AlignBits) 10569 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 10570 } 10571 10572 // If this is a direct reference to a stack slot, use information about the 10573 // stack slot's alignment. 10574 int FrameIdx = INT_MIN; 10575 int64_t FrameOffset = 0; 10576 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 10577 FrameIdx = FI->getIndex(); 10578 } else if (isBaseWithConstantOffset(Ptr) && 10579 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 10580 // Handle FI+Cst 10581 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 10582 FrameOffset = Ptr.getConstantOperandVal(1); 10583 } 10584 10585 if (FrameIdx != INT_MIN) { 10586 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 10587 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 10588 } 10589 10590 return None; 10591 } 10592 10593 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 10594 /// which is split (or expanded) into two not necessarily identical pieces. 10595 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 10596 // Currently all types are split in half. 10597 EVT LoVT, HiVT; 10598 if (!VT.isVector()) 10599 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 10600 else 10601 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 10602 10603 return std::make_pair(LoVT, HiVT); 10604 } 10605 10606 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 10607 /// type, dependent on an enveloping VT that has been split into two identical 10608 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 10609 std::pair<EVT, EVT> 10610 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 10611 bool *HiIsEmpty) const { 10612 EVT EltTp = VT.getVectorElementType(); 10613 // Examples: 10614 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 10615 // custom VL=9 with enveloping VL=8/8 yields 8/1 10616 // custom VL=10 with enveloping VL=8/8 yields 8/2 10617 // etc. 10618 ElementCount VTNumElts = VT.getVectorElementCount(); 10619 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 10620 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 10621 "Mixing fixed width and scalable vectors when enveloping a type"); 10622 EVT LoVT, HiVT; 10623 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 10624 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 10625 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 10626 *HiIsEmpty = false; 10627 } else { 10628 // Flag that hi type has zero storage size, but return split envelop type 10629 // (this would be easier if vector types with zero elements were allowed). 10630 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 10631 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts); 10632 *HiIsEmpty = true; 10633 } 10634 return std::make_pair(LoVT, HiVT); 10635 } 10636 10637 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 10638 /// low/high part. 10639 std::pair<SDValue, SDValue> 10640 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 10641 const EVT &HiVT) { 10642 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 10643 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 10644 "Splitting vector with an invalid mixture of fixed and scalable " 10645 "vector types"); 10646 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 10647 N.getValueType().getVectorMinNumElements() && 10648 "More vector elements requested than available!"); 10649 SDValue Lo, Hi; 10650 Lo = 10651 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 10652 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 10653 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 10654 // IDX with the runtime scaling factor of the result vector type. For 10655 // fixed-width result vectors, that runtime scaling factor is 1. 10656 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 10657 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 10658 return std::make_pair(Lo, Hi); 10659 } 10660 10661 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT, 10662 const SDLoc &DL) { 10663 // Split the vector length parameter. 10664 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts). 10665 EVT VT = N.getValueType(); 10666 assert(VecVT.getVectorElementCount().isKnownEven() && 10667 "Expecting the mask to be an evenly-sized vector"); 10668 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2; 10669 SDValue HalfNumElts = 10670 VecVT.isFixedLengthVector() 10671 ? getConstant(HalfMinNumElts, DL, VT) 10672 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts)); 10673 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts); 10674 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts); 10675 return std::make_pair(Lo, Hi); 10676 } 10677 10678 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 10679 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 10680 EVT VT = N.getValueType(); 10681 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 10682 NextPowerOf2(VT.getVectorNumElements())); 10683 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 10684 getVectorIdxConstant(0, DL)); 10685 } 10686 10687 void SelectionDAG::ExtractVectorElements(SDValue Op, 10688 SmallVectorImpl<SDValue> &Args, 10689 unsigned Start, unsigned Count, 10690 EVT EltVT) { 10691 EVT VT = Op.getValueType(); 10692 if (Count == 0) 10693 Count = VT.getVectorNumElements(); 10694 if (EltVT == EVT()) 10695 EltVT = VT.getVectorElementType(); 10696 SDLoc SL(Op); 10697 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 10698 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 10699 getVectorIdxConstant(i, SL))); 10700 } 10701 } 10702 10703 // getAddressSpace - Return the address space this GlobalAddress belongs to. 10704 unsigned GlobalAddressSDNode::getAddressSpace() const { 10705 return getGlobal()->getType()->getAddressSpace(); 10706 } 10707 10708 Type *ConstantPoolSDNode::getType() const { 10709 if (isMachineConstantPoolEntry()) 10710 return Val.MachineCPVal->getType(); 10711 return Val.ConstVal->getType(); 10712 } 10713 10714 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 10715 unsigned &SplatBitSize, 10716 bool &HasAnyUndefs, 10717 unsigned MinSplatBits, 10718 bool IsBigEndian) const { 10719 EVT VT = getValueType(0); 10720 assert(VT.isVector() && "Expected a vector type"); 10721 unsigned VecWidth = VT.getSizeInBits(); 10722 if (MinSplatBits > VecWidth) 10723 return false; 10724 10725 // FIXME: The widths are based on this node's type, but build vectors can 10726 // truncate their operands. 10727 SplatValue = APInt(VecWidth, 0); 10728 SplatUndef = APInt(VecWidth, 0); 10729 10730 // Get the bits. Bits with undefined values (when the corresponding element 10731 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 10732 // in SplatValue. If any of the values are not constant, give up and return 10733 // false. 10734 unsigned int NumOps = getNumOperands(); 10735 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 10736 unsigned EltWidth = VT.getScalarSizeInBits(); 10737 10738 for (unsigned j = 0; j < NumOps; ++j) { 10739 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 10740 SDValue OpVal = getOperand(i); 10741 unsigned BitPos = j * EltWidth; 10742 10743 if (OpVal.isUndef()) 10744 SplatUndef.setBits(BitPos, BitPos + EltWidth); 10745 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 10746 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 10747 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 10748 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 10749 else 10750 return false; 10751 } 10752 10753 // The build_vector is all constants or undefs. Find the smallest element 10754 // size that splats the vector. 10755 HasAnyUndefs = (SplatUndef != 0); 10756 10757 // FIXME: This does not work for vectors with elements less than 8 bits. 10758 while (VecWidth > 8) { 10759 unsigned HalfSize = VecWidth / 2; 10760 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize); 10761 APInt LowValue = SplatValue.extractBits(HalfSize, 0); 10762 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize); 10763 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0); 10764 10765 // If the two halves do not match (ignoring undef bits), stop here. 10766 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 10767 MinSplatBits > HalfSize) 10768 break; 10769 10770 SplatValue = HighValue | LowValue; 10771 SplatUndef = HighUndef & LowUndef; 10772 10773 VecWidth = HalfSize; 10774 } 10775 10776 SplatBitSize = VecWidth; 10777 return true; 10778 } 10779 10780 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 10781 BitVector *UndefElements) const { 10782 unsigned NumOps = getNumOperands(); 10783 if (UndefElements) { 10784 UndefElements->clear(); 10785 UndefElements->resize(NumOps); 10786 } 10787 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10788 if (!DemandedElts) 10789 return SDValue(); 10790 SDValue Splatted; 10791 for (unsigned i = 0; i != NumOps; ++i) { 10792 if (!DemandedElts[i]) 10793 continue; 10794 SDValue Op = getOperand(i); 10795 if (Op.isUndef()) { 10796 if (UndefElements) 10797 (*UndefElements)[i] = true; 10798 } else if (!Splatted) { 10799 Splatted = Op; 10800 } else if (Splatted != Op) { 10801 return SDValue(); 10802 } 10803 } 10804 10805 if (!Splatted) { 10806 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 10807 assert(getOperand(FirstDemandedIdx).isUndef() && 10808 "Can only have a splat without a constant for all undefs."); 10809 return getOperand(FirstDemandedIdx); 10810 } 10811 10812 return Splatted; 10813 } 10814 10815 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 10816 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10817 return getSplatValue(DemandedElts, UndefElements); 10818 } 10819 10820 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 10821 SmallVectorImpl<SDValue> &Sequence, 10822 BitVector *UndefElements) const { 10823 unsigned NumOps = getNumOperands(); 10824 Sequence.clear(); 10825 if (UndefElements) { 10826 UndefElements->clear(); 10827 UndefElements->resize(NumOps); 10828 } 10829 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10830 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10831 return false; 10832 10833 // Set the undefs even if we don't find a sequence (like getSplatValue). 10834 if (UndefElements) 10835 for (unsigned I = 0; I != NumOps; ++I) 10836 if (DemandedElts[I] && getOperand(I).isUndef()) 10837 (*UndefElements)[I] = true; 10838 10839 // Iteratively widen the sequence length looking for repetitions. 10840 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10841 Sequence.append(SeqLen, SDValue()); 10842 for (unsigned I = 0; I != NumOps; ++I) { 10843 if (!DemandedElts[I]) 10844 continue; 10845 SDValue &SeqOp = Sequence[I % SeqLen]; 10846 SDValue Op = getOperand(I); 10847 if (Op.isUndef()) { 10848 if (!SeqOp) 10849 SeqOp = Op; 10850 continue; 10851 } 10852 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10853 Sequence.clear(); 10854 break; 10855 } 10856 SeqOp = Op; 10857 } 10858 if (!Sequence.empty()) 10859 return true; 10860 } 10861 10862 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10863 return false; 10864 } 10865 10866 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10867 BitVector *UndefElements) const { 10868 APInt DemandedElts = APInt::getAllOnes(getNumOperands()); 10869 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10870 } 10871 10872 ConstantSDNode * 10873 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10874 BitVector *UndefElements) const { 10875 return dyn_cast_or_null<ConstantSDNode>( 10876 getSplatValue(DemandedElts, UndefElements)); 10877 } 10878 10879 ConstantSDNode * 10880 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10881 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10882 } 10883 10884 ConstantFPSDNode * 10885 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10886 BitVector *UndefElements) const { 10887 return dyn_cast_or_null<ConstantFPSDNode>( 10888 getSplatValue(DemandedElts, UndefElements)); 10889 } 10890 10891 ConstantFPSDNode * 10892 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10893 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10894 } 10895 10896 int32_t 10897 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10898 uint32_t BitWidth) const { 10899 if (ConstantFPSDNode *CN = 10900 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10901 bool IsExact; 10902 APSInt IntVal(BitWidth); 10903 const APFloat &APF = CN->getValueAPF(); 10904 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10905 APFloat::opOK || 10906 !IsExact) 10907 return -1; 10908 10909 return IntVal.exactLogBase2(); 10910 } 10911 return -1; 10912 } 10913 10914 bool BuildVectorSDNode::getConstantRawBits( 10915 bool IsLittleEndian, unsigned DstEltSizeInBits, 10916 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const { 10917 // Early-out if this contains anything but Undef/Constant/ConstantFP. 10918 if (!isConstant()) 10919 return false; 10920 10921 unsigned NumSrcOps = getNumOperands(); 10922 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits(); 10923 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 10924 "Invalid bitcast scale"); 10925 10926 // Extract raw src bits. 10927 SmallVector<APInt> SrcBitElements(NumSrcOps, 10928 APInt::getNullValue(SrcEltSizeInBits)); 10929 BitVector SrcUndeElements(NumSrcOps, false); 10930 10931 for (unsigned I = 0; I != NumSrcOps; ++I) { 10932 SDValue Op = getOperand(I); 10933 if (Op.isUndef()) { 10934 SrcUndeElements.set(I); 10935 continue; 10936 } 10937 auto *CInt = dyn_cast<ConstantSDNode>(Op); 10938 auto *CFP = dyn_cast<ConstantFPSDNode>(Op); 10939 assert((CInt || CFP) && "Unknown constant"); 10940 SrcBitElements[I] = 10941 CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits) 10942 : CFP->getValueAPF().bitcastToAPInt(); 10943 } 10944 10945 // Recast to dst width. 10946 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements, 10947 SrcBitElements, UndefElements, SrcUndeElements); 10948 return true; 10949 } 10950 10951 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian, 10952 unsigned DstEltSizeInBits, 10953 SmallVectorImpl<APInt> &DstBitElements, 10954 ArrayRef<APInt> SrcBitElements, 10955 BitVector &DstUndefElements, 10956 const BitVector &SrcUndefElements) { 10957 unsigned NumSrcOps = SrcBitElements.size(); 10958 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth(); 10959 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 && 10960 "Invalid bitcast scale"); 10961 assert(NumSrcOps == SrcUndefElements.size() && 10962 "Vector size mismatch"); 10963 10964 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits; 10965 DstUndefElements.clear(); 10966 DstUndefElements.resize(NumDstOps, false); 10967 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits)); 10968 10969 // Concatenate src elements constant bits together into dst element. 10970 if (SrcEltSizeInBits <= DstEltSizeInBits) { 10971 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits; 10972 for (unsigned I = 0; I != NumDstOps; ++I) { 10973 DstUndefElements.set(I); 10974 APInt &DstBits = DstBitElements[I]; 10975 for (unsigned J = 0; J != Scale; ++J) { 10976 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 10977 if (SrcUndefElements[Idx]) 10978 continue; 10979 DstUndefElements.reset(I); 10980 const APInt &SrcBits = SrcBitElements[Idx]; 10981 assert(SrcBits.getBitWidth() == SrcEltSizeInBits && 10982 "Illegal constant bitwidths"); 10983 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits); 10984 } 10985 } 10986 return; 10987 } 10988 10989 // Split src element constant bits into dst elements. 10990 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits; 10991 for (unsigned I = 0; I != NumSrcOps; ++I) { 10992 if (SrcUndefElements[I]) { 10993 DstUndefElements.set(I * Scale, (I + 1) * Scale); 10994 continue; 10995 } 10996 const APInt &SrcBits = SrcBitElements[I]; 10997 for (unsigned J = 0; J != Scale; ++J) { 10998 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1)); 10999 APInt &DstBits = DstBitElements[Idx]; 11000 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits); 11001 } 11002 } 11003 } 11004 11005 bool BuildVectorSDNode::isConstant() const { 11006 for (const SDValue &Op : op_values()) { 11007 unsigned Opc = Op.getOpcode(); 11008 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 11009 return false; 11010 } 11011 return true; 11012 } 11013 11014 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 11015 // Find the first non-undef value in the shuffle mask. 11016 unsigned i, e; 11017 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 11018 /* search */; 11019 11020 // If all elements are undefined, this shuffle can be considered a splat 11021 // (although it should eventually get simplified away completely). 11022 if (i == e) 11023 return true; 11024 11025 // Make sure all remaining elements are either undef or the same as the first 11026 // non-undef value. 11027 for (int Idx = Mask[i]; i != e; ++i) 11028 if (Mask[i] >= 0 && Mask[i] != Idx) 11029 return false; 11030 return true; 11031 } 11032 11033 // Returns the SDNode if it is a constant integer BuildVector 11034 // or constant integer. 11035 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 11036 if (isa<ConstantSDNode>(N)) 11037 return N.getNode(); 11038 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 11039 return N.getNode(); 11040 // Treat a GlobalAddress supporting constant offset folding as a 11041 // constant integer. 11042 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 11043 if (GA->getOpcode() == ISD::GlobalAddress && 11044 TLI->isOffsetFoldingLegal(GA)) 11045 return GA; 11046 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 11047 isa<ConstantSDNode>(N.getOperand(0))) 11048 return N.getNode(); 11049 return nullptr; 11050 } 11051 11052 // Returns the SDNode if it is a constant float BuildVector 11053 // or constant float. 11054 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 11055 if (isa<ConstantFPSDNode>(N)) 11056 return N.getNode(); 11057 11058 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 11059 return N.getNode(); 11060 11061 return nullptr; 11062 } 11063 11064 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 11065 assert(!Node->OperandList && "Node already has operands"); 11066 assert(SDNode::getMaxNumOperands() >= Vals.size() && 11067 "too many operands to fit into SDNode"); 11068 SDUse *Ops = OperandRecycler.allocate( 11069 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 11070 11071 bool IsDivergent = false; 11072 for (unsigned I = 0; I != Vals.size(); ++I) { 11073 Ops[I].setUser(Node); 11074 Ops[I].setInitial(Vals[I]); 11075 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 11076 IsDivergent |= Ops[I].getNode()->isDivergent(); 11077 } 11078 Node->NumOperands = Vals.size(); 11079 Node->OperandList = Ops; 11080 if (!TLI->isSDNodeAlwaysUniform(Node)) { 11081 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 11082 Node->SDNodeBits.IsDivergent = IsDivergent; 11083 } 11084 checkForCycles(Node); 11085 } 11086 11087 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 11088 SmallVectorImpl<SDValue> &Vals) { 11089 size_t Limit = SDNode::getMaxNumOperands(); 11090 while (Vals.size() > Limit) { 11091 unsigned SliceIdx = Vals.size() - Limit; 11092 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 11093 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 11094 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 11095 Vals.emplace_back(NewTF); 11096 } 11097 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 11098 } 11099 11100 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 11101 EVT VT, SDNodeFlags Flags) { 11102 switch (Opcode) { 11103 default: 11104 return SDValue(); 11105 case ISD::ADD: 11106 case ISD::OR: 11107 case ISD::XOR: 11108 case ISD::UMAX: 11109 return getConstant(0, DL, VT); 11110 case ISD::MUL: 11111 return getConstant(1, DL, VT); 11112 case ISD::AND: 11113 case ISD::UMIN: 11114 return getAllOnesConstant(DL, VT); 11115 case ISD::SMAX: 11116 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 11117 case ISD::SMIN: 11118 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 11119 case ISD::FADD: 11120 return getConstantFP(-0.0, DL, VT); 11121 case ISD::FMUL: 11122 return getConstantFP(1.0, DL, VT); 11123 case ISD::FMINNUM: 11124 case ISD::FMAXNUM: { 11125 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 11126 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 11127 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 11128 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 11129 APFloat::getLargest(Semantics); 11130 if (Opcode == ISD::FMAXNUM) 11131 NeutralAF.changeSign(); 11132 11133 return getConstantFP(NeutralAF, DL, VT); 11134 } 11135 } 11136 } 11137 11138 #ifndef NDEBUG 11139 static void checkForCyclesHelper(const SDNode *N, 11140 SmallPtrSetImpl<const SDNode*> &Visited, 11141 SmallPtrSetImpl<const SDNode*> &Checked, 11142 const llvm::SelectionDAG *DAG) { 11143 // If this node has already been checked, don't check it again. 11144 if (Checked.count(N)) 11145 return; 11146 11147 // If a node has already been visited on this depth-first walk, reject it as 11148 // a cycle. 11149 if (!Visited.insert(N).second) { 11150 errs() << "Detected cycle in SelectionDAG\n"; 11151 dbgs() << "Offending node:\n"; 11152 N->dumprFull(DAG); dbgs() << "\n"; 11153 abort(); 11154 } 11155 11156 for (const SDValue &Op : N->op_values()) 11157 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 11158 11159 Checked.insert(N); 11160 Visited.erase(N); 11161 } 11162 #endif 11163 11164 void llvm::checkForCycles(const llvm::SDNode *N, 11165 const llvm::SelectionDAG *DAG, 11166 bool force) { 11167 #ifndef NDEBUG 11168 bool check = force; 11169 #ifdef EXPENSIVE_CHECKS 11170 check = true; 11171 #endif // EXPENSIVE_CHECKS 11172 if (check) { 11173 assert(N && "Checking nonexistent SDNode"); 11174 SmallPtrSet<const SDNode*, 32> visited; 11175 SmallPtrSet<const SDNode*, 32> checked; 11176 checkForCyclesHelper(N, visited, checked, DAG); 11177 } 11178 #endif // !NDEBUG 11179 } 11180 11181 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 11182 checkForCycles(DAG->getRoot().getNode(), DAG, force); 11183 } 11184