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/FunctionLoweringInfo.h" 32 #include "llvm/CodeGen/ISDOpcodes.h" 33 #include "llvm/CodeGen/MachineBasicBlock.h" 34 #include "llvm/CodeGen/MachineConstantPool.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineMemOperand.h" 38 #include "llvm/CodeGen/RuntimeLibcalls.h" 39 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 40 #include "llvm/CodeGen/SelectionDAGNodes.h" 41 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 42 #include "llvm/CodeGen/TargetFrameLowering.h" 43 #include "llvm/CodeGen/TargetLowering.h" 44 #include "llvm/CodeGen/TargetRegisterInfo.h" 45 #include "llvm/CodeGen/TargetSubtargetInfo.h" 46 #include "llvm/CodeGen/ValueTypes.h" 47 #include "llvm/IR/Constant.h" 48 #include "llvm/IR/Constants.h" 49 #include "llvm/IR/DataLayout.h" 50 #include "llvm/IR/DebugInfoMetadata.h" 51 #include "llvm/IR/DebugLoc.h" 52 #include "llvm/IR/DerivedTypes.h" 53 #include "llvm/IR/Function.h" 54 #include "llvm/IR/GlobalValue.h" 55 #include "llvm/IR/Metadata.h" 56 #include "llvm/IR/Type.h" 57 #include "llvm/IR/Value.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/CodeGen.h" 60 #include "llvm/Support/Compiler.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/KnownBits.h" 64 #include "llvm/Support/MachineValueType.h" 65 #include "llvm/Support/ManagedStatic.h" 66 #include "llvm/Support/MathExtras.h" 67 #include "llvm/Support/Mutex.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include "llvm/Target/TargetOptions.h" 71 #include "llvm/Transforms/Utils/SizeOpts.h" 72 #include <algorithm> 73 #include <cassert> 74 #include <cstdint> 75 #include <cstdlib> 76 #include <limits> 77 #include <set> 78 #include <string> 79 #include <utility> 80 #include <vector> 81 82 using namespace llvm; 83 84 /// makeVTList - Return an instance of the SDVTList struct initialized with the 85 /// specified members. 86 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) { 87 SDVTList Res = {VTs, NumVTs}; 88 return Res; 89 } 90 91 // Default null implementations of the callbacks. 92 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {} 93 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {} 94 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {} 95 96 void SelectionDAG::DAGNodeDeletedListener::anchor() {} 97 98 #define DEBUG_TYPE "selectiondag" 99 100 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt", 101 cl::Hidden, cl::init(true), 102 cl::desc("Gang up loads and stores generated by inlining of memcpy")); 103 104 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max", 105 cl::desc("Number limit for gluing ld/st of memcpy."), 106 cl::Hidden, cl::init(0)); 107 108 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) { 109 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G);); 110 } 111 112 //===----------------------------------------------------------------------===// 113 // ConstantFPSDNode Class 114 //===----------------------------------------------------------------------===// 115 116 /// isExactlyValue - We don't rely on operator== working on double values, as 117 /// it returns true for things that are clearly not equal, like -0.0 and 0.0. 118 /// As such, this method can be used to do an exact bit-for-bit comparison of 119 /// two floating point values. 120 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const { 121 return getValueAPF().bitwiseIsEqual(V); 122 } 123 124 bool ConstantFPSDNode::isValueValidForType(EVT VT, 125 const APFloat& Val) { 126 assert(VT.isFloatingPoint() && "Can only convert between FP types"); 127 128 // convert modifies in place, so make a copy. 129 APFloat Val2 = APFloat(Val); 130 bool losesInfo; 131 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT), 132 APFloat::rmNearestTiesToEven, 133 &losesInfo); 134 return !losesInfo; 135 } 136 137 //===----------------------------------------------------------------------===// 138 // ISD Namespace 139 //===----------------------------------------------------------------------===// 140 141 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) { 142 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 143 unsigned EltSize = 144 N->getValueType(0).getVectorElementType().getSizeInBits(); 145 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 146 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize); 147 return true; 148 } 149 } 150 151 auto *BV = dyn_cast<BuildVectorSDNode>(N); 152 if (!BV) 153 return false; 154 155 APInt SplatUndef; 156 unsigned SplatBitSize; 157 bool HasUndefs; 158 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits(); 159 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs, 160 EltSize) && 161 EltSize == SplatBitSize; 162 } 163 164 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be 165 // specializations of the more general isConstantSplatVector()? 166 167 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) { 168 // Look through a bit convert. 169 while (N->getOpcode() == ISD::BITCAST) 170 N = N->getOperand(0).getNode(); 171 172 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 173 APInt SplatVal; 174 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnesValue(); 175 } 176 177 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 178 179 unsigned i = 0, e = N->getNumOperands(); 180 181 // Skip over all of the undef values. 182 while (i != e && N->getOperand(i).isUndef()) 183 ++i; 184 185 // Do not accept an all-undef vector. 186 if (i == e) return false; 187 188 // Do not accept build_vectors that aren't all constants or which have non-~0 189 // elements. We have to be a bit careful here, as the type of the constant 190 // may not be the same as the type of the vector elements due to type 191 // legalization (the elements are promoted to a legal type for the target and 192 // a vector of a type may be legal when the base element type is not). 193 // We only want to check enough bits to cover the vector elements, because 194 // we care if the resultant vector is all ones, not whether the individual 195 // constants are. 196 SDValue NotZero = N->getOperand(i); 197 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 198 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) { 199 if (CN->getAPIntValue().countTrailingOnes() < EltSize) 200 return false; 201 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) { 202 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize) 203 return false; 204 } else 205 return false; 206 207 // Okay, we have at least one ~0 value, check to see if the rest match or are 208 // undefs. Even with the above element type twiddling, this should be OK, as 209 // the same type legalization should have applied to all the elements. 210 for (++i; i != e; ++i) 211 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef()) 212 return false; 213 return true; 214 } 215 216 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) { 217 // Look through a bit convert. 218 while (N->getOpcode() == ISD::BITCAST) 219 N = N->getOperand(0).getNode(); 220 221 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) { 222 APInt SplatVal; 223 return isConstantSplatVector(N, SplatVal) && SplatVal.isNullValue(); 224 } 225 226 if (N->getOpcode() != ISD::BUILD_VECTOR) return false; 227 228 bool IsAllUndef = true; 229 for (const SDValue &Op : N->op_values()) { 230 if (Op.isUndef()) 231 continue; 232 IsAllUndef = false; 233 // Do not accept build_vectors that aren't all constants or which have non-0 234 // elements. We have to be a bit careful here, as the type of the constant 235 // may not be the same as the type of the vector elements due to type 236 // legalization (the elements are promoted to a legal type for the target 237 // and a vector of a type may be legal when the base element type is not). 238 // We only want to check enough bits to cover the vector elements, because 239 // we care if the resultant vector is all zeros, not whether the individual 240 // constants are. 241 unsigned EltSize = N->getValueType(0).getScalarSizeInBits(); 242 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) { 243 if (CN->getAPIntValue().countTrailingZeros() < EltSize) 244 return false; 245 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) { 246 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize) 247 return false; 248 } else 249 return false; 250 } 251 252 // Do not accept an all-undef vector. 253 if (IsAllUndef) 254 return false; 255 return true; 256 } 257 258 bool ISD::isBuildVectorAllOnes(const SDNode *N) { 259 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true); 260 } 261 262 bool ISD::isBuildVectorAllZeros(const SDNode *N) { 263 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true); 264 } 265 266 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) { 267 if (N->getOpcode() != ISD::BUILD_VECTOR) 268 return false; 269 270 for (const SDValue &Op : N->op_values()) { 271 if (Op.isUndef()) 272 continue; 273 if (!isa<ConstantSDNode>(Op)) 274 return false; 275 } 276 return true; 277 } 278 279 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) { 280 if (N->getOpcode() != ISD::BUILD_VECTOR) 281 return false; 282 283 for (const SDValue &Op : N->op_values()) { 284 if (Op.isUndef()) 285 continue; 286 if (!isa<ConstantFPSDNode>(Op)) 287 return false; 288 } 289 return true; 290 } 291 292 bool ISD::allOperandsUndef(const SDNode *N) { 293 // Return false if the node has no operands. 294 // This is "logically inconsistent" with the definition of "all" but 295 // is probably the desired behavior. 296 if (N->getNumOperands() == 0) 297 return false; 298 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); }); 299 } 300 301 bool ISD::matchUnaryPredicate(SDValue Op, 302 std::function<bool(ConstantSDNode *)> Match, 303 bool AllowUndefs) { 304 // FIXME: Add support for scalar UNDEF cases? 305 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) 306 return Match(Cst); 307 308 // FIXME: Add support for vector UNDEF cases? 309 if (ISD::BUILD_VECTOR != Op.getOpcode() && 310 ISD::SPLAT_VECTOR != Op.getOpcode()) 311 return false; 312 313 EVT SVT = Op.getValueType().getScalarType(); 314 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 315 if (AllowUndefs && Op.getOperand(i).isUndef()) { 316 if (!Match(nullptr)) 317 return false; 318 continue; 319 } 320 321 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i)); 322 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst)) 323 return false; 324 } 325 return true; 326 } 327 328 bool ISD::matchBinaryPredicate( 329 SDValue LHS, SDValue RHS, 330 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match, 331 bool AllowUndefs, bool AllowTypeMismatch) { 332 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType()) 333 return false; 334 335 // TODO: Add support for scalar UNDEF cases? 336 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS)) 337 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS)) 338 return Match(LHSCst, RHSCst); 339 340 // TODO: Add support for vector UNDEF cases? 341 if (ISD::BUILD_VECTOR != LHS.getOpcode() || 342 ISD::BUILD_VECTOR != RHS.getOpcode()) 343 return false; 344 345 EVT SVT = LHS.getValueType().getScalarType(); 346 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) { 347 SDValue LHSOp = LHS.getOperand(i); 348 SDValue RHSOp = RHS.getOperand(i); 349 bool LHSUndef = AllowUndefs && LHSOp.isUndef(); 350 bool RHSUndef = AllowUndefs && RHSOp.isUndef(); 351 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp); 352 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp); 353 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef)) 354 return false; 355 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT || 356 LHSOp.getValueType() != RHSOp.getValueType())) 357 return false; 358 if (!Match(LHSCst, RHSCst)) 359 return false; 360 } 361 return true; 362 } 363 364 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) { 365 switch (VecReduceOpcode) { 366 default: 367 llvm_unreachable("Expected VECREDUCE opcode"); 368 case ISD::VECREDUCE_FADD: 369 case ISD::VECREDUCE_SEQ_FADD: 370 return ISD::FADD; 371 case ISD::VECREDUCE_FMUL: 372 case ISD::VECREDUCE_SEQ_FMUL: 373 return ISD::FMUL; 374 case ISD::VECREDUCE_ADD: 375 return ISD::ADD; 376 case ISD::VECREDUCE_MUL: 377 return ISD::MUL; 378 case ISD::VECREDUCE_AND: 379 return ISD::AND; 380 case ISD::VECREDUCE_OR: 381 return ISD::OR; 382 case ISD::VECREDUCE_XOR: 383 return ISD::XOR; 384 case ISD::VECREDUCE_SMAX: 385 return ISD::SMAX; 386 case ISD::VECREDUCE_SMIN: 387 return ISD::SMIN; 388 case ISD::VECREDUCE_UMAX: 389 return ISD::UMAX; 390 case ISD::VECREDUCE_UMIN: 391 return ISD::UMIN; 392 case ISD::VECREDUCE_FMAX: 393 return ISD::FMAXNUM; 394 case ISD::VECREDUCE_FMIN: 395 return ISD::FMINNUM; 396 } 397 } 398 399 bool ISD::isVPOpcode(unsigned Opcode) { 400 switch (Opcode) { 401 default: 402 return false; 403 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) \ 404 case ISD::SDOPC: \ 405 return true; 406 #include "llvm/IR/VPIntrinsics.def" 407 } 408 } 409 410 /// The operand position of the vector mask. 411 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) { 412 switch (Opcode) { 413 default: 414 return None; 415 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...) \ 416 case ISD::SDOPC: \ 417 return MASKPOS; 418 #include "llvm/IR/VPIntrinsics.def" 419 } 420 } 421 422 /// The operand position of the explicit vector length parameter. 423 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) { 424 switch (Opcode) { 425 default: 426 return None; 427 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \ 428 case ISD::SDOPC: \ 429 return EVLPOS; 430 #include "llvm/IR/VPIntrinsics.def" 431 } 432 } 433 434 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) { 435 switch (ExtType) { 436 case ISD::EXTLOAD: 437 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND; 438 case ISD::SEXTLOAD: 439 return ISD::SIGN_EXTEND; 440 case ISD::ZEXTLOAD: 441 return ISD::ZERO_EXTEND; 442 default: 443 break; 444 } 445 446 llvm_unreachable("Invalid LoadExtType"); 447 } 448 449 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) { 450 // To perform this operation, we just need to swap the L and G bits of the 451 // operation. 452 unsigned OldL = (Operation >> 2) & 1; 453 unsigned OldG = (Operation >> 1) & 1; 454 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits 455 (OldL << 1) | // New G bit 456 (OldG << 2)); // New L bit. 457 } 458 459 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) { 460 unsigned Operation = Op; 461 if (isIntegerLike) 462 Operation ^= 7; // Flip L, G, E bits, but not U. 463 else 464 Operation ^= 15; // Flip all of the condition bits. 465 466 if (Operation > ISD::SETTRUE2) 467 Operation &= ~8; // Don't let N and U bits get set. 468 469 return ISD::CondCode(Operation); 470 } 471 472 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) { 473 return getSetCCInverseImpl(Op, Type.isInteger()); 474 } 475 476 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op, 477 bool isIntegerLike) { 478 return getSetCCInverseImpl(Op, isIntegerLike); 479 } 480 481 /// For an integer comparison, return 1 if the comparison is a signed operation 482 /// and 2 if the result is an unsigned comparison. Return zero if the operation 483 /// does not depend on the sign of the input (setne and seteq). 484 static int isSignedOp(ISD::CondCode Opcode) { 485 switch (Opcode) { 486 default: llvm_unreachable("Illegal integer setcc operation!"); 487 case ISD::SETEQ: 488 case ISD::SETNE: return 0; 489 case ISD::SETLT: 490 case ISD::SETLE: 491 case ISD::SETGT: 492 case ISD::SETGE: return 1; 493 case ISD::SETULT: 494 case ISD::SETULE: 495 case ISD::SETUGT: 496 case ISD::SETUGE: return 2; 497 } 498 } 499 500 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2, 501 EVT Type) { 502 bool IsInteger = Type.isInteger(); 503 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 504 // Cannot fold a signed integer setcc with an unsigned integer setcc. 505 return ISD::SETCC_INVALID; 506 507 unsigned Op = Op1 | Op2; // Combine all of the condition bits. 508 509 // If the N and U bits get set, then the resultant comparison DOES suddenly 510 // care about orderedness, and it is true when ordered. 511 if (Op > ISD::SETTRUE2) 512 Op &= ~16; // Clear the U bit if the N bit is set. 513 514 // Canonicalize illegal integer setcc's. 515 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT 516 Op = ISD::SETNE; 517 518 return ISD::CondCode(Op); 519 } 520 521 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2, 522 EVT Type) { 523 bool IsInteger = Type.isInteger(); 524 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3) 525 // Cannot fold a signed setcc with an unsigned setcc. 526 return ISD::SETCC_INVALID; 527 528 // Combine all of the condition bits. 529 ISD::CondCode Result = ISD::CondCode(Op1 & Op2); 530 531 // Canonicalize illegal integer setcc's. 532 if (IsInteger) { 533 switch (Result) { 534 default: break; 535 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT 536 case ISD::SETOEQ: // SETEQ & SETU[LG]E 537 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE 538 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE 539 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE 540 } 541 } 542 543 return Result; 544 } 545 546 //===----------------------------------------------------------------------===// 547 // SDNode Profile Support 548 //===----------------------------------------------------------------------===// 549 550 /// AddNodeIDOpcode - Add the node opcode to the NodeID data. 551 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) { 552 ID.AddInteger(OpC); 553 } 554 555 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them 556 /// solely with their pointer. 557 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) { 558 ID.AddPointer(VTList.VTs); 559 } 560 561 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 562 static void AddNodeIDOperands(FoldingSetNodeID &ID, 563 ArrayRef<SDValue> Ops) { 564 for (auto& Op : Ops) { 565 ID.AddPointer(Op.getNode()); 566 ID.AddInteger(Op.getResNo()); 567 } 568 } 569 570 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data. 571 static void AddNodeIDOperands(FoldingSetNodeID &ID, 572 ArrayRef<SDUse> Ops) { 573 for (auto& Op : Ops) { 574 ID.AddPointer(Op.getNode()); 575 ID.AddInteger(Op.getResNo()); 576 } 577 } 578 579 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC, 580 SDVTList VTList, ArrayRef<SDValue> OpList) { 581 AddNodeIDOpcode(ID, OpC); 582 AddNodeIDValueTypes(ID, VTList); 583 AddNodeIDOperands(ID, OpList); 584 } 585 586 /// If this is an SDNode with special info, add this info to the NodeID data. 587 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) { 588 switch (N->getOpcode()) { 589 case ISD::TargetExternalSymbol: 590 case ISD::ExternalSymbol: 591 case ISD::MCSymbol: 592 llvm_unreachable("Should only be used on nodes with operands"); 593 default: break; // Normal nodes don't need extra info. 594 case ISD::TargetConstant: 595 case ISD::Constant: { 596 const ConstantSDNode *C = cast<ConstantSDNode>(N); 597 ID.AddPointer(C->getConstantIntValue()); 598 ID.AddBoolean(C->isOpaque()); 599 break; 600 } 601 case ISD::TargetConstantFP: 602 case ISD::ConstantFP: 603 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue()); 604 break; 605 case ISD::TargetGlobalAddress: 606 case ISD::GlobalAddress: 607 case ISD::TargetGlobalTLSAddress: 608 case ISD::GlobalTLSAddress: { 609 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N); 610 ID.AddPointer(GA->getGlobal()); 611 ID.AddInteger(GA->getOffset()); 612 ID.AddInteger(GA->getTargetFlags()); 613 break; 614 } 615 case ISD::BasicBlock: 616 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock()); 617 break; 618 case ISD::Register: 619 ID.AddInteger(cast<RegisterSDNode>(N)->getReg()); 620 break; 621 case ISD::RegisterMask: 622 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask()); 623 break; 624 case ISD::SRCVALUE: 625 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue()); 626 break; 627 case ISD::FrameIndex: 628 case ISD::TargetFrameIndex: 629 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex()); 630 break; 631 case ISD::LIFETIME_START: 632 case ISD::LIFETIME_END: 633 if (cast<LifetimeSDNode>(N)->hasOffset()) { 634 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize()); 635 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset()); 636 } 637 break; 638 case ISD::PSEUDO_PROBE: 639 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid()); 640 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex()); 641 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes()); 642 break; 643 case ISD::JumpTable: 644 case ISD::TargetJumpTable: 645 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex()); 646 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags()); 647 break; 648 case ISD::ConstantPool: 649 case ISD::TargetConstantPool: { 650 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N); 651 ID.AddInteger(CP->getAlign().value()); 652 ID.AddInteger(CP->getOffset()); 653 if (CP->isMachineConstantPoolEntry()) 654 CP->getMachineCPVal()->addSelectionDAGCSEId(ID); 655 else 656 ID.AddPointer(CP->getConstVal()); 657 ID.AddInteger(CP->getTargetFlags()); 658 break; 659 } 660 case ISD::TargetIndex: { 661 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N); 662 ID.AddInteger(TI->getIndex()); 663 ID.AddInteger(TI->getOffset()); 664 ID.AddInteger(TI->getTargetFlags()); 665 break; 666 } 667 case ISD::LOAD: { 668 const LoadSDNode *LD = cast<LoadSDNode>(N); 669 ID.AddInteger(LD->getMemoryVT().getRawBits()); 670 ID.AddInteger(LD->getRawSubclassData()); 671 ID.AddInteger(LD->getPointerInfo().getAddrSpace()); 672 break; 673 } 674 case ISD::STORE: { 675 const StoreSDNode *ST = cast<StoreSDNode>(N); 676 ID.AddInteger(ST->getMemoryVT().getRawBits()); 677 ID.AddInteger(ST->getRawSubclassData()); 678 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 679 break; 680 } 681 case ISD::MLOAD: { 682 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 683 ID.AddInteger(MLD->getMemoryVT().getRawBits()); 684 ID.AddInteger(MLD->getRawSubclassData()); 685 ID.AddInteger(MLD->getPointerInfo().getAddrSpace()); 686 break; 687 } 688 case ISD::MSTORE: { 689 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 690 ID.AddInteger(MST->getMemoryVT().getRawBits()); 691 ID.AddInteger(MST->getRawSubclassData()); 692 ID.AddInteger(MST->getPointerInfo().getAddrSpace()); 693 break; 694 } 695 case ISD::MGATHER: { 696 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N); 697 ID.AddInteger(MG->getMemoryVT().getRawBits()); 698 ID.AddInteger(MG->getRawSubclassData()); 699 ID.AddInteger(MG->getPointerInfo().getAddrSpace()); 700 break; 701 } 702 case ISD::MSCATTER: { 703 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N); 704 ID.AddInteger(MS->getMemoryVT().getRawBits()); 705 ID.AddInteger(MS->getRawSubclassData()); 706 ID.AddInteger(MS->getPointerInfo().getAddrSpace()); 707 break; 708 } 709 case ISD::ATOMIC_CMP_SWAP: 710 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 711 case ISD::ATOMIC_SWAP: 712 case ISD::ATOMIC_LOAD_ADD: 713 case ISD::ATOMIC_LOAD_SUB: 714 case ISD::ATOMIC_LOAD_AND: 715 case ISD::ATOMIC_LOAD_CLR: 716 case ISD::ATOMIC_LOAD_OR: 717 case ISD::ATOMIC_LOAD_XOR: 718 case ISD::ATOMIC_LOAD_NAND: 719 case ISD::ATOMIC_LOAD_MIN: 720 case ISD::ATOMIC_LOAD_MAX: 721 case ISD::ATOMIC_LOAD_UMIN: 722 case ISD::ATOMIC_LOAD_UMAX: 723 case ISD::ATOMIC_LOAD: 724 case ISD::ATOMIC_STORE: { 725 const AtomicSDNode *AT = cast<AtomicSDNode>(N); 726 ID.AddInteger(AT->getMemoryVT().getRawBits()); 727 ID.AddInteger(AT->getRawSubclassData()); 728 ID.AddInteger(AT->getPointerInfo().getAddrSpace()); 729 break; 730 } 731 case ISD::PREFETCH: { 732 const MemSDNode *PF = cast<MemSDNode>(N); 733 ID.AddInteger(PF->getPointerInfo().getAddrSpace()); 734 break; 735 } 736 case ISD::VECTOR_SHUFFLE: { 737 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 738 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements(); 739 i != e; ++i) 740 ID.AddInteger(SVN->getMaskElt(i)); 741 break; 742 } 743 case ISD::TargetBlockAddress: 744 case ISD::BlockAddress: { 745 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N); 746 ID.AddPointer(BA->getBlockAddress()); 747 ID.AddInteger(BA->getOffset()); 748 ID.AddInteger(BA->getTargetFlags()); 749 break; 750 } 751 } // end switch (N->getOpcode()) 752 753 // Target specific memory nodes could also have address spaces to check. 754 if (N->isTargetMemoryOpcode()) 755 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace()); 756 } 757 758 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID 759 /// data. 760 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) { 761 AddNodeIDOpcode(ID, N->getOpcode()); 762 // Add the return value info. 763 AddNodeIDValueTypes(ID, N->getVTList()); 764 // Add the operand info. 765 AddNodeIDOperands(ID, N->ops()); 766 767 // Handle SDNode leafs with special info. 768 AddNodeIDCustom(ID, N); 769 } 770 771 //===----------------------------------------------------------------------===// 772 // SelectionDAG Class 773 //===----------------------------------------------------------------------===// 774 775 /// doNotCSE - Return true if CSE should not be performed for this node. 776 static bool doNotCSE(SDNode *N) { 777 if (N->getValueType(0) == MVT::Glue) 778 return true; // Never CSE anything that produces a flag. 779 780 switch (N->getOpcode()) { 781 default: break; 782 case ISD::HANDLENODE: 783 case ISD::EH_LABEL: 784 return true; // Never CSE these nodes. 785 } 786 787 // Check that remaining values produced are not flags. 788 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i) 789 if (N->getValueType(i) == MVT::Glue) 790 return true; // Never CSE anything that produces a flag. 791 792 return false; 793 } 794 795 /// RemoveDeadNodes - This method deletes all unreachable nodes in the 796 /// SelectionDAG. 797 void SelectionDAG::RemoveDeadNodes() { 798 // Create a dummy node (which is not added to allnodes), that adds a reference 799 // to the root node, preventing it from being deleted. 800 HandleSDNode Dummy(getRoot()); 801 802 SmallVector<SDNode*, 128> DeadNodes; 803 804 // Add all obviously-dead nodes to the DeadNodes worklist. 805 for (SDNode &Node : allnodes()) 806 if (Node.use_empty()) 807 DeadNodes.push_back(&Node); 808 809 RemoveDeadNodes(DeadNodes); 810 811 // If the root changed (e.g. it was a dead load, update the root). 812 setRoot(Dummy.getValue()); 813 } 814 815 /// RemoveDeadNodes - This method deletes the unreachable nodes in the 816 /// given list, and any nodes that become unreachable as a result. 817 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) { 818 819 // Process the worklist, deleting the nodes and adding their uses to the 820 // worklist. 821 while (!DeadNodes.empty()) { 822 SDNode *N = DeadNodes.pop_back_val(); 823 // Skip to next node if we've already managed to delete the node. This could 824 // happen if replacing a node causes a node previously added to the node to 825 // be deleted. 826 if (N->getOpcode() == ISD::DELETED_NODE) 827 continue; 828 829 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 830 DUL->NodeDeleted(N, nullptr); 831 832 // Take the node out of the appropriate CSE map. 833 RemoveNodeFromCSEMaps(N); 834 835 // Next, brutally remove the operand list. This is safe to do, as there are 836 // no cycles in the graph. 837 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 838 SDUse &Use = *I++; 839 SDNode *Operand = Use.getNode(); 840 Use.set(SDValue()); 841 842 // Now that we removed this operand, see if there are no uses of it left. 843 if (Operand->use_empty()) 844 DeadNodes.push_back(Operand); 845 } 846 847 DeallocateNode(N); 848 } 849 } 850 851 void SelectionDAG::RemoveDeadNode(SDNode *N){ 852 SmallVector<SDNode*, 16> DeadNodes(1, N); 853 854 // Create a dummy node that adds a reference to the root node, preventing 855 // it from being deleted. (This matters if the root is an operand of the 856 // dead node.) 857 HandleSDNode Dummy(getRoot()); 858 859 RemoveDeadNodes(DeadNodes); 860 } 861 862 void SelectionDAG::DeleteNode(SDNode *N) { 863 // First take this out of the appropriate CSE map. 864 RemoveNodeFromCSEMaps(N); 865 866 // Finally, remove uses due to operands of this node, remove from the 867 // AllNodes list, and delete the node. 868 DeleteNodeNotInCSEMaps(N); 869 } 870 871 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) { 872 assert(N->getIterator() != AllNodes.begin() && 873 "Cannot delete the entry node!"); 874 assert(N->use_empty() && "Cannot delete a node that is not dead!"); 875 876 // Drop all of the operands and decrement used node's use counts. 877 N->DropOperands(); 878 879 DeallocateNode(N); 880 } 881 882 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) { 883 assert(!(V->isVariadic() && isParameter)); 884 if (isParameter) 885 ByvalParmDbgValues.push_back(V); 886 else 887 DbgValues.push_back(V); 888 for (const SDNode *Node : V->getSDNodes()) 889 if (Node) 890 DbgValMap[Node].push_back(V); 891 } 892 893 void SDDbgInfo::erase(const SDNode *Node) { 894 DbgValMapType::iterator I = DbgValMap.find(Node); 895 if (I == DbgValMap.end()) 896 return; 897 for (auto &Val: I->second) 898 Val->setIsInvalidated(); 899 DbgValMap.erase(I); 900 } 901 902 void SelectionDAG::DeallocateNode(SDNode *N) { 903 // If we have operands, deallocate them. 904 removeOperands(N); 905 906 NodeAllocator.Deallocate(AllNodes.remove(N)); 907 908 // Set the opcode to DELETED_NODE to help catch bugs when node 909 // memory is reallocated. 910 // FIXME: There are places in SDag that have grown a dependency on the opcode 911 // value in the released node. 912 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType)); 913 N->NodeType = ISD::DELETED_NODE; 914 915 // If any of the SDDbgValue nodes refer to this SDNode, invalidate 916 // them and forget about that node. 917 DbgInfo->erase(N); 918 } 919 920 #ifndef NDEBUG 921 /// VerifySDNode - Sanity check the given SDNode. Aborts if it is invalid. 922 static void VerifySDNode(SDNode *N) { 923 switch (N->getOpcode()) { 924 default: 925 break; 926 case ISD::BUILD_PAIR: { 927 EVT VT = N->getValueType(0); 928 assert(N->getNumValues() == 1 && "Too many results!"); 929 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) && 930 "Wrong return type!"); 931 assert(N->getNumOperands() == 2 && "Wrong number of operands!"); 932 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() && 933 "Mismatched operand types!"); 934 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() && 935 "Wrong operand type!"); 936 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() && 937 "Wrong return type size"); 938 break; 939 } 940 case ISD::BUILD_VECTOR: { 941 assert(N->getNumValues() == 1 && "Too many results!"); 942 assert(N->getValueType(0).isVector() && "Wrong return type!"); 943 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() && 944 "Wrong number of operands!"); 945 EVT EltVT = N->getValueType(0).getVectorElementType(); 946 for (const SDUse &Op : N->ops()) { 947 assert((Op.getValueType() == EltVT || 948 (EltVT.isInteger() && Op.getValueType().isInteger() && 949 EltVT.bitsLE(Op.getValueType()))) && 950 "Wrong operand type!"); 951 assert(Op.getValueType() == N->getOperand(0).getValueType() && 952 "Operands must all have the same type"); 953 } 954 break; 955 } 956 } 957 } 958 #endif // NDEBUG 959 960 /// Insert a newly allocated node into the DAG. 961 /// 962 /// Handles insertion into the all nodes list and CSE map, as well as 963 /// verification and other common operations when a new node is allocated. 964 void SelectionDAG::InsertNode(SDNode *N) { 965 AllNodes.push_back(N); 966 #ifndef NDEBUG 967 N->PersistentId = NextPersistentId++; 968 VerifySDNode(N); 969 #endif 970 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 971 DUL->NodeInserted(N); 972 } 973 974 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that 975 /// correspond to it. This is useful when we're about to delete or repurpose 976 /// the node. We don't want future request for structurally identical nodes 977 /// to return N anymore. 978 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) { 979 bool Erased = false; 980 switch (N->getOpcode()) { 981 case ISD::HANDLENODE: return false; // noop. 982 case ISD::CONDCODE: 983 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] && 984 "Cond code doesn't exist!"); 985 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr; 986 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr; 987 break; 988 case ISD::ExternalSymbol: 989 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol()); 990 break; 991 case ISD::TargetExternalSymbol: { 992 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N); 993 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>( 994 ESN->getSymbol(), ESN->getTargetFlags())); 995 break; 996 } 997 case ISD::MCSymbol: { 998 auto *MCSN = cast<MCSymbolSDNode>(N); 999 Erased = MCSymbols.erase(MCSN->getMCSymbol()); 1000 break; 1001 } 1002 case ISD::VALUETYPE: { 1003 EVT VT = cast<VTSDNode>(N)->getVT(); 1004 if (VT.isExtended()) { 1005 Erased = ExtendedValueTypeNodes.erase(VT); 1006 } else { 1007 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr; 1008 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr; 1009 } 1010 break; 1011 } 1012 default: 1013 // Remove it from the CSE Map. 1014 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!"); 1015 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!"); 1016 Erased = CSEMap.RemoveNode(N); 1017 break; 1018 } 1019 #ifndef NDEBUG 1020 // Verify that the node was actually in one of the CSE maps, unless it has a 1021 // flag result (which cannot be CSE'd) or is one of the special cases that are 1022 // not subject to CSE. 1023 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue && 1024 !N->isMachineOpcode() && !doNotCSE(N)) { 1025 N->dump(this); 1026 dbgs() << "\n"; 1027 llvm_unreachable("Node is not in map!"); 1028 } 1029 #endif 1030 return Erased; 1031 } 1032 1033 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE 1034 /// maps and modified in place. Add it back to the CSE maps, unless an identical 1035 /// node already exists, in which case transfer all its users to the existing 1036 /// node. This transfer can potentially trigger recursive merging. 1037 void 1038 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) { 1039 // For node types that aren't CSE'd, just act as if no identical node 1040 // already exists. 1041 if (!doNotCSE(N)) { 1042 SDNode *Existing = CSEMap.GetOrInsertNode(N); 1043 if (Existing != N) { 1044 // If there was already an existing matching node, use ReplaceAllUsesWith 1045 // to replace the dead one with the existing one. This can cause 1046 // recursive merging of other unrelated nodes down the line. 1047 ReplaceAllUsesWith(N, Existing); 1048 1049 // N is now dead. Inform the listeners and delete it. 1050 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1051 DUL->NodeDeleted(N, Existing); 1052 DeleteNodeNotInCSEMaps(N); 1053 return; 1054 } 1055 } 1056 1057 // If the node doesn't already exist, we updated it. Inform listeners. 1058 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next) 1059 DUL->NodeUpdated(N); 1060 } 1061 1062 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1063 /// were replaced with those specified. If this node is never memoized, 1064 /// return null, otherwise return a pointer to the slot it would take. If a 1065 /// node already exists with these operands, the slot will be non-null. 1066 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op, 1067 void *&InsertPos) { 1068 if (doNotCSE(N)) 1069 return nullptr; 1070 1071 SDValue Ops[] = { Op }; 1072 FoldingSetNodeID ID; 1073 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1074 AddNodeIDCustom(ID, N); 1075 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1076 if (Node) 1077 Node->intersectFlagsWith(N->getFlags()); 1078 return Node; 1079 } 1080 1081 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1082 /// were replaced with those specified. If this node is never memoized, 1083 /// return null, otherwise return a pointer to the slot it would take. If a 1084 /// node already exists with these operands, the slot will be non-null. 1085 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 1086 SDValue Op1, SDValue Op2, 1087 void *&InsertPos) { 1088 if (doNotCSE(N)) 1089 return nullptr; 1090 1091 SDValue Ops[] = { Op1, Op2 }; 1092 FoldingSetNodeID ID; 1093 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1094 AddNodeIDCustom(ID, N); 1095 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1096 if (Node) 1097 Node->intersectFlagsWith(N->getFlags()); 1098 return Node; 1099 } 1100 1101 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands 1102 /// were replaced with those specified. If this node is never memoized, 1103 /// return null, otherwise return a pointer to the slot it would take. If a 1104 /// node already exists with these operands, the slot will be non-null. 1105 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops, 1106 void *&InsertPos) { 1107 if (doNotCSE(N)) 1108 return nullptr; 1109 1110 FoldingSetNodeID ID; 1111 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops); 1112 AddNodeIDCustom(ID, N); 1113 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos); 1114 if (Node) 1115 Node->intersectFlagsWith(N->getFlags()); 1116 return Node; 1117 } 1118 1119 Align SelectionDAG::getEVTAlign(EVT VT) const { 1120 Type *Ty = VT == MVT::iPTR ? 1121 PointerType::get(Type::getInt8Ty(*getContext()), 0) : 1122 VT.getTypeForEVT(*getContext()); 1123 1124 return getDataLayout().getABITypeAlign(Ty); 1125 } 1126 1127 // EntryNode could meaningfully have debug info if we can find it... 1128 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL) 1129 : TM(tm), OptLevel(OL), 1130 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)), 1131 Root(getEntryNode()) { 1132 InsertNode(&EntryNode); 1133 DbgInfo = new SDDbgInfo(); 1134 } 1135 1136 void SelectionDAG::init(MachineFunction &NewMF, 1137 OptimizationRemarkEmitter &NewORE, 1138 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, 1139 LegacyDivergenceAnalysis * Divergence, 1140 ProfileSummaryInfo *PSIin, 1141 BlockFrequencyInfo *BFIin) { 1142 MF = &NewMF; 1143 SDAGISelPass = PassPtr; 1144 ORE = &NewORE; 1145 TLI = getSubtarget().getTargetLowering(); 1146 TSI = getSubtarget().getSelectionDAGInfo(); 1147 LibInfo = LibraryInfo; 1148 Context = &MF->getFunction().getContext(); 1149 DA = Divergence; 1150 PSI = PSIin; 1151 BFI = BFIin; 1152 } 1153 1154 SelectionDAG::~SelectionDAG() { 1155 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners"); 1156 allnodes_clear(); 1157 OperandRecycler.clear(OperandAllocator); 1158 delete DbgInfo; 1159 } 1160 1161 bool SelectionDAG::shouldOptForSize() const { 1162 return MF->getFunction().hasOptSize() || 1163 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI); 1164 } 1165 1166 void SelectionDAG::allnodes_clear() { 1167 assert(&*AllNodes.begin() == &EntryNode); 1168 AllNodes.remove(AllNodes.begin()); 1169 while (!AllNodes.empty()) 1170 DeallocateNode(&AllNodes.front()); 1171 #ifndef NDEBUG 1172 NextPersistentId = 0; 1173 #endif 1174 } 1175 1176 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1177 void *&InsertPos) { 1178 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1179 if (N) { 1180 switch (N->getOpcode()) { 1181 default: break; 1182 case ISD::Constant: 1183 case ISD::ConstantFP: 1184 llvm_unreachable("Querying for Constant and ConstantFP nodes requires " 1185 "debug location. Use another overload."); 1186 } 1187 } 1188 return N; 1189 } 1190 1191 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID, 1192 const SDLoc &DL, void *&InsertPos) { 1193 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos); 1194 if (N) { 1195 switch (N->getOpcode()) { 1196 case ISD::Constant: 1197 case ISD::ConstantFP: 1198 // Erase debug location from the node if the node is used at several 1199 // different places. Do not propagate one location to all uses as it 1200 // will cause a worse single stepping debugging experience. 1201 if (N->getDebugLoc() != DL.getDebugLoc()) 1202 N->setDebugLoc(DebugLoc()); 1203 break; 1204 default: 1205 // When the node's point of use is located earlier in the instruction 1206 // sequence than its prior point of use, update its debug info to the 1207 // earlier location. 1208 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder()) 1209 N->setDebugLoc(DL.getDebugLoc()); 1210 break; 1211 } 1212 } 1213 return N; 1214 } 1215 1216 void SelectionDAG::clear() { 1217 allnodes_clear(); 1218 OperandRecycler.clear(OperandAllocator); 1219 OperandAllocator.Reset(); 1220 CSEMap.clear(); 1221 1222 ExtendedValueTypeNodes.clear(); 1223 ExternalSymbols.clear(); 1224 TargetExternalSymbols.clear(); 1225 MCSymbols.clear(); 1226 SDCallSiteDbgInfo.clear(); 1227 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(), 1228 static_cast<CondCodeSDNode*>(nullptr)); 1229 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(), 1230 static_cast<SDNode*>(nullptr)); 1231 1232 EntryNode.UseList = nullptr; 1233 InsertNode(&EntryNode); 1234 Root = getEntryNode(); 1235 DbgInfo->clear(); 1236 } 1237 1238 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) { 1239 return VT.bitsGT(Op.getValueType()) 1240 ? getNode(ISD::FP_EXTEND, DL, VT, Op) 1241 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL)); 1242 } 1243 1244 std::pair<SDValue, SDValue> 1245 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain, 1246 const SDLoc &DL, EVT VT) { 1247 assert(!VT.bitsEq(Op.getValueType()) && 1248 "Strict no-op FP extend/round not allowed."); 1249 SDValue Res = 1250 VT.bitsGT(Op.getValueType()) 1251 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op}) 1252 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other}, 1253 {Chain, Op, getIntPtrConstant(0, DL)}); 1254 1255 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1)); 1256 } 1257 1258 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1259 return VT.bitsGT(Op.getValueType()) ? 1260 getNode(ISD::ANY_EXTEND, DL, VT, Op) : 1261 getNode(ISD::TRUNCATE, DL, VT, Op); 1262 } 1263 1264 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1265 return VT.bitsGT(Op.getValueType()) ? 1266 getNode(ISD::SIGN_EXTEND, DL, VT, Op) : 1267 getNode(ISD::TRUNCATE, DL, VT, Op); 1268 } 1269 1270 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1271 return VT.bitsGT(Op.getValueType()) ? 1272 getNode(ISD::ZERO_EXTEND, DL, VT, Op) : 1273 getNode(ISD::TRUNCATE, DL, VT, Op); 1274 } 1275 1276 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, 1277 EVT OpVT) { 1278 if (VT.bitsLE(Op.getValueType())) 1279 return getNode(ISD::TRUNCATE, SL, VT, Op); 1280 1281 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT); 1282 return getNode(TLI->getExtendForContent(BType), SL, VT, Op); 1283 } 1284 1285 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1286 EVT OpVT = Op.getValueType(); 1287 assert(VT.isInteger() && OpVT.isInteger() && 1288 "Cannot getZeroExtendInReg FP types"); 1289 assert(VT.isVector() == OpVT.isVector() && 1290 "getZeroExtendInReg type should be vector iff the operand " 1291 "type is vector!"); 1292 assert((!VT.isVector() || 1293 VT.getVectorElementCount() == OpVT.getVectorElementCount()) && 1294 "Vector element counts must match in getZeroExtendInReg"); 1295 assert(VT.bitsLE(OpVT) && "Not extending!"); 1296 if (OpVT == VT) 1297 return Op; 1298 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(), 1299 VT.getScalarSizeInBits()); 1300 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT)); 1301 } 1302 1303 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) { 1304 // Only unsigned pointer semantics are supported right now. In the future this 1305 // might delegate to TLI to check pointer signedness. 1306 return getZExtOrTrunc(Op, DL, VT); 1307 } 1308 1309 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) { 1310 // Only unsigned pointer semantics are supported right now. In the future this 1311 // might delegate to TLI to check pointer signedness. 1312 return getZeroExtendInReg(Op, DL, VT); 1313 } 1314 1315 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1). 1316 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1317 EVT EltVT = VT.getScalarType(); 1318 SDValue NegOne = 1319 getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT); 1320 return getNode(ISD::XOR, DL, VT, Val, NegOne); 1321 } 1322 1323 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) { 1324 SDValue TrueValue = getBoolConstant(true, DL, VT, VT); 1325 return getNode(ISD::XOR, DL, VT, Val, TrueValue); 1326 } 1327 1328 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT, 1329 EVT OpVT) { 1330 if (!V) 1331 return getConstant(0, DL, VT); 1332 1333 switch (TLI->getBooleanContents(OpVT)) { 1334 case TargetLowering::ZeroOrOneBooleanContent: 1335 case TargetLowering::UndefinedBooleanContent: 1336 return getConstant(1, DL, VT); 1337 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1338 return getAllOnesConstant(DL, VT); 1339 } 1340 llvm_unreachable("Unexpected boolean content enum!"); 1341 } 1342 1343 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT, 1344 bool isT, bool isO) { 1345 EVT EltVT = VT.getScalarType(); 1346 assert((EltVT.getSizeInBits() >= 64 || 1347 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) && 1348 "getConstant with a uint64_t value that doesn't fit in the type!"); 1349 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO); 1350 } 1351 1352 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT, 1353 bool isT, bool isO) { 1354 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO); 1355 } 1356 1357 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL, 1358 EVT VT, bool isT, bool isO) { 1359 assert(VT.isInteger() && "Cannot create FP integer constant!"); 1360 1361 EVT EltVT = VT.getScalarType(); 1362 const ConstantInt *Elt = &Val; 1363 1364 // In some cases the vector type is legal but the element type is illegal and 1365 // needs to be promoted, for example v8i8 on ARM. In this case, promote the 1366 // inserted value (the type does not need to match the vector element type). 1367 // Any extra bits introduced will be truncated away. 1368 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) == 1369 TargetLowering::TypePromoteInteger) { 1370 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1371 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits()); 1372 Elt = ConstantInt::get(*getContext(), NewVal); 1373 } 1374 // In other cases the element type is illegal and needs to be expanded, for 1375 // example v2i64 on MIPS32. In this case, find the nearest legal type, split 1376 // the value into n parts and use a vector type with n-times the elements. 1377 // Then bitcast to the type requested. 1378 // Legalizing constants too early makes the DAGCombiner's job harder so we 1379 // only legalize if the DAG tells us we must produce legal types. 1380 else if (NewNodesMustHaveLegalTypes && VT.isVector() && 1381 TLI->getTypeAction(*getContext(), EltVT) == 1382 TargetLowering::TypeExpandInteger) { 1383 const APInt &NewVal = Elt->getValue(); 1384 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT); 1385 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits(); 1386 1387 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node. 1388 if (VT.isScalableVector()) { 1389 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 && 1390 "Can only handle an even split!"); 1391 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits; 1392 1393 SmallVector<SDValue, 2> ScalarParts; 1394 for (unsigned i = 0; i != Parts; ++i) 1395 ScalarParts.push_back(getConstant( 1396 NewVal.lshr(i * ViaEltSizeInBits).trunc(ViaEltSizeInBits), DL, 1397 ViaEltVT, isT, isO)); 1398 1399 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts); 1400 } 1401 1402 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits; 1403 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts); 1404 1405 // Check the temporary vector is the correct size. If this fails then 1406 // getTypeToTransformTo() probably returned a type whose size (in bits) 1407 // isn't a power-of-2 factor of the requested type size. 1408 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits()); 1409 1410 SmallVector<SDValue, 2> EltParts; 1411 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) { 1412 EltParts.push_back(getConstant( 1413 NewVal.lshr(i * ViaEltSizeInBits).zextOrTrunc(ViaEltSizeInBits), DL, 1414 ViaEltVT, isT, isO)); 1415 } 1416 1417 // EltParts is currently in little endian order. If we actually want 1418 // big-endian order then reverse it now. 1419 if (getDataLayout().isBigEndian()) 1420 std::reverse(EltParts.begin(), EltParts.end()); 1421 1422 // The elements must be reversed when the element order is different 1423 // to the endianness of the elements (because the BITCAST is itself a 1424 // vector shuffle in this situation). However, we do not need any code to 1425 // perform this reversal because getConstant() is producing a vector 1426 // splat. 1427 // This situation occurs in MIPS MSA. 1428 1429 SmallVector<SDValue, 8> Ops; 1430 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) 1431 llvm::append_range(Ops, EltParts); 1432 1433 SDValue V = 1434 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops)); 1435 return V; 1436 } 1437 1438 assert(Elt->getBitWidth() == EltVT.getSizeInBits() && 1439 "APInt size does not match type size!"); 1440 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant; 1441 FoldingSetNodeID ID; 1442 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1443 ID.AddPointer(Elt); 1444 ID.AddBoolean(isO); 1445 void *IP = nullptr; 1446 SDNode *N = nullptr; 1447 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1448 if (!VT.isVector()) 1449 return SDValue(N, 0); 1450 1451 if (!N) { 1452 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT); 1453 CSEMap.InsertNode(N, IP); 1454 InsertNode(N); 1455 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this); 1456 } 1457 1458 SDValue Result(N, 0); 1459 if (VT.isScalableVector()) 1460 Result = getSplatVector(VT, DL, Result); 1461 else if (VT.isVector()) 1462 Result = getSplatBuildVector(VT, DL, Result); 1463 1464 return Result; 1465 } 1466 1467 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL, 1468 bool isTarget) { 1469 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget); 1470 } 1471 1472 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT, 1473 const SDLoc &DL, bool LegalTypes) { 1474 assert(VT.isInteger() && "Shift amount is not an integer type!"); 1475 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes); 1476 return getConstant(Val, DL, ShiftVT); 1477 } 1478 1479 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL, 1480 bool isTarget) { 1481 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget); 1482 } 1483 1484 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT, 1485 bool isTarget) { 1486 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget); 1487 } 1488 1489 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL, 1490 EVT VT, bool isTarget) { 1491 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!"); 1492 1493 EVT EltVT = VT.getScalarType(); 1494 1495 // Do the map lookup using the actual bit pattern for the floating point 1496 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and 1497 // we don't have issues with SNANs. 1498 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP; 1499 FoldingSetNodeID ID; 1500 AddNodeIDNode(ID, Opc, getVTList(EltVT), None); 1501 ID.AddPointer(&V); 1502 void *IP = nullptr; 1503 SDNode *N = nullptr; 1504 if ((N = FindNodeOrInsertPos(ID, DL, IP))) 1505 if (!VT.isVector()) 1506 return SDValue(N, 0); 1507 1508 if (!N) { 1509 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT); 1510 CSEMap.InsertNode(N, IP); 1511 InsertNode(N); 1512 } 1513 1514 SDValue Result(N, 0); 1515 if (VT.isScalableVector()) 1516 Result = getSplatVector(VT, DL, Result); 1517 else if (VT.isVector()) 1518 Result = getSplatBuildVector(VT, DL, Result); 1519 NewSDValueDbgMsg(Result, "Creating fp constant: ", this); 1520 return Result; 1521 } 1522 1523 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT, 1524 bool isTarget) { 1525 EVT EltVT = VT.getScalarType(); 1526 if (EltVT == MVT::f32) 1527 return getConstantFP(APFloat((float)Val), DL, VT, isTarget); 1528 else if (EltVT == MVT::f64) 1529 return getConstantFP(APFloat(Val), DL, VT, isTarget); 1530 else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 || 1531 EltVT == MVT::f16 || EltVT == MVT::bf16) { 1532 bool Ignored; 1533 APFloat APF = APFloat(Val); 1534 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven, 1535 &Ignored); 1536 return getConstantFP(APF, DL, VT, isTarget); 1537 } else 1538 llvm_unreachable("Unsupported type in getConstantFP"); 1539 } 1540 1541 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, 1542 EVT VT, int64_t Offset, bool isTargetGA, 1543 unsigned TargetFlags) { 1544 assert((TargetFlags == 0 || isTargetGA) && 1545 "Cannot set target flags on target-independent globals"); 1546 1547 // Truncate (with sign-extension) the offset value to the pointer size. 1548 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 1549 if (BitWidth < 64) 1550 Offset = SignExtend64(Offset, BitWidth); 1551 1552 unsigned Opc; 1553 if (GV->isThreadLocal()) 1554 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress; 1555 else 1556 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress; 1557 1558 FoldingSetNodeID ID; 1559 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1560 ID.AddPointer(GV); 1561 ID.AddInteger(Offset); 1562 ID.AddInteger(TargetFlags); 1563 void *IP = nullptr; 1564 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 1565 return SDValue(E, 0); 1566 1567 auto *N = newSDNode<GlobalAddressSDNode>( 1568 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags); 1569 CSEMap.InsertNode(N, IP); 1570 InsertNode(N); 1571 return SDValue(N, 0); 1572 } 1573 1574 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) { 1575 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex; 1576 FoldingSetNodeID ID; 1577 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1578 ID.AddInteger(FI); 1579 void *IP = nullptr; 1580 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1581 return SDValue(E, 0); 1582 1583 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget); 1584 CSEMap.InsertNode(N, IP); 1585 InsertNode(N); 1586 return SDValue(N, 0); 1587 } 1588 1589 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget, 1590 unsigned TargetFlags) { 1591 assert((TargetFlags == 0 || isTarget) && 1592 "Cannot set target flags on target-independent jump tables"); 1593 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable; 1594 FoldingSetNodeID ID; 1595 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1596 ID.AddInteger(JTI); 1597 ID.AddInteger(TargetFlags); 1598 void *IP = nullptr; 1599 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1600 return SDValue(E, 0); 1601 1602 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags); 1603 CSEMap.InsertNode(N, IP); 1604 InsertNode(N); 1605 return SDValue(N, 0); 1606 } 1607 1608 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT, 1609 MaybeAlign Alignment, int Offset, 1610 bool isTarget, unsigned TargetFlags) { 1611 assert((TargetFlags == 0 || isTarget) && 1612 "Cannot set target flags on target-independent globals"); 1613 if (!Alignment) 1614 Alignment = shouldOptForSize() 1615 ? getDataLayout().getABITypeAlign(C->getType()) 1616 : getDataLayout().getPrefTypeAlign(C->getType()); 1617 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1618 FoldingSetNodeID ID; 1619 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1620 ID.AddInteger(Alignment->value()); 1621 ID.AddInteger(Offset); 1622 ID.AddPointer(C); 1623 ID.AddInteger(TargetFlags); 1624 void *IP = nullptr; 1625 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1626 return SDValue(E, 0); 1627 1628 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1629 TargetFlags); 1630 CSEMap.InsertNode(N, IP); 1631 InsertNode(N); 1632 SDValue V = SDValue(N, 0); 1633 NewSDValueDbgMsg(V, "Creating new constant pool: ", this); 1634 return V; 1635 } 1636 1637 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT, 1638 MaybeAlign Alignment, int Offset, 1639 bool isTarget, unsigned TargetFlags) { 1640 assert((TargetFlags == 0 || isTarget) && 1641 "Cannot set target flags on target-independent globals"); 1642 if (!Alignment) 1643 Alignment = getDataLayout().getPrefTypeAlign(C->getType()); 1644 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool; 1645 FoldingSetNodeID ID; 1646 AddNodeIDNode(ID, Opc, getVTList(VT), None); 1647 ID.AddInteger(Alignment->value()); 1648 ID.AddInteger(Offset); 1649 C->addSelectionDAGCSEId(ID); 1650 ID.AddInteger(TargetFlags); 1651 void *IP = nullptr; 1652 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1653 return SDValue(E, 0); 1654 1655 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment, 1656 TargetFlags); 1657 CSEMap.InsertNode(N, IP); 1658 InsertNode(N); 1659 return SDValue(N, 0); 1660 } 1661 1662 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset, 1663 unsigned TargetFlags) { 1664 FoldingSetNodeID ID; 1665 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None); 1666 ID.AddInteger(Index); 1667 ID.AddInteger(Offset); 1668 ID.AddInteger(TargetFlags); 1669 void *IP = nullptr; 1670 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1671 return SDValue(E, 0); 1672 1673 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags); 1674 CSEMap.InsertNode(N, IP); 1675 InsertNode(N); 1676 return SDValue(N, 0); 1677 } 1678 1679 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) { 1680 FoldingSetNodeID ID; 1681 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None); 1682 ID.AddPointer(MBB); 1683 void *IP = nullptr; 1684 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1685 return SDValue(E, 0); 1686 1687 auto *N = newSDNode<BasicBlockSDNode>(MBB); 1688 CSEMap.InsertNode(N, IP); 1689 InsertNode(N); 1690 return SDValue(N, 0); 1691 } 1692 1693 SDValue SelectionDAG::getValueType(EVT VT) { 1694 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >= 1695 ValueTypeNodes.size()) 1696 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1); 1697 1698 SDNode *&N = VT.isExtended() ? 1699 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy]; 1700 1701 if (N) return SDValue(N, 0); 1702 N = newSDNode<VTSDNode>(VT); 1703 InsertNode(N); 1704 return SDValue(N, 0); 1705 } 1706 1707 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) { 1708 SDNode *&N = ExternalSymbols[Sym]; 1709 if (N) return SDValue(N, 0); 1710 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT); 1711 InsertNode(N); 1712 return SDValue(N, 0); 1713 } 1714 1715 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) { 1716 SDNode *&N = MCSymbols[Sym]; 1717 if (N) 1718 return SDValue(N, 0); 1719 N = newSDNode<MCSymbolSDNode>(Sym, VT); 1720 InsertNode(N); 1721 return SDValue(N, 0); 1722 } 1723 1724 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT, 1725 unsigned TargetFlags) { 1726 SDNode *&N = 1727 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)]; 1728 if (N) return SDValue(N, 0); 1729 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT); 1730 InsertNode(N); 1731 return SDValue(N, 0); 1732 } 1733 1734 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) { 1735 if ((unsigned)Cond >= CondCodeNodes.size()) 1736 CondCodeNodes.resize(Cond+1); 1737 1738 if (!CondCodeNodes[Cond]) { 1739 auto *N = newSDNode<CondCodeSDNode>(Cond); 1740 CondCodeNodes[Cond] = N; 1741 InsertNode(N); 1742 } 1743 1744 return SDValue(CondCodeNodes[Cond], 0); 1745 } 1746 1747 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, SDValue Step) { 1748 if (ResVT.isScalableVector()) 1749 return getNode(ISD::STEP_VECTOR, DL, ResVT, Step); 1750 1751 EVT OpVT = Step.getValueType(); 1752 APInt StepVal = cast<ConstantSDNode>(Step)->getAPIntValue(); 1753 SmallVector<SDValue, 16> OpsStepConstants; 1754 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++) 1755 OpsStepConstants.push_back(getConstant(StepVal * i, DL, OpVT)); 1756 return getBuildVector(ResVT, DL, OpsStepConstants); 1757 } 1758 1759 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that 1760 /// point at N1 to point at N2 and indices that point at N2 to point at N1. 1761 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) { 1762 std::swap(N1, N2); 1763 ShuffleVectorSDNode::commuteMask(M); 1764 } 1765 1766 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, 1767 SDValue N2, ArrayRef<int> Mask) { 1768 assert(VT.getVectorNumElements() == Mask.size() && 1769 "Must have the same number of vector elements as mask elements!"); 1770 assert(VT == N1.getValueType() && VT == N2.getValueType() && 1771 "Invalid VECTOR_SHUFFLE"); 1772 1773 // Canonicalize shuffle undef, undef -> undef 1774 if (N1.isUndef() && N2.isUndef()) 1775 return getUNDEF(VT); 1776 1777 // Validate that all indices in Mask are within the range of the elements 1778 // input to the shuffle. 1779 int NElts = Mask.size(); 1780 assert(llvm::all_of(Mask, 1781 [&](int M) { return M < (NElts * 2) && M >= -1; }) && 1782 "Index out of range"); 1783 1784 // Copy the mask so we can do any needed cleanup. 1785 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end()); 1786 1787 // Canonicalize shuffle v, v -> v, undef 1788 if (N1 == N2) { 1789 N2 = getUNDEF(VT); 1790 for (int i = 0; i != NElts; ++i) 1791 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts; 1792 } 1793 1794 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 1795 if (N1.isUndef()) 1796 commuteShuffle(N1, N2, MaskVec); 1797 1798 if (TLI->hasVectorBlend()) { 1799 // If shuffling a splat, try to blend the splat instead. We do this here so 1800 // that even when this arises during lowering we don't have to re-handle it. 1801 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) { 1802 BitVector UndefElements; 1803 SDValue Splat = BV->getSplatValue(&UndefElements); 1804 if (!Splat) 1805 return; 1806 1807 for (int i = 0; i < NElts; ++i) { 1808 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts)) 1809 continue; 1810 1811 // If this input comes from undef, mark it as such. 1812 if (UndefElements[MaskVec[i] - Offset]) { 1813 MaskVec[i] = -1; 1814 continue; 1815 } 1816 1817 // If we can blend a non-undef lane, use that instead. 1818 if (!UndefElements[i]) 1819 MaskVec[i] = i + Offset; 1820 } 1821 }; 1822 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1)) 1823 BlendSplat(N1BV, 0); 1824 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2)) 1825 BlendSplat(N2BV, NElts); 1826 } 1827 1828 // Canonicalize all index into lhs, -> shuffle lhs, undef 1829 // Canonicalize all index into rhs, -> shuffle rhs, undef 1830 bool AllLHS = true, AllRHS = true; 1831 bool N2Undef = N2.isUndef(); 1832 for (int i = 0; i != NElts; ++i) { 1833 if (MaskVec[i] >= NElts) { 1834 if (N2Undef) 1835 MaskVec[i] = -1; 1836 else 1837 AllLHS = false; 1838 } else if (MaskVec[i] >= 0) { 1839 AllRHS = false; 1840 } 1841 } 1842 if (AllLHS && AllRHS) 1843 return getUNDEF(VT); 1844 if (AllLHS && !N2Undef) 1845 N2 = getUNDEF(VT); 1846 if (AllRHS) { 1847 N1 = getUNDEF(VT); 1848 commuteShuffle(N1, N2, MaskVec); 1849 } 1850 // Reset our undef status after accounting for the mask. 1851 N2Undef = N2.isUndef(); 1852 // Re-check whether both sides ended up undef. 1853 if (N1.isUndef() && N2Undef) 1854 return getUNDEF(VT); 1855 1856 // If Identity shuffle return that node. 1857 bool Identity = true, AllSame = true; 1858 for (int i = 0; i != NElts; ++i) { 1859 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false; 1860 if (MaskVec[i] != MaskVec[0]) AllSame = false; 1861 } 1862 if (Identity && NElts) 1863 return N1; 1864 1865 // Shuffling a constant splat doesn't change the result. 1866 if (N2Undef) { 1867 SDValue V = N1; 1868 1869 // Look through any bitcasts. We check that these don't change the number 1870 // (and size) of elements and just changes their types. 1871 while (V.getOpcode() == ISD::BITCAST) 1872 V = V->getOperand(0); 1873 1874 // A splat should always show up as a build vector node. 1875 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) { 1876 BitVector UndefElements; 1877 SDValue Splat = BV->getSplatValue(&UndefElements); 1878 // If this is a splat of an undef, shuffling it is also undef. 1879 if (Splat && Splat.isUndef()) 1880 return getUNDEF(VT); 1881 1882 bool SameNumElts = 1883 V.getValueType().getVectorNumElements() == VT.getVectorNumElements(); 1884 1885 // We only have a splat which can skip shuffles if there is a splatted 1886 // value and no undef lanes rearranged by the shuffle. 1887 if (Splat && UndefElements.none()) { 1888 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the 1889 // number of elements match or the value splatted is a zero constant. 1890 if (SameNumElts) 1891 return N1; 1892 if (auto *C = dyn_cast<ConstantSDNode>(Splat)) 1893 if (C->isNullValue()) 1894 return N1; 1895 } 1896 1897 // If the shuffle itself creates a splat, build the vector directly. 1898 if (AllSame && SameNumElts) { 1899 EVT BuildVT = BV->getValueType(0); 1900 const SDValue &Splatted = BV->getOperand(MaskVec[0]); 1901 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted); 1902 1903 // We may have jumped through bitcasts, so the type of the 1904 // BUILD_VECTOR may not match the type of the shuffle. 1905 if (BuildVT != VT) 1906 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV); 1907 return NewBV; 1908 } 1909 } 1910 } 1911 1912 FoldingSetNodeID ID; 1913 SDValue Ops[2] = { N1, N2 }; 1914 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops); 1915 for (int i = 0; i != NElts; ++i) 1916 ID.AddInteger(MaskVec[i]); 1917 1918 void* IP = nullptr; 1919 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 1920 return SDValue(E, 0); 1921 1922 // Allocate the mask array for the node out of the BumpPtrAllocator, since 1923 // SDNode doesn't have access to it. This memory will be "leaked" when 1924 // the node is deallocated, but recovered when the NodeAllocator is released. 1925 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts); 1926 llvm::copy(MaskVec, MaskAlloc); 1927 1928 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(), 1929 dl.getDebugLoc(), MaskAlloc); 1930 createOperands(N, Ops); 1931 1932 CSEMap.InsertNode(N, IP); 1933 InsertNode(N); 1934 SDValue V = SDValue(N, 0); 1935 NewSDValueDbgMsg(V, "Creating new node: ", this); 1936 return V; 1937 } 1938 1939 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) { 1940 EVT VT = SV.getValueType(0); 1941 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end()); 1942 ShuffleVectorSDNode::commuteMask(MaskVec); 1943 1944 SDValue Op0 = SV.getOperand(0); 1945 SDValue Op1 = SV.getOperand(1); 1946 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec); 1947 } 1948 1949 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) { 1950 FoldingSetNodeID ID; 1951 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None); 1952 ID.AddInteger(RegNo); 1953 void *IP = nullptr; 1954 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1955 return SDValue(E, 0); 1956 1957 auto *N = newSDNode<RegisterSDNode>(RegNo, VT); 1958 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA); 1959 CSEMap.InsertNode(N, IP); 1960 InsertNode(N); 1961 return SDValue(N, 0); 1962 } 1963 1964 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) { 1965 FoldingSetNodeID ID; 1966 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None); 1967 ID.AddPointer(RegMask); 1968 void *IP = nullptr; 1969 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1970 return SDValue(E, 0); 1971 1972 auto *N = newSDNode<RegisterMaskSDNode>(RegMask); 1973 CSEMap.InsertNode(N, IP); 1974 InsertNode(N); 1975 return SDValue(N, 0); 1976 } 1977 1978 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root, 1979 MCSymbol *Label) { 1980 return getLabelNode(ISD::EH_LABEL, dl, Root, Label); 1981 } 1982 1983 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl, 1984 SDValue Root, MCSymbol *Label) { 1985 FoldingSetNodeID ID; 1986 SDValue Ops[] = { Root }; 1987 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops); 1988 ID.AddPointer(Label); 1989 void *IP = nullptr; 1990 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 1991 return SDValue(E, 0); 1992 1993 auto *N = 1994 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label); 1995 createOperands(N, Ops); 1996 1997 CSEMap.InsertNode(N, IP); 1998 InsertNode(N); 1999 return SDValue(N, 0); 2000 } 2001 2002 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT, 2003 int64_t Offset, bool isTarget, 2004 unsigned TargetFlags) { 2005 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress; 2006 2007 FoldingSetNodeID ID; 2008 AddNodeIDNode(ID, Opc, getVTList(VT), None); 2009 ID.AddPointer(BA); 2010 ID.AddInteger(Offset); 2011 ID.AddInteger(TargetFlags); 2012 void *IP = nullptr; 2013 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2014 return SDValue(E, 0); 2015 2016 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags); 2017 CSEMap.InsertNode(N, IP); 2018 InsertNode(N); 2019 return SDValue(N, 0); 2020 } 2021 2022 SDValue SelectionDAG::getSrcValue(const Value *V) { 2023 FoldingSetNodeID ID; 2024 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None); 2025 ID.AddPointer(V); 2026 2027 void *IP = nullptr; 2028 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2029 return SDValue(E, 0); 2030 2031 auto *N = newSDNode<SrcValueSDNode>(V); 2032 CSEMap.InsertNode(N, IP); 2033 InsertNode(N); 2034 return SDValue(N, 0); 2035 } 2036 2037 SDValue SelectionDAG::getMDNode(const MDNode *MD) { 2038 FoldingSetNodeID ID; 2039 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None); 2040 ID.AddPointer(MD); 2041 2042 void *IP = nullptr; 2043 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) 2044 return SDValue(E, 0); 2045 2046 auto *N = newSDNode<MDNodeSDNode>(MD); 2047 CSEMap.InsertNode(N, IP); 2048 InsertNode(N); 2049 return SDValue(N, 0); 2050 } 2051 2052 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) { 2053 if (VT == V.getValueType()) 2054 return V; 2055 2056 return getNode(ISD::BITCAST, SDLoc(V), VT, V); 2057 } 2058 2059 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, 2060 unsigned SrcAS, unsigned DestAS) { 2061 SDValue Ops[] = {Ptr}; 2062 FoldingSetNodeID ID; 2063 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops); 2064 ID.AddInteger(SrcAS); 2065 ID.AddInteger(DestAS); 2066 2067 void *IP = nullptr; 2068 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 2069 return SDValue(E, 0); 2070 2071 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(), 2072 VT, SrcAS, DestAS); 2073 createOperands(N, Ops); 2074 2075 CSEMap.InsertNode(N, IP); 2076 InsertNode(N); 2077 return SDValue(N, 0); 2078 } 2079 2080 SDValue SelectionDAG::getFreeze(SDValue V) { 2081 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V); 2082 } 2083 2084 /// getShiftAmountOperand - Return the specified value casted to 2085 /// the target's desired shift amount type. 2086 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) { 2087 EVT OpTy = Op.getValueType(); 2088 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout()); 2089 if (OpTy == ShTy || OpTy.isVector()) return Op; 2090 2091 return getZExtOrTrunc(Op, SDLoc(Op), ShTy); 2092 } 2093 2094 SDValue SelectionDAG::expandVAArg(SDNode *Node) { 2095 SDLoc dl(Node); 2096 const TargetLowering &TLI = getTargetLoweringInfo(); 2097 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); 2098 EVT VT = Node->getValueType(0); 2099 SDValue Tmp1 = Node->getOperand(0); 2100 SDValue Tmp2 = Node->getOperand(1); 2101 const MaybeAlign MA(Node->getConstantOperandVal(3)); 2102 2103 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1, 2104 Tmp2, MachinePointerInfo(V)); 2105 SDValue VAList = VAListLoad; 2106 2107 if (MA && *MA > TLI.getMinStackArgumentAlignment()) { 2108 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2109 getConstant(MA->value() - 1, dl, VAList.getValueType())); 2110 2111 VAList = 2112 getNode(ISD::AND, dl, VAList.getValueType(), VAList, 2113 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType())); 2114 } 2115 2116 // Increment the pointer, VAList, to the next vaarg 2117 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList, 2118 getConstant(getDataLayout().getTypeAllocSize( 2119 VT.getTypeForEVT(*getContext())), 2120 dl, VAList.getValueType())); 2121 // Store the incremented VAList to the legalized pointer 2122 Tmp1 = 2123 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V)); 2124 // Load the actual argument out of the pointer VAList 2125 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo()); 2126 } 2127 2128 SDValue SelectionDAG::expandVACopy(SDNode *Node) { 2129 SDLoc dl(Node); 2130 const TargetLowering &TLI = getTargetLoweringInfo(); 2131 // This defaults to loading a pointer from the input and storing it to the 2132 // output, returning the chain. 2133 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue(); 2134 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue(); 2135 SDValue Tmp1 = 2136 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0), 2137 Node->getOperand(2), MachinePointerInfo(VS)); 2138 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), 2139 MachinePointerInfo(VD)); 2140 } 2141 2142 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) { 2143 const DataLayout &DL = getDataLayout(); 2144 Type *Ty = VT.getTypeForEVT(*getContext()); 2145 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2146 2147 if (TLI->isTypeLegal(VT) || !VT.isVector()) 2148 return RedAlign; 2149 2150 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2151 const Align StackAlign = TFI->getStackAlign(); 2152 2153 // See if we can choose a smaller ABI alignment in cases where it's an 2154 // illegal vector type that will get broken down. 2155 if (RedAlign > StackAlign) { 2156 EVT IntermediateVT; 2157 MVT RegisterVT; 2158 unsigned NumIntermediates; 2159 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT, 2160 NumIntermediates, RegisterVT); 2161 Ty = IntermediateVT.getTypeForEVT(*getContext()); 2162 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty); 2163 if (RedAlign2 < RedAlign) 2164 RedAlign = RedAlign2; 2165 } 2166 2167 return RedAlign; 2168 } 2169 2170 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) { 2171 MachineFrameInfo &MFI = MF->getFrameInfo(); 2172 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 2173 int StackID = 0; 2174 if (Bytes.isScalable()) 2175 StackID = TFI->getStackIDForScalableVectors(); 2176 // The stack id gives an indication of whether the object is scalable or 2177 // not, so it's safe to pass in the minimum size here. 2178 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment, 2179 false, nullptr, StackID); 2180 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout())); 2181 } 2182 2183 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) { 2184 Type *Ty = VT.getTypeForEVT(*getContext()); 2185 Align StackAlign = 2186 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign)); 2187 return CreateStackTemporary(VT.getStoreSize(), StackAlign); 2188 } 2189 2190 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) { 2191 TypeSize VT1Size = VT1.getStoreSize(); 2192 TypeSize VT2Size = VT2.getStoreSize(); 2193 assert(VT1Size.isScalable() == VT2Size.isScalable() && 2194 "Don't know how to choose the maximum size when creating a stack " 2195 "temporary"); 2196 TypeSize Bytes = 2197 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size; 2198 2199 Type *Ty1 = VT1.getTypeForEVT(*getContext()); 2200 Type *Ty2 = VT2.getTypeForEVT(*getContext()); 2201 const DataLayout &DL = getDataLayout(); 2202 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2)); 2203 return CreateStackTemporary(Bytes, Align); 2204 } 2205 2206 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2, 2207 ISD::CondCode Cond, const SDLoc &dl) { 2208 EVT OpVT = N1.getValueType(); 2209 2210 // These setcc operations always fold. 2211 switch (Cond) { 2212 default: break; 2213 case ISD::SETFALSE: 2214 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT); 2215 case ISD::SETTRUE: 2216 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT); 2217 2218 case ISD::SETOEQ: 2219 case ISD::SETOGT: 2220 case ISD::SETOGE: 2221 case ISD::SETOLT: 2222 case ISD::SETOLE: 2223 case ISD::SETONE: 2224 case ISD::SETO: 2225 case ISD::SETUO: 2226 case ISD::SETUEQ: 2227 case ISD::SETUNE: 2228 assert(!OpVT.isInteger() && "Illegal setcc for integer!"); 2229 break; 2230 } 2231 2232 if (OpVT.isInteger()) { 2233 // For EQ and NE, we can always pick a value for the undef to make the 2234 // predicate pass or fail, so we can return undef. 2235 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2236 // icmp eq/ne X, undef -> undef. 2237 if ((N1.isUndef() || N2.isUndef()) && 2238 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) 2239 return getUNDEF(VT); 2240 2241 // If both operands are undef, we can return undef for int comparison. 2242 // icmp undef, undef -> undef. 2243 if (N1.isUndef() && N2.isUndef()) 2244 return getUNDEF(VT); 2245 2246 // icmp X, X -> true/false 2247 // icmp X, undef -> true/false because undef could be X. 2248 if (N1 == N2) 2249 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT); 2250 } 2251 2252 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) { 2253 const APInt &C2 = N2C->getAPIntValue(); 2254 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) { 2255 const APInt &C1 = N1C->getAPIntValue(); 2256 2257 switch (Cond) { 2258 default: llvm_unreachable("Unknown integer setcc!"); 2259 case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT); 2260 case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT); 2261 case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT); 2262 case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT); 2263 case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT); 2264 case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT); 2265 case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT); 2266 case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT); 2267 case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT); 2268 case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT); 2269 } 2270 } 2271 } 2272 2273 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 2274 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 2275 2276 if (N1CFP && N2CFP) { 2277 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF()); 2278 switch (Cond) { 2279 default: break; 2280 case ISD::SETEQ: if (R==APFloat::cmpUnordered) 2281 return getUNDEF(VT); 2282 LLVM_FALLTHROUGH; 2283 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT, 2284 OpVT); 2285 case ISD::SETNE: if (R==APFloat::cmpUnordered) 2286 return getUNDEF(VT); 2287 LLVM_FALLTHROUGH; 2288 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2289 R==APFloat::cmpLessThan, dl, VT, 2290 OpVT); 2291 case ISD::SETLT: if (R==APFloat::cmpUnordered) 2292 return getUNDEF(VT); 2293 LLVM_FALLTHROUGH; 2294 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT, 2295 OpVT); 2296 case ISD::SETGT: if (R==APFloat::cmpUnordered) 2297 return getUNDEF(VT); 2298 LLVM_FALLTHROUGH; 2299 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl, 2300 VT, OpVT); 2301 case ISD::SETLE: if (R==APFloat::cmpUnordered) 2302 return getUNDEF(VT); 2303 LLVM_FALLTHROUGH; 2304 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan || 2305 R==APFloat::cmpEqual, dl, VT, 2306 OpVT); 2307 case ISD::SETGE: if (R==APFloat::cmpUnordered) 2308 return getUNDEF(VT); 2309 LLVM_FALLTHROUGH; 2310 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan || 2311 R==APFloat::cmpEqual, dl, VT, OpVT); 2312 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT, 2313 OpVT); 2314 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT, 2315 OpVT); 2316 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered || 2317 R==APFloat::cmpEqual, dl, VT, 2318 OpVT); 2319 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT, 2320 OpVT); 2321 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered || 2322 R==APFloat::cmpLessThan, dl, VT, 2323 OpVT); 2324 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan || 2325 R==APFloat::cmpUnordered, dl, VT, 2326 OpVT); 2327 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl, 2328 VT, OpVT); 2329 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT, 2330 OpVT); 2331 } 2332 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) { 2333 // Ensure that the constant occurs on the RHS. 2334 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond); 2335 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT())) 2336 return SDValue(); 2337 return getSetCC(dl, VT, N2, N1, SwappedCond); 2338 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) || 2339 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) { 2340 // If an operand is known to be a nan (or undef that could be a nan), we can 2341 // fold it. 2342 // Choosing NaN for the undef will always make unordered comparison succeed 2343 // and ordered comparison fails. 2344 // Matches behavior in llvm::ConstantFoldCompareInstruction. 2345 switch (ISD::getUnorderedFlavor(Cond)) { 2346 default: 2347 llvm_unreachable("Unknown flavor!"); 2348 case 0: // Known false. 2349 return getBoolConstant(false, dl, VT, OpVT); 2350 case 1: // Known true. 2351 return getBoolConstant(true, dl, VT, OpVT); 2352 case 2: // Undefined. 2353 return getUNDEF(VT); 2354 } 2355 } 2356 2357 // Could not fold it. 2358 return SDValue(); 2359 } 2360 2361 /// See if the specified operand can be simplified with the knowledge that only 2362 /// the bits specified by DemandedBits are used. 2363 /// TODO: really we should be making this into the DAG equivalent of 2364 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2365 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) { 2366 EVT VT = V.getValueType(); 2367 2368 if (VT.isScalableVector()) 2369 return SDValue(); 2370 2371 APInt DemandedElts = VT.isVector() 2372 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2373 : APInt(1, 1); 2374 return GetDemandedBits(V, DemandedBits, DemandedElts); 2375 } 2376 2377 /// See if the specified operand can be simplified with the knowledge that only 2378 /// the bits specified by DemandedBits are used in the elements specified by 2379 /// DemandedElts. 2380 /// TODO: really we should be making this into the DAG equivalent of 2381 /// SimplifyMultipleUseDemandedBits and not generate any new nodes. 2382 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits, 2383 const APInt &DemandedElts) { 2384 switch (V.getOpcode()) { 2385 default: 2386 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts, 2387 *this, 0); 2388 case ISD::Constant: { 2389 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue(); 2390 APInt NewVal = CVal & DemandedBits; 2391 if (NewVal != CVal) 2392 return getConstant(NewVal, SDLoc(V), V.getValueType()); 2393 break; 2394 } 2395 case ISD::SRL: 2396 // Only look at single-use SRLs. 2397 if (!V.getNode()->hasOneUse()) 2398 break; 2399 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2400 // See if we can recursively simplify the LHS. 2401 unsigned Amt = RHSC->getZExtValue(); 2402 2403 // Watch out for shift count overflow though. 2404 if (Amt >= DemandedBits.getBitWidth()) 2405 break; 2406 APInt SrcDemandedBits = DemandedBits << Amt; 2407 if (SDValue SimplifyLHS = 2408 GetDemandedBits(V.getOperand(0), SrcDemandedBits)) 2409 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS, 2410 V.getOperand(1)); 2411 } 2412 break; 2413 } 2414 return SDValue(); 2415 } 2416 2417 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We 2418 /// use this predicate to simplify operations downstream. 2419 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const { 2420 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2421 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth); 2422 } 2423 2424 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use 2425 /// this predicate to simplify operations downstream. Mask is known to be zero 2426 /// for bits that V cannot have. 2427 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2428 unsigned Depth) const { 2429 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero); 2430 } 2431 2432 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in 2433 /// DemandedElts. We use this predicate to simplify operations downstream. 2434 /// Mask is known to be zero for bits that V cannot have. 2435 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask, 2436 const APInt &DemandedElts, 2437 unsigned Depth) const { 2438 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero); 2439 } 2440 2441 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'. 2442 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask, 2443 unsigned Depth) const { 2444 return Mask.isSubsetOf(computeKnownBits(V, Depth).One); 2445 } 2446 2447 /// isSplatValue - Return true if the vector V has the same value 2448 /// across all DemandedElts. For scalable vectors it does not make 2449 /// sense to specify which elements are demanded or undefined, therefore 2450 /// they are simply ignored. 2451 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts, 2452 APInt &UndefElts, unsigned Depth) { 2453 EVT VT = V.getValueType(); 2454 assert(VT.isVector() && "Vector type expected"); 2455 2456 if (!VT.isScalableVector() && !DemandedElts) 2457 return false; // No demanded elts, better to assume we don't know anything. 2458 2459 if (Depth >= MaxRecursionDepth) 2460 return false; // Limit search depth. 2461 2462 // Deal with some common cases here that work for both fixed and scalable 2463 // vector types. 2464 switch (V.getOpcode()) { 2465 case ISD::SPLAT_VECTOR: 2466 UndefElts = V.getOperand(0).isUndef() 2467 ? APInt::getAllOnesValue(DemandedElts.getBitWidth()) 2468 : APInt(DemandedElts.getBitWidth(), 0); 2469 return true; 2470 case ISD::ADD: 2471 case ISD::SUB: 2472 case ISD::AND: 2473 case ISD::XOR: 2474 case ISD::OR: { 2475 APInt UndefLHS, UndefRHS; 2476 SDValue LHS = V.getOperand(0); 2477 SDValue RHS = V.getOperand(1); 2478 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) && 2479 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) { 2480 UndefElts = UndefLHS | UndefRHS; 2481 return true; 2482 } 2483 break; 2484 } 2485 case ISD::ABS: 2486 case ISD::TRUNCATE: 2487 case ISD::SIGN_EXTEND: 2488 case ISD::ZERO_EXTEND: 2489 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1); 2490 } 2491 2492 // We don't support other cases than those above for scalable vectors at 2493 // the moment. 2494 if (VT.isScalableVector()) 2495 return false; 2496 2497 unsigned NumElts = VT.getVectorNumElements(); 2498 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch"); 2499 UndefElts = APInt::getNullValue(NumElts); 2500 2501 switch (V.getOpcode()) { 2502 case ISD::BUILD_VECTOR: { 2503 SDValue Scl; 2504 for (unsigned i = 0; i != NumElts; ++i) { 2505 SDValue Op = V.getOperand(i); 2506 if (Op.isUndef()) { 2507 UndefElts.setBit(i); 2508 continue; 2509 } 2510 if (!DemandedElts[i]) 2511 continue; 2512 if (Scl && Scl != Op) 2513 return false; 2514 Scl = Op; 2515 } 2516 return true; 2517 } 2518 case ISD::VECTOR_SHUFFLE: { 2519 // Check if this is a shuffle node doing a splat. 2520 // TODO: Do we need to handle shuffle(splat, undef, mask)? 2521 int SplatIndex = -1; 2522 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask(); 2523 for (int i = 0; i != (int)NumElts; ++i) { 2524 int M = Mask[i]; 2525 if (M < 0) { 2526 UndefElts.setBit(i); 2527 continue; 2528 } 2529 if (!DemandedElts[i]) 2530 continue; 2531 if (0 <= SplatIndex && SplatIndex != M) 2532 return false; 2533 SplatIndex = M; 2534 } 2535 return true; 2536 } 2537 case ISD::EXTRACT_SUBVECTOR: { 2538 // Offset the demanded elts by the subvector index. 2539 SDValue Src = V.getOperand(0); 2540 // We don't support scalable vectors at the moment. 2541 if (Src.getValueType().isScalableVector()) 2542 return false; 2543 uint64_t Idx = V.getConstantOperandVal(1); 2544 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2545 APInt UndefSrcElts; 2546 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2547 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) { 2548 UndefElts = UndefSrcElts.extractBits(NumElts, Idx); 2549 return true; 2550 } 2551 break; 2552 } 2553 } 2554 2555 return false; 2556 } 2557 2558 /// Helper wrapper to main isSplatValue function. 2559 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) { 2560 EVT VT = V.getValueType(); 2561 assert(VT.isVector() && "Vector type expected"); 2562 2563 APInt UndefElts; 2564 APInt DemandedElts; 2565 2566 // For now we don't support this with scalable vectors. 2567 if (!VT.isScalableVector()) 2568 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2569 return isSplatValue(V, DemandedElts, UndefElts) && 2570 (AllowUndefs || !UndefElts); 2571 } 2572 2573 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) { 2574 V = peekThroughExtractSubvectors(V); 2575 2576 EVT VT = V.getValueType(); 2577 unsigned Opcode = V.getOpcode(); 2578 switch (Opcode) { 2579 default: { 2580 APInt UndefElts; 2581 APInt DemandedElts; 2582 2583 if (!VT.isScalableVector()) 2584 DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements()); 2585 2586 if (isSplatValue(V, DemandedElts, UndefElts)) { 2587 if (VT.isScalableVector()) { 2588 // DemandedElts and UndefElts are ignored for scalable vectors, since 2589 // the only supported cases are SPLAT_VECTOR nodes. 2590 SplatIdx = 0; 2591 } else { 2592 // Handle case where all demanded elements are UNDEF. 2593 if (DemandedElts.isSubsetOf(UndefElts)) { 2594 SplatIdx = 0; 2595 return getUNDEF(VT); 2596 } 2597 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes(); 2598 } 2599 return V; 2600 } 2601 break; 2602 } 2603 case ISD::SPLAT_VECTOR: 2604 SplatIdx = 0; 2605 return V; 2606 case ISD::VECTOR_SHUFFLE: { 2607 if (VT.isScalableVector()) 2608 return SDValue(); 2609 2610 // Check if this is a shuffle node doing a splat. 2611 // TODO - remove this and rely purely on SelectionDAG::isSplatValue, 2612 // getTargetVShiftNode currently struggles without the splat source. 2613 auto *SVN = cast<ShuffleVectorSDNode>(V); 2614 if (!SVN->isSplat()) 2615 break; 2616 int Idx = SVN->getSplatIndex(); 2617 int NumElts = V.getValueType().getVectorNumElements(); 2618 SplatIdx = Idx % NumElts; 2619 return V.getOperand(Idx / NumElts); 2620 } 2621 } 2622 2623 return SDValue(); 2624 } 2625 2626 SDValue SelectionDAG::getSplatValue(SDValue V) { 2627 int SplatIdx; 2628 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) 2629 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), 2630 SrcVector.getValueType().getScalarType(), SrcVector, 2631 getVectorIdxConstant(SplatIdx, SDLoc(V))); 2632 return SDValue(); 2633 } 2634 2635 const APInt * 2636 SelectionDAG::getValidShiftAmountConstant(SDValue V, 2637 const APInt &DemandedElts) const { 2638 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2639 V.getOpcode() == ISD::SRA) && 2640 "Unknown shift node"); 2641 unsigned BitWidth = V.getScalarValueSizeInBits(); 2642 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) { 2643 // Shifting more than the bitwidth is not valid. 2644 const APInt &ShAmt = SA->getAPIntValue(); 2645 if (ShAmt.ult(BitWidth)) 2646 return &ShAmt; 2647 } 2648 return nullptr; 2649 } 2650 2651 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant( 2652 SDValue V, const APInt &DemandedElts) const { 2653 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2654 V.getOpcode() == ISD::SRA) && 2655 "Unknown shift node"); 2656 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2657 return ValidAmt; 2658 unsigned BitWidth = V.getScalarValueSizeInBits(); 2659 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2660 if (!BV) 2661 return nullptr; 2662 const APInt *MinShAmt = nullptr; 2663 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2664 if (!DemandedElts[i]) 2665 continue; 2666 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2667 if (!SA) 2668 return nullptr; 2669 // Shifting more than the bitwidth is not valid. 2670 const APInt &ShAmt = SA->getAPIntValue(); 2671 if (ShAmt.uge(BitWidth)) 2672 return nullptr; 2673 if (MinShAmt && MinShAmt->ule(ShAmt)) 2674 continue; 2675 MinShAmt = &ShAmt; 2676 } 2677 return MinShAmt; 2678 } 2679 2680 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant( 2681 SDValue V, const APInt &DemandedElts) const { 2682 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL || 2683 V.getOpcode() == ISD::SRA) && 2684 "Unknown shift node"); 2685 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts)) 2686 return ValidAmt; 2687 unsigned BitWidth = V.getScalarValueSizeInBits(); 2688 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1)); 2689 if (!BV) 2690 return nullptr; 2691 const APInt *MaxShAmt = nullptr; 2692 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) { 2693 if (!DemandedElts[i]) 2694 continue; 2695 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i)); 2696 if (!SA) 2697 return nullptr; 2698 // Shifting more than the bitwidth is not valid. 2699 const APInt &ShAmt = SA->getAPIntValue(); 2700 if (ShAmt.uge(BitWidth)) 2701 return nullptr; 2702 if (MaxShAmt && MaxShAmt->uge(ShAmt)) 2703 continue; 2704 MaxShAmt = &ShAmt; 2705 } 2706 return MaxShAmt; 2707 } 2708 2709 /// Determine which bits of Op are known to be either zero or one and return 2710 /// them in Known. For vectors, the known bits are those that are shared by 2711 /// every vector element. 2712 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const { 2713 EVT VT = Op.getValueType(); 2714 2715 // TOOD: Until we have a plan for how to represent demanded elements for 2716 // scalable vectors, we can just bail out for now. 2717 if (Op.getValueType().isScalableVector()) { 2718 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2719 return KnownBits(BitWidth); 2720 } 2721 2722 APInt DemandedElts = VT.isVector() 2723 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 2724 : APInt(1, 1); 2725 return computeKnownBits(Op, DemandedElts, Depth); 2726 } 2727 2728 /// Determine which bits of Op are known to be either zero or one and return 2729 /// them in Known. The DemandedElts argument allows us to only collect the known 2730 /// bits that are shared by the requested vector elements. 2731 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts, 2732 unsigned Depth) const { 2733 unsigned BitWidth = Op.getScalarValueSizeInBits(); 2734 2735 KnownBits Known(BitWidth); // Don't know anything. 2736 2737 // TOOD: Until we have a plan for how to represent demanded elements for 2738 // scalable vectors, we can just bail out for now. 2739 if (Op.getValueType().isScalableVector()) 2740 return Known; 2741 2742 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 2743 // We know all of the bits for a constant! 2744 return KnownBits::makeConstant(C->getAPIntValue()); 2745 } 2746 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) { 2747 // We know all of the bits for a constant fp! 2748 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt()); 2749 } 2750 2751 if (Depth >= MaxRecursionDepth) 2752 return Known; // Limit search depth. 2753 2754 KnownBits Known2; 2755 unsigned NumElts = DemandedElts.getBitWidth(); 2756 assert((!Op.getValueType().isVector() || 2757 NumElts == Op.getValueType().getVectorNumElements()) && 2758 "Unexpected vector size"); 2759 2760 if (!DemandedElts) 2761 return Known; // No demanded elts, better to assume we don't know anything. 2762 2763 unsigned Opcode = Op.getOpcode(); 2764 switch (Opcode) { 2765 case ISD::BUILD_VECTOR: 2766 // Collect the known bits that are shared by every demanded vector element. 2767 Known.Zero.setAllBits(); Known.One.setAllBits(); 2768 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 2769 if (!DemandedElts[i]) 2770 continue; 2771 2772 SDValue SrcOp = Op.getOperand(i); 2773 Known2 = computeKnownBits(SrcOp, Depth + 1); 2774 2775 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 2776 if (SrcOp.getValueSizeInBits() != BitWidth) { 2777 assert(SrcOp.getValueSizeInBits() > BitWidth && 2778 "Expected BUILD_VECTOR implicit truncation"); 2779 Known2 = Known2.trunc(BitWidth); 2780 } 2781 2782 // Known bits are the values that are shared by every demanded element. 2783 Known = KnownBits::commonBits(Known, Known2); 2784 2785 // If we don't know any bits, early out. 2786 if (Known.isUnknown()) 2787 break; 2788 } 2789 break; 2790 case ISD::VECTOR_SHUFFLE: { 2791 // Collect the known bits that are shared by every vector element referenced 2792 // by the shuffle. 2793 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 2794 Known.Zero.setAllBits(); Known.One.setAllBits(); 2795 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 2796 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 2797 for (unsigned i = 0; i != NumElts; ++i) { 2798 if (!DemandedElts[i]) 2799 continue; 2800 2801 int M = SVN->getMaskElt(i); 2802 if (M < 0) { 2803 // For UNDEF elements, we don't know anything about the common state of 2804 // the shuffle result. 2805 Known.resetAll(); 2806 DemandedLHS.clearAllBits(); 2807 DemandedRHS.clearAllBits(); 2808 break; 2809 } 2810 2811 if ((unsigned)M < NumElts) 2812 DemandedLHS.setBit((unsigned)M % NumElts); 2813 else 2814 DemandedRHS.setBit((unsigned)M % NumElts); 2815 } 2816 // Known bits are the values that are shared by every demanded element. 2817 if (!!DemandedLHS) { 2818 SDValue LHS = Op.getOperand(0); 2819 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1); 2820 Known = KnownBits::commonBits(Known, Known2); 2821 } 2822 // If we don't know any bits, early out. 2823 if (Known.isUnknown()) 2824 break; 2825 if (!!DemandedRHS) { 2826 SDValue RHS = Op.getOperand(1); 2827 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1); 2828 Known = KnownBits::commonBits(Known, Known2); 2829 } 2830 break; 2831 } 2832 case ISD::CONCAT_VECTORS: { 2833 // Split DemandedElts and test each of the demanded subvectors. 2834 Known.Zero.setAllBits(); Known.One.setAllBits(); 2835 EVT SubVectorVT = Op.getOperand(0).getValueType(); 2836 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 2837 unsigned NumSubVectors = Op.getNumOperands(); 2838 for (unsigned i = 0; i != NumSubVectors; ++i) { 2839 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); 2840 DemandedSub = DemandedSub.trunc(NumSubVectorElts); 2841 if (!!DemandedSub) { 2842 SDValue Sub = Op.getOperand(i); 2843 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1); 2844 Known = KnownBits::commonBits(Known, Known2); 2845 } 2846 // If we don't know any bits, early out. 2847 if (Known.isUnknown()) 2848 break; 2849 } 2850 break; 2851 } 2852 case ISD::INSERT_SUBVECTOR: { 2853 // Demand any elements from the subvector and the remainder from the src its 2854 // inserted into. 2855 SDValue Src = Op.getOperand(0); 2856 SDValue Sub = Op.getOperand(1); 2857 uint64_t Idx = Op.getConstantOperandVal(2); 2858 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 2859 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 2860 APInt DemandedSrcElts = DemandedElts; 2861 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 2862 2863 Known.One.setAllBits(); 2864 Known.Zero.setAllBits(); 2865 if (!!DemandedSubElts) { 2866 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1); 2867 if (Known.isUnknown()) 2868 break; // early-out. 2869 } 2870 if (!!DemandedSrcElts) { 2871 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2872 Known = KnownBits::commonBits(Known, Known2); 2873 } 2874 break; 2875 } 2876 case ISD::EXTRACT_SUBVECTOR: { 2877 // Offset the demanded elts by the subvector index. 2878 SDValue Src = Op.getOperand(0); 2879 // Bail until we can represent demanded elements for scalable vectors. 2880 if (Src.getValueType().isScalableVector()) 2881 break; 2882 uint64_t Idx = Op.getConstantOperandVal(1); 2883 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 2884 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 2885 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1); 2886 break; 2887 } 2888 case ISD::SCALAR_TO_VECTOR: { 2889 // We know about scalar_to_vector as much as we know about it source, 2890 // which becomes the first element of otherwise unknown vector. 2891 if (DemandedElts != 1) 2892 break; 2893 2894 SDValue N0 = Op.getOperand(0); 2895 Known = computeKnownBits(N0, Depth + 1); 2896 if (N0.getValueSizeInBits() != BitWidth) 2897 Known = Known.trunc(BitWidth); 2898 2899 break; 2900 } 2901 case ISD::BITCAST: { 2902 SDValue N0 = Op.getOperand(0); 2903 EVT SubVT = N0.getValueType(); 2904 unsigned SubBitWidth = SubVT.getScalarSizeInBits(); 2905 2906 // Ignore bitcasts from unsupported types. 2907 if (!(SubVT.isInteger() || SubVT.isFloatingPoint())) 2908 break; 2909 2910 // Fast handling of 'identity' bitcasts. 2911 if (BitWidth == SubBitWidth) { 2912 Known = computeKnownBits(N0, DemandedElts, Depth + 1); 2913 break; 2914 } 2915 2916 bool IsLE = getDataLayout().isLittleEndian(); 2917 2918 // Bitcast 'small element' vector to 'large element' scalar/vector. 2919 if ((BitWidth % SubBitWidth) == 0) { 2920 assert(N0.getValueType().isVector() && "Expected bitcast from vector"); 2921 2922 // Collect known bits for the (larger) output by collecting the known 2923 // bits from each set of sub elements and shift these into place. 2924 // We need to separately call computeKnownBits for each set of 2925 // sub elements as the knownbits for each is likely to be different. 2926 unsigned SubScale = BitWidth / SubBitWidth; 2927 APInt SubDemandedElts(NumElts * SubScale, 0); 2928 for (unsigned i = 0; i != NumElts; ++i) 2929 if (DemandedElts[i]) 2930 SubDemandedElts.setBit(i * SubScale); 2931 2932 for (unsigned i = 0; i != SubScale; ++i) { 2933 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i), 2934 Depth + 1); 2935 unsigned Shifts = IsLE ? i : SubScale - 1 - i; 2936 Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts); 2937 Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts); 2938 } 2939 } 2940 2941 // Bitcast 'large element' scalar/vector to 'small element' vector. 2942 if ((SubBitWidth % BitWidth) == 0) { 2943 assert(Op.getValueType().isVector() && "Expected bitcast to vector"); 2944 2945 // Collect known bits for the (smaller) output by collecting the known 2946 // bits from the overlapping larger input elements and extracting the 2947 // sub sections we actually care about. 2948 unsigned SubScale = SubBitWidth / BitWidth; 2949 APInt SubDemandedElts(NumElts / SubScale, 0); 2950 for (unsigned i = 0; i != NumElts; ++i) 2951 if (DemandedElts[i]) 2952 SubDemandedElts.setBit(i / SubScale); 2953 2954 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1); 2955 2956 Known.Zero.setAllBits(); Known.One.setAllBits(); 2957 for (unsigned i = 0; i != NumElts; ++i) 2958 if (DemandedElts[i]) { 2959 unsigned Shifts = IsLE ? i : NumElts - 1 - i; 2960 unsigned Offset = (Shifts % SubScale) * BitWidth; 2961 Known.One &= Known2.One.lshr(Offset).trunc(BitWidth); 2962 Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth); 2963 // If we don't know any bits, early out. 2964 if (Known.isUnknown()) 2965 break; 2966 } 2967 } 2968 break; 2969 } 2970 case ISD::AND: 2971 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2972 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2973 2974 Known &= Known2; 2975 break; 2976 case ISD::OR: 2977 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2978 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2979 2980 Known |= Known2; 2981 break; 2982 case ISD::XOR: 2983 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2984 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2985 2986 Known ^= Known2; 2987 break; 2988 case ISD::MUL: { 2989 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2990 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2991 Known = KnownBits::computeForMul(Known, Known2); 2992 break; 2993 } 2994 case ISD::MULHU: { 2995 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 2996 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 2997 Known = KnownBits::mulhu(Known, Known2); 2998 break; 2999 } 3000 case ISD::MULHS: { 3001 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3002 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3003 Known = KnownBits::mulhs(Known, Known2); 3004 break; 3005 } 3006 case ISD::UMUL_LOHI: { 3007 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3008 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3009 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3010 if (Op.getResNo() == 0) 3011 Known = KnownBits::computeForMul(Known, Known2); 3012 else 3013 Known = KnownBits::mulhu(Known, Known2); 3014 break; 3015 } 3016 case ISD::SMUL_LOHI: { 3017 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result"); 3018 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3019 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3020 if (Op.getResNo() == 0) 3021 Known = KnownBits::computeForMul(Known, Known2); 3022 else 3023 Known = KnownBits::mulhs(Known, Known2); 3024 break; 3025 } 3026 case ISD::UDIV: { 3027 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3028 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3029 Known = KnownBits::udiv(Known, Known2); 3030 break; 3031 } 3032 case ISD::SELECT: 3033 case ISD::VSELECT: 3034 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3035 // If we don't know any bits, early out. 3036 if (Known.isUnknown()) 3037 break; 3038 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1); 3039 3040 // Only known if known in both the LHS and RHS. 3041 Known = KnownBits::commonBits(Known, Known2); 3042 break; 3043 case ISD::SELECT_CC: 3044 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1); 3045 // If we don't know any bits, early out. 3046 if (Known.isUnknown()) 3047 break; 3048 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1); 3049 3050 // Only known if known in both the LHS and RHS. 3051 Known = KnownBits::commonBits(Known, Known2); 3052 break; 3053 case ISD::SMULO: 3054 case ISD::UMULO: 3055 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 3056 if (Op.getResNo() != 1) 3057 break; 3058 // The boolean result conforms to getBooleanContents. 3059 // If we know the result of a setcc has the top bits zero, use this info. 3060 // We know that we have an integer-based boolean since these operations 3061 // are only available for integer. 3062 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) == 3063 TargetLowering::ZeroOrOneBooleanContent && 3064 BitWidth > 1) 3065 Known.Zero.setBitsFrom(1); 3066 break; 3067 case ISD::SETCC: 3068 case ISD::STRICT_FSETCC: 3069 case ISD::STRICT_FSETCCS: { 3070 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3071 // If we know the result of a setcc has the top bits zero, use this info. 3072 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3073 TargetLowering::ZeroOrOneBooleanContent && 3074 BitWidth > 1) 3075 Known.Zero.setBitsFrom(1); 3076 break; 3077 } 3078 case ISD::SHL: 3079 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3080 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3081 Known = KnownBits::shl(Known, Known2); 3082 3083 // Minimum shift low bits are known zero. 3084 if (const APInt *ShMinAmt = 3085 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3086 Known.Zero.setLowBits(ShMinAmt->getZExtValue()); 3087 break; 3088 case ISD::SRL: 3089 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3090 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3091 Known = KnownBits::lshr(Known, Known2); 3092 3093 // Minimum shift high bits are known zero. 3094 if (const APInt *ShMinAmt = 3095 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3096 Known.Zero.setHighBits(ShMinAmt->getZExtValue()); 3097 break; 3098 case ISD::SRA: 3099 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3100 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3101 Known = KnownBits::ashr(Known, Known2); 3102 // TODO: Add minimum shift high known sign bits. 3103 break; 3104 case ISD::FSHL: 3105 case ISD::FSHR: 3106 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) { 3107 unsigned Amt = C->getAPIntValue().urem(BitWidth); 3108 3109 // For fshl, 0-shift returns the 1st arg. 3110 // For fshr, 0-shift returns the 2nd arg. 3111 if (Amt == 0) { 3112 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1), 3113 DemandedElts, Depth + 1); 3114 break; 3115 } 3116 3117 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 3118 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 3119 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3120 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3121 if (Opcode == ISD::FSHL) { 3122 Known.One <<= Amt; 3123 Known.Zero <<= Amt; 3124 Known2.One.lshrInPlace(BitWidth - Amt); 3125 Known2.Zero.lshrInPlace(BitWidth - Amt); 3126 } else { 3127 Known.One <<= BitWidth - Amt; 3128 Known.Zero <<= BitWidth - Amt; 3129 Known2.One.lshrInPlace(Amt); 3130 Known2.Zero.lshrInPlace(Amt); 3131 } 3132 Known.One |= Known2.One; 3133 Known.Zero |= Known2.Zero; 3134 } 3135 break; 3136 case ISD::SIGN_EXTEND_INREG: { 3137 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3138 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3139 Known = Known.sextInReg(EVT.getScalarSizeInBits()); 3140 break; 3141 } 3142 case ISD::CTTZ: 3143 case ISD::CTTZ_ZERO_UNDEF: { 3144 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3145 // If we have a known 1, its position is our upper bound. 3146 unsigned PossibleTZ = Known2.countMaxTrailingZeros(); 3147 unsigned LowBits = Log2_32(PossibleTZ) + 1; 3148 Known.Zero.setBitsFrom(LowBits); 3149 break; 3150 } 3151 case ISD::CTLZ: 3152 case ISD::CTLZ_ZERO_UNDEF: { 3153 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3154 // If we have a known 1, its position is our upper bound. 3155 unsigned PossibleLZ = Known2.countMaxLeadingZeros(); 3156 unsigned LowBits = Log2_32(PossibleLZ) + 1; 3157 Known.Zero.setBitsFrom(LowBits); 3158 break; 3159 } 3160 case ISD::CTPOP: { 3161 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3162 // If we know some of the bits are zero, they can't be one. 3163 unsigned PossibleOnes = Known2.countMaxPopulation(); 3164 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1); 3165 break; 3166 } 3167 case ISD::PARITY: { 3168 // Parity returns 0 everywhere but the LSB. 3169 Known.Zero.setBitsFrom(1); 3170 break; 3171 } 3172 case ISD::LOAD: { 3173 LoadSDNode *LD = cast<LoadSDNode>(Op); 3174 const Constant *Cst = TLI->getTargetConstantFromLoad(LD); 3175 if (ISD::isNON_EXTLoad(LD) && Cst) { 3176 // Determine any common known bits from the loaded constant pool value. 3177 Type *CstTy = Cst->getType(); 3178 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) { 3179 // If its a vector splat, then we can (quickly) reuse the scalar path. 3180 // NOTE: We assume all elements match and none are UNDEF. 3181 if (CstTy->isVectorTy()) { 3182 if (const Constant *Splat = Cst->getSplatValue()) { 3183 Cst = Splat; 3184 CstTy = Cst->getType(); 3185 } 3186 } 3187 // TODO - do we need to handle different bitwidths? 3188 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) { 3189 // Iterate across all vector elements finding common known bits. 3190 Known.One.setAllBits(); 3191 Known.Zero.setAllBits(); 3192 for (unsigned i = 0; i != NumElts; ++i) { 3193 if (!DemandedElts[i]) 3194 continue; 3195 if (Constant *Elt = Cst->getAggregateElement(i)) { 3196 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 3197 const APInt &Value = CInt->getValue(); 3198 Known.One &= Value; 3199 Known.Zero &= ~Value; 3200 continue; 3201 } 3202 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 3203 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 3204 Known.One &= Value; 3205 Known.Zero &= ~Value; 3206 continue; 3207 } 3208 } 3209 Known.One.clearAllBits(); 3210 Known.Zero.clearAllBits(); 3211 break; 3212 } 3213 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) { 3214 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) { 3215 Known = KnownBits::makeConstant(CInt->getValue()); 3216 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) { 3217 Known = 3218 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt()); 3219 } 3220 } 3221 } 3222 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) { 3223 // If this is a ZEXTLoad and we are looking at the loaded value. 3224 EVT VT = LD->getMemoryVT(); 3225 unsigned MemBits = VT.getScalarSizeInBits(); 3226 Known.Zero.setBitsFrom(MemBits); 3227 } else if (const MDNode *Ranges = LD->getRanges()) { 3228 if (LD->getExtensionType() == ISD::NON_EXTLOAD) 3229 computeKnownBitsFromRangeMetadata(*Ranges, Known); 3230 } 3231 break; 3232 } 3233 case ISD::ZERO_EXTEND_VECTOR_INREG: { 3234 EVT InVT = Op.getOperand(0).getValueType(); 3235 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3236 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3237 Known = Known.zext(BitWidth); 3238 break; 3239 } 3240 case ISD::ZERO_EXTEND: { 3241 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3242 Known = Known.zext(BitWidth); 3243 break; 3244 } 3245 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3246 EVT InVT = Op.getOperand(0).getValueType(); 3247 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3248 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3249 // If the sign bit is known to be zero or one, then sext will extend 3250 // it to the top bits, else it will just zext. 3251 Known = Known.sext(BitWidth); 3252 break; 3253 } 3254 case ISD::SIGN_EXTEND: { 3255 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3256 // If the sign bit is known to be zero or one, then sext will extend 3257 // it to the top bits, else it will just zext. 3258 Known = Known.sext(BitWidth); 3259 break; 3260 } 3261 case ISD::ANY_EXTEND_VECTOR_INREG: { 3262 EVT InVT = Op.getOperand(0).getValueType(); 3263 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements()); 3264 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1); 3265 Known = Known.anyext(BitWidth); 3266 break; 3267 } 3268 case ISD::ANY_EXTEND: { 3269 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3270 Known = Known.anyext(BitWidth); 3271 break; 3272 } 3273 case ISD::TRUNCATE: { 3274 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3275 Known = Known.trunc(BitWidth); 3276 break; 3277 } 3278 case ISD::AssertZext: { 3279 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 3280 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits()); 3281 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3282 Known.Zero |= (~InMask); 3283 Known.One &= (~Known.Zero); 3284 break; 3285 } 3286 case ISD::AssertAlign: { 3287 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign()); 3288 assert(LogOfAlign != 0); 3289 // If a node is guaranteed to be aligned, set low zero bits accordingly as 3290 // well as clearing one bits. 3291 Known.Zero.setLowBits(LogOfAlign); 3292 Known.One.clearLowBits(LogOfAlign); 3293 break; 3294 } 3295 case ISD::FGETSIGN: 3296 // All bits are zero except the low bit. 3297 Known.Zero.setBitsFrom(1); 3298 break; 3299 case ISD::USUBO: 3300 case ISD::SSUBO: 3301 if (Op.getResNo() == 1) { 3302 // If we know the result of a setcc has the top bits zero, use this info. 3303 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3304 TargetLowering::ZeroOrOneBooleanContent && 3305 BitWidth > 1) 3306 Known.Zero.setBitsFrom(1); 3307 break; 3308 } 3309 LLVM_FALLTHROUGH; 3310 case ISD::SUB: 3311 case ISD::SUBC: { 3312 assert(Op.getResNo() == 0 && 3313 "We only compute knownbits for the difference here."); 3314 3315 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3316 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3317 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false, 3318 Known, Known2); 3319 break; 3320 } 3321 case ISD::UADDO: 3322 case ISD::SADDO: 3323 case ISD::ADDCARRY: 3324 if (Op.getResNo() == 1) { 3325 // If we know the result of a setcc has the top bits zero, use this info. 3326 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) == 3327 TargetLowering::ZeroOrOneBooleanContent && 3328 BitWidth > 1) 3329 Known.Zero.setBitsFrom(1); 3330 break; 3331 } 3332 LLVM_FALLTHROUGH; 3333 case ISD::ADD: 3334 case ISD::ADDC: 3335 case ISD::ADDE: { 3336 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here."); 3337 3338 // With ADDE and ADDCARRY, a carry bit may be added in. 3339 KnownBits Carry(1); 3340 if (Opcode == ISD::ADDE) 3341 // Can't track carry from glue, set carry to unknown. 3342 Carry.resetAll(); 3343 else if (Opcode == ISD::ADDCARRY) 3344 // TODO: Compute known bits for the carry operand. Not sure if it is worth 3345 // the trouble (how often will we find a known carry bit). And I haven't 3346 // tested this very much yet, but something like this might work: 3347 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1); 3348 // Carry = Carry.zextOrTrunc(1, false); 3349 Carry.resetAll(); 3350 else 3351 Carry.setAllZero(); 3352 3353 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3354 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3355 Known = KnownBits::computeForAddCarry(Known, Known2, Carry); 3356 break; 3357 } 3358 case ISD::SREM: { 3359 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3360 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3361 Known = KnownBits::srem(Known, Known2); 3362 break; 3363 } 3364 case ISD::UREM: { 3365 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3366 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3367 Known = KnownBits::urem(Known, Known2); 3368 break; 3369 } 3370 case ISD::EXTRACT_ELEMENT: { 3371 Known = computeKnownBits(Op.getOperand(0), Depth+1); 3372 const unsigned Index = Op.getConstantOperandVal(1); 3373 const unsigned EltBitWidth = Op.getValueSizeInBits(); 3374 3375 // Remove low part of known bits mask 3376 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3377 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth); 3378 3379 // Remove high part of known bit mask 3380 Known = Known.trunc(EltBitWidth); 3381 break; 3382 } 3383 case ISD::EXTRACT_VECTOR_ELT: { 3384 SDValue InVec = Op.getOperand(0); 3385 SDValue EltNo = Op.getOperand(1); 3386 EVT VecVT = InVec.getValueType(); 3387 // computeKnownBits not yet implemented for scalable vectors. 3388 if (VecVT.isScalableVector()) 3389 break; 3390 const unsigned EltBitWidth = VecVT.getScalarSizeInBits(); 3391 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 3392 3393 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 3394 // anything about the extended bits. 3395 if (BitWidth > EltBitWidth) 3396 Known = Known.trunc(EltBitWidth); 3397 3398 // If we know the element index, just demand that vector element, else for 3399 // an unknown element index, ignore DemandedElts and demand them all. 3400 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 3401 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 3402 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 3403 DemandedSrcElts = 3404 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 3405 3406 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1); 3407 if (BitWidth > EltBitWidth) 3408 Known = Known.anyext(BitWidth); 3409 break; 3410 } 3411 case ISD::INSERT_VECTOR_ELT: { 3412 // If we know the element index, split the demand between the 3413 // source vector and the inserted element, otherwise assume we need 3414 // the original demanded vector elements and the value. 3415 SDValue InVec = Op.getOperand(0); 3416 SDValue InVal = Op.getOperand(1); 3417 SDValue EltNo = Op.getOperand(2); 3418 bool DemandedVal = true; 3419 APInt DemandedVecElts = DemandedElts; 3420 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3421 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3422 unsigned EltIdx = CEltNo->getZExtValue(); 3423 DemandedVal = !!DemandedElts[EltIdx]; 3424 DemandedVecElts.clearBit(EltIdx); 3425 } 3426 Known.One.setAllBits(); 3427 Known.Zero.setAllBits(); 3428 if (DemandedVal) { 3429 Known2 = computeKnownBits(InVal, Depth + 1); 3430 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth)); 3431 } 3432 if (!!DemandedVecElts) { 3433 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1); 3434 Known = KnownBits::commonBits(Known, Known2); 3435 } 3436 break; 3437 } 3438 case ISD::BITREVERSE: { 3439 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3440 Known = Known2.reverseBits(); 3441 break; 3442 } 3443 case ISD::BSWAP: { 3444 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3445 Known = Known2.byteSwap(); 3446 break; 3447 } 3448 case ISD::ABS: { 3449 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3450 Known = Known2.abs(); 3451 break; 3452 } 3453 case ISD::USUBSAT: { 3454 // The result of usubsat will never be larger than the LHS. 3455 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3456 Known.Zero.setHighBits(Known2.countMinLeadingZeros()); 3457 break; 3458 } 3459 case ISD::UMIN: { 3460 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3461 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3462 Known = KnownBits::umin(Known, Known2); 3463 break; 3464 } 3465 case ISD::UMAX: { 3466 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3467 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3468 Known = KnownBits::umax(Known, Known2); 3469 break; 3470 } 3471 case ISD::SMIN: 3472 case ISD::SMAX: { 3473 // If we have a clamp pattern, we know that the number of sign bits will be 3474 // the minimum of the clamp min/max range. 3475 bool IsMax = (Opcode == ISD::SMAX); 3476 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3477 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3478 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3479 CstHigh = 3480 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3481 if (CstLow && CstHigh) { 3482 if (!IsMax) 3483 std::swap(CstLow, CstHigh); 3484 3485 const APInt &ValueLow = CstLow->getAPIntValue(); 3486 const APInt &ValueHigh = CstHigh->getAPIntValue(); 3487 if (ValueLow.sle(ValueHigh)) { 3488 unsigned LowSignBits = ValueLow.getNumSignBits(); 3489 unsigned HighSignBits = ValueHigh.getNumSignBits(); 3490 unsigned MinSignBits = std::min(LowSignBits, HighSignBits); 3491 if (ValueLow.isNegative() && ValueHigh.isNegative()) { 3492 Known.One.setHighBits(MinSignBits); 3493 break; 3494 } 3495 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) { 3496 Known.Zero.setHighBits(MinSignBits); 3497 break; 3498 } 3499 } 3500 } 3501 3502 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3503 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3504 if (IsMax) 3505 Known = KnownBits::smax(Known, Known2); 3506 else 3507 Known = KnownBits::smin(Known, Known2); 3508 break; 3509 } 3510 case ISD::FrameIndex: 3511 case ISD::TargetFrameIndex: 3512 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(), 3513 Known, getMachineFunction()); 3514 break; 3515 3516 default: 3517 if (Opcode < ISD::BUILTIN_OP_END) 3518 break; 3519 LLVM_FALLTHROUGH; 3520 case ISD::INTRINSIC_WO_CHAIN: 3521 case ISD::INTRINSIC_W_CHAIN: 3522 case ISD::INTRINSIC_VOID: 3523 // Allow the target to implement this method for its nodes. 3524 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth); 3525 break; 3526 } 3527 3528 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 3529 return Known; 3530 } 3531 3532 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0, 3533 SDValue N1) const { 3534 // X + 0 never overflow 3535 if (isNullConstant(N1)) 3536 return OFK_Never; 3537 3538 KnownBits N1Known = computeKnownBits(N1); 3539 if (N1Known.Zero.getBoolValue()) { 3540 KnownBits N0Known = computeKnownBits(N0); 3541 3542 bool overflow; 3543 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow); 3544 if (!overflow) 3545 return OFK_Never; 3546 } 3547 3548 // mulhi + 1 never overflow 3549 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 && 3550 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue()) 3551 return OFK_Never; 3552 3553 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) { 3554 KnownBits N0Known = computeKnownBits(N0); 3555 3556 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue()) 3557 return OFK_Never; 3558 } 3559 3560 return OFK_Sometime; 3561 } 3562 3563 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const { 3564 EVT OpVT = Val.getValueType(); 3565 unsigned BitWidth = OpVT.getScalarSizeInBits(); 3566 3567 // Is the constant a known power of 2? 3568 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val)) 3569 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3570 3571 // A left-shift of a constant one will have exactly one bit set because 3572 // shifting the bit off the end is undefined. 3573 if (Val.getOpcode() == ISD::SHL) { 3574 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3575 if (C && C->getAPIntValue() == 1) 3576 return true; 3577 } 3578 3579 // Similarly, a logical right-shift of a constant sign-bit will have exactly 3580 // one bit set. 3581 if (Val.getOpcode() == ISD::SRL) { 3582 auto *C = isConstOrConstSplat(Val.getOperand(0)); 3583 if (C && C->getAPIntValue().isSignMask()) 3584 return true; 3585 } 3586 3587 // Are all operands of a build vector constant powers of two? 3588 if (Val.getOpcode() == ISD::BUILD_VECTOR) 3589 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) { 3590 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E)) 3591 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2(); 3592 return false; 3593 })) 3594 return true; 3595 3596 // More could be done here, though the above checks are enough 3597 // to handle some common cases. 3598 3599 // Fall back to computeKnownBits to catch other known cases. 3600 KnownBits Known = computeKnownBits(Val); 3601 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1); 3602 } 3603 3604 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const { 3605 EVT VT = Op.getValueType(); 3606 3607 // TODO: Assume we don't know anything for now. 3608 if (VT.isScalableVector()) 3609 return 1; 3610 3611 APInt DemandedElts = VT.isVector() 3612 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 3613 : APInt(1, 1); 3614 return ComputeNumSignBits(Op, DemandedElts, Depth); 3615 } 3616 3617 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts, 3618 unsigned Depth) const { 3619 EVT VT = Op.getValueType(); 3620 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!"); 3621 unsigned VTBits = VT.getScalarSizeInBits(); 3622 unsigned NumElts = DemandedElts.getBitWidth(); 3623 unsigned Tmp, Tmp2; 3624 unsigned FirstAnswer = 1; 3625 3626 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 3627 const APInt &Val = C->getAPIntValue(); 3628 return Val.getNumSignBits(); 3629 } 3630 3631 if (Depth >= MaxRecursionDepth) 3632 return 1; // Limit search depth. 3633 3634 if (!DemandedElts || VT.isScalableVector()) 3635 return 1; // No demanded elts, better to assume we don't know anything. 3636 3637 unsigned Opcode = Op.getOpcode(); 3638 switch (Opcode) { 3639 default: break; 3640 case ISD::AssertSext: 3641 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3642 return VTBits-Tmp+1; 3643 case ISD::AssertZext: 3644 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits(); 3645 return VTBits-Tmp; 3646 3647 case ISD::BUILD_VECTOR: 3648 Tmp = VTBits; 3649 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) { 3650 if (!DemandedElts[i]) 3651 continue; 3652 3653 SDValue SrcOp = Op.getOperand(i); 3654 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1); 3655 3656 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 3657 if (SrcOp.getValueSizeInBits() != VTBits) { 3658 assert(SrcOp.getValueSizeInBits() > VTBits && 3659 "Expected BUILD_VECTOR implicit truncation"); 3660 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits; 3661 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1); 3662 } 3663 Tmp = std::min(Tmp, Tmp2); 3664 } 3665 return Tmp; 3666 3667 case ISD::VECTOR_SHUFFLE: { 3668 // Collect the minimum number of sign bits that are shared by every vector 3669 // element referenced by the shuffle. 3670 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0); 3671 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 3672 assert(NumElts == SVN->getMask().size() && "Unexpected vector size"); 3673 for (unsigned i = 0; i != NumElts; ++i) { 3674 int M = SVN->getMaskElt(i); 3675 if (!DemandedElts[i]) 3676 continue; 3677 // For UNDEF elements, we don't know anything about the common state of 3678 // the shuffle result. 3679 if (M < 0) 3680 return 1; 3681 if ((unsigned)M < NumElts) 3682 DemandedLHS.setBit((unsigned)M % NumElts); 3683 else 3684 DemandedRHS.setBit((unsigned)M % NumElts); 3685 } 3686 Tmp = std::numeric_limits<unsigned>::max(); 3687 if (!!DemandedLHS) 3688 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1); 3689 if (!!DemandedRHS) { 3690 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1); 3691 Tmp = std::min(Tmp, Tmp2); 3692 } 3693 // If we don't know anything, early out and try computeKnownBits fall-back. 3694 if (Tmp == 1) 3695 break; 3696 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 3697 return Tmp; 3698 } 3699 3700 case ISD::BITCAST: { 3701 SDValue N0 = Op.getOperand(0); 3702 EVT SrcVT = N0.getValueType(); 3703 unsigned SrcBits = SrcVT.getScalarSizeInBits(); 3704 3705 // Ignore bitcasts from unsupported types.. 3706 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint())) 3707 break; 3708 3709 // Fast handling of 'identity' bitcasts. 3710 if (VTBits == SrcBits) 3711 return ComputeNumSignBits(N0, DemandedElts, Depth + 1); 3712 3713 bool IsLE = getDataLayout().isLittleEndian(); 3714 3715 // Bitcast 'large element' scalar/vector to 'small element' vector. 3716 if ((SrcBits % VTBits) == 0) { 3717 assert(VT.isVector() && "Expected bitcast to vector"); 3718 3719 unsigned Scale = SrcBits / VTBits; 3720 APInt SrcDemandedElts(NumElts / Scale, 0); 3721 for (unsigned i = 0; i != NumElts; ++i) 3722 if (DemandedElts[i]) 3723 SrcDemandedElts.setBit(i / Scale); 3724 3725 // Fast case - sign splat can be simply split across the small elements. 3726 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1); 3727 if (Tmp == SrcBits) 3728 return VTBits; 3729 3730 // Slow case - determine how far the sign extends into each sub-element. 3731 Tmp2 = VTBits; 3732 for (unsigned i = 0; i != NumElts; ++i) 3733 if (DemandedElts[i]) { 3734 unsigned SubOffset = i % Scale; 3735 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset); 3736 SubOffset = SubOffset * VTBits; 3737 if (Tmp <= SubOffset) 3738 return 1; 3739 Tmp2 = std::min(Tmp2, Tmp - SubOffset); 3740 } 3741 return Tmp2; 3742 } 3743 break; 3744 } 3745 3746 case ISD::SIGN_EXTEND: 3747 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits(); 3748 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp; 3749 case ISD::SIGN_EXTEND_INREG: 3750 // Max of the input and what this extends. 3751 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits(); 3752 Tmp = VTBits-Tmp+1; 3753 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3754 return std::max(Tmp, Tmp2); 3755 case ISD::SIGN_EXTEND_VECTOR_INREG: { 3756 SDValue Src = Op.getOperand(0); 3757 EVT SrcVT = Src.getValueType(); 3758 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements()); 3759 Tmp = VTBits - SrcVT.getScalarSizeInBits(); 3760 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp; 3761 } 3762 case ISD::SRA: 3763 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3764 // SRA X, C -> adds C sign bits. 3765 if (const APInt *ShAmt = 3766 getValidMinimumShiftAmountConstant(Op, DemandedElts)) 3767 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits); 3768 return Tmp; 3769 case ISD::SHL: 3770 if (const APInt *ShAmt = 3771 getValidMaximumShiftAmountConstant(Op, DemandedElts)) { 3772 // shl destroys sign bits, ensure it doesn't shift out all sign bits. 3773 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3774 if (ShAmt->ult(Tmp)) 3775 return Tmp - ShAmt->getZExtValue(); 3776 } 3777 break; 3778 case ISD::AND: 3779 case ISD::OR: 3780 case ISD::XOR: // NOT is handled here. 3781 // Logical binary ops preserve the number of sign bits at the worst. 3782 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1); 3783 if (Tmp != 1) { 3784 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3785 FirstAnswer = std::min(Tmp, Tmp2); 3786 // We computed what we know about the sign bits as our first 3787 // answer. Now proceed to the generic code that uses 3788 // computeKnownBits, and pick whichever answer is better. 3789 } 3790 break; 3791 3792 case ISD::SELECT: 3793 case ISD::VSELECT: 3794 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1); 3795 if (Tmp == 1) return 1; // Early out. 3796 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3797 return std::min(Tmp, Tmp2); 3798 case ISD::SELECT_CC: 3799 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1); 3800 if (Tmp == 1) return 1; // Early out. 3801 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1); 3802 return std::min(Tmp, Tmp2); 3803 3804 case ISD::SMIN: 3805 case ISD::SMAX: { 3806 // If we have a clamp pattern, we know that the number of sign bits will be 3807 // the minimum of the clamp min/max range. 3808 bool IsMax = (Opcode == ISD::SMAX); 3809 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr; 3810 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts))) 3811 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX)) 3812 CstHigh = 3813 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts); 3814 if (CstLow && CstHigh) { 3815 if (!IsMax) 3816 std::swap(CstLow, CstHigh); 3817 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) { 3818 Tmp = CstLow->getAPIntValue().getNumSignBits(); 3819 Tmp2 = CstHigh->getAPIntValue().getNumSignBits(); 3820 return std::min(Tmp, Tmp2); 3821 } 3822 } 3823 3824 // Fallback - just get the minimum number of sign bits of the operands. 3825 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3826 if (Tmp == 1) 3827 return 1; // Early out. 3828 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3829 return std::min(Tmp, Tmp2); 3830 } 3831 case ISD::UMIN: 3832 case ISD::UMAX: 3833 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3834 if (Tmp == 1) 3835 return 1; // Early out. 3836 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3837 return std::min(Tmp, Tmp2); 3838 case ISD::SADDO: 3839 case ISD::UADDO: 3840 case ISD::SSUBO: 3841 case ISD::USUBO: 3842 case ISD::SMULO: 3843 case ISD::UMULO: 3844 if (Op.getResNo() != 1) 3845 break; 3846 // The boolean result conforms to getBooleanContents. Fall through. 3847 // If setcc returns 0/-1, all bits are sign bits. 3848 // We know that we have an integer-based boolean since these operations 3849 // are only available for integer. 3850 if (TLI->getBooleanContents(VT.isVector(), false) == 3851 TargetLowering::ZeroOrNegativeOneBooleanContent) 3852 return VTBits; 3853 break; 3854 case ISD::SETCC: 3855 case ISD::STRICT_FSETCC: 3856 case ISD::STRICT_FSETCCS: { 3857 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0; 3858 // If setcc returns 0/-1, all bits are sign bits. 3859 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) == 3860 TargetLowering::ZeroOrNegativeOneBooleanContent) 3861 return VTBits; 3862 break; 3863 } 3864 case ISD::ROTL: 3865 case ISD::ROTR: 3866 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3867 3868 // If we're rotating an 0/-1 value, then it stays an 0/-1 value. 3869 if (Tmp == VTBits) 3870 return VTBits; 3871 3872 if (ConstantSDNode *C = 3873 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) { 3874 unsigned RotAmt = C->getAPIntValue().urem(VTBits); 3875 3876 // Handle rotate right by N like a rotate left by 32-N. 3877 if (Opcode == ISD::ROTR) 3878 RotAmt = (VTBits - RotAmt) % VTBits; 3879 3880 // If we aren't rotating out all of the known-in sign bits, return the 3881 // number that are left. This handles rotl(sext(x), 1) for example. 3882 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt); 3883 } 3884 break; 3885 case ISD::ADD: 3886 case ISD::ADDC: 3887 // Add can have at most one carry bit. Thus we know that the output 3888 // is, at worst, one more bit than the inputs. 3889 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3890 if (Tmp == 1) return 1; // Early out. 3891 3892 // Special case decrementing a value (ADD X, -1): 3893 if (ConstantSDNode *CRHS = 3894 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) 3895 if (CRHS->isAllOnesValue()) { 3896 KnownBits Known = 3897 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 3898 3899 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3900 // sign bits set. 3901 if ((Known.Zero | 1).isAllOnesValue()) 3902 return VTBits; 3903 3904 // If we are subtracting one from a positive number, there is no carry 3905 // out of the result. 3906 if (Known.isNonNegative()) 3907 return Tmp; 3908 } 3909 3910 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3911 if (Tmp2 == 1) return 1; // Early out. 3912 return std::min(Tmp, Tmp2) - 1; 3913 case ISD::SUB: 3914 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1); 3915 if (Tmp2 == 1) return 1; // Early out. 3916 3917 // Handle NEG. 3918 if (ConstantSDNode *CLHS = 3919 isConstOrConstSplat(Op.getOperand(0), DemandedElts)) 3920 if (CLHS->isNullValue()) { 3921 KnownBits Known = 3922 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 3923 // If the input is known to be 0 or 1, the output is 0/-1, which is all 3924 // sign bits set. 3925 if ((Known.Zero | 1).isAllOnesValue()) 3926 return VTBits; 3927 3928 // If the input is known to be positive (the sign bit is known clear), 3929 // the output of the NEG has the same number of sign bits as the input. 3930 if (Known.isNonNegative()) 3931 return Tmp2; 3932 3933 // Otherwise, we treat this like a SUB. 3934 } 3935 3936 // Sub can have at most one carry bit. Thus we know that the output 3937 // is, at worst, one more bit than the inputs. 3938 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3939 if (Tmp == 1) return 1; // Early out. 3940 return std::min(Tmp, Tmp2) - 1; 3941 case ISD::MUL: { 3942 // The output of the Mul can be at most twice the valid bits in the inputs. 3943 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3944 if (SignBitsOp0 == 1) 3945 break; 3946 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1); 3947 if (SignBitsOp1 == 1) 3948 break; 3949 unsigned OutValidBits = 3950 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1); 3951 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1; 3952 } 3953 case ISD::SREM: 3954 // The sign bit is the LHS's sign bit, except when the result of the 3955 // remainder is zero. The magnitude of the result should be less than or 3956 // equal to the magnitude of the LHS. Therefore, the result should have 3957 // at least as many sign bits as the left hand side. 3958 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1); 3959 case ISD::TRUNCATE: { 3960 // Check if the sign bits of source go down as far as the truncated value. 3961 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits(); 3962 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1); 3963 if (NumSrcSignBits > (NumSrcBits - VTBits)) 3964 return NumSrcSignBits - (NumSrcBits - VTBits); 3965 break; 3966 } 3967 case ISD::EXTRACT_ELEMENT: { 3968 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1); 3969 const int BitWidth = Op.getValueSizeInBits(); 3970 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth; 3971 3972 // Get reverse index (starting from 1), Op1 value indexes elements from 3973 // little end. Sign starts at big end. 3974 const int rIndex = Items - 1 - Op.getConstantOperandVal(1); 3975 3976 // If the sign portion ends in our element the subtraction gives correct 3977 // result. Otherwise it gives either negative or > bitwidth result 3978 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0); 3979 } 3980 case ISD::INSERT_VECTOR_ELT: { 3981 // If we know the element index, split the demand between the 3982 // source vector and the inserted element, otherwise assume we need 3983 // the original demanded vector elements and the value. 3984 SDValue InVec = Op.getOperand(0); 3985 SDValue InVal = Op.getOperand(1); 3986 SDValue EltNo = Op.getOperand(2); 3987 bool DemandedVal = true; 3988 APInt DemandedVecElts = DemandedElts; 3989 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo); 3990 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) { 3991 unsigned EltIdx = CEltNo->getZExtValue(); 3992 DemandedVal = !!DemandedElts[EltIdx]; 3993 DemandedVecElts.clearBit(EltIdx); 3994 } 3995 Tmp = std::numeric_limits<unsigned>::max(); 3996 if (DemandedVal) { 3997 // TODO - handle implicit truncation of inserted elements. 3998 if (InVal.getScalarValueSizeInBits() != VTBits) 3999 break; 4000 Tmp2 = ComputeNumSignBits(InVal, Depth + 1); 4001 Tmp = std::min(Tmp, Tmp2); 4002 } 4003 if (!!DemandedVecElts) { 4004 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1); 4005 Tmp = std::min(Tmp, Tmp2); 4006 } 4007 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4008 return Tmp; 4009 } 4010 case ISD::EXTRACT_VECTOR_ELT: { 4011 SDValue InVec = Op.getOperand(0); 4012 SDValue EltNo = Op.getOperand(1); 4013 EVT VecVT = InVec.getValueType(); 4014 // ComputeNumSignBits not yet implemented for scalable vectors. 4015 if (VecVT.isScalableVector()) 4016 break; 4017 const unsigned BitWidth = Op.getValueSizeInBits(); 4018 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 4019 const unsigned NumSrcElts = VecVT.getVectorNumElements(); 4020 4021 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know 4022 // anything about sign bits. But if the sizes match we can derive knowledge 4023 // about sign bits from the vector operand. 4024 if (BitWidth != EltBitWidth) 4025 break; 4026 4027 // If we know the element index, just demand that vector element, else for 4028 // an unknown element index, ignore DemandedElts and demand them all. 4029 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 4030 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo); 4031 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) 4032 DemandedSrcElts = 4033 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue()); 4034 4035 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1); 4036 } 4037 case ISD::EXTRACT_SUBVECTOR: { 4038 // Offset the demanded elts by the subvector index. 4039 SDValue Src = Op.getOperand(0); 4040 // Bail until we can represent demanded elements for scalable vectors. 4041 if (Src.getValueType().isScalableVector()) 4042 break; 4043 uint64_t Idx = Op.getConstantOperandVal(1); 4044 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 4045 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 4046 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4047 } 4048 case ISD::CONCAT_VECTORS: { 4049 // Determine the minimum number of sign bits across all demanded 4050 // elts of the input vectors. Early out if the result is already 1. 4051 Tmp = std::numeric_limits<unsigned>::max(); 4052 EVT SubVectorVT = Op.getOperand(0).getValueType(); 4053 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements(); 4054 unsigned NumSubVectors = Op.getNumOperands(); 4055 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) { 4056 APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts); 4057 DemandedSub = DemandedSub.trunc(NumSubVectorElts); 4058 if (!DemandedSub) 4059 continue; 4060 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1); 4061 Tmp = std::min(Tmp, Tmp2); 4062 } 4063 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4064 return Tmp; 4065 } 4066 case ISD::INSERT_SUBVECTOR: { 4067 // Demand any elements from the subvector and the remainder from the src its 4068 // inserted into. 4069 SDValue Src = Op.getOperand(0); 4070 SDValue Sub = Op.getOperand(1); 4071 uint64_t Idx = Op.getConstantOperandVal(2); 4072 unsigned NumSubElts = Sub.getValueType().getVectorNumElements(); 4073 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx); 4074 APInt DemandedSrcElts = DemandedElts; 4075 DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx); 4076 4077 Tmp = std::numeric_limits<unsigned>::max(); 4078 if (!!DemandedSubElts) { 4079 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1); 4080 if (Tmp == 1) 4081 return 1; // early-out 4082 } 4083 if (!!DemandedSrcElts) { 4084 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1); 4085 Tmp = std::min(Tmp, Tmp2); 4086 } 4087 assert(Tmp <= VTBits && "Failed to determine minimum sign bits"); 4088 return Tmp; 4089 } 4090 } 4091 4092 // If we are looking at the loaded value of the SDNode. 4093 if (Op.getResNo() == 0) { 4094 // Handle LOADX separately here. EXTLOAD case will fallthrough. 4095 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) { 4096 unsigned ExtType = LD->getExtensionType(); 4097 switch (ExtType) { 4098 default: break; 4099 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known. 4100 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4101 return VTBits - Tmp + 1; 4102 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known. 4103 Tmp = LD->getMemoryVT().getScalarSizeInBits(); 4104 return VTBits - Tmp; 4105 case ISD::NON_EXTLOAD: 4106 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) { 4107 // We only need to handle vectors - computeKnownBits should handle 4108 // scalar cases. 4109 Type *CstTy = Cst->getType(); 4110 if (CstTy->isVectorTy() && 4111 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) { 4112 Tmp = VTBits; 4113 for (unsigned i = 0; i != NumElts; ++i) { 4114 if (!DemandedElts[i]) 4115 continue; 4116 if (Constant *Elt = Cst->getAggregateElement(i)) { 4117 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) { 4118 const APInt &Value = CInt->getValue(); 4119 Tmp = std::min(Tmp, Value.getNumSignBits()); 4120 continue; 4121 } 4122 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) { 4123 APInt Value = CFP->getValueAPF().bitcastToAPInt(); 4124 Tmp = std::min(Tmp, Value.getNumSignBits()); 4125 continue; 4126 } 4127 } 4128 // Unknown type. Conservatively assume no bits match sign bit. 4129 return 1; 4130 } 4131 return Tmp; 4132 } 4133 } 4134 break; 4135 } 4136 } 4137 } 4138 4139 // Allow the target to implement this method for its nodes. 4140 if (Opcode >= ISD::BUILTIN_OP_END || 4141 Opcode == ISD::INTRINSIC_WO_CHAIN || 4142 Opcode == ISD::INTRINSIC_W_CHAIN || 4143 Opcode == ISD::INTRINSIC_VOID) { 4144 unsigned NumBits = 4145 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth); 4146 if (NumBits > 1) 4147 FirstAnswer = std::max(FirstAnswer, NumBits); 4148 } 4149 4150 // Finally, if we can prove that the top bits of the result are 0's or 1's, 4151 // use this information. 4152 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth); 4153 4154 APInt Mask; 4155 if (Known.isNonNegative()) { // sign bit is 0 4156 Mask = Known.Zero; 4157 } else if (Known.isNegative()) { // sign bit is 1; 4158 Mask = Known.One; 4159 } else { 4160 // Nothing known. 4161 return FirstAnswer; 4162 } 4163 4164 // Okay, we know that the sign bit in Mask is set. Use CLO to determine 4165 // the number of identical bits in the top of the input value. 4166 Mask <<= Mask.getBitWidth()-VTBits; 4167 return std::max(FirstAnswer, Mask.countLeadingOnes()); 4168 } 4169 4170 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const { 4171 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) || 4172 !isa<ConstantSDNode>(Op.getOperand(1))) 4173 return false; 4174 4175 if (Op.getOpcode() == ISD::OR && 4176 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1))) 4177 return false; 4178 4179 return true; 4180 } 4181 4182 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const { 4183 // If we're told that NaNs won't happen, assume they won't. 4184 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs()) 4185 return true; 4186 4187 if (Depth >= MaxRecursionDepth) 4188 return false; // Limit search depth. 4189 4190 // TODO: Handle vectors. 4191 // If the value is a constant, we can obviously see if it is a NaN or not. 4192 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 4193 return !C->getValueAPF().isNaN() || 4194 (SNaN && !C->getValueAPF().isSignaling()); 4195 } 4196 4197 unsigned Opcode = Op.getOpcode(); 4198 switch (Opcode) { 4199 case ISD::FADD: 4200 case ISD::FSUB: 4201 case ISD::FMUL: 4202 case ISD::FDIV: 4203 case ISD::FREM: 4204 case ISD::FSIN: 4205 case ISD::FCOS: { 4206 if (SNaN) 4207 return true; 4208 // TODO: Need isKnownNeverInfinity 4209 return false; 4210 } 4211 case ISD::FCANONICALIZE: 4212 case ISD::FEXP: 4213 case ISD::FEXP2: 4214 case ISD::FTRUNC: 4215 case ISD::FFLOOR: 4216 case ISD::FCEIL: 4217 case ISD::FROUND: 4218 case ISD::FROUNDEVEN: 4219 case ISD::FRINT: 4220 case ISD::FNEARBYINT: { 4221 if (SNaN) 4222 return true; 4223 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4224 } 4225 case ISD::FABS: 4226 case ISD::FNEG: 4227 case ISD::FCOPYSIGN: { 4228 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4229 } 4230 case ISD::SELECT: 4231 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4232 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4233 case ISD::FP_EXTEND: 4234 case ISD::FP_ROUND: { 4235 if (SNaN) 4236 return true; 4237 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4238 } 4239 case ISD::SINT_TO_FP: 4240 case ISD::UINT_TO_FP: 4241 return true; 4242 case ISD::FMA: 4243 case ISD::FMAD: { 4244 if (SNaN) 4245 return true; 4246 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4247 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) && 4248 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1); 4249 } 4250 case ISD::FSQRT: // Need is known positive 4251 case ISD::FLOG: 4252 case ISD::FLOG2: 4253 case ISD::FLOG10: 4254 case ISD::FPOWI: 4255 case ISD::FPOW: { 4256 if (SNaN) 4257 return true; 4258 // TODO: Refine on operand 4259 return false; 4260 } 4261 case ISD::FMINNUM: 4262 case ISD::FMAXNUM: { 4263 // Only one needs to be known not-nan, since it will be returned if the 4264 // other ends up being one. 4265 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) || 4266 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4267 } 4268 case ISD::FMINNUM_IEEE: 4269 case ISD::FMAXNUM_IEEE: { 4270 if (SNaN) 4271 return true; 4272 // This can return a NaN if either operand is an sNaN, or if both operands 4273 // are NaN. 4274 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) && 4275 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) || 4276 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) && 4277 isKnownNeverSNaN(Op.getOperand(0), Depth + 1)); 4278 } 4279 case ISD::FMINIMUM: 4280 case ISD::FMAXIMUM: { 4281 // TODO: Does this quiet or return the origina NaN as-is? 4282 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) && 4283 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1); 4284 } 4285 case ISD::EXTRACT_VECTOR_ELT: { 4286 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 4287 } 4288 default: 4289 if (Opcode >= ISD::BUILTIN_OP_END || 4290 Opcode == ISD::INTRINSIC_WO_CHAIN || 4291 Opcode == ISD::INTRINSIC_W_CHAIN || 4292 Opcode == ISD::INTRINSIC_VOID) { 4293 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth); 4294 } 4295 4296 return false; 4297 } 4298 } 4299 4300 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const { 4301 assert(Op.getValueType().isFloatingPoint() && 4302 "Floating point type expected"); 4303 4304 // If the value is a constant, we can obviously see if it is a zero or not. 4305 // TODO: Add BuildVector support. 4306 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 4307 return !C->isZero(); 4308 return false; 4309 } 4310 4311 bool SelectionDAG::isKnownNeverZero(SDValue Op) const { 4312 assert(!Op.getValueType().isFloatingPoint() && 4313 "Floating point types unsupported - use isKnownNeverZeroFloat"); 4314 4315 // If the value is a constant, we can obviously see if it is a zero or not. 4316 if (ISD::matchUnaryPredicate( 4317 Op, [](ConstantSDNode *C) { return !C->isNullValue(); })) 4318 return true; 4319 4320 // TODO: Recognize more cases here. 4321 switch (Op.getOpcode()) { 4322 default: break; 4323 case ISD::OR: 4324 if (isKnownNeverZero(Op.getOperand(1)) || 4325 isKnownNeverZero(Op.getOperand(0))) 4326 return true; 4327 break; 4328 } 4329 4330 return false; 4331 } 4332 4333 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const { 4334 // Check the obvious case. 4335 if (A == B) return true; 4336 4337 // For for negative and positive zero. 4338 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) 4339 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) 4340 if (CA->isZero() && CB->isZero()) return true; 4341 4342 // Otherwise they may not be equal. 4343 return false; 4344 } 4345 4346 // FIXME: unify with llvm::haveNoCommonBitsSet. 4347 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M) 4348 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const { 4349 assert(A.getValueType() == B.getValueType() && 4350 "Values must have the same type"); 4351 return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue(); 4352 } 4353 4354 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, 4355 SelectionDAG &DAG) { 4356 if (cast<ConstantSDNode>(Step)->isNullValue()) 4357 return DAG.getConstant(0, DL, VT); 4358 4359 return SDValue(); 4360 } 4361 4362 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, 4363 ArrayRef<SDValue> Ops, 4364 SelectionDAG &DAG) { 4365 int NumOps = Ops.size(); 4366 assert(NumOps != 0 && "Can't build an empty vector!"); 4367 assert(!VT.isScalableVector() && 4368 "BUILD_VECTOR cannot be used with scalable types"); 4369 assert(VT.getVectorNumElements() == (unsigned)NumOps && 4370 "Incorrect element count in BUILD_VECTOR!"); 4371 4372 // BUILD_VECTOR of UNDEFs is UNDEF. 4373 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4374 return DAG.getUNDEF(VT); 4375 4376 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity. 4377 SDValue IdentitySrc; 4378 bool IsIdentity = true; 4379 for (int i = 0; i != NumOps; ++i) { 4380 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT || 4381 Ops[i].getOperand(0).getValueType() != VT || 4382 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) || 4383 !isa<ConstantSDNode>(Ops[i].getOperand(1)) || 4384 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) { 4385 IsIdentity = false; 4386 break; 4387 } 4388 IdentitySrc = Ops[i].getOperand(0); 4389 } 4390 if (IsIdentity) 4391 return IdentitySrc; 4392 4393 return SDValue(); 4394 } 4395 4396 /// Try to simplify vector concatenation to an input value, undef, or build 4397 /// vector. 4398 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, 4399 ArrayRef<SDValue> Ops, 4400 SelectionDAG &DAG) { 4401 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!"); 4402 assert(llvm::all_of(Ops, 4403 [Ops](SDValue Op) { 4404 return Ops[0].getValueType() == Op.getValueType(); 4405 }) && 4406 "Concatenation of vectors with inconsistent value types!"); 4407 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) == 4408 VT.getVectorElementCount() && 4409 "Incorrect element count in vector concatenation!"); 4410 4411 if (Ops.size() == 1) 4412 return Ops[0]; 4413 4414 // Concat of UNDEFs is UNDEF. 4415 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); })) 4416 return DAG.getUNDEF(VT); 4417 4418 // Scan the operands and look for extract operations from a single source 4419 // that correspond to insertion at the same location via this concatenation: 4420 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ... 4421 SDValue IdentitySrc; 4422 bool IsIdentity = true; 4423 for (unsigned i = 0, e = Ops.size(); i != e; ++i) { 4424 SDValue Op = Ops[i]; 4425 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements(); 4426 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR || 4427 Op.getOperand(0).getValueType() != VT || 4428 (IdentitySrc && Op.getOperand(0) != IdentitySrc) || 4429 Op.getConstantOperandVal(1) != IdentityIndex) { 4430 IsIdentity = false; 4431 break; 4432 } 4433 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) && 4434 "Unexpected identity source vector for concat of extracts"); 4435 IdentitySrc = Op.getOperand(0); 4436 } 4437 if (IsIdentity) { 4438 assert(IdentitySrc && "Failed to set source vector of extracts"); 4439 return IdentitySrc; 4440 } 4441 4442 // The code below this point is only designed to work for fixed width 4443 // vectors, so we bail out for now. 4444 if (VT.isScalableVector()) 4445 return SDValue(); 4446 4447 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be 4448 // simplified to one big BUILD_VECTOR. 4449 // FIXME: Add support for SCALAR_TO_VECTOR as well. 4450 EVT SVT = VT.getScalarType(); 4451 SmallVector<SDValue, 16> Elts; 4452 for (SDValue Op : Ops) { 4453 EVT OpVT = Op.getValueType(); 4454 if (Op.isUndef()) 4455 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT)); 4456 else if (Op.getOpcode() == ISD::BUILD_VECTOR) 4457 Elts.append(Op->op_begin(), Op->op_end()); 4458 else 4459 return SDValue(); 4460 } 4461 4462 // BUILD_VECTOR requires all inputs to be of the same type, find the 4463 // maximum type and extend them all. 4464 for (SDValue Op : Elts) 4465 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 4466 4467 if (SVT.bitsGT(VT.getScalarType())) { 4468 for (SDValue &Op : Elts) { 4469 if (Op.isUndef()) 4470 Op = DAG.getUNDEF(SVT); 4471 else 4472 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT) 4473 ? DAG.getZExtOrTrunc(Op, DL, SVT) 4474 : DAG.getSExtOrTrunc(Op, DL, SVT); 4475 } 4476 } 4477 4478 SDValue V = DAG.getBuildVector(VT, DL, Elts); 4479 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG); 4480 return V; 4481 } 4482 4483 /// Gets or creates the specified node. 4484 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) { 4485 FoldingSetNodeID ID; 4486 AddNodeIDNode(ID, Opcode, getVTList(VT), None); 4487 void *IP = nullptr; 4488 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 4489 return SDValue(E, 0); 4490 4491 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), 4492 getVTList(VT)); 4493 CSEMap.InsertNode(N, IP); 4494 4495 InsertNode(N); 4496 SDValue V = SDValue(N, 0); 4497 NewSDValueDbgMsg(V, "Creating new node: ", this); 4498 return V; 4499 } 4500 4501 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4502 SDValue Operand) { 4503 SDNodeFlags Flags; 4504 if (Inserter) 4505 Flags = Inserter->getFlags(); 4506 return getNode(Opcode, DL, VT, Operand, Flags); 4507 } 4508 4509 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 4510 SDValue Operand, const SDNodeFlags Flags) { 4511 assert(Operand.getOpcode() != ISD::DELETED_NODE && 4512 "Operand is DELETED_NODE!"); 4513 // Constant fold unary operations with an integer constant operand. Even 4514 // opaque constant will be folded, because the folding of unary operations 4515 // doesn't create new constants with different values. Nevertheless, the 4516 // opaque flag is preserved during folding to prevent future folding with 4517 // other constants. 4518 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) { 4519 const APInt &Val = C->getAPIntValue(); 4520 switch (Opcode) { 4521 default: break; 4522 case ISD::SIGN_EXTEND: 4523 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT, 4524 C->isTargetOpcode(), C->isOpaque()); 4525 case ISD::TRUNCATE: 4526 if (C->isOpaque()) 4527 break; 4528 LLVM_FALLTHROUGH; 4529 case ISD::ANY_EXTEND: 4530 case ISD::ZERO_EXTEND: 4531 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT, 4532 C->isTargetOpcode(), C->isOpaque()); 4533 case ISD::UINT_TO_FP: 4534 case ISD::SINT_TO_FP: { 4535 APFloat apf(EVTToAPFloatSemantics(VT), 4536 APInt::getNullValue(VT.getSizeInBits())); 4537 (void)apf.convertFromAPInt(Val, 4538 Opcode==ISD::SINT_TO_FP, 4539 APFloat::rmNearestTiesToEven); 4540 return getConstantFP(apf, DL, VT); 4541 } 4542 case ISD::BITCAST: 4543 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16) 4544 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT); 4545 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32) 4546 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT); 4547 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64) 4548 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT); 4549 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128) 4550 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT); 4551 break; 4552 case ISD::ABS: 4553 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(), 4554 C->isOpaque()); 4555 case ISD::BITREVERSE: 4556 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(), 4557 C->isOpaque()); 4558 case ISD::BSWAP: 4559 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(), 4560 C->isOpaque()); 4561 case ISD::CTPOP: 4562 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(), 4563 C->isOpaque()); 4564 case ISD::CTLZ: 4565 case ISD::CTLZ_ZERO_UNDEF: 4566 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(), 4567 C->isOpaque()); 4568 case ISD::CTTZ: 4569 case ISD::CTTZ_ZERO_UNDEF: 4570 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(), 4571 C->isOpaque()); 4572 case ISD::FP16_TO_FP: { 4573 bool Ignored; 4574 APFloat FPV(APFloat::IEEEhalf(), 4575 (Val.getBitWidth() == 16) ? Val : Val.trunc(16)); 4576 4577 // This can return overflow, underflow, or inexact; we don't care. 4578 // FIXME need to be more flexible about rounding mode. 4579 (void)FPV.convert(EVTToAPFloatSemantics(VT), 4580 APFloat::rmNearestTiesToEven, &Ignored); 4581 return getConstantFP(FPV, DL, VT); 4582 } 4583 case ISD::STEP_VECTOR: { 4584 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this)) 4585 return V; 4586 break; 4587 } 4588 } 4589 } 4590 4591 // Constant fold unary operations with a floating point constant operand. 4592 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) { 4593 APFloat V = C->getValueAPF(); // make copy 4594 switch (Opcode) { 4595 case ISD::FNEG: 4596 V.changeSign(); 4597 return getConstantFP(V, DL, VT); 4598 case ISD::FABS: 4599 V.clearSign(); 4600 return getConstantFP(V, DL, VT); 4601 case ISD::FCEIL: { 4602 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive); 4603 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4604 return getConstantFP(V, DL, VT); 4605 break; 4606 } 4607 case ISD::FTRUNC: { 4608 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero); 4609 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4610 return getConstantFP(V, DL, VT); 4611 break; 4612 } 4613 case ISD::FFLOOR: { 4614 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative); 4615 if (fs == APFloat::opOK || fs == APFloat::opInexact) 4616 return getConstantFP(V, DL, VT); 4617 break; 4618 } 4619 case ISD::FP_EXTEND: { 4620 bool ignored; 4621 // This can return overflow, underflow, or inexact; we don't care. 4622 // FIXME need to be more flexible about rounding mode. 4623 (void)V.convert(EVTToAPFloatSemantics(VT), 4624 APFloat::rmNearestTiesToEven, &ignored); 4625 return getConstantFP(V, DL, VT); 4626 } 4627 case ISD::FP_TO_SINT: 4628 case ISD::FP_TO_UINT: { 4629 bool ignored; 4630 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT); 4631 // FIXME need to be more flexible about rounding mode. 4632 APFloat::opStatus s = 4633 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored); 4634 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual 4635 break; 4636 return getConstant(IntVal, DL, VT); 4637 } 4638 case ISD::BITCAST: 4639 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16) 4640 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4641 else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32) 4642 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT); 4643 else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64) 4644 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4645 break; 4646 case ISD::FP_TO_FP16: { 4647 bool Ignored; 4648 // This can return overflow, underflow, or inexact; we don't care. 4649 // FIXME need to be more flexible about rounding mode. 4650 (void)V.convert(APFloat::IEEEhalf(), 4651 APFloat::rmNearestTiesToEven, &Ignored); 4652 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT); 4653 } 4654 } 4655 } 4656 4657 // Constant fold unary operations with a vector integer or float operand. 4658 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) { 4659 if (BV->isConstant()) { 4660 switch (Opcode) { 4661 default: 4662 // FIXME: Entirely reasonable to perform folding of other unary 4663 // operations here as the need arises. 4664 break; 4665 case ISD::FNEG: 4666 case ISD::FABS: 4667 case ISD::FCEIL: 4668 case ISD::FTRUNC: 4669 case ISD::FFLOOR: 4670 case ISD::FP_EXTEND: 4671 case ISD::FP_TO_SINT: 4672 case ISD::FP_TO_UINT: 4673 case ISD::TRUNCATE: 4674 case ISD::ANY_EXTEND: 4675 case ISD::ZERO_EXTEND: 4676 case ISD::SIGN_EXTEND: 4677 case ISD::UINT_TO_FP: 4678 case ISD::SINT_TO_FP: 4679 case ISD::ABS: 4680 case ISD::BITREVERSE: 4681 case ISD::BSWAP: 4682 case ISD::CTLZ: 4683 case ISD::CTLZ_ZERO_UNDEF: 4684 case ISD::CTTZ: 4685 case ISD::CTTZ_ZERO_UNDEF: 4686 case ISD::CTPOP: { 4687 SDValue Ops = { Operand }; 4688 if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) 4689 return Fold; 4690 } 4691 } 4692 } 4693 } 4694 4695 unsigned OpOpcode = Operand.getNode()->getOpcode(); 4696 switch (Opcode) { 4697 case ISD::STEP_VECTOR: 4698 assert(VT.isScalableVector() && 4699 "STEP_VECTOR can only be used with scalable types"); 4700 assert(VT.getScalarSizeInBits() >= 8 && 4701 "STEP_VECTOR can only be used with vectors of integers that are at " 4702 "least 8 bits wide"); 4703 assert(Operand.getValueType().bitsGE(VT.getScalarType()) && 4704 "Operand type should be at least as large as the element type"); 4705 assert(isa<ConstantSDNode>(Operand) && 4706 cast<ConstantSDNode>(Operand)->getAPIntValue().isNonNegative() && 4707 "Expected positive integer constant for STEP_VECTOR"); 4708 break; 4709 case ISD::FREEZE: 4710 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4711 break; 4712 case ISD::TokenFactor: 4713 case ISD::MERGE_VALUES: 4714 case ISD::CONCAT_VECTORS: 4715 return Operand; // Factor, merge or concat of one node? No need. 4716 case ISD::BUILD_VECTOR: { 4717 // Attempt to simplify BUILD_VECTOR. 4718 SDValue Ops[] = {Operand}; 4719 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 4720 return V; 4721 break; 4722 } 4723 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node"); 4724 case ISD::FP_EXTEND: 4725 assert(VT.isFloatingPoint() && 4726 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!"); 4727 if (Operand.getValueType() == VT) return Operand; // noop conversion. 4728 assert((!VT.isVector() || 4729 VT.getVectorElementCount() == 4730 Operand.getValueType().getVectorElementCount()) && 4731 "Vector element count mismatch!"); 4732 assert(Operand.getValueType().bitsLT(VT) && 4733 "Invalid fpext node, dst < src!"); 4734 if (Operand.isUndef()) 4735 return getUNDEF(VT); 4736 break; 4737 case ISD::FP_TO_SINT: 4738 case ISD::FP_TO_UINT: 4739 if (Operand.isUndef()) 4740 return getUNDEF(VT); 4741 break; 4742 case ISD::SINT_TO_FP: 4743 case ISD::UINT_TO_FP: 4744 // [us]itofp(undef) = 0, because the result value is bounded. 4745 if (Operand.isUndef()) 4746 return getConstantFP(0.0, DL, VT); 4747 break; 4748 case ISD::SIGN_EXTEND: 4749 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4750 "Invalid SIGN_EXTEND!"); 4751 assert(VT.isVector() == Operand.getValueType().isVector() && 4752 "SIGN_EXTEND result type type should be vector iff the operand " 4753 "type is vector!"); 4754 if (Operand.getValueType() == VT) return Operand; // noop extension 4755 assert((!VT.isVector() || 4756 VT.getVectorElementCount() == 4757 Operand.getValueType().getVectorElementCount()) && 4758 "Vector element count mismatch!"); 4759 assert(Operand.getValueType().bitsLT(VT) && 4760 "Invalid sext node, dst < src!"); 4761 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) 4762 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4763 else if (OpOpcode == ISD::UNDEF) 4764 // sext(undef) = 0, because the top bits will all be the same. 4765 return getConstant(0, DL, VT); 4766 break; 4767 case ISD::ZERO_EXTEND: 4768 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4769 "Invalid ZERO_EXTEND!"); 4770 assert(VT.isVector() == Operand.getValueType().isVector() && 4771 "ZERO_EXTEND result type type should be vector iff the operand " 4772 "type is vector!"); 4773 if (Operand.getValueType() == VT) return Operand; // noop extension 4774 assert((!VT.isVector() || 4775 VT.getVectorElementCount() == 4776 Operand.getValueType().getVectorElementCount()) && 4777 "Vector element count mismatch!"); 4778 assert(Operand.getValueType().bitsLT(VT) && 4779 "Invalid zext node, dst < src!"); 4780 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x) 4781 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0)); 4782 else if (OpOpcode == ISD::UNDEF) 4783 // zext(undef) = 0, because the top bits will be zero. 4784 return getConstant(0, DL, VT); 4785 break; 4786 case ISD::ANY_EXTEND: 4787 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4788 "Invalid ANY_EXTEND!"); 4789 assert(VT.isVector() == Operand.getValueType().isVector() && 4790 "ANY_EXTEND result type type should be vector iff the operand " 4791 "type is vector!"); 4792 if (Operand.getValueType() == VT) return Operand; // noop extension 4793 assert((!VT.isVector() || 4794 VT.getVectorElementCount() == 4795 Operand.getValueType().getVectorElementCount()) && 4796 "Vector element count mismatch!"); 4797 assert(Operand.getValueType().bitsLT(VT) && 4798 "Invalid anyext node, dst < src!"); 4799 4800 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4801 OpOpcode == ISD::ANY_EXTEND) 4802 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x) 4803 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4804 else if (OpOpcode == ISD::UNDEF) 4805 return getUNDEF(VT); 4806 4807 // (ext (trunc x)) -> x 4808 if (OpOpcode == ISD::TRUNCATE) { 4809 SDValue OpOp = Operand.getOperand(0); 4810 if (OpOp.getValueType() == VT) { 4811 transferDbgValues(Operand, OpOp); 4812 return OpOp; 4813 } 4814 } 4815 break; 4816 case ISD::TRUNCATE: 4817 assert(VT.isInteger() && Operand.getValueType().isInteger() && 4818 "Invalid TRUNCATE!"); 4819 assert(VT.isVector() == Operand.getValueType().isVector() && 4820 "TRUNCATE result type type should be vector iff the operand " 4821 "type is vector!"); 4822 if (Operand.getValueType() == VT) return Operand; // noop truncate 4823 assert((!VT.isVector() || 4824 VT.getVectorElementCount() == 4825 Operand.getValueType().getVectorElementCount()) && 4826 "Vector element count mismatch!"); 4827 assert(Operand.getValueType().bitsGT(VT) && 4828 "Invalid truncate node, src < dst!"); 4829 if (OpOpcode == ISD::TRUNCATE) 4830 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4831 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND || 4832 OpOpcode == ISD::ANY_EXTEND) { 4833 // If the source is smaller than the dest, we still need an extend. 4834 if (Operand.getOperand(0).getValueType().getScalarType() 4835 .bitsLT(VT.getScalarType())) 4836 return getNode(OpOpcode, DL, VT, Operand.getOperand(0)); 4837 if (Operand.getOperand(0).getValueType().bitsGT(VT)) 4838 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0)); 4839 return Operand.getOperand(0); 4840 } 4841 if (OpOpcode == ISD::UNDEF) 4842 return getUNDEF(VT); 4843 break; 4844 case ISD::ANY_EXTEND_VECTOR_INREG: 4845 case ISD::ZERO_EXTEND_VECTOR_INREG: 4846 case ISD::SIGN_EXTEND_VECTOR_INREG: 4847 assert(VT.isVector() && "This DAG node is restricted to vector types."); 4848 assert(Operand.getValueType().bitsLE(VT) && 4849 "The input must be the same size or smaller than the result."); 4850 assert(VT.getVectorNumElements() < 4851 Operand.getValueType().getVectorNumElements() && 4852 "The destination vector type must have fewer lanes than the input."); 4853 break; 4854 case ISD::ABS: 4855 assert(VT.isInteger() && VT == Operand.getValueType() && 4856 "Invalid ABS!"); 4857 if (OpOpcode == ISD::UNDEF) 4858 return getUNDEF(VT); 4859 break; 4860 case ISD::BSWAP: 4861 assert(VT.isInteger() && VT == Operand.getValueType() && 4862 "Invalid BSWAP!"); 4863 assert((VT.getScalarSizeInBits() % 16 == 0) && 4864 "BSWAP types must be a multiple of 16 bits!"); 4865 if (OpOpcode == ISD::UNDEF) 4866 return getUNDEF(VT); 4867 break; 4868 case ISD::BITREVERSE: 4869 assert(VT.isInteger() && VT == Operand.getValueType() && 4870 "Invalid BITREVERSE!"); 4871 if (OpOpcode == ISD::UNDEF) 4872 return getUNDEF(VT); 4873 break; 4874 case ISD::BITCAST: 4875 // Basic sanity checking. 4876 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() && 4877 "Cannot BITCAST between types of different sizes!"); 4878 if (VT == Operand.getValueType()) return Operand; // noop conversion. 4879 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x) 4880 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0)); 4881 if (OpOpcode == ISD::UNDEF) 4882 return getUNDEF(VT); 4883 break; 4884 case ISD::SCALAR_TO_VECTOR: 4885 assert(VT.isVector() && !Operand.getValueType().isVector() && 4886 (VT.getVectorElementType() == Operand.getValueType() || 4887 (VT.getVectorElementType().isInteger() && 4888 Operand.getValueType().isInteger() && 4889 VT.getVectorElementType().bitsLE(Operand.getValueType()))) && 4890 "Illegal SCALAR_TO_VECTOR node!"); 4891 if (OpOpcode == ISD::UNDEF) 4892 return getUNDEF(VT); 4893 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined. 4894 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT && 4895 isa<ConstantSDNode>(Operand.getOperand(1)) && 4896 Operand.getConstantOperandVal(1) == 0 && 4897 Operand.getOperand(0).getValueType() == VT) 4898 return Operand.getOperand(0); 4899 break; 4900 case ISD::FNEG: 4901 // Negation of an unknown bag of bits is still completely undefined. 4902 if (OpOpcode == ISD::UNDEF) 4903 return getUNDEF(VT); 4904 4905 if (OpOpcode == ISD::FNEG) // --X -> X 4906 return Operand.getOperand(0); 4907 break; 4908 case ISD::FABS: 4909 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X) 4910 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0)); 4911 break; 4912 case ISD::VSCALE: 4913 assert(VT == Operand.getValueType() && "Unexpected VT!"); 4914 break; 4915 case ISD::CTPOP: 4916 if (Operand.getValueType().getScalarType() == MVT::i1) 4917 return Operand; 4918 break; 4919 case ISD::CTLZ: 4920 case ISD::CTTZ: 4921 if (Operand.getValueType().getScalarType() == MVT::i1) 4922 return getNOT(DL, Operand, Operand.getValueType()); 4923 break; 4924 case ISD::VECREDUCE_SMIN: 4925 case ISD::VECREDUCE_UMAX: 4926 if (Operand.getValueType().getScalarType() == MVT::i1) 4927 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand); 4928 break; 4929 case ISD::VECREDUCE_SMAX: 4930 case ISD::VECREDUCE_UMIN: 4931 if (Operand.getValueType().getScalarType() == MVT::i1) 4932 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand); 4933 break; 4934 } 4935 4936 SDNode *N; 4937 SDVTList VTs = getVTList(VT); 4938 SDValue Ops[] = {Operand}; 4939 if (VT != MVT::Glue) { // Don't CSE flag producing nodes 4940 FoldingSetNodeID ID; 4941 AddNodeIDNode(ID, Opcode, VTs, Ops); 4942 void *IP = nullptr; 4943 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 4944 E->intersectFlagsWith(Flags); 4945 return SDValue(E, 0); 4946 } 4947 4948 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4949 N->setFlags(Flags); 4950 createOperands(N, Ops); 4951 CSEMap.InsertNode(N, IP); 4952 } else { 4953 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 4954 createOperands(N, Ops); 4955 } 4956 4957 InsertNode(N); 4958 SDValue V = SDValue(N, 0); 4959 NewSDValueDbgMsg(V, "Creating new node: ", this); 4960 return V; 4961 } 4962 4963 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1, 4964 const APInt &C2) { 4965 switch (Opcode) { 4966 case ISD::ADD: return C1 + C2; 4967 case ISD::SUB: return C1 - C2; 4968 case ISD::MUL: return C1 * C2; 4969 case ISD::AND: return C1 & C2; 4970 case ISD::OR: return C1 | C2; 4971 case ISD::XOR: return C1 ^ C2; 4972 case ISD::SHL: return C1 << C2; 4973 case ISD::SRL: return C1.lshr(C2); 4974 case ISD::SRA: return C1.ashr(C2); 4975 case ISD::ROTL: return C1.rotl(C2); 4976 case ISD::ROTR: return C1.rotr(C2); 4977 case ISD::SMIN: return C1.sle(C2) ? C1 : C2; 4978 case ISD::SMAX: return C1.sge(C2) ? C1 : C2; 4979 case ISD::UMIN: return C1.ule(C2) ? C1 : C2; 4980 case ISD::UMAX: return C1.uge(C2) ? C1 : C2; 4981 case ISD::SADDSAT: return C1.sadd_sat(C2); 4982 case ISD::UADDSAT: return C1.uadd_sat(C2); 4983 case ISD::SSUBSAT: return C1.ssub_sat(C2); 4984 case ISD::USUBSAT: return C1.usub_sat(C2); 4985 case ISD::UDIV: 4986 if (!C2.getBoolValue()) 4987 break; 4988 return C1.udiv(C2); 4989 case ISD::UREM: 4990 if (!C2.getBoolValue()) 4991 break; 4992 return C1.urem(C2); 4993 case ISD::SDIV: 4994 if (!C2.getBoolValue()) 4995 break; 4996 return C1.sdiv(C2); 4997 case ISD::SREM: 4998 if (!C2.getBoolValue()) 4999 break; 5000 return C1.srem(C2); 5001 } 5002 return llvm::None; 5003 } 5004 5005 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT, 5006 const GlobalAddressSDNode *GA, 5007 const SDNode *N2) { 5008 if (GA->getOpcode() != ISD::GlobalAddress) 5009 return SDValue(); 5010 if (!TLI->isOffsetFoldingLegal(GA)) 5011 return SDValue(); 5012 auto *C2 = dyn_cast<ConstantSDNode>(N2); 5013 if (!C2) 5014 return SDValue(); 5015 int64_t Offset = C2->getSExtValue(); 5016 switch (Opcode) { 5017 case ISD::ADD: break; 5018 case ISD::SUB: Offset = -uint64_t(Offset); break; 5019 default: return SDValue(); 5020 } 5021 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT, 5022 GA->getOffset() + uint64_t(Offset)); 5023 } 5024 5025 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) { 5026 switch (Opcode) { 5027 case ISD::SDIV: 5028 case ISD::UDIV: 5029 case ISD::SREM: 5030 case ISD::UREM: { 5031 // If a divisor is zero/undef or any element of a divisor vector is 5032 // zero/undef, the whole op is undef. 5033 assert(Ops.size() == 2 && "Div/rem should have 2 operands"); 5034 SDValue Divisor = Ops[1]; 5035 if (Divisor.isUndef() || isNullConstant(Divisor)) 5036 return true; 5037 5038 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) && 5039 llvm::any_of(Divisor->op_values(), 5040 [](SDValue V) { return V.isUndef() || 5041 isNullConstant(V); }); 5042 // TODO: Handle signed overflow. 5043 } 5044 // TODO: Handle oversized shifts. 5045 default: 5046 return false; 5047 } 5048 } 5049 5050 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, 5051 EVT VT, ArrayRef<SDValue> Ops) { 5052 // If the opcode is a target-specific ISD node, there's nothing we can 5053 // do here and the operand rules may not line up with the below, so 5054 // bail early. 5055 if (Opcode >= ISD::BUILTIN_OP_END) 5056 return SDValue(); 5057 5058 // For now, the array Ops should only contain two values. 5059 // This enforcement will be removed once this function is merged with 5060 // FoldConstantVectorArithmetic 5061 if (Ops.size() != 2) 5062 return SDValue(); 5063 5064 if (isUndef(Opcode, Ops)) 5065 return getUNDEF(VT); 5066 5067 SDNode *N1 = Ops[0].getNode(); 5068 SDNode *N2 = Ops[1].getNode(); 5069 5070 // Handle the case of two scalars. 5071 if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) { 5072 if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) { 5073 if (C1->isOpaque() || C2->isOpaque()) 5074 return SDValue(); 5075 5076 Optional<APInt> FoldAttempt = 5077 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue()); 5078 if (!FoldAttempt) 5079 return SDValue(); 5080 5081 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT); 5082 assert((!Folded || !VT.isVector()) && 5083 "Can't fold vectors ops with scalar operands"); 5084 return Folded; 5085 } 5086 } 5087 5088 // fold (add Sym, c) -> Sym+c 5089 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1)) 5090 return FoldSymbolOffset(Opcode, VT, GA, N2); 5091 if (TLI->isCommutativeBinOp(Opcode)) 5092 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2)) 5093 return FoldSymbolOffset(Opcode, VT, GA, N1); 5094 5095 // TODO: All the folds below are performed lane-by-lane and assume a fixed 5096 // vector width, however we should be able to do constant folds involving 5097 // splat vector nodes too. 5098 if (VT.isScalableVector()) 5099 return SDValue(); 5100 5101 // For fixed width vectors, extract each constant element and fold them 5102 // individually. Either input may be an undef value. 5103 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 5104 if (!BV1 && !N1->isUndef()) 5105 return SDValue(); 5106 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2); 5107 if (!BV2 && !N2->isUndef()) 5108 return SDValue(); 5109 // If both operands are undef, that's handled the same way as scalars. 5110 if (!BV1 && !BV2) 5111 return SDValue(); 5112 5113 assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) && 5114 "Vector binop with different number of elements in operands?"); 5115 5116 EVT SVT = VT.getScalarType(); 5117 EVT LegalSVT = SVT; 5118 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5119 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5120 if (LegalSVT.bitsLT(SVT)) 5121 return SDValue(); 5122 } 5123 SmallVector<SDValue, 4> Outputs; 5124 unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands(); 5125 for (unsigned I = 0; I != NumOps; ++I) { 5126 SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT); 5127 SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT); 5128 if (SVT.isInteger()) { 5129 if (V1->getValueType(0).bitsGT(SVT)) 5130 V1 = getNode(ISD::TRUNCATE, DL, SVT, V1); 5131 if (V2->getValueType(0).bitsGT(SVT)) 5132 V2 = getNode(ISD::TRUNCATE, DL, SVT, V2); 5133 } 5134 5135 if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT) 5136 return SDValue(); 5137 5138 // Fold one vector element. 5139 SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2); 5140 if (LegalSVT != SVT) 5141 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5142 5143 // Scalar folding only succeeded if the result is a constant or UNDEF. 5144 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5145 ScalarResult.getOpcode() != ISD::ConstantFP) 5146 return SDValue(); 5147 Outputs.push_back(ScalarResult); 5148 } 5149 5150 assert(VT.getVectorNumElements() == Outputs.size() && 5151 "Vector size mismatch!"); 5152 5153 // We may have a vector type but a scalar result. Create a splat. 5154 Outputs.resize(VT.getVectorNumElements(), Outputs.back()); 5155 5156 // Build a big vector out of the scalar elements we generated. 5157 return getBuildVector(VT, SDLoc(), Outputs); 5158 } 5159 5160 // TODO: Merge with FoldConstantArithmetic 5161 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 5162 const SDLoc &DL, EVT VT, 5163 ArrayRef<SDValue> Ops, 5164 const SDNodeFlags Flags) { 5165 // If the opcode is a target-specific ISD node, there's nothing we can 5166 // do here and the operand rules may not line up with the below, so 5167 // bail early. 5168 if (Opcode >= ISD::BUILTIN_OP_END) 5169 return SDValue(); 5170 5171 if (isUndef(Opcode, Ops)) 5172 return getUNDEF(VT); 5173 5174 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 5175 if (!VT.isVector()) 5176 return SDValue(); 5177 5178 // TODO: All the folds below are performed lane-by-lane and assume a fixed 5179 // vector width, however we should be able to do constant folds involving 5180 // splat vector nodes too. 5181 if (VT.isScalableVector()) 5182 return SDValue(); 5183 5184 // From this point onwards all vectors are assumed to be fixed width. 5185 unsigned NumElts = VT.getVectorNumElements(); 5186 5187 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) { 5188 return !Op.getValueType().isVector() || 5189 Op.getValueType().getVectorNumElements() == NumElts; 5190 }; 5191 5192 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) { 5193 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 5194 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) || 5195 (BV && BV->isConstant()); 5196 }; 5197 5198 // All operands must be vector types with the same number of elements as 5199 // the result type and must be either UNDEF or a build vector of constant 5200 // or UNDEF scalars. 5201 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) || 5202 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5203 return SDValue(); 5204 5205 // If we are comparing vectors, then the result needs to be a i1 boolean 5206 // that is then sign-extended back to the legal result type. 5207 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5208 5209 // Find legal integer scalar type for constant promotion and 5210 // ensure that its scalar size is at least as large as source. 5211 EVT LegalSVT = VT.getScalarType(); 5212 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5213 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5214 if (LegalSVT.bitsLT(VT.getScalarType())) 5215 return SDValue(); 5216 } 5217 5218 // Constant fold each scalar lane separately. 5219 SmallVector<SDValue, 4> ScalarResults; 5220 for (unsigned i = 0; i != NumElts; i++) { 5221 SmallVector<SDValue, 4> ScalarOps; 5222 for (SDValue Op : Ops) { 5223 EVT InSVT = Op.getValueType().getScalarType(); 5224 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op); 5225 if (!InBV) { 5226 // We've checked that this is UNDEF or a constant of some kind. 5227 if (Op.isUndef()) 5228 ScalarOps.push_back(getUNDEF(InSVT)); 5229 else 5230 ScalarOps.push_back(Op); 5231 continue; 5232 } 5233 5234 SDValue ScalarOp = InBV->getOperand(i); 5235 EVT ScalarVT = ScalarOp.getValueType(); 5236 5237 // Build vector (integer) scalar operands may need implicit 5238 // truncation - do this before constant folding. 5239 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5240 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5241 5242 ScalarOps.push_back(ScalarOp); 5243 } 5244 5245 // Constant fold the scalar operands. 5246 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 5247 5248 // Legalize the (integer) scalar constant if necessary. 5249 if (LegalSVT != SVT) 5250 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5251 5252 // Scalar folding only succeeded if the result is a constant or UNDEF. 5253 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5254 ScalarResult.getOpcode() != ISD::ConstantFP) 5255 return SDValue(); 5256 ScalarResults.push_back(ScalarResult); 5257 } 5258 5259 SDValue V = getBuildVector(VT, DL, ScalarResults); 5260 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5261 return V; 5262 } 5263 5264 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5265 EVT VT, SDValue N1, SDValue N2) { 5266 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5267 // should. That will require dealing with a potentially non-default 5268 // rounding mode, checking the "opStatus" return value from the APFloat 5269 // math calculations, and possibly other variations. 5270 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 5271 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 5272 if (N1CFP && N2CFP) { 5273 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF(); 5274 switch (Opcode) { 5275 case ISD::FADD: 5276 C1.add(C2, APFloat::rmNearestTiesToEven); 5277 return getConstantFP(C1, DL, VT); 5278 case ISD::FSUB: 5279 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5280 return getConstantFP(C1, DL, VT); 5281 case ISD::FMUL: 5282 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5283 return getConstantFP(C1, DL, VT); 5284 case ISD::FDIV: 5285 C1.divide(C2, APFloat::rmNearestTiesToEven); 5286 return getConstantFP(C1, DL, VT); 5287 case ISD::FREM: 5288 C1.mod(C2); 5289 return getConstantFP(C1, DL, VT); 5290 case ISD::FCOPYSIGN: 5291 C1.copySign(C2); 5292 return getConstantFP(C1, DL, VT); 5293 default: break; 5294 } 5295 } 5296 if (N1CFP && Opcode == ISD::FP_ROUND) { 5297 APFloat C1 = N1CFP->getValueAPF(); // make copy 5298 bool Unused; 5299 // This can return overflow, underflow, or inexact; we don't care. 5300 // FIXME need to be more flexible about rounding mode. 5301 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5302 &Unused); 5303 return getConstantFP(C1, DL, VT); 5304 } 5305 5306 switch (Opcode) { 5307 case ISD::FSUB: 5308 // -0.0 - undef --> undef (consistent with "fneg undef") 5309 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef()) 5310 return getUNDEF(VT); 5311 LLVM_FALLTHROUGH; 5312 5313 case ISD::FADD: 5314 case ISD::FMUL: 5315 case ISD::FDIV: 5316 case ISD::FREM: 5317 // If both operands are undef, the result is undef. If 1 operand is undef, 5318 // the result is NaN. This should match the behavior of the IR optimizer. 5319 if (N1.isUndef() && N2.isUndef()) 5320 return getUNDEF(VT); 5321 if (N1.isUndef() || N2.isUndef()) 5322 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5323 } 5324 return SDValue(); 5325 } 5326 5327 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5328 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5329 5330 // There's no need to assert on a byte-aligned pointer. All pointers are at 5331 // least byte aligned. 5332 if (A == Align(1)) 5333 return Val; 5334 5335 FoldingSetNodeID ID; 5336 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5337 ID.AddInteger(A.value()); 5338 5339 void *IP = nullptr; 5340 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5341 return SDValue(E, 0); 5342 5343 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5344 Val.getValueType(), A); 5345 createOperands(N, {Val}); 5346 5347 CSEMap.InsertNode(N, IP); 5348 InsertNode(N); 5349 5350 SDValue V(N, 0); 5351 NewSDValueDbgMsg(V, "Creating new node: ", this); 5352 return V; 5353 } 5354 5355 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5356 SDValue N1, SDValue N2) { 5357 SDNodeFlags Flags; 5358 if (Inserter) 5359 Flags = Inserter->getFlags(); 5360 return getNode(Opcode, DL, VT, N1, N2, Flags); 5361 } 5362 5363 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5364 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5365 assert(N1.getOpcode() != ISD::DELETED_NODE && 5366 N2.getOpcode() != ISD::DELETED_NODE && 5367 "Operand is DELETED_NODE!"); 5368 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5369 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5370 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5371 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5372 5373 // Canonicalize constant to RHS if commutative. 5374 if (TLI->isCommutativeBinOp(Opcode)) { 5375 if (N1C && !N2C) { 5376 std::swap(N1C, N2C); 5377 std::swap(N1, N2); 5378 } else if (N1CFP && !N2CFP) { 5379 std::swap(N1CFP, N2CFP); 5380 std::swap(N1, N2); 5381 } 5382 } 5383 5384 switch (Opcode) { 5385 default: break; 5386 case ISD::TokenFactor: 5387 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5388 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5389 // Fold trivial token factors. 5390 if (N1.getOpcode() == ISD::EntryToken) return N2; 5391 if (N2.getOpcode() == ISD::EntryToken) return N1; 5392 if (N1 == N2) return N1; 5393 break; 5394 case ISD::BUILD_VECTOR: { 5395 // Attempt to simplify BUILD_VECTOR. 5396 SDValue Ops[] = {N1, N2}; 5397 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5398 return V; 5399 break; 5400 } 5401 case ISD::CONCAT_VECTORS: { 5402 SDValue Ops[] = {N1, N2}; 5403 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5404 return V; 5405 break; 5406 } 5407 case ISD::AND: 5408 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5409 assert(N1.getValueType() == N2.getValueType() && 5410 N1.getValueType() == VT && "Binary operator types must match!"); 5411 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5412 // worth handling here. 5413 if (N2C && N2C->isNullValue()) 5414 return N2; 5415 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 5416 return N1; 5417 break; 5418 case ISD::OR: 5419 case ISD::XOR: 5420 case ISD::ADD: 5421 case ISD::SUB: 5422 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5423 assert(N1.getValueType() == N2.getValueType() && 5424 N1.getValueType() == VT && "Binary operator types must match!"); 5425 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5426 // it's worth handling here. 5427 if (N2C && N2C->isNullValue()) 5428 return N1; 5429 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5430 VT.getVectorElementType() == MVT::i1) 5431 return getNode(ISD::XOR, DL, VT, N1, N2); 5432 break; 5433 case ISD::MUL: 5434 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5435 assert(N1.getValueType() == N2.getValueType() && 5436 N1.getValueType() == VT && "Binary operator types must match!"); 5437 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5438 return getNode(ISD::AND, DL, VT, N1, N2); 5439 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5440 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5441 const APInt &N2CImm = N2C->getAPIntValue(); 5442 return getVScale(DL, VT, MulImm * N2CImm); 5443 } 5444 break; 5445 case ISD::UDIV: 5446 case ISD::UREM: 5447 case ISD::MULHU: 5448 case ISD::MULHS: 5449 case ISD::SDIV: 5450 case ISD::SREM: 5451 case ISD::SADDSAT: 5452 case ISD::SSUBSAT: 5453 case ISD::UADDSAT: 5454 case ISD::USUBSAT: 5455 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5456 assert(N1.getValueType() == N2.getValueType() && 5457 N1.getValueType() == VT && "Binary operator types must match!"); 5458 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5459 // fold (add_sat x, y) -> (or x, y) for bool types. 5460 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5461 return getNode(ISD::OR, DL, VT, N1, N2); 5462 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5463 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5464 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5465 } 5466 break; 5467 case ISD::SMIN: 5468 case ISD::UMAX: 5469 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5470 assert(N1.getValueType() == N2.getValueType() && 5471 N1.getValueType() == VT && "Binary operator types must match!"); 5472 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5473 return getNode(ISD::OR, DL, VT, N1, N2); 5474 break; 5475 case ISD::SMAX: 5476 case ISD::UMIN: 5477 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5478 assert(N1.getValueType() == N2.getValueType() && 5479 N1.getValueType() == VT && "Binary operator types must match!"); 5480 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5481 return getNode(ISD::AND, DL, VT, N1, N2); 5482 break; 5483 case ISD::FADD: 5484 case ISD::FSUB: 5485 case ISD::FMUL: 5486 case ISD::FDIV: 5487 case ISD::FREM: 5488 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5489 assert(N1.getValueType() == N2.getValueType() && 5490 N1.getValueType() == VT && "Binary operator types must match!"); 5491 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5492 return V; 5493 break; 5494 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5495 assert(N1.getValueType() == VT && 5496 N1.getValueType().isFloatingPoint() && 5497 N2.getValueType().isFloatingPoint() && 5498 "Invalid FCOPYSIGN!"); 5499 break; 5500 case ISD::SHL: 5501 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5502 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5503 const APInt &ShiftImm = N2C->getAPIntValue(); 5504 return getVScale(DL, VT, MulImm << ShiftImm); 5505 } 5506 LLVM_FALLTHROUGH; 5507 case ISD::SRA: 5508 case ISD::SRL: 5509 if (SDValue V = simplifyShift(N1, N2)) 5510 return V; 5511 LLVM_FALLTHROUGH; 5512 case ISD::ROTL: 5513 case ISD::ROTR: 5514 assert(VT == N1.getValueType() && 5515 "Shift operators return type must be the same as their first arg"); 5516 assert(VT.isInteger() && N2.getValueType().isInteger() && 5517 "Shifts only work on integers"); 5518 assert((!VT.isVector() || VT == N2.getValueType()) && 5519 "Vector shift amounts must be in the same as their first arg"); 5520 // Verify that the shift amount VT is big enough to hold valid shift 5521 // amounts. This catches things like trying to shift an i1024 value by an 5522 // i8, which is easy to fall into in generic code that uses 5523 // TLI.getShiftAmount(). 5524 assert(N2.getValueType().getScalarSizeInBits() >= 5525 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5526 "Invalid use of small shift amount with oversized value!"); 5527 5528 // Always fold shifts of i1 values so the code generator doesn't need to 5529 // handle them. Since we know the size of the shift has to be less than the 5530 // size of the value, the shift/rotate count is guaranteed to be zero. 5531 if (VT == MVT::i1) 5532 return N1; 5533 if (N2C && N2C->isNullValue()) 5534 return N1; 5535 break; 5536 case ISD::FP_ROUND: 5537 assert(VT.isFloatingPoint() && 5538 N1.getValueType().isFloatingPoint() && 5539 VT.bitsLE(N1.getValueType()) && 5540 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5541 "Invalid FP_ROUND!"); 5542 if (N1.getValueType() == VT) return N1; // noop conversion. 5543 break; 5544 case ISD::AssertSext: 5545 case ISD::AssertZext: { 5546 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5547 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5548 assert(VT.isInteger() && EVT.isInteger() && 5549 "Cannot *_EXTEND_INREG FP types"); 5550 assert(!EVT.isVector() && 5551 "AssertSExt/AssertZExt type should be the vector element type " 5552 "rather than the vector type!"); 5553 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5554 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5555 break; 5556 } 5557 case ISD::SIGN_EXTEND_INREG: { 5558 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5559 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5560 assert(VT.isInteger() && EVT.isInteger() && 5561 "Cannot *_EXTEND_INREG FP types"); 5562 assert(EVT.isVector() == VT.isVector() && 5563 "SIGN_EXTEND_INREG type should be vector iff the operand " 5564 "type is vector!"); 5565 assert((!EVT.isVector() || 5566 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5567 "Vector element counts must match in SIGN_EXTEND_INREG"); 5568 assert(EVT.bitsLE(VT) && "Not extending!"); 5569 if (EVT == VT) return N1; // Not actually extending 5570 5571 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5572 unsigned FromBits = EVT.getScalarSizeInBits(); 5573 Val <<= Val.getBitWidth() - FromBits; 5574 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5575 return getConstant(Val, DL, ConstantVT); 5576 }; 5577 5578 if (N1C) { 5579 const APInt &Val = N1C->getAPIntValue(); 5580 return SignExtendInReg(Val, VT); 5581 } 5582 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5583 SmallVector<SDValue, 8> Ops; 5584 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5585 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5586 SDValue Op = N1.getOperand(i); 5587 if (Op.isUndef()) { 5588 Ops.push_back(getUNDEF(OpVT)); 5589 continue; 5590 } 5591 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5592 APInt Val = C->getAPIntValue(); 5593 Ops.push_back(SignExtendInReg(Val, OpVT)); 5594 } 5595 return getBuildVector(VT, DL, Ops); 5596 } 5597 break; 5598 } 5599 case ISD::EXTRACT_VECTOR_ELT: 5600 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5601 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5602 element type of the vector."); 5603 5604 // Extract from an undefined value or using an undefined index is undefined. 5605 if (N1.isUndef() || N2.isUndef()) 5606 return getUNDEF(VT); 5607 5608 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5609 // vectors. For scalable vectors we will provide appropriate support for 5610 // dealing with arbitrary indices. 5611 if (N2C && N1.getValueType().isFixedLengthVector() && 5612 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5613 return getUNDEF(VT); 5614 5615 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5616 // expanding copies of large vectors from registers. This only works for 5617 // fixed length vectors, since we need to know the exact number of 5618 // elements. 5619 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5620 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5621 unsigned Factor = 5622 N1.getOperand(0).getValueType().getVectorNumElements(); 5623 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5624 N1.getOperand(N2C->getZExtValue() / Factor), 5625 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5626 } 5627 5628 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5629 // lowering is expanding large vector constants. 5630 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5631 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5632 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5633 N1.getValueType().isFixedLengthVector()) && 5634 "BUILD_VECTOR used for scalable vectors"); 5635 unsigned Index = 5636 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5637 SDValue Elt = N1.getOperand(Index); 5638 5639 if (VT != Elt.getValueType()) 5640 // If the vector element type is not legal, the BUILD_VECTOR operands 5641 // are promoted and implicitly truncated, and the result implicitly 5642 // extended. Make that explicit here. 5643 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5644 5645 return Elt; 5646 } 5647 5648 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5649 // operations are lowered to scalars. 5650 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5651 // If the indices are the same, return the inserted element else 5652 // if the indices are known different, extract the element from 5653 // the original vector. 5654 SDValue N1Op2 = N1.getOperand(2); 5655 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5656 5657 if (N1Op2C && N2C) { 5658 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5659 if (VT == N1.getOperand(1).getValueType()) 5660 return N1.getOperand(1); 5661 else 5662 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5663 } 5664 5665 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5666 } 5667 } 5668 5669 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5670 // when vector types are scalarized and v1iX is legal. 5671 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5672 // Here we are completely ignoring the extract element index (N2), 5673 // which is fine for fixed width vectors, since any index other than 0 5674 // is undefined anyway. However, this cannot be ignored for scalable 5675 // vectors - in theory we could support this, but we don't want to do this 5676 // without a profitability check. 5677 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5678 N1.getValueType().isFixedLengthVector() && 5679 N1.getValueType().getVectorNumElements() == 1) { 5680 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5681 N1.getOperand(1)); 5682 } 5683 break; 5684 case ISD::EXTRACT_ELEMENT: 5685 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5686 assert(!N1.getValueType().isVector() && !VT.isVector() && 5687 (N1.getValueType().isInteger() == VT.isInteger()) && 5688 N1.getValueType() != VT && 5689 "Wrong types for EXTRACT_ELEMENT!"); 5690 5691 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5692 // 64-bit integers into 32-bit parts. Instead of building the extract of 5693 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5694 if (N1.getOpcode() == ISD::BUILD_PAIR) 5695 return N1.getOperand(N2C->getZExtValue()); 5696 5697 // EXTRACT_ELEMENT of a constant int is also very common. 5698 if (N1C) { 5699 unsigned ElementSize = VT.getSizeInBits(); 5700 unsigned Shift = ElementSize * N2C->getZExtValue(); 5701 const APInt &Val = N1C->getAPIntValue(); 5702 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 5703 } 5704 break; 5705 case ISD::EXTRACT_SUBVECTOR: 5706 EVT N1VT = N1.getValueType(); 5707 assert(VT.isVector() && N1VT.isVector() && 5708 "Extract subvector VTs must be vectors!"); 5709 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5710 "Extract subvector VTs must have the same element type!"); 5711 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5712 "Cannot extract a scalable vector from a fixed length vector!"); 5713 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5714 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5715 "Extract subvector must be from larger vector to smaller vector!"); 5716 assert(N2C && "Extract subvector index must be a constant"); 5717 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5718 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5719 N1VT.getVectorMinNumElements()) && 5720 "Extract subvector overflow!"); 5721 assert(N2C->getAPIntValue().getBitWidth() == 5722 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5723 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 5724 5725 // Trivial extraction. 5726 if (VT == N1VT) 5727 return N1; 5728 5729 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 5730 if (N1.isUndef()) 5731 return getUNDEF(VT); 5732 5733 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 5734 // the concat have the same type as the extract. 5735 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 5736 VT == N1.getOperand(0).getValueType()) { 5737 unsigned Factor = VT.getVectorMinNumElements(); 5738 return N1.getOperand(N2C->getZExtValue() / Factor); 5739 } 5740 5741 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 5742 // during shuffle legalization. 5743 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 5744 VT == N1.getOperand(1).getValueType()) 5745 return N1.getOperand(1); 5746 break; 5747 } 5748 5749 // Perform trivial constant folding. 5750 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 5751 return SV; 5752 5753 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2)) 5754 return V; 5755 5756 // Canonicalize an UNDEF to the RHS, even over a constant. 5757 if (N1.isUndef()) { 5758 if (TLI->isCommutativeBinOp(Opcode)) { 5759 std::swap(N1, N2); 5760 } else { 5761 switch (Opcode) { 5762 case ISD::SIGN_EXTEND_INREG: 5763 case ISD::SUB: 5764 return getUNDEF(VT); // fold op(undef, arg2) -> undef 5765 case ISD::UDIV: 5766 case ISD::SDIV: 5767 case ISD::UREM: 5768 case ISD::SREM: 5769 case ISD::SSUBSAT: 5770 case ISD::USUBSAT: 5771 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 5772 } 5773 } 5774 } 5775 5776 // Fold a bunch of operators when the RHS is undef. 5777 if (N2.isUndef()) { 5778 switch (Opcode) { 5779 case ISD::XOR: 5780 if (N1.isUndef()) 5781 // Handle undef ^ undef -> 0 special case. This is a common 5782 // idiom (misuse). 5783 return getConstant(0, DL, VT); 5784 LLVM_FALLTHROUGH; 5785 case ISD::ADD: 5786 case ISD::SUB: 5787 case ISD::UDIV: 5788 case ISD::SDIV: 5789 case ISD::UREM: 5790 case ISD::SREM: 5791 return getUNDEF(VT); // fold op(arg1, undef) -> undef 5792 case ISD::MUL: 5793 case ISD::AND: 5794 case ISD::SSUBSAT: 5795 case ISD::USUBSAT: 5796 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 5797 case ISD::OR: 5798 case ISD::SADDSAT: 5799 case ISD::UADDSAT: 5800 return getAllOnesConstant(DL, VT); 5801 } 5802 } 5803 5804 // Memoize this node if possible. 5805 SDNode *N; 5806 SDVTList VTs = getVTList(VT); 5807 SDValue Ops[] = {N1, N2}; 5808 if (VT != MVT::Glue) { 5809 FoldingSetNodeID ID; 5810 AddNodeIDNode(ID, Opcode, VTs, Ops); 5811 void *IP = nullptr; 5812 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5813 E->intersectFlagsWith(Flags); 5814 return SDValue(E, 0); 5815 } 5816 5817 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5818 N->setFlags(Flags); 5819 createOperands(N, Ops); 5820 CSEMap.InsertNode(N, IP); 5821 } else { 5822 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5823 createOperands(N, Ops); 5824 } 5825 5826 InsertNode(N); 5827 SDValue V = SDValue(N, 0); 5828 NewSDValueDbgMsg(V, "Creating new node: ", this); 5829 return V; 5830 } 5831 5832 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5833 SDValue N1, SDValue N2, SDValue N3) { 5834 SDNodeFlags Flags; 5835 if (Inserter) 5836 Flags = Inserter->getFlags(); 5837 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 5838 } 5839 5840 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5841 SDValue N1, SDValue N2, SDValue N3, 5842 const SDNodeFlags Flags) { 5843 assert(N1.getOpcode() != ISD::DELETED_NODE && 5844 N2.getOpcode() != ISD::DELETED_NODE && 5845 N3.getOpcode() != ISD::DELETED_NODE && 5846 "Operand is DELETED_NODE!"); 5847 // Perform various simplifications. 5848 switch (Opcode) { 5849 case ISD::FMA: { 5850 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5851 assert(N1.getValueType() == VT && N2.getValueType() == VT && 5852 N3.getValueType() == VT && "FMA types must match!"); 5853 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5854 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5855 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 5856 if (N1CFP && N2CFP && N3CFP) { 5857 APFloat V1 = N1CFP->getValueAPF(); 5858 const APFloat &V2 = N2CFP->getValueAPF(); 5859 const APFloat &V3 = N3CFP->getValueAPF(); 5860 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 5861 return getConstantFP(V1, DL, VT); 5862 } 5863 break; 5864 } 5865 case ISD::BUILD_VECTOR: { 5866 // Attempt to simplify BUILD_VECTOR. 5867 SDValue Ops[] = {N1, N2, N3}; 5868 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5869 return V; 5870 break; 5871 } 5872 case ISD::CONCAT_VECTORS: { 5873 SDValue Ops[] = {N1, N2, N3}; 5874 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5875 return V; 5876 break; 5877 } 5878 case ISD::SETCC: { 5879 assert(VT.isInteger() && "SETCC result type must be an integer!"); 5880 assert(N1.getValueType() == N2.getValueType() && 5881 "SETCC operands must have the same type!"); 5882 assert(VT.isVector() == N1.getValueType().isVector() && 5883 "SETCC type should be vector iff the operand type is vector!"); 5884 assert((!VT.isVector() || VT.getVectorElementCount() == 5885 N1.getValueType().getVectorElementCount()) && 5886 "SETCC vector element counts must match!"); 5887 // Use FoldSetCC to simplify SETCC's. 5888 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 5889 return V; 5890 // Vector constant folding. 5891 SDValue Ops[] = {N1, N2, N3}; 5892 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) { 5893 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 5894 return V; 5895 } 5896 break; 5897 } 5898 case ISD::SELECT: 5899 case ISD::VSELECT: 5900 if (SDValue V = simplifySelect(N1, N2, N3)) 5901 return V; 5902 break; 5903 case ISD::VECTOR_SHUFFLE: 5904 llvm_unreachable("should use getVectorShuffle constructor!"); 5905 case ISD::INSERT_VECTOR_ELT: { 5906 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 5907 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 5908 // for scalable vectors where we will generate appropriate code to 5909 // deal with out-of-bounds cases correctly. 5910 if (N3C && N1.getValueType().isFixedLengthVector() && 5911 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 5912 return getUNDEF(VT); 5913 5914 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 5915 if (N3.isUndef()) 5916 return getUNDEF(VT); 5917 5918 // If the inserted element is an UNDEF, just use the input vector. 5919 if (N2.isUndef()) 5920 return N1; 5921 5922 break; 5923 } 5924 case ISD::INSERT_SUBVECTOR: { 5925 // Inserting undef into undef is still undef. 5926 if (N1.isUndef() && N2.isUndef()) 5927 return getUNDEF(VT); 5928 5929 EVT N2VT = N2.getValueType(); 5930 assert(VT == N1.getValueType() && 5931 "Dest and insert subvector source types must match!"); 5932 assert(VT.isVector() && N2VT.isVector() && 5933 "Insert subvector VTs must be vectors!"); 5934 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 5935 "Cannot insert a scalable vector into a fixed length vector!"); 5936 assert((VT.isScalableVector() != N2VT.isScalableVector() || 5937 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 5938 "Insert subvector must be from smaller vector to larger vector!"); 5939 assert(isa<ConstantSDNode>(N3) && 5940 "Insert subvector index must be constant"); 5941 assert((VT.isScalableVector() != N2VT.isScalableVector() || 5942 (N2VT.getVectorMinNumElements() + 5943 cast<ConstantSDNode>(N3)->getZExtValue()) <= 5944 VT.getVectorMinNumElements()) && 5945 "Insert subvector overflow!"); 5946 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 5947 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5948 "Constant index for INSERT_SUBVECTOR has an invalid size"); 5949 5950 // Trivial insertion. 5951 if (VT == N2VT) 5952 return N2; 5953 5954 // If this is an insert of an extracted vector into an undef vector, we 5955 // can just use the input to the extract. 5956 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5957 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 5958 return N2.getOperand(0); 5959 break; 5960 } 5961 case ISD::BITCAST: 5962 // Fold bit_convert nodes from a type to themselves. 5963 if (N1.getValueType() == VT) 5964 return N1; 5965 break; 5966 } 5967 5968 // Memoize node if it doesn't produce a flag. 5969 SDNode *N; 5970 SDVTList VTs = getVTList(VT); 5971 SDValue Ops[] = {N1, N2, N3}; 5972 if (VT != MVT::Glue) { 5973 FoldingSetNodeID ID; 5974 AddNodeIDNode(ID, Opcode, VTs, Ops); 5975 void *IP = nullptr; 5976 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5977 E->intersectFlagsWith(Flags); 5978 return SDValue(E, 0); 5979 } 5980 5981 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5982 N->setFlags(Flags); 5983 createOperands(N, Ops); 5984 CSEMap.InsertNode(N, IP); 5985 } else { 5986 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5987 createOperands(N, Ops); 5988 } 5989 5990 InsertNode(N); 5991 SDValue V = SDValue(N, 0); 5992 NewSDValueDbgMsg(V, "Creating new node: ", this); 5993 return V; 5994 } 5995 5996 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5997 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 5998 SDValue Ops[] = { N1, N2, N3, N4 }; 5999 return getNode(Opcode, DL, VT, Ops); 6000 } 6001 6002 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6003 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6004 SDValue N5) { 6005 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6006 return getNode(Opcode, DL, VT, Ops); 6007 } 6008 6009 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6010 /// the incoming stack arguments to be loaded from the stack. 6011 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6012 SmallVector<SDValue, 8> ArgChains; 6013 6014 // Include the original chain at the beginning of the list. When this is 6015 // used by target LowerCall hooks, this helps legalize find the 6016 // CALLSEQ_BEGIN node. 6017 ArgChains.push_back(Chain); 6018 6019 // Add a chain value for each stack argument. 6020 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 6021 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 6022 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 6023 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6024 if (FI->getIndex() < 0) 6025 ArgChains.push_back(SDValue(L, 1)); 6026 6027 // Build a tokenfactor for all the chains. 6028 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6029 } 6030 6031 /// getMemsetValue - Vectorized representation of the memset value 6032 /// operand. 6033 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6034 const SDLoc &dl) { 6035 assert(!Value.isUndef()); 6036 6037 unsigned NumBits = VT.getScalarSizeInBits(); 6038 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6039 assert(C->getAPIntValue().getBitWidth() == 8); 6040 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6041 if (VT.isInteger()) { 6042 bool IsOpaque = VT.getSizeInBits() > 64 || 6043 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6044 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6045 } 6046 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6047 VT); 6048 } 6049 6050 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6051 EVT IntVT = VT.getScalarType(); 6052 if (!IntVT.isInteger()) 6053 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6054 6055 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6056 if (NumBits > 8) { 6057 // Use a multiplication with 0x010101... to extend the input to the 6058 // required length. 6059 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6060 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6061 DAG.getConstant(Magic, dl, IntVT)); 6062 } 6063 6064 if (VT != Value.getValueType() && !VT.isInteger()) 6065 Value = DAG.getBitcast(VT.getScalarType(), Value); 6066 if (VT != Value.getValueType()) 6067 Value = DAG.getSplatBuildVector(VT, dl, Value); 6068 6069 return Value; 6070 } 6071 6072 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6073 /// used when a memcpy is turned into a memset when the source is a constant 6074 /// string ptr. 6075 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6076 const TargetLowering &TLI, 6077 const ConstantDataArraySlice &Slice) { 6078 // Handle vector with all elements zero. 6079 if (Slice.Array == nullptr) { 6080 if (VT.isInteger()) 6081 return DAG.getConstant(0, dl, VT); 6082 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6083 return DAG.getConstantFP(0.0, dl, VT); 6084 else if (VT.isVector()) { 6085 unsigned NumElts = VT.getVectorNumElements(); 6086 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6087 return DAG.getNode(ISD::BITCAST, dl, VT, 6088 DAG.getConstant(0, dl, 6089 EVT::getVectorVT(*DAG.getContext(), 6090 EltVT, NumElts))); 6091 } else 6092 llvm_unreachable("Expected type!"); 6093 } 6094 6095 assert(!VT.isVector() && "Can't handle vector type here!"); 6096 unsigned NumVTBits = VT.getSizeInBits(); 6097 unsigned NumVTBytes = NumVTBits / 8; 6098 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6099 6100 APInt Val(NumVTBits, 0); 6101 if (DAG.getDataLayout().isLittleEndian()) { 6102 for (unsigned i = 0; i != NumBytes; ++i) 6103 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6104 } else { 6105 for (unsigned i = 0; i != NumBytes; ++i) 6106 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6107 } 6108 6109 // If the "cost" of materializing the integer immediate is less than the cost 6110 // of a load, then it is cost effective to turn the load into the immediate. 6111 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6112 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6113 return DAG.getConstant(Val, dl, VT); 6114 return SDValue(nullptr, 0); 6115 } 6116 6117 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6118 const SDLoc &DL, 6119 const SDNodeFlags Flags) { 6120 EVT VT = Base.getValueType(); 6121 SDValue Index; 6122 6123 if (Offset.isScalable()) 6124 Index = getVScale(DL, Base.getValueType(), 6125 APInt(Base.getValueSizeInBits().getFixedSize(), 6126 Offset.getKnownMinSize())); 6127 else 6128 Index = getConstant(Offset.getFixedSize(), DL, VT); 6129 6130 return getMemBasePlusOffset(Base, Index, DL, Flags); 6131 } 6132 6133 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6134 const SDLoc &DL, 6135 const SDNodeFlags Flags) { 6136 assert(Offset.getValueType().isInteger()); 6137 EVT BasePtrVT = Ptr.getValueType(); 6138 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6139 } 6140 6141 /// Returns true if memcpy source is constant data. 6142 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6143 uint64_t SrcDelta = 0; 6144 GlobalAddressSDNode *G = nullptr; 6145 if (Src.getOpcode() == ISD::GlobalAddress) 6146 G = cast<GlobalAddressSDNode>(Src); 6147 else if (Src.getOpcode() == ISD::ADD && 6148 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6149 Src.getOperand(1).getOpcode() == ISD::Constant) { 6150 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6151 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6152 } 6153 if (!G) 6154 return false; 6155 6156 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6157 SrcDelta + G->getOffset()); 6158 } 6159 6160 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6161 SelectionDAG &DAG) { 6162 // On Darwin, -Os means optimize for size without hurting performance, so 6163 // only really optimize for size when -Oz (MinSize) is used. 6164 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6165 return MF.getFunction().hasMinSize(); 6166 return DAG.shouldOptForSize(); 6167 } 6168 6169 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6170 SmallVector<SDValue, 32> &OutChains, unsigned From, 6171 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6172 SmallVector<SDValue, 16> &OutStoreChains) { 6173 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6174 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6175 SmallVector<SDValue, 16> GluedLoadChains; 6176 for (unsigned i = From; i < To; ++i) { 6177 OutChains.push_back(OutLoadChains[i]); 6178 GluedLoadChains.push_back(OutLoadChains[i]); 6179 } 6180 6181 // Chain for all loads. 6182 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6183 GluedLoadChains); 6184 6185 for (unsigned i = From; i < To; ++i) { 6186 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6187 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6188 ST->getBasePtr(), ST->getMemoryVT(), 6189 ST->getMemOperand()); 6190 OutChains.push_back(NewStore); 6191 } 6192 } 6193 6194 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6195 SDValue Chain, SDValue Dst, SDValue Src, 6196 uint64_t Size, Align Alignment, 6197 bool isVol, bool AlwaysInline, 6198 MachinePointerInfo DstPtrInfo, 6199 MachinePointerInfo SrcPtrInfo) { 6200 // Turn a memcpy of undef to nop. 6201 // FIXME: We need to honor volatile even is Src is undef. 6202 if (Src.isUndef()) 6203 return Chain; 6204 6205 // Expand memcpy to a series of load and store ops if the size operand falls 6206 // below a certain threshold. 6207 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6208 // rather than maybe a humongous number of loads and stores. 6209 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6210 const DataLayout &DL = DAG.getDataLayout(); 6211 LLVMContext &C = *DAG.getContext(); 6212 std::vector<EVT> MemOps; 6213 bool DstAlignCanChange = false; 6214 MachineFunction &MF = DAG.getMachineFunction(); 6215 MachineFrameInfo &MFI = MF.getFrameInfo(); 6216 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6217 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6218 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6219 DstAlignCanChange = true; 6220 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6221 if (!SrcAlign || Alignment > *SrcAlign) 6222 SrcAlign = Alignment; 6223 assert(SrcAlign && "SrcAlign must be set"); 6224 ConstantDataArraySlice Slice; 6225 // If marked as volatile, perform a copy even when marked as constant. 6226 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6227 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6228 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6229 const MemOp Op = isZeroConstant 6230 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6231 /*IsZeroMemset*/ true, isVol) 6232 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6233 *SrcAlign, isVol, CopyFromConstant); 6234 if (!TLI.findOptimalMemOpLowering( 6235 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6236 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6237 return SDValue(); 6238 6239 if (DstAlignCanChange) { 6240 Type *Ty = MemOps[0].getTypeForEVT(C); 6241 Align NewAlign = DL.getABITypeAlign(Ty); 6242 6243 // Don't promote to an alignment that would require dynamic stack 6244 // realignment. 6245 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6246 if (!TRI->needsStackRealignment(MF)) 6247 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6248 NewAlign = NewAlign / 2; 6249 6250 if (NewAlign > Alignment) { 6251 // Give the stack frame object a larger alignment if needed. 6252 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6253 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6254 Alignment = NewAlign; 6255 } 6256 } 6257 6258 MachineMemOperand::Flags MMOFlags = 6259 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6260 SmallVector<SDValue, 16> OutLoadChains; 6261 SmallVector<SDValue, 16> OutStoreChains; 6262 SmallVector<SDValue, 32> OutChains; 6263 unsigned NumMemOps = MemOps.size(); 6264 uint64_t SrcOff = 0, DstOff = 0; 6265 for (unsigned i = 0; i != NumMemOps; ++i) { 6266 EVT VT = MemOps[i]; 6267 unsigned VTSize = VT.getSizeInBits() / 8; 6268 SDValue Value, Store; 6269 6270 if (VTSize > Size) { 6271 // Issuing an unaligned load / store pair that overlaps with the previous 6272 // pair. Adjust the offset accordingly. 6273 assert(i == NumMemOps-1 && i != 0); 6274 SrcOff -= VTSize - Size; 6275 DstOff -= VTSize - Size; 6276 } 6277 6278 if (CopyFromConstant && 6279 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6280 // It's unlikely a store of a vector immediate can be done in a single 6281 // instruction. It would require a load from a constantpool first. 6282 // We only handle zero vectors here. 6283 // FIXME: Handle other cases where store of vector immediate is done in 6284 // a single instruction. 6285 ConstantDataArraySlice SubSlice; 6286 if (SrcOff < Slice.Length) { 6287 SubSlice = Slice; 6288 SubSlice.move(SrcOff); 6289 } else { 6290 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6291 SubSlice.Array = nullptr; 6292 SubSlice.Offset = 0; 6293 SubSlice.Length = VTSize; 6294 } 6295 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6296 if (Value.getNode()) { 6297 Store = DAG.getStore( 6298 Chain, dl, Value, 6299 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6300 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6301 OutChains.push_back(Store); 6302 } 6303 } 6304 6305 if (!Store.getNode()) { 6306 // The type might not be legal for the target. This should only happen 6307 // if the type is smaller than a legal type, as on PPC, so the right 6308 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6309 // to Load/Store if NVT==VT. 6310 // FIXME does the case above also need this? 6311 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6312 assert(NVT.bitsGE(VT)); 6313 6314 bool isDereferenceable = 6315 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6316 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6317 if (isDereferenceable) 6318 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6319 6320 Value = DAG.getExtLoad( 6321 ISD::EXTLOAD, dl, NVT, Chain, 6322 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6323 SrcPtrInfo.getWithOffset(SrcOff), VT, 6324 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags); 6325 OutLoadChains.push_back(Value.getValue(1)); 6326 6327 Store = DAG.getTruncStore( 6328 Chain, dl, Value, 6329 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6330 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags); 6331 OutStoreChains.push_back(Store); 6332 } 6333 SrcOff += VTSize; 6334 DstOff += VTSize; 6335 Size -= VTSize; 6336 } 6337 6338 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6339 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6340 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6341 6342 if (NumLdStInMemcpy) { 6343 // It may be that memcpy might be converted to memset if it's memcpy 6344 // of constants. In such a case, we won't have loads and stores, but 6345 // just stores. In the absence of loads, there is nothing to gang up. 6346 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6347 // If target does not care, just leave as it. 6348 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6349 OutChains.push_back(OutLoadChains[i]); 6350 OutChains.push_back(OutStoreChains[i]); 6351 } 6352 } else { 6353 // Ld/St less than/equal limit set by target. 6354 if (NumLdStInMemcpy <= GluedLdStLimit) { 6355 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6356 NumLdStInMemcpy, OutLoadChains, 6357 OutStoreChains); 6358 } else { 6359 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6360 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6361 unsigned GlueIter = 0; 6362 6363 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6364 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6365 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6366 6367 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6368 OutLoadChains, OutStoreChains); 6369 GlueIter += GluedLdStLimit; 6370 } 6371 6372 // Residual ld/st. 6373 if (RemainingLdStInMemcpy) { 6374 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6375 RemainingLdStInMemcpy, OutLoadChains, 6376 OutStoreChains); 6377 } 6378 } 6379 } 6380 } 6381 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6382 } 6383 6384 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6385 SDValue Chain, SDValue Dst, SDValue Src, 6386 uint64_t Size, Align Alignment, 6387 bool isVol, bool AlwaysInline, 6388 MachinePointerInfo DstPtrInfo, 6389 MachinePointerInfo SrcPtrInfo) { 6390 // Turn a memmove of undef to nop. 6391 // FIXME: We need to honor volatile even is Src is undef. 6392 if (Src.isUndef()) 6393 return Chain; 6394 6395 // Expand memmove to a series of load and store ops if the size operand falls 6396 // below a certain threshold. 6397 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6398 const DataLayout &DL = DAG.getDataLayout(); 6399 LLVMContext &C = *DAG.getContext(); 6400 std::vector<EVT> MemOps; 6401 bool DstAlignCanChange = false; 6402 MachineFunction &MF = DAG.getMachineFunction(); 6403 MachineFrameInfo &MFI = MF.getFrameInfo(); 6404 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6405 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6406 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6407 DstAlignCanChange = true; 6408 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6409 if (!SrcAlign || Alignment > *SrcAlign) 6410 SrcAlign = Alignment; 6411 assert(SrcAlign && "SrcAlign must be set"); 6412 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6413 if (!TLI.findOptimalMemOpLowering( 6414 MemOps, Limit, 6415 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6416 /*IsVolatile*/ true), 6417 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6418 MF.getFunction().getAttributes())) 6419 return SDValue(); 6420 6421 if (DstAlignCanChange) { 6422 Type *Ty = MemOps[0].getTypeForEVT(C); 6423 Align NewAlign = DL.getABITypeAlign(Ty); 6424 if (NewAlign > Alignment) { 6425 // Give the stack frame object a larger alignment if needed. 6426 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6427 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6428 Alignment = NewAlign; 6429 } 6430 } 6431 6432 MachineMemOperand::Flags MMOFlags = 6433 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6434 uint64_t SrcOff = 0, DstOff = 0; 6435 SmallVector<SDValue, 8> LoadValues; 6436 SmallVector<SDValue, 8> LoadChains; 6437 SmallVector<SDValue, 8> OutChains; 6438 unsigned NumMemOps = MemOps.size(); 6439 for (unsigned i = 0; i < NumMemOps; i++) { 6440 EVT VT = MemOps[i]; 6441 unsigned VTSize = VT.getSizeInBits() / 8; 6442 SDValue Value; 6443 6444 bool isDereferenceable = 6445 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6446 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6447 if (isDereferenceable) 6448 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6449 6450 Value = 6451 DAG.getLoad(VT, dl, Chain, 6452 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6453 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags); 6454 LoadValues.push_back(Value); 6455 LoadChains.push_back(Value.getValue(1)); 6456 SrcOff += VTSize; 6457 } 6458 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6459 OutChains.clear(); 6460 for (unsigned i = 0; i < NumMemOps; i++) { 6461 EVT VT = MemOps[i]; 6462 unsigned VTSize = VT.getSizeInBits() / 8; 6463 SDValue Store; 6464 6465 Store = 6466 DAG.getStore(Chain, dl, LoadValues[i], 6467 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6468 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6469 OutChains.push_back(Store); 6470 DstOff += VTSize; 6471 } 6472 6473 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6474 } 6475 6476 /// Lower the call to 'memset' intrinsic function into a series of store 6477 /// operations. 6478 /// 6479 /// \param DAG Selection DAG where lowered code is placed. 6480 /// \param dl Link to corresponding IR location. 6481 /// \param Chain Control flow dependency. 6482 /// \param Dst Pointer to destination memory location. 6483 /// \param Src Value of byte to write into the memory. 6484 /// \param Size Number of bytes to write. 6485 /// \param Alignment Alignment of the destination in bytes. 6486 /// \param isVol True if destination is volatile. 6487 /// \param DstPtrInfo IR information on the memory pointer. 6488 /// \returns New head in the control flow, if lowering was successful, empty 6489 /// SDValue otherwise. 6490 /// 6491 /// The function tries to replace 'llvm.memset' intrinsic with several store 6492 /// operations and value calculation code. This is usually profitable for small 6493 /// memory size. 6494 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6495 SDValue Chain, SDValue Dst, SDValue Src, 6496 uint64_t Size, Align Alignment, bool isVol, 6497 MachinePointerInfo DstPtrInfo) { 6498 // Turn a memset of undef to nop. 6499 // FIXME: We need to honor volatile even is Src is undef. 6500 if (Src.isUndef()) 6501 return Chain; 6502 6503 // Expand memset to a series of load/store ops if the size operand 6504 // falls below a certain threshold. 6505 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6506 std::vector<EVT> MemOps; 6507 bool DstAlignCanChange = false; 6508 MachineFunction &MF = DAG.getMachineFunction(); 6509 MachineFrameInfo &MFI = MF.getFrameInfo(); 6510 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6511 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6512 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6513 DstAlignCanChange = true; 6514 bool IsZeroVal = 6515 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 6516 if (!TLI.findOptimalMemOpLowering( 6517 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6518 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6519 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6520 return SDValue(); 6521 6522 if (DstAlignCanChange) { 6523 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6524 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6525 if (NewAlign > Alignment) { 6526 // Give the stack frame object a larger alignment if needed. 6527 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6528 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6529 Alignment = NewAlign; 6530 } 6531 } 6532 6533 SmallVector<SDValue, 8> OutChains; 6534 uint64_t DstOff = 0; 6535 unsigned NumMemOps = MemOps.size(); 6536 6537 // Find the largest store and generate the bit pattern for it. 6538 EVT LargestVT = MemOps[0]; 6539 for (unsigned i = 1; i < NumMemOps; i++) 6540 if (MemOps[i].bitsGT(LargestVT)) 6541 LargestVT = MemOps[i]; 6542 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6543 6544 for (unsigned i = 0; i < NumMemOps; i++) { 6545 EVT VT = MemOps[i]; 6546 unsigned VTSize = VT.getSizeInBits() / 8; 6547 if (VTSize > Size) { 6548 // Issuing an unaligned load / store pair that overlaps with the previous 6549 // pair. Adjust the offset accordingly. 6550 assert(i == NumMemOps-1 && i != 0); 6551 DstOff -= VTSize - Size; 6552 } 6553 6554 // If this store is smaller than the largest store see whether we can get 6555 // the smaller value for free with a truncate. 6556 SDValue Value = MemSetValue; 6557 if (VT.bitsLT(LargestVT)) { 6558 if (!LargestVT.isVector() && !VT.isVector() && 6559 TLI.isTruncateFree(LargestVT, VT)) 6560 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6561 else 6562 Value = getMemsetValue(Src, VT, DAG, dl); 6563 } 6564 assert(Value.getValueType() == VT && "Value with wrong type."); 6565 SDValue Store = DAG.getStore( 6566 Chain, dl, Value, 6567 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6568 DstPtrInfo.getWithOffset(DstOff), Alignment, 6569 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone); 6570 OutChains.push_back(Store); 6571 DstOff += VT.getSizeInBits() / 8; 6572 Size -= VTSize; 6573 } 6574 6575 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6576 } 6577 6578 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6579 unsigned AS) { 6580 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6581 // pointer operands can be losslessly bitcasted to pointers of address space 0 6582 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6583 report_fatal_error("cannot lower memory intrinsic in address space " + 6584 Twine(AS)); 6585 } 6586 } 6587 6588 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6589 SDValue Src, SDValue Size, Align Alignment, 6590 bool isVol, bool AlwaysInline, bool isTailCall, 6591 MachinePointerInfo DstPtrInfo, 6592 MachinePointerInfo SrcPtrInfo) { 6593 // Check to see if we should lower the memcpy to loads and stores first. 6594 // For cases within the target-specified limits, this is the best choice. 6595 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6596 if (ConstantSize) { 6597 // Memcpy with size zero? Just return the original chain. 6598 if (ConstantSize->isNullValue()) 6599 return Chain; 6600 6601 SDValue Result = getMemcpyLoadsAndStores( 6602 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6603 isVol, false, DstPtrInfo, SrcPtrInfo); 6604 if (Result.getNode()) 6605 return Result; 6606 } 6607 6608 // Then check to see if we should lower the memcpy with target-specific 6609 // code. If the target chooses to do this, this is the next best. 6610 if (TSI) { 6611 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6612 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6613 DstPtrInfo, SrcPtrInfo); 6614 if (Result.getNode()) 6615 return Result; 6616 } 6617 6618 // If we really need inline code and the target declined to provide it, 6619 // use a (potentially long) sequence of loads and stores. 6620 if (AlwaysInline) { 6621 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6622 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6623 ConstantSize->getZExtValue(), Alignment, 6624 isVol, true, DstPtrInfo, SrcPtrInfo); 6625 } 6626 6627 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6628 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6629 6630 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6631 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6632 // respect volatile, so they may do things like read or write memory 6633 // beyond the given memory regions. But fixing this isn't easy, and most 6634 // people don't care. 6635 6636 // Emit a library call. 6637 TargetLowering::ArgListTy Args; 6638 TargetLowering::ArgListEntry Entry; 6639 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6640 Entry.Node = Dst; Args.push_back(Entry); 6641 Entry.Node = Src; Args.push_back(Entry); 6642 6643 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6644 Entry.Node = Size; Args.push_back(Entry); 6645 // FIXME: pass in SDLoc 6646 TargetLowering::CallLoweringInfo CLI(*this); 6647 CLI.setDebugLoc(dl) 6648 .setChain(Chain) 6649 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6650 Dst.getValueType().getTypeForEVT(*getContext()), 6651 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6652 TLI->getPointerTy(getDataLayout())), 6653 std::move(Args)) 6654 .setDiscardResult() 6655 .setTailCall(isTailCall); 6656 6657 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6658 return CallResult.second; 6659 } 6660 6661 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6662 SDValue Dst, unsigned DstAlign, 6663 SDValue Src, unsigned SrcAlign, 6664 SDValue Size, Type *SizeTy, 6665 unsigned ElemSz, bool isTailCall, 6666 MachinePointerInfo DstPtrInfo, 6667 MachinePointerInfo SrcPtrInfo) { 6668 // Emit a library call. 6669 TargetLowering::ArgListTy Args; 6670 TargetLowering::ArgListEntry Entry; 6671 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6672 Entry.Node = Dst; 6673 Args.push_back(Entry); 6674 6675 Entry.Node = Src; 6676 Args.push_back(Entry); 6677 6678 Entry.Ty = SizeTy; 6679 Entry.Node = Size; 6680 Args.push_back(Entry); 6681 6682 RTLIB::Libcall LibraryCall = 6683 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6684 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6685 report_fatal_error("Unsupported element size"); 6686 6687 TargetLowering::CallLoweringInfo CLI(*this); 6688 CLI.setDebugLoc(dl) 6689 .setChain(Chain) 6690 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6691 Type::getVoidTy(*getContext()), 6692 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6693 TLI->getPointerTy(getDataLayout())), 6694 std::move(Args)) 6695 .setDiscardResult() 6696 .setTailCall(isTailCall); 6697 6698 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6699 return CallResult.second; 6700 } 6701 6702 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6703 SDValue Src, SDValue Size, Align Alignment, 6704 bool isVol, bool isTailCall, 6705 MachinePointerInfo DstPtrInfo, 6706 MachinePointerInfo SrcPtrInfo) { 6707 // Check to see if we should lower the memmove to loads and stores first. 6708 // For cases within the target-specified limits, this is the best choice. 6709 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6710 if (ConstantSize) { 6711 // Memmove with size zero? Just return the original chain. 6712 if (ConstantSize->isNullValue()) 6713 return Chain; 6714 6715 SDValue Result = getMemmoveLoadsAndStores( 6716 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6717 isVol, false, DstPtrInfo, SrcPtrInfo); 6718 if (Result.getNode()) 6719 return Result; 6720 } 6721 6722 // Then check to see if we should lower the memmove with target-specific 6723 // code. If the target chooses to do this, this is the next best. 6724 if (TSI) { 6725 SDValue Result = 6726 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 6727 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 6728 if (Result.getNode()) 6729 return Result; 6730 } 6731 6732 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6733 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6734 6735 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 6736 // not be safe. See memcpy above for more details. 6737 6738 // Emit a library call. 6739 TargetLowering::ArgListTy Args; 6740 TargetLowering::ArgListEntry Entry; 6741 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6742 Entry.Node = Dst; Args.push_back(Entry); 6743 Entry.Node = Src; Args.push_back(Entry); 6744 6745 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6746 Entry.Node = Size; Args.push_back(Entry); 6747 // FIXME: pass in SDLoc 6748 TargetLowering::CallLoweringInfo CLI(*this); 6749 CLI.setDebugLoc(dl) 6750 .setChain(Chain) 6751 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 6752 Dst.getValueType().getTypeForEVT(*getContext()), 6753 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 6754 TLI->getPointerTy(getDataLayout())), 6755 std::move(Args)) 6756 .setDiscardResult() 6757 .setTailCall(isTailCall); 6758 6759 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6760 return CallResult.second; 6761 } 6762 6763 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 6764 SDValue Dst, unsigned DstAlign, 6765 SDValue Src, unsigned SrcAlign, 6766 SDValue Size, Type *SizeTy, 6767 unsigned ElemSz, bool isTailCall, 6768 MachinePointerInfo DstPtrInfo, 6769 MachinePointerInfo SrcPtrInfo) { 6770 // Emit a library call. 6771 TargetLowering::ArgListTy Args; 6772 TargetLowering::ArgListEntry Entry; 6773 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6774 Entry.Node = Dst; 6775 Args.push_back(Entry); 6776 6777 Entry.Node = Src; 6778 Args.push_back(Entry); 6779 6780 Entry.Ty = SizeTy; 6781 Entry.Node = Size; 6782 Args.push_back(Entry); 6783 6784 RTLIB::Libcall LibraryCall = 6785 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6786 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6787 report_fatal_error("Unsupported element size"); 6788 6789 TargetLowering::CallLoweringInfo CLI(*this); 6790 CLI.setDebugLoc(dl) 6791 .setChain(Chain) 6792 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6793 Type::getVoidTy(*getContext()), 6794 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6795 TLI->getPointerTy(getDataLayout())), 6796 std::move(Args)) 6797 .setDiscardResult() 6798 .setTailCall(isTailCall); 6799 6800 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6801 return CallResult.second; 6802 } 6803 6804 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 6805 SDValue Src, SDValue Size, Align Alignment, 6806 bool isVol, bool isTailCall, 6807 MachinePointerInfo DstPtrInfo) { 6808 // Check to see if we should lower the memset to stores first. 6809 // For cases within the target-specified limits, this is the best choice. 6810 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6811 if (ConstantSize) { 6812 // Memset with size zero? Just return the original chain. 6813 if (ConstantSize->isNullValue()) 6814 return Chain; 6815 6816 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 6817 ConstantSize->getZExtValue(), Alignment, 6818 isVol, DstPtrInfo); 6819 6820 if (Result.getNode()) 6821 return Result; 6822 } 6823 6824 // Then check to see if we should lower the memset with target-specific 6825 // code. If the target chooses to do this, this is the next best. 6826 if (TSI) { 6827 SDValue Result = TSI->EmitTargetCodeForMemset( 6828 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 6829 if (Result.getNode()) 6830 return Result; 6831 } 6832 6833 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6834 6835 // Emit a library call. 6836 TargetLowering::ArgListTy Args; 6837 TargetLowering::ArgListEntry Entry; 6838 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 6839 Args.push_back(Entry); 6840 Entry.Node = Src; 6841 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 6842 Args.push_back(Entry); 6843 Entry.Node = Size; 6844 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6845 Args.push_back(Entry); 6846 6847 // FIXME: pass in SDLoc 6848 TargetLowering::CallLoweringInfo CLI(*this); 6849 CLI.setDebugLoc(dl) 6850 .setChain(Chain) 6851 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 6852 Dst.getValueType().getTypeForEVT(*getContext()), 6853 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 6854 TLI->getPointerTy(getDataLayout())), 6855 std::move(Args)) 6856 .setDiscardResult() 6857 .setTailCall(isTailCall); 6858 6859 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6860 return CallResult.second; 6861 } 6862 6863 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 6864 SDValue Dst, unsigned DstAlign, 6865 SDValue Value, SDValue Size, Type *SizeTy, 6866 unsigned ElemSz, bool isTailCall, 6867 MachinePointerInfo DstPtrInfo) { 6868 // Emit a library call. 6869 TargetLowering::ArgListTy Args; 6870 TargetLowering::ArgListEntry Entry; 6871 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6872 Entry.Node = Dst; 6873 Args.push_back(Entry); 6874 6875 Entry.Ty = Type::getInt8Ty(*getContext()); 6876 Entry.Node = Value; 6877 Args.push_back(Entry); 6878 6879 Entry.Ty = SizeTy; 6880 Entry.Node = Size; 6881 Args.push_back(Entry); 6882 6883 RTLIB::Libcall LibraryCall = 6884 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6885 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6886 report_fatal_error("Unsupported element size"); 6887 6888 TargetLowering::CallLoweringInfo CLI(*this); 6889 CLI.setDebugLoc(dl) 6890 .setChain(Chain) 6891 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6892 Type::getVoidTy(*getContext()), 6893 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6894 TLI->getPointerTy(getDataLayout())), 6895 std::move(Args)) 6896 .setDiscardResult() 6897 .setTailCall(isTailCall); 6898 6899 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6900 return CallResult.second; 6901 } 6902 6903 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6904 SDVTList VTList, ArrayRef<SDValue> Ops, 6905 MachineMemOperand *MMO) { 6906 FoldingSetNodeID ID; 6907 ID.AddInteger(MemVT.getRawBits()); 6908 AddNodeIDNode(ID, Opcode, VTList, Ops); 6909 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6910 void* IP = nullptr; 6911 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6912 cast<AtomicSDNode>(E)->refineAlignment(MMO); 6913 return SDValue(E, 0); 6914 } 6915 6916 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6917 VTList, MemVT, MMO); 6918 createOperands(N, Ops); 6919 6920 CSEMap.InsertNode(N, IP); 6921 InsertNode(N); 6922 return SDValue(N, 0); 6923 } 6924 6925 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 6926 EVT MemVT, SDVTList VTs, SDValue Chain, 6927 SDValue Ptr, SDValue Cmp, SDValue Swp, 6928 MachineMemOperand *MMO) { 6929 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 6930 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 6931 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 6932 6933 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 6934 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6935 } 6936 6937 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6938 SDValue Chain, SDValue Ptr, SDValue Val, 6939 MachineMemOperand *MMO) { 6940 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 6941 Opcode == ISD::ATOMIC_LOAD_SUB || 6942 Opcode == ISD::ATOMIC_LOAD_AND || 6943 Opcode == ISD::ATOMIC_LOAD_CLR || 6944 Opcode == ISD::ATOMIC_LOAD_OR || 6945 Opcode == ISD::ATOMIC_LOAD_XOR || 6946 Opcode == ISD::ATOMIC_LOAD_NAND || 6947 Opcode == ISD::ATOMIC_LOAD_MIN || 6948 Opcode == ISD::ATOMIC_LOAD_MAX || 6949 Opcode == ISD::ATOMIC_LOAD_UMIN || 6950 Opcode == ISD::ATOMIC_LOAD_UMAX || 6951 Opcode == ISD::ATOMIC_LOAD_FADD || 6952 Opcode == ISD::ATOMIC_LOAD_FSUB || 6953 Opcode == ISD::ATOMIC_SWAP || 6954 Opcode == ISD::ATOMIC_STORE) && 6955 "Invalid Atomic Op"); 6956 6957 EVT VT = Val.getValueType(); 6958 6959 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 6960 getVTList(VT, MVT::Other); 6961 SDValue Ops[] = {Chain, Ptr, Val}; 6962 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6963 } 6964 6965 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6966 EVT VT, SDValue Chain, SDValue Ptr, 6967 MachineMemOperand *MMO) { 6968 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 6969 6970 SDVTList VTs = getVTList(VT, MVT::Other); 6971 SDValue Ops[] = {Chain, Ptr}; 6972 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6973 } 6974 6975 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 6976 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 6977 if (Ops.size() == 1) 6978 return Ops[0]; 6979 6980 SmallVector<EVT, 4> VTs; 6981 VTs.reserve(Ops.size()); 6982 for (const SDValue &Op : Ops) 6983 VTs.push_back(Op.getValueType()); 6984 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 6985 } 6986 6987 SDValue SelectionDAG::getMemIntrinsicNode( 6988 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 6989 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 6990 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 6991 if (!Size && MemVT.isScalableVector()) 6992 Size = MemoryLocation::UnknownSize; 6993 else if (!Size) 6994 Size = MemVT.getStoreSize(); 6995 6996 MachineFunction &MF = getMachineFunction(); 6997 MachineMemOperand *MMO = 6998 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 6999 7000 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 7001 } 7002 7003 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7004 SDVTList VTList, 7005 ArrayRef<SDValue> Ops, EVT MemVT, 7006 MachineMemOperand *MMO) { 7007 assert((Opcode == ISD::INTRINSIC_VOID || 7008 Opcode == ISD::INTRINSIC_W_CHAIN || 7009 Opcode == ISD::PREFETCH || 7010 ((int)Opcode <= std::numeric_limits<int>::max() && 7011 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7012 "Opcode is not a memory-accessing opcode!"); 7013 7014 // Memoize the node unless it returns a flag. 7015 MemIntrinsicSDNode *N; 7016 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7017 FoldingSetNodeID ID; 7018 AddNodeIDNode(ID, Opcode, VTList, Ops); 7019 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7020 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7021 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7022 void *IP = nullptr; 7023 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7024 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7025 return SDValue(E, 0); 7026 } 7027 7028 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7029 VTList, MemVT, MMO); 7030 createOperands(N, Ops); 7031 7032 CSEMap.InsertNode(N, IP); 7033 } else { 7034 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7035 VTList, MemVT, MMO); 7036 createOperands(N, Ops); 7037 } 7038 InsertNode(N); 7039 SDValue V(N, 0); 7040 NewSDValueDbgMsg(V, "Creating new node: ", this); 7041 return V; 7042 } 7043 7044 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7045 SDValue Chain, int FrameIndex, 7046 int64_t Size, int64_t Offset) { 7047 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7048 const auto VTs = getVTList(MVT::Other); 7049 SDValue Ops[2] = { 7050 Chain, 7051 getFrameIndex(FrameIndex, 7052 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7053 true)}; 7054 7055 FoldingSetNodeID ID; 7056 AddNodeIDNode(ID, Opcode, VTs, Ops); 7057 ID.AddInteger(FrameIndex); 7058 ID.AddInteger(Size); 7059 ID.AddInteger(Offset); 7060 void *IP = nullptr; 7061 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7062 return SDValue(E, 0); 7063 7064 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7065 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7066 createOperands(N, Ops); 7067 CSEMap.InsertNode(N, IP); 7068 InsertNode(N); 7069 SDValue V(N, 0); 7070 NewSDValueDbgMsg(V, "Creating new node: ", this); 7071 return V; 7072 } 7073 7074 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7075 uint64_t Guid, uint64_t Index, 7076 uint32_t Attr) { 7077 const unsigned Opcode = ISD::PSEUDO_PROBE; 7078 const auto VTs = getVTList(MVT::Other); 7079 SDValue Ops[] = {Chain}; 7080 FoldingSetNodeID ID; 7081 AddNodeIDNode(ID, Opcode, VTs, Ops); 7082 ID.AddInteger(Guid); 7083 ID.AddInteger(Index); 7084 void *IP = nullptr; 7085 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7086 return SDValue(E, 0); 7087 7088 auto *N = newSDNode<PseudoProbeSDNode>( 7089 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7090 createOperands(N, Ops); 7091 CSEMap.InsertNode(N, IP); 7092 InsertNode(N); 7093 SDValue V(N, 0); 7094 NewSDValueDbgMsg(V, "Creating new node: ", this); 7095 return V; 7096 } 7097 7098 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7099 /// MachinePointerInfo record from it. This is particularly useful because the 7100 /// code generator has many cases where it doesn't bother passing in a 7101 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7102 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7103 SelectionDAG &DAG, SDValue Ptr, 7104 int64_t Offset = 0) { 7105 // If this is FI+Offset, we can model it. 7106 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7107 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7108 FI->getIndex(), Offset); 7109 7110 // If this is (FI+Offset1)+Offset2, we can model it. 7111 if (Ptr.getOpcode() != ISD::ADD || 7112 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7113 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7114 return Info; 7115 7116 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7117 return MachinePointerInfo::getFixedStack( 7118 DAG.getMachineFunction(), FI, 7119 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7120 } 7121 7122 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7123 /// MachinePointerInfo record from it. This is particularly useful because the 7124 /// code generator has many cases where it doesn't bother passing in a 7125 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7126 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7127 SelectionDAG &DAG, SDValue Ptr, 7128 SDValue OffsetOp) { 7129 // If the 'Offset' value isn't a constant, we can't handle this. 7130 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7131 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7132 if (OffsetOp.isUndef()) 7133 return InferPointerInfo(Info, DAG, Ptr); 7134 return Info; 7135 } 7136 7137 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7138 EVT VT, const SDLoc &dl, SDValue Chain, 7139 SDValue Ptr, SDValue Offset, 7140 MachinePointerInfo PtrInfo, EVT MemVT, 7141 Align Alignment, 7142 MachineMemOperand::Flags MMOFlags, 7143 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7144 assert(Chain.getValueType() == MVT::Other && 7145 "Invalid chain type"); 7146 7147 MMOFlags |= MachineMemOperand::MOLoad; 7148 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7149 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7150 // clients. 7151 if (PtrInfo.V.isNull()) 7152 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7153 7154 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7155 MachineFunction &MF = getMachineFunction(); 7156 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7157 Alignment, AAInfo, Ranges); 7158 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7159 } 7160 7161 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7162 EVT VT, const SDLoc &dl, SDValue Chain, 7163 SDValue Ptr, SDValue Offset, EVT MemVT, 7164 MachineMemOperand *MMO) { 7165 if (VT == MemVT) { 7166 ExtType = ISD::NON_EXTLOAD; 7167 } else if (ExtType == ISD::NON_EXTLOAD) { 7168 assert(VT == MemVT && "Non-extending load from different memory type!"); 7169 } else { 7170 // Extending load. 7171 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7172 "Should only be an extending load, not truncating!"); 7173 assert(VT.isInteger() == MemVT.isInteger() && 7174 "Cannot convert from FP to Int or Int -> FP!"); 7175 assert(VT.isVector() == MemVT.isVector() && 7176 "Cannot use an ext load to convert to or from a vector!"); 7177 assert((!VT.isVector() || 7178 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7179 "Cannot use an ext load to change the number of vector elements!"); 7180 } 7181 7182 bool Indexed = AM != ISD::UNINDEXED; 7183 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7184 7185 SDVTList VTs = Indexed ? 7186 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7187 SDValue Ops[] = { Chain, Ptr, Offset }; 7188 FoldingSetNodeID ID; 7189 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7190 ID.AddInteger(MemVT.getRawBits()); 7191 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7192 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7193 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7194 void *IP = nullptr; 7195 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7196 cast<LoadSDNode>(E)->refineAlignment(MMO); 7197 return SDValue(E, 0); 7198 } 7199 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7200 ExtType, MemVT, MMO); 7201 createOperands(N, Ops); 7202 7203 CSEMap.InsertNode(N, IP); 7204 InsertNode(N); 7205 SDValue V(N, 0); 7206 NewSDValueDbgMsg(V, "Creating new node: ", this); 7207 return V; 7208 } 7209 7210 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7211 SDValue Ptr, MachinePointerInfo PtrInfo, 7212 MaybeAlign Alignment, 7213 MachineMemOperand::Flags MMOFlags, 7214 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7215 SDValue Undef = getUNDEF(Ptr.getValueType()); 7216 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7217 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7218 } 7219 7220 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7221 SDValue Ptr, MachineMemOperand *MMO) { 7222 SDValue Undef = getUNDEF(Ptr.getValueType()); 7223 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7224 VT, MMO); 7225 } 7226 7227 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7228 EVT VT, SDValue Chain, SDValue Ptr, 7229 MachinePointerInfo PtrInfo, EVT MemVT, 7230 MaybeAlign Alignment, 7231 MachineMemOperand::Flags MMOFlags, 7232 const AAMDNodes &AAInfo) { 7233 SDValue Undef = getUNDEF(Ptr.getValueType()); 7234 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7235 MemVT, Alignment, MMOFlags, AAInfo); 7236 } 7237 7238 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7239 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7240 MachineMemOperand *MMO) { 7241 SDValue Undef = getUNDEF(Ptr.getValueType()); 7242 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7243 MemVT, MMO); 7244 } 7245 7246 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7247 SDValue Base, SDValue Offset, 7248 ISD::MemIndexedMode AM) { 7249 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7250 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7251 // Don't propagate the invariant or dereferenceable flags. 7252 auto MMOFlags = 7253 LD->getMemOperand()->getFlags() & 7254 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7255 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7256 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7257 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7258 } 7259 7260 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7261 SDValue Ptr, MachinePointerInfo PtrInfo, 7262 Align Alignment, 7263 MachineMemOperand::Flags MMOFlags, 7264 const AAMDNodes &AAInfo) { 7265 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7266 7267 MMOFlags |= MachineMemOperand::MOStore; 7268 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7269 7270 if (PtrInfo.V.isNull()) 7271 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7272 7273 MachineFunction &MF = getMachineFunction(); 7274 uint64_t Size = 7275 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7276 MachineMemOperand *MMO = 7277 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7278 return getStore(Chain, dl, Val, Ptr, MMO); 7279 } 7280 7281 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7282 SDValue Ptr, MachineMemOperand *MMO) { 7283 assert(Chain.getValueType() == MVT::Other && 7284 "Invalid chain type"); 7285 EVT VT = Val.getValueType(); 7286 SDVTList VTs = getVTList(MVT::Other); 7287 SDValue Undef = getUNDEF(Ptr.getValueType()); 7288 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7289 FoldingSetNodeID ID; 7290 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7291 ID.AddInteger(VT.getRawBits()); 7292 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7293 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7294 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7295 void *IP = nullptr; 7296 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7297 cast<StoreSDNode>(E)->refineAlignment(MMO); 7298 return SDValue(E, 0); 7299 } 7300 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7301 ISD::UNINDEXED, false, VT, MMO); 7302 createOperands(N, Ops); 7303 7304 CSEMap.InsertNode(N, IP); 7305 InsertNode(N); 7306 SDValue V(N, 0); 7307 NewSDValueDbgMsg(V, "Creating new node: ", this); 7308 return V; 7309 } 7310 7311 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7312 SDValue Ptr, MachinePointerInfo PtrInfo, 7313 EVT SVT, Align Alignment, 7314 MachineMemOperand::Flags MMOFlags, 7315 const AAMDNodes &AAInfo) { 7316 assert(Chain.getValueType() == MVT::Other && 7317 "Invalid chain type"); 7318 7319 MMOFlags |= MachineMemOperand::MOStore; 7320 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7321 7322 if (PtrInfo.V.isNull()) 7323 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7324 7325 MachineFunction &MF = getMachineFunction(); 7326 MachineMemOperand *MMO = MF.getMachineMemOperand( 7327 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7328 Alignment, AAInfo); 7329 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7330 } 7331 7332 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7333 SDValue Ptr, EVT SVT, 7334 MachineMemOperand *MMO) { 7335 EVT VT = Val.getValueType(); 7336 7337 assert(Chain.getValueType() == MVT::Other && 7338 "Invalid chain type"); 7339 if (VT == SVT) 7340 return getStore(Chain, dl, Val, Ptr, MMO); 7341 7342 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7343 "Should only be a truncating store, not extending!"); 7344 assert(VT.isInteger() == SVT.isInteger() && 7345 "Can't do FP-INT conversion!"); 7346 assert(VT.isVector() == SVT.isVector() && 7347 "Cannot use trunc store to convert to or from a vector!"); 7348 assert((!VT.isVector() || 7349 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7350 "Cannot use trunc store to change the number of vector elements!"); 7351 7352 SDVTList VTs = getVTList(MVT::Other); 7353 SDValue Undef = getUNDEF(Ptr.getValueType()); 7354 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7355 FoldingSetNodeID ID; 7356 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7357 ID.AddInteger(SVT.getRawBits()); 7358 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7359 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7360 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7361 void *IP = nullptr; 7362 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7363 cast<StoreSDNode>(E)->refineAlignment(MMO); 7364 return SDValue(E, 0); 7365 } 7366 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7367 ISD::UNINDEXED, true, SVT, MMO); 7368 createOperands(N, Ops); 7369 7370 CSEMap.InsertNode(N, IP); 7371 InsertNode(N); 7372 SDValue V(N, 0); 7373 NewSDValueDbgMsg(V, "Creating new node: ", this); 7374 return V; 7375 } 7376 7377 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7378 SDValue Base, SDValue Offset, 7379 ISD::MemIndexedMode AM) { 7380 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7381 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7382 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7383 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7384 FoldingSetNodeID ID; 7385 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7386 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7387 ID.AddInteger(ST->getRawSubclassData()); 7388 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7389 void *IP = nullptr; 7390 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7391 return SDValue(E, 0); 7392 7393 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7394 ST->isTruncatingStore(), ST->getMemoryVT(), 7395 ST->getMemOperand()); 7396 createOperands(N, Ops); 7397 7398 CSEMap.InsertNode(N, IP); 7399 InsertNode(N); 7400 SDValue V(N, 0); 7401 NewSDValueDbgMsg(V, "Creating new node: ", this); 7402 return V; 7403 } 7404 7405 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7406 SDValue Base, SDValue Offset, SDValue Mask, 7407 SDValue PassThru, EVT MemVT, 7408 MachineMemOperand *MMO, 7409 ISD::MemIndexedMode AM, 7410 ISD::LoadExtType ExtTy, bool isExpanding) { 7411 bool Indexed = AM != ISD::UNINDEXED; 7412 assert((Indexed || Offset.isUndef()) && 7413 "Unindexed masked load with an offset!"); 7414 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 7415 : getVTList(VT, MVT::Other); 7416 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 7417 FoldingSetNodeID ID; 7418 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 7419 ID.AddInteger(MemVT.getRawBits()); 7420 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 7421 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 7422 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7423 void *IP = nullptr; 7424 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7425 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 7426 return SDValue(E, 0); 7427 } 7428 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7429 AM, ExtTy, isExpanding, MemVT, MMO); 7430 createOperands(N, Ops); 7431 7432 CSEMap.InsertNode(N, IP); 7433 InsertNode(N); 7434 SDValue V(N, 0); 7435 NewSDValueDbgMsg(V, "Creating new node: ", this); 7436 return V; 7437 } 7438 7439 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 7440 SDValue Base, SDValue Offset, 7441 ISD::MemIndexedMode AM) { 7442 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 7443 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 7444 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 7445 Offset, LD->getMask(), LD->getPassThru(), 7446 LD->getMemoryVT(), LD->getMemOperand(), AM, 7447 LD->getExtensionType(), LD->isExpandingLoad()); 7448 } 7449 7450 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 7451 SDValue Val, SDValue Base, SDValue Offset, 7452 SDValue Mask, EVT MemVT, 7453 MachineMemOperand *MMO, 7454 ISD::MemIndexedMode AM, bool IsTruncating, 7455 bool IsCompressing) { 7456 assert(Chain.getValueType() == MVT::Other && 7457 "Invalid chain type"); 7458 bool Indexed = AM != ISD::UNINDEXED; 7459 assert((Indexed || Offset.isUndef()) && 7460 "Unindexed masked store with an offset!"); 7461 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 7462 : getVTList(MVT::Other); 7463 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 7464 FoldingSetNodeID ID; 7465 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 7466 ID.AddInteger(MemVT.getRawBits()); 7467 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 7468 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7469 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7470 void *IP = nullptr; 7471 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7472 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 7473 return SDValue(E, 0); 7474 } 7475 auto *N = 7476 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7477 IsTruncating, IsCompressing, MemVT, MMO); 7478 createOperands(N, Ops); 7479 7480 CSEMap.InsertNode(N, IP); 7481 InsertNode(N); 7482 SDValue V(N, 0); 7483 NewSDValueDbgMsg(V, "Creating new node: ", this); 7484 return V; 7485 } 7486 7487 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 7488 SDValue Base, SDValue Offset, 7489 ISD::MemIndexedMode AM) { 7490 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 7491 assert(ST->getOffset().isUndef() && 7492 "Masked store is already a indexed store!"); 7493 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 7494 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 7495 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 7496 } 7497 7498 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl, 7499 ArrayRef<SDValue> Ops, 7500 MachineMemOperand *MMO, 7501 ISD::MemIndexType IndexType, 7502 ISD::LoadExtType ExtTy) { 7503 assert(Ops.size() == 6 && "Incompatible number of operands"); 7504 7505 FoldingSetNodeID ID; 7506 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 7507 ID.AddInteger(VT.getRawBits()); 7508 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 7509 dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy)); 7510 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7511 void *IP = nullptr; 7512 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7513 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 7514 return SDValue(E, 0); 7515 } 7516 7517 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7518 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7519 VTs, VT, MMO, IndexType, ExtTy); 7520 createOperands(N, Ops); 7521 7522 assert(N->getPassThru().getValueType() == N->getValueType(0) && 7523 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 7524 assert(N->getMask().getValueType().getVectorElementCount() == 7525 N->getValueType(0).getVectorElementCount() && 7526 "Vector width mismatch between mask and data"); 7527 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7528 N->getValueType(0).getVectorElementCount().isScalable() && 7529 "Scalable flags of index and data do not match"); 7530 assert(ElementCount::isKnownGE( 7531 N->getIndex().getValueType().getVectorElementCount(), 7532 N->getValueType(0).getVectorElementCount()) && 7533 "Vector width mismatch between index and data"); 7534 assert(isa<ConstantSDNode>(N->getScale()) && 7535 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7536 "Scale should be a constant power of 2"); 7537 7538 CSEMap.InsertNode(N, IP); 7539 InsertNode(N); 7540 SDValue V(N, 0); 7541 NewSDValueDbgMsg(V, "Creating new node: ", this); 7542 return V; 7543 } 7544 7545 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl, 7546 ArrayRef<SDValue> Ops, 7547 MachineMemOperand *MMO, 7548 ISD::MemIndexType IndexType, 7549 bool IsTrunc) { 7550 assert(Ops.size() == 6 && "Incompatible number of operands"); 7551 7552 FoldingSetNodeID ID; 7553 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 7554 ID.AddInteger(VT.getRawBits()); 7555 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 7556 dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc)); 7557 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7558 void *IP = nullptr; 7559 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7560 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 7561 return SDValue(E, 0); 7562 } 7563 7564 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7565 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7566 VTs, VT, MMO, IndexType, IsTrunc); 7567 createOperands(N, Ops); 7568 7569 assert(N->getMask().getValueType().getVectorElementCount() == 7570 N->getValue().getValueType().getVectorElementCount() && 7571 "Vector width mismatch between mask and data"); 7572 assert( 7573 N->getIndex().getValueType().getVectorElementCount().isScalable() == 7574 N->getValue().getValueType().getVectorElementCount().isScalable() && 7575 "Scalable flags of index and data do not match"); 7576 assert(ElementCount::isKnownGE( 7577 N->getIndex().getValueType().getVectorElementCount(), 7578 N->getValue().getValueType().getVectorElementCount()) && 7579 "Vector width mismatch between index and data"); 7580 assert(isa<ConstantSDNode>(N->getScale()) && 7581 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7582 "Scale should be a constant power of 2"); 7583 7584 CSEMap.InsertNode(N, IP); 7585 InsertNode(N); 7586 SDValue V(N, 0); 7587 NewSDValueDbgMsg(V, "Creating new node: ", this); 7588 return V; 7589 } 7590 7591 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 7592 // select undef, T, F --> T (if T is a constant), otherwise F 7593 // select, ?, undef, F --> F 7594 // select, ?, T, undef --> T 7595 if (Cond.isUndef()) 7596 return isConstantValueOfAnyType(T) ? T : F; 7597 if (T.isUndef()) 7598 return F; 7599 if (F.isUndef()) 7600 return T; 7601 7602 // select true, T, F --> T 7603 // select false, T, F --> F 7604 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 7605 return CondC->isNullValue() ? F : T; 7606 7607 // TODO: This should simplify VSELECT with constant condition using something 7608 // like this (but check boolean contents to be complete?): 7609 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 7610 // return T; 7611 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 7612 // return F; 7613 7614 // select ?, T, T --> T 7615 if (T == F) 7616 return T; 7617 7618 return SDValue(); 7619 } 7620 7621 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 7622 // shift undef, Y --> 0 (can always assume that the undef value is 0) 7623 if (X.isUndef()) 7624 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 7625 // shift X, undef --> undef (because it may shift by the bitwidth) 7626 if (Y.isUndef()) 7627 return getUNDEF(X.getValueType()); 7628 7629 // shift 0, Y --> 0 7630 // shift X, 0 --> X 7631 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 7632 return X; 7633 7634 // shift X, C >= bitwidth(X) --> undef 7635 // All vector elements must be too big (or undef) to avoid partial undefs. 7636 auto isShiftTooBig = [X](ConstantSDNode *Val) { 7637 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 7638 }; 7639 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 7640 return getUNDEF(X.getValueType()); 7641 7642 return SDValue(); 7643 } 7644 7645 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 7646 SDNodeFlags Flags) { 7647 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 7648 // (an undef operand can be chosen to be Nan/Inf), then the result of this 7649 // operation is poison. That result can be relaxed to undef. 7650 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 7651 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 7652 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 7653 (YC && YC->getValueAPF().isNaN()); 7654 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 7655 (YC && YC->getValueAPF().isInfinity()); 7656 7657 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 7658 return getUNDEF(X.getValueType()); 7659 7660 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 7661 return getUNDEF(X.getValueType()); 7662 7663 if (!YC) 7664 return SDValue(); 7665 7666 // X + -0.0 --> X 7667 if (Opcode == ISD::FADD) 7668 if (YC->getValueAPF().isNegZero()) 7669 return X; 7670 7671 // X - +0.0 --> X 7672 if (Opcode == ISD::FSUB) 7673 if (YC->getValueAPF().isPosZero()) 7674 return X; 7675 7676 // X * 1.0 --> X 7677 // X / 1.0 --> X 7678 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 7679 if (YC->getValueAPF().isExactlyValue(1.0)) 7680 return X; 7681 7682 // X * 0.0 --> 0.0 7683 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 7684 if (YC->getValueAPF().isZero()) 7685 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 7686 7687 return SDValue(); 7688 } 7689 7690 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 7691 SDValue Ptr, SDValue SV, unsigned Align) { 7692 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 7693 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 7694 } 7695 7696 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7697 ArrayRef<SDUse> Ops) { 7698 switch (Ops.size()) { 7699 case 0: return getNode(Opcode, DL, VT); 7700 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 7701 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 7702 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 7703 default: break; 7704 } 7705 7706 // Copy from an SDUse array into an SDValue array for use with 7707 // the regular getNode logic. 7708 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 7709 return getNode(Opcode, DL, VT, NewOps); 7710 } 7711 7712 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7713 ArrayRef<SDValue> Ops) { 7714 SDNodeFlags Flags; 7715 if (Inserter) 7716 Flags = Inserter->getFlags(); 7717 return getNode(Opcode, DL, VT, Ops, Flags); 7718 } 7719 7720 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7721 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7722 unsigned NumOps = Ops.size(); 7723 switch (NumOps) { 7724 case 0: return getNode(Opcode, DL, VT); 7725 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 7726 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 7727 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 7728 default: break; 7729 } 7730 7731 #ifndef NDEBUG 7732 for (auto &Op : Ops) 7733 assert(Op.getOpcode() != ISD::DELETED_NODE && 7734 "Operand is DELETED_NODE!"); 7735 #endif 7736 7737 switch (Opcode) { 7738 default: break; 7739 case ISD::BUILD_VECTOR: 7740 // Attempt to simplify BUILD_VECTOR. 7741 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 7742 return V; 7743 break; 7744 case ISD::CONCAT_VECTORS: 7745 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 7746 return V; 7747 break; 7748 case ISD::SELECT_CC: 7749 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 7750 assert(Ops[0].getValueType() == Ops[1].getValueType() && 7751 "LHS and RHS of condition must have same type!"); 7752 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7753 "True and False arms of SelectCC must have same type!"); 7754 assert(Ops[2].getValueType() == VT && 7755 "select_cc node must be of same type as true and false value!"); 7756 break; 7757 case ISD::BR_CC: 7758 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 7759 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7760 "LHS/RHS of comparison should match types!"); 7761 break; 7762 } 7763 7764 // Memoize nodes. 7765 SDNode *N; 7766 SDVTList VTs = getVTList(VT); 7767 7768 if (VT != MVT::Glue) { 7769 FoldingSetNodeID ID; 7770 AddNodeIDNode(ID, Opcode, VTs, Ops); 7771 void *IP = nullptr; 7772 7773 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7774 return SDValue(E, 0); 7775 7776 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7777 createOperands(N, Ops); 7778 7779 CSEMap.InsertNode(N, IP); 7780 } else { 7781 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7782 createOperands(N, Ops); 7783 } 7784 7785 N->setFlags(Flags); 7786 InsertNode(N); 7787 SDValue V(N, 0); 7788 NewSDValueDbgMsg(V, "Creating new node: ", this); 7789 return V; 7790 } 7791 7792 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7793 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 7794 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 7795 } 7796 7797 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7798 ArrayRef<SDValue> Ops) { 7799 SDNodeFlags Flags; 7800 if (Inserter) 7801 Flags = Inserter->getFlags(); 7802 return getNode(Opcode, DL, VTList, Ops, Flags); 7803 } 7804 7805 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7806 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7807 if (VTList.NumVTs == 1) 7808 return getNode(Opcode, DL, VTList.VTs[0], Ops); 7809 7810 #ifndef NDEBUG 7811 for (auto &Op : Ops) 7812 assert(Op.getOpcode() != ISD::DELETED_NODE && 7813 "Operand is DELETED_NODE!"); 7814 #endif 7815 7816 switch (Opcode) { 7817 case ISD::STRICT_FP_EXTEND: 7818 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 7819 "Invalid STRICT_FP_EXTEND!"); 7820 assert(VTList.VTs[0].isFloatingPoint() && 7821 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 7822 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7823 "STRICT_FP_EXTEND result type should be vector iff the operand " 7824 "type is vector!"); 7825 assert((!VTList.VTs[0].isVector() || 7826 VTList.VTs[0].getVectorNumElements() == 7827 Ops[1].getValueType().getVectorNumElements()) && 7828 "Vector element count mismatch!"); 7829 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 7830 "Invalid fpext node, dst <= src!"); 7831 break; 7832 case ISD::STRICT_FP_ROUND: 7833 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 7834 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7835 "STRICT_FP_ROUND result type should be vector iff the operand " 7836 "type is vector!"); 7837 assert((!VTList.VTs[0].isVector() || 7838 VTList.VTs[0].getVectorNumElements() == 7839 Ops[1].getValueType().getVectorNumElements()) && 7840 "Vector element count mismatch!"); 7841 assert(VTList.VTs[0].isFloatingPoint() && 7842 Ops[1].getValueType().isFloatingPoint() && 7843 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 7844 isa<ConstantSDNode>(Ops[2]) && 7845 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 7846 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 7847 "Invalid STRICT_FP_ROUND!"); 7848 break; 7849 #if 0 7850 // FIXME: figure out how to safely handle things like 7851 // int foo(int x) { return 1 << (x & 255); } 7852 // int bar() { return foo(256); } 7853 case ISD::SRA_PARTS: 7854 case ISD::SRL_PARTS: 7855 case ISD::SHL_PARTS: 7856 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 7857 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 7858 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7859 else if (N3.getOpcode() == ISD::AND) 7860 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 7861 // If the and is only masking out bits that cannot effect the shift, 7862 // eliminate the and. 7863 unsigned NumBits = VT.getScalarSizeInBits()*2; 7864 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 7865 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7866 } 7867 break; 7868 #endif 7869 } 7870 7871 // Memoize the node unless it returns a flag. 7872 SDNode *N; 7873 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7874 FoldingSetNodeID ID; 7875 AddNodeIDNode(ID, Opcode, VTList, Ops); 7876 void *IP = nullptr; 7877 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7878 return SDValue(E, 0); 7879 7880 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7881 createOperands(N, Ops); 7882 CSEMap.InsertNode(N, IP); 7883 } else { 7884 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7885 createOperands(N, Ops); 7886 } 7887 7888 N->setFlags(Flags); 7889 InsertNode(N); 7890 SDValue V(N, 0); 7891 NewSDValueDbgMsg(V, "Creating new node: ", this); 7892 return V; 7893 } 7894 7895 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7896 SDVTList VTList) { 7897 return getNode(Opcode, DL, VTList, None); 7898 } 7899 7900 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7901 SDValue N1) { 7902 SDValue Ops[] = { N1 }; 7903 return getNode(Opcode, DL, VTList, Ops); 7904 } 7905 7906 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7907 SDValue N1, SDValue N2) { 7908 SDValue Ops[] = { N1, N2 }; 7909 return getNode(Opcode, DL, VTList, Ops); 7910 } 7911 7912 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7913 SDValue N1, SDValue N2, SDValue N3) { 7914 SDValue Ops[] = { N1, N2, N3 }; 7915 return getNode(Opcode, DL, VTList, Ops); 7916 } 7917 7918 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7919 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 7920 SDValue Ops[] = { N1, N2, N3, N4 }; 7921 return getNode(Opcode, DL, VTList, Ops); 7922 } 7923 7924 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7925 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 7926 SDValue N5) { 7927 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 7928 return getNode(Opcode, DL, VTList, Ops); 7929 } 7930 7931 SDVTList SelectionDAG::getVTList(EVT VT) { 7932 return makeVTList(SDNode::getValueTypeList(VT), 1); 7933 } 7934 7935 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 7936 FoldingSetNodeID ID; 7937 ID.AddInteger(2U); 7938 ID.AddInteger(VT1.getRawBits()); 7939 ID.AddInteger(VT2.getRawBits()); 7940 7941 void *IP = nullptr; 7942 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7943 if (!Result) { 7944 EVT *Array = Allocator.Allocate<EVT>(2); 7945 Array[0] = VT1; 7946 Array[1] = VT2; 7947 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 7948 VTListMap.InsertNode(Result, IP); 7949 } 7950 return Result->getSDVTList(); 7951 } 7952 7953 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 7954 FoldingSetNodeID ID; 7955 ID.AddInteger(3U); 7956 ID.AddInteger(VT1.getRawBits()); 7957 ID.AddInteger(VT2.getRawBits()); 7958 ID.AddInteger(VT3.getRawBits()); 7959 7960 void *IP = nullptr; 7961 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7962 if (!Result) { 7963 EVT *Array = Allocator.Allocate<EVT>(3); 7964 Array[0] = VT1; 7965 Array[1] = VT2; 7966 Array[2] = VT3; 7967 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 7968 VTListMap.InsertNode(Result, IP); 7969 } 7970 return Result->getSDVTList(); 7971 } 7972 7973 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 7974 FoldingSetNodeID ID; 7975 ID.AddInteger(4U); 7976 ID.AddInteger(VT1.getRawBits()); 7977 ID.AddInteger(VT2.getRawBits()); 7978 ID.AddInteger(VT3.getRawBits()); 7979 ID.AddInteger(VT4.getRawBits()); 7980 7981 void *IP = nullptr; 7982 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7983 if (!Result) { 7984 EVT *Array = Allocator.Allocate<EVT>(4); 7985 Array[0] = VT1; 7986 Array[1] = VT2; 7987 Array[2] = VT3; 7988 Array[3] = VT4; 7989 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 7990 VTListMap.InsertNode(Result, IP); 7991 } 7992 return Result->getSDVTList(); 7993 } 7994 7995 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 7996 unsigned NumVTs = VTs.size(); 7997 FoldingSetNodeID ID; 7998 ID.AddInteger(NumVTs); 7999 for (unsigned index = 0; index < NumVTs; index++) { 8000 ID.AddInteger(VTs[index].getRawBits()); 8001 } 8002 8003 void *IP = nullptr; 8004 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8005 if (!Result) { 8006 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 8007 llvm::copy(VTs, Array); 8008 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 8009 VTListMap.InsertNode(Result, IP); 8010 } 8011 return Result->getSDVTList(); 8012 } 8013 8014 8015 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 8016 /// specified operands. If the resultant node already exists in the DAG, 8017 /// this does not modify the specified node, instead it returns the node that 8018 /// already exists. If the resultant node does not exist in the DAG, the 8019 /// input node is returned. As a degenerate case, if you specify the same 8020 /// input operands as the node already has, the input node is returned. 8021 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 8022 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 8023 8024 // Check to see if there is no change. 8025 if (Op == N->getOperand(0)) return N; 8026 8027 // See if the modified node already exists. 8028 void *InsertPos = nullptr; 8029 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 8030 return Existing; 8031 8032 // Nope it doesn't. Remove the node from its current place in the maps. 8033 if (InsertPos) 8034 if (!RemoveNodeFromCSEMaps(N)) 8035 InsertPos = nullptr; 8036 8037 // Now we update the operands. 8038 N->OperandList[0].set(Op); 8039 8040 updateDivergence(N); 8041 // If this gets put into a CSE map, add it. 8042 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8043 return N; 8044 } 8045 8046 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 8047 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 8048 8049 // Check to see if there is no change. 8050 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 8051 return N; // No operands changed, just return the input node. 8052 8053 // See if the modified node already exists. 8054 void *InsertPos = nullptr; 8055 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 8056 return Existing; 8057 8058 // Nope it doesn't. Remove the node from its current place in the maps. 8059 if (InsertPos) 8060 if (!RemoveNodeFromCSEMaps(N)) 8061 InsertPos = nullptr; 8062 8063 // Now we update the operands. 8064 if (N->OperandList[0] != Op1) 8065 N->OperandList[0].set(Op1); 8066 if (N->OperandList[1] != Op2) 8067 N->OperandList[1].set(Op2); 8068 8069 updateDivergence(N); 8070 // If this gets put into a CSE map, add it. 8071 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8072 return N; 8073 } 8074 8075 SDNode *SelectionDAG:: 8076 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 8077 SDValue Ops[] = { Op1, Op2, Op3 }; 8078 return UpdateNodeOperands(N, Ops); 8079 } 8080 8081 SDNode *SelectionDAG:: 8082 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8083 SDValue Op3, SDValue Op4) { 8084 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 8085 return UpdateNodeOperands(N, Ops); 8086 } 8087 8088 SDNode *SelectionDAG:: 8089 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8090 SDValue Op3, SDValue Op4, SDValue Op5) { 8091 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 8092 return UpdateNodeOperands(N, Ops); 8093 } 8094 8095 SDNode *SelectionDAG:: 8096 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 8097 unsigned NumOps = Ops.size(); 8098 assert(N->getNumOperands() == NumOps && 8099 "Update with wrong number of operands"); 8100 8101 // If no operands changed just return the input node. 8102 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 8103 return N; 8104 8105 // See if the modified node already exists. 8106 void *InsertPos = nullptr; 8107 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8108 return Existing; 8109 8110 // Nope it doesn't. Remove the node from its current place in the maps. 8111 if (InsertPos) 8112 if (!RemoveNodeFromCSEMaps(N)) 8113 InsertPos = nullptr; 8114 8115 // Now we update the operands. 8116 for (unsigned i = 0; i != NumOps; ++i) 8117 if (N->OperandList[i] != Ops[i]) 8118 N->OperandList[i].set(Ops[i]); 8119 8120 updateDivergence(N); 8121 // If this gets put into a CSE map, add it. 8122 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8123 return N; 8124 } 8125 8126 /// DropOperands - Release the operands and set this node to have 8127 /// zero operands. 8128 void SDNode::DropOperands() { 8129 // Unlike the code in MorphNodeTo that does this, we don't need to 8130 // watch for dead nodes here. 8131 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8132 SDUse &Use = *I++; 8133 Use.set(SDValue()); 8134 } 8135 } 8136 8137 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8138 ArrayRef<MachineMemOperand *> NewMemRefs) { 8139 if (NewMemRefs.empty()) { 8140 N->clearMemRefs(); 8141 return; 8142 } 8143 8144 // Check if we can avoid allocating by storing a single reference directly. 8145 if (NewMemRefs.size() == 1) { 8146 N->MemRefs = NewMemRefs[0]; 8147 N->NumMemRefs = 1; 8148 return; 8149 } 8150 8151 MachineMemOperand **MemRefsBuffer = 8152 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8153 llvm::copy(NewMemRefs, MemRefsBuffer); 8154 N->MemRefs = MemRefsBuffer; 8155 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8156 } 8157 8158 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8159 /// machine opcode. 8160 /// 8161 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8162 EVT VT) { 8163 SDVTList VTs = getVTList(VT); 8164 return SelectNodeTo(N, MachineOpc, VTs, None); 8165 } 8166 8167 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8168 EVT VT, SDValue Op1) { 8169 SDVTList VTs = getVTList(VT); 8170 SDValue Ops[] = { Op1 }; 8171 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8172 } 8173 8174 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8175 EVT VT, SDValue Op1, 8176 SDValue Op2) { 8177 SDVTList VTs = getVTList(VT); 8178 SDValue Ops[] = { Op1, Op2 }; 8179 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8180 } 8181 8182 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8183 EVT VT, SDValue Op1, 8184 SDValue Op2, SDValue Op3) { 8185 SDVTList VTs = getVTList(VT); 8186 SDValue Ops[] = { Op1, Op2, Op3 }; 8187 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8188 } 8189 8190 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8191 EVT VT, ArrayRef<SDValue> Ops) { 8192 SDVTList VTs = getVTList(VT); 8193 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8194 } 8195 8196 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8197 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8198 SDVTList VTs = getVTList(VT1, VT2); 8199 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8200 } 8201 8202 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8203 EVT VT1, EVT VT2) { 8204 SDVTList VTs = getVTList(VT1, VT2); 8205 return SelectNodeTo(N, MachineOpc, VTs, None); 8206 } 8207 8208 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8209 EVT VT1, EVT VT2, EVT VT3, 8210 ArrayRef<SDValue> Ops) { 8211 SDVTList VTs = getVTList(VT1, VT2, VT3); 8212 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8213 } 8214 8215 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8216 EVT VT1, EVT VT2, 8217 SDValue Op1, SDValue Op2) { 8218 SDVTList VTs = getVTList(VT1, VT2); 8219 SDValue Ops[] = { Op1, Op2 }; 8220 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8221 } 8222 8223 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8224 SDVTList VTs,ArrayRef<SDValue> Ops) { 8225 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8226 // Reset the NodeID to -1. 8227 New->setNodeId(-1); 8228 if (New != N) { 8229 ReplaceAllUsesWith(N, New); 8230 RemoveDeadNode(N); 8231 } 8232 return New; 8233 } 8234 8235 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8236 /// the line number information on the merged node since it is not possible to 8237 /// preserve the information that operation is associated with multiple lines. 8238 /// This will make the debugger working better at -O0, were there is a higher 8239 /// probability having other instructions associated with that line. 8240 /// 8241 /// For IROrder, we keep the smaller of the two 8242 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8243 DebugLoc NLoc = N->getDebugLoc(); 8244 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8245 N->setDebugLoc(DebugLoc()); 8246 } 8247 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8248 N->setIROrder(Order); 8249 return N; 8250 } 8251 8252 /// MorphNodeTo - This *mutates* the specified node to have the specified 8253 /// return type, opcode, and operands. 8254 /// 8255 /// Note that MorphNodeTo returns the resultant node. If there is already a 8256 /// node of the specified opcode and operands, it returns that node instead of 8257 /// the current one. Note that the SDLoc need not be the same. 8258 /// 8259 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8260 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8261 /// node, and because it doesn't require CSE recalculation for any of 8262 /// the node's users. 8263 /// 8264 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8265 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8266 /// the legalizer which maintain worklists that would need to be updated when 8267 /// deleting things. 8268 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8269 SDVTList VTs, ArrayRef<SDValue> Ops) { 8270 // If an identical node already exists, use it. 8271 void *IP = nullptr; 8272 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8273 FoldingSetNodeID ID; 8274 AddNodeIDNode(ID, Opc, VTs, Ops); 8275 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8276 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8277 } 8278 8279 if (!RemoveNodeFromCSEMaps(N)) 8280 IP = nullptr; 8281 8282 // Start the morphing. 8283 N->NodeType = Opc; 8284 N->ValueList = VTs.VTs; 8285 N->NumValues = VTs.NumVTs; 8286 8287 // Clear the operands list, updating used nodes to remove this from their 8288 // use list. Keep track of any operands that become dead as a result. 8289 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8290 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8291 SDUse &Use = *I++; 8292 SDNode *Used = Use.getNode(); 8293 Use.set(SDValue()); 8294 if (Used->use_empty()) 8295 DeadNodeSet.insert(Used); 8296 } 8297 8298 // For MachineNode, initialize the memory references information. 8299 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8300 MN->clearMemRefs(); 8301 8302 // Swap for an appropriately sized array from the recycler. 8303 removeOperands(N); 8304 createOperands(N, Ops); 8305 8306 // Delete any nodes that are still dead after adding the uses for the 8307 // new operands. 8308 if (!DeadNodeSet.empty()) { 8309 SmallVector<SDNode *, 16> DeadNodes; 8310 for (SDNode *N : DeadNodeSet) 8311 if (N->use_empty()) 8312 DeadNodes.push_back(N); 8313 RemoveDeadNodes(DeadNodes); 8314 } 8315 8316 if (IP) 8317 CSEMap.InsertNode(N, IP); // Memoize the new node. 8318 return N; 8319 } 8320 8321 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8322 unsigned OrigOpc = Node->getOpcode(); 8323 unsigned NewOpc; 8324 switch (OrigOpc) { 8325 default: 8326 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8327 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8328 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8329 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8330 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8331 #include "llvm/IR/ConstrainedOps.def" 8332 } 8333 8334 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8335 8336 // We're taking this node out of the chain, so we need to re-link things. 8337 SDValue InputChain = Node->getOperand(0); 8338 SDValue OutputChain = SDValue(Node, 1); 8339 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8340 8341 SmallVector<SDValue, 3> Ops; 8342 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8343 Ops.push_back(Node->getOperand(i)); 8344 8345 SDVTList VTs = getVTList(Node->getValueType(0)); 8346 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8347 8348 // MorphNodeTo can operate in two ways: if an existing node with the 8349 // specified operands exists, it can just return it. Otherwise, it 8350 // updates the node in place to have the requested operands. 8351 if (Res == Node) { 8352 // If we updated the node in place, reset the node ID. To the isel, 8353 // this should be just like a newly allocated machine node. 8354 Res->setNodeId(-1); 8355 } else { 8356 ReplaceAllUsesWith(Node, Res); 8357 RemoveDeadNode(Node); 8358 } 8359 8360 return Res; 8361 } 8362 8363 /// getMachineNode - These are used for target selectors to create a new node 8364 /// with specified return type(s), MachineInstr opcode, and operands. 8365 /// 8366 /// Note that getMachineNode returns the resultant node. If there is already a 8367 /// node of the specified opcode and operands, it returns that node instead of 8368 /// the current one. 8369 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8370 EVT VT) { 8371 SDVTList VTs = getVTList(VT); 8372 return getMachineNode(Opcode, dl, VTs, None); 8373 } 8374 8375 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8376 EVT VT, SDValue Op1) { 8377 SDVTList VTs = getVTList(VT); 8378 SDValue Ops[] = { Op1 }; 8379 return getMachineNode(Opcode, dl, VTs, Ops); 8380 } 8381 8382 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8383 EVT VT, SDValue Op1, SDValue Op2) { 8384 SDVTList VTs = getVTList(VT); 8385 SDValue Ops[] = { Op1, Op2 }; 8386 return getMachineNode(Opcode, dl, VTs, Ops); 8387 } 8388 8389 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8390 EVT VT, SDValue Op1, SDValue Op2, 8391 SDValue Op3) { 8392 SDVTList VTs = getVTList(VT); 8393 SDValue Ops[] = { Op1, Op2, Op3 }; 8394 return getMachineNode(Opcode, dl, VTs, Ops); 8395 } 8396 8397 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8398 EVT VT, ArrayRef<SDValue> Ops) { 8399 SDVTList VTs = getVTList(VT); 8400 return getMachineNode(Opcode, dl, VTs, Ops); 8401 } 8402 8403 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8404 EVT VT1, EVT VT2, SDValue Op1, 8405 SDValue Op2) { 8406 SDVTList VTs = getVTList(VT1, VT2); 8407 SDValue Ops[] = { Op1, Op2 }; 8408 return getMachineNode(Opcode, dl, VTs, Ops); 8409 } 8410 8411 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8412 EVT VT1, EVT VT2, SDValue Op1, 8413 SDValue Op2, SDValue Op3) { 8414 SDVTList VTs = getVTList(VT1, VT2); 8415 SDValue Ops[] = { Op1, Op2, Op3 }; 8416 return getMachineNode(Opcode, dl, VTs, Ops); 8417 } 8418 8419 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8420 EVT VT1, EVT VT2, 8421 ArrayRef<SDValue> Ops) { 8422 SDVTList VTs = getVTList(VT1, VT2); 8423 return getMachineNode(Opcode, dl, VTs, Ops); 8424 } 8425 8426 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8427 EVT VT1, EVT VT2, EVT VT3, 8428 SDValue Op1, SDValue Op2) { 8429 SDVTList VTs = getVTList(VT1, VT2, VT3); 8430 SDValue Ops[] = { Op1, Op2 }; 8431 return getMachineNode(Opcode, dl, VTs, Ops); 8432 } 8433 8434 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8435 EVT VT1, EVT VT2, EVT VT3, 8436 SDValue Op1, SDValue Op2, 8437 SDValue Op3) { 8438 SDVTList VTs = getVTList(VT1, VT2, VT3); 8439 SDValue Ops[] = { Op1, Op2, Op3 }; 8440 return getMachineNode(Opcode, dl, VTs, Ops); 8441 } 8442 8443 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8444 EVT VT1, EVT VT2, EVT VT3, 8445 ArrayRef<SDValue> Ops) { 8446 SDVTList VTs = getVTList(VT1, VT2, VT3); 8447 return getMachineNode(Opcode, dl, VTs, Ops); 8448 } 8449 8450 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8451 ArrayRef<EVT> ResultTys, 8452 ArrayRef<SDValue> Ops) { 8453 SDVTList VTs = getVTList(ResultTys); 8454 return getMachineNode(Opcode, dl, VTs, Ops); 8455 } 8456 8457 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 8458 SDVTList VTs, 8459 ArrayRef<SDValue> Ops) { 8460 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 8461 MachineSDNode *N; 8462 void *IP = nullptr; 8463 8464 if (DoCSE) { 8465 FoldingSetNodeID ID; 8466 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 8467 IP = nullptr; 8468 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8469 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 8470 } 8471 } 8472 8473 // Allocate a new MachineSDNode. 8474 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8475 createOperands(N, Ops); 8476 8477 if (DoCSE) 8478 CSEMap.InsertNode(N, IP); 8479 8480 InsertNode(N); 8481 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 8482 return N; 8483 } 8484 8485 /// getTargetExtractSubreg - A convenience function for creating 8486 /// TargetOpcode::EXTRACT_SUBREG nodes. 8487 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8488 SDValue Operand) { 8489 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8490 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 8491 VT, Operand, SRIdxVal); 8492 return SDValue(Subreg, 0); 8493 } 8494 8495 /// getTargetInsertSubreg - A convenience function for creating 8496 /// TargetOpcode::INSERT_SUBREG nodes. 8497 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8498 SDValue Operand, SDValue Subreg) { 8499 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8500 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 8501 VT, Operand, Subreg, SRIdxVal); 8502 return SDValue(Result, 0); 8503 } 8504 8505 /// getNodeIfExists - Get the specified node if it's already available, or 8506 /// else return NULL. 8507 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8508 ArrayRef<SDValue> Ops) { 8509 SDNodeFlags Flags; 8510 if (Inserter) 8511 Flags = Inserter->getFlags(); 8512 return getNodeIfExists(Opcode, VTList, Ops, Flags); 8513 } 8514 8515 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8516 ArrayRef<SDValue> Ops, 8517 const SDNodeFlags Flags) { 8518 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8519 FoldingSetNodeID ID; 8520 AddNodeIDNode(ID, Opcode, VTList, Ops); 8521 void *IP = nullptr; 8522 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 8523 E->intersectFlagsWith(Flags); 8524 return E; 8525 } 8526 } 8527 return nullptr; 8528 } 8529 8530 /// doesNodeExist - Check if a node exists without modifying its flags. 8531 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 8532 ArrayRef<SDValue> Ops) { 8533 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8534 FoldingSetNodeID ID; 8535 AddNodeIDNode(ID, Opcode, VTList, Ops); 8536 void *IP = nullptr; 8537 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 8538 return true; 8539 } 8540 return false; 8541 } 8542 8543 /// getDbgValue - Creates a SDDbgValue node. 8544 /// 8545 /// SDNode 8546 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 8547 SDNode *N, unsigned R, bool IsIndirect, 8548 const DebugLoc &DL, unsigned O) { 8549 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8550 "Expected inlined-at fields to agree"); 8551 return new (DbgInfo->getAlloc()) 8552 SDDbgValue(Var, Expr, SDDbgOperand::fromNode(N, R), N, IsIndirect, DL, O, 8553 /*IsVariadic=*/false); 8554 } 8555 8556 /// Constant 8557 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 8558 DIExpression *Expr, 8559 const Value *C, 8560 const DebugLoc &DL, unsigned O) { 8561 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8562 "Expected inlined-at fields to agree"); 8563 return new (DbgInfo->getAlloc()) SDDbgValue( 8564 Var, Expr, SDDbgOperand::fromConst(C), {}, /*IsIndirect=*/false, DL, O, 8565 /*IsVariadic=*/false); 8566 } 8567 8568 /// FrameIndex 8569 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8570 DIExpression *Expr, unsigned FI, 8571 bool IsIndirect, 8572 const DebugLoc &DL, 8573 unsigned O) { 8574 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8575 "Expected inlined-at fields to agree"); 8576 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 8577 } 8578 8579 /// FrameIndex with dependencies 8580 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8581 DIExpression *Expr, unsigned FI, 8582 ArrayRef<SDNode *> Dependencies, 8583 bool IsIndirect, 8584 const DebugLoc &DL, 8585 unsigned O) { 8586 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8587 "Expected inlined-at fields to agree"); 8588 return new (DbgInfo->getAlloc()) 8589 SDDbgValue(Var, Expr, SDDbgOperand::fromFrameIdx(FI), Dependencies, 8590 IsIndirect, DL, O, 8591 /*IsVariadic=*/false); 8592 } 8593 8594 /// VReg 8595 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 8596 unsigned VReg, bool IsIndirect, 8597 const DebugLoc &DL, unsigned O) { 8598 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8599 "Expected inlined-at fields to agree"); 8600 return new (DbgInfo->getAlloc()) 8601 SDDbgValue(Var, Expr, SDDbgOperand::fromVReg(VReg), {}, IsIndirect, DL, O, 8602 /*IsVariadic=*/false); 8603 } 8604 8605 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 8606 ArrayRef<SDDbgOperand> Locs, 8607 ArrayRef<SDNode *> Dependencies, 8608 bool IsIndirect, const DebugLoc &DL, 8609 unsigned O, bool IsVariadic) { 8610 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8611 "Expected inlined-at fields to agree"); 8612 return new (DbgInfo->getAlloc()) 8613 SDDbgValue(Var, Expr, Locs, Dependencies, IsIndirect, DL, O, IsVariadic); 8614 } 8615 8616 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 8617 unsigned OffsetInBits, unsigned SizeInBits, 8618 bool InvalidateDbg) { 8619 SDNode *FromNode = From.getNode(); 8620 SDNode *ToNode = To.getNode(); 8621 assert(FromNode && ToNode && "Can't modify dbg values"); 8622 8623 // PR35338 8624 // TODO: assert(From != To && "Redundant dbg value transfer"); 8625 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 8626 if (From == To || FromNode == ToNode) 8627 return; 8628 8629 if (!FromNode->getHasDebugValue()) 8630 return; 8631 8632 SDDbgOperand FromLocOp = 8633 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 8634 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 8635 8636 SmallVector<SDDbgValue *, 2> ClonedDVs; 8637 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 8638 if (Dbg->isInvalidated()) 8639 continue; 8640 8641 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 8642 8643 // Create a new location ops vector that is equal to the old vector, but 8644 // with each instance of FromLocOp replaced with ToLocOp. 8645 bool Changed = false; 8646 auto NewLocOps = Dbg->copyLocationOps(); 8647 std::replace_if( 8648 NewLocOps.begin(), NewLocOps.end(), 8649 [&Changed, FromLocOp](const SDDbgOperand &Op) { 8650 bool Match = Op == FromLocOp; 8651 Changed |= Match; 8652 return Match; 8653 }, 8654 ToLocOp); 8655 // Ignore this SDDbgValue if we didn't find a matching location. 8656 if (!Changed) 8657 continue; 8658 8659 DIVariable *Var = Dbg->getVariable(); 8660 auto *Expr = Dbg->getExpression(); 8661 // If a fragment is requested, update the expression. 8662 if (SizeInBits) { 8663 // When splitting a larger (e.g., sign-extended) value whose 8664 // lower bits are described with an SDDbgValue, do not attempt 8665 // to transfer the SDDbgValue to the upper bits. 8666 if (auto FI = Expr->getFragmentInfo()) 8667 if (OffsetInBits + SizeInBits > FI->SizeInBits) 8668 continue; 8669 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 8670 SizeInBits); 8671 if (!Fragment) 8672 continue; 8673 Expr = *Fragment; 8674 } 8675 8676 auto NewDependencies = Dbg->copySDNodes(); 8677 std::replace(NewDependencies.begin(), NewDependencies.end(), FromNode, 8678 ToNode); 8679 // Clone the SDDbgValue and move it to To. 8680 SDDbgValue *Clone = getDbgValueList( 8681 Var, Expr, NewLocOps, NewDependencies, Dbg->isIndirect(), 8682 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 8683 Dbg->isVariadic()); 8684 ClonedDVs.push_back(Clone); 8685 8686 if (InvalidateDbg) { 8687 // Invalidate value and indicate the SDDbgValue should not be emitted. 8688 Dbg->setIsInvalidated(); 8689 Dbg->setIsEmitted(); 8690 } 8691 } 8692 8693 for (SDDbgValue *Dbg : ClonedDVs) { 8694 assert(is_contained(Dbg->getSDNodes(), ToNode) && 8695 "Transferred DbgValues should depend on the new SDNode"); 8696 AddDbgValue(Dbg, false); 8697 } 8698 } 8699 8700 void SelectionDAG::salvageDebugInfo(SDNode &N) { 8701 if (!N.getHasDebugValue()) 8702 return; 8703 8704 SmallVector<SDDbgValue *, 2> ClonedDVs; 8705 for (auto DV : GetDbgValues(&N)) { 8706 if (DV->isInvalidated()) 8707 continue; 8708 switch (N.getOpcode()) { 8709 default: 8710 break; 8711 case ISD::ADD: 8712 SDValue N0 = N.getOperand(0); 8713 SDValue N1 = N.getOperand(1); 8714 if (!isConstantIntBuildVectorOrConstantInt(N0) && 8715 isConstantIntBuildVectorOrConstantInt(N1)) { 8716 uint64_t Offset = N.getConstantOperandVal(1); 8717 8718 // Rewrite an ADD constant node into a DIExpression. Since we are 8719 // performing arithmetic to compute the variable's *value* in the 8720 // DIExpression, we need to mark the expression with a 8721 // DW_OP_stack_value. 8722 auto *DIExpr = DV->getExpression(); 8723 auto NewLocOps = DV->copyLocationOps(); 8724 bool Changed = false; 8725 for (size_t i = 0; i < NewLocOps.size(); ++i) { 8726 // We're not given a ResNo to compare against because the whole 8727 // node is going away. We know that any ISD::ADD only has one 8728 // result, so we can assume any node match is using the result. 8729 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 8730 NewLocOps[i].getSDNode() != &N) 8731 continue; 8732 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 8733 SmallVector<uint64_t, 3> ExprOps; 8734 DIExpression::appendOffset(ExprOps, Offset); 8735 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 8736 Changed = true; 8737 } 8738 (void)Changed; 8739 assert(Changed && "Salvage target doesn't use N"); 8740 8741 auto NewDependencies = DV->copySDNodes(); 8742 std::replace(NewDependencies.begin(), NewDependencies.end(), &N, 8743 N0.getNode()); 8744 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 8745 NewLocOps, NewDependencies, 8746 DV->isIndirect(), DV->getDebugLoc(), 8747 DV->getOrder(), DV->isVariadic()); 8748 ClonedDVs.push_back(Clone); 8749 DV->setIsInvalidated(); 8750 DV->setIsEmitted(); 8751 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 8752 N0.getNode()->dumprFull(this); 8753 dbgs() << " into " << *DIExpr << '\n'); 8754 } 8755 } 8756 } 8757 8758 for (SDDbgValue *Dbg : ClonedDVs) { 8759 assert(!Dbg->getSDNodes().empty() && 8760 "Salvaged DbgValue should depend on a new SDNode"); 8761 AddDbgValue(Dbg, false); 8762 } 8763 } 8764 8765 /// Creates a SDDbgLabel node. 8766 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 8767 const DebugLoc &DL, unsigned O) { 8768 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 8769 "Expected inlined-at fields to agree"); 8770 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 8771 } 8772 8773 namespace { 8774 8775 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 8776 /// pointed to by a use iterator is deleted, increment the use iterator 8777 /// so that it doesn't dangle. 8778 /// 8779 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 8780 SDNode::use_iterator &UI; 8781 SDNode::use_iterator &UE; 8782 8783 void NodeDeleted(SDNode *N, SDNode *E) override { 8784 // Increment the iterator as needed. 8785 while (UI != UE && N == *UI) 8786 ++UI; 8787 } 8788 8789 public: 8790 RAUWUpdateListener(SelectionDAG &d, 8791 SDNode::use_iterator &ui, 8792 SDNode::use_iterator &ue) 8793 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 8794 }; 8795 8796 } // end anonymous namespace 8797 8798 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8799 /// This can cause recursive merging of nodes in the DAG. 8800 /// 8801 /// This version assumes From has a single result value. 8802 /// 8803 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 8804 SDNode *From = FromN.getNode(); 8805 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 8806 "Cannot replace with this method!"); 8807 assert(From != To.getNode() && "Cannot replace uses of with self"); 8808 8809 // Preserve Debug Values 8810 transferDbgValues(FromN, To); 8811 8812 // Iterate over all the existing uses of From. New uses will be added 8813 // to the beginning of the use list, which we avoid visiting. 8814 // This specifically avoids visiting uses of From that arise while the 8815 // replacement is happening, because any such uses would be the result 8816 // of CSE: If an existing node looks like From after one of its operands 8817 // is replaced by To, we don't want to replace of all its users with To 8818 // too. See PR3018 for more info. 8819 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8820 RAUWUpdateListener Listener(*this, UI, UE); 8821 while (UI != UE) { 8822 SDNode *User = *UI; 8823 8824 // This node is about to morph, remove its old self from the CSE maps. 8825 RemoveNodeFromCSEMaps(User); 8826 8827 // A user can appear in a use list multiple times, and when this 8828 // happens the uses are usually next to each other in the list. 8829 // To help reduce the number of CSE recomputations, process all 8830 // the uses of this user that we can find this way. 8831 do { 8832 SDUse &Use = UI.getUse(); 8833 ++UI; 8834 Use.set(To); 8835 if (To->isDivergent() != From->isDivergent()) 8836 updateDivergence(User); 8837 } while (UI != UE && *UI == User); 8838 // Now that we have modified User, add it back to the CSE maps. If it 8839 // already exists there, recursively merge the results together. 8840 AddModifiedNodeToCSEMaps(User); 8841 } 8842 8843 // If we just RAUW'd the root, take note. 8844 if (FromN == getRoot()) 8845 setRoot(To); 8846 } 8847 8848 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8849 /// This can cause recursive merging of nodes in the DAG. 8850 /// 8851 /// This version assumes that for each value of From, there is a 8852 /// corresponding value in To in the same position with the same type. 8853 /// 8854 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 8855 #ifndef NDEBUG 8856 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8857 assert((!From->hasAnyUseOfValue(i) || 8858 From->getValueType(i) == To->getValueType(i)) && 8859 "Cannot use this version of ReplaceAllUsesWith!"); 8860 #endif 8861 8862 // Handle the trivial case. 8863 if (From == To) 8864 return; 8865 8866 // Preserve Debug Info. Only do this if there's a use. 8867 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8868 if (From->hasAnyUseOfValue(i)) { 8869 assert((i < To->getNumValues()) && "Invalid To location"); 8870 transferDbgValues(SDValue(From, i), SDValue(To, i)); 8871 } 8872 8873 // Iterate over just the existing users of From. See the comments in 8874 // the ReplaceAllUsesWith above. 8875 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8876 RAUWUpdateListener Listener(*this, UI, UE); 8877 while (UI != UE) { 8878 SDNode *User = *UI; 8879 8880 // This node is about to morph, remove its old self from the CSE maps. 8881 RemoveNodeFromCSEMaps(User); 8882 8883 // A user can appear in a use list multiple times, and when this 8884 // happens the uses are usually next to each other in the list. 8885 // To help reduce the number of CSE recomputations, process all 8886 // the uses of this user that we can find this way. 8887 do { 8888 SDUse &Use = UI.getUse(); 8889 ++UI; 8890 Use.setNode(To); 8891 if (To->isDivergent() != From->isDivergent()) 8892 updateDivergence(User); 8893 } while (UI != UE && *UI == User); 8894 8895 // Now that we have modified User, add it back to the CSE maps. If it 8896 // already exists there, recursively merge the results together. 8897 AddModifiedNodeToCSEMaps(User); 8898 } 8899 8900 // If we just RAUW'd the root, take note. 8901 if (From == getRoot().getNode()) 8902 setRoot(SDValue(To, getRoot().getResNo())); 8903 } 8904 8905 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8906 /// This can cause recursive merging of nodes in the DAG. 8907 /// 8908 /// This version can replace From with any result values. To must match the 8909 /// number and types of values returned by From. 8910 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 8911 if (From->getNumValues() == 1) // Handle the simple case efficiently. 8912 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 8913 8914 // Preserve Debug Info. 8915 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8916 transferDbgValues(SDValue(From, i), To[i]); 8917 8918 // Iterate over just the existing users of From. See the comments in 8919 // the ReplaceAllUsesWith above. 8920 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8921 RAUWUpdateListener Listener(*this, UI, UE); 8922 while (UI != UE) { 8923 SDNode *User = *UI; 8924 8925 // This node is about to morph, remove its old self from the CSE maps. 8926 RemoveNodeFromCSEMaps(User); 8927 8928 // A user can appear in a use list multiple times, and when this happens the 8929 // uses are usually next to each other in the list. To help reduce the 8930 // number of CSE and divergence recomputations, process all the uses of this 8931 // user that we can find this way. 8932 bool To_IsDivergent = false; 8933 do { 8934 SDUse &Use = UI.getUse(); 8935 const SDValue &ToOp = To[Use.getResNo()]; 8936 ++UI; 8937 Use.set(ToOp); 8938 To_IsDivergent |= ToOp->isDivergent(); 8939 } while (UI != UE && *UI == User); 8940 8941 if (To_IsDivergent != From->isDivergent()) 8942 updateDivergence(User); 8943 8944 // Now that we have modified User, add it back to the CSE maps. If it 8945 // already exists there, recursively merge the results together. 8946 AddModifiedNodeToCSEMaps(User); 8947 } 8948 8949 // If we just RAUW'd the root, take note. 8950 if (From == getRoot().getNode()) 8951 setRoot(SDValue(To[getRoot().getResNo()])); 8952 } 8953 8954 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 8955 /// uses of other values produced by From.getNode() alone. The Deleted 8956 /// vector is handled the same way as for ReplaceAllUsesWith. 8957 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 8958 // Handle the really simple, really trivial case efficiently. 8959 if (From == To) return; 8960 8961 // Handle the simple, trivial, case efficiently. 8962 if (From.getNode()->getNumValues() == 1) { 8963 ReplaceAllUsesWith(From, To); 8964 return; 8965 } 8966 8967 // Preserve Debug Info. 8968 transferDbgValues(From, To); 8969 8970 // Iterate over just the existing users of From. See the comments in 8971 // the ReplaceAllUsesWith above. 8972 SDNode::use_iterator UI = From.getNode()->use_begin(), 8973 UE = From.getNode()->use_end(); 8974 RAUWUpdateListener Listener(*this, UI, UE); 8975 while (UI != UE) { 8976 SDNode *User = *UI; 8977 bool UserRemovedFromCSEMaps = false; 8978 8979 // A user can appear in a use list multiple times, and when this 8980 // happens the uses are usually next to each other in the list. 8981 // To help reduce the number of CSE recomputations, process all 8982 // the uses of this user that we can find this way. 8983 do { 8984 SDUse &Use = UI.getUse(); 8985 8986 // Skip uses of different values from the same node. 8987 if (Use.getResNo() != From.getResNo()) { 8988 ++UI; 8989 continue; 8990 } 8991 8992 // If this node hasn't been modified yet, it's still in the CSE maps, 8993 // so remove its old self from the CSE maps. 8994 if (!UserRemovedFromCSEMaps) { 8995 RemoveNodeFromCSEMaps(User); 8996 UserRemovedFromCSEMaps = true; 8997 } 8998 8999 ++UI; 9000 Use.set(To); 9001 if (To->isDivergent() != From->isDivergent()) 9002 updateDivergence(User); 9003 } while (UI != UE && *UI == User); 9004 // We are iterating over all uses of the From node, so if a use 9005 // doesn't use the specific value, no changes are made. 9006 if (!UserRemovedFromCSEMaps) 9007 continue; 9008 9009 // Now that we have modified User, add it back to the CSE maps. If it 9010 // already exists there, recursively merge the results together. 9011 AddModifiedNodeToCSEMaps(User); 9012 } 9013 9014 // If we just RAUW'd the root, take note. 9015 if (From == getRoot()) 9016 setRoot(To); 9017 } 9018 9019 namespace { 9020 9021 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 9022 /// to record information about a use. 9023 struct UseMemo { 9024 SDNode *User; 9025 unsigned Index; 9026 SDUse *Use; 9027 }; 9028 9029 /// operator< - Sort Memos by User. 9030 bool operator<(const UseMemo &L, const UseMemo &R) { 9031 return (intptr_t)L.User < (intptr_t)R.User; 9032 } 9033 9034 } // end anonymous namespace 9035 9036 bool SelectionDAG::calculateDivergence(SDNode *N) { 9037 if (TLI->isSDNodeAlwaysUniform(N)) { 9038 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 9039 "Conflicting divergence information!"); 9040 return false; 9041 } 9042 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 9043 return true; 9044 for (auto &Op : N->ops()) { 9045 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 9046 return true; 9047 } 9048 return false; 9049 } 9050 9051 void SelectionDAG::updateDivergence(SDNode *N) { 9052 SmallVector<SDNode *, 16> Worklist(1, N); 9053 do { 9054 N = Worklist.pop_back_val(); 9055 bool IsDivergent = calculateDivergence(N); 9056 if (N->SDNodeBits.IsDivergent != IsDivergent) { 9057 N->SDNodeBits.IsDivergent = IsDivergent; 9058 llvm::append_range(Worklist, N->uses()); 9059 } 9060 } while (!Worklist.empty()); 9061 } 9062 9063 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 9064 DenseMap<SDNode *, unsigned> Degree; 9065 Order.reserve(AllNodes.size()); 9066 for (auto &N : allnodes()) { 9067 unsigned NOps = N.getNumOperands(); 9068 Degree[&N] = NOps; 9069 if (0 == NOps) 9070 Order.push_back(&N); 9071 } 9072 for (size_t I = 0; I != Order.size(); ++I) { 9073 SDNode *N = Order[I]; 9074 for (auto U : N->uses()) { 9075 unsigned &UnsortedOps = Degree[U]; 9076 if (0 == --UnsortedOps) 9077 Order.push_back(U); 9078 } 9079 } 9080 } 9081 9082 #ifndef NDEBUG 9083 void SelectionDAG::VerifyDAGDiverence() { 9084 std::vector<SDNode *> TopoOrder; 9085 CreateTopologicalOrder(TopoOrder); 9086 for (auto *N : TopoOrder) { 9087 assert(calculateDivergence(N) == N->isDivergent() && 9088 "Divergence bit inconsistency detected"); 9089 } 9090 } 9091 #endif 9092 9093 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 9094 /// uses of other values produced by From.getNode() alone. The same value 9095 /// may appear in both the From and To list. The Deleted vector is 9096 /// handled the same way as for ReplaceAllUsesWith. 9097 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 9098 const SDValue *To, 9099 unsigned Num){ 9100 // Handle the simple, trivial case efficiently. 9101 if (Num == 1) 9102 return ReplaceAllUsesOfValueWith(*From, *To); 9103 9104 transferDbgValues(*From, *To); 9105 9106 // Read up all the uses and make records of them. This helps 9107 // processing new uses that are introduced during the 9108 // replacement process. 9109 SmallVector<UseMemo, 4> Uses; 9110 for (unsigned i = 0; i != Num; ++i) { 9111 unsigned FromResNo = From[i].getResNo(); 9112 SDNode *FromNode = From[i].getNode(); 9113 for (SDNode::use_iterator UI = FromNode->use_begin(), 9114 E = FromNode->use_end(); UI != E; ++UI) { 9115 SDUse &Use = UI.getUse(); 9116 if (Use.getResNo() == FromResNo) { 9117 UseMemo Memo = { *UI, i, &Use }; 9118 Uses.push_back(Memo); 9119 } 9120 } 9121 } 9122 9123 // Sort the uses, so that all the uses from a given User are together. 9124 llvm::sort(Uses); 9125 9126 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 9127 UseIndex != UseIndexEnd; ) { 9128 // We know that this user uses some value of From. If it is the right 9129 // value, update it. 9130 SDNode *User = Uses[UseIndex].User; 9131 9132 // This node is about to morph, remove its old self from the CSE maps. 9133 RemoveNodeFromCSEMaps(User); 9134 9135 // The Uses array is sorted, so all the uses for a given User 9136 // are next to each other in the list. 9137 // To help reduce the number of CSE recomputations, process all 9138 // the uses of this user that we can find this way. 9139 do { 9140 unsigned i = Uses[UseIndex].Index; 9141 SDUse &Use = *Uses[UseIndex].Use; 9142 ++UseIndex; 9143 9144 Use.set(To[i]); 9145 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 9146 9147 // Now that we have modified User, add it back to the CSE maps. If it 9148 // already exists there, recursively merge the results together. 9149 AddModifiedNodeToCSEMaps(User); 9150 } 9151 } 9152 9153 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 9154 /// based on their topological order. It returns the maximum id and a vector 9155 /// of the SDNodes* in assigned order by reference. 9156 unsigned SelectionDAG::AssignTopologicalOrder() { 9157 unsigned DAGSize = 0; 9158 9159 // SortedPos tracks the progress of the algorithm. Nodes before it are 9160 // sorted, nodes after it are unsorted. When the algorithm completes 9161 // it is at the end of the list. 9162 allnodes_iterator SortedPos = allnodes_begin(); 9163 9164 // Visit all the nodes. Move nodes with no operands to the front of 9165 // the list immediately. Annotate nodes that do have operands with their 9166 // operand count. Before we do this, the Node Id fields of the nodes 9167 // may contain arbitrary values. After, the Node Id fields for nodes 9168 // before SortedPos will contain the topological sort index, and the 9169 // Node Id fields for nodes At SortedPos and after will contain the 9170 // count of outstanding operands. 9171 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 9172 SDNode *N = &*I++; 9173 checkForCycles(N, this); 9174 unsigned Degree = N->getNumOperands(); 9175 if (Degree == 0) { 9176 // A node with no uses, add it to the result array immediately. 9177 N->setNodeId(DAGSize++); 9178 allnodes_iterator Q(N); 9179 if (Q != SortedPos) 9180 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 9181 assert(SortedPos != AllNodes.end() && "Overran node list"); 9182 ++SortedPos; 9183 } else { 9184 // Temporarily use the Node Id as scratch space for the degree count. 9185 N->setNodeId(Degree); 9186 } 9187 } 9188 9189 // Visit all the nodes. As we iterate, move nodes into sorted order, 9190 // such that by the time the end is reached all nodes will be sorted. 9191 for (SDNode &Node : allnodes()) { 9192 SDNode *N = &Node; 9193 checkForCycles(N, this); 9194 // N is in sorted position, so all its uses have one less operand 9195 // that needs to be sorted. 9196 for (SDNode *P : N->uses()) { 9197 unsigned Degree = P->getNodeId(); 9198 assert(Degree != 0 && "Invalid node degree"); 9199 --Degree; 9200 if (Degree == 0) { 9201 // All of P's operands are sorted, so P may sorted now. 9202 P->setNodeId(DAGSize++); 9203 if (P->getIterator() != SortedPos) 9204 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9205 assert(SortedPos != AllNodes.end() && "Overran node list"); 9206 ++SortedPos; 9207 } else { 9208 // Update P's outstanding operand count. 9209 P->setNodeId(Degree); 9210 } 9211 } 9212 if (Node.getIterator() == SortedPos) { 9213 #ifndef NDEBUG 9214 allnodes_iterator I(N); 9215 SDNode *S = &*++I; 9216 dbgs() << "Overran sorted position:\n"; 9217 S->dumprFull(this); dbgs() << "\n"; 9218 dbgs() << "Checking if this is due to cycles\n"; 9219 checkForCycles(this, true); 9220 #endif 9221 llvm_unreachable(nullptr); 9222 } 9223 } 9224 9225 assert(SortedPos == AllNodes.end() && 9226 "Topological sort incomplete!"); 9227 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9228 "First node in topological sort is not the entry token!"); 9229 assert(AllNodes.front().getNodeId() == 0 && 9230 "First node in topological sort has non-zero id!"); 9231 assert(AllNodes.front().getNumOperands() == 0 && 9232 "First node in topological sort has operands!"); 9233 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9234 "Last node in topologic sort has unexpected id!"); 9235 assert(AllNodes.back().use_empty() && 9236 "Last node in topologic sort has users!"); 9237 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9238 return DAGSize; 9239 } 9240 9241 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9242 /// value is produced by SD. 9243 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 9244 for (SDNode *SD : DB->getSDNodes()) { 9245 if (!SD) 9246 continue; 9247 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9248 SD->setHasDebugValue(true); 9249 } 9250 DbgInfo->add(DB, isParameter); 9251 } 9252 9253 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 9254 9255 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9256 SDValue NewMemOpChain) { 9257 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9258 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9259 // The new memory operation must have the same position as the old load in 9260 // terms of memory dependency. Create a TokenFactor for the old load and new 9261 // memory operation and update uses of the old load's output chain to use that 9262 // TokenFactor. 9263 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9264 return NewMemOpChain; 9265 9266 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9267 OldChain, NewMemOpChain); 9268 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9269 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9270 return TokenFactor; 9271 } 9272 9273 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9274 SDValue NewMemOp) { 9275 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9276 SDValue OldChain = SDValue(OldLoad, 1); 9277 SDValue NewMemOpChain = NewMemOp.getValue(1); 9278 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9279 } 9280 9281 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9282 Function **OutFunction) { 9283 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9284 9285 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9286 auto *Module = MF->getFunction().getParent(); 9287 auto *Function = Module->getFunction(Symbol); 9288 9289 if (OutFunction != nullptr) 9290 *OutFunction = Function; 9291 9292 if (Function != nullptr) { 9293 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9294 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9295 } 9296 9297 std::string ErrorStr; 9298 raw_string_ostream ErrorFormatter(ErrorStr); 9299 9300 ErrorFormatter << "Undefined external symbol "; 9301 ErrorFormatter << '"' << Symbol << '"'; 9302 ErrorFormatter.flush(); 9303 9304 report_fatal_error(ErrorStr); 9305 } 9306 9307 //===----------------------------------------------------------------------===// 9308 // SDNode Class 9309 //===----------------------------------------------------------------------===// 9310 9311 bool llvm::isNullConstant(SDValue V) { 9312 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9313 return Const != nullptr && Const->isNullValue(); 9314 } 9315 9316 bool llvm::isNullFPConstant(SDValue V) { 9317 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9318 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9319 } 9320 9321 bool llvm::isAllOnesConstant(SDValue V) { 9322 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9323 return Const != nullptr && Const->isAllOnesValue(); 9324 } 9325 9326 bool llvm::isOneConstant(SDValue V) { 9327 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9328 return Const != nullptr && Const->isOne(); 9329 } 9330 9331 SDValue llvm::peekThroughBitcasts(SDValue V) { 9332 while (V.getOpcode() == ISD::BITCAST) 9333 V = V.getOperand(0); 9334 return V; 9335 } 9336 9337 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9338 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9339 V = V.getOperand(0); 9340 return V; 9341 } 9342 9343 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9344 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9345 V = V.getOperand(0); 9346 return V; 9347 } 9348 9349 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9350 if (V.getOpcode() != ISD::XOR) 9351 return false; 9352 V = peekThroughBitcasts(V.getOperand(1)); 9353 unsigned NumBits = V.getScalarValueSizeInBits(); 9354 ConstantSDNode *C = 9355 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 9356 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 9357 } 9358 9359 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 9360 bool AllowTruncation) { 9361 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9362 return CN; 9363 9364 // SplatVectors can truncate their operands. Ignore that case here unless 9365 // AllowTruncation is set. 9366 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 9367 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 9368 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9369 EVT CVT = CN->getValueType(0); 9370 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 9371 if (AllowTruncation || CVT == VecEltVT) 9372 return CN; 9373 } 9374 } 9375 9376 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9377 BitVector UndefElements; 9378 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 9379 9380 // BuildVectors can truncate their operands. Ignore that case here unless 9381 // AllowTruncation is set. 9382 if (CN && (UndefElements.none() || AllowUndefs)) { 9383 EVT CVT = CN->getValueType(0); 9384 EVT NSVT = N.getValueType().getScalarType(); 9385 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9386 if (AllowTruncation || (CVT == NSVT)) 9387 return CN; 9388 } 9389 } 9390 9391 return nullptr; 9392 } 9393 9394 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 9395 bool AllowUndefs, 9396 bool AllowTruncation) { 9397 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9398 return CN; 9399 9400 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9401 BitVector UndefElements; 9402 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 9403 9404 // BuildVectors can truncate their operands. Ignore that case here unless 9405 // AllowTruncation is set. 9406 if (CN && (UndefElements.none() || AllowUndefs)) { 9407 EVT CVT = CN->getValueType(0); 9408 EVT NSVT = N.getValueType().getScalarType(); 9409 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9410 if (AllowTruncation || (CVT == NSVT)) 9411 return CN; 9412 } 9413 } 9414 9415 return nullptr; 9416 } 9417 9418 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 9419 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9420 return CN; 9421 9422 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9423 BitVector UndefElements; 9424 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 9425 if (CN && (UndefElements.none() || AllowUndefs)) 9426 return CN; 9427 } 9428 9429 if (N.getOpcode() == ISD::SPLAT_VECTOR) 9430 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 9431 return CN; 9432 9433 return nullptr; 9434 } 9435 9436 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 9437 const APInt &DemandedElts, 9438 bool AllowUndefs) { 9439 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9440 return CN; 9441 9442 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9443 BitVector UndefElements; 9444 ConstantFPSDNode *CN = 9445 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 9446 if (CN && (UndefElements.none() || AllowUndefs)) 9447 return CN; 9448 } 9449 9450 return nullptr; 9451 } 9452 9453 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 9454 // TODO: may want to use peekThroughBitcast() here. 9455 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9456 return C && C->isNullValue(); 9457 } 9458 9459 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 9460 // TODO: may want to use peekThroughBitcast() here. 9461 unsigned BitWidth = N.getScalarValueSizeInBits(); 9462 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9463 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 9464 } 9465 9466 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 9467 N = peekThroughBitcasts(N); 9468 unsigned BitWidth = N.getScalarValueSizeInBits(); 9469 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9470 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth; 9471 } 9472 9473 HandleSDNode::~HandleSDNode() { 9474 DropOperands(); 9475 } 9476 9477 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 9478 const DebugLoc &DL, 9479 const GlobalValue *GA, EVT VT, 9480 int64_t o, unsigned TF) 9481 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 9482 TheGlobal = GA; 9483 } 9484 9485 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 9486 EVT VT, unsigned SrcAS, 9487 unsigned DestAS) 9488 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 9489 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 9490 9491 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 9492 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 9493 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 9494 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 9495 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 9496 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 9497 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 9498 9499 // We check here that the size of the memory operand fits within the size of 9500 // the MMO. This is because the MMO might indicate only a possible address 9501 // range instead of specifying the affected memory addresses precisely. 9502 // TODO: Make MachineMemOperands aware of scalable vectors. 9503 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 9504 "Size mismatch!"); 9505 } 9506 9507 /// Profile - Gather unique data for the node. 9508 /// 9509 void SDNode::Profile(FoldingSetNodeID &ID) const { 9510 AddNodeIDNode(ID, this); 9511 } 9512 9513 namespace { 9514 9515 struct EVTArray { 9516 std::vector<EVT> VTs; 9517 9518 EVTArray() { 9519 VTs.reserve(MVT::LAST_VALUETYPE); 9520 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 9521 VTs.push_back(MVT((MVT::SimpleValueType)i)); 9522 } 9523 }; 9524 9525 } // end anonymous namespace 9526 9527 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 9528 static ManagedStatic<EVTArray> SimpleVTArray; 9529 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 9530 9531 /// getValueTypeList - Return a pointer to the specified value type. 9532 /// 9533 const EVT *SDNode::getValueTypeList(EVT VT) { 9534 if (VT.isExtended()) { 9535 sys::SmartScopedLock<true> Lock(*VTMutex); 9536 return &(*EVTs->insert(VT).first); 9537 } else { 9538 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 9539 "Value type out of range!"); 9540 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 9541 } 9542 } 9543 9544 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 9545 /// indicated value. This method ignores uses of other values defined by this 9546 /// operation. 9547 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 9548 assert(Value < getNumValues() && "Bad value!"); 9549 9550 // TODO: Only iterate over uses of a given value of the node 9551 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 9552 if (UI.getUse().getResNo() == Value) { 9553 if (NUses == 0) 9554 return false; 9555 --NUses; 9556 } 9557 } 9558 9559 // Found exactly the right number of uses? 9560 return NUses == 0; 9561 } 9562 9563 /// hasAnyUseOfValue - Return true if there are any use of the indicated 9564 /// value. This method ignores uses of other values defined by this operation. 9565 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 9566 assert(Value < getNumValues() && "Bad value!"); 9567 9568 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 9569 if (UI.getUse().getResNo() == Value) 9570 return true; 9571 9572 return false; 9573 } 9574 9575 /// isOnlyUserOf - Return true if this node is the only use of N. 9576 bool SDNode::isOnlyUserOf(const SDNode *N) const { 9577 bool Seen = false; 9578 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9579 SDNode *User = *I; 9580 if (User == this) 9581 Seen = true; 9582 else 9583 return false; 9584 } 9585 9586 return Seen; 9587 } 9588 9589 /// Return true if the only users of N are contained in Nodes. 9590 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 9591 bool Seen = false; 9592 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9593 SDNode *User = *I; 9594 if (llvm::is_contained(Nodes, User)) 9595 Seen = true; 9596 else 9597 return false; 9598 } 9599 9600 return Seen; 9601 } 9602 9603 /// isOperand - Return true if this node is an operand of N. 9604 bool SDValue::isOperandOf(const SDNode *N) const { 9605 return is_contained(N->op_values(), *this); 9606 } 9607 9608 bool SDNode::isOperandOf(const SDNode *N) const { 9609 return any_of(N->op_values(), 9610 [this](SDValue Op) { return this == Op.getNode(); }); 9611 } 9612 9613 /// reachesChainWithoutSideEffects - Return true if this operand (which must 9614 /// be a chain) reaches the specified operand without crossing any 9615 /// side-effecting instructions on any chain path. In practice, this looks 9616 /// through token factors and non-volatile loads. In order to remain efficient, 9617 /// this only looks a couple of nodes in, it does not do an exhaustive search. 9618 /// 9619 /// Note that we only need to examine chains when we're searching for 9620 /// side-effects; SelectionDAG requires that all side-effects are represented 9621 /// by chains, even if another operand would force a specific ordering. This 9622 /// constraint is necessary to allow transformations like splitting loads. 9623 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 9624 unsigned Depth) const { 9625 if (*this == Dest) return true; 9626 9627 // Don't search too deeply, we just want to be able to see through 9628 // TokenFactor's etc. 9629 if (Depth == 0) return false; 9630 9631 // If this is a token factor, all inputs to the TF happen in parallel. 9632 if (getOpcode() == ISD::TokenFactor) { 9633 // First, try a shallow search. 9634 if (is_contained((*this)->ops(), Dest)) { 9635 // We found the chain we want as an operand of this TokenFactor. 9636 // Essentially, we reach the chain without side-effects if we could 9637 // serialize the TokenFactor into a simple chain of operations with 9638 // Dest as the last operation. This is automatically true if the 9639 // chain has one use: there are no other ordering constraints. 9640 // If the chain has more than one use, we give up: some other 9641 // use of Dest might force a side-effect between Dest and the current 9642 // node. 9643 if (Dest.hasOneUse()) 9644 return true; 9645 } 9646 // Next, try a deep search: check whether every operand of the TokenFactor 9647 // reaches Dest. 9648 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 9649 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 9650 }); 9651 } 9652 9653 // Loads don't have side effects, look through them. 9654 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 9655 if (Ld->isUnordered()) 9656 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 9657 } 9658 return false; 9659 } 9660 9661 bool SDNode::hasPredecessor(const SDNode *N) const { 9662 SmallPtrSet<const SDNode *, 32> Visited; 9663 SmallVector<const SDNode *, 16> Worklist; 9664 Worklist.push_back(this); 9665 return hasPredecessorHelper(N, Visited, Worklist); 9666 } 9667 9668 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 9669 this->Flags.intersectWith(Flags); 9670 } 9671 9672 SDValue 9673 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 9674 ArrayRef<ISD::NodeType> CandidateBinOps, 9675 bool AllowPartials) { 9676 // The pattern must end in an extract from index 0. 9677 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9678 !isNullConstant(Extract->getOperand(1))) 9679 return SDValue(); 9680 9681 // Match against one of the candidate binary ops. 9682 SDValue Op = Extract->getOperand(0); 9683 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 9684 return Op.getOpcode() == unsigned(BinOp); 9685 })) 9686 return SDValue(); 9687 9688 // Floating-point reductions may require relaxed constraints on the final step 9689 // of the reduction because they may reorder intermediate operations. 9690 unsigned CandidateBinOp = Op.getOpcode(); 9691 if (Op.getValueType().isFloatingPoint()) { 9692 SDNodeFlags Flags = Op->getFlags(); 9693 switch (CandidateBinOp) { 9694 case ISD::FADD: 9695 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 9696 return SDValue(); 9697 break; 9698 default: 9699 llvm_unreachable("Unhandled FP opcode for binop reduction"); 9700 } 9701 } 9702 9703 // Matching failed - attempt to see if we did enough stages that a partial 9704 // reduction from a subvector is possible. 9705 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 9706 if (!AllowPartials || !Op) 9707 return SDValue(); 9708 EVT OpVT = Op.getValueType(); 9709 EVT OpSVT = OpVT.getScalarType(); 9710 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 9711 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 9712 return SDValue(); 9713 BinOp = (ISD::NodeType)CandidateBinOp; 9714 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 9715 getVectorIdxConstant(0, SDLoc(Op))); 9716 }; 9717 9718 // At each stage, we're looking for something that looks like: 9719 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 9720 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 9721 // i32 undef, i32 undef, i32 undef, i32 undef> 9722 // %a = binop <8 x i32> %op, %s 9723 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 9724 // we expect something like: 9725 // <4,5,6,7,u,u,u,u> 9726 // <2,3,u,u,u,u,u,u> 9727 // <1,u,u,u,u,u,u,u> 9728 // While a partial reduction match would be: 9729 // <2,3,u,u,u,u,u,u> 9730 // <1,u,u,u,u,u,u,u> 9731 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 9732 SDValue PrevOp; 9733 for (unsigned i = 0; i < Stages; ++i) { 9734 unsigned MaskEnd = (1 << i); 9735 9736 if (Op.getOpcode() != CandidateBinOp) 9737 return PartialReduction(PrevOp, MaskEnd); 9738 9739 SDValue Op0 = Op.getOperand(0); 9740 SDValue Op1 = Op.getOperand(1); 9741 9742 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 9743 if (Shuffle) { 9744 Op = Op1; 9745 } else { 9746 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 9747 Op = Op0; 9748 } 9749 9750 // The first operand of the shuffle should be the same as the other operand 9751 // of the binop. 9752 if (!Shuffle || Shuffle->getOperand(0) != Op) 9753 return PartialReduction(PrevOp, MaskEnd); 9754 9755 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 9756 for (int Index = 0; Index < (int)MaskEnd; ++Index) 9757 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 9758 return PartialReduction(PrevOp, MaskEnd); 9759 9760 PrevOp = Op; 9761 } 9762 9763 // Handle subvector reductions, which tend to appear after the shuffle 9764 // reduction stages. 9765 while (Op.getOpcode() == CandidateBinOp) { 9766 unsigned NumElts = Op.getValueType().getVectorNumElements(); 9767 SDValue Op0 = Op.getOperand(0); 9768 SDValue Op1 = Op.getOperand(1); 9769 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9770 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9771 Op0.getOperand(0) != Op1.getOperand(0)) 9772 break; 9773 SDValue Src = Op0.getOperand(0); 9774 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 9775 if (NumSrcElts != (2 * NumElts)) 9776 break; 9777 if (!(Op0.getConstantOperandAPInt(1) == 0 && 9778 Op1.getConstantOperandAPInt(1) == NumElts) && 9779 !(Op1.getConstantOperandAPInt(1) == 0 && 9780 Op0.getConstantOperandAPInt(1) == NumElts)) 9781 break; 9782 Op = Src; 9783 } 9784 9785 BinOp = (ISD::NodeType)CandidateBinOp; 9786 return Op; 9787 } 9788 9789 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 9790 assert(N->getNumValues() == 1 && 9791 "Can't unroll a vector with multiple results!"); 9792 9793 EVT VT = N->getValueType(0); 9794 unsigned NE = VT.getVectorNumElements(); 9795 EVT EltVT = VT.getVectorElementType(); 9796 SDLoc dl(N); 9797 9798 SmallVector<SDValue, 8> Scalars; 9799 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 9800 9801 // If ResNE is 0, fully unroll the vector op. 9802 if (ResNE == 0) 9803 ResNE = NE; 9804 else if (NE > ResNE) 9805 NE = ResNE; 9806 9807 unsigned i; 9808 for (i= 0; i != NE; ++i) { 9809 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 9810 SDValue Operand = N->getOperand(j); 9811 EVT OperandVT = Operand.getValueType(); 9812 if (OperandVT.isVector()) { 9813 // A vector operand; extract a single element. 9814 EVT OperandEltVT = OperandVT.getVectorElementType(); 9815 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 9816 Operand, getVectorIdxConstant(i, dl)); 9817 } else { 9818 // A scalar operand; just use it as is. 9819 Operands[j] = Operand; 9820 } 9821 } 9822 9823 switch (N->getOpcode()) { 9824 default: { 9825 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 9826 N->getFlags())); 9827 break; 9828 } 9829 case ISD::VSELECT: 9830 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 9831 break; 9832 case ISD::SHL: 9833 case ISD::SRA: 9834 case ISD::SRL: 9835 case ISD::ROTL: 9836 case ISD::ROTR: 9837 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 9838 getShiftAmountOperand(Operands[0].getValueType(), 9839 Operands[1]))); 9840 break; 9841 case ISD::SIGN_EXTEND_INREG: { 9842 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 9843 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 9844 Operands[0], 9845 getValueType(ExtVT))); 9846 } 9847 } 9848 } 9849 9850 for (; i < ResNE; ++i) 9851 Scalars.push_back(getUNDEF(EltVT)); 9852 9853 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 9854 return getBuildVector(VecVT, dl, Scalars); 9855 } 9856 9857 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 9858 SDNode *N, unsigned ResNE) { 9859 unsigned Opcode = N->getOpcode(); 9860 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 9861 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 9862 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 9863 "Expected an overflow opcode"); 9864 9865 EVT ResVT = N->getValueType(0); 9866 EVT OvVT = N->getValueType(1); 9867 EVT ResEltVT = ResVT.getVectorElementType(); 9868 EVT OvEltVT = OvVT.getVectorElementType(); 9869 SDLoc dl(N); 9870 9871 // If ResNE is 0, fully unroll the vector op. 9872 unsigned NE = ResVT.getVectorNumElements(); 9873 if (ResNE == 0) 9874 ResNE = NE; 9875 else if (NE > ResNE) 9876 NE = ResNE; 9877 9878 SmallVector<SDValue, 8> LHSScalars; 9879 SmallVector<SDValue, 8> RHSScalars; 9880 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 9881 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 9882 9883 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 9884 SDVTList VTs = getVTList(ResEltVT, SVT); 9885 SmallVector<SDValue, 8> ResScalars; 9886 SmallVector<SDValue, 8> OvScalars; 9887 for (unsigned i = 0; i < NE; ++i) { 9888 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 9889 SDValue Ov = 9890 getSelect(dl, OvEltVT, Res.getValue(1), 9891 getBoolConstant(true, dl, OvEltVT, ResVT), 9892 getConstant(0, dl, OvEltVT)); 9893 9894 ResScalars.push_back(Res); 9895 OvScalars.push_back(Ov); 9896 } 9897 9898 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 9899 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 9900 9901 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 9902 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 9903 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 9904 getBuildVector(NewOvVT, dl, OvScalars)); 9905 } 9906 9907 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 9908 LoadSDNode *Base, 9909 unsigned Bytes, 9910 int Dist) const { 9911 if (LD->isVolatile() || Base->isVolatile()) 9912 return false; 9913 // TODO: probably too restrictive for atomics, revisit 9914 if (!LD->isSimple()) 9915 return false; 9916 if (LD->isIndexed() || Base->isIndexed()) 9917 return false; 9918 if (LD->getChain() != Base->getChain()) 9919 return false; 9920 EVT VT = LD->getValueType(0); 9921 if (VT.getSizeInBits() / 8 != Bytes) 9922 return false; 9923 9924 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 9925 auto LocDecomp = BaseIndexOffset::match(LD, *this); 9926 9927 int64_t Offset = 0; 9928 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 9929 return (Dist * Bytes == Offset); 9930 return false; 9931 } 9932 9933 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 9934 /// if it cannot be inferred. 9935 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 9936 // If this is a GlobalAddress + cst, return the alignment. 9937 const GlobalValue *GV = nullptr; 9938 int64_t GVOffset = 0; 9939 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 9940 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 9941 KnownBits Known(PtrWidth); 9942 llvm::computeKnownBits(GV, Known, getDataLayout()); 9943 unsigned AlignBits = Known.countMinTrailingZeros(); 9944 if (AlignBits) 9945 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 9946 } 9947 9948 // If this is a direct reference to a stack slot, use information about the 9949 // stack slot's alignment. 9950 int FrameIdx = INT_MIN; 9951 int64_t FrameOffset = 0; 9952 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 9953 FrameIdx = FI->getIndex(); 9954 } else if (isBaseWithConstantOffset(Ptr) && 9955 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 9956 // Handle FI+Cst 9957 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 9958 FrameOffset = Ptr.getConstantOperandVal(1); 9959 } 9960 9961 if (FrameIdx != INT_MIN) { 9962 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 9963 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 9964 } 9965 9966 return None; 9967 } 9968 9969 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 9970 /// which is split (or expanded) into two not necessarily identical pieces. 9971 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 9972 // Currently all types are split in half. 9973 EVT LoVT, HiVT; 9974 if (!VT.isVector()) 9975 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 9976 else 9977 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 9978 9979 return std::make_pair(LoVT, HiVT); 9980 } 9981 9982 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 9983 /// type, dependent on an enveloping VT that has been split into two identical 9984 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 9985 std::pair<EVT, EVT> 9986 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 9987 bool *HiIsEmpty) const { 9988 EVT EltTp = VT.getVectorElementType(); 9989 // Examples: 9990 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 9991 // custom VL=9 with enveloping VL=8/8 yields 8/1 9992 // custom VL=10 with enveloping VL=8/8 yields 8/2 9993 // etc. 9994 ElementCount VTNumElts = VT.getVectorElementCount(); 9995 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 9996 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 9997 "Mixing fixed width and scalable vectors when enveloping a type"); 9998 EVT LoVT, HiVT; 9999 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 10000 LoVT = EnvVT; 10001 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 10002 *HiIsEmpty = false; 10003 } else { 10004 // Flag that hi type has zero storage size, but return split envelop type 10005 // (this would be easier if vector types with zero elements were allowed). 10006 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 10007 HiVT = EnvVT; 10008 *HiIsEmpty = true; 10009 } 10010 return std::make_pair(LoVT, HiVT); 10011 } 10012 10013 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 10014 /// low/high part. 10015 std::pair<SDValue, SDValue> 10016 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 10017 const EVT &HiVT) { 10018 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 10019 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 10020 "Splitting vector with an invalid mixture of fixed and scalable " 10021 "vector types"); 10022 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 10023 N.getValueType().getVectorMinNumElements() && 10024 "More vector elements requested than available!"); 10025 SDValue Lo, Hi; 10026 Lo = 10027 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 10028 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 10029 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 10030 // IDX with the runtime scaling factor of the result vector type. For 10031 // fixed-width result vectors, that runtime scaling factor is 1. 10032 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 10033 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 10034 return std::make_pair(Lo, Hi); 10035 } 10036 10037 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 10038 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 10039 EVT VT = N.getValueType(); 10040 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 10041 NextPowerOf2(VT.getVectorNumElements())); 10042 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 10043 getVectorIdxConstant(0, DL)); 10044 } 10045 10046 void SelectionDAG::ExtractVectorElements(SDValue Op, 10047 SmallVectorImpl<SDValue> &Args, 10048 unsigned Start, unsigned Count, 10049 EVT EltVT) { 10050 EVT VT = Op.getValueType(); 10051 if (Count == 0) 10052 Count = VT.getVectorNumElements(); 10053 if (EltVT == EVT()) 10054 EltVT = VT.getVectorElementType(); 10055 SDLoc SL(Op); 10056 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 10057 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 10058 getVectorIdxConstant(i, SL))); 10059 } 10060 } 10061 10062 // getAddressSpace - Return the address space this GlobalAddress belongs to. 10063 unsigned GlobalAddressSDNode::getAddressSpace() const { 10064 return getGlobal()->getType()->getAddressSpace(); 10065 } 10066 10067 Type *ConstantPoolSDNode::getType() const { 10068 if (isMachineConstantPoolEntry()) 10069 return Val.MachineCPVal->getType(); 10070 return Val.ConstVal->getType(); 10071 } 10072 10073 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 10074 unsigned &SplatBitSize, 10075 bool &HasAnyUndefs, 10076 unsigned MinSplatBits, 10077 bool IsBigEndian) const { 10078 EVT VT = getValueType(0); 10079 assert(VT.isVector() && "Expected a vector type"); 10080 unsigned VecWidth = VT.getSizeInBits(); 10081 if (MinSplatBits > VecWidth) 10082 return false; 10083 10084 // FIXME: The widths are based on this node's type, but build vectors can 10085 // truncate their operands. 10086 SplatValue = APInt(VecWidth, 0); 10087 SplatUndef = APInt(VecWidth, 0); 10088 10089 // Get the bits. Bits with undefined values (when the corresponding element 10090 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 10091 // in SplatValue. If any of the values are not constant, give up and return 10092 // false. 10093 unsigned int NumOps = getNumOperands(); 10094 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 10095 unsigned EltWidth = VT.getScalarSizeInBits(); 10096 10097 for (unsigned j = 0; j < NumOps; ++j) { 10098 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 10099 SDValue OpVal = getOperand(i); 10100 unsigned BitPos = j * EltWidth; 10101 10102 if (OpVal.isUndef()) 10103 SplatUndef.setBits(BitPos, BitPos + EltWidth); 10104 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 10105 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 10106 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 10107 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 10108 else 10109 return false; 10110 } 10111 10112 // The build_vector is all constants or undefs. Find the smallest element 10113 // size that splats the vector. 10114 HasAnyUndefs = (SplatUndef != 0); 10115 10116 // FIXME: This does not work for vectors with elements less than 8 bits. 10117 while (VecWidth > 8) { 10118 unsigned HalfSize = VecWidth / 2; 10119 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 10120 APInt LowValue = SplatValue.trunc(HalfSize); 10121 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 10122 APInt LowUndef = SplatUndef.trunc(HalfSize); 10123 10124 // If the two halves do not match (ignoring undef bits), stop here. 10125 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 10126 MinSplatBits > HalfSize) 10127 break; 10128 10129 SplatValue = HighValue | LowValue; 10130 SplatUndef = HighUndef & LowUndef; 10131 10132 VecWidth = HalfSize; 10133 } 10134 10135 SplatBitSize = VecWidth; 10136 return true; 10137 } 10138 10139 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 10140 BitVector *UndefElements) const { 10141 unsigned NumOps = getNumOperands(); 10142 if (UndefElements) { 10143 UndefElements->clear(); 10144 UndefElements->resize(NumOps); 10145 } 10146 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10147 if (!DemandedElts) 10148 return SDValue(); 10149 SDValue Splatted; 10150 for (unsigned i = 0; i != NumOps; ++i) { 10151 if (!DemandedElts[i]) 10152 continue; 10153 SDValue Op = getOperand(i); 10154 if (Op.isUndef()) { 10155 if (UndefElements) 10156 (*UndefElements)[i] = true; 10157 } else if (!Splatted) { 10158 Splatted = Op; 10159 } else if (Splatted != Op) { 10160 return SDValue(); 10161 } 10162 } 10163 10164 if (!Splatted) { 10165 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 10166 assert(getOperand(FirstDemandedIdx).isUndef() && 10167 "Can only have a splat without a constant for all undefs."); 10168 return getOperand(FirstDemandedIdx); 10169 } 10170 10171 return Splatted; 10172 } 10173 10174 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 10175 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 10176 return getSplatValue(DemandedElts, UndefElements); 10177 } 10178 10179 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 10180 SmallVectorImpl<SDValue> &Sequence, 10181 BitVector *UndefElements) const { 10182 unsigned NumOps = getNumOperands(); 10183 Sequence.clear(); 10184 if (UndefElements) { 10185 UndefElements->clear(); 10186 UndefElements->resize(NumOps); 10187 } 10188 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10189 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10190 return false; 10191 10192 // Set the undefs even if we don't find a sequence (like getSplatValue). 10193 if (UndefElements) 10194 for (unsigned I = 0; I != NumOps; ++I) 10195 if (DemandedElts[I] && getOperand(I).isUndef()) 10196 (*UndefElements)[I] = true; 10197 10198 // Iteratively widen the sequence length looking for repetitions. 10199 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10200 Sequence.append(SeqLen, SDValue()); 10201 for (unsigned I = 0; I != NumOps; ++I) { 10202 if (!DemandedElts[I]) 10203 continue; 10204 SDValue &SeqOp = Sequence[I % SeqLen]; 10205 SDValue Op = getOperand(I); 10206 if (Op.isUndef()) { 10207 if (!SeqOp) 10208 SeqOp = Op; 10209 continue; 10210 } 10211 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10212 Sequence.clear(); 10213 break; 10214 } 10215 SeqOp = Op; 10216 } 10217 if (!Sequence.empty()) 10218 return true; 10219 } 10220 10221 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10222 return false; 10223 } 10224 10225 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10226 BitVector *UndefElements) const { 10227 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 10228 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10229 } 10230 10231 ConstantSDNode * 10232 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10233 BitVector *UndefElements) const { 10234 return dyn_cast_or_null<ConstantSDNode>( 10235 getSplatValue(DemandedElts, UndefElements)); 10236 } 10237 10238 ConstantSDNode * 10239 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10240 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10241 } 10242 10243 ConstantFPSDNode * 10244 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10245 BitVector *UndefElements) const { 10246 return dyn_cast_or_null<ConstantFPSDNode>( 10247 getSplatValue(DemandedElts, UndefElements)); 10248 } 10249 10250 ConstantFPSDNode * 10251 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10252 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10253 } 10254 10255 int32_t 10256 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10257 uint32_t BitWidth) const { 10258 if (ConstantFPSDNode *CN = 10259 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10260 bool IsExact; 10261 APSInt IntVal(BitWidth); 10262 const APFloat &APF = CN->getValueAPF(); 10263 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10264 APFloat::opOK || 10265 !IsExact) 10266 return -1; 10267 10268 return IntVal.exactLogBase2(); 10269 } 10270 return -1; 10271 } 10272 10273 bool BuildVectorSDNode::isConstant() const { 10274 for (const SDValue &Op : op_values()) { 10275 unsigned Opc = Op.getOpcode(); 10276 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 10277 return false; 10278 } 10279 return true; 10280 } 10281 10282 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 10283 // Find the first non-undef value in the shuffle mask. 10284 unsigned i, e; 10285 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 10286 /* search */; 10287 10288 // If all elements are undefined, this shuffle can be considered a splat 10289 // (although it should eventually get simplified away completely). 10290 if (i == e) 10291 return true; 10292 10293 // Make sure all remaining elements are either undef or the same as the first 10294 // non-undef value. 10295 for (int Idx = Mask[i]; i != e; ++i) 10296 if (Mask[i] >= 0 && Mask[i] != Idx) 10297 return false; 10298 return true; 10299 } 10300 10301 // Returns the SDNode if it is a constant integer BuildVector 10302 // or constant integer. 10303 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 10304 if (isa<ConstantSDNode>(N)) 10305 return N.getNode(); 10306 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 10307 return N.getNode(); 10308 // Treat a GlobalAddress supporting constant offset folding as a 10309 // constant integer. 10310 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 10311 if (GA->getOpcode() == ISD::GlobalAddress && 10312 TLI->isOffsetFoldingLegal(GA)) 10313 return GA; 10314 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 10315 isa<ConstantSDNode>(N.getOperand(0))) 10316 return N.getNode(); 10317 return nullptr; 10318 } 10319 10320 // Returns the SDNode if it is a constant float BuildVector 10321 // or constant float. 10322 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 10323 if (isa<ConstantFPSDNode>(N)) 10324 return N.getNode(); 10325 10326 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 10327 return N.getNode(); 10328 10329 return nullptr; 10330 } 10331 10332 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 10333 assert(!Node->OperandList && "Node already has operands"); 10334 assert(SDNode::getMaxNumOperands() >= Vals.size() && 10335 "too many operands to fit into SDNode"); 10336 SDUse *Ops = OperandRecycler.allocate( 10337 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 10338 10339 bool IsDivergent = false; 10340 for (unsigned I = 0; I != Vals.size(); ++I) { 10341 Ops[I].setUser(Node); 10342 Ops[I].setInitial(Vals[I]); 10343 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 10344 IsDivergent |= Ops[I].getNode()->isDivergent(); 10345 } 10346 Node->NumOperands = Vals.size(); 10347 Node->OperandList = Ops; 10348 if (!TLI->isSDNodeAlwaysUniform(Node)) { 10349 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 10350 Node->SDNodeBits.IsDivergent = IsDivergent; 10351 } 10352 checkForCycles(Node); 10353 } 10354 10355 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 10356 SmallVectorImpl<SDValue> &Vals) { 10357 size_t Limit = SDNode::getMaxNumOperands(); 10358 while (Vals.size() > Limit) { 10359 unsigned SliceIdx = Vals.size() - Limit; 10360 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 10361 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 10362 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 10363 Vals.emplace_back(NewTF); 10364 } 10365 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 10366 } 10367 10368 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 10369 EVT VT, SDNodeFlags Flags) { 10370 switch (Opcode) { 10371 default: 10372 return SDValue(); 10373 case ISD::ADD: 10374 case ISD::OR: 10375 case ISD::XOR: 10376 case ISD::UMAX: 10377 return getConstant(0, DL, VT); 10378 case ISD::MUL: 10379 return getConstant(1, DL, VT); 10380 case ISD::AND: 10381 case ISD::UMIN: 10382 return getAllOnesConstant(DL, VT); 10383 case ISD::SMAX: 10384 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 10385 case ISD::SMIN: 10386 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 10387 case ISD::FADD: 10388 return getConstantFP(-0.0, DL, VT); 10389 case ISD::FMUL: 10390 return getConstantFP(1.0, DL, VT); 10391 case ISD::FMINNUM: 10392 case ISD::FMAXNUM: { 10393 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 10394 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 10395 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 10396 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 10397 APFloat::getLargest(Semantics); 10398 if (Opcode == ISD::FMAXNUM) 10399 NeutralAF.changeSign(); 10400 10401 return getConstantFP(NeutralAF, DL, VT); 10402 } 10403 } 10404 } 10405 10406 #ifndef NDEBUG 10407 static void checkForCyclesHelper(const SDNode *N, 10408 SmallPtrSetImpl<const SDNode*> &Visited, 10409 SmallPtrSetImpl<const SDNode*> &Checked, 10410 const llvm::SelectionDAG *DAG) { 10411 // If this node has already been checked, don't check it again. 10412 if (Checked.count(N)) 10413 return; 10414 10415 // If a node has already been visited on this depth-first walk, reject it as 10416 // a cycle. 10417 if (!Visited.insert(N).second) { 10418 errs() << "Detected cycle in SelectionDAG\n"; 10419 dbgs() << "Offending node:\n"; 10420 N->dumprFull(DAG); dbgs() << "\n"; 10421 abort(); 10422 } 10423 10424 for (const SDValue &Op : N->op_values()) 10425 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 10426 10427 Checked.insert(N); 10428 Visited.erase(N); 10429 } 10430 #endif 10431 10432 void llvm::checkForCycles(const llvm::SDNode *N, 10433 const llvm::SelectionDAG *DAG, 10434 bool force) { 10435 #ifndef NDEBUG 10436 bool check = force; 10437 #ifdef EXPENSIVE_CHECKS 10438 check = true; 10439 #endif // EXPENSIVE_CHECKS 10440 if (check) { 10441 assert(N && "Checking nonexistent SDNode"); 10442 SmallPtrSet<const SDNode*, 32> visited; 10443 SmallPtrSet<const SDNode*, 32> checked; 10444 checkForCyclesHelper(N, visited, checked, DAG); 10445 } 10446 #endif // !NDEBUG 10447 } 10448 10449 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 10450 checkForCycles(DAG->getRoot().getNode(), DAG, force); 10451 } 10452