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 // Build a big vector out of the scalar elements we generated. 5154 return getBuildVector(VT, SDLoc(), Outputs); 5155 } 5156 5157 // TODO: Merge with FoldConstantArithmetic 5158 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode, 5159 const SDLoc &DL, EVT VT, 5160 ArrayRef<SDValue> Ops, 5161 const SDNodeFlags Flags) { 5162 // If the opcode is a target-specific ISD node, there's nothing we can 5163 // do here and the operand rules may not line up with the below, so 5164 // bail early. 5165 if (Opcode >= ISD::BUILTIN_OP_END) 5166 return SDValue(); 5167 5168 if (isUndef(Opcode, Ops)) 5169 return getUNDEF(VT); 5170 5171 // We can only fold vectors - maybe merge with FoldConstantArithmetic someday? 5172 if (!VT.isVector()) 5173 return SDValue(); 5174 5175 // TODO: All the folds below are performed lane-by-lane and assume a fixed 5176 // vector width, however we should be able to do constant folds involving 5177 // splat vector nodes too. 5178 if (VT.isScalableVector()) 5179 return SDValue(); 5180 5181 // From this point onwards all vectors are assumed to be fixed width. 5182 unsigned NumElts = VT.getVectorNumElements(); 5183 5184 auto IsScalarOrSameVectorSize = [&](const SDValue &Op) { 5185 return !Op.getValueType().isVector() || 5186 Op.getValueType().getVectorNumElements() == NumElts; 5187 }; 5188 5189 auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) { 5190 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op); 5191 return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) || 5192 (BV && BV->isConstant()); 5193 }; 5194 5195 // All operands must be vector types with the same number of elements as 5196 // the result type and must be either UNDEF or a build vector of constant 5197 // or UNDEF scalars. 5198 if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) || 5199 !llvm::all_of(Ops, IsScalarOrSameVectorSize)) 5200 return SDValue(); 5201 5202 // If we are comparing vectors, then the result needs to be a i1 boolean 5203 // that is then sign-extended back to the legal result type. 5204 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType()); 5205 5206 // Find legal integer scalar type for constant promotion and 5207 // ensure that its scalar size is at least as large as source. 5208 EVT LegalSVT = VT.getScalarType(); 5209 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) { 5210 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT); 5211 if (LegalSVT.bitsLT(VT.getScalarType())) 5212 return SDValue(); 5213 } 5214 5215 // Constant fold each scalar lane separately. 5216 SmallVector<SDValue, 4> ScalarResults; 5217 for (unsigned i = 0; i != NumElts; i++) { 5218 SmallVector<SDValue, 4> ScalarOps; 5219 for (SDValue Op : Ops) { 5220 EVT InSVT = Op.getValueType().getScalarType(); 5221 BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op); 5222 if (!InBV) { 5223 // We've checked that this is UNDEF or a constant of some kind. 5224 if (Op.isUndef()) 5225 ScalarOps.push_back(getUNDEF(InSVT)); 5226 else 5227 ScalarOps.push_back(Op); 5228 continue; 5229 } 5230 5231 SDValue ScalarOp = InBV->getOperand(i); 5232 EVT ScalarVT = ScalarOp.getValueType(); 5233 5234 // Build vector (integer) scalar operands may need implicit 5235 // truncation - do this before constant folding. 5236 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) 5237 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp); 5238 5239 ScalarOps.push_back(ScalarOp); 5240 } 5241 5242 // Constant fold the scalar operands. 5243 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags); 5244 5245 // Legalize the (integer) scalar constant if necessary. 5246 if (LegalSVT != SVT) 5247 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult); 5248 5249 // Scalar folding only succeeded if the result is a constant or UNDEF. 5250 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant && 5251 ScalarResult.getOpcode() != ISD::ConstantFP) 5252 return SDValue(); 5253 ScalarResults.push_back(ScalarResult); 5254 } 5255 5256 SDValue V = getBuildVector(VT, DL, ScalarResults); 5257 NewSDValueDbgMsg(V, "New node fold constant vector: ", this); 5258 return V; 5259 } 5260 5261 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL, 5262 EVT VT, SDValue N1, SDValue N2) { 5263 // TODO: We don't do any constant folding for strict FP opcodes here, but we 5264 // should. That will require dealing with a potentially non-default 5265 // rounding mode, checking the "opStatus" return value from the APFloat 5266 // math calculations, and possibly other variations. 5267 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode()); 5268 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode()); 5269 if (N1CFP && N2CFP) { 5270 APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF(); 5271 switch (Opcode) { 5272 case ISD::FADD: 5273 C1.add(C2, APFloat::rmNearestTiesToEven); 5274 return getConstantFP(C1, DL, VT); 5275 case ISD::FSUB: 5276 C1.subtract(C2, APFloat::rmNearestTiesToEven); 5277 return getConstantFP(C1, DL, VT); 5278 case ISD::FMUL: 5279 C1.multiply(C2, APFloat::rmNearestTiesToEven); 5280 return getConstantFP(C1, DL, VT); 5281 case ISD::FDIV: 5282 C1.divide(C2, APFloat::rmNearestTiesToEven); 5283 return getConstantFP(C1, DL, VT); 5284 case ISD::FREM: 5285 C1.mod(C2); 5286 return getConstantFP(C1, DL, VT); 5287 case ISD::FCOPYSIGN: 5288 C1.copySign(C2); 5289 return getConstantFP(C1, DL, VT); 5290 default: break; 5291 } 5292 } 5293 if (N1CFP && Opcode == ISD::FP_ROUND) { 5294 APFloat C1 = N1CFP->getValueAPF(); // make copy 5295 bool Unused; 5296 // This can return overflow, underflow, or inexact; we don't care. 5297 // FIXME need to be more flexible about rounding mode. 5298 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven, 5299 &Unused); 5300 return getConstantFP(C1, DL, VT); 5301 } 5302 5303 switch (Opcode) { 5304 case ISD::FSUB: 5305 // -0.0 - undef --> undef (consistent with "fneg undef") 5306 if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef()) 5307 return getUNDEF(VT); 5308 LLVM_FALLTHROUGH; 5309 5310 case ISD::FADD: 5311 case ISD::FMUL: 5312 case ISD::FDIV: 5313 case ISD::FREM: 5314 // If both operands are undef, the result is undef. If 1 operand is undef, 5315 // the result is NaN. This should match the behavior of the IR optimizer. 5316 if (N1.isUndef() && N2.isUndef()) 5317 return getUNDEF(VT); 5318 if (N1.isUndef() || N2.isUndef()) 5319 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT); 5320 } 5321 return SDValue(); 5322 } 5323 5324 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) { 5325 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!"); 5326 5327 // There's no need to assert on a byte-aligned pointer. All pointers are at 5328 // least byte aligned. 5329 if (A == Align(1)) 5330 return Val; 5331 5332 FoldingSetNodeID ID; 5333 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val}); 5334 ID.AddInteger(A.value()); 5335 5336 void *IP = nullptr; 5337 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 5338 return SDValue(E, 0); 5339 5340 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), 5341 Val.getValueType(), A); 5342 createOperands(N, {Val}); 5343 5344 CSEMap.InsertNode(N, IP); 5345 InsertNode(N); 5346 5347 SDValue V(N, 0); 5348 NewSDValueDbgMsg(V, "Creating new node: ", this); 5349 return V; 5350 } 5351 5352 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5353 SDValue N1, SDValue N2) { 5354 SDNodeFlags Flags; 5355 if (Inserter) 5356 Flags = Inserter->getFlags(); 5357 return getNode(Opcode, DL, VT, N1, N2, Flags); 5358 } 5359 5360 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5361 SDValue N1, SDValue N2, const SDNodeFlags Flags) { 5362 assert(N1.getOpcode() != ISD::DELETED_NODE && 5363 N2.getOpcode() != ISD::DELETED_NODE && 5364 "Operand is DELETED_NODE!"); 5365 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5366 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2); 5367 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5368 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5369 5370 // Canonicalize constant to RHS if commutative. 5371 if (TLI->isCommutativeBinOp(Opcode)) { 5372 if (N1C && !N2C) { 5373 std::swap(N1C, N2C); 5374 std::swap(N1, N2); 5375 } else if (N1CFP && !N2CFP) { 5376 std::swap(N1CFP, N2CFP); 5377 std::swap(N1, N2); 5378 } 5379 } 5380 5381 switch (Opcode) { 5382 default: break; 5383 case ISD::TokenFactor: 5384 assert(VT == MVT::Other && N1.getValueType() == MVT::Other && 5385 N2.getValueType() == MVT::Other && "Invalid token factor!"); 5386 // Fold trivial token factors. 5387 if (N1.getOpcode() == ISD::EntryToken) return N2; 5388 if (N2.getOpcode() == ISD::EntryToken) return N1; 5389 if (N1 == N2) return N1; 5390 break; 5391 case ISD::BUILD_VECTOR: { 5392 // Attempt to simplify BUILD_VECTOR. 5393 SDValue Ops[] = {N1, N2}; 5394 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5395 return V; 5396 break; 5397 } 5398 case ISD::CONCAT_VECTORS: { 5399 SDValue Ops[] = {N1, N2}; 5400 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5401 return V; 5402 break; 5403 } 5404 case ISD::AND: 5405 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5406 assert(N1.getValueType() == N2.getValueType() && 5407 N1.getValueType() == VT && "Binary operator types must match!"); 5408 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's 5409 // worth handling here. 5410 if (N2C && N2C->isNullValue()) 5411 return N2; 5412 if (N2C && N2C->isAllOnesValue()) // X & -1 -> X 5413 return N1; 5414 break; 5415 case ISD::OR: 5416 case ISD::XOR: 5417 case ISD::ADD: 5418 case ISD::SUB: 5419 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5420 assert(N1.getValueType() == N2.getValueType() && 5421 N1.getValueType() == VT && "Binary operator types must match!"); 5422 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so 5423 // it's worth handling here. 5424 if (N2C && N2C->isNullValue()) 5425 return N1; 5426 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() && 5427 VT.getVectorElementType() == MVT::i1) 5428 return getNode(ISD::XOR, DL, VT, N1, N2); 5429 break; 5430 case ISD::MUL: 5431 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5432 assert(N1.getValueType() == N2.getValueType() && 5433 N1.getValueType() == VT && "Binary operator types must match!"); 5434 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5435 return getNode(ISD::AND, DL, VT, N1, N2); 5436 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5437 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5438 const APInt &N2CImm = N2C->getAPIntValue(); 5439 return getVScale(DL, VT, MulImm * N2CImm); 5440 } 5441 break; 5442 case ISD::UDIV: 5443 case ISD::UREM: 5444 case ISD::MULHU: 5445 case ISD::MULHS: 5446 case ISD::SDIV: 5447 case ISD::SREM: 5448 case ISD::SADDSAT: 5449 case ISD::SSUBSAT: 5450 case ISD::UADDSAT: 5451 case ISD::USUBSAT: 5452 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5453 assert(N1.getValueType() == N2.getValueType() && 5454 N1.getValueType() == VT && "Binary operator types must match!"); 5455 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) { 5456 // fold (add_sat x, y) -> (or x, y) for bool types. 5457 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT) 5458 return getNode(ISD::OR, DL, VT, N1, N2); 5459 // fold (sub_sat x, y) -> (and x, ~y) for bool types. 5460 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT) 5461 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT)); 5462 } 5463 break; 5464 case ISD::SMIN: 5465 case ISD::UMAX: 5466 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5467 assert(N1.getValueType() == N2.getValueType() && 5468 N1.getValueType() == VT && "Binary operator types must match!"); 5469 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5470 return getNode(ISD::OR, DL, VT, N1, N2); 5471 break; 5472 case ISD::SMAX: 5473 case ISD::UMIN: 5474 assert(VT.isInteger() && "This operator does not apply to FP types!"); 5475 assert(N1.getValueType() == N2.getValueType() && 5476 N1.getValueType() == VT && "Binary operator types must match!"); 5477 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) 5478 return getNode(ISD::AND, DL, VT, N1, N2); 5479 break; 5480 case ISD::FADD: 5481 case ISD::FSUB: 5482 case ISD::FMUL: 5483 case ISD::FDIV: 5484 case ISD::FREM: 5485 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5486 assert(N1.getValueType() == N2.getValueType() && 5487 N1.getValueType() == VT && "Binary operator types must match!"); 5488 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags)) 5489 return V; 5490 break; 5491 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match. 5492 assert(N1.getValueType() == VT && 5493 N1.getValueType().isFloatingPoint() && 5494 N2.getValueType().isFloatingPoint() && 5495 "Invalid FCOPYSIGN!"); 5496 break; 5497 case ISD::SHL: 5498 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) { 5499 const APInt &MulImm = N1->getConstantOperandAPInt(0); 5500 const APInt &ShiftImm = N2C->getAPIntValue(); 5501 return getVScale(DL, VT, MulImm << ShiftImm); 5502 } 5503 LLVM_FALLTHROUGH; 5504 case ISD::SRA: 5505 case ISD::SRL: 5506 if (SDValue V = simplifyShift(N1, N2)) 5507 return V; 5508 LLVM_FALLTHROUGH; 5509 case ISD::ROTL: 5510 case ISD::ROTR: 5511 assert(VT == N1.getValueType() && 5512 "Shift operators return type must be the same as their first arg"); 5513 assert(VT.isInteger() && N2.getValueType().isInteger() && 5514 "Shifts only work on integers"); 5515 assert((!VT.isVector() || VT == N2.getValueType()) && 5516 "Vector shift amounts must be in the same as their first arg"); 5517 // Verify that the shift amount VT is big enough to hold valid shift 5518 // amounts. This catches things like trying to shift an i1024 value by an 5519 // i8, which is easy to fall into in generic code that uses 5520 // TLI.getShiftAmount(). 5521 assert(N2.getValueType().getScalarSizeInBits() >= 5522 Log2_32_Ceil(VT.getScalarSizeInBits()) && 5523 "Invalid use of small shift amount with oversized value!"); 5524 5525 // Always fold shifts of i1 values so the code generator doesn't need to 5526 // handle them. Since we know the size of the shift has to be less than the 5527 // size of the value, the shift/rotate count is guaranteed to be zero. 5528 if (VT == MVT::i1) 5529 return N1; 5530 if (N2C && N2C->isNullValue()) 5531 return N1; 5532 break; 5533 case ISD::FP_ROUND: 5534 assert(VT.isFloatingPoint() && 5535 N1.getValueType().isFloatingPoint() && 5536 VT.bitsLE(N1.getValueType()) && 5537 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) && 5538 "Invalid FP_ROUND!"); 5539 if (N1.getValueType() == VT) return N1; // noop conversion. 5540 break; 5541 case ISD::AssertSext: 5542 case ISD::AssertZext: { 5543 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5544 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5545 assert(VT.isInteger() && EVT.isInteger() && 5546 "Cannot *_EXTEND_INREG FP types"); 5547 assert(!EVT.isVector() && 5548 "AssertSExt/AssertZExt type should be the vector element type " 5549 "rather than the vector type!"); 5550 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!"); 5551 if (VT.getScalarType() == EVT) return N1; // noop assertion. 5552 break; 5553 } 5554 case ISD::SIGN_EXTEND_INREG: { 5555 EVT EVT = cast<VTSDNode>(N2)->getVT(); 5556 assert(VT == N1.getValueType() && "Not an inreg extend!"); 5557 assert(VT.isInteger() && EVT.isInteger() && 5558 "Cannot *_EXTEND_INREG FP types"); 5559 assert(EVT.isVector() == VT.isVector() && 5560 "SIGN_EXTEND_INREG type should be vector iff the operand " 5561 "type is vector!"); 5562 assert((!EVT.isVector() || 5563 EVT.getVectorElementCount() == VT.getVectorElementCount()) && 5564 "Vector element counts must match in SIGN_EXTEND_INREG"); 5565 assert(EVT.bitsLE(VT) && "Not extending!"); 5566 if (EVT == VT) return N1; // Not actually extending 5567 5568 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) { 5569 unsigned FromBits = EVT.getScalarSizeInBits(); 5570 Val <<= Val.getBitWidth() - FromBits; 5571 Val.ashrInPlace(Val.getBitWidth() - FromBits); 5572 return getConstant(Val, DL, ConstantVT); 5573 }; 5574 5575 if (N1C) { 5576 const APInt &Val = N1C->getAPIntValue(); 5577 return SignExtendInReg(Val, VT); 5578 } 5579 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) { 5580 SmallVector<SDValue, 8> Ops; 5581 llvm::EVT OpVT = N1.getOperand(0).getValueType(); 5582 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) { 5583 SDValue Op = N1.getOperand(i); 5584 if (Op.isUndef()) { 5585 Ops.push_back(getUNDEF(OpVT)); 5586 continue; 5587 } 5588 ConstantSDNode *C = cast<ConstantSDNode>(Op); 5589 APInt Val = C->getAPIntValue(); 5590 Ops.push_back(SignExtendInReg(Val, OpVT)); 5591 } 5592 return getBuildVector(VT, DL, Ops); 5593 } 5594 break; 5595 } 5596 case ISD::EXTRACT_VECTOR_ELT: 5597 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() && 5598 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \ 5599 element type of the vector."); 5600 5601 // Extract from an undefined value or using an undefined index is undefined. 5602 if (N1.isUndef() || N2.isUndef()) 5603 return getUNDEF(VT); 5604 5605 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length 5606 // vectors. For scalable vectors we will provide appropriate support for 5607 // dealing with arbitrary indices. 5608 if (N2C && N1.getValueType().isFixedLengthVector() && 5609 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements())) 5610 return getUNDEF(VT); 5611 5612 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is 5613 // expanding copies of large vectors from registers. This only works for 5614 // fixed length vectors, since we need to know the exact number of 5615 // elements. 5616 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() && 5617 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) { 5618 unsigned Factor = 5619 N1.getOperand(0).getValueType().getVectorNumElements(); 5620 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, 5621 N1.getOperand(N2C->getZExtValue() / Factor), 5622 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL)); 5623 } 5624 5625 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while 5626 // lowering is expanding large vector constants. 5627 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR || 5628 N1.getOpcode() == ISD::SPLAT_VECTOR)) { 5629 assert((N1.getOpcode() != ISD::BUILD_VECTOR || 5630 N1.getValueType().isFixedLengthVector()) && 5631 "BUILD_VECTOR used for scalable vectors"); 5632 unsigned Index = 5633 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0; 5634 SDValue Elt = N1.getOperand(Index); 5635 5636 if (VT != Elt.getValueType()) 5637 // If the vector element type is not legal, the BUILD_VECTOR operands 5638 // are promoted and implicitly truncated, and the result implicitly 5639 // extended. Make that explicit here. 5640 Elt = getAnyExtOrTrunc(Elt, DL, VT); 5641 5642 return Elt; 5643 } 5644 5645 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector 5646 // operations are lowered to scalars. 5647 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) { 5648 // If the indices are the same, return the inserted element else 5649 // if the indices are known different, extract the element from 5650 // the original vector. 5651 SDValue N1Op2 = N1.getOperand(2); 5652 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2); 5653 5654 if (N1Op2C && N2C) { 5655 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) { 5656 if (VT == N1.getOperand(1).getValueType()) 5657 return N1.getOperand(1); 5658 else 5659 return getSExtOrTrunc(N1.getOperand(1), DL, VT); 5660 } 5661 5662 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2); 5663 } 5664 } 5665 5666 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed 5667 // when vector types are scalarized and v1iX is legal. 5668 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx). 5669 // Here we are completely ignoring the extract element index (N2), 5670 // which is fine for fixed width vectors, since any index other than 0 5671 // is undefined anyway. However, this cannot be ignored for scalable 5672 // vectors - in theory we could support this, but we don't want to do this 5673 // without a profitability check. 5674 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5675 N1.getValueType().isFixedLengthVector() && 5676 N1.getValueType().getVectorNumElements() == 1) { 5677 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), 5678 N1.getOperand(1)); 5679 } 5680 break; 5681 case ISD::EXTRACT_ELEMENT: 5682 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!"); 5683 assert(!N1.getValueType().isVector() && !VT.isVector() && 5684 (N1.getValueType().isInteger() == VT.isInteger()) && 5685 N1.getValueType() != VT && 5686 "Wrong types for EXTRACT_ELEMENT!"); 5687 5688 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding 5689 // 64-bit integers into 32-bit parts. Instead of building the extract of 5690 // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 5691 if (N1.getOpcode() == ISD::BUILD_PAIR) 5692 return N1.getOperand(N2C->getZExtValue()); 5693 5694 // EXTRACT_ELEMENT of a constant int is also very common. 5695 if (N1C) { 5696 unsigned ElementSize = VT.getSizeInBits(); 5697 unsigned Shift = ElementSize * N2C->getZExtValue(); 5698 const APInt &Val = N1C->getAPIntValue(); 5699 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT); 5700 } 5701 break; 5702 case ISD::EXTRACT_SUBVECTOR: 5703 EVT N1VT = N1.getValueType(); 5704 assert(VT.isVector() && N1VT.isVector() && 5705 "Extract subvector VTs must be vectors!"); 5706 assert(VT.getVectorElementType() == N1VT.getVectorElementType() && 5707 "Extract subvector VTs must have the same element type!"); 5708 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) && 5709 "Cannot extract a scalable vector from a fixed length vector!"); 5710 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5711 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) && 5712 "Extract subvector must be from larger vector to smaller vector!"); 5713 assert(N2C && "Extract subvector index must be a constant"); 5714 assert((VT.isScalableVector() != N1VT.isScalableVector() || 5715 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <= 5716 N1VT.getVectorMinNumElements()) && 5717 "Extract subvector overflow!"); 5718 assert(N2C->getAPIntValue().getBitWidth() == 5719 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5720 "Constant index for EXTRACT_SUBVECTOR has an invalid size"); 5721 5722 // Trivial extraction. 5723 if (VT == N1VT) 5724 return N1; 5725 5726 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF. 5727 if (N1.isUndef()) 5728 return getUNDEF(VT); 5729 5730 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of 5731 // the concat have the same type as the extract. 5732 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 && 5733 VT == N1.getOperand(0).getValueType()) { 5734 unsigned Factor = VT.getVectorMinNumElements(); 5735 return N1.getOperand(N2C->getZExtValue() / Factor); 5736 } 5737 5738 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created 5739 // during shuffle legalization. 5740 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) && 5741 VT == N1.getOperand(1).getValueType()) 5742 return N1.getOperand(1); 5743 break; 5744 } 5745 5746 // Perform trivial constant folding. 5747 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2})) 5748 return SV; 5749 5750 if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2)) 5751 return V; 5752 5753 // Canonicalize an UNDEF to the RHS, even over a constant. 5754 if (N1.isUndef()) { 5755 if (TLI->isCommutativeBinOp(Opcode)) { 5756 std::swap(N1, N2); 5757 } else { 5758 switch (Opcode) { 5759 case ISD::SIGN_EXTEND_INREG: 5760 case ISD::SUB: 5761 return getUNDEF(VT); // fold op(undef, arg2) -> undef 5762 case ISD::UDIV: 5763 case ISD::SDIV: 5764 case ISD::UREM: 5765 case ISD::SREM: 5766 case ISD::SSUBSAT: 5767 case ISD::USUBSAT: 5768 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0 5769 } 5770 } 5771 } 5772 5773 // Fold a bunch of operators when the RHS is undef. 5774 if (N2.isUndef()) { 5775 switch (Opcode) { 5776 case ISD::XOR: 5777 if (N1.isUndef()) 5778 // Handle undef ^ undef -> 0 special case. This is a common 5779 // idiom (misuse). 5780 return getConstant(0, DL, VT); 5781 LLVM_FALLTHROUGH; 5782 case ISD::ADD: 5783 case ISD::SUB: 5784 case ISD::UDIV: 5785 case ISD::SDIV: 5786 case ISD::UREM: 5787 case ISD::SREM: 5788 return getUNDEF(VT); // fold op(arg1, undef) -> undef 5789 case ISD::MUL: 5790 case ISD::AND: 5791 case ISD::SSUBSAT: 5792 case ISD::USUBSAT: 5793 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0 5794 case ISD::OR: 5795 case ISD::SADDSAT: 5796 case ISD::UADDSAT: 5797 return getAllOnesConstant(DL, VT); 5798 } 5799 } 5800 5801 // Memoize this node if possible. 5802 SDNode *N; 5803 SDVTList VTs = getVTList(VT); 5804 SDValue Ops[] = {N1, N2}; 5805 if (VT != MVT::Glue) { 5806 FoldingSetNodeID ID; 5807 AddNodeIDNode(ID, Opcode, VTs, Ops); 5808 void *IP = nullptr; 5809 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5810 E->intersectFlagsWith(Flags); 5811 return SDValue(E, 0); 5812 } 5813 5814 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5815 N->setFlags(Flags); 5816 createOperands(N, Ops); 5817 CSEMap.InsertNode(N, IP); 5818 } else { 5819 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5820 createOperands(N, Ops); 5821 } 5822 5823 InsertNode(N); 5824 SDValue V = SDValue(N, 0); 5825 NewSDValueDbgMsg(V, "Creating new node: ", this); 5826 return V; 5827 } 5828 5829 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5830 SDValue N1, SDValue N2, SDValue N3) { 5831 SDNodeFlags Flags; 5832 if (Inserter) 5833 Flags = Inserter->getFlags(); 5834 return getNode(Opcode, DL, VT, N1, N2, N3, Flags); 5835 } 5836 5837 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5838 SDValue N1, SDValue N2, SDValue N3, 5839 const SDNodeFlags Flags) { 5840 assert(N1.getOpcode() != ISD::DELETED_NODE && 5841 N2.getOpcode() != ISD::DELETED_NODE && 5842 N3.getOpcode() != ISD::DELETED_NODE && 5843 "Operand is DELETED_NODE!"); 5844 // Perform various simplifications. 5845 switch (Opcode) { 5846 case ISD::FMA: { 5847 assert(VT.isFloatingPoint() && "This operator only applies to FP types!"); 5848 assert(N1.getValueType() == VT && N2.getValueType() == VT && 5849 N3.getValueType() == VT && "FMA types must match!"); 5850 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 5851 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2); 5852 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3); 5853 if (N1CFP && N2CFP && N3CFP) { 5854 APFloat V1 = N1CFP->getValueAPF(); 5855 const APFloat &V2 = N2CFP->getValueAPF(); 5856 const APFloat &V3 = N3CFP->getValueAPF(); 5857 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven); 5858 return getConstantFP(V1, DL, VT); 5859 } 5860 break; 5861 } 5862 case ISD::BUILD_VECTOR: { 5863 // Attempt to simplify BUILD_VECTOR. 5864 SDValue Ops[] = {N1, N2, N3}; 5865 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 5866 return V; 5867 break; 5868 } 5869 case ISD::CONCAT_VECTORS: { 5870 SDValue Ops[] = {N1, N2, N3}; 5871 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 5872 return V; 5873 break; 5874 } 5875 case ISD::SETCC: { 5876 assert(VT.isInteger() && "SETCC result type must be an integer!"); 5877 assert(N1.getValueType() == N2.getValueType() && 5878 "SETCC operands must have the same type!"); 5879 assert(VT.isVector() == N1.getValueType().isVector() && 5880 "SETCC type should be vector iff the operand type is vector!"); 5881 assert((!VT.isVector() || VT.getVectorElementCount() == 5882 N1.getValueType().getVectorElementCount()) && 5883 "SETCC vector element counts must match!"); 5884 // Use FoldSetCC to simplify SETCC's. 5885 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL)) 5886 return V; 5887 // Vector constant folding. 5888 SDValue Ops[] = {N1, N2, N3}; 5889 if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) { 5890 NewSDValueDbgMsg(V, "New node vector constant folding: ", this); 5891 return V; 5892 } 5893 break; 5894 } 5895 case ISD::SELECT: 5896 case ISD::VSELECT: 5897 if (SDValue V = simplifySelect(N1, N2, N3)) 5898 return V; 5899 break; 5900 case ISD::VECTOR_SHUFFLE: 5901 llvm_unreachable("should use getVectorShuffle constructor!"); 5902 case ISD::INSERT_VECTOR_ELT: { 5903 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3); 5904 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except 5905 // for scalable vectors where we will generate appropriate code to 5906 // deal with out-of-bounds cases correctly. 5907 if (N3C && N1.getValueType().isFixedLengthVector() && 5908 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements()) 5909 return getUNDEF(VT); 5910 5911 // Undefined index can be assumed out-of-bounds, so that's UNDEF too. 5912 if (N3.isUndef()) 5913 return getUNDEF(VT); 5914 5915 // If the inserted element is an UNDEF, just use the input vector. 5916 if (N2.isUndef()) 5917 return N1; 5918 5919 break; 5920 } 5921 case ISD::INSERT_SUBVECTOR: { 5922 // Inserting undef into undef is still undef. 5923 if (N1.isUndef() && N2.isUndef()) 5924 return getUNDEF(VT); 5925 5926 EVT N2VT = N2.getValueType(); 5927 assert(VT == N1.getValueType() && 5928 "Dest and insert subvector source types must match!"); 5929 assert(VT.isVector() && N2VT.isVector() && 5930 "Insert subvector VTs must be vectors!"); 5931 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) && 5932 "Cannot insert a scalable vector into a fixed length vector!"); 5933 assert((VT.isScalableVector() != N2VT.isScalableVector() || 5934 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) && 5935 "Insert subvector must be from smaller vector to larger vector!"); 5936 assert(isa<ConstantSDNode>(N3) && 5937 "Insert subvector index must be constant"); 5938 assert((VT.isScalableVector() != N2VT.isScalableVector() || 5939 (N2VT.getVectorMinNumElements() + 5940 cast<ConstantSDNode>(N3)->getZExtValue()) <= 5941 VT.getVectorMinNumElements()) && 5942 "Insert subvector overflow!"); 5943 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() == 5944 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() && 5945 "Constant index for INSERT_SUBVECTOR has an invalid size"); 5946 5947 // Trivial insertion. 5948 if (VT == N2VT) 5949 return N2; 5950 5951 // If this is an insert of an extracted vector into an undef vector, we 5952 // can just use the input to the extract. 5953 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR && 5954 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) 5955 return N2.getOperand(0); 5956 break; 5957 } 5958 case ISD::BITCAST: 5959 // Fold bit_convert nodes from a type to themselves. 5960 if (N1.getValueType() == VT) 5961 return N1; 5962 break; 5963 } 5964 5965 // Memoize node if it doesn't produce a flag. 5966 SDNode *N; 5967 SDVTList VTs = getVTList(VT); 5968 SDValue Ops[] = {N1, N2, N3}; 5969 if (VT != MVT::Glue) { 5970 FoldingSetNodeID ID; 5971 AddNodeIDNode(ID, Opcode, VTs, Ops); 5972 void *IP = nullptr; 5973 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 5974 E->intersectFlagsWith(Flags); 5975 return SDValue(E, 0); 5976 } 5977 5978 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5979 N->setFlags(Flags); 5980 createOperands(N, Ops); 5981 CSEMap.InsertNode(N, IP); 5982 } else { 5983 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 5984 createOperands(N, Ops); 5985 } 5986 5987 InsertNode(N); 5988 SDValue V = SDValue(N, 0); 5989 NewSDValueDbgMsg(V, "Creating new node: ", this); 5990 return V; 5991 } 5992 5993 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 5994 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 5995 SDValue Ops[] = { N1, N2, N3, N4 }; 5996 return getNode(Opcode, DL, VT, Ops); 5997 } 5998 5999 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 6000 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 6001 SDValue N5) { 6002 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 6003 return getNode(Opcode, DL, VT, Ops); 6004 } 6005 6006 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all 6007 /// the incoming stack arguments to be loaded from the stack. 6008 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) { 6009 SmallVector<SDValue, 8> ArgChains; 6010 6011 // Include the original chain at the beginning of the list. When this is 6012 // used by target LowerCall hooks, this helps legalize find the 6013 // CALLSEQ_BEGIN node. 6014 ArgChains.push_back(Chain); 6015 6016 // Add a chain value for each stack argument. 6017 for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(), 6018 UE = getEntryNode().getNode()->use_end(); U != UE; ++U) 6019 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 6020 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 6021 if (FI->getIndex() < 0) 6022 ArgChains.push_back(SDValue(L, 1)); 6023 6024 // Build a tokenfactor for all the chains. 6025 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 6026 } 6027 6028 /// getMemsetValue - Vectorized representation of the memset value 6029 /// operand. 6030 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG, 6031 const SDLoc &dl) { 6032 assert(!Value.isUndef()); 6033 6034 unsigned NumBits = VT.getScalarSizeInBits(); 6035 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) { 6036 assert(C->getAPIntValue().getBitWidth() == 8); 6037 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue()); 6038 if (VT.isInteger()) { 6039 bool IsOpaque = VT.getSizeInBits() > 64 || 6040 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue()); 6041 return DAG.getConstant(Val, dl, VT, false, IsOpaque); 6042 } 6043 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl, 6044 VT); 6045 } 6046 6047 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?"); 6048 EVT IntVT = VT.getScalarType(); 6049 if (!IntVT.isInteger()) 6050 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits()); 6051 6052 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value); 6053 if (NumBits > 8) { 6054 // Use a multiplication with 0x010101... to extend the input to the 6055 // required length. 6056 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01)); 6057 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value, 6058 DAG.getConstant(Magic, dl, IntVT)); 6059 } 6060 6061 if (VT != Value.getValueType() && !VT.isInteger()) 6062 Value = DAG.getBitcast(VT.getScalarType(), Value); 6063 if (VT != Value.getValueType()) 6064 Value = DAG.getSplatBuildVector(VT, dl, Value); 6065 6066 return Value; 6067 } 6068 6069 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only 6070 /// used when a memcpy is turned into a memset when the source is a constant 6071 /// string ptr. 6072 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, 6073 const TargetLowering &TLI, 6074 const ConstantDataArraySlice &Slice) { 6075 // Handle vector with all elements zero. 6076 if (Slice.Array == nullptr) { 6077 if (VT.isInteger()) 6078 return DAG.getConstant(0, dl, VT); 6079 else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 6080 return DAG.getConstantFP(0.0, dl, VT); 6081 else if (VT.isVector()) { 6082 unsigned NumElts = VT.getVectorNumElements(); 6083 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64; 6084 return DAG.getNode(ISD::BITCAST, dl, VT, 6085 DAG.getConstant(0, dl, 6086 EVT::getVectorVT(*DAG.getContext(), 6087 EltVT, NumElts))); 6088 } else 6089 llvm_unreachable("Expected type!"); 6090 } 6091 6092 assert(!VT.isVector() && "Can't handle vector type here!"); 6093 unsigned NumVTBits = VT.getSizeInBits(); 6094 unsigned NumVTBytes = NumVTBits / 8; 6095 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length)); 6096 6097 APInt Val(NumVTBits, 0); 6098 if (DAG.getDataLayout().isLittleEndian()) { 6099 for (unsigned i = 0; i != NumBytes; ++i) 6100 Val |= (uint64_t)(unsigned char)Slice[i] << i*8; 6101 } else { 6102 for (unsigned i = 0; i != NumBytes; ++i) 6103 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8; 6104 } 6105 6106 // If the "cost" of materializing the integer immediate is less than the cost 6107 // of a load, then it is cost effective to turn the load into the immediate. 6108 Type *Ty = VT.getTypeForEVT(*DAG.getContext()); 6109 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty)) 6110 return DAG.getConstant(Val, dl, VT); 6111 return SDValue(nullptr, 0); 6112 } 6113 6114 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset, 6115 const SDLoc &DL, 6116 const SDNodeFlags Flags) { 6117 EVT VT = Base.getValueType(); 6118 SDValue Index; 6119 6120 if (Offset.isScalable()) 6121 Index = getVScale(DL, Base.getValueType(), 6122 APInt(Base.getValueSizeInBits().getFixedSize(), 6123 Offset.getKnownMinSize())); 6124 else 6125 Index = getConstant(Offset.getFixedSize(), DL, VT); 6126 6127 return getMemBasePlusOffset(Base, Index, DL, Flags); 6128 } 6129 6130 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset, 6131 const SDLoc &DL, 6132 const SDNodeFlags Flags) { 6133 assert(Offset.getValueType().isInteger()); 6134 EVT BasePtrVT = Ptr.getValueType(); 6135 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags); 6136 } 6137 6138 /// Returns true if memcpy source is constant data. 6139 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) { 6140 uint64_t SrcDelta = 0; 6141 GlobalAddressSDNode *G = nullptr; 6142 if (Src.getOpcode() == ISD::GlobalAddress) 6143 G = cast<GlobalAddressSDNode>(Src); 6144 else if (Src.getOpcode() == ISD::ADD && 6145 Src.getOperand(0).getOpcode() == ISD::GlobalAddress && 6146 Src.getOperand(1).getOpcode() == ISD::Constant) { 6147 G = cast<GlobalAddressSDNode>(Src.getOperand(0)); 6148 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue(); 6149 } 6150 if (!G) 6151 return false; 6152 6153 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8, 6154 SrcDelta + G->getOffset()); 6155 } 6156 6157 static bool shouldLowerMemFuncForSize(const MachineFunction &MF, 6158 SelectionDAG &DAG) { 6159 // On Darwin, -Os means optimize for size without hurting performance, so 6160 // only really optimize for size when -Oz (MinSize) is used. 6161 if (MF.getTarget().getTargetTriple().isOSDarwin()) 6162 return MF.getFunction().hasMinSize(); 6163 return DAG.shouldOptForSize(); 6164 } 6165 6166 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, 6167 SmallVector<SDValue, 32> &OutChains, unsigned From, 6168 unsigned To, SmallVector<SDValue, 16> &OutLoadChains, 6169 SmallVector<SDValue, 16> &OutStoreChains) { 6170 assert(OutLoadChains.size() && "Missing loads in memcpy inlining"); 6171 assert(OutStoreChains.size() && "Missing stores in memcpy inlining"); 6172 SmallVector<SDValue, 16> GluedLoadChains; 6173 for (unsigned i = From; i < To; ++i) { 6174 OutChains.push_back(OutLoadChains[i]); 6175 GluedLoadChains.push_back(OutLoadChains[i]); 6176 } 6177 6178 // Chain for all loads. 6179 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, 6180 GluedLoadChains); 6181 6182 for (unsigned i = From; i < To; ++i) { 6183 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]); 6184 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(), 6185 ST->getBasePtr(), ST->getMemoryVT(), 6186 ST->getMemOperand()); 6187 OutChains.push_back(NewStore); 6188 } 6189 } 6190 6191 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6192 SDValue Chain, SDValue Dst, SDValue Src, 6193 uint64_t Size, Align Alignment, 6194 bool isVol, bool AlwaysInline, 6195 MachinePointerInfo DstPtrInfo, 6196 MachinePointerInfo SrcPtrInfo) { 6197 // Turn a memcpy of undef to nop. 6198 // FIXME: We need to honor volatile even is Src is undef. 6199 if (Src.isUndef()) 6200 return Chain; 6201 6202 // Expand memcpy to a series of load and store ops if the size operand falls 6203 // below a certain threshold. 6204 // TODO: In the AlwaysInline case, if the size is big then generate a loop 6205 // rather than maybe a humongous number of loads and stores. 6206 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6207 const DataLayout &DL = DAG.getDataLayout(); 6208 LLVMContext &C = *DAG.getContext(); 6209 std::vector<EVT> MemOps; 6210 bool DstAlignCanChange = false; 6211 MachineFunction &MF = DAG.getMachineFunction(); 6212 MachineFrameInfo &MFI = MF.getFrameInfo(); 6213 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6214 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6215 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6216 DstAlignCanChange = true; 6217 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6218 if (!SrcAlign || Alignment > *SrcAlign) 6219 SrcAlign = Alignment; 6220 assert(SrcAlign && "SrcAlign must be set"); 6221 ConstantDataArraySlice Slice; 6222 // If marked as volatile, perform a copy even when marked as constant. 6223 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice); 6224 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr; 6225 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize); 6226 const MemOp Op = isZeroConstant 6227 ? MemOp::Set(Size, DstAlignCanChange, Alignment, 6228 /*IsZeroMemset*/ true, isVol) 6229 : MemOp::Copy(Size, DstAlignCanChange, Alignment, 6230 *SrcAlign, isVol, CopyFromConstant); 6231 if (!TLI.findOptimalMemOpLowering( 6232 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), 6233 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes())) 6234 return SDValue(); 6235 6236 if (DstAlignCanChange) { 6237 Type *Ty = MemOps[0].getTypeForEVT(C); 6238 Align NewAlign = DL.getABITypeAlign(Ty); 6239 6240 // Don't promote to an alignment that would require dynamic stack 6241 // realignment. 6242 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 6243 if (!TRI->hasStackRealignment(MF)) 6244 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign)) 6245 NewAlign = NewAlign / 2; 6246 6247 if (NewAlign > Alignment) { 6248 // Give the stack frame object a larger alignment if needed. 6249 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6250 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6251 Alignment = NewAlign; 6252 } 6253 } 6254 6255 MachineMemOperand::Flags MMOFlags = 6256 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6257 SmallVector<SDValue, 16> OutLoadChains; 6258 SmallVector<SDValue, 16> OutStoreChains; 6259 SmallVector<SDValue, 32> OutChains; 6260 unsigned NumMemOps = MemOps.size(); 6261 uint64_t SrcOff = 0, DstOff = 0; 6262 for (unsigned i = 0; i != NumMemOps; ++i) { 6263 EVT VT = MemOps[i]; 6264 unsigned VTSize = VT.getSizeInBits() / 8; 6265 SDValue Value, Store; 6266 6267 if (VTSize > Size) { 6268 // Issuing an unaligned load / store pair that overlaps with the previous 6269 // pair. Adjust the offset accordingly. 6270 assert(i == NumMemOps-1 && i != 0); 6271 SrcOff -= VTSize - Size; 6272 DstOff -= VTSize - Size; 6273 } 6274 6275 if (CopyFromConstant && 6276 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) { 6277 // It's unlikely a store of a vector immediate can be done in a single 6278 // instruction. It would require a load from a constantpool first. 6279 // We only handle zero vectors here. 6280 // FIXME: Handle other cases where store of vector immediate is done in 6281 // a single instruction. 6282 ConstantDataArraySlice SubSlice; 6283 if (SrcOff < Slice.Length) { 6284 SubSlice = Slice; 6285 SubSlice.move(SrcOff); 6286 } else { 6287 // This is an out-of-bounds access and hence UB. Pretend we read zero. 6288 SubSlice.Array = nullptr; 6289 SubSlice.Offset = 0; 6290 SubSlice.Length = VTSize; 6291 } 6292 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice); 6293 if (Value.getNode()) { 6294 Store = DAG.getStore( 6295 Chain, dl, Value, 6296 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6297 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6298 OutChains.push_back(Store); 6299 } 6300 } 6301 6302 if (!Store.getNode()) { 6303 // The type might not be legal for the target. This should only happen 6304 // if the type is smaller than a legal type, as on PPC, so the right 6305 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify 6306 // to Load/Store if NVT==VT. 6307 // FIXME does the case above also need this? 6308 EVT NVT = TLI.getTypeToTransformTo(C, VT); 6309 assert(NVT.bitsGE(VT)); 6310 6311 bool isDereferenceable = 6312 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6313 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6314 if (isDereferenceable) 6315 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6316 6317 Value = DAG.getExtLoad( 6318 ISD::EXTLOAD, dl, NVT, Chain, 6319 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6320 SrcPtrInfo.getWithOffset(SrcOff), VT, 6321 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags); 6322 OutLoadChains.push_back(Value.getValue(1)); 6323 6324 Store = DAG.getTruncStore( 6325 Chain, dl, Value, 6326 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6327 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags); 6328 OutStoreChains.push_back(Store); 6329 } 6330 SrcOff += VTSize; 6331 DstOff += VTSize; 6332 Size -= VTSize; 6333 } 6334 6335 unsigned GluedLdStLimit = MaxLdStGlue == 0 ? 6336 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue; 6337 unsigned NumLdStInMemcpy = OutStoreChains.size(); 6338 6339 if (NumLdStInMemcpy) { 6340 // It may be that memcpy might be converted to memset if it's memcpy 6341 // of constants. In such a case, we won't have loads and stores, but 6342 // just stores. In the absence of loads, there is nothing to gang up. 6343 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) { 6344 // If target does not care, just leave as it. 6345 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) { 6346 OutChains.push_back(OutLoadChains[i]); 6347 OutChains.push_back(OutStoreChains[i]); 6348 } 6349 } else { 6350 // Ld/St less than/equal limit set by target. 6351 if (NumLdStInMemcpy <= GluedLdStLimit) { 6352 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6353 NumLdStInMemcpy, OutLoadChains, 6354 OutStoreChains); 6355 } else { 6356 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit; 6357 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit; 6358 unsigned GlueIter = 0; 6359 6360 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) { 6361 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit; 6362 unsigned IndexTo = NumLdStInMemcpy - GlueIter; 6363 6364 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo, 6365 OutLoadChains, OutStoreChains); 6366 GlueIter += GluedLdStLimit; 6367 } 6368 6369 // Residual ld/st. 6370 if (RemainingLdStInMemcpy) { 6371 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0, 6372 RemainingLdStInMemcpy, OutLoadChains, 6373 OutStoreChains); 6374 } 6375 } 6376 } 6377 } 6378 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6379 } 6380 6381 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, 6382 SDValue Chain, SDValue Dst, SDValue Src, 6383 uint64_t Size, Align Alignment, 6384 bool isVol, bool AlwaysInline, 6385 MachinePointerInfo DstPtrInfo, 6386 MachinePointerInfo SrcPtrInfo) { 6387 // Turn a memmove of undef to nop. 6388 // FIXME: We need to honor volatile even is Src is undef. 6389 if (Src.isUndef()) 6390 return Chain; 6391 6392 // Expand memmove to a series of load and store ops if the size operand falls 6393 // below a certain threshold. 6394 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6395 const DataLayout &DL = DAG.getDataLayout(); 6396 LLVMContext &C = *DAG.getContext(); 6397 std::vector<EVT> MemOps; 6398 bool DstAlignCanChange = false; 6399 MachineFunction &MF = DAG.getMachineFunction(); 6400 MachineFrameInfo &MFI = MF.getFrameInfo(); 6401 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6402 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6403 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6404 DstAlignCanChange = true; 6405 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src); 6406 if (!SrcAlign || Alignment > *SrcAlign) 6407 SrcAlign = Alignment; 6408 assert(SrcAlign && "SrcAlign must be set"); 6409 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize); 6410 if (!TLI.findOptimalMemOpLowering( 6411 MemOps, Limit, 6412 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, 6413 /*IsVolatile*/ true), 6414 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(), 6415 MF.getFunction().getAttributes())) 6416 return SDValue(); 6417 6418 if (DstAlignCanChange) { 6419 Type *Ty = MemOps[0].getTypeForEVT(C); 6420 Align NewAlign = DL.getABITypeAlign(Ty); 6421 if (NewAlign > Alignment) { 6422 // Give the stack frame object a larger alignment if needed. 6423 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6424 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6425 Alignment = NewAlign; 6426 } 6427 } 6428 6429 MachineMemOperand::Flags MMOFlags = 6430 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 6431 uint64_t SrcOff = 0, DstOff = 0; 6432 SmallVector<SDValue, 8> LoadValues; 6433 SmallVector<SDValue, 8> LoadChains; 6434 SmallVector<SDValue, 8> OutChains; 6435 unsigned NumMemOps = MemOps.size(); 6436 for (unsigned i = 0; i < NumMemOps; i++) { 6437 EVT VT = MemOps[i]; 6438 unsigned VTSize = VT.getSizeInBits() / 8; 6439 SDValue Value; 6440 6441 bool isDereferenceable = 6442 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL); 6443 MachineMemOperand::Flags SrcMMOFlags = MMOFlags; 6444 if (isDereferenceable) 6445 SrcMMOFlags |= MachineMemOperand::MODereferenceable; 6446 6447 Value = 6448 DAG.getLoad(VT, dl, Chain, 6449 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl), 6450 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags); 6451 LoadValues.push_back(Value); 6452 LoadChains.push_back(Value.getValue(1)); 6453 SrcOff += VTSize; 6454 } 6455 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); 6456 OutChains.clear(); 6457 for (unsigned i = 0; i < NumMemOps; i++) { 6458 EVT VT = MemOps[i]; 6459 unsigned VTSize = VT.getSizeInBits() / 8; 6460 SDValue Store; 6461 6462 Store = 6463 DAG.getStore(Chain, dl, LoadValues[i], 6464 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6465 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags); 6466 OutChains.push_back(Store); 6467 DstOff += VTSize; 6468 } 6469 6470 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6471 } 6472 6473 /// Lower the call to 'memset' intrinsic function into a series of store 6474 /// operations. 6475 /// 6476 /// \param DAG Selection DAG where lowered code is placed. 6477 /// \param dl Link to corresponding IR location. 6478 /// \param Chain Control flow dependency. 6479 /// \param Dst Pointer to destination memory location. 6480 /// \param Src Value of byte to write into the memory. 6481 /// \param Size Number of bytes to write. 6482 /// \param Alignment Alignment of the destination in bytes. 6483 /// \param isVol True if destination is volatile. 6484 /// \param DstPtrInfo IR information on the memory pointer. 6485 /// \returns New head in the control flow, if lowering was successful, empty 6486 /// SDValue otherwise. 6487 /// 6488 /// The function tries to replace 'llvm.memset' intrinsic with several store 6489 /// operations and value calculation code. This is usually profitable for small 6490 /// memory size. 6491 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, 6492 SDValue Chain, SDValue Dst, SDValue Src, 6493 uint64_t Size, Align Alignment, bool isVol, 6494 MachinePointerInfo DstPtrInfo) { 6495 // Turn a memset of undef to nop. 6496 // FIXME: We need to honor volatile even is Src is undef. 6497 if (Src.isUndef()) 6498 return Chain; 6499 6500 // Expand memset to a series of load/store ops if the size operand 6501 // falls below a certain threshold. 6502 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6503 std::vector<EVT> MemOps; 6504 bool DstAlignCanChange = false; 6505 MachineFunction &MF = DAG.getMachineFunction(); 6506 MachineFrameInfo &MFI = MF.getFrameInfo(); 6507 bool OptSize = shouldLowerMemFuncForSize(MF, DAG); 6508 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst); 6509 if (FI && !MFI.isFixedObjectIndex(FI->getIndex())) 6510 DstAlignCanChange = true; 6511 bool IsZeroVal = 6512 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue(); 6513 if (!TLI.findOptimalMemOpLowering( 6514 MemOps, TLI.getMaxStoresPerMemset(OptSize), 6515 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol), 6516 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes())) 6517 return SDValue(); 6518 6519 if (DstAlignCanChange) { 6520 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext()); 6521 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty); 6522 if (NewAlign > Alignment) { 6523 // Give the stack frame object a larger alignment if needed. 6524 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign) 6525 MFI.setObjectAlignment(FI->getIndex(), NewAlign); 6526 Alignment = NewAlign; 6527 } 6528 } 6529 6530 SmallVector<SDValue, 8> OutChains; 6531 uint64_t DstOff = 0; 6532 unsigned NumMemOps = MemOps.size(); 6533 6534 // Find the largest store and generate the bit pattern for it. 6535 EVT LargestVT = MemOps[0]; 6536 for (unsigned i = 1; i < NumMemOps; i++) 6537 if (MemOps[i].bitsGT(LargestVT)) 6538 LargestVT = MemOps[i]; 6539 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl); 6540 6541 for (unsigned i = 0; i < NumMemOps; i++) { 6542 EVT VT = MemOps[i]; 6543 unsigned VTSize = VT.getSizeInBits() / 8; 6544 if (VTSize > Size) { 6545 // Issuing an unaligned load / store pair that overlaps with the previous 6546 // pair. Adjust the offset accordingly. 6547 assert(i == NumMemOps-1 && i != 0); 6548 DstOff -= VTSize - Size; 6549 } 6550 6551 // If this store is smaller than the largest store see whether we can get 6552 // the smaller value for free with a truncate. 6553 SDValue Value = MemSetValue; 6554 if (VT.bitsLT(LargestVT)) { 6555 if (!LargestVT.isVector() && !VT.isVector() && 6556 TLI.isTruncateFree(LargestVT, VT)) 6557 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue); 6558 else 6559 Value = getMemsetValue(Src, VT, DAG, dl); 6560 } 6561 assert(Value.getValueType() == VT && "Value with wrong type."); 6562 SDValue Store = DAG.getStore( 6563 Chain, dl, Value, 6564 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl), 6565 DstPtrInfo.getWithOffset(DstOff), Alignment, 6566 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone); 6567 OutChains.push_back(Store); 6568 DstOff += VT.getSizeInBits() / 8; 6569 Size -= VTSize; 6570 } 6571 6572 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains); 6573 } 6574 6575 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, 6576 unsigned AS) { 6577 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all 6578 // pointer operands can be losslessly bitcasted to pointers of address space 0 6579 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) { 6580 report_fatal_error("cannot lower memory intrinsic in address space " + 6581 Twine(AS)); 6582 } 6583 } 6584 6585 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, 6586 SDValue Src, SDValue Size, Align Alignment, 6587 bool isVol, bool AlwaysInline, bool isTailCall, 6588 MachinePointerInfo DstPtrInfo, 6589 MachinePointerInfo SrcPtrInfo) { 6590 // Check to see if we should lower the memcpy to loads and stores first. 6591 // For cases within the target-specified limits, this is the best choice. 6592 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6593 if (ConstantSize) { 6594 // Memcpy with size zero? Just return the original chain. 6595 if (ConstantSize->isNullValue()) 6596 return Chain; 6597 6598 SDValue Result = getMemcpyLoadsAndStores( 6599 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6600 isVol, false, DstPtrInfo, SrcPtrInfo); 6601 if (Result.getNode()) 6602 return Result; 6603 } 6604 6605 // Then check to see if we should lower the memcpy with target-specific 6606 // code. If the target chooses to do this, this is the next best. 6607 if (TSI) { 6608 SDValue Result = TSI->EmitTargetCodeForMemcpy( 6609 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, 6610 DstPtrInfo, SrcPtrInfo); 6611 if (Result.getNode()) 6612 return Result; 6613 } 6614 6615 // If we really need inline code and the target declined to provide it, 6616 // use a (potentially long) sequence of loads and stores. 6617 if (AlwaysInline) { 6618 assert(ConstantSize && "AlwaysInline requires a constant size!"); 6619 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src, 6620 ConstantSize->getZExtValue(), Alignment, 6621 isVol, true, DstPtrInfo, SrcPtrInfo); 6622 } 6623 6624 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6625 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6626 6627 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc 6628 // memcpy is not guaranteed to be safe. libc memcpys aren't required to 6629 // respect volatile, so they may do things like read or write memory 6630 // beyond the given memory regions. But fixing this isn't easy, and most 6631 // people don't care. 6632 6633 // Emit a library call. 6634 TargetLowering::ArgListTy Args; 6635 TargetLowering::ArgListEntry Entry; 6636 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6637 Entry.Node = Dst; Args.push_back(Entry); 6638 Entry.Node = Src; Args.push_back(Entry); 6639 6640 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6641 Entry.Node = Size; Args.push_back(Entry); 6642 // FIXME: pass in SDLoc 6643 TargetLowering::CallLoweringInfo CLI(*this); 6644 CLI.setDebugLoc(dl) 6645 .setChain(Chain) 6646 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY), 6647 Dst.getValueType().getTypeForEVT(*getContext()), 6648 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY), 6649 TLI->getPointerTy(getDataLayout())), 6650 std::move(Args)) 6651 .setDiscardResult() 6652 .setTailCall(isTailCall); 6653 6654 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6655 return CallResult.second; 6656 } 6657 6658 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl, 6659 SDValue Dst, unsigned DstAlign, 6660 SDValue Src, unsigned SrcAlign, 6661 SDValue Size, Type *SizeTy, 6662 unsigned ElemSz, bool isTailCall, 6663 MachinePointerInfo DstPtrInfo, 6664 MachinePointerInfo SrcPtrInfo) { 6665 // Emit a library call. 6666 TargetLowering::ArgListTy Args; 6667 TargetLowering::ArgListEntry Entry; 6668 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6669 Entry.Node = Dst; 6670 Args.push_back(Entry); 6671 6672 Entry.Node = Src; 6673 Args.push_back(Entry); 6674 6675 Entry.Ty = SizeTy; 6676 Entry.Node = Size; 6677 Args.push_back(Entry); 6678 6679 RTLIB::Libcall LibraryCall = 6680 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6681 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6682 report_fatal_error("Unsupported element size"); 6683 6684 TargetLowering::CallLoweringInfo CLI(*this); 6685 CLI.setDebugLoc(dl) 6686 .setChain(Chain) 6687 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6688 Type::getVoidTy(*getContext()), 6689 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6690 TLI->getPointerTy(getDataLayout())), 6691 std::move(Args)) 6692 .setDiscardResult() 6693 .setTailCall(isTailCall); 6694 6695 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6696 return CallResult.second; 6697 } 6698 6699 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, 6700 SDValue Src, SDValue Size, Align Alignment, 6701 bool isVol, bool isTailCall, 6702 MachinePointerInfo DstPtrInfo, 6703 MachinePointerInfo SrcPtrInfo) { 6704 // Check to see if we should lower the memmove to loads and stores first. 6705 // For cases within the target-specified limits, this is the best choice. 6706 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6707 if (ConstantSize) { 6708 // Memmove with size zero? Just return the original chain. 6709 if (ConstantSize->isNullValue()) 6710 return Chain; 6711 6712 SDValue Result = getMemmoveLoadsAndStores( 6713 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment, 6714 isVol, false, DstPtrInfo, SrcPtrInfo); 6715 if (Result.getNode()) 6716 return Result; 6717 } 6718 6719 // Then check to see if we should lower the memmove with target-specific 6720 // code. If the target chooses to do this, this is the next best. 6721 if (TSI) { 6722 SDValue Result = 6723 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, 6724 Alignment, isVol, DstPtrInfo, SrcPtrInfo); 6725 if (Result.getNode()) 6726 return Result; 6727 } 6728 6729 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6730 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace()); 6731 6732 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may 6733 // not be safe. See memcpy above for more details. 6734 6735 // Emit a library call. 6736 TargetLowering::ArgListTy Args; 6737 TargetLowering::ArgListEntry Entry; 6738 Entry.Ty = Type::getInt8PtrTy(*getContext()); 6739 Entry.Node = Dst; Args.push_back(Entry); 6740 Entry.Node = Src; Args.push_back(Entry); 6741 6742 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6743 Entry.Node = Size; Args.push_back(Entry); 6744 // FIXME: pass in SDLoc 6745 TargetLowering::CallLoweringInfo CLI(*this); 6746 CLI.setDebugLoc(dl) 6747 .setChain(Chain) 6748 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE), 6749 Dst.getValueType().getTypeForEVT(*getContext()), 6750 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE), 6751 TLI->getPointerTy(getDataLayout())), 6752 std::move(Args)) 6753 .setDiscardResult() 6754 .setTailCall(isTailCall); 6755 6756 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6757 return CallResult.second; 6758 } 6759 6760 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl, 6761 SDValue Dst, unsigned DstAlign, 6762 SDValue Src, unsigned SrcAlign, 6763 SDValue Size, Type *SizeTy, 6764 unsigned ElemSz, bool isTailCall, 6765 MachinePointerInfo DstPtrInfo, 6766 MachinePointerInfo SrcPtrInfo) { 6767 // Emit a library call. 6768 TargetLowering::ArgListTy Args; 6769 TargetLowering::ArgListEntry Entry; 6770 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6771 Entry.Node = Dst; 6772 Args.push_back(Entry); 6773 6774 Entry.Node = Src; 6775 Args.push_back(Entry); 6776 6777 Entry.Ty = SizeTy; 6778 Entry.Node = Size; 6779 Args.push_back(Entry); 6780 6781 RTLIB::Libcall LibraryCall = 6782 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6783 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6784 report_fatal_error("Unsupported element size"); 6785 6786 TargetLowering::CallLoweringInfo CLI(*this); 6787 CLI.setDebugLoc(dl) 6788 .setChain(Chain) 6789 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6790 Type::getVoidTy(*getContext()), 6791 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6792 TLI->getPointerTy(getDataLayout())), 6793 std::move(Args)) 6794 .setDiscardResult() 6795 .setTailCall(isTailCall); 6796 6797 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6798 return CallResult.second; 6799 } 6800 6801 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, 6802 SDValue Src, SDValue Size, Align Alignment, 6803 bool isVol, bool isTailCall, 6804 MachinePointerInfo DstPtrInfo) { 6805 // Check to see if we should lower the memset to stores first. 6806 // For cases within the target-specified limits, this is the best choice. 6807 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size); 6808 if (ConstantSize) { 6809 // Memset with size zero? Just return the original chain. 6810 if (ConstantSize->isNullValue()) 6811 return Chain; 6812 6813 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src, 6814 ConstantSize->getZExtValue(), Alignment, 6815 isVol, DstPtrInfo); 6816 6817 if (Result.getNode()) 6818 return Result; 6819 } 6820 6821 // Then check to see if we should lower the memset with target-specific 6822 // code. If the target chooses to do this, this is the next best. 6823 if (TSI) { 6824 SDValue Result = TSI->EmitTargetCodeForMemset( 6825 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo); 6826 if (Result.getNode()) 6827 return Result; 6828 } 6829 6830 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace()); 6831 6832 // Emit a library call. 6833 TargetLowering::ArgListTy Args; 6834 TargetLowering::ArgListEntry Entry; 6835 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext()); 6836 Args.push_back(Entry); 6837 Entry.Node = Src; 6838 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext()); 6839 Args.push_back(Entry); 6840 Entry.Node = Size; 6841 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6842 Args.push_back(Entry); 6843 6844 // FIXME: pass in SDLoc 6845 TargetLowering::CallLoweringInfo CLI(*this); 6846 CLI.setDebugLoc(dl) 6847 .setChain(Chain) 6848 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET), 6849 Dst.getValueType().getTypeForEVT(*getContext()), 6850 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET), 6851 TLI->getPointerTy(getDataLayout())), 6852 std::move(Args)) 6853 .setDiscardResult() 6854 .setTailCall(isTailCall); 6855 6856 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI); 6857 return CallResult.second; 6858 } 6859 6860 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl, 6861 SDValue Dst, unsigned DstAlign, 6862 SDValue Value, SDValue Size, Type *SizeTy, 6863 unsigned ElemSz, bool isTailCall, 6864 MachinePointerInfo DstPtrInfo) { 6865 // Emit a library call. 6866 TargetLowering::ArgListTy Args; 6867 TargetLowering::ArgListEntry Entry; 6868 Entry.Ty = getDataLayout().getIntPtrType(*getContext()); 6869 Entry.Node = Dst; 6870 Args.push_back(Entry); 6871 6872 Entry.Ty = Type::getInt8Ty(*getContext()); 6873 Entry.Node = Value; 6874 Args.push_back(Entry); 6875 6876 Entry.Ty = SizeTy; 6877 Entry.Node = Size; 6878 Args.push_back(Entry); 6879 6880 RTLIB::Libcall LibraryCall = 6881 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz); 6882 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL) 6883 report_fatal_error("Unsupported element size"); 6884 6885 TargetLowering::CallLoweringInfo CLI(*this); 6886 CLI.setDebugLoc(dl) 6887 .setChain(Chain) 6888 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall), 6889 Type::getVoidTy(*getContext()), 6890 getExternalSymbol(TLI->getLibcallName(LibraryCall), 6891 TLI->getPointerTy(getDataLayout())), 6892 std::move(Args)) 6893 .setDiscardResult() 6894 .setTailCall(isTailCall); 6895 6896 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI); 6897 return CallResult.second; 6898 } 6899 6900 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6901 SDVTList VTList, ArrayRef<SDValue> Ops, 6902 MachineMemOperand *MMO) { 6903 FoldingSetNodeID ID; 6904 ID.AddInteger(MemVT.getRawBits()); 6905 AddNodeIDNode(ID, Opcode, VTList, Ops); 6906 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 6907 void* IP = nullptr; 6908 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 6909 cast<AtomicSDNode>(E)->refineAlignment(MMO); 6910 return SDValue(E, 0); 6911 } 6912 6913 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 6914 VTList, MemVT, MMO); 6915 createOperands(N, Ops); 6916 6917 CSEMap.InsertNode(N, IP); 6918 InsertNode(N); 6919 return SDValue(N, 0); 6920 } 6921 6922 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, 6923 EVT MemVT, SDVTList VTs, SDValue Chain, 6924 SDValue Ptr, SDValue Cmp, SDValue Swp, 6925 MachineMemOperand *MMO) { 6926 assert(Opcode == ISD::ATOMIC_CMP_SWAP || 6927 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 6928 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types"); 6929 6930 SDValue Ops[] = {Chain, Ptr, Cmp, Swp}; 6931 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6932 } 6933 6934 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6935 SDValue Chain, SDValue Ptr, SDValue Val, 6936 MachineMemOperand *MMO) { 6937 assert((Opcode == ISD::ATOMIC_LOAD_ADD || 6938 Opcode == ISD::ATOMIC_LOAD_SUB || 6939 Opcode == ISD::ATOMIC_LOAD_AND || 6940 Opcode == ISD::ATOMIC_LOAD_CLR || 6941 Opcode == ISD::ATOMIC_LOAD_OR || 6942 Opcode == ISD::ATOMIC_LOAD_XOR || 6943 Opcode == ISD::ATOMIC_LOAD_NAND || 6944 Opcode == ISD::ATOMIC_LOAD_MIN || 6945 Opcode == ISD::ATOMIC_LOAD_MAX || 6946 Opcode == ISD::ATOMIC_LOAD_UMIN || 6947 Opcode == ISD::ATOMIC_LOAD_UMAX || 6948 Opcode == ISD::ATOMIC_LOAD_FADD || 6949 Opcode == ISD::ATOMIC_LOAD_FSUB || 6950 Opcode == ISD::ATOMIC_SWAP || 6951 Opcode == ISD::ATOMIC_STORE) && 6952 "Invalid Atomic Op"); 6953 6954 EVT VT = Val.getValueType(); 6955 6956 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) : 6957 getVTList(VT, MVT::Other); 6958 SDValue Ops[] = {Chain, Ptr, Val}; 6959 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6960 } 6961 6962 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, 6963 EVT VT, SDValue Chain, SDValue Ptr, 6964 MachineMemOperand *MMO) { 6965 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op"); 6966 6967 SDVTList VTs = getVTList(VT, MVT::Other); 6968 SDValue Ops[] = {Chain, Ptr}; 6969 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO); 6970 } 6971 6972 /// getMergeValues - Create a MERGE_VALUES node from the given operands. 6973 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) { 6974 if (Ops.size() == 1) 6975 return Ops[0]; 6976 6977 SmallVector<EVT, 4> VTs; 6978 VTs.reserve(Ops.size()); 6979 for (const SDValue &Op : Ops) 6980 VTs.push_back(Op.getValueType()); 6981 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops); 6982 } 6983 6984 SDValue SelectionDAG::getMemIntrinsicNode( 6985 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops, 6986 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, 6987 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) { 6988 if (!Size && MemVT.isScalableVector()) 6989 Size = MemoryLocation::UnknownSize; 6990 else if (!Size) 6991 Size = MemVT.getStoreSize(); 6992 6993 MachineFunction &MF = getMachineFunction(); 6994 MachineMemOperand *MMO = 6995 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo); 6996 6997 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO); 6998 } 6999 7000 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, 7001 SDVTList VTList, 7002 ArrayRef<SDValue> Ops, EVT MemVT, 7003 MachineMemOperand *MMO) { 7004 assert((Opcode == ISD::INTRINSIC_VOID || 7005 Opcode == ISD::INTRINSIC_W_CHAIN || 7006 Opcode == ISD::PREFETCH || 7007 ((int)Opcode <= std::numeric_limits<int>::max() && 7008 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) && 7009 "Opcode is not a memory-accessing opcode!"); 7010 7011 // Memoize the node unless it returns a flag. 7012 MemIntrinsicSDNode *N; 7013 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7014 FoldingSetNodeID ID; 7015 AddNodeIDNode(ID, Opcode, VTList, Ops); 7016 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>( 7017 Opcode, dl.getIROrder(), VTList, MemVT, MMO)); 7018 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7019 void *IP = nullptr; 7020 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7021 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO); 7022 return SDValue(E, 0); 7023 } 7024 7025 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7026 VTList, MemVT, MMO); 7027 createOperands(N, Ops); 7028 7029 CSEMap.InsertNode(N, IP); 7030 } else { 7031 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), 7032 VTList, MemVT, MMO); 7033 createOperands(N, Ops); 7034 } 7035 InsertNode(N); 7036 SDValue V(N, 0); 7037 NewSDValueDbgMsg(V, "Creating new node: ", this); 7038 return V; 7039 } 7040 7041 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl, 7042 SDValue Chain, int FrameIndex, 7043 int64_t Size, int64_t Offset) { 7044 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END; 7045 const auto VTs = getVTList(MVT::Other); 7046 SDValue Ops[2] = { 7047 Chain, 7048 getFrameIndex(FrameIndex, 7049 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()), 7050 true)}; 7051 7052 FoldingSetNodeID ID; 7053 AddNodeIDNode(ID, Opcode, VTs, Ops); 7054 ID.AddInteger(FrameIndex); 7055 ID.AddInteger(Size); 7056 ID.AddInteger(Offset); 7057 void *IP = nullptr; 7058 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7059 return SDValue(E, 0); 7060 7061 LifetimeSDNode *N = newSDNode<LifetimeSDNode>( 7062 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset); 7063 createOperands(N, Ops); 7064 CSEMap.InsertNode(N, IP); 7065 InsertNode(N); 7066 SDValue V(N, 0); 7067 NewSDValueDbgMsg(V, "Creating new node: ", this); 7068 return V; 7069 } 7070 7071 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, 7072 uint64_t Guid, uint64_t Index, 7073 uint32_t Attr) { 7074 const unsigned Opcode = ISD::PSEUDO_PROBE; 7075 const auto VTs = getVTList(MVT::Other); 7076 SDValue Ops[] = {Chain}; 7077 FoldingSetNodeID ID; 7078 AddNodeIDNode(ID, Opcode, VTs, Ops); 7079 ID.AddInteger(Guid); 7080 ID.AddInteger(Index); 7081 void *IP = nullptr; 7082 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP)) 7083 return SDValue(E, 0); 7084 7085 auto *N = newSDNode<PseudoProbeSDNode>( 7086 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr); 7087 createOperands(N, Ops); 7088 CSEMap.InsertNode(N, IP); 7089 InsertNode(N); 7090 SDValue V(N, 0); 7091 NewSDValueDbgMsg(V, "Creating new node: ", this); 7092 return V; 7093 } 7094 7095 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7096 /// MachinePointerInfo record from it. This is particularly useful because the 7097 /// code generator has many cases where it doesn't bother passing in a 7098 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7099 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7100 SelectionDAG &DAG, SDValue Ptr, 7101 int64_t Offset = 0) { 7102 // If this is FI+Offset, we can model it. 7103 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) 7104 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 7105 FI->getIndex(), Offset); 7106 7107 // If this is (FI+Offset1)+Offset2, we can model it. 7108 if (Ptr.getOpcode() != ISD::ADD || 7109 !isa<ConstantSDNode>(Ptr.getOperand(1)) || 7110 !isa<FrameIndexSDNode>(Ptr.getOperand(0))) 7111 return Info; 7112 7113 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 7114 return MachinePointerInfo::getFixedStack( 7115 DAG.getMachineFunction(), FI, 7116 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue()); 7117 } 7118 7119 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a 7120 /// MachinePointerInfo record from it. This is particularly useful because the 7121 /// code generator has many cases where it doesn't bother passing in a 7122 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst". 7123 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, 7124 SelectionDAG &DAG, SDValue Ptr, 7125 SDValue OffsetOp) { 7126 // If the 'Offset' value isn't a constant, we can't handle this. 7127 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp)) 7128 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue()); 7129 if (OffsetOp.isUndef()) 7130 return InferPointerInfo(Info, DAG, Ptr); 7131 return Info; 7132 } 7133 7134 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7135 EVT VT, const SDLoc &dl, SDValue Chain, 7136 SDValue Ptr, SDValue Offset, 7137 MachinePointerInfo PtrInfo, EVT MemVT, 7138 Align Alignment, 7139 MachineMemOperand::Flags MMOFlags, 7140 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7141 assert(Chain.getValueType() == MVT::Other && 7142 "Invalid chain type"); 7143 7144 MMOFlags |= MachineMemOperand::MOLoad; 7145 assert((MMOFlags & MachineMemOperand::MOStore) == 0); 7146 // If we don't have a PtrInfo, infer the trivial frame index case to simplify 7147 // clients. 7148 if (PtrInfo.V.isNull()) 7149 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset); 7150 7151 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize()); 7152 MachineFunction &MF = getMachineFunction(); 7153 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, 7154 Alignment, AAInfo, Ranges); 7155 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO); 7156 } 7157 7158 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, 7159 EVT VT, const SDLoc &dl, SDValue Chain, 7160 SDValue Ptr, SDValue Offset, EVT MemVT, 7161 MachineMemOperand *MMO) { 7162 if (VT == MemVT) { 7163 ExtType = ISD::NON_EXTLOAD; 7164 } else if (ExtType == ISD::NON_EXTLOAD) { 7165 assert(VT == MemVT && "Non-extending load from different memory type!"); 7166 } else { 7167 // Extending load. 7168 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) && 7169 "Should only be an extending load, not truncating!"); 7170 assert(VT.isInteger() == MemVT.isInteger() && 7171 "Cannot convert from FP to Int or Int -> FP!"); 7172 assert(VT.isVector() == MemVT.isVector() && 7173 "Cannot use an ext load to convert to or from a vector!"); 7174 assert((!VT.isVector() || 7175 VT.getVectorElementCount() == MemVT.getVectorElementCount()) && 7176 "Cannot use an ext load to change the number of vector elements!"); 7177 } 7178 7179 bool Indexed = AM != ISD::UNINDEXED; 7180 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!"); 7181 7182 SDVTList VTs = Indexed ? 7183 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other); 7184 SDValue Ops[] = { Chain, Ptr, Offset }; 7185 FoldingSetNodeID ID; 7186 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops); 7187 ID.AddInteger(MemVT.getRawBits()); 7188 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>( 7189 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO)); 7190 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7191 void *IP = nullptr; 7192 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7193 cast<LoadSDNode>(E)->refineAlignment(MMO); 7194 return SDValue(E, 0); 7195 } 7196 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7197 ExtType, MemVT, MMO); 7198 createOperands(N, Ops); 7199 7200 CSEMap.InsertNode(N, IP); 7201 InsertNode(N); 7202 SDValue V(N, 0); 7203 NewSDValueDbgMsg(V, "Creating new node: ", this); 7204 return V; 7205 } 7206 7207 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7208 SDValue Ptr, MachinePointerInfo PtrInfo, 7209 MaybeAlign Alignment, 7210 MachineMemOperand::Flags MMOFlags, 7211 const AAMDNodes &AAInfo, const MDNode *Ranges) { 7212 SDValue Undef = getUNDEF(Ptr.getValueType()); 7213 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7214 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges); 7215 } 7216 7217 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7218 SDValue Ptr, MachineMemOperand *MMO) { 7219 SDValue Undef = getUNDEF(Ptr.getValueType()); 7220 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef, 7221 VT, MMO); 7222 } 7223 7224 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7225 EVT VT, SDValue Chain, SDValue Ptr, 7226 MachinePointerInfo PtrInfo, EVT MemVT, 7227 MaybeAlign Alignment, 7228 MachineMemOperand::Flags MMOFlags, 7229 const AAMDNodes &AAInfo) { 7230 SDValue Undef = getUNDEF(Ptr.getValueType()); 7231 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo, 7232 MemVT, Alignment, MMOFlags, AAInfo); 7233 } 7234 7235 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, 7236 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT, 7237 MachineMemOperand *MMO) { 7238 SDValue Undef = getUNDEF(Ptr.getValueType()); 7239 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, 7240 MemVT, MMO); 7241 } 7242 7243 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, 7244 SDValue Base, SDValue Offset, 7245 ISD::MemIndexedMode AM) { 7246 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad); 7247 assert(LD->getOffset().isUndef() && "Load is already a indexed load!"); 7248 // Don't propagate the invariant or dereferenceable flags. 7249 auto MMOFlags = 7250 LD->getMemOperand()->getFlags() & 7251 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 7252 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, 7253 LD->getChain(), Base, Offset, LD->getPointerInfo(), 7254 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo()); 7255 } 7256 7257 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7258 SDValue Ptr, MachinePointerInfo PtrInfo, 7259 Align Alignment, 7260 MachineMemOperand::Flags MMOFlags, 7261 const AAMDNodes &AAInfo) { 7262 assert(Chain.getValueType() == MVT::Other && "Invalid chain type"); 7263 7264 MMOFlags |= MachineMemOperand::MOStore; 7265 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7266 7267 if (PtrInfo.V.isNull()) 7268 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7269 7270 MachineFunction &MF = getMachineFunction(); 7271 uint64_t Size = 7272 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize()); 7273 MachineMemOperand *MMO = 7274 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo); 7275 return getStore(Chain, dl, Val, Ptr, MMO); 7276 } 7277 7278 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7279 SDValue Ptr, MachineMemOperand *MMO) { 7280 assert(Chain.getValueType() == MVT::Other && 7281 "Invalid chain type"); 7282 EVT VT = Val.getValueType(); 7283 SDVTList VTs = getVTList(MVT::Other); 7284 SDValue Undef = getUNDEF(Ptr.getValueType()); 7285 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7286 FoldingSetNodeID ID; 7287 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7288 ID.AddInteger(VT.getRawBits()); 7289 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7290 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO)); 7291 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7292 void *IP = nullptr; 7293 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7294 cast<StoreSDNode>(E)->refineAlignment(MMO); 7295 return SDValue(E, 0); 7296 } 7297 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7298 ISD::UNINDEXED, false, VT, MMO); 7299 createOperands(N, Ops); 7300 7301 CSEMap.InsertNode(N, IP); 7302 InsertNode(N); 7303 SDValue V(N, 0); 7304 NewSDValueDbgMsg(V, "Creating new node: ", this); 7305 return V; 7306 } 7307 7308 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7309 SDValue Ptr, MachinePointerInfo PtrInfo, 7310 EVT SVT, Align Alignment, 7311 MachineMemOperand::Flags MMOFlags, 7312 const AAMDNodes &AAInfo) { 7313 assert(Chain.getValueType() == MVT::Other && 7314 "Invalid chain type"); 7315 7316 MMOFlags |= MachineMemOperand::MOStore; 7317 assert((MMOFlags & MachineMemOperand::MOLoad) == 0); 7318 7319 if (PtrInfo.V.isNull()) 7320 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr); 7321 7322 MachineFunction &MF = getMachineFunction(); 7323 MachineMemOperand *MMO = MF.getMachineMemOperand( 7324 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()), 7325 Alignment, AAInfo); 7326 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO); 7327 } 7328 7329 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, 7330 SDValue Ptr, EVT SVT, 7331 MachineMemOperand *MMO) { 7332 EVT VT = Val.getValueType(); 7333 7334 assert(Chain.getValueType() == MVT::Other && 7335 "Invalid chain type"); 7336 if (VT == SVT) 7337 return getStore(Chain, dl, Val, Ptr, MMO); 7338 7339 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) && 7340 "Should only be a truncating store, not extending!"); 7341 assert(VT.isInteger() == SVT.isInteger() && 7342 "Can't do FP-INT conversion!"); 7343 assert(VT.isVector() == SVT.isVector() && 7344 "Cannot use trunc store to convert to or from a vector!"); 7345 assert((!VT.isVector() || 7346 VT.getVectorElementCount() == SVT.getVectorElementCount()) && 7347 "Cannot use trunc store to change the number of vector elements!"); 7348 7349 SDVTList VTs = getVTList(MVT::Other); 7350 SDValue Undef = getUNDEF(Ptr.getValueType()); 7351 SDValue Ops[] = { Chain, Val, Ptr, Undef }; 7352 FoldingSetNodeID ID; 7353 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7354 ID.AddInteger(SVT.getRawBits()); 7355 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>( 7356 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO)); 7357 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7358 void *IP = nullptr; 7359 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7360 cast<StoreSDNode>(E)->refineAlignment(MMO); 7361 return SDValue(E, 0); 7362 } 7363 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7364 ISD::UNINDEXED, true, SVT, MMO); 7365 createOperands(N, Ops); 7366 7367 CSEMap.InsertNode(N, IP); 7368 InsertNode(N); 7369 SDValue V(N, 0); 7370 NewSDValueDbgMsg(V, "Creating new node: ", this); 7371 return V; 7372 } 7373 7374 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl, 7375 SDValue Base, SDValue Offset, 7376 ISD::MemIndexedMode AM) { 7377 StoreSDNode *ST = cast<StoreSDNode>(OrigStore); 7378 assert(ST->getOffset().isUndef() && "Store is already a indexed store!"); 7379 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other); 7380 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset }; 7381 FoldingSetNodeID ID; 7382 AddNodeIDNode(ID, ISD::STORE, VTs, Ops); 7383 ID.AddInteger(ST->getMemoryVT().getRawBits()); 7384 ID.AddInteger(ST->getRawSubclassData()); 7385 ID.AddInteger(ST->getPointerInfo().getAddrSpace()); 7386 void *IP = nullptr; 7387 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) 7388 return SDValue(E, 0); 7389 7390 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7391 ST->isTruncatingStore(), ST->getMemoryVT(), 7392 ST->getMemOperand()); 7393 createOperands(N, Ops); 7394 7395 CSEMap.InsertNode(N, IP); 7396 InsertNode(N); 7397 SDValue V(N, 0); 7398 NewSDValueDbgMsg(V, "Creating new node: ", this); 7399 return V; 7400 } 7401 7402 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, 7403 SDValue Base, SDValue Offset, SDValue Mask, 7404 SDValue PassThru, EVT MemVT, 7405 MachineMemOperand *MMO, 7406 ISD::MemIndexedMode AM, 7407 ISD::LoadExtType ExtTy, bool isExpanding) { 7408 bool Indexed = AM != ISD::UNINDEXED; 7409 assert((Indexed || Offset.isUndef()) && 7410 "Unindexed masked load with an offset!"); 7411 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other) 7412 : getVTList(VT, MVT::Other); 7413 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru}; 7414 FoldingSetNodeID ID; 7415 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops); 7416 ID.AddInteger(MemVT.getRawBits()); 7417 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>( 7418 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO)); 7419 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7420 void *IP = nullptr; 7421 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7422 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO); 7423 return SDValue(E, 0); 7424 } 7425 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, 7426 AM, ExtTy, isExpanding, MemVT, MMO); 7427 createOperands(N, Ops); 7428 7429 CSEMap.InsertNode(N, IP); 7430 InsertNode(N); 7431 SDValue V(N, 0); 7432 NewSDValueDbgMsg(V, "Creating new node: ", this); 7433 return V; 7434 } 7435 7436 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, 7437 SDValue Base, SDValue Offset, 7438 ISD::MemIndexedMode AM) { 7439 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad); 7440 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!"); 7441 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base, 7442 Offset, LD->getMask(), LD->getPassThru(), 7443 LD->getMemoryVT(), LD->getMemOperand(), AM, 7444 LD->getExtensionType(), LD->isExpandingLoad()); 7445 } 7446 7447 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl, 7448 SDValue Val, SDValue Base, SDValue Offset, 7449 SDValue Mask, EVT MemVT, 7450 MachineMemOperand *MMO, 7451 ISD::MemIndexedMode AM, bool IsTruncating, 7452 bool IsCompressing) { 7453 assert(Chain.getValueType() == MVT::Other && 7454 "Invalid chain type"); 7455 bool Indexed = AM != ISD::UNINDEXED; 7456 assert((Indexed || Offset.isUndef()) && 7457 "Unindexed masked store with an offset!"); 7458 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other) 7459 : getVTList(MVT::Other); 7460 SDValue Ops[] = {Chain, Val, Base, Offset, Mask}; 7461 FoldingSetNodeID ID; 7462 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops); 7463 ID.AddInteger(MemVT.getRawBits()); 7464 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>( 7465 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO)); 7466 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7467 void *IP = nullptr; 7468 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7469 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO); 7470 return SDValue(E, 0); 7471 } 7472 auto *N = 7473 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM, 7474 IsTruncating, IsCompressing, MemVT, MMO); 7475 createOperands(N, Ops); 7476 7477 CSEMap.InsertNode(N, IP); 7478 InsertNode(N); 7479 SDValue V(N, 0); 7480 NewSDValueDbgMsg(V, "Creating new node: ", this); 7481 return V; 7482 } 7483 7484 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, 7485 SDValue Base, SDValue Offset, 7486 ISD::MemIndexedMode AM) { 7487 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore); 7488 assert(ST->getOffset().isUndef() && 7489 "Masked store is already a indexed store!"); 7490 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset, 7491 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(), 7492 AM, ST->isTruncatingStore(), ST->isCompressingStore()); 7493 } 7494 7495 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl, 7496 ArrayRef<SDValue> Ops, 7497 MachineMemOperand *MMO, 7498 ISD::MemIndexType IndexType, 7499 ISD::LoadExtType ExtTy) { 7500 assert(Ops.size() == 6 && "Incompatible number of operands"); 7501 7502 FoldingSetNodeID ID; 7503 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops); 7504 ID.AddInteger(VT.getRawBits()); 7505 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>( 7506 dl.getIROrder(), VTs, VT, MMO, IndexType, ExtTy)); 7507 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7508 void *IP = nullptr; 7509 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7510 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO); 7511 return SDValue(E, 0); 7512 } 7513 7514 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7515 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7516 VTs, VT, MMO, IndexType, ExtTy); 7517 createOperands(N, Ops); 7518 7519 assert(N->getPassThru().getValueType() == N->getValueType(0) && 7520 "Incompatible type of the PassThru value in MaskedGatherSDNode"); 7521 assert(N->getMask().getValueType().getVectorElementCount() == 7522 N->getValueType(0).getVectorElementCount() && 7523 "Vector width mismatch between mask and data"); 7524 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() == 7525 N->getValueType(0).getVectorElementCount().isScalable() && 7526 "Scalable flags of index and data do not match"); 7527 assert(ElementCount::isKnownGE( 7528 N->getIndex().getValueType().getVectorElementCount(), 7529 N->getValueType(0).getVectorElementCount()) && 7530 "Vector width mismatch between index and data"); 7531 assert(isa<ConstantSDNode>(N->getScale()) && 7532 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7533 "Scale should be a constant power of 2"); 7534 7535 CSEMap.InsertNode(N, IP); 7536 InsertNode(N); 7537 SDValue V(N, 0); 7538 NewSDValueDbgMsg(V, "Creating new node: ", this); 7539 return V; 7540 } 7541 7542 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl, 7543 ArrayRef<SDValue> Ops, 7544 MachineMemOperand *MMO, 7545 ISD::MemIndexType IndexType, 7546 bool IsTrunc) { 7547 assert(Ops.size() == 6 && "Incompatible number of operands"); 7548 7549 FoldingSetNodeID ID; 7550 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops); 7551 ID.AddInteger(VT.getRawBits()); 7552 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>( 7553 dl.getIROrder(), VTs, VT, MMO, IndexType, IsTrunc)); 7554 ID.AddInteger(MMO->getPointerInfo().getAddrSpace()); 7555 void *IP = nullptr; 7556 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) { 7557 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO); 7558 return SDValue(E, 0); 7559 } 7560 7561 IndexType = TLI->getCanonicalIndexType(IndexType, VT, Ops[4]); 7562 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), 7563 VTs, VT, MMO, IndexType, IsTrunc); 7564 createOperands(N, Ops); 7565 7566 assert(N->getMask().getValueType().getVectorElementCount() == 7567 N->getValue().getValueType().getVectorElementCount() && 7568 "Vector width mismatch between mask and data"); 7569 assert( 7570 N->getIndex().getValueType().getVectorElementCount().isScalable() == 7571 N->getValue().getValueType().getVectorElementCount().isScalable() && 7572 "Scalable flags of index and data do not match"); 7573 assert(ElementCount::isKnownGE( 7574 N->getIndex().getValueType().getVectorElementCount(), 7575 N->getValue().getValueType().getVectorElementCount()) && 7576 "Vector width mismatch between index and data"); 7577 assert(isa<ConstantSDNode>(N->getScale()) && 7578 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() && 7579 "Scale should be a constant power of 2"); 7580 7581 CSEMap.InsertNode(N, IP); 7582 InsertNode(N); 7583 SDValue V(N, 0); 7584 NewSDValueDbgMsg(V, "Creating new node: ", this); 7585 return V; 7586 } 7587 7588 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) { 7589 // select undef, T, F --> T (if T is a constant), otherwise F 7590 // select, ?, undef, F --> F 7591 // select, ?, T, undef --> T 7592 if (Cond.isUndef()) 7593 return isConstantValueOfAnyType(T) ? T : F; 7594 if (T.isUndef()) 7595 return F; 7596 if (F.isUndef()) 7597 return T; 7598 7599 // select true, T, F --> T 7600 // select false, T, F --> F 7601 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond)) 7602 return CondC->isNullValue() ? F : T; 7603 7604 // TODO: This should simplify VSELECT with constant condition using something 7605 // like this (but check boolean contents to be complete?): 7606 // if (ISD::isBuildVectorAllOnes(Cond.getNode())) 7607 // return T; 7608 // if (ISD::isBuildVectorAllZeros(Cond.getNode())) 7609 // return F; 7610 7611 // select ?, T, T --> T 7612 if (T == F) 7613 return T; 7614 7615 return SDValue(); 7616 } 7617 7618 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) { 7619 // shift undef, Y --> 0 (can always assume that the undef value is 0) 7620 if (X.isUndef()) 7621 return getConstant(0, SDLoc(X.getNode()), X.getValueType()); 7622 // shift X, undef --> undef (because it may shift by the bitwidth) 7623 if (Y.isUndef()) 7624 return getUNDEF(X.getValueType()); 7625 7626 // shift 0, Y --> 0 7627 // shift X, 0 --> X 7628 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y)) 7629 return X; 7630 7631 // shift X, C >= bitwidth(X) --> undef 7632 // All vector elements must be too big (or undef) to avoid partial undefs. 7633 auto isShiftTooBig = [X](ConstantSDNode *Val) { 7634 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits()); 7635 }; 7636 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true)) 7637 return getUNDEF(X.getValueType()); 7638 7639 return SDValue(); 7640 } 7641 7642 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, 7643 SDNodeFlags Flags) { 7644 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 7645 // (an undef operand can be chosen to be Nan/Inf), then the result of this 7646 // operation is poison. That result can be relaxed to undef. 7647 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true); 7648 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true); 7649 bool HasNan = (XC && XC->getValueAPF().isNaN()) || 7650 (YC && YC->getValueAPF().isNaN()); 7651 bool HasInf = (XC && XC->getValueAPF().isInfinity()) || 7652 (YC && YC->getValueAPF().isInfinity()); 7653 7654 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef())) 7655 return getUNDEF(X.getValueType()); 7656 7657 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef())) 7658 return getUNDEF(X.getValueType()); 7659 7660 if (!YC) 7661 return SDValue(); 7662 7663 // X + -0.0 --> X 7664 if (Opcode == ISD::FADD) 7665 if (YC->getValueAPF().isNegZero()) 7666 return X; 7667 7668 // X - +0.0 --> X 7669 if (Opcode == ISD::FSUB) 7670 if (YC->getValueAPF().isPosZero()) 7671 return X; 7672 7673 // X * 1.0 --> X 7674 // X / 1.0 --> X 7675 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV) 7676 if (YC->getValueAPF().isExactlyValue(1.0)) 7677 return X; 7678 7679 // X * 0.0 --> 0.0 7680 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros()) 7681 if (YC->getValueAPF().isZero()) 7682 return getConstantFP(0.0, SDLoc(Y), Y.getValueType()); 7683 7684 return SDValue(); 7685 } 7686 7687 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, 7688 SDValue Ptr, SDValue SV, unsigned Align) { 7689 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) }; 7690 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops); 7691 } 7692 7693 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7694 ArrayRef<SDUse> Ops) { 7695 switch (Ops.size()) { 7696 case 0: return getNode(Opcode, DL, VT); 7697 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0])); 7698 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]); 7699 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]); 7700 default: break; 7701 } 7702 7703 // Copy from an SDUse array into an SDValue array for use with 7704 // the regular getNode logic. 7705 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end()); 7706 return getNode(Opcode, DL, VT, NewOps); 7707 } 7708 7709 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7710 ArrayRef<SDValue> Ops) { 7711 SDNodeFlags Flags; 7712 if (Inserter) 7713 Flags = Inserter->getFlags(); 7714 return getNode(Opcode, DL, VT, Ops, Flags); 7715 } 7716 7717 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT, 7718 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7719 unsigned NumOps = Ops.size(); 7720 switch (NumOps) { 7721 case 0: return getNode(Opcode, DL, VT); 7722 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags); 7723 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags); 7724 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags); 7725 default: break; 7726 } 7727 7728 #ifndef NDEBUG 7729 for (auto &Op : Ops) 7730 assert(Op.getOpcode() != ISD::DELETED_NODE && 7731 "Operand is DELETED_NODE!"); 7732 #endif 7733 7734 switch (Opcode) { 7735 default: break; 7736 case ISD::BUILD_VECTOR: 7737 // Attempt to simplify BUILD_VECTOR. 7738 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this)) 7739 return V; 7740 break; 7741 case ISD::CONCAT_VECTORS: 7742 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this)) 7743 return V; 7744 break; 7745 case ISD::SELECT_CC: 7746 assert(NumOps == 5 && "SELECT_CC takes 5 operands!"); 7747 assert(Ops[0].getValueType() == Ops[1].getValueType() && 7748 "LHS and RHS of condition must have same type!"); 7749 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7750 "True and False arms of SelectCC must have same type!"); 7751 assert(Ops[2].getValueType() == VT && 7752 "select_cc node must be of same type as true and false value!"); 7753 break; 7754 case ISD::BR_CC: 7755 assert(NumOps == 5 && "BR_CC takes 5 operands!"); 7756 assert(Ops[2].getValueType() == Ops[3].getValueType() && 7757 "LHS/RHS of comparison should match types!"); 7758 break; 7759 } 7760 7761 // Memoize nodes. 7762 SDNode *N; 7763 SDVTList VTs = getVTList(VT); 7764 7765 if (VT != MVT::Glue) { 7766 FoldingSetNodeID ID; 7767 AddNodeIDNode(ID, Opcode, VTs, Ops); 7768 void *IP = nullptr; 7769 7770 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7771 return SDValue(E, 0); 7772 7773 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7774 createOperands(N, Ops); 7775 7776 CSEMap.InsertNode(N, IP); 7777 } else { 7778 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 7779 createOperands(N, Ops); 7780 } 7781 7782 N->setFlags(Flags); 7783 InsertNode(N); 7784 SDValue V(N, 0); 7785 NewSDValueDbgMsg(V, "Creating new node: ", this); 7786 return V; 7787 } 7788 7789 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7790 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) { 7791 return getNode(Opcode, DL, getVTList(ResultTys), Ops); 7792 } 7793 7794 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7795 ArrayRef<SDValue> Ops) { 7796 SDNodeFlags Flags; 7797 if (Inserter) 7798 Flags = Inserter->getFlags(); 7799 return getNode(Opcode, DL, VTList, Ops, Flags); 7800 } 7801 7802 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7803 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) { 7804 if (VTList.NumVTs == 1) 7805 return getNode(Opcode, DL, VTList.VTs[0], Ops); 7806 7807 #ifndef NDEBUG 7808 for (auto &Op : Ops) 7809 assert(Op.getOpcode() != ISD::DELETED_NODE && 7810 "Operand is DELETED_NODE!"); 7811 #endif 7812 7813 switch (Opcode) { 7814 case ISD::STRICT_FP_EXTEND: 7815 assert(VTList.NumVTs == 2 && Ops.size() == 2 && 7816 "Invalid STRICT_FP_EXTEND!"); 7817 assert(VTList.VTs[0].isFloatingPoint() && 7818 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!"); 7819 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7820 "STRICT_FP_EXTEND result type should be vector iff the operand " 7821 "type is vector!"); 7822 assert((!VTList.VTs[0].isVector() || 7823 VTList.VTs[0].getVectorNumElements() == 7824 Ops[1].getValueType().getVectorNumElements()) && 7825 "Vector element count mismatch!"); 7826 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) && 7827 "Invalid fpext node, dst <= src!"); 7828 break; 7829 case ISD::STRICT_FP_ROUND: 7830 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!"); 7831 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() && 7832 "STRICT_FP_ROUND result type should be vector iff the operand " 7833 "type is vector!"); 7834 assert((!VTList.VTs[0].isVector() || 7835 VTList.VTs[0].getVectorNumElements() == 7836 Ops[1].getValueType().getVectorNumElements()) && 7837 "Vector element count mismatch!"); 7838 assert(VTList.VTs[0].isFloatingPoint() && 7839 Ops[1].getValueType().isFloatingPoint() && 7840 VTList.VTs[0].bitsLT(Ops[1].getValueType()) && 7841 isa<ConstantSDNode>(Ops[2]) && 7842 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 || 7843 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) && 7844 "Invalid STRICT_FP_ROUND!"); 7845 break; 7846 #if 0 7847 // FIXME: figure out how to safely handle things like 7848 // int foo(int x) { return 1 << (x & 255); } 7849 // int bar() { return foo(256); } 7850 case ISD::SRA_PARTS: 7851 case ISD::SRL_PARTS: 7852 case ISD::SHL_PARTS: 7853 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG && 7854 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1) 7855 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7856 else if (N3.getOpcode() == ISD::AND) 7857 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) { 7858 // If the and is only masking out bits that cannot effect the shift, 7859 // eliminate the and. 7860 unsigned NumBits = VT.getScalarSizeInBits()*2; 7861 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1) 7862 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0)); 7863 } 7864 break; 7865 #endif 7866 } 7867 7868 // Memoize the node unless it returns a flag. 7869 SDNode *N; 7870 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) { 7871 FoldingSetNodeID ID; 7872 AddNodeIDNode(ID, Opcode, VTList, Ops); 7873 void *IP = nullptr; 7874 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) 7875 return SDValue(E, 0); 7876 7877 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7878 createOperands(N, Ops); 7879 CSEMap.InsertNode(N, IP); 7880 } else { 7881 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList); 7882 createOperands(N, Ops); 7883 } 7884 7885 N->setFlags(Flags); 7886 InsertNode(N); 7887 SDValue V(N, 0); 7888 NewSDValueDbgMsg(V, "Creating new node: ", this); 7889 return V; 7890 } 7891 7892 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, 7893 SDVTList VTList) { 7894 return getNode(Opcode, DL, VTList, None); 7895 } 7896 7897 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7898 SDValue N1) { 7899 SDValue Ops[] = { N1 }; 7900 return getNode(Opcode, DL, VTList, Ops); 7901 } 7902 7903 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7904 SDValue N1, SDValue N2) { 7905 SDValue Ops[] = { N1, N2 }; 7906 return getNode(Opcode, DL, VTList, Ops); 7907 } 7908 7909 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7910 SDValue N1, SDValue N2, SDValue N3) { 7911 SDValue Ops[] = { N1, N2, N3 }; 7912 return getNode(Opcode, DL, VTList, Ops); 7913 } 7914 7915 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7916 SDValue N1, SDValue N2, SDValue N3, SDValue N4) { 7917 SDValue Ops[] = { N1, N2, N3, N4 }; 7918 return getNode(Opcode, DL, VTList, Ops); 7919 } 7920 7921 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList, 7922 SDValue N1, SDValue N2, SDValue N3, SDValue N4, 7923 SDValue N5) { 7924 SDValue Ops[] = { N1, N2, N3, N4, N5 }; 7925 return getNode(Opcode, DL, VTList, Ops); 7926 } 7927 7928 SDVTList SelectionDAG::getVTList(EVT VT) { 7929 return makeVTList(SDNode::getValueTypeList(VT), 1); 7930 } 7931 7932 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) { 7933 FoldingSetNodeID ID; 7934 ID.AddInteger(2U); 7935 ID.AddInteger(VT1.getRawBits()); 7936 ID.AddInteger(VT2.getRawBits()); 7937 7938 void *IP = nullptr; 7939 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7940 if (!Result) { 7941 EVT *Array = Allocator.Allocate<EVT>(2); 7942 Array[0] = VT1; 7943 Array[1] = VT2; 7944 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2); 7945 VTListMap.InsertNode(Result, IP); 7946 } 7947 return Result->getSDVTList(); 7948 } 7949 7950 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) { 7951 FoldingSetNodeID ID; 7952 ID.AddInteger(3U); 7953 ID.AddInteger(VT1.getRawBits()); 7954 ID.AddInteger(VT2.getRawBits()); 7955 ID.AddInteger(VT3.getRawBits()); 7956 7957 void *IP = nullptr; 7958 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7959 if (!Result) { 7960 EVT *Array = Allocator.Allocate<EVT>(3); 7961 Array[0] = VT1; 7962 Array[1] = VT2; 7963 Array[2] = VT3; 7964 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3); 7965 VTListMap.InsertNode(Result, IP); 7966 } 7967 return Result->getSDVTList(); 7968 } 7969 7970 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) { 7971 FoldingSetNodeID ID; 7972 ID.AddInteger(4U); 7973 ID.AddInteger(VT1.getRawBits()); 7974 ID.AddInteger(VT2.getRawBits()); 7975 ID.AddInteger(VT3.getRawBits()); 7976 ID.AddInteger(VT4.getRawBits()); 7977 7978 void *IP = nullptr; 7979 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 7980 if (!Result) { 7981 EVT *Array = Allocator.Allocate<EVT>(4); 7982 Array[0] = VT1; 7983 Array[1] = VT2; 7984 Array[2] = VT3; 7985 Array[3] = VT4; 7986 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4); 7987 VTListMap.InsertNode(Result, IP); 7988 } 7989 return Result->getSDVTList(); 7990 } 7991 7992 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) { 7993 unsigned NumVTs = VTs.size(); 7994 FoldingSetNodeID ID; 7995 ID.AddInteger(NumVTs); 7996 for (unsigned index = 0; index < NumVTs; index++) { 7997 ID.AddInteger(VTs[index].getRawBits()); 7998 } 7999 8000 void *IP = nullptr; 8001 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP); 8002 if (!Result) { 8003 EVT *Array = Allocator.Allocate<EVT>(NumVTs); 8004 llvm::copy(VTs, Array); 8005 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs); 8006 VTListMap.InsertNode(Result, IP); 8007 } 8008 return Result->getSDVTList(); 8009 } 8010 8011 8012 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the 8013 /// specified operands. If the resultant node already exists in the DAG, 8014 /// this does not modify the specified node, instead it returns the node that 8015 /// already exists. If the resultant node does not exist in the DAG, the 8016 /// input node is returned. As a degenerate case, if you specify the same 8017 /// input operands as the node already has, the input node is returned. 8018 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) { 8019 assert(N->getNumOperands() == 1 && "Update with wrong number of operands"); 8020 8021 // Check to see if there is no change. 8022 if (Op == N->getOperand(0)) return N; 8023 8024 // See if the modified node already exists. 8025 void *InsertPos = nullptr; 8026 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos)) 8027 return Existing; 8028 8029 // Nope it doesn't. Remove the node from its current place in the maps. 8030 if (InsertPos) 8031 if (!RemoveNodeFromCSEMaps(N)) 8032 InsertPos = nullptr; 8033 8034 // Now we update the operands. 8035 N->OperandList[0].set(Op); 8036 8037 updateDivergence(N); 8038 // If this gets put into a CSE map, add it. 8039 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8040 return N; 8041 } 8042 8043 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) { 8044 assert(N->getNumOperands() == 2 && "Update with wrong number of operands"); 8045 8046 // Check to see if there is no change. 8047 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1)) 8048 return N; // No operands changed, just return the input node. 8049 8050 // See if the modified node already exists. 8051 void *InsertPos = nullptr; 8052 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos)) 8053 return Existing; 8054 8055 // Nope it doesn't. Remove the node from its current place in the maps. 8056 if (InsertPos) 8057 if (!RemoveNodeFromCSEMaps(N)) 8058 InsertPos = nullptr; 8059 8060 // Now we update the operands. 8061 if (N->OperandList[0] != Op1) 8062 N->OperandList[0].set(Op1); 8063 if (N->OperandList[1] != Op2) 8064 N->OperandList[1].set(Op2); 8065 8066 updateDivergence(N); 8067 // If this gets put into a CSE map, add it. 8068 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8069 return N; 8070 } 8071 8072 SDNode *SelectionDAG:: 8073 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) { 8074 SDValue Ops[] = { Op1, Op2, Op3 }; 8075 return UpdateNodeOperands(N, Ops); 8076 } 8077 8078 SDNode *SelectionDAG:: 8079 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8080 SDValue Op3, SDValue Op4) { 8081 SDValue Ops[] = { Op1, Op2, Op3, Op4 }; 8082 return UpdateNodeOperands(N, Ops); 8083 } 8084 8085 SDNode *SelectionDAG:: 8086 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, 8087 SDValue Op3, SDValue Op4, SDValue Op5) { 8088 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 }; 8089 return UpdateNodeOperands(N, Ops); 8090 } 8091 8092 SDNode *SelectionDAG:: 8093 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) { 8094 unsigned NumOps = Ops.size(); 8095 assert(N->getNumOperands() == NumOps && 8096 "Update with wrong number of operands"); 8097 8098 // If no operands changed just return the input node. 8099 if (std::equal(Ops.begin(), Ops.end(), N->op_begin())) 8100 return N; 8101 8102 // See if the modified node already exists. 8103 void *InsertPos = nullptr; 8104 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos)) 8105 return Existing; 8106 8107 // Nope it doesn't. Remove the node from its current place in the maps. 8108 if (InsertPos) 8109 if (!RemoveNodeFromCSEMaps(N)) 8110 InsertPos = nullptr; 8111 8112 // Now we update the operands. 8113 for (unsigned i = 0; i != NumOps; ++i) 8114 if (N->OperandList[i] != Ops[i]) 8115 N->OperandList[i].set(Ops[i]); 8116 8117 updateDivergence(N); 8118 // If this gets put into a CSE map, add it. 8119 if (InsertPos) CSEMap.InsertNode(N, InsertPos); 8120 return N; 8121 } 8122 8123 /// DropOperands - Release the operands and set this node to have 8124 /// zero operands. 8125 void SDNode::DropOperands() { 8126 // Unlike the code in MorphNodeTo that does this, we don't need to 8127 // watch for dead nodes here. 8128 for (op_iterator I = op_begin(), E = op_end(); I != E; ) { 8129 SDUse &Use = *I++; 8130 Use.set(SDValue()); 8131 } 8132 } 8133 8134 void SelectionDAG::setNodeMemRefs(MachineSDNode *N, 8135 ArrayRef<MachineMemOperand *> NewMemRefs) { 8136 if (NewMemRefs.empty()) { 8137 N->clearMemRefs(); 8138 return; 8139 } 8140 8141 // Check if we can avoid allocating by storing a single reference directly. 8142 if (NewMemRefs.size() == 1) { 8143 N->MemRefs = NewMemRefs[0]; 8144 N->NumMemRefs = 1; 8145 return; 8146 } 8147 8148 MachineMemOperand **MemRefsBuffer = 8149 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size()); 8150 llvm::copy(NewMemRefs, MemRefsBuffer); 8151 N->MemRefs = MemRefsBuffer; 8152 N->NumMemRefs = static_cast<int>(NewMemRefs.size()); 8153 } 8154 8155 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a 8156 /// machine opcode. 8157 /// 8158 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8159 EVT VT) { 8160 SDVTList VTs = getVTList(VT); 8161 return SelectNodeTo(N, MachineOpc, VTs, None); 8162 } 8163 8164 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8165 EVT VT, SDValue Op1) { 8166 SDVTList VTs = getVTList(VT); 8167 SDValue Ops[] = { Op1 }; 8168 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8169 } 8170 8171 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8172 EVT VT, SDValue Op1, 8173 SDValue Op2) { 8174 SDVTList VTs = getVTList(VT); 8175 SDValue Ops[] = { Op1, Op2 }; 8176 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8177 } 8178 8179 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8180 EVT VT, SDValue Op1, 8181 SDValue Op2, SDValue Op3) { 8182 SDVTList VTs = getVTList(VT); 8183 SDValue Ops[] = { Op1, Op2, Op3 }; 8184 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8185 } 8186 8187 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8188 EVT VT, ArrayRef<SDValue> Ops) { 8189 SDVTList VTs = getVTList(VT); 8190 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8191 } 8192 8193 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8194 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) { 8195 SDVTList VTs = getVTList(VT1, VT2); 8196 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8197 } 8198 8199 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8200 EVT VT1, EVT VT2) { 8201 SDVTList VTs = getVTList(VT1, VT2); 8202 return SelectNodeTo(N, MachineOpc, VTs, None); 8203 } 8204 8205 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8206 EVT VT1, EVT VT2, EVT VT3, 8207 ArrayRef<SDValue> Ops) { 8208 SDVTList VTs = getVTList(VT1, VT2, VT3); 8209 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8210 } 8211 8212 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8213 EVT VT1, EVT VT2, 8214 SDValue Op1, SDValue Op2) { 8215 SDVTList VTs = getVTList(VT1, VT2); 8216 SDValue Ops[] = { Op1, Op2 }; 8217 return SelectNodeTo(N, MachineOpc, VTs, Ops); 8218 } 8219 8220 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 8221 SDVTList VTs,ArrayRef<SDValue> Ops) { 8222 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops); 8223 // Reset the NodeID to -1. 8224 New->setNodeId(-1); 8225 if (New != N) { 8226 ReplaceAllUsesWith(N, New); 8227 RemoveDeadNode(N); 8228 } 8229 return New; 8230 } 8231 8232 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away 8233 /// the line number information on the merged node since it is not possible to 8234 /// preserve the information that operation is associated with multiple lines. 8235 /// This will make the debugger working better at -O0, were there is a higher 8236 /// probability having other instructions associated with that line. 8237 /// 8238 /// For IROrder, we keep the smaller of the two 8239 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) { 8240 DebugLoc NLoc = N->getDebugLoc(); 8241 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) { 8242 N->setDebugLoc(DebugLoc()); 8243 } 8244 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder()); 8245 N->setIROrder(Order); 8246 return N; 8247 } 8248 8249 /// MorphNodeTo - This *mutates* the specified node to have the specified 8250 /// return type, opcode, and operands. 8251 /// 8252 /// Note that MorphNodeTo returns the resultant node. If there is already a 8253 /// node of the specified opcode and operands, it returns that node instead of 8254 /// the current one. Note that the SDLoc need not be the same. 8255 /// 8256 /// Using MorphNodeTo is faster than creating a new node and swapping it in 8257 /// with ReplaceAllUsesWith both because it often avoids allocating a new 8258 /// node, and because it doesn't require CSE recalculation for any of 8259 /// the node's users. 8260 /// 8261 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG. 8262 /// As a consequence it isn't appropriate to use from within the DAG combiner or 8263 /// the legalizer which maintain worklists that would need to be updated when 8264 /// deleting things. 8265 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 8266 SDVTList VTs, ArrayRef<SDValue> Ops) { 8267 // If an identical node already exists, use it. 8268 void *IP = nullptr; 8269 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) { 8270 FoldingSetNodeID ID; 8271 AddNodeIDNode(ID, Opc, VTs, Ops); 8272 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP)) 8273 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N)); 8274 } 8275 8276 if (!RemoveNodeFromCSEMaps(N)) 8277 IP = nullptr; 8278 8279 // Start the morphing. 8280 N->NodeType = Opc; 8281 N->ValueList = VTs.VTs; 8282 N->NumValues = VTs.NumVTs; 8283 8284 // Clear the operands list, updating used nodes to remove this from their 8285 // use list. Keep track of any operands that become dead as a result. 8286 SmallPtrSet<SDNode*, 16> DeadNodeSet; 8287 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) { 8288 SDUse &Use = *I++; 8289 SDNode *Used = Use.getNode(); 8290 Use.set(SDValue()); 8291 if (Used->use_empty()) 8292 DeadNodeSet.insert(Used); 8293 } 8294 8295 // For MachineNode, initialize the memory references information. 8296 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) 8297 MN->clearMemRefs(); 8298 8299 // Swap for an appropriately sized array from the recycler. 8300 removeOperands(N); 8301 createOperands(N, Ops); 8302 8303 // Delete any nodes that are still dead after adding the uses for the 8304 // new operands. 8305 if (!DeadNodeSet.empty()) { 8306 SmallVector<SDNode *, 16> DeadNodes; 8307 for (SDNode *N : DeadNodeSet) 8308 if (N->use_empty()) 8309 DeadNodes.push_back(N); 8310 RemoveDeadNodes(DeadNodes); 8311 } 8312 8313 if (IP) 8314 CSEMap.InsertNode(N, IP); // Memoize the new node. 8315 return N; 8316 } 8317 8318 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) { 8319 unsigned OrigOpc = Node->getOpcode(); 8320 unsigned NewOpc; 8321 switch (OrigOpc) { 8322 default: 8323 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!"); 8324 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8325 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break; 8326 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \ 8327 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break; 8328 #include "llvm/IR/ConstrainedOps.def" 8329 } 8330 8331 assert(Node->getNumValues() == 2 && "Unexpected number of results!"); 8332 8333 // We're taking this node out of the chain, so we need to re-link things. 8334 SDValue InputChain = Node->getOperand(0); 8335 SDValue OutputChain = SDValue(Node, 1); 8336 ReplaceAllUsesOfValueWith(OutputChain, InputChain); 8337 8338 SmallVector<SDValue, 3> Ops; 8339 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) 8340 Ops.push_back(Node->getOperand(i)); 8341 8342 SDVTList VTs = getVTList(Node->getValueType(0)); 8343 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops); 8344 8345 // MorphNodeTo can operate in two ways: if an existing node with the 8346 // specified operands exists, it can just return it. Otherwise, it 8347 // updates the node in place to have the requested operands. 8348 if (Res == Node) { 8349 // If we updated the node in place, reset the node ID. To the isel, 8350 // this should be just like a newly allocated machine node. 8351 Res->setNodeId(-1); 8352 } else { 8353 ReplaceAllUsesWith(Node, Res); 8354 RemoveDeadNode(Node); 8355 } 8356 8357 return Res; 8358 } 8359 8360 /// getMachineNode - These are used for target selectors to create a new node 8361 /// with specified return type(s), MachineInstr opcode, and operands. 8362 /// 8363 /// Note that getMachineNode returns the resultant node. If there is already a 8364 /// node of the specified opcode and operands, it returns that node instead of 8365 /// the current one. 8366 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8367 EVT VT) { 8368 SDVTList VTs = getVTList(VT); 8369 return getMachineNode(Opcode, dl, VTs, None); 8370 } 8371 8372 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8373 EVT VT, SDValue Op1) { 8374 SDVTList VTs = getVTList(VT); 8375 SDValue Ops[] = { Op1 }; 8376 return getMachineNode(Opcode, dl, VTs, Ops); 8377 } 8378 8379 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8380 EVT VT, SDValue Op1, SDValue Op2) { 8381 SDVTList VTs = getVTList(VT); 8382 SDValue Ops[] = { Op1, Op2 }; 8383 return getMachineNode(Opcode, dl, VTs, Ops); 8384 } 8385 8386 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8387 EVT VT, SDValue Op1, SDValue Op2, 8388 SDValue Op3) { 8389 SDVTList VTs = getVTList(VT); 8390 SDValue Ops[] = { Op1, Op2, Op3 }; 8391 return getMachineNode(Opcode, dl, VTs, Ops); 8392 } 8393 8394 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8395 EVT VT, ArrayRef<SDValue> Ops) { 8396 SDVTList VTs = getVTList(VT); 8397 return getMachineNode(Opcode, dl, VTs, Ops); 8398 } 8399 8400 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8401 EVT VT1, EVT VT2, SDValue Op1, 8402 SDValue Op2) { 8403 SDVTList VTs = getVTList(VT1, VT2); 8404 SDValue Ops[] = { Op1, Op2 }; 8405 return getMachineNode(Opcode, dl, VTs, Ops); 8406 } 8407 8408 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8409 EVT VT1, EVT VT2, SDValue Op1, 8410 SDValue Op2, SDValue Op3) { 8411 SDVTList VTs = getVTList(VT1, VT2); 8412 SDValue Ops[] = { Op1, Op2, Op3 }; 8413 return getMachineNode(Opcode, dl, VTs, Ops); 8414 } 8415 8416 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8417 EVT VT1, EVT VT2, 8418 ArrayRef<SDValue> Ops) { 8419 SDVTList VTs = getVTList(VT1, VT2); 8420 return getMachineNode(Opcode, dl, VTs, Ops); 8421 } 8422 8423 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8424 EVT VT1, EVT VT2, EVT VT3, 8425 SDValue Op1, SDValue Op2) { 8426 SDVTList VTs = getVTList(VT1, VT2, VT3); 8427 SDValue Ops[] = { Op1, Op2 }; 8428 return getMachineNode(Opcode, dl, VTs, Ops); 8429 } 8430 8431 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8432 EVT VT1, EVT VT2, EVT VT3, 8433 SDValue Op1, SDValue Op2, 8434 SDValue Op3) { 8435 SDVTList VTs = getVTList(VT1, VT2, VT3); 8436 SDValue Ops[] = { Op1, Op2, Op3 }; 8437 return getMachineNode(Opcode, dl, VTs, Ops); 8438 } 8439 8440 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8441 EVT VT1, EVT VT2, EVT VT3, 8442 ArrayRef<SDValue> Ops) { 8443 SDVTList VTs = getVTList(VT1, VT2, VT3); 8444 return getMachineNode(Opcode, dl, VTs, Ops); 8445 } 8446 8447 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl, 8448 ArrayRef<EVT> ResultTys, 8449 ArrayRef<SDValue> Ops) { 8450 SDVTList VTs = getVTList(ResultTys); 8451 return getMachineNode(Opcode, dl, VTs, Ops); 8452 } 8453 8454 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL, 8455 SDVTList VTs, 8456 ArrayRef<SDValue> Ops) { 8457 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue; 8458 MachineSDNode *N; 8459 void *IP = nullptr; 8460 8461 if (DoCSE) { 8462 FoldingSetNodeID ID; 8463 AddNodeIDNode(ID, ~Opcode, VTs, Ops); 8464 IP = nullptr; 8465 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) { 8466 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL)); 8467 } 8468 } 8469 8470 // Allocate a new MachineSDNode. 8471 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs); 8472 createOperands(N, Ops); 8473 8474 if (DoCSE) 8475 CSEMap.InsertNode(N, IP); 8476 8477 InsertNode(N); 8478 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this); 8479 return N; 8480 } 8481 8482 /// getTargetExtractSubreg - A convenience function for creating 8483 /// TargetOpcode::EXTRACT_SUBREG nodes. 8484 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8485 SDValue Operand) { 8486 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8487 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, 8488 VT, Operand, SRIdxVal); 8489 return SDValue(Subreg, 0); 8490 } 8491 8492 /// getTargetInsertSubreg - A convenience function for creating 8493 /// TargetOpcode::INSERT_SUBREG nodes. 8494 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, 8495 SDValue Operand, SDValue Subreg) { 8496 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32); 8497 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 8498 VT, Operand, Subreg, SRIdxVal); 8499 return SDValue(Result, 0); 8500 } 8501 8502 /// getNodeIfExists - Get the specified node if it's already available, or 8503 /// else return NULL. 8504 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8505 ArrayRef<SDValue> Ops) { 8506 SDNodeFlags Flags; 8507 if (Inserter) 8508 Flags = Inserter->getFlags(); 8509 return getNodeIfExists(Opcode, VTList, Ops, Flags); 8510 } 8511 8512 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList, 8513 ArrayRef<SDValue> Ops, 8514 const SDNodeFlags Flags) { 8515 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8516 FoldingSetNodeID ID; 8517 AddNodeIDNode(ID, Opcode, VTList, Ops); 8518 void *IP = nullptr; 8519 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) { 8520 E->intersectFlagsWith(Flags); 8521 return E; 8522 } 8523 } 8524 return nullptr; 8525 } 8526 8527 /// doesNodeExist - Check if a node exists without modifying its flags. 8528 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList, 8529 ArrayRef<SDValue> Ops) { 8530 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) { 8531 FoldingSetNodeID ID; 8532 AddNodeIDNode(ID, Opcode, VTList, Ops); 8533 void *IP = nullptr; 8534 if (FindNodeOrInsertPos(ID, SDLoc(), IP)) 8535 return true; 8536 } 8537 return false; 8538 } 8539 8540 /// getDbgValue - Creates a SDDbgValue node. 8541 /// 8542 /// SDNode 8543 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr, 8544 SDNode *N, unsigned R, bool IsIndirect, 8545 const DebugLoc &DL, unsigned O) { 8546 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8547 "Expected inlined-at fields to agree"); 8548 return new (DbgInfo->getAlloc()) 8549 SDDbgValue(Var, Expr, SDDbgOperand::fromNode(N, R), N, IsIndirect, DL, O, 8550 /*IsVariadic=*/false); 8551 } 8552 8553 /// Constant 8554 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var, 8555 DIExpression *Expr, 8556 const Value *C, 8557 const DebugLoc &DL, unsigned O) { 8558 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8559 "Expected inlined-at fields to agree"); 8560 return new (DbgInfo->getAlloc()) SDDbgValue( 8561 Var, Expr, SDDbgOperand::fromConst(C), {}, /*IsIndirect=*/false, DL, O, 8562 /*IsVariadic=*/false); 8563 } 8564 8565 /// FrameIndex 8566 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8567 DIExpression *Expr, unsigned FI, 8568 bool IsIndirect, 8569 const DebugLoc &DL, 8570 unsigned O) { 8571 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8572 "Expected inlined-at fields to agree"); 8573 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O); 8574 } 8575 8576 /// FrameIndex with dependencies 8577 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var, 8578 DIExpression *Expr, unsigned FI, 8579 ArrayRef<SDNode *> Dependencies, 8580 bool IsIndirect, 8581 const DebugLoc &DL, 8582 unsigned O) { 8583 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8584 "Expected inlined-at fields to agree"); 8585 return new (DbgInfo->getAlloc()) 8586 SDDbgValue(Var, Expr, SDDbgOperand::fromFrameIdx(FI), Dependencies, 8587 IsIndirect, DL, O, 8588 /*IsVariadic=*/false); 8589 } 8590 8591 /// VReg 8592 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr, 8593 unsigned VReg, bool IsIndirect, 8594 const DebugLoc &DL, unsigned O) { 8595 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8596 "Expected inlined-at fields to agree"); 8597 return new (DbgInfo->getAlloc()) 8598 SDDbgValue(Var, Expr, SDDbgOperand::fromVReg(VReg), {}, IsIndirect, DL, O, 8599 /*IsVariadic=*/false); 8600 } 8601 8602 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr, 8603 ArrayRef<SDDbgOperand> Locs, 8604 ArrayRef<SDNode *> Dependencies, 8605 bool IsIndirect, const DebugLoc &DL, 8606 unsigned O, bool IsVariadic) { 8607 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) && 8608 "Expected inlined-at fields to agree"); 8609 return new (DbgInfo->getAlloc()) 8610 SDDbgValue(Var, Expr, Locs, Dependencies, IsIndirect, DL, O, IsVariadic); 8611 } 8612 8613 void SelectionDAG::transferDbgValues(SDValue From, SDValue To, 8614 unsigned OffsetInBits, unsigned SizeInBits, 8615 bool InvalidateDbg) { 8616 SDNode *FromNode = From.getNode(); 8617 SDNode *ToNode = To.getNode(); 8618 assert(FromNode && ToNode && "Can't modify dbg values"); 8619 8620 // PR35338 8621 // TODO: assert(From != To && "Redundant dbg value transfer"); 8622 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer"); 8623 if (From == To || FromNode == ToNode) 8624 return; 8625 8626 if (!FromNode->getHasDebugValue()) 8627 return; 8628 8629 SDDbgOperand FromLocOp = 8630 SDDbgOperand::fromNode(From.getNode(), From.getResNo()); 8631 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo()); 8632 8633 SmallVector<SDDbgValue *, 2> ClonedDVs; 8634 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) { 8635 if (Dbg->isInvalidated()) 8636 continue; 8637 8638 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value"); 8639 8640 // Create a new location ops vector that is equal to the old vector, but 8641 // with each instance of FromLocOp replaced with ToLocOp. 8642 bool Changed = false; 8643 auto NewLocOps = Dbg->copyLocationOps(); 8644 std::replace_if( 8645 NewLocOps.begin(), NewLocOps.end(), 8646 [&Changed, FromLocOp](const SDDbgOperand &Op) { 8647 bool Match = Op == FromLocOp; 8648 Changed |= Match; 8649 return Match; 8650 }, 8651 ToLocOp); 8652 // Ignore this SDDbgValue if we didn't find a matching location. 8653 if (!Changed) 8654 continue; 8655 8656 DIVariable *Var = Dbg->getVariable(); 8657 auto *Expr = Dbg->getExpression(); 8658 // If a fragment is requested, update the expression. 8659 if (SizeInBits) { 8660 // When splitting a larger (e.g., sign-extended) value whose 8661 // lower bits are described with an SDDbgValue, do not attempt 8662 // to transfer the SDDbgValue to the upper bits. 8663 if (auto FI = Expr->getFragmentInfo()) 8664 if (OffsetInBits + SizeInBits > FI->SizeInBits) 8665 continue; 8666 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits, 8667 SizeInBits); 8668 if (!Fragment) 8669 continue; 8670 Expr = *Fragment; 8671 } 8672 8673 auto NewDependencies = Dbg->copySDNodes(); 8674 std::replace(NewDependencies.begin(), NewDependencies.end(), FromNode, 8675 ToNode); 8676 // Clone the SDDbgValue and move it to To. 8677 SDDbgValue *Clone = getDbgValueList( 8678 Var, Expr, NewLocOps, NewDependencies, Dbg->isIndirect(), 8679 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()), 8680 Dbg->isVariadic()); 8681 ClonedDVs.push_back(Clone); 8682 8683 if (InvalidateDbg) { 8684 // Invalidate value and indicate the SDDbgValue should not be emitted. 8685 Dbg->setIsInvalidated(); 8686 Dbg->setIsEmitted(); 8687 } 8688 } 8689 8690 for (SDDbgValue *Dbg : ClonedDVs) { 8691 assert(is_contained(Dbg->getSDNodes(), ToNode) && 8692 "Transferred DbgValues should depend on the new SDNode"); 8693 AddDbgValue(Dbg, false); 8694 } 8695 } 8696 8697 void SelectionDAG::salvageDebugInfo(SDNode &N) { 8698 if (!N.getHasDebugValue()) 8699 return; 8700 8701 SmallVector<SDDbgValue *, 2> ClonedDVs; 8702 for (auto DV : GetDbgValues(&N)) { 8703 if (DV->isInvalidated()) 8704 continue; 8705 switch (N.getOpcode()) { 8706 default: 8707 break; 8708 case ISD::ADD: 8709 SDValue N0 = N.getOperand(0); 8710 SDValue N1 = N.getOperand(1); 8711 if (!isConstantIntBuildVectorOrConstantInt(N0) && 8712 isConstantIntBuildVectorOrConstantInt(N1)) { 8713 uint64_t Offset = N.getConstantOperandVal(1); 8714 8715 // Rewrite an ADD constant node into a DIExpression. Since we are 8716 // performing arithmetic to compute the variable's *value* in the 8717 // DIExpression, we need to mark the expression with a 8718 // DW_OP_stack_value. 8719 auto *DIExpr = DV->getExpression(); 8720 auto NewLocOps = DV->copyLocationOps(); 8721 bool Changed = false; 8722 for (size_t i = 0; i < NewLocOps.size(); ++i) { 8723 // We're not given a ResNo to compare against because the whole 8724 // node is going away. We know that any ISD::ADD only has one 8725 // result, so we can assume any node match is using the result. 8726 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE || 8727 NewLocOps[i].getSDNode() != &N) 8728 continue; 8729 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo()); 8730 SmallVector<uint64_t, 3> ExprOps; 8731 DIExpression::appendOffset(ExprOps, Offset); 8732 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true); 8733 Changed = true; 8734 } 8735 (void)Changed; 8736 assert(Changed && "Salvage target doesn't use N"); 8737 8738 auto NewDependencies = DV->copySDNodes(); 8739 std::replace(NewDependencies.begin(), NewDependencies.end(), &N, 8740 N0.getNode()); 8741 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr, 8742 NewLocOps, NewDependencies, 8743 DV->isIndirect(), DV->getDebugLoc(), 8744 DV->getOrder(), DV->isVariadic()); 8745 ClonedDVs.push_back(Clone); 8746 DV->setIsInvalidated(); 8747 DV->setIsEmitted(); 8748 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; 8749 N0.getNode()->dumprFull(this); 8750 dbgs() << " into " << *DIExpr << '\n'); 8751 } 8752 } 8753 } 8754 8755 for (SDDbgValue *Dbg : ClonedDVs) { 8756 assert(!Dbg->getSDNodes().empty() && 8757 "Salvaged DbgValue should depend on a new SDNode"); 8758 AddDbgValue(Dbg, false); 8759 } 8760 } 8761 8762 /// Creates a SDDbgLabel node. 8763 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label, 8764 const DebugLoc &DL, unsigned O) { 8765 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) && 8766 "Expected inlined-at fields to agree"); 8767 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O); 8768 } 8769 8770 namespace { 8771 8772 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node 8773 /// pointed to by a use iterator is deleted, increment the use iterator 8774 /// so that it doesn't dangle. 8775 /// 8776 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener { 8777 SDNode::use_iterator &UI; 8778 SDNode::use_iterator &UE; 8779 8780 void NodeDeleted(SDNode *N, SDNode *E) override { 8781 // Increment the iterator as needed. 8782 while (UI != UE && N == *UI) 8783 ++UI; 8784 } 8785 8786 public: 8787 RAUWUpdateListener(SelectionDAG &d, 8788 SDNode::use_iterator &ui, 8789 SDNode::use_iterator &ue) 8790 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {} 8791 }; 8792 8793 } // end anonymous namespace 8794 8795 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8796 /// This can cause recursive merging of nodes in the DAG. 8797 /// 8798 /// This version assumes From has a single result value. 8799 /// 8800 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) { 8801 SDNode *From = FromN.getNode(); 8802 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 8803 "Cannot replace with this method!"); 8804 assert(From != To.getNode() && "Cannot replace uses of with self"); 8805 8806 // Preserve Debug Values 8807 transferDbgValues(FromN, To); 8808 8809 // Iterate over all the existing uses of From. New uses will be added 8810 // to the beginning of the use list, which we avoid visiting. 8811 // This specifically avoids visiting uses of From that arise while the 8812 // replacement is happening, because any such uses would be the result 8813 // of CSE: If an existing node looks like From after one of its operands 8814 // is replaced by To, we don't want to replace of all its users with To 8815 // too. See PR3018 for more info. 8816 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8817 RAUWUpdateListener Listener(*this, UI, UE); 8818 while (UI != UE) { 8819 SDNode *User = *UI; 8820 8821 // This node is about to morph, remove its old self from the CSE maps. 8822 RemoveNodeFromCSEMaps(User); 8823 8824 // A user can appear in a use list multiple times, and when this 8825 // happens the uses are usually next to each other in the list. 8826 // To help reduce the number of CSE recomputations, process all 8827 // the uses of this user that we can find this way. 8828 do { 8829 SDUse &Use = UI.getUse(); 8830 ++UI; 8831 Use.set(To); 8832 if (To->isDivergent() != From->isDivergent()) 8833 updateDivergence(User); 8834 } while (UI != UE && *UI == User); 8835 // Now that we have modified User, add it back to the CSE maps. If it 8836 // already exists there, recursively merge the results together. 8837 AddModifiedNodeToCSEMaps(User); 8838 } 8839 8840 // If we just RAUW'd the root, take note. 8841 if (FromN == getRoot()) 8842 setRoot(To); 8843 } 8844 8845 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8846 /// This can cause recursive merging of nodes in the DAG. 8847 /// 8848 /// This version assumes that for each value of From, there is a 8849 /// corresponding value in To in the same position with the same type. 8850 /// 8851 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) { 8852 #ifndef NDEBUG 8853 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8854 assert((!From->hasAnyUseOfValue(i) || 8855 From->getValueType(i) == To->getValueType(i)) && 8856 "Cannot use this version of ReplaceAllUsesWith!"); 8857 #endif 8858 8859 // Handle the trivial case. 8860 if (From == To) 8861 return; 8862 8863 // Preserve Debug Info. Only do this if there's a use. 8864 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8865 if (From->hasAnyUseOfValue(i)) { 8866 assert((i < To->getNumValues()) && "Invalid To location"); 8867 transferDbgValues(SDValue(From, i), SDValue(To, i)); 8868 } 8869 8870 // Iterate over just the existing users of From. See the comments in 8871 // the ReplaceAllUsesWith above. 8872 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8873 RAUWUpdateListener Listener(*this, UI, UE); 8874 while (UI != UE) { 8875 SDNode *User = *UI; 8876 8877 // This node is about to morph, remove its old self from the CSE maps. 8878 RemoveNodeFromCSEMaps(User); 8879 8880 // A user can appear in a use list multiple times, and when this 8881 // happens the uses are usually next to each other in the list. 8882 // To help reduce the number of CSE recomputations, process all 8883 // the uses of this user that we can find this way. 8884 do { 8885 SDUse &Use = UI.getUse(); 8886 ++UI; 8887 Use.setNode(To); 8888 if (To->isDivergent() != From->isDivergent()) 8889 updateDivergence(User); 8890 } while (UI != UE && *UI == User); 8891 8892 // Now that we have modified User, add it back to the CSE maps. If it 8893 // already exists there, recursively merge the results together. 8894 AddModifiedNodeToCSEMaps(User); 8895 } 8896 8897 // If we just RAUW'd the root, take note. 8898 if (From == getRoot().getNode()) 8899 setRoot(SDValue(To, getRoot().getResNo())); 8900 } 8901 8902 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead. 8903 /// This can cause recursive merging of nodes in the DAG. 8904 /// 8905 /// This version can replace From with any result values. To must match the 8906 /// number and types of values returned by From. 8907 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) { 8908 if (From->getNumValues() == 1) // Handle the simple case efficiently. 8909 return ReplaceAllUsesWith(SDValue(From, 0), To[0]); 8910 8911 // Preserve Debug Info. 8912 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) 8913 transferDbgValues(SDValue(From, i), To[i]); 8914 8915 // Iterate over just the existing users of From. See the comments in 8916 // the ReplaceAllUsesWith above. 8917 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end(); 8918 RAUWUpdateListener Listener(*this, UI, UE); 8919 while (UI != UE) { 8920 SDNode *User = *UI; 8921 8922 // This node is about to morph, remove its old self from the CSE maps. 8923 RemoveNodeFromCSEMaps(User); 8924 8925 // A user can appear in a use list multiple times, and when this happens the 8926 // uses are usually next to each other in the list. To help reduce the 8927 // number of CSE and divergence recomputations, process all the uses of this 8928 // user that we can find this way. 8929 bool To_IsDivergent = false; 8930 do { 8931 SDUse &Use = UI.getUse(); 8932 const SDValue &ToOp = To[Use.getResNo()]; 8933 ++UI; 8934 Use.set(ToOp); 8935 To_IsDivergent |= ToOp->isDivergent(); 8936 } while (UI != UE && *UI == User); 8937 8938 if (To_IsDivergent != From->isDivergent()) 8939 updateDivergence(User); 8940 8941 // Now that we have modified User, add it back to the CSE maps. If it 8942 // already exists there, recursively merge the results together. 8943 AddModifiedNodeToCSEMaps(User); 8944 } 8945 8946 // If we just RAUW'd the root, take note. 8947 if (From == getRoot().getNode()) 8948 setRoot(SDValue(To[getRoot().getResNo()])); 8949 } 8950 8951 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving 8952 /// uses of other values produced by From.getNode() alone. The Deleted 8953 /// vector is handled the same way as for ReplaceAllUsesWith. 8954 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){ 8955 // Handle the really simple, really trivial case efficiently. 8956 if (From == To) return; 8957 8958 // Handle the simple, trivial, case efficiently. 8959 if (From.getNode()->getNumValues() == 1) { 8960 ReplaceAllUsesWith(From, To); 8961 return; 8962 } 8963 8964 // Preserve Debug Info. 8965 transferDbgValues(From, To); 8966 8967 // Iterate over just the existing users of From. See the comments in 8968 // the ReplaceAllUsesWith above. 8969 SDNode::use_iterator UI = From.getNode()->use_begin(), 8970 UE = From.getNode()->use_end(); 8971 RAUWUpdateListener Listener(*this, UI, UE); 8972 while (UI != UE) { 8973 SDNode *User = *UI; 8974 bool UserRemovedFromCSEMaps = false; 8975 8976 // A user can appear in a use list multiple times, and when this 8977 // happens the uses are usually next to each other in the list. 8978 // To help reduce the number of CSE recomputations, process all 8979 // the uses of this user that we can find this way. 8980 do { 8981 SDUse &Use = UI.getUse(); 8982 8983 // Skip uses of different values from the same node. 8984 if (Use.getResNo() != From.getResNo()) { 8985 ++UI; 8986 continue; 8987 } 8988 8989 // If this node hasn't been modified yet, it's still in the CSE maps, 8990 // so remove its old self from the CSE maps. 8991 if (!UserRemovedFromCSEMaps) { 8992 RemoveNodeFromCSEMaps(User); 8993 UserRemovedFromCSEMaps = true; 8994 } 8995 8996 ++UI; 8997 Use.set(To); 8998 if (To->isDivergent() != From->isDivergent()) 8999 updateDivergence(User); 9000 } while (UI != UE && *UI == User); 9001 // We are iterating over all uses of the From node, so if a use 9002 // doesn't use the specific value, no changes are made. 9003 if (!UserRemovedFromCSEMaps) 9004 continue; 9005 9006 // Now that we have modified User, add it back to the CSE maps. If it 9007 // already exists there, recursively merge the results together. 9008 AddModifiedNodeToCSEMaps(User); 9009 } 9010 9011 // If we just RAUW'd the root, take note. 9012 if (From == getRoot()) 9013 setRoot(To); 9014 } 9015 9016 namespace { 9017 9018 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith 9019 /// to record information about a use. 9020 struct UseMemo { 9021 SDNode *User; 9022 unsigned Index; 9023 SDUse *Use; 9024 }; 9025 9026 /// operator< - Sort Memos by User. 9027 bool operator<(const UseMemo &L, const UseMemo &R) { 9028 return (intptr_t)L.User < (intptr_t)R.User; 9029 } 9030 9031 } // end anonymous namespace 9032 9033 bool SelectionDAG::calculateDivergence(SDNode *N) { 9034 if (TLI->isSDNodeAlwaysUniform(N)) { 9035 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) && 9036 "Conflicting divergence information!"); 9037 return false; 9038 } 9039 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA)) 9040 return true; 9041 for (auto &Op : N->ops()) { 9042 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent()) 9043 return true; 9044 } 9045 return false; 9046 } 9047 9048 void SelectionDAG::updateDivergence(SDNode *N) { 9049 SmallVector<SDNode *, 16> Worklist(1, N); 9050 do { 9051 N = Worklist.pop_back_val(); 9052 bool IsDivergent = calculateDivergence(N); 9053 if (N->SDNodeBits.IsDivergent != IsDivergent) { 9054 N->SDNodeBits.IsDivergent = IsDivergent; 9055 llvm::append_range(Worklist, N->uses()); 9056 } 9057 } while (!Worklist.empty()); 9058 } 9059 9060 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) { 9061 DenseMap<SDNode *, unsigned> Degree; 9062 Order.reserve(AllNodes.size()); 9063 for (auto &N : allnodes()) { 9064 unsigned NOps = N.getNumOperands(); 9065 Degree[&N] = NOps; 9066 if (0 == NOps) 9067 Order.push_back(&N); 9068 } 9069 for (size_t I = 0; I != Order.size(); ++I) { 9070 SDNode *N = Order[I]; 9071 for (auto U : N->uses()) { 9072 unsigned &UnsortedOps = Degree[U]; 9073 if (0 == --UnsortedOps) 9074 Order.push_back(U); 9075 } 9076 } 9077 } 9078 9079 #ifndef NDEBUG 9080 void SelectionDAG::VerifyDAGDiverence() { 9081 std::vector<SDNode *> TopoOrder; 9082 CreateTopologicalOrder(TopoOrder); 9083 for (auto *N : TopoOrder) { 9084 assert(calculateDivergence(N) == N->isDivergent() && 9085 "Divergence bit inconsistency detected"); 9086 } 9087 } 9088 #endif 9089 9090 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving 9091 /// uses of other values produced by From.getNode() alone. The same value 9092 /// may appear in both the From and To list. The Deleted vector is 9093 /// handled the same way as for ReplaceAllUsesWith. 9094 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From, 9095 const SDValue *To, 9096 unsigned Num){ 9097 // Handle the simple, trivial case efficiently. 9098 if (Num == 1) 9099 return ReplaceAllUsesOfValueWith(*From, *To); 9100 9101 transferDbgValues(*From, *To); 9102 9103 // Read up all the uses and make records of them. This helps 9104 // processing new uses that are introduced during the 9105 // replacement process. 9106 SmallVector<UseMemo, 4> Uses; 9107 for (unsigned i = 0; i != Num; ++i) { 9108 unsigned FromResNo = From[i].getResNo(); 9109 SDNode *FromNode = From[i].getNode(); 9110 for (SDNode::use_iterator UI = FromNode->use_begin(), 9111 E = FromNode->use_end(); UI != E; ++UI) { 9112 SDUse &Use = UI.getUse(); 9113 if (Use.getResNo() == FromResNo) { 9114 UseMemo Memo = { *UI, i, &Use }; 9115 Uses.push_back(Memo); 9116 } 9117 } 9118 } 9119 9120 // Sort the uses, so that all the uses from a given User are together. 9121 llvm::sort(Uses); 9122 9123 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size(); 9124 UseIndex != UseIndexEnd; ) { 9125 // We know that this user uses some value of From. If it is the right 9126 // value, update it. 9127 SDNode *User = Uses[UseIndex].User; 9128 9129 // This node is about to morph, remove its old self from the CSE maps. 9130 RemoveNodeFromCSEMaps(User); 9131 9132 // The Uses array is sorted, so all the uses for a given User 9133 // are next to each other in the list. 9134 // To help reduce the number of CSE recomputations, process all 9135 // the uses of this user that we can find this way. 9136 do { 9137 unsigned i = Uses[UseIndex].Index; 9138 SDUse &Use = *Uses[UseIndex].Use; 9139 ++UseIndex; 9140 9141 Use.set(To[i]); 9142 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User); 9143 9144 // Now that we have modified User, add it back to the CSE maps. If it 9145 // already exists there, recursively merge the results together. 9146 AddModifiedNodeToCSEMaps(User); 9147 } 9148 } 9149 9150 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG 9151 /// based on their topological order. It returns the maximum id and a vector 9152 /// of the SDNodes* in assigned order by reference. 9153 unsigned SelectionDAG::AssignTopologicalOrder() { 9154 unsigned DAGSize = 0; 9155 9156 // SortedPos tracks the progress of the algorithm. Nodes before it are 9157 // sorted, nodes after it are unsorted. When the algorithm completes 9158 // it is at the end of the list. 9159 allnodes_iterator SortedPos = allnodes_begin(); 9160 9161 // Visit all the nodes. Move nodes with no operands to the front of 9162 // the list immediately. Annotate nodes that do have operands with their 9163 // operand count. Before we do this, the Node Id fields of the nodes 9164 // may contain arbitrary values. After, the Node Id fields for nodes 9165 // before SortedPos will contain the topological sort index, and the 9166 // Node Id fields for nodes At SortedPos and after will contain the 9167 // count of outstanding operands. 9168 for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) { 9169 SDNode *N = &*I++; 9170 checkForCycles(N, this); 9171 unsigned Degree = N->getNumOperands(); 9172 if (Degree == 0) { 9173 // A node with no uses, add it to the result array immediately. 9174 N->setNodeId(DAGSize++); 9175 allnodes_iterator Q(N); 9176 if (Q != SortedPos) 9177 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q)); 9178 assert(SortedPos != AllNodes.end() && "Overran node list"); 9179 ++SortedPos; 9180 } else { 9181 // Temporarily use the Node Id as scratch space for the degree count. 9182 N->setNodeId(Degree); 9183 } 9184 } 9185 9186 // Visit all the nodes. As we iterate, move nodes into sorted order, 9187 // such that by the time the end is reached all nodes will be sorted. 9188 for (SDNode &Node : allnodes()) { 9189 SDNode *N = &Node; 9190 checkForCycles(N, this); 9191 // N is in sorted position, so all its uses have one less operand 9192 // that needs to be sorted. 9193 for (SDNode *P : N->uses()) { 9194 unsigned Degree = P->getNodeId(); 9195 assert(Degree != 0 && "Invalid node degree"); 9196 --Degree; 9197 if (Degree == 0) { 9198 // All of P's operands are sorted, so P may sorted now. 9199 P->setNodeId(DAGSize++); 9200 if (P->getIterator() != SortedPos) 9201 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P)); 9202 assert(SortedPos != AllNodes.end() && "Overran node list"); 9203 ++SortedPos; 9204 } else { 9205 // Update P's outstanding operand count. 9206 P->setNodeId(Degree); 9207 } 9208 } 9209 if (Node.getIterator() == SortedPos) { 9210 #ifndef NDEBUG 9211 allnodes_iterator I(N); 9212 SDNode *S = &*++I; 9213 dbgs() << "Overran sorted position:\n"; 9214 S->dumprFull(this); dbgs() << "\n"; 9215 dbgs() << "Checking if this is due to cycles\n"; 9216 checkForCycles(this, true); 9217 #endif 9218 llvm_unreachable(nullptr); 9219 } 9220 } 9221 9222 assert(SortedPos == AllNodes.end() && 9223 "Topological sort incomplete!"); 9224 assert(AllNodes.front().getOpcode() == ISD::EntryToken && 9225 "First node in topological sort is not the entry token!"); 9226 assert(AllNodes.front().getNodeId() == 0 && 9227 "First node in topological sort has non-zero id!"); 9228 assert(AllNodes.front().getNumOperands() == 0 && 9229 "First node in topological sort has operands!"); 9230 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 && 9231 "Last node in topologic sort has unexpected id!"); 9232 assert(AllNodes.back().use_empty() && 9233 "Last node in topologic sort has users!"); 9234 assert(DAGSize == allnodes_size() && "Node count mismatch!"); 9235 return DAGSize; 9236 } 9237 9238 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the 9239 /// value is produced by SD. 9240 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) { 9241 for (SDNode *SD : DB->getSDNodes()) { 9242 if (!SD) 9243 continue; 9244 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue()); 9245 SD->setHasDebugValue(true); 9246 } 9247 DbgInfo->add(DB, isParameter); 9248 } 9249 9250 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); } 9251 9252 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain, 9253 SDValue NewMemOpChain) { 9254 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node"); 9255 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT"); 9256 // The new memory operation must have the same position as the old load in 9257 // terms of memory dependency. Create a TokenFactor for the old load and new 9258 // memory operation and update uses of the old load's output chain to use that 9259 // TokenFactor. 9260 if (OldChain == NewMemOpChain || OldChain.use_empty()) 9261 return NewMemOpChain; 9262 9263 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other, 9264 OldChain, NewMemOpChain); 9265 ReplaceAllUsesOfValueWith(OldChain, TokenFactor); 9266 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain); 9267 return TokenFactor; 9268 } 9269 9270 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad, 9271 SDValue NewMemOp) { 9272 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node"); 9273 SDValue OldChain = SDValue(OldLoad, 1); 9274 SDValue NewMemOpChain = NewMemOp.getValue(1); 9275 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain); 9276 } 9277 9278 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op, 9279 Function **OutFunction) { 9280 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol"); 9281 9282 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol(); 9283 auto *Module = MF->getFunction().getParent(); 9284 auto *Function = Module->getFunction(Symbol); 9285 9286 if (OutFunction != nullptr) 9287 *OutFunction = Function; 9288 9289 if (Function != nullptr) { 9290 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace()); 9291 return getGlobalAddress(Function, SDLoc(Op), PtrTy); 9292 } 9293 9294 std::string ErrorStr; 9295 raw_string_ostream ErrorFormatter(ErrorStr); 9296 9297 ErrorFormatter << "Undefined external symbol "; 9298 ErrorFormatter << '"' << Symbol << '"'; 9299 ErrorFormatter.flush(); 9300 9301 report_fatal_error(ErrorStr); 9302 } 9303 9304 //===----------------------------------------------------------------------===// 9305 // SDNode Class 9306 //===----------------------------------------------------------------------===// 9307 9308 bool llvm::isNullConstant(SDValue V) { 9309 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9310 return Const != nullptr && Const->isNullValue(); 9311 } 9312 9313 bool llvm::isNullFPConstant(SDValue V) { 9314 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V); 9315 return Const != nullptr && Const->isZero() && !Const->isNegative(); 9316 } 9317 9318 bool llvm::isAllOnesConstant(SDValue V) { 9319 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9320 return Const != nullptr && Const->isAllOnesValue(); 9321 } 9322 9323 bool llvm::isOneConstant(SDValue V) { 9324 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V); 9325 return Const != nullptr && Const->isOne(); 9326 } 9327 9328 SDValue llvm::peekThroughBitcasts(SDValue V) { 9329 while (V.getOpcode() == ISD::BITCAST) 9330 V = V.getOperand(0); 9331 return V; 9332 } 9333 9334 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) { 9335 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse()) 9336 V = V.getOperand(0); 9337 return V; 9338 } 9339 9340 SDValue llvm::peekThroughExtractSubvectors(SDValue V) { 9341 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) 9342 V = V.getOperand(0); 9343 return V; 9344 } 9345 9346 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) { 9347 if (V.getOpcode() != ISD::XOR) 9348 return false; 9349 V = peekThroughBitcasts(V.getOperand(1)); 9350 unsigned NumBits = V.getScalarValueSizeInBits(); 9351 ConstantSDNode *C = 9352 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true); 9353 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits); 9354 } 9355 9356 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs, 9357 bool AllowTruncation) { 9358 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9359 return CN; 9360 9361 // SplatVectors can truncate their operands. Ignore that case here unless 9362 // AllowTruncation is set. 9363 if (N->getOpcode() == ISD::SPLAT_VECTOR) { 9364 EVT VecEltVT = N->getValueType(0).getVectorElementType(); 9365 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) { 9366 EVT CVT = CN->getValueType(0); 9367 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension"); 9368 if (AllowTruncation || CVT == VecEltVT) 9369 return CN; 9370 } 9371 } 9372 9373 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9374 BitVector UndefElements; 9375 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements); 9376 9377 // BuildVectors can truncate their operands. Ignore that case here unless 9378 // AllowTruncation is set. 9379 if (CN && (UndefElements.none() || AllowUndefs)) { 9380 EVT CVT = CN->getValueType(0); 9381 EVT NSVT = N.getValueType().getScalarType(); 9382 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9383 if (AllowTruncation || (CVT == NSVT)) 9384 return CN; 9385 } 9386 } 9387 9388 return nullptr; 9389 } 9390 9391 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts, 9392 bool AllowUndefs, 9393 bool AllowTruncation) { 9394 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) 9395 return CN; 9396 9397 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9398 BitVector UndefElements; 9399 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements); 9400 9401 // BuildVectors can truncate their operands. Ignore that case here unless 9402 // AllowTruncation is set. 9403 if (CN && (UndefElements.none() || AllowUndefs)) { 9404 EVT CVT = CN->getValueType(0); 9405 EVT NSVT = N.getValueType().getScalarType(); 9406 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension"); 9407 if (AllowTruncation || (CVT == NSVT)) 9408 return CN; 9409 } 9410 } 9411 9412 return nullptr; 9413 } 9414 9415 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) { 9416 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9417 return CN; 9418 9419 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9420 BitVector UndefElements; 9421 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements); 9422 if (CN && (UndefElements.none() || AllowUndefs)) 9423 return CN; 9424 } 9425 9426 if (N.getOpcode() == ISD::SPLAT_VECTOR) 9427 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0))) 9428 return CN; 9429 9430 return nullptr; 9431 } 9432 9433 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, 9434 const APInt &DemandedElts, 9435 bool AllowUndefs) { 9436 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N)) 9437 return CN; 9438 9439 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) { 9440 BitVector UndefElements; 9441 ConstantFPSDNode *CN = 9442 BV->getConstantFPSplatNode(DemandedElts, &UndefElements); 9443 if (CN && (UndefElements.none() || AllowUndefs)) 9444 return CN; 9445 } 9446 9447 return nullptr; 9448 } 9449 9450 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) { 9451 // TODO: may want to use peekThroughBitcast() here. 9452 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9453 return C && C->isNullValue(); 9454 } 9455 9456 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) { 9457 // TODO: may want to use peekThroughBitcast() here. 9458 unsigned BitWidth = N.getScalarValueSizeInBits(); 9459 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9460 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth; 9461 } 9462 9463 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) { 9464 N = peekThroughBitcasts(N); 9465 unsigned BitWidth = N.getScalarValueSizeInBits(); 9466 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs); 9467 return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth; 9468 } 9469 9470 HandleSDNode::~HandleSDNode() { 9471 DropOperands(); 9472 } 9473 9474 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order, 9475 const DebugLoc &DL, 9476 const GlobalValue *GA, EVT VT, 9477 int64_t o, unsigned TF) 9478 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) { 9479 TheGlobal = GA; 9480 } 9481 9482 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, 9483 EVT VT, unsigned SrcAS, 9484 unsigned DestAS) 9485 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)), 9486 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {} 9487 9488 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, 9489 SDVTList VTs, EVT memvt, MachineMemOperand *mmo) 9490 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) { 9491 MemSDNodeBits.IsVolatile = MMO->isVolatile(); 9492 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal(); 9493 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable(); 9494 MemSDNodeBits.IsInvariant = MMO->isInvariant(); 9495 9496 // We check here that the size of the memory operand fits within the size of 9497 // the MMO. This is because the MMO might indicate only a possible address 9498 // range instead of specifying the affected memory addresses precisely. 9499 // TODO: Make MachineMemOperands aware of scalable vectors. 9500 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() && 9501 "Size mismatch!"); 9502 } 9503 9504 /// Profile - Gather unique data for the node. 9505 /// 9506 void SDNode::Profile(FoldingSetNodeID &ID) const { 9507 AddNodeIDNode(ID, this); 9508 } 9509 9510 namespace { 9511 9512 struct EVTArray { 9513 std::vector<EVT> VTs; 9514 9515 EVTArray() { 9516 VTs.reserve(MVT::LAST_VALUETYPE); 9517 for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i) 9518 VTs.push_back(MVT((MVT::SimpleValueType)i)); 9519 } 9520 }; 9521 9522 } // end anonymous namespace 9523 9524 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs; 9525 static ManagedStatic<EVTArray> SimpleVTArray; 9526 static ManagedStatic<sys::SmartMutex<true>> VTMutex; 9527 9528 /// getValueTypeList - Return a pointer to the specified value type. 9529 /// 9530 const EVT *SDNode::getValueTypeList(EVT VT) { 9531 if (VT.isExtended()) { 9532 sys::SmartScopedLock<true> Lock(*VTMutex); 9533 return &(*EVTs->insert(VT).first); 9534 } else { 9535 assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE && 9536 "Value type out of range!"); 9537 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy]; 9538 } 9539 } 9540 9541 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the 9542 /// indicated value. This method ignores uses of other values defined by this 9543 /// operation. 9544 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const { 9545 assert(Value < getNumValues() && "Bad value!"); 9546 9547 // TODO: Only iterate over uses of a given value of the node 9548 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) { 9549 if (UI.getUse().getResNo() == Value) { 9550 if (NUses == 0) 9551 return false; 9552 --NUses; 9553 } 9554 } 9555 9556 // Found exactly the right number of uses? 9557 return NUses == 0; 9558 } 9559 9560 /// hasAnyUseOfValue - Return true if there are any use of the indicated 9561 /// value. This method ignores uses of other values defined by this operation. 9562 bool SDNode::hasAnyUseOfValue(unsigned Value) const { 9563 assert(Value < getNumValues() && "Bad value!"); 9564 9565 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) 9566 if (UI.getUse().getResNo() == Value) 9567 return true; 9568 9569 return false; 9570 } 9571 9572 /// isOnlyUserOf - Return true if this node is the only use of N. 9573 bool SDNode::isOnlyUserOf(const SDNode *N) const { 9574 bool Seen = false; 9575 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9576 SDNode *User = *I; 9577 if (User == this) 9578 Seen = true; 9579 else 9580 return false; 9581 } 9582 9583 return Seen; 9584 } 9585 9586 /// Return true if the only users of N are contained in Nodes. 9587 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) { 9588 bool Seen = false; 9589 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 9590 SDNode *User = *I; 9591 if (llvm::is_contained(Nodes, User)) 9592 Seen = true; 9593 else 9594 return false; 9595 } 9596 9597 return Seen; 9598 } 9599 9600 /// isOperand - Return true if this node is an operand of N. 9601 bool SDValue::isOperandOf(const SDNode *N) const { 9602 return is_contained(N->op_values(), *this); 9603 } 9604 9605 bool SDNode::isOperandOf(const SDNode *N) const { 9606 return any_of(N->op_values(), 9607 [this](SDValue Op) { return this == Op.getNode(); }); 9608 } 9609 9610 /// reachesChainWithoutSideEffects - Return true if this operand (which must 9611 /// be a chain) reaches the specified operand without crossing any 9612 /// side-effecting instructions on any chain path. In practice, this looks 9613 /// through token factors and non-volatile loads. In order to remain efficient, 9614 /// this only looks a couple of nodes in, it does not do an exhaustive search. 9615 /// 9616 /// Note that we only need to examine chains when we're searching for 9617 /// side-effects; SelectionDAG requires that all side-effects are represented 9618 /// by chains, even if another operand would force a specific ordering. This 9619 /// constraint is necessary to allow transformations like splitting loads. 9620 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 9621 unsigned Depth) const { 9622 if (*this == Dest) return true; 9623 9624 // Don't search too deeply, we just want to be able to see through 9625 // TokenFactor's etc. 9626 if (Depth == 0) return false; 9627 9628 // If this is a token factor, all inputs to the TF happen in parallel. 9629 if (getOpcode() == ISD::TokenFactor) { 9630 // First, try a shallow search. 9631 if (is_contained((*this)->ops(), Dest)) { 9632 // We found the chain we want as an operand of this TokenFactor. 9633 // Essentially, we reach the chain without side-effects if we could 9634 // serialize the TokenFactor into a simple chain of operations with 9635 // Dest as the last operation. This is automatically true if the 9636 // chain has one use: there are no other ordering constraints. 9637 // If the chain has more than one use, we give up: some other 9638 // use of Dest might force a side-effect between Dest and the current 9639 // node. 9640 if (Dest.hasOneUse()) 9641 return true; 9642 } 9643 // Next, try a deep search: check whether every operand of the TokenFactor 9644 // reaches Dest. 9645 return llvm::all_of((*this)->ops(), [=](SDValue Op) { 9646 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1); 9647 }); 9648 } 9649 9650 // Loads don't have side effects, look through them. 9651 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) { 9652 if (Ld->isUnordered()) 9653 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1); 9654 } 9655 return false; 9656 } 9657 9658 bool SDNode::hasPredecessor(const SDNode *N) const { 9659 SmallPtrSet<const SDNode *, 32> Visited; 9660 SmallVector<const SDNode *, 16> Worklist; 9661 Worklist.push_back(this); 9662 return hasPredecessorHelper(N, Visited, Worklist); 9663 } 9664 9665 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) { 9666 this->Flags.intersectWith(Flags); 9667 } 9668 9669 SDValue 9670 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, 9671 ArrayRef<ISD::NodeType> CandidateBinOps, 9672 bool AllowPartials) { 9673 // The pattern must end in an extract from index 0. 9674 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9675 !isNullConstant(Extract->getOperand(1))) 9676 return SDValue(); 9677 9678 // Match against one of the candidate binary ops. 9679 SDValue Op = Extract->getOperand(0); 9680 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) { 9681 return Op.getOpcode() == unsigned(BinOp); 9682 })) 9683 return SDValue(); 9684 9685 // Floating-point reductions may require relaxed constraints on the final step 9686 // of the reduction because they may reorder intermediate operations. 9687 unsigned CandidateBinOp = Op.getOpcode(); 9688 if (Op.getValueType().isFloatingPoint()) { 9689 SDNodeFlags Flags = Op->getFlags(); 9690 switch (CandidateBinOp) { 9691 case ISD::FADD: 9692 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation()) 9693 return SDValue(); 9694 break; 9695 default: 9696 llvm_unreachable("Unhandled FP opcode for binop reduction"); 9697 } 9698 } 9699 9700 // Matching failed - attempt to see if we did enough stages that a partial 9701 // reduction from a subvector is possible. 9702 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) { 9703 if (!AllowPartials || !Op) 9704 return SDValue(); 9705 EVT OpVT = Op.getValueType(); 9706 EVT OpSVT = OpVT.getScalarType(); 9707 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts); 9708 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0)) 9709 return SDValue(); 9710 BinOp = (ISD::NodeType)CandidateBinOp; 9711 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op, 9712 getVectorIdxConstant(0, SDLoc(Op))); 9713 }; 9714 9715 // At each stage, we're looking for something that looks like: 9716 // %s = shufflevector <8 x i32> %op, <8 x i32> undef, 9717 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef, 9718 // i32 undef, i32 undef, i32 undef, i32 undef> 9719 // %a = binop <8 x i32> %op, %s 9720 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid, 9721 // we expect something like: 9722 // <4,5,6,7,u,u,u,u> 9723 // <2,3,u,u,u,u,u,u> 9724 // <1,u,u,u,u,u,u,u> 9725 // While a partial reduction match would be: 9726 // <2,3,u,u,u,u,u,u> 9727 // <1,u,u,u,u,u,u,u> 9728 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements()); 9729 SDValue PrevOp; 9730 for (unsigned i = 0; i < Stages; ++i) { 9731 unsigned MaskEnd = (1 << i); 9732 9733 if (Op.getOpcode() != CandidateBinOp) 9734 return PartialReduction(PrevOp, MaskEnd); 9735 9736 SDValue Op0 = Op.getOperand(0); 9737 SDValue Op1 = Op.getOperand(1); 9738 9739 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0); 9740 if (Shuffle) { 9741 Op = Op1; 9742 } else { 9743 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1); 9744 Op = Op0; 9745 } 9746 9747 // The first operand of the shuffle should be the same as the other operand 9748 // of the binop. 9749 if (!Shuffle || Shuffle->getOperand(0) != Op) 9750 return PartialReduction(PrevOp, MaskEnd); 9751 9752 // Verify the shuffle has the expected (at this stage of the pyramid) mask. 9753 for (int Index = 0; Index < (int)MaskEnd; ++Index) 9754 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index)) 9755 return PartialReduction(PrevOp, MaskEnd); 9756 9757 PrevOp = Op; 9758 } 9759 9760 // Handle subvector reductions, which tend to appear after the shuffle 9761 // reduction stages. 9762 while (Op.getOpcode() == CandidateBinOp) { 9763 unsigned NumElts = Op.getValueType().getVectorNumElements(); 9764 SDValue Op0 = Op.getOperand(0); 9765 SDValue Op1 = Op.getOperand(1); 9766 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9767 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR || 9768 Op0.getOperand(0) != Op1.getOperand(0)) 9769 break; 9770 SDValue Src = Op0.getOperand(0); 9771 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 9772 if (NumSrcElts != (2 * NumElts)) 9773 break; 9774 if (!(Op0.getConstantOperandAPInt(1) == 0 && 9775 Op1.getConstantOperandAPInt(1) == NumElts) && 9776 !(Op1.getConstantOperandAPInt(1) == 0 && 9777 Op0.getConstantOperandAPInt(1) == NumElts)) 9778 break; 9779 Op = Src; 9780 } 9781 9782 BinOp = (ISD::NodeType)CandidateBinOp; 9783 return Op; 9784 } 9785 9786 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) { 9787 assert(N->getNumValues() == 1 && 9788 "Can't unroll a vector with multiple results!"); 9789 9790 EVT VT = N->getValueType(0); 9791 unsigned NE = VT.getVectorNumElements(); 9792 EVT EltVT = VT.getVectorElementType(); 9793 SDLoc dl(N); 9794 9795 SmallVector<SDValue, 8> Scalars; 9796 SmallVector<SDValue, 4> Operands(N->getNumOperands()); 9797 9798 // If ResNE is 0, fully unroll the vector op. 9799 if (ResNE == 0) 9800 ResNE = NE; 9801 else if (NE > ResNE) 9802 NE = ResNE; 9803 9804 unsigned i; 9805 for (i= 0; i != NE; ++i) { 9806 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) { 9807 SDValue Operand = N->getOperand(j); 9808 EVT OperandVT = Operand.getValueType(); 9809 if (OperandVT.isVector()) { 9810 // A vector operand; extract a single element. 9811 EVT OperandEltVT = OperandVT.getVectorElementType(); 9812 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, 9813 Operand, getVectorIdxConstant(i, dl)); 9814 } else { 9815 // A scalar operand; just use it as is. 9816 Operands[j] = Operand; 9817 } 9818 } 9819 9820 switch (N->getOpcode()) { 9821 default: { 9822 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands, 9823 N->getFlags())); 9824 break; 9825 } 9826 case ISD::VSELECT: 9827 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands)); 9828 break; 9829 case ISD::SHL: 9830 case ISD::SRA: 9831 case ISD::SRL: 9832 case ISD::ROTL: 9833 case ISD::ROTR: 9834 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0], 9835 getShiftAmountOperand(Operands[0].getValueType(), 9836 Operands[1]))); 9837 break; 9838 case ISD::SIGN_EXTEND_INREG: { 9839 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType(); 9840 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, 9841 Operands[0], 9842 getValueType(ExtVT))); 9843 } 9844 } 9845 } 9846 9847 for (; i < ResNE; ++i) 9848 Scalars.push_back(getUNDEF(EltVT)); 9849 9850 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE); 9851 return getBuildVector(VecVT, dl, Scalars); 9852 } 9853 9854 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp( 9855 SDNode *N, unsigned ResNE) { 9856 unsigned Opcode = N->getOpcode(); 9857 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO || 9858 Opcode == ISD::USUBO || Opcode == ISD::SSUBO || 9859 Opcode == ISD::UMULO || Opcode == ISD::SMULO) && 9860 "Expected an overflow opcode"); 9861 9862 EVT ResVT = N->getValueType(0); 9863 EVT OvVT = N->getValueType(1); 9864 EVT ResEltVT = ResVT.getVectorElementType(); 9865 EVT OvEltVT = OvVT.getVectorElementType(); 9866 SDLoc dl(N); 9867 9868 // If ResNE is 0, fully unroll the vector op. 9869 unsigned NE = ResVT.getVectorNumElements(); 9870 if (ResNE == 0) 9871 ResNE = NE; 9872 else if (NE > ResNE) 9873 NE = ResNE; 9874 9875 SmallVector<SDValue, 8> LHSScalars; 9876 SmallVector<SDValue, 8> RHSScalars; 9877 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE); 9878 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE); 9879 9880 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT); 9881 SDVTList VTs = getVTList(ResEltVT, SVT); 9882 SmallVector<SDValue, 8> ResScalars; 9883 SmallVector<SDValue, 8> OvScalars; 9884 for (unsigned i = 0; i < NE; ++i) { 9885 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]); 9886 SDValue Ov = 9887 getSelect(dl, OvEltVT, Res.getValue(1), 9888 getBoolConstant(true, dl, OvEltVT, ResVT), 9889 getConstant(0, dl, OvEltVT)); 9890 9891 ResScalars.push_back(Res); 9892 OvScalars.push_back(Ov); 9893 } 9894 9895 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT)); 9896 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT)); 9897 9898 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE); 9899 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE); 9900 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars), 9901 getBuildVector(NewOvVT, dl, OvScalars)); 9902 } 9903 9904 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD, 9905 LoadSDNode *Base, 9906 unsigned Bytes, 9907 int Dist) const { 9908 if (LD->isVolatile() || Base->isVolatile()) 9909 return false; 9910 // TODO: probably too restrictive for atomics, revisit 9911 if (!LD->isSimple()) 9912 return false; 9913 if (LD->isIndexed() || Base->isIndexed()) 9914 return false; 9915 if (LD->getChain() != Base->getChain()) 9916 return false; 9917 EVT VT = LD->getValueType(0); 9918 if (VT.getSizeInBits() / 8 != Bytes) 9919 return false; 9920 9921 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this); 9922 auto LocDecomp = BaseIndexOffset::match(LD, *this); 9923 9924 int64_t Offset = 0; 9925 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset)) 9926 return (Dist * Bytes == Offset); 9927 return false; 9928 } 9929 9930 /// InferPtrAlignment - Infer alignment of a load / store address. Return None 9931 /// if it cannot be inferred. 9932 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const { 9933 // If this is a GlobalAddress + cst, return the alignment. 9934 const GlobalValue *GV = nullptr; 9935 int64_t GVOffset = 0; 9936 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) { 9937 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType()); 9938 KnownBits Known(PtrWidth); 9939 llvm::computeKnownBits(GV, Known, getDataLayout()); 9940 unsigned AlignBits = Known.countMinTrailingZeros(); 9941 if (AlignBits) 9942 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset); 9943 } 9944 9945 // If this is a direct reference to a stack slot, use information about the 9946 // stack slot's alignment. 9947 int FrameIdx = INT_MIN; 9948 int64_t FrameOffset = 0; 9949 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) { 9950 FrameIdx = FI->getIndex(); 9951 } else if (isBaseWithConstantOffset(Ptr) && 9952 isa<FrameIndexSDNode>(Ptr.getOperand(0))) { 9953 // Handle FI+Cst 9954 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex(); 9955 FrameOffset = Ptr.getConstantOperandVal(1); 9956 } 9957 9958 if (FrameIdx != INT_MIN) { 9959 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo(); 9960 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset); 9961 } 9962 9963 return None; 9964 } 9965 9966 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type 9967 /// which is split (or expanded) into two not necessarily identical pieces. 9968 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const { 9969 // Currently all types are split in half. 9970 EVT LoVT, HiVT; 9971 if (!VT.isVector()) 9972 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT); 9973 else 9974 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext()); 9975 9976 return std::make_pair(LoVT, HiVT); 9977 } 9978 9979 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a 9980 /// type, dependent on an enveloping VT that has been split into two identical 9981 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size. 9982 std::pair<EVT, EVT> 9983 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, 9984 bool *HiIsEmpty) const { 9985 EVT EltTp = VT.getVectorElementType(); 9986 // Examples: 9987 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty) 9988 // custom VL=9 with enveloping VL=8/8 yields 8/1 9989 // custom VL=10 with enveloping VL=8/8 yields 8/2 9990 // etc. 9991 ElementCount VTNumElts = VT.getVectorElementCount(); 9992 ElementCount EnvNumElts = EnvVT.getVectorElementCount(); 9993 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() && 9994 "Mixing fixed width and scalable vectors when enveloping a type"); 9995 EVT LoVT, HiVT; 9996 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) { 9997 LoVT = EnvVT; 9998 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts); 9999 *HiIsEmpty = false; 10000 } else { 10001 // Flag that hi type has zero storage size, but return split envelop type 10002 // (this would be easier if vector types with zero elements were allowed). 10003 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts); 10004 HiVT = EnvVT; 10005 *HiIsEmpty = true; 10006 } 10007 return std::make_pair(LoVT, HiVT); 10008 } 10009 10010 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the 10011 /// low/high part. 10012 std::pair<SDValue, SDValue> 10013 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, 10014 const EVT &HiVT) { 10015 assert(LoVT.isScalableVector() == HiVT.isScalableVector() && 10016 LoVT.isScalableVector() == N.getValueType().isScalableVector() && 10017 "Splitting vector with an invalid mixture of fixed and scalable " 10018 "vector types"); 10019 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <= 10020 N.getValueType().getVectorMinNumElements() && 10021 "More vector elements requested than available!"); 10022 SDValue Lo, Hi; 10023 Lo = 10024 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL)); 10025 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements() 10026 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales 10027 // IDX with the runtime scaling factor of the result vector type. For 10028 // fixed-width result vectors, that runtime scaling factor is 1. 10029 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N, 10030 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL)); 10031 return std::make_pair(Lo, Hi); 10032 } 10033 10034 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR. 10035 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) { 10036 EVT VT = N.getValueType(); 10037 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(), 10038 NextPowerOf2(VT.getVectorNumElements())); 10039 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N, 10040 getVectorIdxConstant(0, DL)); 10041 } 10042 10043 void SelectionDAG::ExtractVectorElements(SDValue Op, 10044 SmallVectorImpl<SDValue> &Args, 10045 unsigned Start, unsigned Count, 10046 EVT EltVT) { 10047 EVT VT = Op.getValueType(); 10048 if (Count == 0) 10049 Count = VT.getVectorNumElements(); 10050 if (EltVT == EVT()) 10051 EltVT = VT.getVectorElementType(); 10052 SDLoc SL(Op); 10053 for (unsigned i = Start, e = Start + Count; i != e; ++i) { 10054 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op, 10055 getVectorIdxConstant(i, SL))); 10056 } 10057 } 10058 10059 // getAddressSpace - Return the address space this GlobalAddress belongs to. 10060 unsigned GlobalAddressSDNode::getAddressSpace() const { 10061 return getGlobal()->getType()->getAddressSpace(); 10062 } 10063 10064 Type *ConstantPoolSDNode::getType() const { 10065 if (isMachineConstantPoolEntry()) 10066 return Val.MachineCPVal->getType(); 10067 return Val.ConstVal->getType(); 10068 } 10069 10070 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef, 10071 unsigned &SplatBitSize, 10072 bool &HasAnyUndefs, 10073 unsigned MinSplatBits, 10074 bool IsBigEndian) const { 10075 EVT VT = getValueType(0); 10076 assert(VT.isVector() && "Expected a vector type"); 10077 unsigned VecWidth = VT.getSizeInBits(); 10078 if (MinSplatBits > VecWidth) 10079 return false; 10080 10081 // FIXME: The widths are based on this node's type, but build vectors can 10082 // truncate their operands. 10083 SplatValue = APInt(VecWidth, 0); 10084 SplatUndef = APInt(VecWidth, 0); 10085 10086 // Get the bits. Bits with undefined values (when the corresponding element 10087 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared 10088 // in SplatValue. If any of the values are not constant, give up and return 10089 // false. 10090 unsigned int NumOps = getNumOperands(); 10091 assert(NumOps > 0 && "isConstantSplat has 0-size build vector"); 10092 unsigned EltWidth = VT.getScalarSizeInBits(); 10093 10094 for (unsigned j = 0; j < NumOps; ++j) { 10095 unsigned i = IsBigEndian ? NumOps - 1 - j : j; 10096 SDValue OpVal = getOperand(i); 10097 unsigned BitPos = j * EltWidth; 10098 10099 if (OpVal.isUndef()) 10100 SplatUndef.setBits(BitPos, BitPos + EltWidth); 10101 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal)) 10102 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos); 10103 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal)) 10104 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos); 10105 else 10106 return false; 10107 } 10108 10109 // The build_vector is all constants or undefs. Find the smallest element 10110 // size that splats the vector. 10111 HasAnyUndefs = (SplatUndef != 0); 10112 10113 // FIXME: This does not work for vectors with elements less than 8 bits. 10114 while (VecWidth > 8) { 10115 unsigned HalfSize = VecWidth / 2; 10116 APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize); 10117 APInt LowValue = SplatValue.trunc(HalfSize); 10118 APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize); 10119 APInt LowUndef = SplatUndef.trunc(HalfSize); 10120 10121 // If the two halves do not match (ignoring undef bits), stop here. 10122 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) || 10123 MinSplatBits > HalfSize) 10124 break; 10125 10126 SplatValue = HighValue | LowValue; 10127 SplatUndef = HighUndef & LowUndef; 10128 10129 VecWidth = HalfSize; 10130 } 10131 10132 SplatBitSize = VecWidth; 10133 return true; 10134 } 10135 10136 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts, 10137 BitVector *UndefElements) const { 10138 unsigned NumOps = getNumOperands(); 10139 if (UndefElements) { 10140 UndefElements->clear(); 10141 UndefElements->resize(NumOps); 10142 } 10143 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10144 if (!DemandedElts) 10145 return SDValue(); 10146 SDValue Splatted; 10147 for (unsigned i = 0; i != NumOps; ++i) { 10148 if (!DemandedElts[i]) 10149 continue; 10150 SDValue Op = getOperand(i); 10151 if (Op.isUndef()) { 10152 if (UndefElements) 10153 (*UndefElements)[i] = true; 10154 } else if (!Splatted) { 10155 Splatted = Op; 10156 } else if (Splatted != Op) { 10157 return SDValue(); 10158 } 10159 } 10160 10161 if (!Splatted) { 10162 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros(); 10163 assert(getOperand(FirstDemandedIdx).isUndef() && 10164 "Can only have a splat without a constant for all undefs."); 10165 return getOperand(FirstDemandedIdx); 10166 } 10167 10168 return Splatted; 10169 } 10170 10171 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const { 10172 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 10173 return getSplatValue(DemandedElts, UndefElements); 10174 } 10175 10176 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts, 10177 SmallVectorImpl<SDValue> &Sequence, 10178 BitVector *UndefElements) const { 10179 unsigned NumOps = getNumOperands(); 10180 Sequence.clear(); 10181 if (UndefElements) { 10182 UndefElements->clear(); 10183 UndefElements->resize(NumOps); 10184 } 10185 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size"); 10186 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps)) 10187 return false; 10188 10189 // Set the undefs even if we don't find a sequence (like getSplatValue). 10190 if (UndefElements) 10191 for (unsigned I = 0; I != NumOps; ++I) 10192 if (DemandedElts[I] && getOperand(I).isUndef()) 10193 (*UndefElements)[I] = true; 10194 10195 // Iteratively widen the sequence length looking for repetitions. 10196 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) { 10197 Sequence.append(SeqLen, SDValue()); 10198 for (unsigned I = 0; I != NumOps; ++I) { 10199 if (!DemandedElts[I]) 10200 continue; 10201 SDValue &SeqOp = Sequence[I % SeqLen]; 10202 SDValue Op = getOperand(I); 10203 if (Op.isUndef()) { 10204 if (!SeqOp) 10205 SeqOp = Op; 10206 continue; 10207 } 10208 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) { 10209 Sequence.clear(); 10210 break; 10211 } 10212 SeqOp = Op; 10213 } 10214 if (!Sequence.empty()) 10215 return true; 10216 } 10217 10218 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern"); 10219 return false; 10220 } 10221 10222 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence, 10223 BitVector *UndefElements) const { 10224 APInt DemandedElts = APInt::getAllOnesValue(getNumOperands()); 10225 return getRepeatedSequence(DemandedElts, Sequence, UndefElements); 10226 } 10227 10228 ConstantSDNode * 10229 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts, 10230 BitVector *UndefElements) const { 10231 return dyn_cast_or_null<ConstantSDNode>( 10232 getSplatValue(DemandedElts, UndefElements)); 10233 } 10234 10235 ConstantSDNode * 10236 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const { 10237 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements)); 10238 } 10239 10240 ConstantFPSDNode * 10241 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts, 10242 BitVector *UndefElements) const { 10243 return dyn_cast_or_null<ConstantFPSDNode>( 10244 getSplatValue(DemandedElts, UndefElements)); 10245 } 10246 10247 ConstantFPSDNode * 10248 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const { 10249 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements)); 10250 } 10251 10252 int32_t 10253 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, 10254 uint32_t BitWidth) const { 10255 if (ConstantFPSDNode *CN = 10256 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) { 10257 bool IsExact; 10258 APSInt IntVal(BitWidth); 10259 const APFloat &APF = CN->getValueAPF(); 10260 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) != 10261 APFloat::opOK || 10262 !IsExact) 10263 return -1; 10264 10265 return IntVal.exactLogBase2(); 10266 } 10267 return -1; 10268 } 10269 10270 bool BuildVectorSDNode::isConstant() const { 10271 for (const SDValue &Op : op_values()) { 10272 unsigned Opc = Op.getOpcode(); 10273 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP) 10274 return false; 10275 } 10276 return true; 10277 } 10278 10279 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) { 10280 // Find the first non-undef value in the shuffle mask. 10281 unsigned i, e; 10282 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i) 10283 /* search */; 10284 10285 // If all elements are undefined, this shuffle can be considered a splat 10286 // (although it should eventually get simplified away completely). 10287 if (i == e) 10288 return true; 10289 10290 // Make sure all remaining elements are either undef or the same as the first 10291 // non-undef value. 10292 for (int Idx = Mask[i]; i != e; ++i) 10293 if (Mask[i] >= 0 && Mask[i] != Idx) 10294 return false; 10295 return true; 10296 } 10297 10298 // Returns the SDNode if it is a constant integer BuildVector 10299 // or constant integer. 10300 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const { 10301 if (isa<ConstantSDNode>(N)) 10302 return N.getNode(); 10303 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode())) 10304 return N.getNode(); 10305 // Treat a GlobalAddress supporting constant offset folding as a 10306 // constant integer. 10307 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N)) 10308 if (GA->getOpcode() == ISD::GlobalAddress && 10309 TLI->isOffsetFoldingLegal(GA)) 10310 return GA; 10311 if ((N.getOpcode() == ISD::SPLAT_VECTOR) && 10312 isa<ConstantSDNode>(N.getOperand(0))) 10313 return N.getNode(); 10314 return nullptr; 10315 } 10316 10317 // Returns the SDNode if it is a constant float BuildVector 10318 // or constant float. 10319 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const { 10320 if (isa<ConstantFPSDNode>(N)) 10321 return N.getNode(); 10322 10323 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 10324 return N.getNode(); 10325 10326 return nullptr; 10327 } 10328 10329 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) { 10330 assert(!Node->OperandList && "Node already has operands"); 10331 assert(SDNode::getMaxNumOperands() >= Vals.size() && 10332 "too many operands to fit into SDNode"); 10333 SDUse *Ops = OperandRecycler.allocate( 10334 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator); 10335 10336 bool IsDivergent = false; 10337 for (unsigned I = 0; I != Vals.size(); ++I) { 10338 Ops[I].setUser(Node); 10339 Ops[I].setInitial(Vals[I]); 10340 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence. 10341 IsDivergent |= Ops[I].getNode()->isDivergent(); 10342 } 10343 Node->NumOperands = Vals.size(); 10344 Node->OperandList = Ops; 10345 if (!TLI->isSDNodeAlwaysUniform(Node)) { 10346 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA); 10347 Node->SDNodeBits.IsDivergent = IsDivergent; 10348 } 10349 checkForCycles(Node); 10350 } 10351 10352 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL, 10353 SmallVectorImpl<SDValue> &Vals) { 10354 size_t Limit = SDNode::getMaxNumOperands(); 10355 while (Vals.size() > Limit) { 10356 unsigned SliceIdx = Vals.size() - Limit; 10357 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit); 10358 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs); 10359 Vals.erase(Vals.begin() + SliceIdx, Vals.end()); 10360 Vals.emplace_back(NewTF); 10361 } 10362 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals); 10363 } 10364 10365 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL, 10366 EVT VT, SDNodeFlags Flags) { 10367 switch (Opcode) { 10368 default: 10369 return SDValue(); 10370 case ISD::ADD: 10371 case ISD::OR: 10372 case ISD::XOR: 10373 case ISD::UMAX: 10374 return getConstant(0, DL, VT); 10375 case ISD::MUL: 10376 return getConstant(1, DL, VT); 10377 case ISD::AND: 10378 case ISD::UMIN: 10379 return getAllOnesConstant(DL, VT); 10380 case ISD::SMAX: 10381 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT); 10382 case ISD::SMIN: 10383 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT); 10384 case ISD::FADD: 10385 return getConstantFP(-0.0, DL, VT); 10386 case ISD::FMUL: 10387 return getConstantFP(1.0, DL, VT); 10388 case ISD::FMINNUM: 10389 case ISD::FMAXNUM: { 10390 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF. 10391 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT); 10392 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) : 10393 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) : 10394 APFloat::getLargest(Semantics); 10395 if (Opcode == ISD::FMAXNUM) 10396 NeutralAF.changeSign(); 10397 10398 return getConstantFP(NeutralAF, DL, VT); 10399 } 10400 } 10401 } 10402 10403 #ifndef NDEBUG 10404 static void checkForCyclesHelper(const SDNode *N, 10405 SmallPtrSetImpl<const SDNode*> &Visited, 10406 SmallPtrSetImpl<const SDNode*> &Checked, 10407 const llvm::SelectionDAG *DAG) { 10408 // If this node has already been checked, don't check it again. 10409 if (Checked.count(N)) 10410 return; 10411 10412 // If a node has already been visited on this depth-first walk, reject it as 10413 // a cycle. 10414 if (!Visited.insert(N).second) { 10415 errs() << "Detected cycle in SelectionDAG\n"; 10416 dbgs() << "Offending node:\n"; 10417 N->dumprFull(DAG); dbgs() << "\n"; 10418 abort(); 10419 } 10420 10421 for (const SDValue &Op : N->op_values()) 10422 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG); 10423 10424 Checked.insert(N); 10425 Visited.erase(N); 10426 } 10427 #endif 10428 10429 void llvm::checkForCycles(const llvm::SDNode *N, 10430 const llvm::SelectionDAG *DAG, 10431 bool force) { 10432 #ifndef NDEBUG 10433 bool check = force; 10434 #ifdef EXPENSIVE_CHECKS 10435 check = true; 10436 #endif // EXPENSIVE_CHECKS 10437 if (check) { 10438 assert(N && "Checking nonexistent SDNode"); 10439 SmallPtrSet<const SDNode*, 32> visited; 10440 SmallPtrSet<const SDNode*, 32> checked; 10441 checkForCyclesHelper(N, visited, checked, DAG); 10442 } 10443 #endif // !NDEBUG 10444 } 10445 10446 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) { 10447 checkForCycles(DAG->getRoot().getNode(), DAG, force); 10448 } 10449